Skip to content

Commit

Permalink
Add refresh action
Browse files Browse the repository at this point in the history
  • Loading branch information
amaximus committed Nov 20, 2024
1 parent 0267343 commit 93056c6
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 5 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ Define sensors with the following configuration parameters:<br />
| minsBefore | **Y** | `0` | Skip vehicles departing from station in `minsBefore` minutes, e.g. while walking to the station. Use non-positive value! |
---

The integration provides an action ```bkk_stop:refresh``` for instant refresh requiring an entity_id.

On begining of June the test API key has been revoked, therefore to use this integration you'll have to create an account
at [opendata.bkk.hu](https://opendata.bkk.hu/), generate an API key for yourself and set that in the integration configuration.

Expand Down
2 changes: 1 addition & 1 deletion custom_components/bkk_stop/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
"codeowners": ["@amaximus"],
"iot_class": "cloud_polling",
"requirements": [],
"version": "2.9.11"
"version": "2.10.0"
}
47 changes: 43 additions & 4 deletions custom_components/bkk_stop/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
import time
import voluptuous as vol

from homeassistant.core import ServiceCall
from homeassistant.components.sensor import PLATFORM_SCHEMA, ENTITY_ID_FORMAT
from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME, ATTR_ENTITY_ID
from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME, ATTR_ENTITY_ID, CONF_ENTITY_ID
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity, async_generate_entity_id
Expand All @@ -33,6 +34,14 @@

DEFAULT_NAME = 'Budapest GO'
DEFAULT_ICON = 'mdi:bus'
DOMAIN = "bkk_stop"
SENSOR_PLATFORM = "sensor"

REFRESH_SCHEMA = vol.Schema(
{
vol.Required(CONF_ENTITY_ID): vol.All(cv.ensure_list, [cv.string]),
}
)

HTTP_TIMEOUT = 60 # secs
MAX_RETRIES = 3
Expand All @@ -59,6 +68,7 @@ async def async_setup_platform(hass, config, async_add_devices, discovery_info=N

name = config.get(CONF_NAME)
entityid = config.get(ATTR_ENTITY_ID)

stopid = config.get(CONF_STOPID)
maxitems = config.get(CONF_MAXITEMS)
minsafter = config.get(CONF_MINSAFTER)
Expand All @@ -78,10 +88,15 @@ async def async_setup_platform(hass, config, async_add_devices, discovery_info=N
def _sleep(secs):
time.sleep(secs)


class BKKPublicTransportSensor(Entity):

def __init__(self, hass, name, entityid, stopid, minsafter, wheelchair, bikes, colors, ignorenow, maxitems, routes, inpredicted, apikey, headsigns, minsbefore):

async def handle_refresh(call: ServiceCall) -> None:
"""Handle the refresh service call."""
_LOGGER.debug("called refesh for %s", self._stopid)
self.async_schedule_update_ha_state(force_refresh=True)

"""Initialize the sensor."""
self._name = name
self._hass = hass
Expand All @@ -106,6 +121,15 @@ def __init__(self, hass, name, entityid, stopid, minsafter, wheelchair, bikes, c
else:
self.entity_id = async_generate_entity_id(ENTITY_ID_FORMAT, entityid, None, hass)

hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN].setdefault(SENSOR_PLATFORM, {})
hass.services.async_register(
DOMAIN,
"refresh",
handle_refresh,
schema=REFRESH_SCHEMA,
)

@property
def extra_state_attributes(self):
bkkjson = {}
Expand Down Expand Up @@ -175,6 +199,7 @@ def extra_state_attributes(self):
break
dt_now = datetime.now()
bkkjson["updatedAt"] = dt_now.strftime("%Y/%m/%d %H:%M")
self._state = bkkjson["vehicles"][0]["in"]

return bkkjson

Expand All @@ -199,8 +224,6 @@ async def async_update(self):
_LOGGER.error(f'error: {err} of type: {type(err)}')
await self._hass.async_add_executor_job(_sleep, 10)

self._state = 1

if 'status' in self._bkkdata:
if self._bkkdata["status"] != "OK":
self._state = None
Expand All @@ -213,16 +236,32 @@ async def async_update(self):
else:
self._state = None

_LOGGER.debug("bkk_stop updated for " + self._stopid + ": " + str(self._state))

return self._state

@property
def name(self):
return self._name

@property
def native_value(self) -> object:
"""Return the state of the sensor."""
return self._state

@property
def state(self):
return self._state

@property
def unique_id(self) -> str:
return self.entity_id

def __repr__(self) -> str:
"""Return main sensor parameters."""
return (
f"{self.__class__.__name__}(name={self._name}, "
f"entity_id={self.entity_id}, "
f"state={self.state}, "
f"attributes={self.extra_state_attributes})"
)
9 changes: 9 additions & 0 deletions custom_components/bkk_stop/services.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
refresh:
description: Refresh Budapest GO stop data
target:
entity:
integration: bkk_stop
fields:
entity_id:
description: The BKK stop sensor entity_id
example: sensor.bkk_99b

0 comments on commit 93056c6

Please sign in to comment.