from machine import Pin, ADC
import network
import time
import json
from umqtt.simple import MQTTClient
pot = ADC(Pin(34))
pot.atten(ADC.ATTN_11DB)
led = Pin(2, Pin.OUT)
WIFI_NAME = "Wokwi-GUEST"
WIFI_PASSWORD = ""
MQTT_BROKER = "broker.emqx.io"
MQTT_CLIENT_ID = "wokwi-la-client"
SENSOR_TOPIC = b"lnu/iot/la/sensor"
LED_TOPIC = b"lnu/iot/la/command/led"
def handle_message(topic, message):
print("Message received:", topic, message)
if topic == LED_TOPIC:
data = json.loads(message)
if data["state"] == True:
led.on()
print("LED ON")
else:
led.off()
print("LED OFF")
print("Connecting to WiFi...")
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(WIFI_NAME, WIFI_PASSWORD)
while not wifi.isconnected():
time.sleep(0.2)
print(".")
print("Connected to WiFi")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.set_callback(handle_message)
client.connect()
client.subscribe(LED_TOPIC)
print("Connected to MQTT")
print("Subscribed to LED topic")
client.publish(LED_TOPIC, b'{"state":true}')
print("Test command sent")
while True:
client.check_msg()
value = pot.read()
payload = {
"value": value,
"timestamp": time.time()
}
message = json.dumps(payload)
client.publish(SENSOR_TOPIC, message)
print(message)
time.sleep(2)