import network
import time
import socket
import struct
import random
BROKER = "broker.hivemq.com"
PORT = 1883
CLIENT_ID = b"bridge_node1_final"
client = None
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to WiFi...")
wlan.connect("Wokwi-GUEST", "")
while not wlan.isconnected():
time.sleep(1)
print("WiFi Connected!")
def connect_mqtt():
global client
client = socket.socket()
client.settimeout(10)
address = socket.getaddrinfo(BROKER, PORT)[0][-1]
client.connect(address)
packet = b"\x10" + bytes([12 + len(CLIENT_ID)])
packet += b"\x00\x04MQTT\x04\x02\x00\x3c"
packet += bytes([0, len(CLIENT_ID)]) + CLIENT_ID
client.send(packet)
response = client.recv(4)
if response[0] == 0x20 and response[3] == 0:
print("MQTT Connected Successfully!")
else:
raise Exception("MQTT connection failed")
def publish(topic, message):
topic_bytes = topic.encode()
msg_bytes = str(message).encode()
length = 2 + len(topic_bytes) + len(msg_bytes)
packet = b"\x30" + bytes([length])
packet += struct.pack("!H", len(topic_bytes))
packet += topic_bytes + msg_bytes
client.send(packet)
print(f"Published [{topic}]: {message}")
# ---------------- MAIN PROGRAM ----------------
print("SMART BRIDGE - NODE 1 (ALL SENSORS)")
while True:
try:
connect_wifi()
if client is None:
connect_mqtt()
# Read/Simulate all three sensors on Node 1
vibration = random.randint(10, 100)
temperature = random.randint(25, 60)
strain = random.randint(100, 800)
# Publish each sensor reading to its respective topic
publish("bridge/node1/vibration", vibration)
publish("bridge/node1/temperature", temperature)
publish("bridge/node1/strain", strain)
print("----------------------")
time.sleep(5)
except Exception as error:
print("Connection Error:", error)
if client is not None:
try:
client.close()
except:
pass
client = None
print("Reconnecting in 3 seconds...")
time.sleep(3)Loading
esp32-devkit-c-v4
esp32-devkit-c-v4
Loading
esp32-devkit-c-v4
esp32-devkit-c-v4