#!/usr/bin/env python3
from time import sleep, time
from sys import exit
import minimalmodbus
import serial

#slave_address_list = [ 252, 253 ]
slave_address_list = [ 254 ]

# read
readout_count = 0
readout_error_count = 0
while True:
    for slave_address in slave_address_list:
        readout_count += 1
        # initialize modbus
        instrument = minimalmodbus.Instrument('/dev/rs485', slave_address, close_port_after_each_call=True)  # port name, slave address (in decimal)
        instrument.serial.baudrate = 19200
        instrument.serial.bytesize = 8
        instrument.serial.parity   = serial.PARITY_EVEN
        instrument.serial.stopbits = 1
        instrument.serial.timeout  = 0.05          # seconds
        instrument.mode = minimalmodbus.MODE_RTU   # rtu or ascii mode
        instrument.clear_buffers_before_each_transaction = True

        try:
            CO2_addr = 9
            CO2 = instrument.read_register(CO2_addr, 1, functioncode=4) * 10
            T_SHT4x_addr = 10
            T_SHT4x = instrument.read_register(T_SHT4x_addr, 1, functioncode=4)
            RH_SHT4x_addr = 11
            RH_SHT4x = instrument.read_register(RH_SHT4x_addr, 1, functioncode=4) * 10
            T_SCD4x_addr = 12
            T_SCD4x = instrument.read_register(T_SCD4x_addr, 1, functioncode=4)
            RH_SCD4x_addr = 13
            RH_SCD4x = instrument.read_register(RH_SCD4x_addr, 1, functioncode=4) * 10
            T_SHT4x_signed_addr = 14
            T_SHT4x_signed = instrument.read_register(T_SHT4x_signed_addr,  1, functioncode=4, signed=True)
            T_SCD4x_signed_addr = 15
            T_SCD4x_signed = instrument.read_register(T_SCD4x_signed_addr, 1, functioncode=4, signed=True)
            with open(f'measurement_device_{slave_address}.csv', 'a+') as f:
                f.write(f'{time():.1f} {CO2} {T_SHT4x} {RH_SHT4x} {T_SCD4x} {RH_SCD4x} {T_SHT4x_signed} {T_SCD4x_signed}\n')
        except (minimalmodbus.NoResponseError, minimalmodbus.InvalidResponseError) as e:
            readout_error_count += 1
            with open('measure.log', 'a+') as logfile:
                logfile.write(f'Read error for device {slave_address} at {time()} ({str(e)}) ({readout_error_count}/{readout_count} readouts failed)\n')
            continue
    sleep(10)
