-
Notifications
You must be signed in to change notification settings - Fork 0
/
MQTT_An_Aus.py
79 lines (67 loc) · 2.63 KB
/
MQTT_An_Aus.py
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
73
74
75
76
77
78
79
"""
A simple example that connects to the Adafruit IO MQTT server
and subscribes to a topic, which will signal the onboard LED
to turn ON or OFF
"""
import time
import network
from machine import Pin
from umqtt.simple import MQTTClient
# Setup the onboard LED so we can turn it on/off
led = Pin("LED", Pin.OUT)
# Fill in your WiFi network name (ssid) and password here:
wifi_ssid = "ZTE_7VPQPK_2.4G"
wifi_password = "2cT5554hn67"
# Connect to WiFi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(wifi_ssid, wifi_password)
while wlan.isconnected() == False:
print('Waiting for connection...')
time.sleep(1)
print("Connected to WiFi")
# Fill in your Adafruit IO Authentication and Feed MQTT Topic details
mqtt_host = "io.adafruit.com"
mqtt_username = "Ted_1958" # Your Adafruit IO username
mqtt_password = "aio_EtES27xF1Bi7MCsMEltwZ9Ey82aL" # Adafruit IO Key
mqtt_receive_topic = "Ted_1958/feeds/led-feed" # The MQTT topic for your Adafruit IO Feed
# Enter a random ID for this MQTT Client
# It needs to be globally unique across all of Adafruit IO.
mqtt_client_id = "somethingreallyrandomandunique123"
# Initialize our MQTTClient and connect to the MQTT server
mqtt_client = MQTTClient(
client_id=mqtt_client_id,
server=mqtt_host,
user=mqtt_username,
password=mqtt_password)
# So that we can respond to messages on an MQTT topic, we need a callback
# function that will handle the messages.
def mqtt_subscription_callback(topic, message):
# Umwandlung von Byte-Strings in normale Zeichenketten
topic_str = topic.decode('utf-8')
message_str = message.decode('utf-8')
print (f'Topic {topic} received message {message}') # Debug print out of what was received over MQTT
if message_str == "on":
print("LED ON")
led.value(1)
elif message_str == "off":
print("LED OFF")
led.value(0)
# Before connecting, tell the MQTT client to use the callback
mqtt_client.set_callback(mqtt_subscription_callback)
mqtt_client.connect()
# Once connected, subscribe to the MQTT topic
mqtt_client.subscribe(mqtt_receive_topic)
print("Connected and subscribed")
led.value(1)
try:
while True:
# Infinitely wait for messages on the topic.
# Note wait_msg() is a blocking call, if you're doing multiple things
# on the Pico you may want to look at putting this on another thread.
print(f'Waiting for messages on {mqtt_receive_topic}')
mqtt_client.wait_msg()
except Exception as e:
print(f'Failed to wait for MQTT messages: {e}')
finally:
mqtt_client.disconnect()