Skip to content

Commit

Permalink
bugfixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Bram van Dartel committed Dec 18, 2024
1 parent 0632338 commit e292134
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 65 deletions.
46 changes: 23 additions & 23 deletions custom_components/afvalwijzer/__init__.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
# from homeassistant.config_entries import ConfigEntry
# from homeassistant.core import HomeAssistant
# from homeassistant.helpers.typing import ConfigType
# from .const.const import DOMAIN
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType
from .const.const import DOMAIN


# async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
# """Set up the Afvalwijzer integration."""
# hass.data.setdefault(DOMAIN, {})
# return True
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the Afvalwijzer integration."""
hass.data.setdefault(DOMAIN, {})
return True


# async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
# """Set up Afvalwijzer from a config entry."""
# # Store config entry data
# hass.data[DOMAIN][entry.entry_id] = entry.data
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Afvalwijzer from a config entry."""
# Store config entry data
hass.data[DOMAIN][entry.entry_id] = entry.data

# # Forward the setup to the sensor platform
# await hass.config_entries.async_forward_entry_setups(entry, ["sensor"])
# return True
# Forward the setup to the sensor platform
await hass.config_entries.async_forward_entry_setups(entry, ["sensor"])
return True


# async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
# """Unload a config entry."""
# # Remove stored data
# if entry.entry_id in hass.data[DOMAIN]:
# hass.data[DOMAIN].pop(entry.entry_id)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
# Remove stored data
if entry.entry_id in hass.data[DOMAIN]:
hass.data[DOMAIN].pop(entry.entry_id)

# # Unload the sensor platform
# await hass.config_entries.async_forward_entry_unload(entry, "sensor")
# return True
# Unload the sensor platform
await hass.config_entries.async_forward_entry_unload(entry, "sensor")
return True
57 changes: 20 additions & 37 deletions custom_components/afvalwijzer/collector/afvalalert.py
Original file line number Diff line number Diff line change
@@ -1,62 +1,45 @@
from ..const.const import _LOGGER, SENSOR_COLLECTOR_TO_URL
from ..const.const import _LOGGER, SENSOR_COLLECTORS_AFVALALERT
from ..common.main_functions import _waste_type_rename
from datetime import datetime

import requests
from urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


def get_waste_data_raw(
provider,
postal_code,
street_number,
suffix,
):
url = f"{SENSOR_COLLECTOR_TO_URL[provider][0]}"
def get_waste_data_raw(provider, postal_code, street_number, suffix):
if provider not in SENSOR_COLLECTORS_AFVALALERT:
raise ValueError(f"Invalid provider: {provider}, please verify")

try:
get_url = f'{url}/{postal_code}/{street_number}{suffix}'
raw_response = requests.get(get_url, timeout=60, verify=False)
suffix = "a"
url = SENSOR_COLLECTORS_AFVALALERT[provider]

response = requests.get('{}/{}/{}{}'.format(url, postal_code, street_number, suffix), timeout=60, verify=False)
print(response)
response.raise_for_status() # Raise an HTTPError for bad responses
except requests.exceptions.RequestException as err:
raise ValueError(err) from err

try:
response = raw_response.json()
except ValueError as err:
raise ValueError(f"Invalid and/or no data received from {url}") from err

if not response:
_LOGGER.error("No waste data found!")
return
return []

try:

for item in response['items']:
print(item)
waste_data_raw = []

try:
for item in response['items']:
if not item['date']:
continue
waste_type = _waste_type_rename(item["menu_title"].strip().lower())
waste_type =_waste_type_rename(item['type'])
if not waste_type:
continue
waste_date=datetime.strptime(item['date'], '%Y-%m-%d'),
waste_data_raw.append({"type": waste_type, "date": waste_date})

# waste_data_raw_temp = requests.get(url, timeout=60, verify=False).json()
# waste_data_raw = []
# for item in waste_data_raw_temp:
# if not item["ophaaldatum"]:
# continue
# waste_type = item["menu_title"]
# if not waste_type:
# continue
# temp = {"type": _waste_type_rename(item["menu_title"].strip().lower())}
# temp["date"] = datetime.strptime(item["ophaaldatum"], "%Y-%m-%d").strftime(
# "%Y-%m-%d"
# )
# waste_data_raw.append(temp)
except ValueError as err:
raise ValueError(f"Invalid and/or no data received from {url}") from err
except requests.exceptions.RequestException as exc:
_LOGGER.error('Error occurred while fetching data: %r', exc)
return False

return waste_data_raw

Expand Down
10 changes: 9 additions & 1 deletion custom_components/afvalwijzer/collector/main_collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from ..const.const import (
_LOGGER,
SENSOR_COLLECTORS_AFVALWIJZER,
SENSOR_COLLECTORS_AFVALALERT,
SENSOR_COLLECTORS_BURGERPORTAAL,
SENSOR_COLLECTORS_CIRCULUS,
SENSOR_COLLECTORS_DEAFVALAPP,
Expand All @@ -13,7 +14,7 @@
)

try:
from . import burgerportaal, circulus, deafvalapp, icalendar, mijnafvalwijzer, opzet, rd4, rova, rwm, ximmio
from . import afvalalert, burgerportaal, circulus, deafvalapp, icalendar, mijnafvalwijzer, opzet, rd4, rova, rwm, ximmio
except ImportError as err:
_LOGGER.error(f"Import error {err.args}")

Expand Down Expand Up @@ -53,6 +54,13 @@ def __init__(
self.street_number,
self.suffix,
)
elif provider in SENSOR_COLLECTORS_AFVALALERT.keys():
waste_data_raw = afvalalert.get_waste_data_raw(
self.provider,
self.postal_code,
self.street_number,
self.suffix,
)
elif provider in SENSOR_COLLECTORS_BURGERPORTAAL.keys():
waste_data_raw = burgerportaal.get_waste_data_raw(
self.provider,
Expand Down
1 change: 0 additions & 1 deletion custom_components/afvalwijzer/collector/ximmio.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ def get_waste_data_raw(provider, postal_code, street_number, suffix):

if suffix:
data["HouseLetter"] = suffix
print(data)
response = requests.post(url="{}/api/FetchAdress".format(url), timeout=60, data=data).json()

if not response['dataList']:
Expand Down
4 changes: 4 additions & 0 deletions custom_components/afvalwijzer/const/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@
"rd4": "https://data.rd4.nl/api/v1/waste-calendar?postal_code={0}&house_number={1}&house_number_extension={2}&year={3}",
}

SENSOR_COLLECTORS_AFVALALERT = {
"afvalalert": "https://www.afvalalert.nl/kalender",
}

SENSOR_COLLECTORS_CIRCULUS = {
"circulus": "https://mijn.circulus.nl",
}
Expand Down
11 changes: 8 additions & 3 deletions custom_components/afvalwijzer/tests/test_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,14 @@
# postal_code = "5146eg"
# street_number = "1"

provider = "mijnafvalwijzer"
postal_code = "5563CM"
street_number = "22"
# provider = "mijnafvalwijzer"
# postal_code = "5563CM"
# street_number = "22"

# Afvalalert
provider = "afvalalert"
postal_code = "7881NW"
street_number = "4"

# ACV
# provider = "acv"
Expand Down

0 comments on commit e292134

Please sign in to comment.