#20 November 2023
"""
Task 1: ESP32 Programming
Connect the HC-SR04 Ultrasonic Distance Sensor to the ESP32 microcontroller in wokwi web-based simulator.
Write a program to read data from the sensor.
In your program code replace MQTT_CLIENT_ID = "Your BITD_ID" (Example:: MQTT_CLIENT_ID = "2023pj16001")
Integrate MQTT library for ESP32 and publish sensor data to a specific MQTT topic: /IIoT/Your BITS_ID/distance (Example:: /IIoT/2023pj16001/distance)
Task 2: MQTT Broker Setup
Use mosquitto.org which hosts a publicly available Eclipse Mosquitto MQTT server/broker or hivemq broker.
Task 3: Node-RED Configuration
Access the Node-RED interface and set up the necessary nodes for MQTT communication.
Create an MQTT input node to subscribe to the topic where the ESP32 is publishing data.
Utilize the debug node to confirm that Node-RED is receiving the data.
Task 4: Node-RED Flow
Design a Node-RED flow that processes the incoming MQTT data.
Include nodes for data visualization (e.g., dashboard nodes) to display the sensor data.
Add nodes for any additional processing or logic required for the specific use case.
Task 5: Testing and Validation
Test the end-to-end functionality of the system.
Verify that data from the sensor is transmitted via MQTT to Node-RED.
Ensure Node-RED processes the data correctly and displays it on the chosen visualization components.
https://wokwi.com/projects/360421664389825537
"""
import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
from hcsr04 import HCSR04
from time import sleep
# MQTT Server Parameters
MQTT_CLIENT_ID = "2023pj16001"
MQTT_BROKER = "test.mosquitto.org"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "/IIoT/2023pj16001/distance" # change to your topic
# ESP32
#sensor1 = HCSR04(trigger_pin=5, echo_pin=18, echo_timeout_us=100000)
sensor1 = HCSR04(trigger_pin=5, echo_pin=18, echo_timeout_us=100000)
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!")
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
prev_distance = ""
while True:
distance = sensor1.distance_cm()
print('Distance:', distance, 'cm')
sleep(1)
message = ujson.dumps(distance)
if message != prev_distance:
print("Updated!")
print("Reporting to MQTT topic {}:{} ".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
prev_distance = message
else:
print("No change")
time.sleep(1)