#!/usr/bin/env python3
from sensor import Sensor
from sys import argv, exit
from flask import Flask
from time import sleep, time
import threading

app = Flask('Sensor central unit')
# list of sensor addresses
address_list = [ 247 ]
baudrate = 19200
sensors = []
modbus_mutex = threading.Lock()

# Flask functions
@app.route('/')
def index():
    html = ''
    for s in sensors:
        html += f'<h2>Address {s.address}</h2><br><h3>Input registers:</h3><br>'
        for reg_name in s.input_registers:
            reg_number = s.input_registers[reg_name]
            with modbus_mutex:
                reg_value = s.read_register(reg_number)
            html += f'{reg_number : <10}&nbsp&nbsp{int(reg_value) : >10}&nbsp&nbsp{reg_name}<br>'
        html += '<h3>Holding registers</h3><br>'
        for reg_name in s.holding_registers:
            reg_number = s.holding_registers[reg_name]
            with modbus_mutex:
                reg_value = s.read_register(reg_number)
            html += f'{reg_number : <10}&nbsp&nbsp{int(reg_value) : >10}&nbsp&nbsp{reg_name}<br>'
    return html

for addr in address_list:
    sensors.append(Sensor(addr, baudrate))

# run webserver thread
flask_thread = threading.Thread(target=app.run, kwargs={'host': '0.0.0.0', 'port': 8080})
flask_thread.start()
#app.run(host='0.0.0.0', port=8080)

# measuring
while True:
    # logging: for now just writing to csv file (can be anything: write to db, mqtt...)
    for s in sensors:
        log_string = f'{time():.1f} '
        for reg_name, reg_number in s.input_registers.items():
            with modbus_mutex:
                log_string += str(int(s.read_register(reg_number))) + ' '
        log_string += str(s.readout_total) + ' '
        log_string += str(s.readout_error_no_response) + ' '
        log_string += str(s.readout_error_invalid_response) + ' '
        with open(f'sensor_{s.address}.csv', 'a+') as f:
            f.write(log_string + '\n')
    sleep(10)

