Advertisement
Guest User

growPi

a guest
Jan 15th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.09 KB | None | 0 0
  1. import time
  2. import board
  3. import busio
  4. #Add Temperature/Humidity sensor driver
  5. import adafruit_sht31d
  6. from decimal import *
  7. #Add ability to run external commands and retrieve output
  8. from subprocess import check_output
  9. import datetime as dt
  10. import urllib.request
  11. import logging
  12. import configparser
  13. import sys
  14. import math
  15. import os
  16. from influxdb import InfluxDBClient
  17.  
  18. #global loopcount, humidifierstatusm heaterstatus, fanstatus, templow, temphigh, humlow, humhigh, heateroncycles, heateroffcycles, fanoncycles, fanoffcycles, humidifieroncycles humidifieroffcycles, lastpictime, i2c, sensor, logger, handler, formatter, coldprotecttemp, coldprotecttriggered, client
  19.  
  20. #Set up logging
  21. logger = logging.getLogger()
  22. handler = logging.FileHandler('/home/pi/Desktop/growPi.log', 'a+')
  23. formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
  24. handler.setFormatter(formatter)
  25. logger.addHandler(handler)
  26. logger.setLevel(logging.DEBUG)
  27. logger.debug("Script started.")
  28. # Create library object using our Bus I2C port
  29. try:
  30. i2c = busio.I2C(board.SCL, board.SDA)
  31. except Exception as e:
  32. logger.debug("Could not get i2c bus: "+str(e))
  33. #Connect to sensor
  34. try:
  35. sensor = adafruit_sht31d.SHT31D(i2c)
  36. except Exception as e:
  37. logger.debug("Could not get SHT31-D Temp/Humidity sensor: "+str(e))
  38.  
  39. # Configure InfluxDB connection variables
  40. host = "10.0.0.13" # My Ubuntu NUC
  41. port = 8086 # default port
  42. user = "rpi-3" # the user/password created for the pi, with write access
  43. password = "data@LOG"
  44. dbname = "sensor_data" # the database we created earlier
  45. # Create the InfluxDB client object
  46. client = InfluxDBClient(host, port, user, password, dbname)
  47. loopcount = 0
  48. fanoncycles = 0
  49. fanoffcycles = 0
  50. humidifieroncycles = 0
  51. humidifieroffcycles = 0
  52. heateroncycles = 0
  53. heateroffcycles = 0
  54. humidifierstatus = "not set"
  55. fanstatus = "not set"
  56. heaterstatus = "not set"
  57. coldprotecttriggered = 0
  58. starthr = 8 # before midnight
  59. startmin = 1
  60. stophr = 16 # after midnight
  61. stopmin = 1
  62. piccount = 0
  63. #Initialize last picture time to one hour before the script started, so it always takes a picture off the start
  64. #lastpictime = dt.datetime.now() - dt.timedelta(hours=1)
  65. lastpictime = dt.datetime.now()
  66. picfoldername = dt.datetime.now().strftime("%Y-%m-%d_%H:%M:%S")
  67. vpdset = 9.0 #set default value
  68. nightvpdset = 7.5 #set default value
  69.  
  70. def makepicdir(folder):
  71. try:
  72. os.makedirs("/home/pi/Pictures/"+folder)
  73. except Exception as e:
  74. logger.debug("Could not create picture folder: "+str(e))
  75.  
  76. def shipEnviroData(grafTemp, grafHum, grafvpd):
  77. global sensortype
  78. iso = time.ctime()
  79. # Create the JSON data structure
  80. enviroData = [
  81. {
  82. "measurement": "rpi-sht-31d",
  83. "tags": {
  84. "sensortype": "environmental",
  85. },
  86. "time": iso,
  87. "fields": {
  88. "temperature" : grafTemp,
  89. "humidity": grafHum,
  90. "vpd": grafvpd
  91. }
  92. }
  93. ]
  94. try:
  95. client.write_points(enviroData, time_precision='ms')
  96. except Exception as e:
  97. logger.debug("Cannot ship data to grafana: "+str(e))
  98.  
  99. #Read config
  100. def readconfig():
  101. global lastpictime, nighttemphigh, nighttemplow, nighthumhigh, nighthumlow, temphigh, templow, humhigh, humlow, coldprotecttemp, sleeptime, vpdset, nightvpdset
  102. try:
  103. config = configparser.ConfigParser()
  104. config.read('config.ini')
  105. temphigh = Decimal(config['DEFAULT']['HIGHTEMP']) #28.0
  106. templow = Decimal(config['DEFAULT']['LOWTEMP']) #25.0
  107. humhigh = Decimal(config['DEFAULT']['HIGHHUM']) #40.0
  108. humlow = Decimal(config['DEFAULT']['LOWHUM']) #30.0
  109. nighttemphigh = Decimal(config['DEFAULT']['NIGHTHIGHTEMP']) #28.0
  110. nighttemplow = Decimal(config['DEFAULT']['NIGHTLOWTEMP']) #25.0
  111. nighthumhigh = Decimal(config['DEFAULT']['NIGHTHIGHHUM']) #40.0
  112. nighthumlow = Decimal(config['DEFAULT']['NIGHTLOWHUM']) #30.0
  113. sleeptime = Decimal(config['DEFAULT']['SLEEPTIME']) #1
  114. coldprotecttemp = Decimal(config['DEFAULT']['COLDPROTECTTEMP']) #15.0
  115. honcount = Decimal(config['DEFAULT']['HONCOUNT'])
  116. hoffcount = Decimal(config['DEFAULT']['HOFFCOUNT'])
  117. humoncount = Decimal(config['DEFAULT']['HUMONCOUNT'])
  118. humoffcount = Decimal(config['DEFAULT']['HUMOFFCOUNT'])
  119. fanoncount = Decimal(config['DEFAULT']['FANONCOUNT'])
  120. fanoffcount = Decimal(config['DEFAULT']['FANOFFCOUNT'])
  121. vpdset = Decimal(config['DEFAULT']['VPD'])
  122. nightvpdset = Decimal(config['DEFAULT']['NIGHTVPD'])
  123. except Exception as e:
  124. logger.debug("Could not read configuration: "+str(e))
  125. exit()
  126.  
  127. def calcVPD():
  128. global temp, humidity, vpd
  129. try:
  130. ftemp=float(temp)
  131. fhumidity=float(humidity)
  132. VPsat = 6.11*(10**((7.5 * ftemp) / (237.3 + ftemp)))# Saturation vapor pressure
  133. vpd = ((100.0 - fhumidity) /100.0)/10 * VPsat # Vapor Pressure Deficit in Pascals
  134. logger.debug("VPD: "+str(round(Decimal(vpd),2)))
  135. return vpd
  136. except Exception as e:
  137. logger.debug("Could not calculate VPD: "+str(e))
  138.  
  139. def takepic():
  140. if when == True:
  141. #Day
  142. global lastpictime, piccount, picfoldername
  143. split = dt.datetime.now() - lastpictime
  144. #Take a picture if 5 minutes have passed
  145. if (split.total_seconds() > 298) or (piccount == 0):
  146. try:
  147. urllib.request.urlretrieve("http://192.168.0.90/axis-cgi/jpg/image.cgi?resolution=1280x720", "/home/pi/Pictures/"+picfoldername+"/"+str(piccount)+".jpg")
  148. lastpictime = dt.datetime.now()
  149. piccount += 1
  150. logger.debug("Image saved")
  151. except Exception as e:
  152. logger.debug("Could not take picture: "+str(e))
  153.  
  154. def fanon():
  155. global fanoncycles
  156. try:
  157. check = check_output("python /usr/local/bin/wemo switch fan on",shell=True)
  158. fanoncycles += 1
  159. logger.debug("Fan turned on. Count: "+str(fanoncycles))
  160. except Exception as e:
  161. logger.debug("Could not turn on fan: "+str(e))
  162.  
  163. def humidifieron():
  164. global humidifieroncycles
  165. try:
  166. check = check_output("python /usr/local/bin/wemo switch humidifier on",shell=True)
  167. humidifieroncycles += 1
  168. logger.debug("Humidifier turned on. Count: "+str(humidifieroffcycles))
  169. except Exception as e:
  170. logger.debug("Could not turn humidifier on: "+str(e))
  171.  
  172. def fanoff():
  173. global fanoffcycles
  174. try:
  175. check = check_output("python /usr/local/bin/wemo switch fan off",shell=True)
  176. fanoffcycles += 1
  177. logger.debug("Fan turned off. Count: "+str(fanoffcycles))
  178. except Exception as e:
  179. logger.debug("Could not turn fan off: "+str(e))
  180.  
  181. def humidifieroff():
  182. global humidifieroffcycles
  183. try:
  184. check_output("python /usr/local/bin/wemo switch humidifier off",shell=True)
  185. humidifieroffcycles += 1
  186. logger.debug("Humidifier turned off. Count: "+str(humidifieroffcycles))
  187. except Exception as e:
  188. logger.debug("Could not turn humidifier off: "+str(e))
  189.  
  190. def heateron():
  191. global heateroncycles
  192. try:
  193. check_output("python /usr/local/bin/wemo switch 'heater bud 1' on",shell=True)
  194. heateroncycles += 1
  195. logger.debug("Heater turned on. Count: "+str(heateroncycles))
  196. except Exception as e:
  197. logger.debug("Could not turn heater on: "+str(e))
  198.  
  199. def heateroff():
  200. global heateroffcycles
  201. try:
  202. check_output("python /usr/local/bin/wemo switch 'heater bud 1' off",shell=True)
  203. heateroffcycles += 1
  204. logger.debug("Heater turned off. Count: "+str(heateroffcycles))
  205. except Exception as e:
  206. logger.debug("Could not turn heater off: "+str(e))
  207.  
  208. def gettemp():
  209. #Get current temperature
  210. try:
  211. temp = round(sensor.temperature,1)
  212. return round(Decimal(temp),2)
  213. except Exception as e:
  214. logger.debug("Could not get temperature: "+str(e))
  215.  
  216. def gethum():
  217. #Get current humidity
  218. try:
  219. humidity = round(sensor.relative_humidity,1)
  220. return round(Decimal(humidity),2)
  221. except Exception as e:
  222. logger.debug("Could not get humidity: "+str(e))
  223.  
  224. def checkfan():
  225. try:
  226. check = check_output("python /usr/local/bin/wemo -v switch fan status",shell=True)
  227. return str(check)
  228. except Exception as e:
  229. logger.debug("Could not get fan status: "+str(e))
  230.  
  231. def checkhumidifier():
  232. try:
  233. check = check_output("python /usr/local/bin/wemo -v switch humidifier status",shell=True)
  234. return str(check)
  235. except Exception as e:
  236. logger.debug("Could not get humidifier status: "+str(e))
  237.  
  238. def checkheater():
  239. try:
  240. check = check_output("python /usr/local/bin/wemo -v switch 'heater bud 1' status",shell=True)
  241. return str(check)
  242. except Exception as e:
  243. logger.debug("Could not get heater status: "+str(e))
  244.  
  245. def fixvpd():
  246. global vpd, when, vpdset, nightvpdset
  247. #day
  248. if when == True:
  249. if vpd < vpdset:
  250. if "on" in humidifierstatus:
  251. logger.debug("VPD is below target, turning humidifier off.")
  252. humidifieroff()
  253. elif vpd > vpdset:
  254. if "off" in humidifierstatus:
  255. logger.debug("VPD is above target, turning humidifier on.")
  256. humidifieron()
  257. #night
  258. elif when == False:
  259. if vpd < nightvpdset:
  260. if "on" in humidifierstatus:
  261. logger.debug("VPD is below target, turning humidifier off.")
  262. humidifieroff()
  263. elif vpd > nightvpdset:
  264. if "off" in humidifierstatus:
  265. logger.debug("VPD is above target, turning humidifier on.")
  266. humidifieron()
  267.  
  268.  
  269. def fixtemp():
  270. global temp, temphigh, nighttemphigh, fanstatus, fanoncycles, templow, nighttemplow, fanoffcycles, coldprotecttriggered, coldprotecttemp, when, heaterstatus
  271. if temp <= coldprotecttemp:
  272. try:
  273. if "off" in heaterstatus:
  274. logger.debug("Temperature has fallen below Cold Protect temperature of "+str(coldprotecttemp)+", turning heater on.")
  275. heateron()
  276. coldprotecttriggered = 1
  277. return
  278. except Exception as e:
  279. logger.debug("Could not turn on heater for cold protection: "+str(e))
  280. if when == False:
  281. #Night
  282. logger.debug("Night temp adjustment:")
  283. if temp >= (nighttemphigh):
  284. if "on" in heaterstatus:
  285. logger.debug("Temperature is "+str(temp)+", turning heater off.")
  286. heateroff()
  287. elif "off" in heaterstatus:
  288. logger.debug("Temp is above High Temp setting. Heater is off already.")
  289. else:
  290. logger.debug(type(fanstatus))
  291. logger.debug("Fan status is "+fanstatus)
  292. elif temp <= (nighttemplow):
  293. if "off" in heaterstatus:
  294. logger.debug("Temperature is "+str(temp)+", turning heater on.")
  295. heateron()
  296. elif "on" in heaterstatus:
  297. logger.debug("Temp is below Low Temp setting. Heater is on already.")
  298. else:
  299. logger.debug(type(fanstatus))
  300. logger.debug("Fan status is "+fanstatus)
  301.  
  302. if coldprotecttriggered == 1:
  303. if temp >= nighttemplow:
  304. try:
  305. if "on" in heaterstatus:
  306. logger.debug("Temperature has recovered to Low Temperature setting. Turning heater off.")
  307. heateroff()
  308. coldprotecttriggered = 0
  309. except Exception as e:
  310. logger.debug("Could not turn off heater to exit cold protection: "+str(e))
  311.  
  312. elif when == True:
  313. #Day
  314. logger.debug("Day temp adjustment:")
  315. if temp >= temphigh:
  316. if "off" in fanstatus:
  317. logger.debug("Temperature is "+str(temp)+", turning fan on.")
  318. fanon()
  319. elif "on" in fanstatus:
  320. logger.debug("Temp is above High Temp setting. Fan is on already.")
  321. else:
  322. logger.debug(type(fanstatus))
  323. logger.debug("Fan status is "+fanstatus)
  324. elif temp <= templow:
  325. if "on" in fanstatus:
  326. logger.debug("Temperature is "+str(temp)+", turning fan off.")
  327. fanoff()
  328. elif "off" in fanstatus:
  329. logger.debug("Temp is below Low Temp setting. Fan is off already.")
  330. else:
  331. logger.debug(type(fanstatus))
  332. logger.debug("Fan status is "+fanstatus)
  333. if coldprotecttriggered == 1:
  334. if temp >= templow:
  335. try:
  336. heaterstatus = checkheater()
  337. if "on" in heaterstatus:
  338. logger.debug("Temperature has recovered to Low Temperature setting. Turning heater off.")
  339. heateroff()
  340. coldprotecttriggered = 0
  341. except Exception as e:
  342. logger.debug("Could not turn off heater to exit cold protection: "+str(e))
  343.  
  344. def fixhum():
  345. global humidity, humhigh, nighthumhigh, humlow, nighthumlow, humidifierstatus, humidifieroffcycles, humidifieroncycles, when, heaterstatus, fanstatus
  346. if when == False:
  347. #Night
  348. logger.debug("Night hum adjustment:")
  349. if humidity >= nighthumhigh:
  350. if "on" in humidifierstatus:
  351. logger.debug("Humidity is "+str(humidity)+", turning humidifier off.")
  352. humidifieroff()
  353. if "off" in fanstatus:
  354. if humidity >= 60:
  355. logger.debug("Humidity is "+str(humidity)+", turning fan on.")
  356. fanon()
  357. elif "on" in fanstatus:
  358. if humidity <= nighthumhigh:
  359. logger.debug("Humidity is "+str(humidity)+", turning fan off.")
  360. fanoff()
  361.  
  362. if humidity <= nighthumlow:
  363. if "off" in humidifierstatus:
  364. logger.debug("Humidity is "+str(humidity)+", turning humidifier on.")
  365. humidifieron()
  366. if "on" in humidifierstatus:
  367. logger.debug("Humidifier is on already.")
  368. if "on" in fanstatus:
  369. logger.debug("Turning fan off.")
  370. fanoff()
  371.  
  372. elif when == True:
  373. #Day
  374. logger.debug("Day hum adjustment:")
  375. if humidity >= humhigh:
  376. if "on" in humidifierstatus:
  377. logger.debug("Humidity is "+str(humidity)+", turning humidifier off.")
  378. humidifieroff()
  379. elif "off" in humidifierstatus:
  380. logger.debug("Humidifier is off already")
  381. if humidity <= humlow:
  382. if "off" in humidifierstatus:
  383. logger.debug("Humidity is "+str(humidity)+", turning humidifier on.")
  384. humidifieron()
  385. elif "on" in humidifierstatus:
  386. logger.debug("Humidifier is on already.")
  387.  
  388. def checktime(starthour, startmin, stophour, stopmin):
  389. # Set the now time to an integer that is hours * 60 + minutes
  390. n = dt.datetime.now()
  391. now = n.hour * 60 + n.minute
  392.  
  393. # Set the start time to an integer that is hours * 60 + minutes
  394. str = dt.time(starthour, startmin)
  395. start = str.hour * 60 + str.minute
  396.  
  397. # Set the stop time to an integer that is hours * 60 + minutes
  398. stp = dt.time(stophour, stopmin)
  399. stop = stp.hour * 60 + stp.minute
  400. if n.hour >= str.hour:
  401. if n.hour < stp.hour:
  402. return False #night
  403. return True
  404. # handle midnight by adding 24 hours to stop time and now time
  405. #if stop < start:
  406. # stop += 1440
  407. # now += 1440
  408. #see if we are in the range
  409. # if start <= now > stop:
  410. # return True
  411. # return False
  412.  
  413. def pilightsoff():
  414. try:
  415. check_output("sudo sh -c 'echo 0 > /sys/class/leds/led0/brightness'",shell=True)
  416. check_output("sudo sh -c 'echo 0 > /sys/class/leds/led1/brightness'",shell=True)
  417. except Exception as e:
  418. logger.debug("Cannot disable Pi LEDs: "+str(e))
  419.  
  420.  
  421. makepicdir(picfoldername)
  422. pilightsoff()
  423. ####MAIN LOOP####
  424. while True:
  425. try:
  426. logger.debug("\r")
  427. when = checktime(starthr,startmin,stophr,stopmin)
  428. if when == False:
  429. logger.debug("Night time detected.")
  430. elif when == True:
  431. logger.debug("Day time detected.")
  432. readconfig()
  433. temp = gettemp()
  434. humidity = gethum()
  435. fanstatus = checkfan()
  436. humidifierstatus = checkhumidifier()
  437. heaterstatus = checkheater()
  438. logger.debug("Temperature: "+str(temp))
  439. logger.debug("Humidity: "+str(humidity))
  440. calcVPD()
  441. shipEnviroData(str(temp),str(humidity),str(vpd))
  442. fixtemp()
  443. fixvpd()
  444. #fixhum()
  445. takepic()
  446. loopcount += 1
  447. time.sleep(int(sleeptime))
  448. except Exception as e:
  449. logger.debug("Loop failed: "+str(e))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement