Skip to content

Commit

Permalink
Starting with config_flow and coordinator
Browse files Browse the repository at this point in the history
  • Loading branch information
rgerbranda committed Mar 11, 2024
1 parent 147f30b commit a762f65
Show file tree
Hide file tree
Showing 8 changed files with 270 additions and 165 deletions.
133 changes: 31 additions & 102 deletions custom_components/rbfa/API.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@
from datetime import datetime, timedelta
import json
import requests
#import pytz
from zoneinfo import ZoneInfo

from homeassistant.helpers.event import async_track_point_in_utc_time
from homeassistant.util import dt as dt_util
from homeassistant.components import persistent_notification

Expand All @@ -15,69 +13,6 @@
_LOGGER = logging.getLogger(__name__)


class TeamData(object):

def __init__(self, hass, team, update_interval):
self.hass = hass
self.team = team
self.update_interval = update_interval
self.collector = TeamApp(self.hass, team)

async def schedule_update(self, interval):
now = dt_util.utcnow()
start = datetime(
now.year,
now.month,
now.day,
START.hour,
START.minute,
tzinfo = ZoneInfo(TZ)
)
end = datetime(
now.year,
now.month,
now.day,
END.hour,
END.minute,
tzinfo = ZoneInfo(TZ)
)

if interval == timedelta():
nxt = now
elif now < start:
nxt = start
elif now > end:
nxt = start + timedelta(days=1)
else:
nxt = now + interval

_LOGGER.debug('interval: %r', interval)

_LOGGER.debug('schedule_update %r', nxt)

async_track_point_in_utc_time(self.hass, self.async_update, nxt)

async def async_update(self, *_):
_LOGGER.debug('async_update')
await self.collector.update()
if self.update_interval != 0:
await self.schedule_update(timedelta(minutes=self.update_interval))
else:
await self.schedule_update(SCHEDULE_UPDATE_INTERVAL)

@property
def collections(self):
return self.collector.collections

def teamdata(self):
return self.collector.teamdata

def upcoming(self):
return self.collector.upcoming

def lastmatch(self):
return self.collector.lastmatch

class TeamApp(object):

def __init__(self, hass, team):
Expand Down Expand Up @@ -178,36 +113,45 @@ async def update(self):
if item['outcome']['homeTeamPenaltiesScored'] != None:
result += '; Penalties: ' + str(item['outcome']['homeTeamPenaltiesScored']) + ' - ' + str(item['outcome']['awayTeamPenaltiesScored'])

matchdata = {
'uid': item['id'],
'team': self.team,
'date': starttime,
'location': location,
'hometeam': item['homeTeam']['name'],
'homelogo': item['homeTeam']['logo'],
'awayteam': item['awayTeam']['name'],
'awaylogo': item['awayTeam']['logo'],
'series': item['series']['name'],
'seriesid': item['series']['id'],
'result': result,
'ranking': 0,
'position': 0,
}

if starttime >= now and self.upcoming == None:
self.series = previous['seriesid']

self.upcoming = matchdata
self.lastmatch = previous
self.series = previous['series']['id']

prevposition = None
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']}
ranking.append(rankteam)
if rank['teamId'] == self.team:
self.lastmatch['position'] = rank['position']
self.lastmatch['ranking'] = ranking
prevposition = rank['position']

self.upcoming = {
'uid': item['id'],
'team': self.team,
'teamname': self.teamdata['name'],
'clubname': self.teamdata['clubName'],
'date': starttime,
'location': location,
'hometeam': item['homeTeam']['name'],
'homelogo': item['homeTeam']['logo'],
'awayteam': item['awayTeam']['name'],
'awaylogo': item['awayTeam']['logo'],
'prevhometeam': previous['homeTeam']['name'],
'prevhomelogo': previous['homeTeam']['logo'],
'prevawayteam': previous['awayTeam']['name'],
'prevawaylogo': previous['awayTeam']['logo'],
'series': item['series']['name'],
'prevseries': previous['series']['name'],
'seriesid': item['series']['id'],
'result': result,
'prevseries': previous['series']['name'],
'prevposition': prevposition,
'prevranking': ranking,
'position': 0,
'prevresulthome': previous['outcome']['homeTeamGoals']
}


summary = '[' + item['state'] + '] ' + item['homeTeam']['name'] + ' - ' + item['awayTeam']['name']
# if item['state'] == 'postponed':
Expand All @@ -222,19 +166,4 @@ async def update(self):
}

self.collections.append(collection)
previous = matchdata


def get_rbfa_data_from_config(hass, config):
_LOGGER.debug("Get Rest API retriever")
team = config.get(CONF_TEAM)
update_interval = config.get(CONF_UPDATE_INTERVAL)

_LOGGER.debug('API team: %r', team)

td = TeamData(
hass,
team,
update_interval,
)
return td
previous = item
33 changes: 28 additions & 5 deletions custom_components/rbfa/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,33 @@
rbra:
team: 123456
"""
#from __future__ import annotations

import logging
#from datetime import datetime
from datetime import timedelta

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform

from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType
from homeassistant.components import persistent_notification

from .const import DOMAIN, PLATFORM_SCHEMA, CONF_TEAM, CONF_UPDATE_INTERVAL
from .API import TeamData
from .API import TeamApp

from .coordinator import MyCoordinator

from homeassistant.config_entries import ConfigEntry

__version__ = "0.1"


_LOGGER = logging.getLogger(__name__)

PLATFORMS = [Platform.CALENDAR]

'''
async def async_setup(hass: HomeAssistant, config: ConfigType):
_LOGGER.debug("Setup of RBFA component Rest API retriever")
Expand All @@ -52,9 +58,9 @@ async def async_setup(hass: HomeAssistant, config: ConfigType):
Platform.CALENDAR, DOMAIN, {"config": conf}, conf
)
hass.helpers.discovery.load_platform(
Platform.SENSOR, DOMAIN, {"config": conf}, conf
)
# hass.helpers.discovery.load_platform(
# Platform.SENSOR, DOMAIN, {"config": conf}, conf
# )
_LOGGER.debug("data schedule update")
await data.schedule_update(timedelta())
Expand All @@ -67,3 +73,20 @@ async def async_setup(hass: HomeAssistant, config: ConfigType):
)
return True
'''

async def async_setup_entry(hass, entry) -> bool:
"""Set up Elgato Light from a config entry."""
coordinator = MyCoordinator(hass, entry)
_LOGGER.debug('first refresh')
await coordinator.async_config_entry_first_refresh()

hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

return True

#async def async_update_options(hass: HomeAssistant, config_entry: ConfigEntry) -> None:
# """Update options."""
# await hass.config_entries.async_reload(config_entry.entry_id)

40 changes: 22 additions & 18 deletions custom_components/rbfa/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,26 @@

from .const import DOMAIN, CONF_TEAM

from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.config_entries import ConfigEntry

_LOGGER = logging.getLogger(__name__)


def setup_platform(hass, config, async_add_entities, discovery_info=None):

if discovery_info and "config" in discovery_info:
conf = discovery_info["config"]
else:
conf = config

if not conf:
return

async_add_entities([TeamCalendar(hass.data[DOMAIN][conf[CONF_TEAM]], conf)])
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up Elgato sensor based on a config entry."""
coordinator: MyCoordinator = hass.data[DOMAIN][entry.entry_id]

async_add_entities(
[TeamCalendar(
coordinator,
entry,
)]
)

class TeamCalendar(CalendarEntity):
"""Defines a RBFA Team Calendar."""
Expand All @@ -41,22 +45,22 @@ def __init__(
"""Initialize the RBFA Team entity."""
self.TeamData = TeamData
self.config = config

self._attr_name = f"{DOMAIN} {config[CONF_TEAM]}"
self._attr_unique_id = f"{DOMAIN}_calendar_{config[CONF_TEAM]}"
team = config.data['team']
_LOGGER.debug('team: %r', team)
self._attr_name = f"{DOMAIN} {team}"
self._attr_unique_id = f"{DOMAIN}_calendar_{team}"

self._event = None

@property
def event(self) -> Optional[CalendarEvent]:
"""Return the next upcoming event."""
# _LOGGER.debug('set upcoming event')
if self.TeamData.teamdata() != None:
teamdata = self.TeamData.teamdata()
self._attr_name = f"{teamdata['name']} | {teamdata['clubName']}"
_LOGGER.debug('set upcoming event')

if self.TeamData.upcoming() != None:
team_items = self.TeamData.upcoming()
_LOGGER.debug('name: %r', team_items['teamname'])
self._attr_name = f"{team_items['clubname']} | {team_items['teamname']}"
return CalendarEvent(
uid = team_items['uid'],
summary = team_items['hometeam'] + ' - ' + team_items['awayteam'],
Expand Down
48 changes: 48 additions & 0 deletions custom_components/rbfa/coordinator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@


from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from datetime import timedelta

from .const import DOMAIN
import logging
from .API import TeamApp

_LOGGER = logging.getLogger(__name__)



class MyCoordinator(DataUpdateCoordinator):
"""Class to manage fetching Elgato data."""

def __init__(self, hass: HomeAssistant, my_api) -> None:
"""Initialize the coordinator."""
team = '283884'
team = '300872'

self.collector = TeamApp(hass, my_api.data['team'])
super().__init__(
hass,
_LOGGER,
name=f"{DOMAIN}",
update_interval=timedelta(seconds=30),
)

async def _async_update_data(self):
"""Fetch data from the Elgato device."""
_LOGGER.debug('fetch data coordinator')
await self.collector.update()

@property
def collections(self):
return self.collector.collections

# def teamdata(self):
# return self.collector.teamdata

def upcoming(self):
return self.collector.upcoming

# def lastmatch(self):
# return self.collector.lastmatch
1 change: 1 addition & 0 deletions custom_components/rbfa/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"name": "RBFA",
"documentation": "https://github.com/rgerbranda/rbfa",
"issue_tracker": "https://github.com/rgerbranda/rbfa/issues",
"config_flow": true,
"dependencies": [],
"codeowners": ["@rgerbranda"],
"requirements": [],
Expand Down
Loading

0 comments on commit a762f65

Please sign in to comment.