Make sure to flush stdout + some refractoring

This commit is contained in:
Odd Stråbø 2021-11-03 04:35:49 +01:00
parent 06453f90e1
commit 0ee53a73ea

View file

@ -2,6 +2,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import datetime import datetime
import struct import struct
import sys
import time import time
from bluepy import btle from bluepy import btle
@ -200,6 +201,7 @@ def parsePacket(data):
print(timestamp, res) print(timestamp, res)
return res return res
print(timestamp, data) print(timestamp, data)
sys.stdout.flush()
class Delegate(btle.DefaultDelegate): class Delegate(btle.DefaultDelegate):
@ -227,30 +229,70 @@ def write(fh, data):
fh.write(data + bcrc) fh.write(data + bcrc)
def construct_request(address, words=1):
return struct.pack("!BBHH", 0xFF, 0x03, address, words)
def poll(dev: btle.Peripheral, timeout: float = 1) -> bool:
start = time.time()
while not dev.waitForNotifications(0.2):
if time.time() < start + timeout:
return False
while dev.waitForNotifications(0.2):
pass
return True
def log(string: str):
print(datetime.datetime.utcnow().isoformat(" "), string)
sys.stdout.flush()
if __name__ == "__main__":
dlgt = Delegate() dlgt = Delegate()
prev = time.time() - INTERVAL prev = time.time() - INTERVAL
while True: while True:
try: try:
log("Connecting...")
with btle.Peripheral(MAC).withDelegate(dlgt) as dev: with btle.Peripheral(MAC).withDelegate(dlgt) as dev:
wd = dev.getCharacteristics(uuid=write_device)[0] wd = dev.getCharacteristics(uuid=write_device)[0]
log("Connected.")
poll(dev)
write(wd, construct_request(0, 32))
poll(dev)
poll(dev)
poll(dev)
# Memory dump
# for address in range(0, 0x10000, 16):
# log(f"Reading 0x{address:04X}...")
# write(wd, construct_request(address, 16))
# poll(dev)
# poll(dev)
# poll(dev)
# poll(dev)
# poll(dev)
while True: while True:
dev.waitForNotifications(1) poll(dev)
now = time.time() now = time.time()
diff = now - prev diff = now - prev
if diff >= INTERVAL: if diff >= INTERVAL:
prev += INTERVAL prev += INTERVAL
write(wd, CMD_GET_PANEL_STATUS) write(wd, construct_request(0x0107, 4)) # CMD_GET_PANEL_STATUS
dev.waitForNotifications(1) poll(dev)
write(wd, CMD_GET_BATTERY_STATE) write(wd, construct_request(0x0100, 7)) # CMD_GET_BATTERY_STATE
dev.waitForNotifications(1) poll(dev)
# if STATUS.get('load_enabled'): # if STATUS.get('load_enabled'):
# write(wd, CMD_DISABLE_LOAD) # write(wd, CMD_DISABLE_LOAD)
@ -258,5 +300,9 @@ while True:
# write(wd, CMD_ENABLE_LOAD) # write(wd, CMD_ENABLE_LOAD)
except btle.BTLEDisconnectError: except btle.BTLEDisconnectError:
print(datetime.datetime.utcnow().isoformat(" "), "ERROR: Disconnected") log("ERROR: Disconnected")
time.sleep(1) time.sleep(1)
try:
dev.close()
except Exception:
pass