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

slave_address = 247
instrument = minimalmodbus.Instrument('/dev/ttyUSB0', 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

# holding register numbers
LED_on_register = 0
LED_brightness_register = 1
LED_smooth_register = 2
CO2_alert_limit_1_register = 3
CO2_alert_limit_2_register = 4
SCD4x_temperature_offset_register = 5
MODBUS_address_register = 6
baudrate_register = 7
# holding register readout
print('---- Reading from holding registers ----')
LED_on = int(instrument.read_register(LED_on_register, 1, functioncode=3) * 10)
LED_brightness = int(instrument.read_register(LED_brightness_register, 1, functioncode=3) * 10)
LED_smooth = int(instrument.read_register(LED_smooth_register, 1, functioncode=3) * 10)
CO2_alert_limit_1 = int(instrument.read_register(CO2_alert_limit_1_register, 1, functioncode=3) * 10)
CO2_alert_limit_2 = int(instrument.read_register(CO2_alert_limit_2_register, 1, functioncode=3) * 10)
SCD4x_temperature_offset = int(instrument.read_register(SCD4x_temperature_offset_register, 1, functioncode=3) * 10)
MODBUS_address = int(instrument.read_register(MODBUS_address_register, 1, functioncode=3) * 10)
baudrate = int(instrument.read_register(baudrate_register, 1, functioncode=3) * 10)
# print
reg_base = 40001
print(
f'''[{LED_on_register+reg_base}] LED_on = {LED_on}
[{LED_brightness_register+reg_base}] LED_brightness = {LED_brightness}
[{LED_smooth_register+reg_base}] LED_smooth = {LED_smooth}
[{CO2_alert_limit_1_register+reg_base}] CO2_alert_limit_1 = {CO2_alert_limit_1}
[{CO2_alert_limit_2_register+reg_base}] CO2_alert_limit_2 = {CO2_alert_limit_2}
[{SCD4x_temperature_offset_register+reg_base}] SCD4x_temperature_offset = {SCD4x_temperature_offset}
[{MODBUS_address_register+reg_base}] MODBUS_address = {MODBUS_address}
[{baudrate_register+reg_base}] baudrate = {baudrate}''')
# write to holding register
print('---- Writing to holding registers ----')
led_brightness = int(argv[1])
print(f'brightness = {led_brightness}') 
instrument.write_register(LED_brightness_register, led_brightness, functioncode=6)
print('---- DONE ----')
exit(0)
