import minimalmodbus
import serial
import time

# Configure the instrument
instrument = minimalmodbus.Instrument("COM4", 1)  # Port name of my USB port, device address (in decimal)

# Configure serial settings
instrument.serial.baudrate = 9600
instrument.serial.bytesize = 8
instrument.serial.parity = serial.PARITY_NONE
instrument.serial.stopbits = 1
instrument.serial.timeout = 1  # seconds
instrument.clear_buffers_before_each_transaction = True

while True:
    # function to convert a reading in the form of complement code, for below 0C readings
    def two_complement_to_dec(value):
       val = int(value*10) # the value in the register of the Ebyte module is devided by 10 
       val = bin(val)[2:] # remove the "0b" prefix
       invertedBin = val.replace('1', '_TEMP_').replace('0', '1').replace('_TEMP_', '0')
       invertedDec = (int(invertedBin,2)+1) / 10 # add 1 as part of the 2's complement conversion 
       return ("-" + str(invertedDec))
        
    try:
        channel1 = instrument.read_register(0x0190, 0, functioncode=4)/10 # Register address, number of decimals, function code, divide by 10 per the user manual
        if channel1 > 850: # reading above 850 is in the form of complement code (ex: 6548.6). See section 4.1.2 of the user manual
            channel1 = two_complement_to_dec(channel1)
        channel2 = instrument.read_register(0x0191, 0, functioncode=4)/10
        if channel2 > 850:
            channel2 = two_complement_to_dec(channel2)
        channel3 = instrument.read_register(0x0192, 0, functioncode=4)/10
        if channel3 > 850:
            channel3 = two_complement_to_dec(channel3)
        channel4 = instrument.read_register(0x0193, 0, functioncode=4)/10
        if channel4 > 850:
            channel4 = two_complement_to_dec(channel4)
        time.sleep(1)
        print(f"CH1: {channel1}, CH2: {channel2}, CH3: {channel3}, CH4: {channel4}")
            
    except IOError as e:
        print(f"Error reading register: {e}")
    
    
   
