#!/usr/bin/python3
# -*- coding: utf-8 -*-

import libscrc
import serial
import sys
import struct
def str_to_bytes(data):
    return [hex(ord(c)) for c in data]
port=sys.argv[1]
addr=sys.argv[2]
def get_value(data,port,addr):
    crc16 = libscrc.modbus(data)
    crc16_str = '0x{:04x}'.format(crc16)
    data.append(int(crc16_str[2:][2:4],16))
    data.append(int(crc16_str[2:][0:2],16))
    ser = serial.Serial(port,9600,timeout=0.1,bytesize=8,stopbits=1,parity='N',writeTimeout=0)
    ser.write(data)
    line = ser.read(100)
    ret = (''.join('{:02x}'.format(ord(x)) for x in line))
    val = struct.unpack('>f',line[3:7])[0]
    return "%.3f" % val
    ser.close()
data = bytearray(b'\x00\x04\x00\x00\x00\x02')
data[0]=int(addr)
voltage = get_value(data,port,addr)
data = bytearray(b'\x00\x04\x00\x08\x00\x02')
data[0]=int(addr)
current = get_value(data,port,addr)
data = bytearray(b'\x00\x04\x00\x12\x00\x02')
data[0]=int(addr)
power = get_value(data,port,addr)
data = bytearray(b'\x00\x04\x01\x00\x00\x02')
data[0]=int(addr)
power_total = get_value(data,port,addr)
print("U="+voltage+" I="+current+" P="+power+" W="+power_total+"|U="+voltage+";; I="+current+";; P="+power+";; "+"W="+power_total+";; ")