mqtt.py
import time
from umqtt.robust import MQTTClient
#simple, simple2, robust2 all experimented same result
class MQTTSubscriber:
def __init__(self, server, port, client_id, username, password, topic, ssl, ssl_params):
self.server = server
self.port = port
self.client_id = client_id
self.username = username
self.password = password
self.topic = topic
self.ssl = ssl
self.ssl_params = ssl_params
self.client = MQTTClient(self.client_id, self.server, port=self.port, user=self.username, password=self.password, ssl=self.ssl, ssl_params=self.ssl_params)
self.client.set_callback(self.callback)
def callback(self, topic, msg):
print("Received message on topic: {}, Message: {}".format(topic, msg))
def connect(self):
self.client.connect()
self.client.subscribe(self.topic)
def publish_message(self, message):
self.client.publish(self.topic, message)
print("Published message: {}".format(message))
def run(self, interval):
while True:
self.publish_message("Hello, world!")
time.sleep(interval)
def disconnect(self):
self.client.disconnect()
wifi.py
import network
class WiFiManager:
def __init__(self, ssid, password):
self.ssid = ssid
self.password = password
self.wlan = network.WLAN(network.STA_IF)
def connect(self):
self.wlan.active(True)
if not self.wlan.isconnected():
print("Connecting to Wi-Fi...")
self.wlan.connect(self.ssid, self.password)
while not self.wlan.isconnected():
pass
print("Wi-Fi connected!")
print("IP address:", self.wlan.ifconfig()[0])
def disconnect(self):
self.wlan.disconnect()
main.py
from mqtt import MQTTSubscriber
from time import sleep
from wifi import WiFiManager
import ubinascii
import machine
import gc
gc.collect()
# ESP32
sensor1 = HCSR04(trigger_pin=5, echo_pin=18, echo_timeout_us=10000)
sensor2 = HCSR04(trigger_pin=4, echo_pin=16, echo_timeout_us=10000)
# ESP8266
#sensor = HCSR04(trigger_pin=12, echo_pin=14, echo_timeout_us=10000)
# Wi-Fi credentials
wifi_ssid = "MYSSID"
wifi_password = "MYPASSWORD"
# Instantiate the WiFiManager and MQTTSubscriber classes
wifi_manager = WiFiManager(wifi_ssid, wifi_password)
# Connect to Wi-Fi, MQTT, run, and disconnect
wifi_manager.connect()
# Instantiate the MQTTSubscriber class
subscriber = MQTTSubscriber(
server= b"MYBROKER.s2.eu.hivemq.cloud",
port=8883,
client_id= ubinascii.hexlify(machine.unique_id()),
#created credentials in access management
username="MQTTUSER",
password="MQTTPASS",
topic= b"Floor00/Desk01",
ssl= False,
ssl_params={}
)
interval=3
# Connect, run, and disconnect
subscriber.connect()