import spidev
import tkinter as tk
import threading
from flask import Flask, render_template

IDs = [hex(int('0101000110111001011100011111', 2))[2:], hex(int('0100100011111110111100100111', 2))[2:], hex(int('0101011011110010101010100000', 2))[2:], hex(int('0101001000100110101011000011', 2))[2:]]

window = tk.Tk()
window.geometry("600x400")
window.title("Kontrola tlaku")
app = Flask(__name__)

spi = spidev.SpiDev()
spi.open(1,0)

spi.max_speed_hz = 1000000
spi.mode = 0

sensor_count = 4

class Sensor:
    def __init__(self, ID, status, pressure, CheckSum):
        self.ID = ID
        self.status = status
        self.pressure = pressure
        self.CheckSum = CheckSum

Sensors = [Sensor(IDs[0],0,0,0), Sensor(IDs[1],0,0,0), Sensor(IDs[2],0,0,0), Sensor(IDs[3],0,0,0)]


def read_data():
     received_data = spi.readbytes(7)
     return(received_data)

def parse_data(received_data):
    hex_values = hex(int(received_data, 2))[2:]
    ID = hex_values[:7]
    status = bin(int(hex_values[7]))[2:]
    pressure = 0.06895*int(hex_values[8:10],16)
    CheckSum = hex_values[12:14]
    return(ID,status,pressure,CheckSum)

def update_values(p1,p2,p3,p4):
    label0.config(text = str("Tlak 1: ") + str("{:.2f}".format(p1) + str("bar")))
    label1.config(text = str("Tlak 2: ") + str("{:.2f}".format(p2) + str("bar")))
    label2.config(text = str("Tlak 3: ") + str("{:.2f}".format(p3) + str("bar")))
    label3.config(text = str("Tlak 4: ") + str("{:.2f}".format(p4) + str("bar")))

@app.route('/')
def send_data():
    var1 = request.args.get('var1', '')
    var2 = request.args.get('var2', '')
    var3 = request.args.get('var3', '')
    var4 = request.args.get('var4', '')
    return render_template('index.html', var1=Sensors[0].pressure, var2=Sensors[1].pressure, var3=Sensors[2].pressure, var4=Sensors[3].pressure)
    

def process_data(raw_data):
    (ID,status,pressure,CheckSum) = parse_data(raw_data)
    for i, cID in enumerate(IDs):
        if cID == ID:
            Sensors[i].status = status
            Sensors[i].pressure = pressure
            Sensors[i].CheckSum = CheckSum
            update_values(Sensors[0].pressure, Sensors[1].pressure, Sensors[2].pressure, Sensors[3].pressure)
            send_data()

label0 = tk.Label(window, text=(str("Tlak 1: ") + str(Sensors[0].pressure)), font=('Arial', 50))
label0.pack()
label1 = tk.Label(window, text=(str("Tlak 2: ") + str(Sensors[1].pressure)), font=('Arial', 50))
label1.pack()
label2 = tk.Label(window, text=(str("Tlak 3: ") + str(Sensors[2].pressure)), font=('Arial', 50))
label2.pack()
label3 = tk.Label(window, text=(str("Tlak 4: ") + str(Sensors[3].pressure)), font=('Arial', 50))
label3.pack()

def run_background_code():
    while True:
        process_data(read_data())


background_thread = threading.Thread(target=run_background_code)
background_thread.start()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)
window.mainloop()