-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGartenwasserGPIO.py
executable file
·119 lines (96 loc) · 2.67 KB
/
GartenwasserGPIO.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
#!/usr/bin/env python
__author__ = "Bernd Gewehr"
# import python libraries
import signal
import time
import sys
import RPi.GPIO as GPIO
# import libraries
import lib_mqtt as MQTT
DEBUG = False
#DEBUG = True
print 'GPIO daemon starting'
MQTT_TOPIC_IN = "/Gartenwasser/#"
MQTT_TOPIC = "/Gartenwasser"
MQTT_QOS = 0
MONITOR_REFRESH = "/Gartenwasser/refresh"
GPIO_OUTPUT_PINS = []
MONITOR_PINS = []
# Convert the list of strings to a list of ints.
# Also strips any whitespace padding
PINS = []
if MONITOR_PINS:
PINS = map(int, MONITOR_PINS.split(","))
# Append a column to the list of PINS. This will be used to store state.
for PIN in PINS:
PINS[PINS.index(PIN)] = [PIN, -1]
def on_message(mosq, obj, msg):
"""
Handle incoming messages
"""
if msg.topic == MONITOR_REFRESH:
refresh()
return
topicparts = msg.topic.split("/")
pin = int(topicparts[len(topicparts) - 1])
try:
value = int(float(msg.payload))
except ValueError:
value = 0
if pin not in GPIO_OUTPUT_PINS:
GPIO.setup(pin, GPIO.OUT, initial=GPIO.HIGH)
GPIO_OUTPUT_PINS.append(pin)
if topicparts[2] == 'in':
if value == 1:
GPIO.output(pin, GPIO.LOW)
else:
GPIO.output(pin, GPIO.HIGH)
# End of MQTT callbacks
def cleanup(signum, frame):
"""
Signal handler to ensure we disconnect cleanly
in the event of a SIGTERM or SIGINT.
"""
# Cleanup modules
MQTT.cleanup()
GPIO.cleanup()
# Exit from application
print "GPIO daemon stopped"
sys.exit(signum)
def init_gpio():
"""
Initialise the GPIO library
"""
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
for PIN in PINS:
index = [y[0] for y in PINS].index(PIN[0])
pin = PINS[index][0]
GPIO.setup(pin, GPIO.IN)
def loop():
"""
The main loop in which we mow the lawn.
"""
print 'GPIO daemon started'
while True:
for PIN in PINS:
index = [y[0] for y in PINS].index(PIN[0])
pin = PINS[index][0]
oldstate = PINS[index][1]
newstate = GPIO.input(pin)
if newstate != oldstate:
mqttc.publish(MQTT_TOPIC_OUT % pin, payload=newstate, qos=MQTT_QOS, retain=MQTT_RETAIN)
PINS[index][1] = newstate
time.sleep(.8)
# Use the signal module to handle signals
for sig in [signal.SIGTERM, signal.SIGINT, signal.SIGHUP, signal.SIGQUIT]:
signal.signal(sig, cleanup)
# Initialise our libraries
MQTT.init()
print 'MQTT initiated'
MQTT.mqttc.on_message = on_message
MQTT.mqttc.subscribe(MQTT_TOPIC_IN, qos=MQTT_QOS)
init_gpio()
print 'GPIO initiated'
# start main procedure
loop()