Skip to content

Commit

Permalink
improve sensors
Browse files Browse the repository at this point in the history
  • Loading branch information
rgerbranda committed Mar 12, 2024
1 parent a762f65 commit d2cd8a3
Show file tree
Hide file tree
Showing 5 changed files with 162 additions and 95 deletions.
76 changes: 39 additions & 37 deletions custom_components/rbfa/API.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class TeamApp(object):
def __init__(self, hass, team):
self.teamdata = None
self.upcoming = None
self.matchdata = {'upcoming': None, 'lastmatch': None}
self.lastmatch = None
self.hass = hass
self.team = team
Expand Down Expand Up @@ -71,7 +72,7 @@ def __get_match(self):
return response

def __get_ranking(self):
_LOGGER.debug(self.series)
# _LOGGER.debug(self.series)
response = self.__get_url('GetSeriesRankings', self.series)
return response

Expand All @@ -90,6 +91,7 @@ async def update(self):

self.collections = []
ranking = []
position = None

for item in r['data']['teamCalendar']:
self.match = item['id']
Expand All @@ -107,56 +109,56 @@ async def update(self):
naive_dt = datetime.strptime(item['startTime'], '%Y-%m-%dT%H:%M:%S')
starttime = naive_dt.replace(tzinfo = ZoneInfo(TZ))

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'])

matchdata = {
'uid': item['id'],
'team': self.team,
'teamname': self.teamdata['name'],
'clubname': self.teamdata['clubName'],
'date': starttime,
'location': location,
'hometeam': item['homeTeam']['name'],
'hometeamlogo': item['homeTeam']['logo'],
'hometeamgoals': item['outcome']['homeTeamGoals'],
'hometeampenalties': item['outcome']['homeTeamPenaltiesScored'],
'awayteam': item['awayTeam']['name'],
'awayteamlogo': item['awayTeam']['logo'],
'awayteamgoals': item['outcome']['awayTeamGoals'],
'awayteampenalties': item['outcome']['awayTeamPenaltiesScored'],
'series': item['series']['name'],
'seriesid': item['series']['id'],
'ranking': ranking,
'position': position,
}

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

prevposition = None
self.series = item['series']['id']
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:
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']
}
matchdata['position'] = rank['position']
matchdata['ranking'] = ranking
_LOGGER.debug('position: %r', position)

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


summary = '[' + item['state'] + '] ' + item['homeTeam']['name'] + ' - ' + item['awayTeam']['name']
# if item['state'] == 'postponed':
# summary = '[postponed] ' + summary


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'])

collection = {
'uid': item['id'],
'date': starttime,
Expand All @@ -166,4 +168,4 @@ async def update(self):
}

self.collections.append(collection)
previous = item
previous = matchdata
2 changes: 1 addition & 1 deletion custom_components/rbfa/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

_LOGGER = logging.getLogger(__name__)

PLATFORMS = [Platform.CALENDAR]
PLATFORMS = [Platform.CALENDAR, Platform.SENSOR]

'''
async def async_setup(hass: HomeAssistant, config: ConfigType):
Expand Down
8 changes: 4 additions & 4 deletions custom_components/rbfa/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ async def _async_update_data(self):
def collections(self):
return self.collector.collections

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

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

# def lastmatch(self):
# return self.collector.lastmatch
def lastmatch(self):
return self.collector.lastmatch
74 changes: 50 additions & 24 deletions custom_components/rbfa/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,23 @@ class RbfaSensorEntityDescription(SensorEntityDescription):
icon="mdi:map-marker",
),
RbfaSensorEntityDescription(
key="prevposition",
translation_key="prevposition",
key="series",
translation_key="series",
),
RbfaSensorEntityDescription(
key="prevresulthome",
translation_key="prevresulthome",
icon = "mdi:scoreboard"
key="position",
translation_key="position",
),
# RbfaSensorEntityDescription(
# key="hometeamgoals",
# translation_key="hometeamgoals",
# icon = "mdi:scoreboard"
# ),
# RbfaSensorEntityDescription(
# key="awayteamgoals",
# translation_key="awayteamgoals",
# icon = "mdi:scoreboard"
# ),
]

async def async_setup_entry(
Expand All @@ -69,13 +78,26 @@ async def async_setup_entry(
"""Set up Elgato sensor based on a config entry."""
coordinator: MyCoordinator = hass.data[DOMAIN][entry.entry_id]

async_add_entities(
RbfaSensor(
coordinator,
description,
entry,
all_sensors = []
for description in SENSORS:
all_sensors.append(
RbfaSensor(
coordinator,
description,
entry,
collection='upcoming',
)
)
all_sensors.append(
RbfaSensor(
coordinator,
description,
entry,
collection='lastmatch',
)
)
for description in SENSORS
async_add_entities(
all_sensors
)

class RbfaEntity(CoordinatorEntity[MyCoordinator]):
Expand All @@ -95,18 +117,23 @@ def __init__(
coordinator: MyCoordinator,
description: RbfaSensorEntityDescription,
entry,
collection,
) -> None:
super().__init__(coordinator)
self.entity_description = description
self.TeamData = coordinator.upcoming()
self.extra_attributes = {}

self.TeamData = coordinator.matchdata().get(collection)

self.team = entry.data.get('team')
self._attr_unique_id = f"{DOMAIN}_{description.key}_{self.team}"
self._attr_unique_id = f"{DOMAIN}_{collection}_{description.key}_{self.team}"

if description.key == 'hometeam':
self._attr_entity_picture = self.TeamData['homelogo']
if description.key == 'awayteam':
self._attr_entity_picture = self.TeamData['awaylogo']
if description.key == 'hometeam' or description.key == 'awayteam':
self._attr_entity_picture = self.TeamData[description.key + 'logo']
self.extra_attributes = {
'goals': self.TeamData[description.key + 'goals'],
'penalties': self.TeamData[description.key + 'penalties'],
}

@property
def native_value(self):
Expand All @@ -117,16 +144,15 @@ def extra_state_attributes(self):
"""Return attributes for sensor."""

basic_attributes = {
'Team': self.TeamData['teamname'],
'Date': self.TeamData['date'],
'team': self.TeamData['teamname'],
'date': self.TeamData['date'],
}

extra_attributes = {}
if self.entity_description.key == 'prevposition':
extra_attributes = {
'Ranking': self.TeamData['prevranking'],
if self.entity_description.key == 'position':
self.extra_attributes = {
'ranking': self.TeamData['ranking'],
}
return basic_attributes | extra_attributes
return basic_attributes | self.extra_attributes

class HomeSensor(SensorEntity):
"""Representation of a Sensor."""
Expand Down
97 changes: 68 additions & 29 deletions custom_components/rbfa/translations/nl.json
Original file line number Diff line number Diff line change
@@ -1,33 +1,72 @@
{
"config": {
"step": {
"user": {
"data": {
"team": "Identiteit van het team"
}
}
},
"error": {
"already_configured": "[%key:common::config_flow::abort::already_configured_location%]"
},
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_location%]"
}
},
"entity": {
"sensor": {
"hometeam": {
"name": "Thuis"
},
"awayteam": {
"name": "Uit"
"config":{
"step":{
"user":{
"data":{
"team":"Identiteit van het team"
}
}
},
"location": {
"name": "Locatie"
"error":{
"already_configured":"[%key:common::config_flow::abort::already_configured_location%]"
},
"date": {
"name": "Datum"
"abort":{
"already_configured":"[%key:common::config_flow::abort::already_configured_location%]"
}
},
"entity":{
"sensor":{
"hometeam":{
"name":"Thuis",
"state_attributes":{
"team":{
"name":"Elftal"
},
"goals":{
"name":"Doelpunten"
},
"penalties":{
"name":"Strafschoppen"
},
"date":{
"name":"Datum"
}
}
},
"awayteam":{
"name":"Uit"
},
"location":{
"name":"Locatie"
},
"date":{
"name":"Datum"
},
"series":{
"name":"Reeks",
"state_attributes":{
"team":{
"name":"Elftal"
},
"date":{
"name":"Datum"
}
}
},
"position":{
"name":"Positie",
"state_attributes":{
"ranking":{
"name":"Rangschikking"
}
}
},
"hometeamgoals":{
"name":"Score thuis"
},
"awayteamgoals":{
"name":"Score uit"
}
}
}
}
}
}
}

0 comments on commit d2cd8a3

Please sign in to comment.