Advertisement
Guest User

Untitled

a guest
Apr 29th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.57 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. # Set up imports
  4. import RPI_ADC0832
  5. import RPi.GPIO as GPIO
  6. import Adafruit_DHT
  7. import sys
  8. import time
  9. import mysql.connector
  10. import datetime
  11. import matplotlib.pyplot as plt
  12. from numpy import array
  13.  
  14.  
  15. # Set up the Raspberry Pi GPIO pins ================
  16. GPIO.setmode(GPIO.BCM)
  17. # Light Photocell ================================
  18. GPIO.setup(4,GPIO.IN)
  19. # Humidity ================================
  20. GPIO.setup(11,GPIO.IN)
  21. # Temperature ================================
  22. GPIO.setup(18,GPIO.IN)
  23. # LED Status Light ================================
  24. GPIO.setup(26,GPIO.OUT)
  25. # DC Pump ================================
  26. GPIO.setup(23,GPIO.OUT)
  27. # Set DC Pump as "OFF"
  28. GPIO.output(23,GPIO.HIGH)
  29. # Reads DateTime info from the PlotlyDatabase.
  30.  
  31. # Analog->Digital MOISTURE SETUP ================================
  32. # Set up moisture 1 sensor
  33. adc = RPI_ADC0832.ADC0832()
  34.  
  35. adc.csPin = 17 # Default pin: 17
  36. adc.clkPin = 27 # Default pin: 27
  37. adc.doPin = 22 # Default pin: 23
  38. adc.diPin = 22 # Default pin: 24
  39.  
  40. # Create an ADC0832 instance
  41. adc2 = RPI_ADC0832.ADC0832()
  42.  
  43. adc2.csPin = 5
  44. adc2.clkPin = 6
  45. adc2.doPin = 13
  46. adc2.diPin = 13
  47. # For non-default pins, make sure to set up the CD and CLK pins as outputs
  48. GPIO.setup(adc2.csPin, GPIO.OUT, initial = GPIO.HIGH)
  49. GPIO.setup(adc2.clkPin, GPIO.OUT, initial=GPIO.LOW)
  50.  
  51.  
  52. # Function which fetches the X values of data from a database
  53. def readXData(name):
  54.     f = '%Y-%m-%d %H:%M:%S'
  55.     # Create a dictionary which will redirect according to what we need
  56.     switch = {"LastWaterX":0, "LastWaterY":1, "TempX":2, "TempY":3, "HumidityX":4, "HumidityY":5}
  57.     # If we didn't get a hit, break
  58.     index = switch.get(name, "Invalid Column")
  59.     if (index == "Invalid Column"):
  60.          return
  61.     # Set up the MYSQL connection
  62.     mydb = mysql.connector.connect(host = "localhost", user = "root", password = "tacocat", database = "PlantData")
  63.     mycursor = mydb.cursor()
  64.     # Get the data
  65.     mycursor.execute("SELECT * FROM PlotlyData")
  66.     # Get the row value
  67.     row = mycursor.fetchone()
  68.     # Create an empty list to store our values in
  69.     values = []
  70.     # Loop through all rows, compiling any row that isn't empty
  71.     while row is not None:
  72.         #print (row[index])
  73.         temp = (row[index])
  74.         temp = temp.strftime(f)
  75. #       print(temp)
  76.         values.append(temp)
  77.         row = mycursor.fetchone()
  78.     # Close the connection
  79. #   print(values)
  80.     mycursor.close()
  81.     mydb.close()
  82.     return values
  83. # Reads Int/Float values from the Plotly database.
  84. # Function that fetches the Y values from the database
  85. def readYData(name):
  86.     f = '%Y-%m-%d %H:%M:%S'
  87.     # Create a dictionary which will redirect according to what we need
  88.     switch = {"DateTime":0, "Light":1, "Humidity":2, "Temp":3, "AutoMoisture":4, "ControlMoisture":5, "TimeSinceWatered":6}
  89.     # If we didn't get a hit, break
  90.     index = switch.get(name, "Invalid Column")
  91.     if (index == "Invalid Column"):
  92.          return
  93.     # Set up the MYSQL connection
  94.     mydb = mysql.connector.connect(host = "localhost", user = "root", password = "tacocat", database = "PlantData")
  95.     mycursor = mydb.cursor()
  96.     # Get the data
  97.     mycursor.execute("SELECT * FROM Phase2Data")
  98.     # Get the row value
  99.     row = mycursor.fetchone()
  100.     # Create an empty list to store our values in
  101.     values = []
  102.     # Loop through all rows, compiling any row that isn't empty
  103.     while row is not None:
  104.         #print (row[index])
  105.         temp = (row[index])
  106. #       print(temp)
  107.         values.append(temp)
  108.         row = mycursor.fetchone()
  109.     # Close the connection
  110. #   print(values)
  111.     mycursor.close()
  112.     mydb.close()
  113.     return values
  114.  
  115. # Main method of the program
  116. def run():
  117.     print("===============================================================================================================================================================================================================================")
  118.     print("")
  119.     print("===================================================")
  120.     print("Program began running at %s" % datetime.datetime.today())
  121.     print("===================================================")
  122.     print("")
  123.     print("============")
  124.     print("[Heartbeat:] \t\t Setting Up")
  125.     # 1. Set up the MySQL and Plotly Variables
  126.     mydb = mysql.connector.connect(host = "localhost", user = "root", password = "tacocat", database = "PlantData")
  127.     mycursor = mydb.cursor()
  128.     sql = "INSERT INTO Phase2Data (Light, Humidity, Temp, AutoMoisture, ControlMoisture, TimeSinceWatered) VALUES (%s%s%s%s%s%s)"
  129.     sqlFetch = "SELECT * FROM Phase2Data"
  130.     # 2. Load the MySQL variables into their arrays
  131.    
  132.    
  133.  
  134.  
  135.     # 3. Begin program
  136.     print("[Heartbeat:] \t\t Running")
  137.     print(datetime.datetime.now())
  138.     print("============")
  139.     print("")
  140.     waterEnabled = True
  141.     while True:
  142.         datetime_values = readXData("DateTime")
  143.         light_values = readYData("Light")
  144.         humidity_values = readYData("Humidity")
  145.         temp_values = readYData("Temp")
  146.         auto_moisture_values = readYData("AutoMoisture")
  147.         control_moisture_values = readYData("ControlMoisture")
  148.         time_since_watered_values = readYData("TimeSinceWatered")
  149.         time_since_watered = time_since_watered_values[len(time_since_watered_values)-1]
  150.         # =========[LIGHT SETUP]==========
  151.         # Light sensor, 0 reading is light, 1 reading is dark
  152.         Light = GPIO.input(4)
  153.         print("========")
  154.         print ("[Light:] \t\t %s" % GPIO.input(4))
  155.         print("========")
  156.         print("")
  157.        
  158.         # Moisture Left: Autowatering ================================
  159.         auto_moisture_reading = str(adc.read_adc(0))
  160.         print("[Auto Moisture:] %s"%auto_moisture_reading)
  161.  
  162.         if (waterEnabled):
  163.             if(auto_moisutre_reading >= 190): # If we are dry
  164.                 print("The plant is currently dry. Redirecting.")
  165.                 if (time_since_watered > 96): # If it's been over 24 hours
  166.                     print("It has been over 24 hours since the plant was last watered. Watering now.")
  167.                     GPIO.output(26, GPIO.LOW)
  168.                     GPIO.output(23, GPIO.LOW)
  169.                     time.sleep(3)
  170.                     GPIO.output(23,GPIO.HIGH)
  171.                     time_since_watered = 0
  172.                 else: # If it has been less than 24 hours
  173.                     print("It has been less than 24 hours and the plant is dry. Aborting and flagging.")
  174.                     enabled = False
  175.                     GPIO.ouput(26, GPIO.HIGH)
  176.                     print("ISSUE WITH AUTO WATERING PUMP")
  177.                     time_since_watered = -1
  178.             else: # If we are still wet, do nothing
  179.                 print("Plant is still dry. Last watered:")
  180.                 print(time_since_watered)
  181.                 print("minutes ago.")
  182.         else:
  183.             print("ISSUE WITH AUTO WATERING PUMP")
  184.             time_since_watered = -1
  185.             GPIO.output(26, GPIO.HIGH)
  186.  
  187.         # Moisture Right: JustReading ================================
  188.         control_moisture_reading = str(adc2.read_adc(0))
  189.         print("[Control Moisture:] %s"%control_moisture_reading)
  190.        
  191.         # =========[TEMP/HUMIDITY SETUP]==========
  192.         humidity, temperature = Adafruit_DHT.read_retry(11,18)
  193.         print("===============")
  194.         Temp = float("{0:0.1f}".format(temperature))
  195.         Humidity = float("{0:0.1f}".format(humidity))
  196.         if humidity is not None and temperature is not None:
  197.             print("[Temperature:] \t\t Temp={0:0.1f}*C %".format(temperature))
  198.             print("[Humidity:] \t\t Humidity={0:0.1f}*C %".format(humidity))
  199.             # print('Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(temperature, humidity))
  200.         else:
  201.             print('[Temp/Humidity:] \t\t Failed to get reading. Try again!')
  202.         print("===============")
  203.         print('')
  204.        
  205.         # Add values to your y array for plotting later
  206.         #temp_values.append(Temp)
  207.         #humidity_values.append(Humidity)
  208.  
  209.         # =========[MYSQL INFORMATION]============
  210.         val = (str(Light), str(Humidity), str(Temp), str(auto_moisture_reading), str(control_moisture_reading), time_since_watered)
  211.         #valPlotly = (last_water/60, Temp, Humidity)
  212.         #mycursor.execute(sql,val)
  213.         #mycursor.execute(sqlPlotly, valPlotly)
  214.         mycursor.execute("""
  215.            INSERT INTO
  216.              Phase2Data(Light, Humidity, Temp, AutoMoisture, ControlMoisture, TimeSinceWatered)
  217.            VALUES
  218.                (%s, %s, %s, %s, %s, %s)""", val)
  219.         mydb.commit()
  220.         print("========")
  221.         print("[MySQL:] \t\t Records Inserted")
  222.         print("========")
  223.         print("")    
  224.  
  225.         # =========[MATPLOTLIB INFORMATION]===========
  226.         #Fetch the datetimes for each data
  227.         print("=================")
  228.         # print("[Plotly:] X Vals: \t %s" % last_water_x)
  229.         # print("[Plotly:] Y Vals: \t %s" % last_water_y)
  230.         print("=================")
  231.         print("")
  232.  
  233.  
  234.         #datetime_values = readXData("DateTime")
  235.         baseArr = []
  236.         i = 1
  237.         for item in light_values:
  238.             baseArr.append(i)
  239.             i+=1
  240.         baseArr = array(baseArr)
  241.         plt.plot(baseArr, array(light_values),'r')
  242.         plt.plot(baseArr, array(humidity_values),'g')
  243.         plt.plot(baseArr, array(temp_values),'y')
  244.         plt.plot(baseArr, array(auto_moisture_values),'b')
  245.         plt.plot(baseArr, array(control_moisture_values),'c')
  246.         #plt.plot(baseArr, light_values, 'b')
  247.        
  248.        
  249.         #plt.ylabel('Optimal Soil Moisture Time(Blue), Temperature Over Time (Red), Humidity Over Time (Green)...')
  250.         plt.ion()
  251.         plt.show()
  252.         plt.draw()
  253.         plt.pause(0.0001)
  254.         #REST PERIOD
  255.         time.sleep(900)
  256.         plt.close()
  257.        
  258.         if (time_since_watered != -1):
  259.             time_since_watered += 15
  260.        
  261.  
  262. run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement