from modbus import Modbus, MBError, NoResponseError
import colorama
from colorama import Fore
import time
import os
import struct

reg_table = {'hw_base': 0x0200}

class SBS(Modbus):
    def __init__(self, tty: str, brate: int, address: int):
        super().__init__(tty, brate, address)

    @staticmethod
    def swap(data: bytes) -> bytes: 
        return bytes([data[2], data[3], data[1], data[2]])

    @staticmethod
    def swap_registers(data: bytes, *args) -> bytes:
        for i in args:
            data[i], data[i + 2] = data[i + 2], data[i]
            data[i + 1], data[i + 3] = data[i + 3], data[i + 1]
        return data

    def read_pack(self, addr: int, cnt: int):
        return self.read_holding_registers(addr, cnt)

    def read_hv_params(self):
        raw_data = self.read_holding_registers_raw(reg_table['hw_base'], 15)
        self.swap_registers(raw_data, 2, 8, 12, 16, 20, 24)
        return struct.unpack('>HfHfffffH', raw_data)


def main():
    colorama.init(autoreset=True)
    dev = SBS('COM9', 115200, 34)
    dev.MB_DEBUG = False

    while True:
        # data = dev.read_pack(0x300, 30)
        # print("Output :", Fore.GREEN + ' '.join(str(el) for el in data))
        
        print(dev.read_hv_params())

        time.sleep(1)


if __name__ == '__main__':
    main()
