-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwifi.py
More file actions
74 lines (58 loc) · 2.21 KB
/
wifi.py
File metadata and controls
74 lines (58 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import network
import credentials
import time
from simple import MQTTClient
import screen
wifi_connected = 0
mqtt_connected = 0
# Define the callback function for when a message is received
def on_message(topic, msg):
print("Received message:", msg.decode())
print("From topic:", topic.decode())
screen.hscroll_text(msg.decode())
def on_connect():
print("MQTT Conencted")
mqtt_connected = 1
def on_disconnect():
print("MQTT Disconnected")
mqtt_connected = 0
# Start the WLAN module in station mode
wlan = network.WLAN(network.STA_IF)
mqttClient = MQTTClient(credentials.client_id, credentials.mqtt_server, port=credentials.mqtt_port, user=credentials.mqtt_user, password=credentials.mqtt_password)
mqttClient.set_callback(on_message)
mqttClient.on_connect = on_connect()
mqttClient.on_disconnect = on_disconnect()
def connect_mqtt():
if wlan.isconnected():
# Proceed to connect to the MQTT server
try:
mqttClient.connect()
print("Connected to MQTT Broker!")
screen.display_centered_text("MQTT OK")
mqttClient.subscribe(credentials.mqtt_topic)
print(f"Subscribed to {credentials.mqtt_topic}")
screen.display_centered_text("SUB OK")
mqtt_connected = 1
# Wait for messages indefinitely
while True:
mqttClient.check_msg()
time.sleep(1) # A small delay to prevent CPU hogging
except Exception as e:
print("Failed to connect to MQTT broker. Error:", e)
screen.display_centered_text("MQTT Fail")
def connect_wifi():
wlan.active(True)
# Connect to the specified WiFi network
wlan.connect(credentials.ssid, credentials.password)
# Wait for the connection to be established
while not wlan.isconnected() and wlan.status() >= 0:
print("Waiting for connection...")
time.sleep(1)
# Check if the Pico W is connected to the WiFi
if wlan.isconnected():
wifi_connected = 1
print(f"Connected to {credentials.ssid}")
screen.display_centered_text("Connected")
else:
print("Failed to connect to WiFi network.")
screen.display_centered_text("WiFi Fail")