Skip to content

Commit

Permalink
nou readme i millores
Browse files Browse the repository at this point in the history
  • Loading branch information
oscarsanchezdm committed Aug 20, 2024
1 parent eb681ad commit 6fab140
Show file tree
Hide file tree
Showing 6 changed files with 24 additions and 84 deletions.
28 changes: 12 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,28 @@


## Què és?

Una integració per a monitoritzar l'estat del servei del Bicing al Home Assistant. El motiu que m'ha portat a desenvolupar-lo és per, a banda d'aprendre com funcionen les integracions del Home Assistant, saber quantes bicicletes elèctriques hi ha abans de sortir per anar a treballar.


## Instal·lació


### Directa usando _My Home Assistant_
### Usant _My Home Assistant_
[![Open your Home Assistant instance and open a repository inside the Home Assistant Community Store.](https://my.home-assistant.io/badges/hacs_repository.svg)](https://my.home-assistant.io/redirect/hacs_repository/?owner=oscarsanchezdm&repository=bicing-hassio&category=integration)


### Manual

```
HACS -> Integraciones -> Tres puntitos -> Repositorios Personalizados
```



## Configuració
Et farà falta generar un token del servei de dades obertes de l'Ajuntament de Barcelona. Pots obtenir-ne un de forma completament gratuïta des d'[aquest enllaç](https://opendata-ajuntament.barcelona.cat/ca/tokens)

Un cop tinguis el token, caldrà que afegeixis una entrada des de la pantalla d'integracions del Home Assistant. A continuació, enganxa el token obtingut i selecciona les estacions del Bicing que vulguis monitoritzar. Més tard podràs afegir-ne més usant el botó de reconfigurar.

![Chart](images/chart.png)


Es crearà una entitat per a cadascuna de les estacions. El valor de l'entitat serà el nombre total de bicicletes disponibles a l'estació i, els atributs seran els següents:
- Bicicletes elèctriques disponibles
- Bicicletes mecàniques disponibles
- Ancoratges disponibles

Amb aquestes dades, podràs crear automatitzacions per a que et notifiqui si queden bicicletes o no, ancoratges, etc.

## Origen de les dades
[Informació de les estacions del Bicing](https://opendata-ajuntament.barcelona.cat/data/ca/dataset/informacio-estacions-bicing)
[Estat de les estacions del Bicing](https://opendata-ajuntament.barcelona.cat/data/ca/dataset/estat-estacions-bicing)

## Origen de los Datos - Obtenció del token

78 changes: 11 additions & 67 deletions custom_components/bicing/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,7 @@
TextSelector
)

from homeassistant.helpers.entity_registry import (
async_entries_for_config_entry,
async_entries_for_device,
)
from homeassistant.helpers.entity_registry import async_entries_for_config_entry
from homeassistant.const import STATE_UNAVAILABLE

from homeassistant.helpers import config_validation as cv # type: ignore
Expand All @@ -42,13 +39,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
VERSION = 1
token: str
station_ids: []

reauth_entry: config_entries.ConfigEntry | None = None

#@staticmethod
#@callback
#def async_get_options_flow(config_entry):
# return OptionFlowHandler(config_entry)
config_entry: config_entries.ConfigEntry | None = None

async def async_step_user(self, user_input: dict[str, Any] | None = None) -> FlowResult:
if user_input is not None:
Expand Down Expand Up @@ -93,7 +84,7 @@ async def async_step_token(self, user_input: dict[str, Any] | None = None) -> Fl
self.token = user_input[TOKEN]
return await self.async_update_token(data={
TOKEN: user_input[TOKEN],
CONF_STATION_IDS: self.reauth_entry.data[CONF_STATION_IDS]
CONF_STATION_IDS: self.config_entry.data[CONF_STATION_IDS]
})

schema = vol.Schema({
Expand All @@ -104,7 +95,7 @@ async def async_step_token(self, user_input: dict[str, Any] | None = None) -> Fl

async def async_step_reauth(self, user_input=None):
"""Perform reauth upon an API authentication error."""
self.reauth_entry = self.hass.config_entries.async_get_entry(
self.config_entry = self.hass.config_entries.async_get_entry(
self.context["entry_id"]
)
return await self.async_step_reauth_confirm()
Expand All @@ -120,18 +111,18 @@ async def async_step_reauth_confirm(self, user_input=None):

async def async_update_token(self, data: dict) -> dict:
"""Create an oauth config entry or update existing entry for reauth."""
if self.reauth_entry:
if self.config_entry:
return self.async_update_reload_and_abort(
self.reauth_entry,
self.config_entry,
data=data,
)
return await super().async_update_token(data)

async def async_step_reconfigure(self, user_input: dict[str, Any] | None = None):
self.reauth_entry = self.hass.config_entries.async_get_entry(self.context["entry_id"])
self.config_entry = self.hass.config_entries.async_get_entry(self.context["entry_id"])

estacions_actuals = self.reauth_entry.data[CONF_STATION_IDS]
token_actual = self.reauth_entry.data[TOKEN]
estacions_actuals = self.config_entry.data[CONF_STATION_IDS]
token_actual = self.config_entry.data[TOKEN]

if user_input is not None:
station_ids = []
Expand All @@ -142,12 +133,12 @@ async def async_step_reconfigure(self, user_input: dict[str, Any] | None = None)
self.station_ids = station_ids

self.hass.config_entries.async_update_entry(
self.reauth_entry, data={TOKEN: token_actual, CONF_STATION_IDS: station_ids}, options=self.reauth_entry.options
self.config_entry, data={TOKEN: token_actual, CONF_STATION_IDS: station_ids}, options=self.config_entry.options
)

# buscar entitats antigues
entity_registry = self.hass.helpers.entity_registry.async_get()
entity_entries = async_entries_for_config_entry(entity_registry, self.reauth_entry.entry_id)
entity_entries = async_entries_for_config_entry(entity_registry, self.config_entry.entry_id)

entities_to_remove = []
_LOGGER.error(entity_entries)
Expand Down Expand Up @@ -180,50 +171,3 @@ async def async_step_reconfigure(self, user_input: dict[str, Any] | None = None)

return self.async_show_form(step_id="reconfigure", data_schema=schema)


class OptionFlowHandler(config_entries.OptionsFlow):
#TODO: esborrar entitats quan es treuen de la llista. revisar que siguin uniques i no es repeteixin

def __init__(self, config_entry):
self.config_entry = config_entry

async def async_update_data(self, data: dict) -> dict:
"""Create an oauth config entry or update existing entry for reauth."""
if self.config_entry:
return self.async_update_reload_and_abort(
self.config_entry,
data=data,
)
return await super().async_update_token(data)

async def async_step_init(self, user_input=None):
estacions_actuals = self.config_entry.options.get(CONF_STATION_IDS, self.config_entry.data[CONF_STATION_IDS])
token_actual = self.config_entry.options.get(TOKEN, self.config_entry.data[TOKEN])

if user_input is not None:
station_ids = []

for station_input in user_input[CONF_STATION_IDS]:
station_ids.append(station_input)

return await self.async_update_data(data={
TOKEN: token_actual,
CONF_STATION_IDS: station_ids,
})

try:
stations = await BikeStationApi.get_bike_stations(token_actual)
except aiohttp.ContentTypeError as exc: #token error
return self.async_abort(reason="token_error")
except aiohttp.ServerConnectionError as exc:
return self.async_abort(reason="status_error")

options = list(map(lambda p: SelectOptionDict(label=str(p.id) + " - " + p.name, value=str(p.id)), stations))

schema = vol.Schema({
vol.Required(CONF_STATION_IDS,default=list(estacions_actuals)): SelectSelector(
SelectSelectorConfig(options=options, multiple=True, mode=SelectSelectorMode.DROPDOWN)
)
})

return self.async_show_form(step_id="init", data_schema=schema)
2 changes: 1 addition & 1 deletion custom_components/bicing/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
"iot_class": "cloud_polling",
"issue_tracker": "https://github.com/oscarsanchezdm/bicing-hassio/issues",
"requirements": [],
"version": "0.2"
"version": "0.3"
}
Binary file removed images/chart.png
Binary file not shown.
Binary file removed images/wizard1.png
Binary file not shown.
Binary file removed images/wizard2.png
Binary file not shown.

0 comments on commit 6fab140

Please sign in to comment.