1#!/usr/bin/env python3
2# Copyright (c) 2022 Rodrigo Peixoto <rodrigopex@gmail.com>
3# SPDX-License-Identifier: Apache-2.0
4import serial
5import json
6import argparse
7
8j = """
9[
10    {"name":"version","on_changed": false, "read_only": true, "message_size": 4},
11    {"name":"sensor_data","on_changed": true, "read_only": false, "message_size":8},
12    {"name":"start_measurement","on_changed": false, "read_only": false, "message_size": 1},
13    {"name":"finish","on_changed": false, "read_only": false, "message_size": 1}
14]
15"""
16
17parser = argparse.ArgumentParser(description='Read zbus events via serial.', allow_abbrev=False)
18parser.add_argument("port", type=str, help='The tty or COM port to be used')
19
20args = parser.parse_args()
21
22channels = json.loads(j)
23
24
25def fetch_sentence():
26    name = b""
27    while True:
28        b = ser.read(size=1)
29        if b == b",":
30            break
31        name += b
32    print(name)
33    found_msg_size = int.from_bytes(ser.read(size=1), byteorder="little")
34    found_msg = ser.read(found_msg_size)
35    return name, found_msg_size, found_msg
36
37
38try:
39    ser = serial.Serial(args.port)
40    while True:
41        d = ser.read()
42        if d == b'$':
43            channel_name, msg_size, msg = fetch_sentence()
44            print(f"PUB [{channel_name}] -> {msg}")
45except serial.serialutil.SerialException as e:
46    print(e)
47