srne-mqtt/srnemqtt/__main__.py

99 lines
3 KiB
Python
Raw Normal View History

2023-01-07 18:02:34 +00:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
from typing import List, Optional, cast
2023-01-07 18:02:34 +00:00
from bluepy.btle import BTLEDisconnectError
from serial import SerialException
2023-01-07 18:02:34 +00:00
from srnemqtt.consumers import BaseConsumer
2023-04-07 21:57:37 +00:00
from .config import get_config, get_consumers, get_interface
from .srne import Srne
2023-01-07 21:18:30 +00:00
from .util import Periodical, log
2023-01-07 18:02:34 +00:00
class CommunicationError(BTLEDisconnectError, SerialException, TimeoutError):
pass
def main() -> None:
2023-01-07 18:02:34 +00:00
conf = get_config()
consumers: Optional[List[BaseConsumer]] = None
2023-01-07 18:02:34 +00:00
per_voltages = Periodical(interval=15)
per_current_hist = Periodical(interval=60)
try:
while True:
try:
log("Connecting...")
2023-04-07 21:57:37 +00:00
with get_interface() as dev:
srne = Srne(dev)
2023-01-07 18:02:34 +00:00
log("Connected.")
if consumers is None:
consumers = get_consumers(srne, conf)
2023-01-07 18:02:34 +00:00
days = 7
res = srne.get_historical_entry()
2023-01-07 18:02:34 +00:00
if res:
log(res)
for consumer in consumers:
consumer.write(res)
days = cast(int, res.get("run_days", 7))
for i in range(days):
res = srne.get_historical_entry(i)
2023-01-07 18:02:34 +00:00
if res:
log({i: res})
for consumer in consumers:
consumer.write({str(i): res})
while True:
now = time.time()
if per_voltages(now):
data = srne.get_battery_state()
2023-01-07 18:02:34 +00:00
if data:
log(data)
for consumer in consumers:
consumer.write(data)
if per_current_hist(now):
try:
data = srne.get_historical_entry()
2023-01-07 18:02:34 +00:00
log(data)
for consumer in consumers:
consumer.write(data)
except TimeoutError:
pass
2023-01-07 18:02:34 +00:00
# print(".")
for consumer in consumers:
consumer.poll()
time.sleep(max(0, 1 - time.time() - now)) # 1s loop
2023-01-07 18:02:34 +00:00
# if STATUS.get('load_enabled'):
# write(wd, CMD_DISABLE_LOAD)
# else:
# write(wd, CMD_ENABLE_LOAD)
except CommunicationError:
2023-01-07 18:02:34 +00:00
log("ERROR: Disconnected")
time.sleep(1)
except (KeyboardInterrupt, SystemExit, Exception) as e:
if consumers is not None:
for consumer in consumers:
consumer.exit()
2023-01-07 18:02:34 +00:00
if type(e) is not KeyboardInterrupt:
raise
if __name__ == "__main__":
main()