-
Notifications
You must be signed in to change notification settings - Fork 1
/
mqtt_publisher.py
209 lines (190 loc) · 7.6 KB
/
mqtt_publisher.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import paho.mqtt.publish as publish
import RPi.GPIO as GPIO
import Adafruit_DHT
import argparse
import threading
import time
import datetime
import pw
import sys
MQTT_SERVER = "192.168.178.67"
mydb = pw.login
mycursor = mydb.cursor()
DHTSensor = Adafruit_DHT.DHT11
GPIO.setmode(GPIO.BCM)
channel = 21
GPIO.setup(channel, GPIO.IN)
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO_Pin = 23
stopthread = 0
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--debug", help="Toggle debug output and additional commands", action="store_true")
args = parser.parse_args()
debug = args.debug
################### Welcome Message ###################
print("-----------------------------------------------------------------")
print(" Publisher program started ")
print("-----------------------------------------------------------------")
print("")
################################################
try:
mycursor.execute("SELECT * FROM settings")
records = mycursor.fetchall()
for row in records:
# print("Id = ", row[0], )
print("Name: ", row[1])
print("setHumidity: ", row[5])
print("setTemperature: ", row[6])
print("LightFrom: ", row[3])
print("LightTo: ", row[4], "\n")
setHumidity = row[5]
setTemperature = row[6]
LightFrom = row[3]
LightTo = row[4]
print("Current time: " + datetime.datetime.now().strftime('%H:%M:%S'))
except Error as e:
print ("Error while connecting to MySQL", e)
finally:
#closing database connection.
if(mydb.is_connected()):
mycursor.close()
print("MySQL connection is closed")
################################################
print("|------------|------------------------|-----------|")
def push():
try:
global stopthread
date = datetime.datetime.now().strftime('%d.%m.%Y')
timeNow = datetime.datetime.now().strftime('%H:%M:%S')
Humidity, Temperature = Adafruit_DHT.read_retry(DHTSensor, GPIO_Pin)
publish.single("tmp_humidity", Humidity, hostname=MQTT_SERVER)
print("| {} | humidity sent | {}% |".format(date, Humidity))
print("|------------|------------------------|-----------|")
t1 = threading.Timer(900, push, args=[])
t1.start()
if stopthread is 1:
# _stop_event.set()
t1.cancel()
t1.join()
stopthread = 0
return
except (KeyboardInterrupt, SystemExit):
t1.join()
exit()
#cleanup_stop_thread()
sys.exit()
def push2():
try:
global stopthread
timeNow = datetime.datetime.now().strftime('%H:%M:%S')
Humidity, Temperature = Adafruit_DHT.read_retry(DHTSensor, GPIO_Pin)
publish.single("tmp_temperature", int(Temperature), hostname=MQTT_SERVER)
print("| {} | temperature sent | {}°C |".format(timeNow, Temperature))
t2 = threading.Timer(900, push2, args=[])
t2.start()
if stopthread is 1:
# _stop_event.set()
t2.cancel()
t2.join()
stopthread = 0
return
except (KeyboardInterrupt, SystemExit):
t2.join()
exit()
#cleanup_stop_thread()
sys.exit()
##Soil sensor
def callback(channel):
if GPIO.input(channel):
print("no water detected")
publish.single("tmp_soil", "no water", hostname=MQTT_SERVER)
print("message sent")
else:
publish.single("tmp_soil", "water", hostname=MQTT_SERVER)
print("water detected")
GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300)
GPIO.add_event_callback(channel, callback)
##Water sensor
def button_callback(channel1):
print("Button pressed!")
GPIO.add_event_detect(10, GPIO.RISING)
GPIO.add_event_callback(10, button_callback)
push()
print(">>> {} Setting up initial time delay".format(datetime.datetime.now().strftime('%H:%M:%S')))
time.sleep(15) #450
print(">>> Done")
print("|------------|------------------------|-----------|")
push2()
while True:
try:
global stopthread
command = input()
print("Input: "+ " " + command)
if command == "force measure":
print("")
print("|------------|------------------------|-----------|")
date = datetime.datetime.now().strftime('%d.%m.%Y')
timeNow = datetime.datetime.now().strftime('%H:%M:%S')
Humidity, Temperature = Adafruit_DHT.read_retry(DHTSensor, GPIO_Pin)
publish.single("tmp_humidity", Humidity, hostname=MQTT_SERVER)
print("| {} | humidity sent | {}% |".format(date, Humidity))
time.sleep(1)
publish.single("tmp_temperature", int(Temperature), hostname=MQTT_SERVER)
print("| {} | temperature sent | {}°C |".format(timeNow, Temperature))
print("|------------|------------------------|-----------|")
elif command == "fanspeed":
fan_speed = input("Fanspeed:")
try:
fan_speed = int(fan_speed) #Make sure input is a number
if fan_speed: #Check if user gave input or just hit enter to skip
print("Fanspeed: " + str(fan_speed))
publish.single("fan_speed", fan_speed, hostname=MQTT_SERVER)
except ValueError:
if fan_speed:
print("Input has to be a number")
#print("|------------|------------------------|-----------|")
elif command == "light on":
publish.single("msg_light", "on", hostname=MQTT_SERVER)
print("Turning on light...")
elif command == "light off":
publish.single("msg_light", "off", hostname=MQTT_SERVER)
print("Turning off light...")
elif command == "simulate temperature" and debug: #Only allow command if script is started in debugmode
sim_temperature = input("Temperature:")
try:
sim_temperature = int(sim_temperature) #Make sure input is a number
if sim_temperature: #Check if user gave input or just hit enter to skip
print("Simulating Temperature: {}°C".format(sim_temperature))
publish.single("tmp_temperature", sim_temperature, hostname=MQTT_SERVER)
except ValueError:
if sim_temperature:
print("Input has to be a number")
elif command == "simulate humidity" and debug: #Only allow command if script is started in debugmode
sim_humidity = input("Humidity:")
try:
sim_humidity = int(sim_humidity) #Make sure input is a number
if sim_humidity: #Check if user gave input or just hit enter to skip
print("Simulating Humidity: {}%".format(sim_humidity))
publish.single("tmp_humidity", sim_humidity, hostname=MQTT_SERVER)
except ValueError:
if sim_humidity:
print("Input has to be a number")
elif command == "help":
print("Available commands:")
print(" >fanspeed")
print(" >force measure")
print(" >light on")
print(" >light off")
if debug:
print(" >simulate temperature")
print(" >simulate humidty")
print(" >exit")
elif command == "exit":
#sys.exit()
stopthread = 1
cleanup_stop_thread()
raise SystemExit(0)
except:
exit()