Skip to content

Commit

Permalink
Versione 2.0.0
Browse files Browse the repository at this point in the history
*Purtroppo le api di football-data sono state bloccate, o comunque non sono piu funzionanti, ho considerato di spostare tutto su api ESPN, purtroppo queste API's non hanno una guida e le informazioni sono solo per passaparola, quindi abbiamo perso sia la
- card capocannonieri
- i match 'mistati' di una squadra,
- tutti i match della giornata odierna

Spero in futuro di riuscire a recuperare informazioni per questi sensori, al contempo ora ci sono sensori.

Per una squadra TEAM vengono creati 2 sensori:
1 permette di vedere la prossima partita (del campionato)
2 permette di vedere la partite passate e concluse (del campionato)

Per il campionato:
1 classifica
2 partite della settimana + tre giorni precedenti, quindi se siamo al 4/10, verranno considerate anche le partite del 1-2-3
  • Loading branch information
Bobsilvio committed Oct 2, 2024
1 parent fb56188 commit b8e902b
Show file tree
Hide file tree
Showing 15 changed files with 672 additions and 276 deletions.
5 changes: 1 addition & 4 deletions custom_components/calcio_live/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant

from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)
from .const import DOMAIN, _LOGGER

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Setup calcio_live from a config entry."""
Expand Down
124 changes: 82 additions & 42 deletions custom_components/calcio_live/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@
from homeassistant import config_entries
from homeassistant.core import callback
import logging
import requests
import aiohttp
from .const import DOMAIN, COMPETITIONS

_LOGGER = logging.getLogger(__name__)

OPTION_SELECT_CAMPIONATO = "Campionato"
OPTION_SELECT_TEAM = "Team"
OPTION_MANUAL_TEAM = "Inserimento Manuale ID"

@config_entries.HANDLERS.register(DOMAIN)
class CalcioLiveConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
Expand All @@ -17,8 +20,10 @@ class CalcioLiveConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
def __init__(self):
self._errors = {}
self._data = {}
self._teams = []

async def async_step_user(self, user_input=None):
"""Prima schermata per selezionare Campionato o Team."""
self._errors = {}

if user_input is not None:
Expand All @@ -30,102 +35,137 @@ async def async_step_user(self, user_input=None):

elif selection == OPTION_SELECT_TEAM:
self._data.update(user_input)
return await self.async_step_team()
return await self.async_step_select_competition_for_team()

return self.async_show_form(
step_id="user",
data_schema=vol.Schema({
vol.Required("selection", default=OPTION_SELECT_CAMPIONATO): vol.In([OPTION_SELECT_CAMPIONATO, OPTION_SELECT_TEAM]),
vol.Required("api_key", description={"suggested_value": "Inserisci la tua chiave API"}): str,
}),
errors=self._errors,
description_placeholders={}
)



async def async_step_campionato(self, user_input=None):
"""Schermata per selezionare il campionato (senza richiesta API)."""
if user_input is not None:
self._data.update(user_input)
competition_code = user_input.get("competition_code")
self._data.update({"competition_code": competition_code})

nome = user_input.get("name", "Nome Campionato (a piacere)")
nome_normalizzato = nome.replace(" ", "_").lower()
nome_sensore = COMPETITIONS.get(competition_code, competition_code)

return self.async_create_entry(
title=f"{COMPETITIONS[user_input['competition_code']]}",
title=f"{COMPETITIONS[competition_code]}",
data={
**self._data,
"competition_code": user_input["competition_code"],
"competition_code": competition_code,
"team_id": None,
"name": nome_normalizzato,
"name": nome_sensore,
},
)

return self.async_show_form(
step_id="campionato",
data_schema=vol.Schema({
vol.Required("competition_code"): vol.In(COMPETITIONS),
vol.Optional("name", default="Nome Campionato (a piacere)"): str,
}),
errors=self._errors,
)


async def async_step_select_competition_for_team(self, user_input=None):
"""Schermata per selezionare il campionato per un Team (passo intermedio)."""
if user_input is not None:
competition_code = user_input.get("competition_code")
self._data.update({"competition_code": competition_code})

await self._get_teams(competition_code)
return await self.async_step_team()

return self.async_show_form(
step_id="select_competition_for_team",
data_schema=vol.Schema({
vol.Required("competition_code"): vol.In(COMPETITIONS),
}),
errors=self._errors,
)

async def async_step_team(self, user_input=None):
"""Schermata per selezionare la squadra (dopo aver selezionato il campionato)."""
if user_input is not None:
self._data.update(user_input)
if user_input["team_id"] == OPTION_MANUAL_TEAM:
return await self.async_step_manual_team()

team_id = user_input["team_id"]
self._data.update({"team_id": team_id})

nome_squadra = user_input.get("name", "Nome Squadra (a piacere)")
nome_squadra = next((team['displayName'] for team in self._teams if team['id'] == team_id), "Nome Squadra")
nome_squadra_normalizzato = nome_squadra.replace(" ", "_").lower()

return self.async_create_entry(
title=f"Team {team_id} {nome_squadra_normalizzato}",
data={
**self._data,
"competition_code": None,
"team_id": team_id,
"name": f"Team {team_id} {nome_squadra_normalizzato}",
},
)

team_options = {team['id']: team['displayName'] for team in self._teams}
team_options[OPTION_MANUAL_TEAM] = OPTION_MANUAL_TEAM

return self.async_show_form(
step_id="team",
data_schema=vol.Schema({
vol.Required("team_id", description={"suggested_value": "Inserisci il Team ID"}): str,
vol.Optional("name", default="Nome Squadra (a piacere)"): str,
vol.Required("team_id"): vol.In(team_options),
}),
errors=self._errors,
)

@staticmethod
@callback
def async_get_options_flow(config_entry):
return CalcioLiveOptionsFlowHandler(config_entry)


class CalcioLiveOptionsFlowHandler(config_entries.OptionsFlow):

def __init__(self, config_entry):
self.config_entry = config_entry
self._errors = {}

async def async_step_init(self, user_input=None):
async def async_step_manual_team(self, user_input=None):
"""Schermata per inserire manualmente l'ID del team."""
if user_input is not None:
return self.async_create_entry(title="", data=user_input)

return await self._show_options_form(user_input)
team_id = user_input["manual_team_id"]
nome_squadra = user_input.get("name", "Nome Squadra (a piacere)")
nome_squadra_normalizzato = nome_squadra.replace(" ", "_").lower()

async def _show_options_form(self, user_input):
defaults = {
"api_key": self.config_entry.data.get("api_key"),
"selection": self.config_entry.data.get("selection"),
"competition_code": self.config_entry.data.get("competition_code"),
"team_id": self.config_entry.data.get("team_id"),
"name": self.config_entry.data.get("name"),
}
return self.async_create_entry(
title=f"Team {team_id} {nome_squadra_normalizzato}",
data={
**self._data,
"team_id": team_id,
"name": f"Team {team_id} {nome_squadra_normalizzato}",
},
)

return self.async_show_form(
step_id="init",
step_id="manual_team",
data_schema=vol.Schema({
vol.Optional("api_key", default=defaults.get("api_key")): str,
vol.Optional("name", default=defaults.get("name", "Nome Campionato (a piacere)")): str,
vol.Required("manual_team_id", description={"suggested_value": "Inserisci l'ID del Team manualmente"}): str,
vol.Optional("name", default="Nome Squadra (a piacere)"): str,
}),
errors=self._errors,
)

async def _get_teams(self, competition_code):
"""Recupera la lista delle squadre dal campionato selezionato tramite API."""
url = f"https://site.api.espn.com/apis/site/v2/sports/soccer/{competition_code}/teams"
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
response.raise_for_status()
teams_data = await response.json()

# Estrai le squadre
self._teams = [
{
"id": team['team']['id'],
"displayName": team['team']['displayName']
}
for team in teams_data.get("sports", [])[0].get("leagues", [])[0].get("teams", [])
]
_LOGGER.debug(f"Squadre caricate per {competition_code}: {self._teams}")
except aiohttp.ClientError as e:
_LOGGER.error(f"Errore nel caricamento delle squadre per {competition_code}: {e}")
self._teams = []
51 changes: 28 additions & 23 deletions custom_components/calcio_live/const.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,33 @@
import logging
_LOGGER = logging.getLogger(__name__)

DOMAIN = "calcio_live"
CONF_API_KEY = "api_key"
CONF_COMPETITION_CODE = "competition_code"

COMPETITIONS = {
'BL1': 'Bundesliga',
'BSA': 'Brasileirao',
'CL': 'Champions League',
'CLI': 'Copa Libertadores',
'DED': 'Eredivisie',
'EC': 'European Championship',
'ELC': 'Championship',
'FL1': 'Ligue 1',
'PD': 'La Liga',
'PL': 'Premier League',
'PPL': 'Primeira Liga',
'SA': 'Serie A',
'WC': 'World Cup'
'ita.1': 'Serie A',
'ger.1': 'Bundesliga',
'esp.1': 'La Liga',
'por.1': 'Primeira Liga',
'uefa.europa_qual': 'UEFA Europa League Qualifying',
'uefa.champions_qual': 'UEFA Champions League Qualifying',
'fifa.intercontinental.cup': 'FIFA Intercontinental Cup',
'mex.2': 'Liga de Expansión MX',
'arg.5': 'Primera C Metropolitana',
'wal.1': 'Cymru Premier',
'ven.2': 'Segunda División Venezolana',
'arg.4': 'Primera D Metropolitana',
'irl.1': 'League of Ireland Premier Division',
'uru.2': 'Segunda División Uruguaya',
'aut.promotion.relegation': 'Austrian Promotion/Relegation Playoff',
'arg.3': 'Primera B Metropolitana',
'den.promotion.relegation': 'Danish Promotion/Relegation Playoff',
'chi.2': 'Primera B de Chile',
'ned.1': 'Eredivisie',
'nor.1': 'Eliteserien',
'swe.1': 'Allsvenskan',
'sui.1': 'Swiss Super League',
'tur.1': 'Super Lig',
'usa.1': 'Major League Soccer (MLS)',
'arg.copa': 'Copa Argentina',
}


SENSOR_TYPES = {
"competizioni": "Competizioni",
"competizione_specifica": "Competizione Specifica",
"classifica": "Classifica",
"match_day": "Match Day",
"cannonieri": "Cannonieri",
}
2 changes: 1 addition & 1 deletion custom_components/calcio_live/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@
"iot_class": "cloud_polling",
"issue_tracker": "https://github.com/Bobsilvio/calcio_live/issues",
"requirements": ["arrow", "aiofiles"],
"version": "1.0.14"
"version": "2.0.0"
}
Loading

0 comments on commit b8e902b

Please sign in to comment.