-
Notifications
You must be signed in to change notification settings - Fork 1
/
MQTT_Publisher.py
41 lines (31 loc) · 933 Bytes
/
MQTT_Publisher.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
#!/usr/bin/python3
import paho.mqtt.client as mqtt
from urllib.parse import urlparse
import sys
import time
import json
# Define event callbacks
def on_connect(client, userdata, flags, rc):
print("Connection Result: " + str(rc))
def on_publish(client, obj, mid):
print("Message ID: " + str(mid))
mqttc = mqtt.Client()
# Assign event callbacks
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
# parse mqtt url for connection details
url_str = sys.argv[1]
print(url_str)
url = urlparse(url_str)
base_topic = url.path[1:]
# Connect
if (url.username):
mqttc.username_pw_set(url.username, url.password)
mqttc.connect(url.hostname, url.port)
mqttc.loop_start()
# Publish a message to temp every 15 seconds
while True:
temp=round(sense.get_temperature(),2)
temp_json=json.dumps({"temperature":temp, "timestamp":time.time()})
mqttc.publish(base_topic+"/temperature", temp_json)
time.sleep(15)