-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmqtt-ted1000.py
270 lines (218 loc) · 7.59 KB
/
mqtt-ted1000.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
__author__ = "Mike Loebl"
__copyright__ = "Copyright (C) Mike Loebl"
# Script based on mqtt-owfs-temp written by Kyle Gordon and converted for use with ted1000
# Source: https://github.com/kylegordon/mqtt-owfs-temp
import os
import logging
import signal
import socket
import time
import sys
import binascii
import paho.mqtt.client as paho
import ConfigParser
import setproctitle
import ted
from datetime import datetime, timedelta
# Read the config file
config = ConfigParser.RawConfigParser()
config.read("/etc/mqtt-ted1000/mqtt-ted1000.cfg")
# Use ConfigParser to pick out the settings
DEBUG = config.getboolean("global", "debug")
LOGFILE = config.get("global", "logfile")
MQTT_HOST = config.get("global", "mqtt_host")
MQTT_PORT = config.getint("global", "mqtt_port")
MQTT_SUBTOPIC = config.get("global", "MQTT_SUBTOPIC")
MQTT_TOPIC = "/raw/" + socket.getfqdn() + MQTT_SUBTOPIC
MQTT_USERNAME = config.get("global", "MQTT_USERNAME")
MQTT_PASSWORD = config.get("global", "MQTT_PASSWORD")
METRICUNITS = config.get("global", "METRICUNITS")
POLLINTERVAL = config.getint("global", "pollinterval")
DEVICE = config.get("global", "device")
owserver = "localhost"
APPNAME = "ted1000"
PRESENCETOPIC = "clients/" + socket.getfqdn() + "/" + APPNAME + "/state"
setproctitle.setproctitle(APPNAME)
client_id = APPNAME + "_%d" % os.getpid()
mqttc = paho.Client()
LOGFORMAT = '%(asctime)-15s %(message)s'
if DEBUG:
logging.basicConfig(filename=LOGFILE,
level=logging.DEBUG,
format=LOGFORMAT)
else:
logging.basicConfig(filename=LOGFILE,
level=logging.INFO,
format=LOGFORMAT)
logging.info("Starting " + APPNAME)
logging.info("INFO MODE")
logging.debug("DEBUG MODE")
def celsiusCon(farenheit):
return (farenheit - 32)*(5/9)
def farenheitCon(celsius):
return ((celsius*(9/5)) + 32)
# All the MQTT callbacks start here
def on_publish(mosq, obj, mid):
"""
What to do when a message is published
"""
logging.debug("MID " + str(mid) + " published.")
def on_subscribe(mosq, obj, mid, qos_list):
"""
What to do in the event of subscribing to a topic"
"""
logging.debug("Subscribe with mid " + str(mid) + " received.")
def on_unsubscribe(mosq, obj, mid):
"""
What to do in the event of unsubscribing from a topic
"""
logging.debug("Unsubscribe with mid " + str(mid) + " received.")
def on_connect(mosq, obj, result_code):
"""
Handle connections (or failures) to the broker.
This is called after the client has received a CONNACK message
from the broker in response to calling connect().
The parameter rc is an integer giving the return code:
0: Success
1: Refused – unacceptable protocol version
2: Refused – identifier rejected
3: Refused – server unavailable
4: Refused – bad user name or password (MQTT v3.1 broker only)
5: Refused – not authorised (MQTT v3.1 broker only)
"""
logging.debug("on_connect RC: " + str(result_code))
if result_code == 0:
logging.info("Connected to %s:%s", MQTT_HOST, MQTT_PORT)
# Publish retained LWT as per
# http://stackoverflow.com/q/97694
# See also the will_set function in connect() below
mqttc.publish(PRESENCETOPIC, "1", retain=True)
process_connection()
elif result_code == 1:
logging.info("Connection refused - unacceptable protocol version")
cleanup()
elif result_code == 2:
logging.info("Connection refused - identifier rejected")
cleanup()
elif result_code == 3:
logging.info("Connection refused - server unavailable")
logging.info("Retrying in 30 seconds")
time.sleep(30)
elif result_code == 4:
logging.info("Connection refused - bad user name or password")
cleanup()
elif result_code == 5:
logging.info("Connection refused - not authorised")
cleanup()
else:
logging.warning("Something went wrong. RC:" + str(result_code))
cleanup()
def on_disconnect(mosq, obj, result_code):
"""
Handle disconnections from the broker
"""
if result_code == 0:
logging.info("Clean disconnection")
else:
logging.info("Unexpected disconnection! Reconnecting in 5 seconds")
logging.debug("Result code: %s", result_code)
time.sleep(5)
def on_message(mosq, obj, msg):
"""
What to do when the client recieves a message from the broker
"""
logging.debug("Received: " + msg.payload +
" received on topic " + msg.topic +
" with QoS " + str(msg.qos))
process_message(msg)
def on_log(mosq, obj, level, string):
"""
What to do with debug log output from the MQTT library
"""
logging.debug(string)
# End of MQTT callbacks
def cleanup(signum, frame):
"""
Signal handler to ensure we disconnect cleanly
in the event of a SIGTERM or SIGINT.
"""
logging.info("Disconnecting from broker")
# Publish a retained message to state that this client is offline
mqttc.publish(PRESENCETOPIC, "0", retain=True)
mqttc.disconnect()
mqttc.loop_stop()
logging.info("Exiting on signal %d", signum)
sys.exit(signum)
def connect():
"""
Connect to the broker, define the callbacks, and subscribe
This will also set the Last Will and Testament (LWT)
The LWT will be published in the event of an unclean or
unexpected disconnection.
"""
logging.info("Connecting to %s:%s", MQTT_HOST, MQTT_PORT)
if MQTT_USERNAME:
logging.info("Found username %s", MQTT_USERNAME)
mqttc.username_pw_set(MQTT_USERNAME, MQTT_PASSWORD)
# Set the Last Will and Testament (LWT) *before* connecting
mqttc.will_set(PRESENCETOPIC, "0", qos=0, retain=True)
result = mqttc.connect(MQTT_HOST, MQTT_PORT, 60)
if result != 0:
logging.info("Connection failed with error code %s. Retrying", result)
time.sleep(10)
connect()
# Define the callbacks
mqttc.on_connect = on_connect
mqttc.on_disconnect = on_disconnect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
mqttc.on_unsubscribe = on_unsubscribe
mqttc.on_message = on_message
if DEBUG:
mqttc.on_log = on_log
mqttc.loop_start()
def process_connection():
"""
What to do when a new connection is established
"""
logging.debug("Processing connection")
def process_message(mosq, obj, msg):
"""
What to do with the message that's arrived
"""
logging.debug("Received: %s", msg.topic)
def find_in_sublists(lst, value):
for sub_i, sublist in enumerate(lst):
try:
return (sub_i, sublist.index(value))
except ValueError:
pass
raise ValueError("%s is not in lists" % value)
def main_loop():
"""
The main loop in which we stay connected to the broker
"""
t = ted.TED(DEVICE)
while True:
for packet in t.poll():
# print
# print "%d byte packet: %r" % (
# len(packet.data), binascii.b2a_hex(packet.data))
# print
for name, value in packet.fields.items():
# print "%s = %s" % (name, value)
mqttc.publish(MQTT_TOPIC + name, value)
time.sleep(POLLINTERVAL)
# Use the signal module to handle signals
signal.signal(signal.SIGTERM, cleanup)
signal.signal(signal.SIGINT, cleanup)
# Connect to the broker and enter the main loop
connect()
# Try to start the main loop
try:
main_loop()
except KeyboardInterrupt:
logging.info("Interrupted by keypress")
sys.exit(0)