import network
import time
from machine import Pin, Timer, I2C
import ssd1306
from umqtt.simple import MQTTClient

# ESP32 Pin assignment 
i2c = I2C(0, scl=Pin(22), sda=Pin(21))

oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)

# MQTT Server Parameters
MQTT_CLIENT_ID      = "micropython-buttons-iot-hw"
MQTT_BROKER         = "broker.mqttdashboard.com"
MQTT_BELL_TOPIC   = "elsys/nikola-petrov/bell"

buttons = [
    Pin(19, Pin.IN, Pin.PULL_DOWN),
    Pin(18, Pin.IN, Pin.PULL_DOWN),
    Pin(17, Pin.IN, Pin.PULL_DOWN),
    Pin(16, Pin.IN, Pin.PULL_DOWN),
]

last_button_press_time = 0

def connect_to_wifi():
    # Connect to Wi-Fi
    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!")

def connect_to_mqtt_broker():
    # Connect to HiveMQ MQTT broker
    connect_to_wifi()
    print("Connecting to MQTT server... ", end="")
    client.connect()
    print("Connected!")

def button_press(pin):
    global last_button_press_time

    current_time = time.ticks_ms()

    # Check if 5 seconds have passed since the last button press
    if current_time - last_button_press_time >= 5000:
        last_button_press_time = current_time

        button_index = buttons.index(pin)
        message = str(button_index)
        oled.fill(0)  # Clear the display
        oled.text("Report to topic".format(MQTT_BELL_TOPIC), 0, 10)
        oled.text("Button index {}".format(button_index), 0, 20)
        oled.text("Buzzerindex {}".format(button_index), 0, 30)
        oled.text("Message: {}".format(button_index), 0, 40)
        oled.show()
        client.publish(MQTT_BELL_TOPIC, message)

# set up interrupt for pressed Button
for btn_pin in buttons:
    btn_pin.irq(trigger=Pin.IRQ_RISING, handler=button_press)

client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
connect_to_mqtt_broker()

try:
    while 1:
        time.sleep(1)  # Add some delay to keep the loop running
finally:
    client.disconnect()