From feeb4dfb37fac4c372ca75f193477c604ed9d7da Mon Sep 17 00:00:00 2001 From: myTselection Date: Sun, 16 Jul 2023 22:29:00 +0200 Subject: [PATCH] 5.0.0 support for German (DE) Fuel prices added --- README.md | 36 +++-- custom_components/carbu_com/config_flow.py | 11 +- custom_components/carbu_com/manifest.json | 2 +- custom_components/carbu_com/sensor.py | 34 ++-- .../carbu_com/translations/en.json | 8 +- custom_components/carbu_com/utils.py | 152 ++++++++++++++---- 6 files changed, 169 insertions(+), 74 deletions(-) diff --git a/README.md b/README.md index cbdff2f..acca1a1 100644 --- a/README.md +++ b/README.md @@ -7,10 +7,12 @@ [![GitHub commit activity](https://img.shields.io/github/commit-activity/m/myTselection/carbu_com.svg)](https://github.com/myTselection/carbu_com/graphs/commit-activity) # Carbu.com Home Assistant integration -[Carbu.com](https://www.Carbu.com/) Home Assistant custom component. This custom component has been built from the ground up to bring Carbu.com & Mazout.com site data to compare and save on your fuel oil, diesel and Super prices and integrate this information into Home Assistant to help you towards a better follow up. This integration is built against the public website provided by Carbu.com for Belgium and has not been tested for any other countries. - +[Carbu.com](https://www.Carbu.com/) Home Assistant custom component. This custom component has been built from the ground up to bring Carbu.com & Mazout.com site data to compare and save on your fuel oil, diesel and Super prices and integrate this information into Home Assistant to help you towards a better follow up. This integration is built against the public website provided by Carbu.com. This integration is in no way affiliated with Carbu.com. +Since R5.0, support for fuel prices in Germany (DE) has been added. City or postalcode can be provided as location. + + Some discussion on this topic can be found within [the Home Assistant community forum](https://community.home-assistant.io/t/rest-sensor-needs-to-get-latest-element-of-list/404882/4). For electricity price expectations [this Entso-E HACS integration](https://github.com/JaccoR/hass-entso-e) can be used. @@ -22,12 +24,12 @@ For electricity price expectations [this Entso-E HACS integration](https://githu - [HACS](https://hacs.xyz/): add url https://github.com/myTselection/carbu_com as custom repository (HACS > Integration > option: Custom Repositories) - Restart Home Assistant - Add 'Carbu.com' integration via HA Settings > 'Devices and Services' > 'Integrations' -- Provide country (currently only tested with BE), postal code and select the desired sensors - - If your postal code is not unique, the name of the town can be selected from the dropdown in the next step of the setup config flow. See [carbu.com](https://carbu.com) website for known towns and postal codes. +- Provide country, postal code and select the desired sensors + - If your postal code is not unique, the name of the town can be selected from the dropdown in the next step of the setup config flow. See [carbu.com](https://carbu.com) website for known towns and postal codes. (Not supported for DE) - A filter on supplier brand name can be set (optional). If the filter match, the fuel station will be considered, else next will be searched. A python regex filter value be set ## Integration --
Sensor diesel and super sensor.carbu_com_[fueltype]_[postalcode]_price and fuel oil sensor.carbu_com_[fueltype]_[postalcode]_[quantity]l_price +-
Sensor diesel and super sensor.carbu_com_[fueltype]_[postalcode]_price and fuel oil sensor.carbu_com_[fueltype]_[postalcode]_[quantity]l_price Fuel oil only supported for BE/FR/LU | Attribute | Description | | --------- | ----------- | @@ -37,7 +39,7 @@ For electricity price expectations [this Entso-E HACS integration](https://githu | `fuelname` | Full name of the fuel type | | `postalcode` | Postalcode at which the price was retrieved | | **`supplier`** | **Name of the supplier of the fuel** | - | `supplier_brand` | Brand name of the supplier (eg Shell, Texaco, ...) | + | `supplier_brand` | Brand name of the supplier (eg Shell, Texaco, ...) Not supported for DE | | `url` | Url with details of the supplier | | `entity_picture` | Url with the logo of the supplier | | `address` | Address of the supplier | @@ -62,13 +64,13 @@ For electricity price expectations [this Entso-E HACS integration](https://githu | `fuelname` | Full name of the fuel type | | `postalcode` | Postalcode at which the price was retrieved | | `supplier` | Name of the supplier of the fuel | - | `supplier_brand` | Brand name of the supplier (eg Shell, Texaco, ...) | + | `supplier_brand` | Brand name of the supplier (eg Shell, Texaco, ...) Not supported for DE | | `url` | Url with details of the supplier | | `entity_picture` | Url with the logo of the supplier | | `address` | Address of the supplier | | `city` | City of the supplier | - | `latitude` | Latitude of the supplier | - | `longitude` | Longitude of the supplier | + | `latitude` | Latitude of the supplier Not supported for DE | + | `longitude` | Longitude of the supplier Not supported for DE | | `region` | Distand 5km or 10km around postal code in which cheapest prices is found | | **`distance`** | **Distance to the supplier vs postal code** | | **`price diff`** | **Price difference between the cheapest found in region versus the local price** | @@ -79,7 +81,7 @@ For electricity price expectations [this Entso-E HACS integration](https://githu | `score` | Score of the supplier |
--
Sensor diesel and super prediction: sensor.carbu_com_[fueltype]_prediction +-
Sensor diesel and super prediction: sensor.carbu_com_[fueltype]_prediction Only supported for BE/FR/LU | Attribute | Description | | --------- | ----------- | @@ -90,7 +92,7 @@ For electricity price expectations [this Entso-E HACS integration](https://githu | `date` | Date for the validity of the price |
--
Sensor fuel oil prediction: sensor.carbu_com_[oiltype]_[quantity]l_prediction +-
Sensor fuel oil prediction: sensor.carbu_com_[oiltype]_[quantity]l_prediction Only supported for BE/FR/LU | Attribute | Description | | --------- | ----------- | @@ -115,13 +117,13 @@ A **service `carbu_com.get_lowest_fuel_price`** to get the lowest fuel price in | `fuelname` | Full name of the fuel type | | `postalcode` | Postalcode at which the price was retrieved | | `supplier` | Name of the supplier of the fuel | - | `supplier_brand` | Brand name of the supplier (eg Shell, Texaco, ...) | + | `supplier_brand` | Brand name of the supplier (eg Shell, Texaco, ...) Not supported for DE | | `url` | Url with details of the supplier | | `entity_picture` | Url with the logo of the supplier | | `address` | Address of the supplier | | `city` | City of the supplier | - | `latitude` | Latitude of the supplier | - | `longitude` | Longitude of the supplier | + | `latitude` | Latitude of the supplier Not supported for DE | + | `longitude` | Longitude of the supplier Not supported for DE | | `region` | Distand 5km or 10km around postal code in which cheapest prices is found | | **`distance`** | **Distance to the supplier vs postal code** | | **`price diff`** | **Price difference between the cheapest found in region versus the local price** | @@ -194,13 +196,13 @@ A **service `carbu_com.get_lowest_fuel_price_on_route`** (**BETA**) to get the l | `fuelname` | Full name of the fuel type | | `postalcode` | Postalcode at which the price was retrieved | | `supplier` | Name of the supplier of the fuel | - | `supplier_brand` | Brand name of the supplier (eg Shell, Texaco, ...) | + | `supplier_brand` | Brand name of the supplier (eg Shell, Texaco, ...) Not supported for DE | | `url` | Url with details of the supplier | | `entity_picture` | Url with the logo of the supplier | | `address` | Address of the supplier | | `city` | City of the supplier | - | `latitude` | Latitude of the supplier | - | `longitude` | Longitude of the supplier | + | `latitude` | Latitude of the supplier Not supported for DE | + | `longitude` | Longitude of the supplier Not supported for DE | | `region` | Distand 5km or 10km around postal code in which cheapest prices is found | | **`distance`** | **Distance to the supplier vs postal code** | | **`price diff`** | **Price difference between the cheapest found in region versus the local price** | diff --git a/custom_components/carbu_com/config_flow.py b/custom_components/carbu_com/config_flow.py index 7f75c48..1e4ff62 100644 --- a/custom_components/carbu_com/config_flow.py +++ b/custom_components/carbu_com/config_flow.py @@ -51,7 +51,12 @@ def create_schema(entry, option=False): data_schema = OrderedDict() data_schema[ vol.Required("country", default=default_country, description="Country") - ] = str + ] = selector({ + "select": { + "options": ['BE','FR','LU','DE'], + "mode": "dropdown" + } + }) data_schema[ vol.Required("postalcode", default=default_postalcode, description="Postal Code") ] = str @@ -91,7 +96,7 @@ def create_town_schema(towns): "options": towns, "mode": "dropdown" } - }) + }) return data_schema @@ -117,6 +122,8 @@ async def async_step_user(self, user_input=None): # pylint: disable=dangerous-d self._init_info = user_input if not(self._session): self._session = ComponentSession() + if user_input.get('country') == 'DE': + return self.async_create_entry(title=NAME, data=self._init_info) carbuLocationInfo = await self.hass.async_add_executor_job(lambda: self._session.convertPostalCodeMultiMatch(user_input.get('postalcode'), user_input.get('country'))) if len(carbuLocationInfo) > 1: for location in carbuLocationInfo: diff --git a/custom_components/carbu_com/manifest.json b/custom_components/carbu_com/manifest.json index 17f7d6c..8456d83 100644 --- a/custom_components/carbu_com/manifest.json +++ b/custom_components/carbu_com/manifest.json @@ -9,5 +9,5 @@ "iot_class": "cloud_polling", "issue_tracker": "https://github.com/myTselection/carbu_com/issues", "requirements": ["bs4","requests","ratelimit"], - "version": "4.2.0" + "version": "5.0.0" } diff --git a/custom_components/carbu_com/sensor.py b/custom_components/carbu_com/sensor.py index 2734777..a6bcdfc 100644 --- a/custom_components/carbu_com/sensor.py +++ b/custom_components/carbu_com/sensor.py @@ -79,9 +79,10 @@ async def dry_setup(hass, config_entry, async_add_devices): # await sensorSuper95Neigh.async_update() sensors.append(sensorSuper95Neigh) - sensorSuper95Prediction = ComponentFuelPredictionSensor(componentData, FuelType.SUPER95_Prediction) - # await sensorSuper95Prediction.async_update() - sensors.append(sensorSuper95Prediction) + if country != 'DE': + sensorSuper95Prediction = ComponentFuelPredictionSensor(componentData, FuelType.SUPER95_Prediction) + # await sensorSuper95Prediction.async_update() + sensors.append(sensorSuper95Prediction) if super98: @@ -110,11 +111,12 @@ async def dry_setup(hass, config_entry, async_add_devices): # await sensorDieselNeigh.async_update() sensors.append(sensorDieselNeigh) - sensorDieselPrediction = ComponentFuelPredictionSensor(componentData, FuelType.DIESEL_Prediction) - # await sensorDieselPrediction.async_update() - sensors.append(sensorDieselPrediction) + if country != 'DE': + sensorDieselPrediction = ComponentFuelPredictionSensor(componentData, FuelType.DIESEL_Prediction) + # await sensorDieselPrediction.async_update() + sensors.append(sensorDieselPrediction) - if oilstd: + if oilstd and country != 'DE': sensorOilstd = ComponentPriceSensor(componentData, FuelType.OILSTD, postalcode, True, quantity) # await sensorOilstd.async_update() sensors.append(sensorOilstd) @@ -123,7 +125,7 @@ async def dry_setup(hass, config_entry, async_add_devices): # await sensorOilstdPrediction.async_update() sensors.append(sensorOilstdPrediction) - if oilextra: + if oilextra and country != 'DE': sensorOilextra = ComponentPriceSensor(componentData, FuelType.OILEXTRA, postalcode, True, quantity) # await sensorOilextra.async_update() sensors.append(sensorOilextra) @@ -203,7 +205,7 @@ def __init__(self, config, hass): async def get_fuel_price_info(self, fuel_type: FuelType): _LOGGER.debug(f"{NAME} getting fuel price_info {fuel_type.name_lowercase}") - price_info = await self._hass.async_add_executor_job(lambda: self._session.getFuelPrices(self._postalcode, self._country, self._town, self._locationid, fuel_type.code, False)) + price_info = await self._hass.async_add_executor_job(lambda: self._session.getFuelPrices(self._postalcode, self._country, self._town, self._locationid, fuel_type, False)) self._price_info[fuel_type] = price_info _LOGGER.debug(f"{NAME} price_info {fuel_type.name_lowercase} {price_info}") @@ -239,7 +241,7 @@ async def _forced_update(self): if self._session: _LOGGER.debug("Starting with session for " + NAME) - if self._locationid is None: + if self._locationid is None and self._country != 'DE': self._carbuLocationInfo = await self._hass.async_add_executor_job(lambda: self._session.convertPostalCode(self._postalcode, self._country, self._town)) self._town = self._carbuLocationInfo.get("n") self._city = self._carbuLocationInfo.get("pn") @@ -248,7 +250,8 @@ async def _forced_update(self): # postalcode, country, town, locationid, fueltypecode) if self._super95: await self.get_fuel_price_info(FuelType.SUPER95) - await self.get_fuel_price_prediction_info(FuelType.SUPER95_Prediction) + if self._country != 'DE': + await self.get_fuel_price_prediction_info(FuelType.SUPER95_Prediction) else: _LOGGER.debug(f"{NAME} not getting fuel price_info {self._super95} FueltType.SUPER95.name_lowercase {FuelType.SUPER95.name_lowercase}") @@ -257,15 +260,16 @@ async def _forced_update(self): if self._diesel: await self.get_fuel_price_info(FuelType.DIESEL) - await self.get_fuel_price_prediction_info(FuelType.DIESEL_Prediction) + if self._country != 'DE': + await self.get_fuel_price_prediction_info(FuelType.DIESEL_Prediction) - if self._oilstd: + if self._oilstd and self._country != 'DE': await self.get_oil_price_info(FuelType.OILSTD) - if self._oilextra: + if self._oilextra and self._country != 'DE': await self.get_oil_price_info(FuelType.OILEXTRA) - if self._oilstd or self._oilextra: + if self._oilstd or self._oilextra and self._country != 'DE': await self.get_oil_price_prediction_info() self._lastupdate = datetime.now() diff --git a/custom_components/carbu_com/translations/en.json b/custom_components/carbu_com/translations/en.json index 39a3e06..e4067a6 100644 --- a/custom_components/carbu_com/translations/en.json +++ b/custom_components/carbu_com/translations/en.json @@ -5,7 +5,7 @@ "user": { "description": "Setup Carbu.com and Mazout.com sensors.", "data": { - "country": "Country (BE/FR/LU)", + "country": "Country (BE/FR/LU/DE)", "postalcode": "Postal code", "town": "Town", "filter": "Supplier brand filter (optional)", @@ -25,7 +25,7 @@ "edit": { "description": "Setup Carbu.com and Mazout.com sensors.", "data": { - "country": "Country (BE/FR/LU)", + "country": "Country (BE/FR/LU/DE)", "postalcode": "Postal code", "town": "Town", "filter": "Supplier brand filter (optional)", @@ -51,7 +51,7 @@ "edit": { "description": "Setup Carbu.com and Mazout.com sensors.", "data": { - "country": "Country (BE/FR/LU)", + "country": "Country (BE/FR/LU/DE)", "postalcode": "Postal code", "town": "Town", "filter": "Supplier brand filter (optional)", @@ -65,7 +65,7 @@ } }, "error": { - "missing country": "Please provide a valid country: BE/FR/LU", + "missing country": "Please provide a valid country: BE/FR/LU/DE", "missing postal code": "Please provide a valid postal code", "missing data options handler": "Option handler failed", "no_valid_settings": "No valid settings check in ha config." diff --git a/custom_components/carbu_com/utils.py b/custom_components/carbu_com/utils.py index f4fd192..44028e6 100644 --- a/custom_components/carbu_com/utils.py +++ b/custom_components/carbu_com/utils.py @@ -4,6 +4,7 @@ import re from bs4 import BeautifulSoup from ratelimit import limits, sleep_and_retry +from datetime import date import urllib.parse from enum import Enum @@ -30,18 +31,19 @@ def check_settings(config, hass): class FuelType(Enum): - SUPER95 = ("E10") + SUPER95 = ("E10", 5) SUPER95_Prediction = ("E95") - SUPER98 = ("SP98") - DIESEL = ("GO") + SUPER98 = ("SP98", 6) + DIESEL = ("GO",3) DIESEL_Prediction = ("D") OILSTD = ("7") OILSTD_Prediction = ("mazout50s") OILEXTRA = ("2") OILEXTRA_Prediction = ("extra") - def __init__(self, code): + def __init__(self, code, de_code=0): self.code = code + self.de_code = de_code @property def name_lowercase(self): @@ -116,11 +118,13 @@ def convertPostalCodeMultiMatch(self, postalcode, country, town = ''): @sleep_and_retry @limits(calls=1, period=1) - def getFuelPrices(self, postalcode, country, town, locationid, fueltypecode, single): + def getFuelPrices(self, postalcode, country, town, locationid, fueltype: FuelType, single): + if country.lower() == 'de': + return self.getFuelPricesDE(postalcode,country,town,locationid, fueltype, single) header = {"Content-Type": "application/x-www-form-urlencoded"} # https://carbu.com/belgie//liste-stations-service/GO/Diegem/1831/BE_bf_279 - response = self.s.get(f"https://carbu.com/belgie//liste-stations-service/{fueltypecode}/{town}/{postalcode}/{locationid}",headers=header,timeout=50) + response = self.s.get(f"https://carbu.com/belgie//liste-stations-service/{fueltype.code}/{town}/{postalcode}/{locationid}",headers=header,timeout=50) if response.status_code != 200: _LOGGER.error(f"ERROR: {response.text}") assert response.status_code == 200 @@ -193,7 +197,7 @@ def getFuelPrices(self, postalcode, country, town, locationid, fueltypecode, sin except AttributeError: date = "" - stationdetails.append({"id":stationid,"name":name,"url":url,"logo_url":logo_url,"brand":brand,"address":', '.join(el for el in address),"postalcode": address_postalcode, "locality":locality,"price":price,"lat":lat,"lon":lng,"fuelname":fuelname,"distance":distance,"date":date}) + stationdetails.append({"id":stationid,"name":name,"url":url,"logo_url":logo_url,"brand":brand,"address":', '.join(el for el in address),"postalcode": address_postalcode, "locality":locality,"price":price,"lat":lat,"lon":lng,"fuelname":fuelname,"distance":distance,"date":date, "country": country}) # _LOGGER.debug(f"stationdetails: {stationdetails}") if single: @@ -201,6 +205,74 @@ def getFuelPrices(self, postalcode, country, town, locationid, fueltypecode, sin if single: break return stationdetails + + + @sleep_and_retry + @limits(calls=1, period=1) + def getFuelPricesDE(self, postalcode, country, town, locationid, fueltype: FuelType, single): + if country.lower() != 'de': + return self.getFuelPrices(postalcode,country,town,locationid, fueltype, single) + header = {"Content-Type": "application/x-www-form-urlencoded"} + # https://www.clever-tanken.de/tankstelle_liste?lat=&lon=&ort=Kr%C3%BCn&spritsorte=3&r=5 + # _LOGGER.debug(f"https://www.clever-tanken.de/tankstelle_liste?lat=&lon=&ort={postalcode}&spritsorte={fueltype.de_code}&r=25&sort=km") + + response = self.s.get(f"https://www.clever-tanken.de/tankstelle_liste?lat=&lon=&ort={postalcode}&spritsorte={fueltype.de_code}&r=25&sort=km",headers=header,timeout=50) + if response.status_code != 200: + _LOGGER.error(f"ERROR: {response.text}") + assert response.status_code == 200 + + stationdetails = [] + + soup = BeautifulSoup(response.text, 'html.parser') + blocks = soup.find_all('a', href=lambda href: href and href.startswith('/tankstelle_details/')) + # _LOGGER.debug(f"blocks: {len(blocks)}") + + stationdetails = [] + for block in blocks: + url = block['href'] + station_id = url.split('/')[-1] + station_name = block.find('span', class_='fuel-station-location-name').text.strip() + station_street = block.find('div', class_='fuel-station-location-street').text.strip() + station_city = block.find('div', class_='fuel-station-location-city').text.strip() + station_postalcode, station_locality = station_city.split(maxsplit=1) + price_text = block.find('div', class_='price-text') + if price_text != None: + price_text = price_text.text.strip() + else: + continue + price_changed = [span.text.strip() for span in block.find_all('span', class_='price-changed')] + logo_url = block.find('img', class_='mtsk-logo')['src'] + distance = float(block.find('div', class_='fuel-station-location-distance').text.strip().replace(' km','')) + today = date.today() + current_date = today.strftime("%Y-%m-%d") + # _LOGGER.debug(f"blocks id : {station_id}, postalcode: {station_postalcode}") + + + block_data = { + 'id': station_id, + 'name': station_name, + 'url': f"https://www.clever-tanken.de{url}", + 'logo_url': f"https://www.clever-tanken.de/{logo_url}", + 'brand': station_name, + 'address': f"{station_street}, {station_city}", + 'postalcode': station_postalcode, + 'locality': station_locality, + 'price': price_text, + 'price_changed': price_changed, + 'lat': 0, + 'lon': 0, + 'fuelname': fueltype.name, + 'distance': distance, + 'date': current_date, + 'country': country + } + if single: + if postalcode == station_postalcode: + stationdetails.append(block_data) + return stationdetails + else: + stationdetails.append(block_data) + return stationdetails @sleep_and_retry @limits(calls=1, period=1) @@ -314,36 +386,40 @@ def getOilPrediction(self): return oildetails def getStationInfo(self, postalcode, country, fuel_type: FuelType, town="", max_distance=0, filter=""): - - carbuLocationInfo = self.convertPostalCode(postalcode, country, town) - if not carbuLocationInfo: - raise Exception(f"Location not found country: {country}, postalcode: {postalcode}, town: {town}") - town = carbuLocationInfo.get("n") - city = carbuLocationInfo.get("pn") - countryname = carbuLocationInfo.get("cn") - locationid = carbuLocationInfo.get("id") - _LOGGER.debug(f"convertPostalCode postalcode: {postalcode}, town: {town}, city: {city}, countryname: {countryname}, locationid: {locationid}") - price_info = self.getFuelPrices(postalcode, country, town, locationid, fuel_type.code, False) + town = None + locationid = None + if country != "DE": + carbuLocationInfo = self.convertPostalCode(postalcode, country, town) + if not carbuLocationInfo: + raise Exception(f"Location not found country: {country}, postalcode: {postalcode}, town: {town}") + town = carbuLocationInfo.get("n") + city = carbuLocationInfo.get("pn") + countryname = carbuLocationInfo.get("cn") + locationid = carbuLocationInfo.get("id") + _LOGGER.debug(f"convertPostalCode postalcode: {postalcode}, town: {town}, city: {city}, countryname: {countryname}, locationid: {locationid}") + price_info = self.getFuelPrices(postalcode, country, town, locationid, fuel_type, False) # _LOGGER.debug(f"price_info {fuel_type.name} {price_info}") return self.getStationInfoFromPriceInfo(price_info, postalcode, fuel_type, max_distance, filter) + def getStationInfoLatLon(self,latitude, longitude, fuel_type: FuelType, max_distance=0, filter=""): - - postal_code_country = self.reverseGeocodeOSM((longitude, latitude)) - - carbuLocationInfo = self.convertPostalCode(postal_code_country[0], postal_code_country[1]) - if not carbuLocationInfo: - raise Exception(f"Location not found country: {postal_code_country[1]}, postalcode: {postal_code_country[0]}") - town = carbuLocationInfo.get("n") - city = carbuLocationInfo.get("pn") - countryname = carbuLocationInfo.get("cn") - locationid = carbuLocationInfo.get("id") - _LOGGER.debug(f"convertPostalCode postalcode: {postal_code_country[0]}, town: {town}, city: {city}, countryname: {countryname}, locationid: {locationid}") - price_info = self.getFuelPrices(postal_code_country[0], postal_code_country[1], town, locationid, fuel_type.code, False) + town = None + locationid = None + if postal_code_country[1].lower() != "de": + carbuLocationInfo = self.convertPostalCode(postal_code_country[0], postal_code_country[1]) + if not carbuLocationInfo: + raise Exception(f"Location not found country: {postal_code_country[1]}, postalcode: {postal_code_country[0]}") + town = carbuLocationInfo.get("n") + city = carbuLocationInfo.get("pn") + countryname = carbuLocationInfo.get("cn") + locationid = carbuLocationInfo.get("id") + _LOGGER.debug(f"convertPostalCode postalcode: {postal_code_country[0]}, town: {town}, city: {city}, countryname: {countryname}, locationid: {locationid}") + price_info = self.getFuelPrices(postal_code_country[0], postal_code_country[1], town, locationid, fuel_type, False) # _LOGGER.debug(f"price_info {fuel_type.name} {price_info}") return self.getStationInfoFromPriceInfo(price_info, postal_code_country[0], fuel_type, max_distance, filter) + def getStationInfoFromPriceInfo(self,price_info, postalcode, fuel_type: FuelType, max_distance=0, filter=""): data = { @@ -366,9 +442,10 @@ def getStationInfoFromPriceInfo(self,price_info, postalcode, fuel_type: FuelType "longitude" : None, "fuelname" : None, "fueltype" : fuel_type, - "date" : None + "date" : None, + "country": None } - _LOGGER.debug(f"getStationInfoFromPriceInfo {fuel_type.name}, postalcode: {postalcode}, max_distance : {max_distance}, filter: {filter}, price_info: {price_info}") + # _LOGGER.debug(f"getStationInfoFromPriceInfo {fuel_type.name}, postalcode: {postalcode}, max_distance : {max_distance}, filter: {filter}, price_info: {price_info}") filterSet = False if filter is not None and filter.strip() != "": @@ -393,7 +470,7 @@ def getStationInfoFromPriceInfo(self,price_info, postalcode, fuel_type: FuelType data["localPrice"] = 0 if price_info[0].get("price") == '' else float(price_info[0].get("price")) data["diff"] = round(data["price"] - data["localPrice"],3) data["diff30"] = round(data["diff"] * 30,3) - data["diffPct"] = round(100*((data["price"] - data["localPrice"])/data["price"]),3) + data["diffPct"] = 0 if data["price"] == 0 else round(100*((data["price"] - data["localPrice"])/data["price"]),3) data["supplier"] = station.get("name") data["supplier_brand"] = station.get("brand") data["url"] = station.get("url") @@ -407,14 +484,18 @@ def getStationInfoFromPriceInfo(self,price_info, postalcode, fuel_type: FuelType data["date"] = station.get("date") if data["postalcode"] not in data["postalcodes"]: data["postalcodes"].append(data["postalcode"]) + data['country'] = station.get('country') + # _LOGGER.debug(f"before break {max_distance}, country: {station.get('country') }, postalcode: {station.get('postalcode')} required postalcode {postalcode}") if max_distance == 0: - break + # _LOGGER.debug(f"break {max_distance}, country: {station.get('country') }, postalcode: {station.get('postalcode')} required postalcode {postalcode}") + break if data["supplier"] is None and filterSet: _LOGGER.warning(f"{postalcode} the station filter '{filter}' may result in no results found, if needed, please review filter") _LOGGER.debug(f"get_lowest_fuel_price info found: {data}") return data + # NOT USED def geocodeHere(self, country, postalcode, here_api_key): header = {"Content-Type": "application/x-www-form-urlencoded"} # header = {"Accept-Language": "nl-BE"} @@ -435,7 +516,7 @@ def geocodeHere(self, country, postalcode, here_api_key): location = response.json()["items"][0]["position"] return location - + # NOT USED def getPriceOnRouteORS(self, country, fuel_type: FuelType, from_postalcode, to_postalcode, ors_api_key, filter = ""): from_location = self.geocodeORS(country, from_postalcode, ors_api_key) assert from_location is not None @@ -463,7 +544,7 @@ def getPriceOnRouteORS(self, country, fuel_type: FuelType, from_postalcode, to_p return bestStationOnRoute - + #USED BY Service: handle_get_lowest_fuel_price_on_route def getPriceOnRoute(self, country, fuel_type: FuelType, from_postalcode, to_postalcode, to_country = "", filter = ""): from_location = self.geocodeOSM(country, from_postalcode) assert from_location is not None @@ -474,6 +555,7 @@ def getPriceOnRoute(self, country, fuel_type: FuelType, from_postalcode, to_post return self.getPriceOnRouteLatLon(fuel_type, from_location[0], from_location[1], to_location[0], to_location[1], filter) + #USED BY Service: handle_get_lowest_fuel_price_on_route_coor def getPriceOnRouteLatLon(self, fuel_type: FuelType, from_latitude, from_longitude, to_latitude, to_longitude, filter = ""): from_location = (from_latitude, from_longitude) assert from_location is not None