-
Notifications
You must be signed in to change notification settings - Fork 0
/
growpi.py
226 lines (179 loc) · 6.45 KB
/
growpi.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
import csv
import math
import os
import picamera
import time
import secrets
from ftplib import FTP
from grovepi import *
from grove_rgb_lcd import *
# Connect the Grove Moisture Sensor to analog port A0, Light Sensor to A1, Display to IC2
# Connect Waterpump to D2, Red Led to D3, Temp Sensor to D4, UltrasonicRanger to D6
# Sensors
moistureSensor = 0
lightSensor = 1
waterPump = 2
ledRed = 3
tempSensor = 4
distanceSensor = 6
# Heights
potHeight = 12
sensorHeight = 73
displayInterval = 1 * 60 # How long should the display stay on?
checkInterval = 10 * 60 # How long before loop starts again?
lightThreshold = 10 # Value above threshold is lightsOn
dryIntervals = 5 # How many consecutive dry intervals before waterPlants
mlSecond = 5 # How much ml water the waterpump produces per second
waterAmount = 50 # How much ml water should be given to the plants
localImagePath = '/home/pi/Desktop/images/' # Where the images are stored
# Write data to csv
def appendCSV():
fields = ['Time', 'Temperature', 'Humidity', 'Moisture', 'MoistureClass',
'LightValue', 'Lights', 'PiTemperature', 'Height', 'SonicDistance', 'Image', 'WaterGiven']
with open(r'temp.csv', 'a') as f:
writer = csv.DictWriter(f, fieldnames=fields)
writer.writerow({'Time': currentTime,
'Temperature': temp,
'Humidity': humidity,
'Moisture': moisture,
'MoistureClass': moistureClass,
'LightValue': lightValue,
'Lights': lightsOn,
'PiTemperature': (piTemperature()),
'Height': (calcPlantHeight()),
'SonicDistance': ultraSonicDistance,
'Image': image,
'WaterGiven': waterGiven
})
def calcPlantHeight():
return sensorHeight - potHeight - ultraSonicDistance
def displayText():
setRGB(0, 128, 64) # background color led display
setText("{}C {}% {}\n{} ({}) {}".format(temp, humidity,
piTemperature(), moisture, moistureClass, lightValue))
time.sleep(displayInterval)
setText("")
setRGB(0, 0, 0)
def piTemperature():
temp = os.popen("vcgencmd measure_temp").readline()
return temp[5:9]
def moistureClassifier():
if moisture < 300:
moistureResult = 'Dry'
elif moisture < 600:
moistureResult = 'Moist'
else:
moistureResult = 'Wet'
return moistureResult
def printSensorData():
print(currentTime)
if math.isnan(temp) == False and math.isnan(humidity) == False:
print("Temperature: {}'C\nHumidity: {}%".format(temp, humidity))
else:
print("Couldn't get temperature/humidity sensor readings")
print('Moisture: {0} ({1})'.format(moisture, moistureClass))
print("Lights: {} ({})".format(lightValue, "On" if lightsOn else "Off"))
print("Height: {} cm".format(calcPlantHeight()))
print("Raspberry pi: {}'C".format(piTemperature()))
if waterGiven:
print("Water given: {}ml".format(waterGiven))
if lightsOn:
print("Image: {}\n".format(image))
else:
print("")
# Calculates time to next tenth minute and sleeps
def sleepTimer():
currentMinute = time.strftime("%M")
currentSecond = time.strftime("%S")
sleeptime = (10 - int(currentMinute[1])) * 60 - int(currentSecond)
time.sleep(sleeptime)
def takePicture():
timestamp = time.strftime("%Y-%m-%d--%H-%M")
image = '{}.jpg'.format(timestamp)
imagePath = localImagePath + image
with picamera.PiCamera() as camera:
camera.start_preview()
camera.awb_mode = 'sunlight'
time.sleep(5)
camera.capture(imagePath)
camera.stop_preview()
return image
def uploadCSV():
ftp = FTP(secrets.FTP_URL)
ftp.login(user=secrets.USERNAME, passwd=secrets.PASSWORD)
filename = 'temp.csv'
ftp.storbinary('STOR ' + filename, open(filename, 'rb'))
ftp.quit()
def uploadImage():
if image:
ftp = FTP(secrets.FTP_URL)
ftp.login(user=secrets.USERNAME, passwd=secrets.PASSWORD)
ftp.cwd('/images/')
filename = localImagePath + image
ftp.storbinary('STOR ' + image, open(filename, 'rb'))
ftp.quit()
def waterPlants():
digitalWrite(waterPump, 1)
time.sleep(waterAmount / mlSecond)
digitalWrite(waterPump, 0)
# Main Loop
waterCheck = []
while True:
try:
# Start loop at every tenth minute of the hour
sleepTimer()
# Get sensor readings
lightValue = analogRead(lightSensor)
ultraSonicDistance = ultrasonicRead(distanceSensor)
moisture = analogRead(moistureSensor)
[temp, humidity] = dht(tempSensor, 1)
currentTime = time.ctime()
moistureClass = moistureClassifier()
lightsOn = lightValue > lightThreshold
# Lights on
if lightsOn:
# Turn on red LED when ground is dry, when lightsOn
if moistureClass == 'Dry':
digitalWrite(ledRed, 1)
waterCheck.append(moisture)
# Get x consecutive dryIntervals, before waterPlants
if len(waterCheck) >= dryIntervals:
waterPlants()
waterGiven = waterAmount
waterCheck = []
else:
waterGiven = 0
# Ground not dry
else:
waterCheck = []
waterGiven = 0
digitalWrite(ledRed, 0)
# Take picture every loop, while lightsOn, store path in image variable
image = takePicture()
# PrintSensorData and appendCSV, before displayText
printSensorData()
appendCSV()
uploadImage()
uploadCSV()
# Textdisplay when lightsOn
displayText()
# Lights off
else:
waterCheck = []
waterGiven = 0
# In case ground was dry, when lightsOn
digitalWrite(ledRed, 0)
# No picture when lights off, empty string for appendCSV
image = ''
printSensorData()
appendCSV()
uploadCSV()
except KeyboardInterrupt:
digitalWrite(waterPump, 0)
digitalWrite(ledRed, 0)
setText("")
setRGB(0, 0, 0)
print(" Leds and RGB shutdown safely")
break
except IOError:
print("Error")