Compare commits

...
3 Commits
Author SHA1 Message Date
Tanner a3963ff91b Prevent ECU polling from hanging on stalled sockets 2026-11-03 16:24:25 +00:00
Tanner 518b422915 /history/ return 503 when influxdb isn't ready 2026-11-03 16:19:17 +00:00
Tanner 98f5705224 Wait for influxdb to be ready 2026-11-03 16:16:15 +00:00
2 changed files with 75 additions and 24 deletions
+35 -22
View File
@@ -4,6 +4,7 @@
import socket
import binascii
import logging
import time
class APSystemsInvalidData(Exception):
pass
@@ -58,13 +59,40 @@ class APSystemsECUR:
self.reader = None
self.writer = None
def query_ecu(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.ipaddr,self.port))
def _query(self, command, description):
deadline = time.monotonic() + self.timeout
with socket.create_connection(
(self.ipaddr, self.port), timeout=self.timeout) as sock:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise socket.timeout(f'{description} timed out connecting to ECU')
sock.settimeout(remaining)
sock.sendall(command.encode('utf-8'))
response = bytearray()
while True:
terminator = response.find(self.recv_suffix)
if terminator >= 0:
end = terminator + len(self.recv_suffix)
return bytes(response[:end])
remaining = deadline - time.monotonic()
if remaining <= 0:
raise socket.timeout(f'{description} timed out waiting for ECU response')
sock.settimeout(remaining)
chunk = sock.recv(self.recv_size)
if not chunk:
raise APSystemsInvalidData(
f'{description} connection closed before response terminator')
response.extend(chunk)
if len(response) > self.recv_size:
raise APSystemsInvalidData(
f'{description} response exceeded {self.recv_size} bytes')
def query_ecu(self):
logging.debug('ecu query: %s', self.ecu_query)
sock.sendall(self.ecu_query.encode('utf-8'))
self.ecu_raw_data = sock.recv(self.recv_size)
self.ecu_raw_data = self._query(self.ecu_query, 'ECU query')
logging.debug('raw ecu data: %s', self.ecu_raw_data)
logging.debug('ecu id: %s', self.ecu_raw_data[13:25])
@@ -73,33 +101,18 @@ class APSystemsECUR:
self.process_ecu_data()
sock.shutdown(socket.SHUT_RDWR)
sock.close()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.ipaddr,self.port))
cmd = self.inverter_query_prefix + self.ecu_id + self.inverter_query_suffix
logging.debug('inverter data cmd: %s', cmd)
sock.sendall(cmd.encode('utf-8'))
self.inverter_raw_data = sock.recv(self.recv_size)
self.inverter_raw_data = self._query(cmd, 'Inverter query')
logging.debug('raw inverter data: %s', self.inverter_raw_data)
sock.shutdown(socket.SHUT_RDWR)
sock.close()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.ipaddr,self.port))
cmd = self.inverter_signal_prefix + self.ecu_id + self.inverter_signal_suffix
logging.debug('inverter signal cmd: %s', cmd)
sock.sendall(cmd.encode('utf-8'))
self.inverter_raw_signal = sock.recv(self.recv_size)
self.inverter_raw_signal = self._query(cmd, 'Inverter signal query')
logging.debug('raw signal data: %s', self.inverter_raw_signal)
sock.shutdown(socket.SHUT_RDWR)
sock.close()
data = self.process_inverter_data()
data['ecu_id'] = self.ecu_id
+40 -2
View File
@@ -21,6 +21,35 @@ solar_data = {}
from influxdb import InfluxDBClient
client = InfluxDBClient('localhost', 8086, database='solar2')
influx_probe = InfluxDBClient('localhost', 8086, timeout=2)
INFLUX_STARTUP_TIMEOUT = 60
INFLUX_RETRY_INTERVAL = 2
async def wait_for_influxdb():
loop = asyncio.get_running_loop()
deadline = loop.time() + INFLUX_STARTUP_TIMEOUT
last_error = None
while True:
remaining = deadline - loop.time()
if remaining <= 0:
logging.warning(
'InfluxDB did not become ready within %s seconds; starting anyway (last error: %s)',
INFLUX_STARTUP_TIMEOUT, last_error)
return
try:
await asyncio.wait_for(
asyncio.to_thread(influx_probe.ping), timeout=min(2, remaining))
logging.info('InfluxDB is ready')
return
except Exception as err:
last_error = err
remaining = deadline - loop.time()
if remaining <= 0:
continue
logging.debug('InfluxDB is not ready yet: %s', err)
await asyncio.sleep(min(INFLUX_RETRY_INTERVAL, remaining))
async def proxy(reader, writer):
message = await reader.read(1024)
@@ -51,6 +80,7 @@ async def get_data():
global solar_data
await asyncio.sleep(1)
await wait_for_influxdb()
while True:
try:
@@ -122,7 +152,10 @@ async def get_data():
client.write_points(points)
logging.info('Wrote %s points to InfluxDB', len(points))
else:
logging.info(
'ECU poll completed; no new sample (ECU time: %s)',
data['timestamp'])
prev_ecu_timestamp = data['timestamp']
@@ -154,7 +187,12 @@ async def history(request):
end = int(end.timestamp())
q = 'select * from ecu where time >= {}s and time < {}s'.format(start, end)
history = list(client.query(q).get_points())
try:
await asyncio.wait_for(asyncio.to_thread(influx_probe.ping), timeout=2)
history = list(client.query(q).get_points())
except Exception as err:
logging.warning('InfluxDB unavailable for history request: %s', err)
raise web.HTTPServiceUnavailable(text='InfluxDB is not ready') from err
return web.json_response(history)