-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1W2MQTT-docker.py
executable file
·341 lines (249 loc) · 8.07 KB
/
1W2MQTT-docker.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
#!/usr/bin/python
import json
import sys
import ownet
import paho.mqtt.client as mqtt
import time
import thread
import operator
from terminaltables import AsciiTable
import os
class OwEventHandler(mqtt.Client):
def __init__(self,ip = "mqtt", port = 1883, clientId = "1W2MQTT", user = "driver", password = "1234", prefix = "1-wire",owserver = "owserver", owport = 4304):
mqtt.Client.__init__(self,clientId)
self.prefix = prefix
self.ip = ip
self.port = port
self.clientId = clientId
self.user = user
self.password = password
if user != None:
self.username_pw_set(user,password)
self.will_set( topic = "system/" + self.prefix, payload="Offline", qos=1, retain=True)
print "Connecting"
self.connect(ip,keepalive=10)
self.subscribe(self.prefix + "/#", 0)
self.on_connect = self.mqtt_on_connect
self.on_message = self.mqtt_on_message
self.publish(topic = "system/"+ self.prefix, payload="Online", qos=1, retain=True)
# 1 wire stuff
self.owserver = owserver
self.owport = owport
#Setup.
self.Updates = {}
self.LastChecked = {}
self.alarmlist = []
self.LastCycled = None
self.cycletime = 0
self.LastUpdate = ""
self.MQTTstatus = ""
#thread.start_new_thread(self.ControlLoop,())
self.loop_start()
return
def mqtt_on_connect(self, client, userdata, flags, rc):
self.MQTTstatus = "MQTT connected!"
self.subscribe(self.prefix + "/#", 0)
def mqtt_on_message(self, selfX,mosq, msg):
self.MQTTstatus = "RECIEVED MQTT MESSAGE: "+msg.topic + " " + str(msg.payload)
return
def ControlLoop(self):
# schedule the client loop to handle messages, etc.
self.loop_forever()
self.MQTTstatus = "Closing connection to MQTT"
time.sleep(1)
def PollOwServer(self):
#Init connection.
self.root = ownet.Sensor("/",self.owserver,self.owport)
#Create a list which keeps track of when sensors was read.
self.LastChecked = self.CheckForNewSensors()
#Init alarm path
self.alarm = ownet.Sensor("/alarm",self.owserver,self.owport)
#Check all sensors.
self.CheckSensors(self.LastChecked.keys())
now = time.time()
while(True):
#Update the LastChecked list with added or removed sensors.
self.LastChecked = self.CheckForNewSensors(self.LastChecked)
#Do some iterations then check for new sensors.
for f in range(0,30):
#Sleep some to not overload the system with requests.
time.sleep(0.1)
#Time the loop
lasttime = now
now = time.time()
self.cycletime = now-lasttime
#Check if there is alarms and check them.
self.alarmlist = self.GetAlarmList()
for sensor in self.alarmlist:
sensor.alarm = now
self.CheckSensors(self.alarmlist,False)
#Update old values and non alarm sensors. Check one each iteration.
#Update the LastChecked list with added or removed sensors.
self.LastChecked = self.CheckForNewSensors(self.LastChecked)
#Try to find the oldest one.
try:
(sensor,checked) = self.GetOldestUpdate()[0]
except IndexError:
continue
#Avoid updating sensors more than once each second.
if (now - checked) < 1.0:
continue
#Check the sensor.
self.CheckSensors([sensor])
self.LastCycled = sensor
#Debug print.
if f%1==0:
self.PrintLastCheckedTimes()
return
#Check for new sensors and remove old ones.
def CheckForNewSensors(self,old_dict={}):
sensorlist = self.root.sensorList()
new_dict = {}
now = time.time()
for sensor in sensorlist:
sensor.present = True
sensor.alarm = 0
#Make a new list
for sensor in sensorlist:
try:
#Copy update time from old list if possible.
new_dict[sensor] = old_dict[sensor]
except KeyError:
#Not in old so new snesor. Indicate that it has never been checked.
sensor.present = True
new_dict[sensor] = 0.0
#Readd sensors that disconnected but pospone reading.
for sensor in old_dict:
if not sensor in new_dict:
sensor.present = False
new_dict[sensor]=old_dict[sensor]
return new_dict
#Returns a list with the N sensors with oldest update times.
def GetOldestUpdate(self,n=1):
return sorted(self.LastChecked.items(), key=operator.itemgetter(1))[:n]
def PrintLastCheckedTimes(self):
dictlist = [["Sensor","Time since update","update bar","Update reason","Present"]]
now = time.time()
for sensor, value in self.LastChecked.iteritems():
try:
id = str(sensor.family) +"."+sensor.id
except:
continue
deltatime = int(now-value)
bar = deltatime
if bar > 20:
bar = 20
update = " "
try:
if sensor == self.LastCycled:
update = " <-"
except:
pass
if sensor in self.alarmlist:
update = "(!)"
try:
if now - sensor.alarm < 3.0:
update = "(!)"
except:
update += "_"
try:
if sensor.present:
present="Y"
else:
present="N"
except:
present="-"
temp = [id,str(deltatime),("*" * bar) + (" " * (20-bar)),update,present ]
dictlist.append(temp)
table = AsciiTable(dictlist)
#Print topics
dictlist2=[[" ","Topic","Payload"]]
for topic, payload in self.Updates.iteritems():
updated = " "
if topic == self.LastUpdate:
self.LastUpdate = ""
updated = "*"
temp = [updated ,topic,str(payload)]
dictlist2.append(temp)
table2 = AsciiTable(dictlist2)
os.system('clear')
print "-" * 50
print " " * 15 + "1WIRE TO MQTT"
print "-" * 50
print " "
print "Owserver traffic"
print table.table
print " "
print "Cycle time = %f" % self.cycletime
print " "
print "MQTT traffic"
print table2.table
print " "
print self.MQTTstatus
print "\n"*4
print "Created by Anton Gustafsson"
return
#This function takes the format deliverd from alarm and turns it into an sensor object list.
def GetAlarmList(self):
list = self.alarm.entryList()
sensorlist = []
all_sensors = self.LastChecked.keys()
now = time.time()
#Loop trough all known sensors and see if they are in the list provided.
for sensor in all_sensors:
try:
id = str(sensor.family) +"."+sensor.id
except:
continue
if id in list:
sensor.alarm = now
sensorlist.append(sensor)
#print sensorlist
return sensorlist
def Update(self,topic,value):
#Filter already sent stuff.
if topic in self.Updates:
if value == self.Updates[topic]:
#print "Rejected repeated message!"
return False
self.Updates[topic] = value
self.LastUpdate = topic
#Create json msg
timestamp = time.time()
msg = json.dumps({"time":timestamp,"value":value})
#print "New event: " + topic
self.publish(topic,msg,1)
return True
def UpdateDS2406(self,sensor, init = False):
id = str(sensor.family) +"/"+ str(sensor.id)
values = sensor.sensed_ALL.split(",")
trigger = sensor.latch_ALL.split(",")
#Loop trough pins
for i in range(0,len(values)):
topic = self.prefix+"/"+id+"/"+str(i)
try:
value = int(values[i])
except:
value = values[i]
self.Update(topic,value)
sensor.latch_BYTE = 0
if init:
if not sensor.set_alarm == 311:
sensor.set_alarm = 311
return
def CheckSensors(self,sensorlist,init=False):
for sensor in sensorlist:
now = time.time()
self.LastChecked[sensor]=now
sensor.LastChecked = now
if not hasattr(sensor,"type"):
continue
stype = sensor.type
if stype == "DS2406":
self.UpdateDS2406(sensor,init)
else:
continue
return
if __name__ == '__main__':
EventHandler = OwEventHandler()
EventHandler.PollOwServer()