Skip to content

Commit

Permalink
extend config flow
Browse files Browse the repository at this point in the history
  • Loading branch information
rgerbranda committed May 18, 2024
1 parent 8ce9bde commit 484587a
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 46 deletions.
93 changes: 52 additions & 41 deletions custom_components/rbfa/API.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,11 @@
class TeamApp(object):

def __init__(self, hass, my_api):
self.teamdata = None
self.matchdata = {'upcoming': None, 'lastmatch': None}
# self.teamdata = None
# self.matchdata = {'upcoming': None, 'lastmatch': None}
self.hass = hass
self.team = my_api.data['team']

if 'duration' in my_api.options:
self.duration = my_api.options['duration']
else:
self.duration = my_api.data['duration']

self.collections = [];
_LOGGER.debug('duration: %r', self.duration)

def __get_url(self, operation, value):
with open(operation + ".txt", 'r') as fson:
Expand Down Expand Up @@ -87,9 +80,25 @@ def __get_ranking(self):
return response


async def update(self):
async def update(self, my_api):
_LOGGER.debug('Updating match details using Rest API')

if 'duration' in my_api.options:
self.duration = my_api.options['duration']
else:
self.duration = my_api.data['duration']

if 'show_ranking' in my_api.options:
self.show_ranking = my_api.options['show_ranking']
elif 'show_ranking' in my_api.data:
self.show_ranking = my_api.data['show_ranking']
else:
self.show_ranking = True

self.collections = [];
_LOGGER.debug('duration: %r', self.duration)
_LOGGER.debug('show ranking: %r', self.show_ranking)

now = dt_util.utcnow()

r = await self.hass.async_add_executor_job(self.__get_team)
Expand Down Expand Up @@ -153,56 +162,58 @@ async def update(self):

if endtime >= now and not upcoming:

self.series = matchdata['seriesid']
r = await self.hass.async_add_executor_job(self.__get_ranking)
if r != None:
for rank in r['data']['seriesRankings']['rankings'][0]['teams']:
rankteam = {'position': rank['position'], 'team': rank['name'], 'id': rank['teamId']}
matchdata['ranking'].append(rankteam)
if rank['teamId'] == matchdata['hometeamid']:
matchdata['hometeamposition'] = rank['position']
if rank['teamId'] == matchdata['awayteamid']:
matchdata['awayteamposition'] = rank['position']

self.series = previous['seriesid']
r = await self.hass.async_add_executor_job(self.__get_ranking)
if r != None:
for rank in r['data']['seriesRankings']['rankings'][0]['teams']:
rankteam = {'position': rank['position'], 'team': rank['name'], 'id': rank['teamId']}
previous['ranking'].append(rankteam)
if rank['teamId'] == previous['hometeamid']:
previous['hometeamposition'] = rank['position']
if rank['teamId'] == previous['awayteamid']:
previous['awayteamposition'] = rank['position']

upcoming = True
self.matchdata = {
'upcoming': matchdata,
'lastmatch': previous
}

if self.show_ranking:
await self.get_ranking('upcoming')
await self.get_ranking('lastmatch')

summary = '[' + item['state'] + '] ' + item['homeTeam']['name'] + ' - ' + item['awayTeam']['name']
description = item['series']['name']

result = 'No match score'
if item['outcome']['homeTeamGoals'] != None:
result = 'Goals: ' + str(item['outcome']['homeTeamGoals']) + ' - ' + str(item['outcome']['awayTeamGoals'])
if item['outcome']['homeTeamPenaltiesScored'] != None:
result += '; Penalties: ' + str(item['outcome']['homeTeamPenaltiesScored']) + ' - ' + str(item['outcome']['awayTeamPenaltiesScored'])
if self.show_ranking:
result = 'No match score'
if item['outcome']['homeTeamGoals'] != None:
result = 'Goals: ' + str(item['outcome']['homeTeamGoals']) + ' - ' + str(item['outcome']['awayTeamGoals'])
if item['outcome']['homeTeamPenaltiesScored'] != None:
result += '; Penalties: ' + str(item['outcome']['homeTeamPenaltiesScored']) + ' - '
result += str(item['outcome']['awayTeamPenaltiesScored'])
description += "; " + result

collection = {
'uid': item['id'],
'starttime': starttime,
'endtime': endtime,
'summary': summary,
'location': location,
'description': item['series']['name'] + "; " + result,
'description': description,
}

self.collections.append(collection)
previous = matchdata

if not upcoming:
_LOGGER.debug('previous=last')
self.matchdata['lastmatch'] = previous
self.matchdata['upcoming'] = None
self.matchdata = {
'upcoming': None,
'lastmatch': previous
}
if self.show_ranking:
await self.get_ranking('lastmatch')

async def get_ranking (self, tag):
_LOGGER.debug('show ranking')

self.series = self.matchdata[tag]['seriesid']
r = await self.hass.async_add_executor_job(self.__get_ranking)
if r != None:
for rank in r['data']['seriesRankings']['rankings'][0]['teams']:
rankteam = {'position': rank['position'], 'team': rank['name'], 'id': rank['teamId']}
self.matchdata[tag]['ranking'].append(rankteam)
if rank['teamId'] == self.matchdata[tag]['hometeamid']:
self.matchdata[tag]['hometeamposition'] = rank['position']
if rank['teamId'] == self.matchdata[tag]['awayteamid']:
self.matchdata[tag]['awayteamposition'] = rank['position']
7 changes: 6 additions & 1 deletion custom_components/rbfa/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,12 @@ def __init__(
def event(self) -> Optional[CalendarEvent]:
"""Return the next upcoming event."""

self._attr_name = f"{self.TeamData.teamdata['clubName']} | {self.TeamData.teamdata['name']}"
if 'alt_name' in self.config.options:
self._attr_name = self.config.options['alt_name']
elif 'alt_name' in self.config.data:
self._attr_name = self.config.data['alt_name']
else:
self._attr_name = f"{self.TeamData.teamdata['clubName']} | {self.TeamData.teamdata['name']}"

upcoming = self.TeamData.data['upcoming']
lastmatch = self.TeamData.data['lastmatch']
Expand Down
19 changes: 19 additions & 0 deletions custom_components/rbfa/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ async def async_step_user(self, user_input):
if user_input is not None:
team = user_input.get('team')
duration = user_input.get('duration')
show_ranking = user_input.get('show_ranking')

await self.async_set_unique_id(f"{team}")
self._abort_if_unique_id_configured()
Expand All @@ -34,6 +35,7 @@ async def async_step_user(self, user_input):
schema = vol.Schema(
{
vol.Required('team'): str,
vol.Optional('alt_name'): str,
vol.Required('duration', default=105
): selector.NumberSelector(
selector.NumberSelectorConfig(
Expand All @@ -44,6 +46,7 @@ async def async_step_user(self, user_input):
unit_of_measurement=UnitOfTime.MINUTES,
),
),
vol.Required('show_ranking', default=True): bool,
}
)

Expand Down Expand Up @@ -75,15 +78,30 @@ async def async_step_init(
if user_input is not None:
return self.async_create_entry(title="test", data=user_input)

if 'alt_name' in self.config_entry.options:
alt_name = self.config_entry.options['alt_name']
elif 'alt_name' in self.config_entry.data:
alt_name = self.config_entry.data['alt_name']
else:
alt_name = ''

if 'duration' in self.config_entry.options:
duration = self.config_entry.options['duration']
else:
duration = self.config_entry.data['duration']

if 'show_ranking' in self.config_entry.options:
show_ranking = self.config_entry.options['show_ranking']
elif 'show_ranking' in self.config_entry.data:
show_ranking = self.config_entry.data['show_ranking']
else:
show_ranking = True
# https://community.home-assistant.io/t/voluptuous-options-flow-validation-for-an-optional-string-how/305538/3
return self.async_show_form(
step_id="init",
data_schema=vol.Schema(
{
vol.Optional('alt_name', description={"suggested_value": alt_name}): str,
vol.Required('duration', default=duration
): selector.NumberSelector(
selector.NumberSelectorConfig(
Expand All @@ -94,6 +112,7 @@ async def async_step_init(
unit_of_measurement=UnitOfTime.MINUTES,
),
),
vol.Required('show_ranking', default=show_ranking): bool,
}
),
)
3 changes: 2 additions & 1 deletion custom_components/rbfa/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,12 @@ def __init__(self, hass: HomeAssistant, my_api) -> None:
name=f"{DOMAIN}",
update_interval=timedelta(seconds=15),
)
self.api = my_api

async def _async_update_data(self):
"""Fetch data from the RBFA service."""
_LOGGER.debug('fetch data coordinator')
await self.collector.update()
await self.collector.update(self.api)
return self.collector.matchdata

@property
Expand Down
2 changes: 1 addition & 1 deletion custom_components/rbfa/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def extra_state_attributes(self):
if result != None:
attributes[t] = result

if key == 'series':
if key == 'series' and data['ranking']:
attributes['ranking'] = data['ranking']

return attributes
8 changes: 6 additions & 2 deletions custom_components/rbfa/translations/nl.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
"description":"Royal Belgian Football Association",
"data":{
"team":"Identiteit van het team",
"duration":"Duur van de wedstrijd inclusief rust"
"alt_name":"Alternatieve naam",
"duration":"Duur van de wedstrijd inclusief rust",
"show_ranking":"Toon uitslagen en rangschikking"
}
}
},
Expand All @@ -20,7 +22,9 @@
"title":"RBFA",
"description":"Royal Belgian Football Association",
"data":{
"duration":"Duur van de wedstrijd inclusief rust"
"alt_name":"Alternatieve naam",
"duration":"Duur van de wedstrijd inclusief rust",
"show_ranking":"Toon uitslagen en rangschikking"
}
}
}
Expand Down

0 comments on commit 484587a

Please sign in to comment.