Skip to content

Commit 69c9653

Browse files
committed
A bit closer to get it working
1 parent 7c9dfd9 commit 69c9653

3 files changed

Lines changed: 28 additions & 82 deletions

File tree

__init__.py

Lines changed: 2 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def setup(hass: HomeAssistant, base_config: ConfigType) -> bool:
6262
hass.data[DOMAIN].start()
6363

6464
discovery.load_platform(hass, Platform.SENSOR, DOMAIN, {}, config)
65-
discovery.load_platform(hass, Platform.BINARY_SENSOR, DOMAIN, {}, config)
65+
# discovery.load_platform(hass, Platform.BINARY_SENSOR, DOMAIN, {}, config)
6666
return True
6767

6868

@@ -76,41 +76,13 @@ class DeviceData(threading.Thread):
7676

7777
def __init__(self, hass, client: device.Device) -> None:
7878
super().__init__()
79+
self.name = "Ph803wThread"
7980
self.hass = hass
8081
self.client = client
8182
self.unit = self.client.host
8283
self._shutdown = False
8384
self._fails = 0
8485

85-
# def _reconnect(self):
86-
# """Reconnect on a failure."""
87-
88-
# self._fails += 1
89-
# if self._fails > MAX_FAILS:
90-
# _LOGGER.error("Failed to reconnect. Thread stopped")
91-
# persistent_notification.create(
92-
# self.hass,
93-
# "Error:<br/>Connection to PH-803W device failed "
94-
# "the maximum number of times. Thread has stopped",
95-
# title=NOTIFICATION_TITLE,
96-
# notification_id=NOTIFICATION_ID,
97-
# )
98-
99-
# self._shutdown = True
100-
# return
101-
102-
# # sleep first before the reconnect attempt
103-
# _LOGGER.debug("Sleeping for fail # %s", self._fails)
104-
# time.sleep(self._fails * ERROR_INTERVAL.total_seconds())
105-
106-
# try:
107-
# self.client.run(once=False)
108-
# except:
109-
# _LOGGER.exception("Failed to reconnect attempt %s", self._fails)
110-
# else:
111-
# _LOGGER.debug("Reconnected to device")
112-
# self._fails = 0
113-
11486
def run(self):
11587
"""Thread run loop."""
11688

@@ -163,46 +135,3 @@ def shutdown(event):
163135
)
164136
self.client.reset_socket()
165137
time.sleep(sleep_time)
166-
167-
# while True:
168-
# if self._shutdown:
169-
# _LOGGER.debug("Graceful shutdown")
170-
# return
171-
172-
# try:
173-
# self.data = self.client.run(once=False)
174-
175-
# except WFException:
176-
# # WFExceptions are things the WF library understands
177-
# # that pretty much can all be solved by logging in and
178-
# # back out again.
179-
# _LOGGER.exception("Failed to read data, attempting to recover")
180-
# self._reconnect()
181-
182-
# else:
183-
# dispatcher_send(self.hass, UPDATE_TOPIC)
184-
# time.sleep(SCAN_INTERVAL.total_seconds())
185-
186-
187-
# async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
188-
# """Set up Hello World from a config entry."""
189-
# # Store an instance of the "connecting" class that does the work of speaking
190-
# # with your actual devices.
191-
# hass.data.setdefault(DOMAIN, {})[entry.entry_id] = hub.Hub(hass, entry.data["host"])
192-
193-
# # This creates each HA object for each platform your device requires.
194-
# # It's done by calling the `async_setup_entry` function in each platform module.
195-
# hass.config_entries.async_setup_platforms(entry, PLATFORMS)
196-
# return True
197-
198-
199-
# async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
200-
# """Unload a config entry."""
201-
# # This is called when an entry/configured device is to be removed. The class
202-
# # needs to unload itself, and remove callbacks. See the classes for further
203-
# # details
204-
# unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
205-
# if unload_ok:
206-
# hass.data[DOMAIN].pop(entry.entry_id)
207-
208-
# return unload_ok

lib/device.py

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ def __init__(self, host):
2222
self.host = host
2323
self.passcode = ""
2424
self._measurements = []
25+
self._latest_measurement = None
2526
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2627
self._loop = True
2728
self._empty_counter = 0
@@ -38,10 +39,15 @@ async def run_async(self, once: bool = True) -> bool:
3839
return self.run(once)
3940

4041
def run(self, once: bool = True) -> bool:
42+
self._loop = True
4143
if once:
44+
if self._socket.fileno() == -1:
45+
self.reset_socket()
4246
self._connect()
4347
return self._run(once)
4448
else:
49+
if self._socket.fileno() == -1:
50+
self.reset_socket()
4551
self._connect()
4652
self._run(once)
4753
return not self._loop
@@ -165,7 +171,9 @@ def _handle_login_response(self, data):
165171
def _handle_data_response(self, data):
166172
if len(data) == 18:
167173
meas = Measurement(data)
174+
_LOGGER.debug("Adding result: %s" % meas)
168175
self._measurements.append(meas)
176+
self._latest_measurement = meas
169177
if len(self._measurements) > 100:
170178
self._measurements.pop(0)
171179
else:
@@ -208,12 +216,13 @@ def close(self):
208216
except:
209217
pass
210218

211-
def get_latest_measurement_and_empty(self):
212-
if len(self._measurements) > 0:
213-
m = self._measurements.pop()
214-
self._measurements.clear()
215-
return m
216-
return None
219+
def get_measurements_and_empty(self):
220+
meas = self._measurements
221+
self._measurements.clear()
222+
return meas
223+
224+
def get_latest_measurement(self):
225+
return self._latest_measurement
217226

218227
def __enter__(self):
219228
return self

sensor.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Platform for sensor integration."""
22
from __future__ import annotations
3+
import logging
34

45
from homeassistant.components.sensor import (
56
ENTITY_ID_FORMAT,
@@ -18,6 +19,8 @@
1819
from . import UPDATE_TOPIC
1920
from .const import DOMAIN
2021

22+
_LOGGER = logging.getLogger(__name__)
23+
2124

2225
class DeviceSensorConfig:
2326
"""PH-803W Device Sensor configuration."""
@@ -39,7 +42,7 @@ def __init__(
3942

4043

4144
SENSORS = [
42-
DeviceSensorConfig("pH Sensor", "ph", "mdi:water-percent"),
45+
DeviceSensorConfig("pH Sensor", "ph", "mdi:water-percent", ""),
4346
DeviceSensorConfig(
4447
"ORP Sensor",
4548
"orp",
@@ -77,6 +80,10 @@ def __init__(self, client, config):
7780
self._name = config.friendly_name
7881
self._attr = config.field
7982
self._state = None
83+
if self.client.client.get_latest_measurement() is not None:
84+
self._state = getattr(
85+
self.client.client.get_latest_measurement(), self._attr, None
86+
)
8087
self._icon = config.icon
8188
self._unit_of_measurement = config.unit_of_measurement
8289
self._attr_device_class = config.device_class
@@ -122,8 +129,9 @@ async def async_added_to_hass(self):
122129
@callback
123130
def async_update_callback(self):
124131
"""Update state."""
125-
if self.client.data is not None:
132+
_LOGGER.info("Read sensor data: %s" % self.client.get_latest_measurement())
133+
if self.client.client.get_latest_measurement() is not None:
126134
self._state = getattr(
127-
self.client.get_latest_measurement_and_empty(), self._attr, None
135+
self.client.client.get_latest_measurement(), self._attr, None
128136
)
129137
self.async_write_ha_state()

0 commit comments

Comments
 (0)