Skip to content

Commit b0fbf65

Browse files
committed
Sensoren und Ports
1 parent 9f1c054 commit b0fbf65

3 files changed

Lines changed: 85 additions & 54 deletions

File tree

custom_components/enpal_webparser/button.py

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import logging
2-
import requests
2+
import aiohttp
3+
from homeassistant.helpers.aiohttp_client import async_get_clientsession
34
from homeassistant.components.button import ButtonEntity
45
from homeassistant.helpers.entity import EntityCategory
56
from .const import DOMAIN
@@ -19,18 +20,19 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
1920
if not options.get("use_wallbox_addon", False):
2021
return
2122

22-
base_url = "http://localhost:8090/wallbox"
23+
base_url = "http://localhost:36725/wallbox"
2324
buttons = [
24-
EnpalWallboxButton("Start Charging", f"{base_url}/start", "start"),
25-
EnpalWallboxButton("Stop Charging", f"{base_url}/stop", "stop"),
25+
EnpalWallboxButton(hass, "Start Charging", f"{base_url}/start", "start"),
26+
EnpalWallboxButton(hass, "Stop Charging", f"{base_url}/stop", "stop"),
2627
]
2728
for key, label in MODES.items():
28-
buttons.append(EnpalWallboxButton(f"Set {label}", f"{base_url}/set_{key}", f"set_{key}"))
29+
buttons.append(EnpalWallboxButton(hass, f"Set {label}", f"{base_url}/set_{key}", f"set_{key}"))
2930

3031
async_add_entities(buttons)
3132

3233
class EnpalWallboxButton(ButtonEntity):
33-
def __init__(self, name, url, unique_id):
34+
def __init__(self, hass, name, url, unique_id):
35+
self.hass = hass
3436
self._attr_name = f"Wallbox {name}"
3537
self._url = url
3638
self._attr_unique_id = f"enpal_wallbox_button_{unique_id}"
@@ -47,8 +49,13 @@ def device_info(self):
4749

4850
async def async_press(self):
4951
try:
50-
response = requests.post(self._url, timeout=5)
51-
if not response.ok:
52-
_LOGGER.warning("Wallbox command failed: %s", response.text)
52+
session = async_get_clientsession(self.hass)
53+
async with session.post(self._url, timeout=5) as response:
54+
if response.status != 200:
55+
_LOGGER.warning("Wallbox command failed: %s", await response.text())
5356
except Exception as e:
54-
_LOGGER.error("Wallbox request failed: %s", e)
57+
_LOGGER.error("Wallbox request failed: %s", e)
58+
# Sensor-Update anstoßen
59+
coordinator = self.hass.data[DOMAIN].get("coordinator")
60+
if coordinator:
61+
await coordinator.async_request_refresh()

custom_components/enpal_webparser/config_flow.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ def is_valid_enpal_url_format(url: str) -> bool:
1919
def validate_enpal_url(url: str) -> bool:
2020
try:
2121
resp = requests.get(url, timeout=5)
22+
_LOGGER.info("[Enpal] Url-Status: %s", resp.status_code)
2223
return resp.status_code == 200
2324
except Exception as e:
2425
_LOGGER.warning(f"[Enpal] URL nicht erreichbar: {e}")
@@ -98,7 +99,7 @@ async def async_step_init(self, user_input=None):
9899
url_input = current.get("url", DEFAULT_URL)
99100
interval_input = current.get("interval", DEFAULT_INTERVAL)
100101
groups_input = current.get("groups", DEFAULT_GROUPS)
101-
use_wallbox_addon = current.get("use_wallbox_addon", False)
102+
use_wallbox_addon = current.get("use_wallbox_addon", DEFAULT_USE_WALLBOX_ADDON)
102103

103104
if user_input:
104105
url_input = user_input.get("url", url_input)
@@ -123,7 +124,7 @@ async def async_step_init(self, user_input=None):
123124
vol.Required("url", default=url_input): str,
124125
vol.Required("interval", default=interval_input): int,
125126
vol.Optional("groups", default=groups_input): cv.multi_select(DEFAULT_GROUPS),
126-
vol.Optional("use_wallbox_addon", default=False): bool,
127+
vol.Optional("use_wallbox_addon", default=use_wallbox_addon): bool,
127128
}),
128129
errors=errors
129130
)

custom_components/enpal_webparser/sensor.py

Lines changed: 65 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
from homeassistant.components.sensor import SensorEntity
99
from homeassistant.config_entries import ConfigEntry
1010
from homeassistant.helpers.entity_platform import AddEntitiesCallback
11-
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
11+
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, CoordinatorEntity, UpdateFailed
12+
from homeassistant.helpers.entity import EntityCategory
1213

1314
from .const import DOMAIN, DEFAULT_INTERVAL, DEFAULT_URL
1415

@@ -139,6 +140,8 @@ async def async_update_data():
139140
update_interval=timedelta(seconds=interval),
140141
)
141142

143+
hass.data[DOMAIN]["coordinator"] = coordinator
144+
142145
await coordinator.async_config_entry_first_refresh()
143146

144147
entities = []
@@ -147,52 +150,41 @@ async def async_update_data():
147150
_LOGGER.debug(f"[Enpal] Sensor hinzugefügt: {sensor['name']}")
148151
entities.append(EnpalSensor(uid, sensor, coordinator))
149152

150-
if entry.options.get("use_wallbox_addon", False):
151-
entities.extend([
152-
WallboxModeSensor("Wallbox Lademodus", "wallbox_mode", "Wallbox Lademodus", "http://127.0.0.1:8090/wallbox/status", "mode"),
153-
WallboxStatusSensor("Wallbox Status", "wallbox_status", "Wallbox Status", "http://127.0.0.1:8090/wallbox/status", "status"),
154-
])
155-
156-
async_add_entities(entities)
157-
158-
159-
class WallboxSensorBase(SensorEntity):
160-
def __init__(self, name, unique_id, friendly_name, status_url, key):
161-
self._attr_name = friendly_name
162-
self._attr_unique_id = unique_id
163-
self._status_url = status_url
164-
self._key = key
165-
self._attr_icon = "mdi:ev-station"
166-
self._attr_device_class = None
167-
self._attr_native_unit_of_measurement = None
168-
self._attr_should_poll = True
169-
self._attr_extra_state_attributes = {}
170-
171-
@property
172-
def device_info(self):
173-
return {
174-
"identifiers": {(DOMAIN, "enpal_device")},
175-
"name": "Enpal Webgerät",
176-
"manufacturer": "Enpal",
177-
"model": "Webparser",
178-
}
179-
180-
async def async_update(self):
153+
154+
wallbox_url = "http://127.0.0.1:36725/wallbox/status"
155+
156+
async def async_wallbox_update():
157+
wallbox_url = "http://127.0.0.1:36725/wallbox/status"
181158
try:
182159
async with aiohttp.ClientSession() as session:
183-
async with session.get(self._status_url, timeout=5) as resp:
184-
data = await resp.json()
185-
self._attr_native_value = data.get(self._key)
160+
async with session.get(wallbox_url, timeout=5) as resp:
161+
if resp.status != 200:
162+
raise UpdateFailed(f"Wallbox API Error: {resp.status}")
163+
return await resp.json()
186164
except Exception as e:
187-
_LOGGER.warning(f"[WallboxSensor] Fehler beim Abrufen: {e}")
188-
self._attr_native_value = None
165+
_LOGGER.error(f"[Enpal] Fehler beim Wallbox-Statusabruf: {e}")
166+
raise UpdateFailed(f"Wallbox-Update fehlgeschlagen: {e}")
167+
168+
wallbox_coordinator = DataUpdateCoordinator(
169+
hass,
170+
logger=_LOGGER,
171+
name="Wallbox Status",
172+
update_method=async_wallbox_update,
173+
update_interval=timedelta(seconds=30),
174+
)
175+
try:
176+
await wallbox_coordinator.async_config_entry_first_refresh()
177+
except Exception as e:
178+
raise ConfigEntryNotReady(f"Wallbox-Daten konnten nicht geladen werden: {e}")
189179

180+
if entry.options.get("use_wallbox_addon", False):
181+
entities.extend([
182+
WallboxModeSensor(wallbox_coordinator),
183+
WallboxStatusSensor(wallbox_coordinator),
184+
])
190185

191-
class WallboxModeSensor(WallboxSensorBase):
192-
pass
186+
async_add_entities(entities)
193187

194-
class WallboxStatusSensor(WallboxSensorBase):
195-
pass
196188

197189
class EnpalSensor(SensorEntity):
198190
def __init__(self, uid: str, sensor: dict, coordinator: DataUpdateCoordinator):
@@ -235,4 +227,35 @@ def _handle_coordinator_update(self):
235227
self._attr_native_value = sensor["value"]
236228
self._attr_extra_state_attributes["enpal_last_update"] = sensor.get("enpal_last_update")
237229
break
238-
self.async_write_ha_state()
230+
self.async_write_ha_state()
231+
232+
233+
class WallboxCoordinatorEntity(CoordinatorEntity, SensorEntity):
234+
def __init__(self, coordinator, name, unique_id, key):
235+
super().__init__(coordinator)
236+
self._attr_name = name
237+
self._attr_unique_id = unique_id
238+
self._key = key
239+
self._attr_icon = "mdi:ev-station"
240+
self._attr_entity_category = EntityCategory.DIAGNOSTIC
241+
242+
@property
243+
def device_info(self):
244+
return {
245+
"identifiers": {(DOMAIN, "enpal_device")},
246+
"name": "Enpal Webgerät",
247+
"manufacturer": "Enpal",
248+
"model": "Webparser",
249+
}
250+
251+
@property
252+
def native_value(self):
253+
return self.coordinator.data.get(self._key)
254+
255+
class WallboxModeSensor(WallboxCoordinatorEntity):
256+
def __init__(self, coordinator):
257+
super().__init__(coordinator, "Wallbox Lademodus", "wallbox_mode", "mode")
258+
259+
class WallboxStatusSensor(WallboxCoordinatorEntity):
260+
def __init__(self, coordinator):
261+
super().__init__(coordinator, "Wallbox Status", "wallbox_status", "status")

0 commit comments

Comments
 (0)