import dht
import time
import network
import ssd1306

from machine import Pin, PWM, I2C
from umqtt.simple import MQTTClient

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

# DHT constants
DHT_PIN = 13

# Display constants
DISPLAY_SCL_PIN = 21
DISPLAY_SDA_PIN = 22
DISPLAY_WIDTH = 128
DISPLAY_HEIGHT = 64

# 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_wifi()
    print("Connecting to MQTT server... ", end="")
    client.connect()
    print("Connected!")

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

# Publish temperature
def publish_temp(temp):
    client.publish(MQTT_TOPIC, str(temp))

# Fill display
def fill_display(temp):
    display.fill(0)
    display.text("Updated", 0, 0)
    display.text("Temperature:", 0, 15)
    display.text("{:.2f}".format(temp), 0, 30)
    display.show()

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

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

# Init OLED display
i2c = I2C(0, scl=Pin(DISPLAY_SCL_PIN), sda=Pin(DISPLAY_SDA_PIN))
display = ssd1306.SSD1306_I2C(DISPLAY_WIDTH, DISPLAY_HEIGHT, i2c)

# Loop
try:
    last_temp = 0
    while 1:
        last_temp = measure_temperature(last_temp)
        time.sleep(0.5)
finally:
    client.disconnect()