-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpublisher.py
More file actions
50 lines (37 loc) · 1.45 KB
/
Copy pathpublisher.py
File metadata and controls
50 lines (37 loc) · 1.45 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
import ssl,os
from paho import mqtt
import paho.mqtt.client as paho
import time, random
from dotenv import load_dotenv
def on_connect(client, userdata, flags, reason_code, properties):
if reason_code == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code: %d", reason_code)
def on_publish(client, userdata, mid, reason_code, properties):
print("Message ID: "+str(mid), f"Published from {userdata['location']}")
# Simulate temperature sensor
def read_temperature():
return round(random.uniform(20, 35), 1)
load_dotenv()
HOST_NAME = os.getenv("HOST_NAME")
PORT = os.getenv("PORT")
USER_NAME = os.getenv("USER_NAME")
PASSWORD = os.getenv("PASSWORD")
sensor_data = {"location": "room1"}
client = paho.Client(protocol=paho.MQTTv5,
callback_api_version=paho.CallbackAPIVersion.VERSION2,
client_id="sensor_publisher_001",
userdata=sensor_data)
client.on_publish = on_publish
client.on_connect = on_connect
client.tls_set(tls_version=mqtt.client.ssl.PROTOCOL_TLS)
client.username_pw_set(f"{USER_NAME}", f"{PASSWORD}")
client.connect(f"{HOST_NAME}", int(PORT))
# loop_start triggers the on_message, on_publish and on_connect callbacks
client.loop_start()
while True:
temperature = read_temperature()
(rc, mid) = client.publish('sensors/temp', str(temperature), qos=1, retain=True)
print(f"Published: {temperature}°C")
time.sleep(5)