import network
import time
import random
import socket
import struct
# ---------------- CONFIGURATION ----------------
BROKER = "broker.hivemq.com"
PORT = 1883
# Change this to "node1" for the first board, and "node2" for the second board
NODE_ID = "node2"
CLIENT_ID = ("bridge_" + NODE_ID + "_combined").encode()
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if wlan.isconnected():
return True
print(f"[{NODE_ID}] Connecting to Wi-Fi...")
try:
wlan.connect("Wokwi-GUEST", "")
except:
pass
for i in range(20):
if wlan.isconnected():
print(f"[{NODE_ID}] Wi-Fi Connected!")
return True
time.sleep(1)
return False
def connect_mqtt():
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 or response[3] != 0:
raise Exception("MQTT connection failed")
print(f"[{NODE_ID}] MQTT Connected!")
return client
def publish_metric(client, metric_name, value):
topic = f"bridge/{NODE_ID}/{metric_name}".encode()
message = str(value).encode()
length = 2 + len(topic) + len(message)
packet = b"\x30" + bytes([length])
packet += struct.pack("!H", len(topic))
packet += topic + message
client.send(packet)
print(f"[{NODE_ID}] Published {metric_name}: {value}")
print(f"SMART BRIDGE - {NODE_ID.upper()} (ALL SENSORS)")
client = None
last_ping = time.time()
while True:
try:
if not connect_wifi():
print(f"[{NODE_ID}] Wi-Fi unavailable. Retrying...")
time.sleep(3)
continue
if client is None:
print(f"[{NODE_ID}] Connecting to MQTT...")
client = connect_mqtt()
last_ping = time.time()
# Read all three sensors on this single node
vibration = random.randint(10, 100)
temperature = random.randint(25, 60)
strain = random.randint(100, 800)
# Publish each sensor reading to its respective topic
publish_metric(client, "vibration", vibration)
publish_metric(client, "temperature", temperature)
publish_metric(client, "strain", strain)
if time.time() - last_ping >= 30:
client.send(b"\xc0\x00")
last_ping = time.time()
print("----------------------")
time.sleep(5)
except Exception as error:
print(f"[{NODE_ID}] Connection Error:", error)
if client is not None:
try:
client.close()
except:
pass
client = None
print(f"[{NODE_ID}] 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
Loading
esp32-devkit-c-v4
esp32-devkit-c-v4
Board not found
board-mpu6050
board-mpu6050
Board not found
board-mpu6050
board-mpu6050