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

slave_address = 247
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

print('---- Reading from input registers ----')
# read
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)
print(f'[{CO2_addr+30001}] CO2:\t\t{CO2} ppm')
print(f'[{T_SHT4x_addr+30001}] T_SHT4x:\t{T_SHT4x} deg C')
print(f'[{RH_SHT4x_addr+30001}] RH_SHT4x:\t{RH_SHT4x} %')
print(f'[{T_SCD4x_addr+30001}] T_SCD4x:\t{T_SCD4x} deg C')
print(f'[{RH_SCD4x_addr+30001}] RH_SCD4x:\t{RH_SCD4x} %')
print(f'[{T_SHT4x_signed_addr+30001}] T_SHT4x_signed:\t{T_SHT4x_signed} deg C')
print(f'[{T_SCD4x_signed_addr+30001}] T_SCD4x_signed:\t{T_SCD4x_signed} deg C')
print('---- DONE ----')
exit(0)
