-
Notifications
You must be signed in to change notification settings - Fork 0
/
currentcost-power
executable file
·51 lines (40 loc) · 1.21 KB
/
currentcost-power
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
#!/usr/bin/env python
import paho.mqtt.client
import mqtt_config
import time
import xmltodict
import json
import serial
#Test in test/, check http://spacehub.somakeit.org.uk
#for advice choosing a topic for production
TOPIC = "somakeit/space/power/usage"
SERIAL_PORT = "/dev/ttyUSB0"
BAUD_RATE = 57600
#Connect to a broker
mqtt = paho.mqtt.client.Client(client_id=mqtt_config.client_id, clean_session=True)
#Use real root certificates
mqtt.tls_set(("/etc/ssl/certs/ca-certificates.crt"))
mqtt.username_pw_set(mqtt_config.user_name, mqtt_config.password)
mqtt.loop_start()
while True:
try:
mqtt.connect(mqtt_config.server, port=mqtt_config.port)
break
except Exception as e:
print "failed to connecct: " + str(e)
time.sleep(60)
print "retrying.."
#open the serial port
ser = serial.Serial(SERIAL_PORT, BAUD_RATE)
while True:
timestamp = int(time.time())
#get the next line from the meter
line = ser.readline()
#convrt to sane data if we can
try:
data = xmltodict.parse(line)
except Exception:
continue
data.update({"timestamp": timestamp})
message = json.dumps(data)
mqtt.publish(TOPIC, payload=message, qos=0, retain=True)