-
Notifications
You must be signed in to change notification settings - Fork 0
/
sensor.py
343 lines (272 loc) · 10 KB
/
sensor.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
342
343
#! python3.4
import paho.mqtt.client as mqtt
import json
import os
import time
import logging,random,os
import sys,getopt
options=dict()
brokers=["192.168.1.206","192.168.1.157","192.168.1.204","192.168.1.185","test.mosquitto.org",\
"broker.hivemq.com","iot.eclipse.org"]
def yesno():
answer = input("¿Desea conectarse al broker '192.168.1.157'? (yes/no): ")
if answer == "yes":
options["broker"]=brokers[1]
elif answer == "no":
options["broker"]= input("Introduzca la direccion del broker al que desea conectarse: ")
else:
print("Please enter yes or no.")
yesno()
options["port"]=1883
options["verbose"]=False
options["username"]=""
options["password"]=""
options["cname"]=""
options["sensor_type"]="light"
options["topic_base"]="sensors"
options["interval"]=10 #loop time when sensor publishes in verbose
options["interval_pub"]=300 # in non chatty mode publish
options["keepalive"]=120
options["loglevel"]=logging.ERROR
cname=""
QOS0=0
mqttclient_log=False
username=""
password=""
chatty=False
interval=2 #loop time when sensor publishes
sensor_pub_interval=300# how often to publish if status is unchanged
def command_input(options):
topics_in=[]
qos_in=[]
valid_options=" -h <broker> -b <broker> -p <port>-t <topic> -q QOS -v -h <help>\
-d logging debug -n Client ID or Name -i loop Interval\
-s <set states to open and closed> -u Username -P Password --h <help>"
print_options_flag=False
try:
opts, args = getopt.getopt(sys.argv[1:],"h:b:i:dk:p:t:q:l:vsn:r:u:P:")
except getopt.GetoptError:
print (sys.argv[0],valid_options)
sys.exit(2)
qos=0
for opt, arg in opts:
if opt == '-h':
options["broker"] = str(arg)
elif opt == "-b":
options["broker"] = str(arg)
elif opt == "-i":
options["interval"] = int(arg)
elif opt == "-k":
options["keepalive"] = int(arg)
elif opt=="-r":
options["topic_base"]=str(arg)
elif opt =="-p":
options["port"] = int(arg)
elif opt =="-t":
topics_in.append(arg)
elif opt =="-q":
qos_in.append(int(arg))
elif opt =="-n":
options["cname"]=arg
elif opt =="-d":
options["loglevel"]=logging.DEBUG
elif opt =="-v":
options["verbose"]=True
elif opt =="-s":
options["sensor_type"]="door"
elif opt == "-P":
options["password"] = str(arg)
elif opt == "-u":
options["username"] = str(arg)
lqos=len(qos_in)
for i in range(len(topics_in)):
if lqos >i:
topics_in[i]=(topics_in[i],int(qos_in[i]))
else:
topics_in[i]=(topics_in[i],0)
if topics_in:
options["topics"]=topics_in
def on_message(client,userdata, msg):
print(client)
print(userdata)
print(msg)
topic=msg.topic
m_decode=str(msg.payload.decode("utf-8","ignore"))
logging.debug("Message Received "+m_decode)
print(m_decode)
message_handler(client,m_decode,topic)
def message_handler(client,msg,topic):
if topic==topic_control: #Recibido control message
print("control message ",msg)
update_status(client,msg)
def on_connect(client, userdata, flags, rc):
logging.debug("Connected flags"+str(flags)+"result code "\
+str(rc)+"client1_id")
if rc==0:
client.connected_flag=True
client.publish(connected_topic,1,retain=True)
client.subscribe(options["topics"])
else:
client.bad_connection_flag=True
def on_disconnect(client, userdata, rc):
logging.debug("disconnecting reason " + str(rc))
client.connected_flag=False
client.disconnect_flag=True
client.subscribe_flag=False
def update_status(client,status):
status=status.upper()
if status==states[0] or status==states[1]: #Si esta dentro de los margenes aceptados
client.sensor_status=status #update
print("updating status",client.sensor_status)
def publish_status(client):
global start_flag #used to publish on start
pubflag=False
if start_flag:
start_flag=False
pubflag=True
if time.time()-client.last_pub_time >=options["interval_pub"]:
pubflag=True
if time.time()-client.last_pub_time >=options["interval"] and chatty:
pubflag=True
logging.debug("old "+str(client.sensor_status_old))
logging.debug("new "+ str(client.sensor_status))
if client.sensor_status_old!=client.sensor_status or pubflag:
client.publish(sensor_status_topic,client.sensor_status,0,True)
print("publish on",sensor_status_topic,\
" message ",client.sensor_status)
client.last_pub_time=time.time()
client.sensor_status_old=client.sensor_status
def Initialise_client_object():
mqtt.Client.last_pub_time=time.time()
mqtt.Client.topic_ack=[]
mqtt.Client.run_flag=True
mqtt.Client.subscribe_flag=False
mqtt.Client.sensor_status=states[1]
mqtt.Client.sensor_status_old=None
mqtt.Client.bad_connection_flag=False
mqtt.Client.connected_flag=False
mqtt.Client.disconnect_flag=False
mqtt.Client.disconnect_time=0.0
mqtt.Client.disconnect_flagset=False
mqtt.Client.pub_msg_count=0
def Initialise_clients(cname):
#flags set
client= mqtt.Client(cname)
if mqttclient_log: #enable mqqt client logging
client.on_log=on_log
client.on_connect= on_connect #attach function to callback
client.on_message=on_message #attach function to callback
client.on_disconnect=on_disconnect
return client
def Connect(client,broker,port,keepalive,run_forever=False):
"""Attempts connection set delay to >1 to keep trying
but at longer intervals """
connflag=False
delay=5
#print("connecting ",client)
badcount=0 # counter for bad connection attempts
while not connflag:
logging.info("connecting to broker "+str(broker))
print("connecting to broker "+str(broker)+":"+str(port))
print("Attempts ",badcount)
try:
res=client.connect(broker,port,keepalive) #connect to broker
if res==0:
connflag=True
return 0
else:
logging.debug("connection failed ",res)
badcount +=1
if badcount>=3 and not run_forever:
return -1
raise SystemExit #give up
elif run_forever and badcount<3:
delay=5
else:
delay=30
except:
client.badconnection_flag=True
logging.debug("connection failed")
badcount +=1
if badcount>=3 and not run_forever:
return -1
raise SystemExit #give up
elif run_forever and badcount<3:
delay=5*badcount
elif delay<300:
delay=30*badcount
time.sleep(delay)
return 0
def wait_for(client,msgType,period=.25,wait_time=40,running_loop=False):
#running loop is true when using loop_start or loop_forever
client.running_loop=running_loop #
wcount=0
while True:
logging.info("waiting"+ msgType)
if msgType=="CONNACK":
if client.on_connect:
if client.connected_flag:
return True
if client.bad_connection_flag: #
return False
if not client.running_loop:
client.loop(.01) #check for messages manually
time.sleep(period)
wcount+=1
if wcount>wait_time:
print("return from wait loop taken too long")
return False
if __name__ == "__main__" and len(sys.argv)>=2:
command_input(options)
chatty=options["verbose"]
logging.basicConfig(level=options["loglevel"]) #error logging
#use DEBUG,INFO,WARNING,ERROR
if not options["cname"]:
r=random.randrange(1,10000)
r=3542
cname="sensor-"+str(r)
else:
cname=str(options["cname"])
##Por si se quieren cambiar los topics
connected_topic=options["topic_base"]+"/connected/"+"light"
sensor_status_topic=options["topic_base"]+"/"+"light"
topic_control=sensor_status_topic+"/control"
options["topics"]=[(topic_control,0)]
if not options["verbose"]:
print("only sending changes")
if options["sensor_type"]=="light":
states=["ON","OFF"] #possible sensor states
else:
states=["OPEN","CLOSED"] #possible sensor states
Initialise_client_object() # add extra flags
logging.info("creating client"+cname)
client=Initialise_clients(cname)#create and initialise client object
if options["username"] !="":
client.username_pw_set(options["username"],options["password"])
client.will_set(connected_topic,0, qos=0, retain=True) #set will
print("Starting")
print("Publishing on ",sensor_status_topic)
print("Send control to ",topic_control)
print("Sensors States are ",states)
start_flag=True #used to always publish when starting
run_flag=True
bad_conn_count=0
try:
while run_flag:
client.loop(0.05)
if not client.connected_flag:
if Connect(client,options["broker"],options["port"],\
options["keepalive"],run_forever=True) !=-1:
if not wait_for(client,"CONNACK"):
run_flag=False #break
else:
run_flag=False #break
#subbscribes to control in on_connect calback
if client.connected_flag:
publish_status(client)
except KeyboardInterrupt:
print("interrrupted by keyboard")
if client.connected_flag:
client.publish(connected_topic,0,retain=True)
time.sleep(1)
client.disconnect()