-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path16_B_Mqtt.py
62 lines (52 loc) · 1.95 KB
/
16_B_Mqtt.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
"""
A simple example that connects to the Adafruit IO MQTT server
and publishes values that represent a sine wave
"""
import network
import time
from math import sin
from umqtt.simple import MQTTClient
# Fill in your WiFi network name (ssid) and password here:
wifi_ssid = "Gr.Hasenpfad_2.4"
wifi_password = "robo-1958!"
# 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_WDZt35eLSS52hu52gspmX7Ex5Uo0" # Adafruit IO Key
mqtt_publish_topic = "Ted_1958/feeds/dht11-daten" # 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 = "Robo-Studio_Test_1"
# 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)
mqtt_client.connect()
# Publish a data point to the Adafruit IO MQTT server every 3 seconds
# Note: Adafruit IO has rate limits in place, every 3 seconds is frequent
# enough to see data in realtime without exceeding the rate limit.
counter = 0
try:
while True:
# Generate some dummy data that changes every loop
sine = sin(counter)
counter += .8
# Publish the data to the topic!
print(f'Publish {sine:.2f}')
mqtt_client.publish(mqtt_publish_topic, str(sine))
# Delay a bit to avoid hitting the rate limit
time.sleep(3)
except Exception as e:
print(f'Failed to publish message: {e}')
finally:
mqtt_client.disconnect()