Skip to content

Commit

Permalink
normalize names and add fuel type attr (#71)
Browse files Browse the repository at this point in the history
* normalize names

* Add fuel type on sensor attributes

* use title

* add stations

* code improvments

* Allow to override station data from local file (address, postal code, city, brand, logo)
  • Loading branch information
Aohzan authored Nov 3, 2024
1 parent 0ae1024 commit 0b5e73d
Show file tree
Hide file tree
Showing 10 changed files with 19,570 additions and 19,504 deletions.
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
# CHANGELOG

## 3.8.0

- Normalize name, address and city of stations if put in uppercase or lowercase exclusively
- Allow to override station data from local file (address, postal code, city, brand, logo)
- Add fuel type on sensor attributes
- Add icon for service
- Sensor entity will now restore last value after a restart if price is not available

## 3.7.0

- Add lat/lon to the output of the service call

## 3.6.0

- Fix event loop warning
Expand Down
21 changes: 16 additions & 5 deletions README.fr.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,13 @@ Un service est mis à disposition pour trouver le meilleur prix d'un carburant d

### Ajouter/modifier une station

Faire une PR en ajoutant/modifiant la station dans le fichier [stations_name.json](custom_components/prix_carburant/stations_name.json). Bien vérifier que le champs `Marque` corresponde à une marque existante en respectant la casse.
Faire une PR en ajoutant/modifiant la station dans le fichier [stations_name.json](custom_components/prix_carburant/stations_name.json). Bien vérifier que le champs `brand` corresponde à une marque existante en respectant la casse. Il est possible de surcharger par rapport aux données fournis par l'API les informations suivantes:

- `name`: Nom de la station
- `brand`: Marque de la station
- `address`: Adresse de la station
- `postal_code`: Code postal de la station
- `city`: Ville de la station

### Ajouter/corriger une image d'entité (entity picture)

Expand Down Expand Up @@ -326,10 +332,14 @@ card_mod:
margin-top: 0em;
}
```

### Créer une carte et indiquer les stations autour d'un device movible

Note: c'est un exemple donc on peut changer comme on veut.

1. Créer le sensor avec des stations autour de 'toi'
Utiliser le service (action)

```
template:
- trigger:
Expand All @@ -349,13 +359,14 @@ template:
attributes:
stations: "{{ stations_feed.stations }}"
```
Ça donne
![image](https://github.com/user-attachments/assets/fc174513-9a06-4d19-a752-f4e91b16b81e)
Ça donne
![image](https://github.com/user-attachments/assets/fc174513-9a06-4d19-a752-f4e91b16b81e)
2. l'automatisation pour créer des zones qui représentent les stations
Important: il faut installer ['spook'](https://github.com/frenck/spook) pour avoir les services/actions 'create zone' et 'delete zone'
Ici par exemple chaque minute une maj (trops je pense) mais on peut aussi utiliser un trigger quand le mobile bouge
Ici par exemple chaque minute une maj (trops je pense) mais on peut aussi utiliser un trigger quand le mobile bouge
```
alias: Station Zones
description: ""
Expand Down Expand Up @@ -384,11 +395,11 @@ action:
longitude: "{{ repeat.item.longitude }}"
mode: single
```
3. Créer la carte
![image](https://github.com/user-attachments/assets/77be362e-7f2a-4cfd-93ee-2165469a1469)
```
type: custom:auto-entities
card:
Expand Down
7 changes: 6 additions & 1 deletion custom_components/prix_carburant/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@
import logging

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_NAME, CONF_SCAN_INTERVAL, ATTR_LATITUDE, ATTR_LONGITUDE
from homeassistant.const import (
ATTR_LATITUDE,
ATTR_LONGITUDE,
ATTR_NAME,
CONF_SCAN_INTERVAL,
)
from homeassistant.core import (
HomeAssistant,
ServiceCall,
Expand Down
3 changes: 2 additions & 1 deletion custom_components/prix_carburant/button.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Prix Carburant button platform."""

from __future__ import annotations

import logging
Expand Down Expand Up @@ -35,7 +36,7 @@ def __init__(self, coordinator) -> None:
self._attr_device_class = ButtonDeviceClass.UPDATE
self._attr_name = "Prix Carburant - Refresh prices"
self._attr_icon = "mdi:refresh-circle"
self._attr_unique_id = "_".join([DOMAIN, "refresh_button"])
self._attr_unique_id = f"{DOMAIN}_refresh_button"

async def async_press(self) -> None:
"""Press the button."""
Expand Down
15 changes: 10 additions & 5 deletions custom_components/prix_carburant/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
"""Config flow to configure the Prix Carburant integration."""

from __future__ import annotations

from collections.abc import Mapping
from typing import Any

import voluptuous as vol

from homeassistant.config_entries import ConfigEntry, ConfigFlow, OptionsFlow
from homeassistant.config_entries import (
ConfigEntry,
ConfigFlow,
ConfigFlowResult,
OptionsFlow,
)
from homeassistant.const import CONF_SCAN_INTERVAL
from homeassistant.core import callback
from homeassistant.data_entry_flow import FlowResult

from .const import (
CONF_DISPLAY_ENTITY_PICTURES,
Expand Down Expand Up @@ -65,7 +70,7 @@ class PrixCarburantConfigFlow(ConfigFlow, domain=DOMAIN):

VERSION = 1

async def async_step_import(self, import_info) -> FlowResult:
async def async_step_import(self, import_info) -> ConfigFlowResult:
"""Import a config entry from YAML config."""
entry = await self.async_set_unique_id(DOMAIN)

Expand All @@ -75,7 +80,7 @@ async def async_step_import(self, import_info) -> FlowResult:

return self.async_create_entry(title=DEFAULT_NAME, data=import_info)

async def async_step_user(self, user_input=None) -> FlowResult:
async def async_step_user(self, user_input=None) -> ConfigFlowResult:
"""Get configuration from the user."""
errors: dict[str, str] = {}
if user_input is None:
Expand Down Expand Up @@ -107,7 +112,7 @@ def __init__(self, config_entry: ConfigEntry) -> None:
"""Initialize options flow."""
self.config_entry = config_entry

async def async_step_init(self, user_input) -> FlowResult:
async def async_step_init(self, user_input) -> ConfigFlowResult:
"""Manage the options."""
errors: dict[str, str] = {}
if user_input is not None:
Expand Down
4 changes: 3 additions & 1 deletion custom_components/prix_carburant/const.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""Constants for the Prix Carburant integration."""

from typing import Final

from homeassistant.const import Platform

DOMAIN: Final = "prix_carburant"
PLATFORMS: Final = [Platform.SENSOR, Platform.BUTTON]
PLATFORMS: Final = [Platform.BUTTON, Platform.SENSOR]

DEFAULT_NAME: Final = "Prix Carburant"
DEFAULT_MAX_KM: Final = 15
Expand All @@ -16,6 +17,7 @@
ATTR_CITY = "city"
ATTR_DISTANCE = "distance"
ATTR_FUELS = "fuels"
ATTR_FUEL_TYPE = "fuel_type"
ATTR_UPDATED_DATE = "updated_date"
ATTR_DAYS_SINCE_LAST_UPDATE = "days_since_last_update"
ATTR_PRICE = "price"
Expand Down
2 changes: 1 addition & 1 deletion custom_components/prix_carburant/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@
"iot_class": "cloud_polling",
"issue_tracker": "https://github.com/Aohzan/hass-prixcarburant/issues",
"requirements": [],
"version": "3.7.0-2"
"version": "3.8.0"
}
19 changes: 12 additions & 7 deletions custom_components/prix_carburant/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@

import voluptuous as vol

from homeassistant.components.sensor import SensorDeviceClass, SensorEntity
from homeassistant.components.sensor import (
PLATFORM_SCHEMA_BASE,
RestoreSensor,
SensorDeviceClass,
)
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE, ATTR_NAME, CURRENCY_EURO
from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.config_validation import PLATFORM_SCHEMA_BASE
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
Expand All @@ -24,6 +27,7 @@
ATTR_CITY,
ATTR_DAYS_SINCE_LAST_UPDATE,
ATTR_DISTANCE,
ATTR_FUEL_TYPE,
ATTR_FUELS,
ATTR_POSTAL_CODE,
ATTR_PRICE,
Expand All @@ -34,7 +38,7 @@
DOMAIN,
FUELS,
)
from .tools import PrixCarburantTool, get_entity_picture
from .tools import PrixCarburantTool, get_entity_picture, normalize_string

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -92,7 +96,7 @@ async def async_setup_entry(
async_add_entities(entities, True)


class PrixCarburant(CoordinatorEntity, SensorEntity):
class PrixCarburant(CoordinatorEntity, RestoreSensor):
"""Representation of a Sensor."""

_attr_icon = "mdi:gas-station"
Expand Down Expand Up @@ -129,16 +133,17 @@ def __init__(
configuration_url="https://www.prix-carburants.gouv.fr/",
)
self._attr_extra_state_attributes = {
ATTR_NAME: self.station_info[ATTR_NAME],
ATTR_NAME: normalize_string(self.station_info[ATTR_NAME]),
ATTR_BRAND: self.station_info[ATTR_BRAND],
ATTR_ADDRESS: self.station_info[ATTR_ADDRESS],
ATTR_ADDRESS: normalize_string(self.station_info[ATTR_ADDRESS]),
ATTR_POSTAL_CODE: self.station_info[ATTR_POSTAL_CODE],
ATTR_CITY: self.station_info[ATTR_CITY],
ATTR_CITY: normalize_string(self.station_info[ATTR_CITY]),
ATTR_LATITUDE: self.station_info[ATTR_LATITUDE],
ATTR_LONGITUDE: self.station_info[ATTR_LONGITUDE],
ATTR_DISTANCE: self.station_info[ATTR_DISTANCE],
ATTR_UPDATED_DATE: None,
ATTR_DAYS_SINCE_LAST_UPDATE: None,
ATTR_FUEL_TYPE: self.fuel,
}

@property
Expand Down
Loading

0 comments on commit 0b5e73d

Please sign in to comment.