import time
import machine
import network
from umqtt_simple import MQTTClient
# --- Wokwi WiFi Configuration ---
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# --- Local Node-RED MQTT Broker Configuration ---
MQTT_BROKER = "10.10.0.1" # عنوان الـ Gateway المحلي لجهازك في Wokwi
MQTT_PORT = 1883
MQTT_CLIENT_ID = "pico_client_local"
# --- Hardware Setup ---
led_green = machine.Pin(0, machine.Pin.OUT)
led_red = machine.Pin(1, machine.Pin.OUT)
# --- MQTT Topics ---
sub_topic_red_led = "alaaq/led_red/topic"
sub_topic_green_led = "alaaq/led_green/topic"
pub_topic_temperature = "alaaq/temperature/topic"
# --- Connect to Wokwi WiFi ---
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
print("Connecting to Wokwi-GUEST WiFi", end="")
while not wlan.isconnected():
time.sleep(1)
print(".", end="")
print("\nConnected to the WiFi:", wlan.ifconfig())
# --- MQTT Callback Function ---
def callback(topic, msg):
sub_msg = msg.decode("utf-8")
sub_topic = topic.decode("utf-8")
print("Received message -", sub_msg, "on topic -", sub_topic)
if sub_topic == sub_topic_red_led:
led_red.value(int(sub_msg))
elif sub_topic == sub_topic_green_led:
led_green.value(int(sub_msg))
# --- Initialize Public MQTT Client ---
mqtt_client = MQTTClient(
client_id=MQTT_CLIENT_ID, server=MQTT_BROKER, port=MQTT_PORT
)
mqtt_client.set_callback(callback)
# --- Connect with Retry Logic (لتجاوز بطء المحاكي) ---
print("Connecting to public MQTT broker...")
connected = False
while not connected:
try:
mqtt_client.connect()
connected = True
print("Connected to MQTT broker successfully!")
except Exception as e:
print("Connection failed, retrying in 3 seconds...", e)
time.sleep(3)
mqtt_client.subscribe(sub_topic_red_led)
mqtt_client.subscribe(sub_topic_green_led)
# --- Read Internal Temperature ---
def read_temperature():
adc = machine.ADC(4)
conversion_factor = 3.3 / 65535
sensor_value = adc.read_u16() * conversion_factor
temperature = 27 - (sensor_value - 0.706) / 0.001721
return temperature
# --- Main Loop ---
try:
while True:
# Check for incoming messages
mqtt_client.check_msg()
# Read and publish temperature
temperature = read_temperature()
temp_str = str(round(temperature, 2))
mqtt_client.publish(pub_topic_temperature, temp_str.encode("utf-8"))
print("Temp published:", temp_str)
time.sleep(2)
except KeyboardInterrupt:
print("Disconnected!")
mqtt_client.disconnect()