from machine import Pin
from utime import sleep
import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient

# MQTT Server Parameters
MQTT_CLIENT_ID = "Challenge"
MQTT_BROKER    = "broker.emqx.io"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC     = "/JMK35/Marcello/LEDtest"

led = Pin(15, Pin.OUT)

print("Connecting to WiFi", 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!")

# MQTT Server connection
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")

# Build the message in JSON format and send the message only if there is a change
led_status = ""
while True:
  led.on()
  sleep(0.5)
  print("led on")
  led.off()
  sleep(0.5)
  print("led off")
  message = ujson.dumps({
    "led off","led on",
    
    # sleep(0.5),
    # "temp2": sensor2.temperature(),
    # "humidity2": sensor2.humidity(),
  })

  if message != led_status:
    print("Updated!")
    print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
    # Send the message
    client.publish(MQTT_TOPIC, message)
  else:
    print("No change")
  time.sleep(1)