Skip to content

Commit

Permalink
Attempt to add support for querying all packs to logger
Browse files Browse the repository at this point in the history
  • Loading branch information
warhammerkid committed Jul 17, 2022
1 parent 6e814a0 commit 5aeef4d
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 24 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Change Log

## FUTURE

* Added support for paging through batteries in the logger to collect more information about how things work.

## 0.6.0

* Added support for configuring username / password / port for MQTT broker
Expand Down
74 changes: 50 additions & 24 deletions bluetti_mqtt/logger_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@
import time
from bleak import BleakScanner
from bluetti_mqtt.bluetooth.client import BluetoothClient
from bluetti_mqtt.bluetooth.exc import ParseError, BadConnectionError
from bluetti_mqtt.commands import QueryRangeCommand
from bluetti_mqtt.bluetooth.exc import InvalidRequestError, ParseError, BadConnectionError
from bluetti_mqtt.commands import QueryRangeCommand, UpdateFieldCommand, DeviceCommand
from bluetti_mqtt.parser import MidStatusPageParser


async def scan():
Expand All @@ -25,7 +26,7 @@ async def scan():
print(f'Found {d.name}: address {d.address}')


def log_packet(output: TextIOWrapper, data: bytes, command: QueryRangeCommand):
def log_packet(output: TextIOWrapper, data: bytes, command: DeviceCommand):
log_entry = {
'type': 'client',
'time': time.strftime('%Y-%m-%d %H:%M:%S %z', time.localtime()),
Expand All @@ -35,33 +36,58 @@ def log_packet(output: TextIOWrapper, data: bytes, command: QueryRangeCommand):
output.write(json.dumps(log_entry) + '\n')


def log_invalid(output: TextIOWrapper, err: InvalidRequestError, command: DeviceCommand):
log_entry = {
'type': 'client',
'time': time.strftime('%Y-%m-%d %H:%M:%S %z', time.localtime()),
'error': err.args[0],
'command': base64.b64encode(bytes(command)).decode('ascii'),
}
output.write(json.dumps(log_entry) + '\n')


async def log_command(device: BluetoothClient, command: DeviceCommand, log_file: TextIOWrapper):
result_future = await device.perform(command)
try:
result = await result_future
log_packet(log_file, result, command)
except InvalidRequestError as err:
print('Got a "invalid request" error')
log_invalid(log_file, err, command)
except ParseError:
print('Got a parse exception...')
except BadConnectionError as err:
print(f'Needed to disconnect due to error: {err}')


async def log(address: str, path: str):
print(f'Connecting to {address}')
device = BluetoothClient(address)
asyncio.get_running_loop().create_task(device.run())
commands = [
QueryRangeCommand(0x00, 0x00, 0x46),
QueryRangeCommand(0x00, 0x46, 0x42),
QueryRangeCommand(0x00, 0x88, 0x4a),
QueryRangeCommand(0x0B, 0xB9, 0x3D)
]

with open(path, 'a') as log_file:
command: QueryRangeCommand
for command in itertools.cycle(commands):
if not device.is_connected:
print('Waiting for connection...')
await asyncio.sleep(1)
continue

result_future = await device.perform(command)
try:
result = await result_future
log_packet(log_file, result, command)
except ParseError:
print('Got a parse exception...')
except BadConnectionError as err:
print(f'Needed to disconnect due to error: {err}')
# Wait for device connection
while not device.is_connected:
print('Waiting for connection...')
await asyncio.sleep(1)
continue

# Get pack max
result_future = await device.perform(MidStatusPageParser.build_query_command())
result = await result_future
pack_max = MidStatusPageParser(result[3:-2]).parse().pack_num_max
print(f'Device has a maximum of {pack_max} battery packs')

# Poll device
while True:
await log_command(device, QueryRangeCommand(0x00, 0x00, 0x46), log_file)
await log_command(device, QueryRangeCommand(0x0B, 0xB9, 0x3D), log_file)

for pack in range(1, pack_max):
await log_command(device, UpdateFieldCommand(0x0B, 0xBE, pack), log_file)
await asyncio.sleep(1) # We need to wait after switching packs for the data to be available
await log_command(device, QueryRangeCommand(0x00, 0x46, 0x42), log_file)
await log_command(device, QueryRangeCommand(0x00, 0x88, 0x4a), log_file)


def main():
Expand Down

0 comments on commit 5aeef4d

Please sign in to comment.