-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspaceopen-detector
executable file
·68 lines (55 loc) · 1.74 KB
/
spaceopen-detector
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
#!/usr/bin/env python
import paho.mqtt.client
import mqtt_config
import time
import RPi.GPIO as gpio
TOPIC = "somakeit/space/open"
POLL_TIME = 0.05 #seconds
IO_SWITCH = 11
IO_LED = 13
space_open = False
mqtt = paho.mqtt.client.Client(client_id=mqtt_config.client_id, clean_session=True)
mqtt.tls_set(("/etc/ssl/certs/ca-certificates.crt"))
mqtt.username_pw_set(mqtt_config.user_name, mqtt_config.password)
mqtt.will_set('somakeit/space/open', payload='false', qos=1, retain=True)
mqtt.loop_start()
def on_disconnect(client, userdata, rc):
print "Reconnecting.."
mqtt.reconnect()
mqtt.on_disconnect = on_disconnect
def on_connect(client, userdate, flags, rc):
publish_openness()
print "Connected"
mqtt.on_connect = on_connect
def connect():
while True:
try:
print "Connecting to: " + mqtt_config.server + ":" + str(mqtt_config.port)
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.."
connect()
gpio.setmode(gpio.BOARD)
gpio.setup(IO_SWITCH, gpio.IN, pull_up_down=gpio.PUD_UP)
gpio.setup(IO_LED, gpio.OUT)
gpio.output(IO_LED, gpio.LOW)
def publish_openness():
global space_open
if gpio.input(IO_SWITCH) == 1:
gpio.output(IO_LED, gpio.LOW)
mqtt.publish(TOPIC, payload='0', qos=1, retain=True)
if space_open:
print "Space closed"
space_open = False
else:
gpio.output(IO_LED, gpio.HIGH)
mqtt.publish(TOPIC, payload='1', qos=1, retain=True)
if not space_open:
print "Space open"
space_open = True
while True:
time.sleep(POLL_TIME)
publish_openness()