import dht
import time
import json
import network
import _thread

from machine import Pin
from umqtt.simple import MQTTClient

# Modify wherever the values contain <>
SENSOR_ID = 1
MQTT_BROKER = "broker.hivemq.com"
MQTT_CLIENT_ID = "dht-<class>-<number in class>-<name>"
MQTT_TOPIC = "elsys/tcu/<class>/<number in class>/<name>/temperature-sensor/"

# DHT constants
DHT_PIN = 13

# LED constants
LED_PIN = 21

# System constants
turned_on = True

# Connect to Wi-Fi
def connect_to_wifi():
    print("Connecting to Wi-Fi", end="")
    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    sta_if.connect('Wokwi-GUEST', '')
    while not sta_if.isconnected():
        print(".", end="")
        time.sleep(0.1)
    print(" Connected!")


# --------------------------------------------------------------------------------------------

# Connect to MQTT Broker
def connect_to_mqtt_broker():
    # Connect to Wi-Fi and connect to broker
    # Subscribe to topic for specific device with matching ID
    pass

# Handle incoming MQTT messages
def on_message(topic, message):
    # Handle incoming messages for turning on/off the system
    pass

# Publish temperature
def publish_temp(temp):
    # Publish MQTT message with the new temperature and who sent it
    pass

# --------------------------------------------------------------------------------------------


# Start measuring data from DHT sensor and publishing data
def activate_sensor():
    last_temp = 0
    led.value(1)
    while turned_on:
        last_temp = measure_temperature(last_temp)
        time.sleep(0.5)
    led.value(0)

# Measure temperature
def measure_temperature(last_temp):
    dht_sensor.measure()
    current_temp = dht_sensor.temperature()
    if current_temp != last_temp:
        publish_temp(current_temp)
        return current_temp
    return last_temp

# Init MQTT client
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.set_callback(on_message)
connect_to_mqtt_broker()

# Init DHT sensor
dht_sensor = dht.DHT22(Pin(DHT_PIN))

# Init LED
led = Pin(LED_PIN, Pin.OUT)
led.value(0)

# Loop
try:
    # Start thread when starting system
    _thread.start_new_thread(activate_sensor, ())
    while True:
        client.wait_msg()
finally:
    client.disconnect()