· 6 years ago · Feb 19, 2020, 06:00 AM
1import RPi.GPIO as GPIO
2import time
3from time import sleep
4import pigpio #library that used for waterflow
5from urllib.request import urlopen #library that used for connection
6import sys
7
8#libraries for sending mail
9import smtplib
10from email.mime.multipart import MIMEMultipart
11from email.mime.text import MIMEText
12from email.mime.base import MIMEBase
13
14location = 2 #location of drain
15
16fromaddr = "asmathesispurpose@gmail.com" #sender mail
17toaddr = "asmachycu15@gmail.com" #receiver mail
18
19mail = MIMEMultipart()
20
21mail['From'] = fromaddr
22mail['To'] = toaddr
23mail['Subject'] = "Alert"
24body = "Water-logging found at Point:"+str(location)
25
26sum_flow = 0 #used for average flow calculation
27sum_dist = 0 #used for average distance calculation
28
29avg_flow = 0
30avg_dist = 0
31
32waterflow = 0
33distance = 0
34
35data = "Water-logging found"
36
37flowGpio = 4 #set GPIO pin numbering for flow sensor
38
39#upload
40import http.client, urllib
41
42#write api key Thingspeak channel to update
43key = 'YJ6FQCDAJSXWUFMJ'
44BASE_URL = "https://api.thingspeak.com/update?api_key={}".format(key)
45thingspeakPrevSec = 0
46thingspeakInterval = 5
47
48
49#ultrasonic sensor
50GPIO.setmode(GPIO.BCM) #Set GPIO pin numbering for ultrasonic sensor
51TRIG = 23 #Associate pin 23 to TRIG
52ECHO = 24 #Associate pin 24 to ECHO
53
54intervalTime = 1 # in seconds
55old_count = 0
56
57print ("Distance and WaterFlow measurement in progress")
58
59GPIO.setup(TRIG,GPIO.OUT) #Set pin as GPIO out
60GPIO.setup(ECHO,GPIO.IN) #Set pin as GPIO in
61
62datacount = 0
63falsedata = 0
64
65timecountdist = 0
66timecountflow = 0
67
68def sendMail(data): #method for sending mail
69 mail.attach(MIMEText(body, 'plain'))
70 print (data)
71 #connecting with SMTP server
72 server = smtplib.SMTP('smtp.gmail.com', 587)
73 server.ehlo()
74 server.starttls()
75 server.login(fromaddr, "43asma43")
76 text = mail.as_string()
77 server.sendmail(fromaddr, toaddr, text)
78 server.close()
79
80###################
81 #method for uploading data on website
82def uploadAvgMeanValue(waterflow, distance, avg_flow, avg_dist):
83 #the url
84 thingspeakHttp=BASE_URL+ "&field1={:d}/s&field2={:.2f}cm&field3={:.2f}/s&field4={:.2f}cm".format(waterflow, distance, avg_flow, avg_dist)
85 print (thingspeakHttp)
86 try:
87 conn = urlopen(thingspeakHttp) #connect to the url address
88 print("Response: {}".format(conn.read()))
89 conn.close()
90 except: #if the connection failed
91 print ("connection failed")
92
93##########
94
95#calculation of the average values of 25 second before starting the continuous process
96while timecountdist <= 5 and timecountflow <= 5 :
97 #Starting of the flow measurement
98 pi = pigpio.pi()
99 old_count = 0
100 pi.set_mode(flowGpio, pigpio.INPUT)
101 pi.set_pull_up_down(flowGpio, pigpio.PUD_DOWN)
102
103 flowCallback = pi.callback(flowGpio, pigpio.FALLING_EDGE)
104 time.sleep(intervalTime)
105
106 count = flowCallback.tally()
107 waterflow = (count - old_count)
108 print(waterflow)
109 old_count = count
110 #End of the flow measurement
111
112 #starting of the water-level measurement
113 GPIO.output(TRIG, False) #Set TRIG as LOW
114 print ("Waitng For Sensor To Settle")
115 time.sleep(2) #Delay of 2 seconds
116
117 GPIO.output(TRIG, True) #Set TRIG as HIGH
118 time.sleep(0.00001) #Delay of 0.0001 seconds
119 GPIO.output(TRIG, False) #Set TRIG as LOW
120
121 while GPIO.input(ECHO)==0: #Check whether the ECHO is LOW
122 pulse_start = time.time() #Saves the last known time of LOW pulse
123
124 while GPIO.input(ECHO)==1: #Check whether the ECHO is HIGH
125 pulse_end = time.time() #Saves the last known time of HIGH pulse
126
127 pulse_duration = pulse_end - pulse_start #Get pulse duration to a variable
128 distance = pulse_duration * 17150 #Multiply pulse duration by 17150 to get distance
129 distance = round(distance, 2) #Round to two decimal points
130 distance = distance - 0.5
131 #End of the water-level measurement
132
133 datacount = datacount + 1 #Increased the number of measured data
134 if distance >= 300 or distance <= 1.2 : #The condition of false data
135 falsedata = falsedata + 1 #Increased the number of false data
136 continue #Ignoring the conditions for false data
137
138
139 timecountdist=timecountdist +1 #Counting Time to measure average distance
140 datacount = datacount + 1 #Increased the number of measured data
141 sum_dist = sum_dist + distance #Summation of water-level distance
142 print ("waterflow: ",waterflow)
143 print ("Distance: ",distance,"cm")
144
145 timecountflow=timecountflow+1 #Counting Time to measure average flow
146 sum_flow = sum_flow + waterflow #Summation of flow
147
148 if distance >= 20 : #Safe distance condition
149 print("Safe Distance from water!")
150
151 #Set warning if water level is more than half of the dept
152 elif distance >= 15 and distance < 20 :
153 print("Warning! Distance is low!")
154
155 #Set alert if the water level is more than the 1/5 of the depth
156 elif distance < 15 :
157 print ("Danger! Danger! Sending mail...")
158
159 #sending mail
160 try:
161 data = "Water-logging found"
162 body = "Water-logging found at Point:"+str(location)
163 sendMail(data) #Calling method for sending mail
164
165 #if connection failed
166 except:
167 print("Check Internet connection")
168
169#Calculating the average water-level distance and waterflow
170avg_dist = sum_dist/5
171avg_flow = sum_flow/5
172sum_dist = 0
173sum_flow = 0
174
175#Loop for the continues process of measuring data and so on
176while True:
177 try:
178 #Starting flow measurement
179 pi = pigpio.pi()
180 old_count = 0
181 pi.set_mode(flowGpio, pigpio.INPUT)
182 pi.set_pull_up_down(flowGpio, pigpio.PUD_DOWN)
183
184 flowCallback = pi.callback(flowGpio, pigpio.FALLING_EDGE)
185 time.sleep(intervalTime)
186
187 count = flowCallback.tally()
188 waterflow = (count - old_count)
189 old_count = count
190 #Ending of flow measurement
191 ###############
192
193 #Starting of water-level distance measurement
194 GPIO.output(TRIG, False) #Set TRIG as LOW
195 print ("Waitng For Sensor To Settle")
196 time.sleep(2) #Delay of 2 seconds
197
198 GPIO.output(TRIG, True) #Set TRIG as HIGH
199 time.sleep(0.00001) #Delay of 0.0001 seconds
200 GPIO.output(TRIG, False) #Set TRIG as LOW
201
202 while GPIO.input(ECHO)==0: #Check whether the ECHO is LOW
203 pulse_start = time.time() #Saves the last known time of LOW pulse
204
205 while GPIO.input(ECHO)==1: #Check whether the ECHO is HIGH
206 pulse_end = time.time() #Saves the last known time of HIGH pulse
207
208 pulse_duration = pulse_end - pulse_start #Get pulse duration to a variable
209 distance = pulse_duration * 17150 #Multiply pulse duration by 17150 to get distance
210 distance = round(distance, 2) #Round to two decimal points
211 distance = distance - 0.5
212 #Ending of water-level distance measurement
213 ####################
214
215 datacount = datacount + 1 #Increased the number of measured data
216
217 #The condition of false data
218 if avg_dist - distance > 200 or distance - avg_dist > 200 or distance >= 300:
219 falsedata = falsedata + 1 #Increased the number of false data
220 continue #Ignoring the conditions for false data
221
222 datacount = datacount + 1 #Increased the number of measured data
223 timecountdist=timecountdist+1 #Counting Time to measure average distance
224 timecountflow=timecountflow+1 #Counting Time to measure average flow
225
226 sum_dist = sum_dist + distance #Summation of water-level distance
227 sum_flow = sum_flow + waterflow #Summation of flow
228
229
230 print ("waterflow: ",waterflow)
231 print ("Distance: ",distance,"cm")
232
233 #Detection of Blockage comparing average values
234 if avg_flow - waterflow >= 10 and avg_dist - distance >= 5 :
235 print ("Warning! Warning! Blockage is detected!")
236 print("Blockage is found between location ",location-1," and location ",location,"!")
237
238
239 if distance >= 20 : #Safe water-level condition
240 print("Safe Distance from water!")
241
242 #Set warning if water level is more than half of the dept
243 elif distance >= 15 and distance < 20 :
244 print("Warning! Distance is low!")
245
246 #Set alert if the water level is more than the 1/5 of the depth
247 elif distance < 15 :
248 print ("Danger! Danger! Sending mail...")
249 try: #Sending mail
250 body = "Water-logging found at Point:"+str(location)
251 sendMail(data) #Calling method for sending mail
252 except: #if connection falied
253 print("Check Internet connection")
254
255
256 #Calculating average water-level distance
257 if timecountdist == 5 :
258 avg_dist = sum_dist/5
259 sum_dist = 0
260 print("Average Distance is: ",avg_dist)
261
262 #Calculating average waterflow
263 if timecountflow == 5 :
264 avg_flow= sum_flow/5
265 sum_flow = 0
266 print("Average water flow is: ", avg_flow)
267
268 #Uploading data to the IoT cloud
269 uploadAvgMeanValue(waterflow, distance, avg_flow, avg_dist)
270
271 except KeyboardInterrupt: #If keyboard Interrupt occured
272
273 print ('\ncaught keyboard interrupt!')
274
275 #Measuring the accuracy of the system
276 accuracy = ( (datacount - falsedata) * 100) / datacount
277 accuracy = round(accuracy, 2)
278 print("Measurement Accuracy: ", accuracy, "% .")
279 GPIO.cleanup()
280 sys.exit()