import network
import time
import ujson
from umqtt.simple import MQTTClient
# -----------------------------
# WiFi configuration
# -----------------------------
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# -----------------------------
# ThingsBoard MQTT configuration
# -----------------------------
# Use your device access token from ThingsBoard.
TB_CLIENT_ID = "esp32-01"
TB_BROKER = "thingsboard.cloud"
TB_PORT = 1883
TB_TOKEN = "yBa31inQF6yYOWLf0603"
TB_TOPIC = "v1/devices/me/telemetry"
def connect_wifi():
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
if not sta_if.isconnected():
print("Connecting to WiFi", end="")
sta_if.connect(WIFI_SSID, WIFI_PASSWORD)
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.2)
print(" Connected!")
print("IP:", sta_if.ifconfig()[0])
return sta_if
def connect_thingsboard():
print("Connecting to ThingsBoard...", end="")
client = MQTTClient(
client_id=TB_CLIENT_ID,
server=TB_BROKER,
port=TB_PORT,
user=TB_TOKEN,
password="",
)
client.connect()
print(" Connected!")
return client
def main():
connect_wifi()
client = connect_thingsboard()
print("Starting counter loop")
count = 1
while True:
payload = ujson.dumps({"counter": count})
print("Sending:", payload)
client.publish(TB_TOPIC, payload)
time.sleep_ms(2000)
count += 1
if count > 1000:
count = 1
print("Done")
if __name__ == "__main__":
main()