"""
MicroPython IoT Weather Station Example for Wokwi.com
To view the data:
1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-weather" then click "Subscribe"
Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.
Copyright (C) 2022, Uri Shaked
https://wokwi.com/arduino/projects/322577683855704658
"""
import network, ubinascii
import time
from machine import Pin, time_pulse_us
from utime import sleep_us
import ujson
from umqtt.simple import MQTTClient
from hcsr04 import HCSR04
# MQTT Server Parameters
MQTT_BROKER = "f708b6b31c2b4a12bc09a1c954ab4b14.s1.eu.hivemq.cloud"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-distance/data"
MQTT_CMD_TOPIC = "wokwi-relay/command"
sensor = HCSR04(trigger_pin=5, echo_pin=18)
led = Pin(32, 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!")
wlan_mac = sta_if.config('mac')
mac_id = ubinascii.hexlify(wlan_mac).decode().upper()
print("Mac Id", mac_id)
def sub_cb(topic, msg):
decoded = ujson.loads(msg.decode())
print(decoded)
relay = decoded.get('relay', -1)
target_device_mac_id = decoded.get('deviceMacId', "")
if relay == -1 or target_device_mac_id != mac_id: return
led(relay == 1)
led(True)
MQTT_CLIENT_ID = "fullstack-iot-" + mac_id
ssl_params = {"server_hostname": MQTT_BROKER}
print("Connecting to MQTT server with id {}... ".format(MQTT_CLIENT_ID), end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, port=8883, ssl=True, ssl_params=ssl_params, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(sub_cb)
client.connect()
client.subscribe(MQTT_CMD_TOPIC)
print("Connected!")
prev_distance = -1
debounce_limit = 0.2
while True:
print("Measuring distance... ", end="")
client.check_msg()
time.sleep(5)
distance = sensor.distance_cm()
print('Distance:', distance, 'cm')
delta = abs(distance - prev_distance)
if delta > debounce_limit:
print("Updated!")
message = ujson.dumps({
"deviceMacId": mac_id,
"Distance": distance
})
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
prev_distance = distance
else:
print("No change")