Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # Set up imports
- import RPI_ADC0832
- import RPi.GPIO as GPIO
- import Adafruit_DHT
- import sys
- import time
- import mysql.connector
- import datetime
- import matplotlib.pyplot as plt
- from numpy import array
- # Set up the Raspberry Pi GPIO pins ================
- GPIO.setmode(GPIO.BCM)
- # Light Photocell ================================
- GPIO.setup(4,GPIO.IN)
- # Humidity ================================
- GPIO.setup(11,GPIO.IN)
- # Temperature ================================
- GPIO.setup(18,GPIO.IN)
- # LED Status Light ================================
- GPIO.setup(26,GPIO.OUT)
- # DC Pump ================================
- GPIO.setup(23,GPIO.OUT)
- # Set DC Pump as "OFF"
- GPIO.output(23,GPIO.HIGH)
- # Reads DateTime info from the PlotlyDatabase.
- # Analog->Digital MOISTURE SETUP ================================
- # Set up moisture 1 sensor
- adc = RPI_ADC0832.ADC0832()
- adc.csPin = 17 # Default pin: 17
- adc.clkPin = 27 # Default pin: 27
- adc.doPin = 22 # Default pin: 23
- adc.diPin = 22 # Default pin: 24
- # Create an ADC0832 instance
- adc2 = RPI_ADC0832.ADC0832()
- adc2.csPin = 5
- adc2.clkPin = 6
- adc2.doPin = 13
- adc2.diPin = 13
- # For non-default pins, make sure to set up the CD and CLK pins as outputs
- GPIO.setup(adc2.csPin, GPIO.OUT, initial = GPIO.HIGH)
- GPIO.setup(adc2.clkPin, GPIO.OUT, initial=GPIO.LOW)
- # Function which fetches the X values of data from a database
- def readXData(name):
- f = '%Y-%m-%d %H:%M:%S'
- # Create a dictionary which will redirect according to what we need
- switch = {"LastWaterX":0, "LastWaterY":1, "TempX":2, "TempY":3, "HumidityX":4, "HumidityY":5}
- # If we didn't get a hit, break
- index = switch.get(name, "Invalid Column")
- if (index == "Invalid Column"):
- return
- # Set up the MYSQL connection
- mydb = mysql.connector.connect(host = "localhost", user = "root", password = "tacocat", database = "PlantData")
- mycursor = mydb.cursor()
- # Get the data
- mycursor.execute("SELECT * FROM PlotlyData")
- # Get the row value
- row = mycursor.fetchone()
- # Create an empty list to store our values in
- values = []
- # Loop through all rows, compiling any row that isn't empty
- while row is not None:
- #print (row[index])
- temp = (row[index])
- temp = temp.strftime(f)
- # print(temp)
- values.append(temp)
- row = mycursor.fetchone()
- # Close the connection
- # print(values)
- mycursor.close()
- mydb.close()
- return values
- # Reads Int/Float values from the Plotly database.
- # Function that fetches the Y values from the database
- def readYData(name):
- f = '%Y-%m-%d %H:%M:%S'
- # Create a dictionary which will redirect according to what we need
- switch = {"DateTime":0, "Light":1, "Humidity":2, "Temp":3, "AutoMoisture":4, "ControlMoisture":5, "TimeSinceWatered":6}
- # If we didn't get a hit, break
- index = switch.get(name, "Invalid Column")
- if (index == "Invalid Column"):
- return
- # Set up the MYSQL connection
- mydb = mysql.connector.connect(host = "localhost", user = "root", password = "tacocat", database = "PlantData")
- mycursor = mydb.cursor()
- # Get the data
- mycursor.execute("SELECT * FROM Phase2Data")
- # Get the row value
- row = mycursor.fetchone()
- # Create an empty list to store our values in
- values = []
- # Loop through all rows, compiling any row that isn't empty
- while row is not None:
- #print (row[index])
- temp = (row[index])
- # print(temp)
- values.append(temp)
- row = mycursor.fetchone()
- # Close the connection
- # print(values)
- mycursor.close()
- mydb.close()
- return values
- # Main method of the program
- def run():
- print("===============================================================================================================================================================================================================================")
- print("")
- print("===================================================")
- print("Program began running at %s" % datetime.datetime.today())
- print("===================================================")
- print("")
- print("============")
- print("[Heartbeat:] \t\t Setting Up")
- # 1. Set up the MySQL and Plotly Variables
- mydb = mysql.connector.connect(host = "localhost", user = "root", password = "tacocat", database = "PlantData")
- mycursor = mydb.cursor()
- sql = "INSERT INTO Phase2Data (Light, Humidity, Temp, AutoMoisture, ControlMoisture, TimeSinceWatered) VALUES (%s%s%s%s%s%s)"
- sqlFetch = "SELECT * FROM Phase2Data"
- # 2. Load the MySQL variables into their arrays
- # 3. Begin program
- print("[Heartbeat:] \t\t Running")
- print(datetime.datetime.now())
- print("============")
- print("")
- waterEnabled = True
- while True:
- datetime_values = readXData("DateTime")
- light_values = readYData("Light")
- humidity_values = readYData("Humidity")
- temp_values = readYData("Temp")
- auto_moisture_values = readYData("AutoMoisture")
- control_moisture_values = readYData("ControlMoisture")
- time_since_watered_values = readYData("TimeSinceWatered")
- time_since_watered = time_since_watered_values[len(time_since_watered_values)-1]
- # =========[LIGHT SETUP]==========
- # Light sensor, 0 reading is light, 1 reading is dark
- Light = GPIO.input(4)
- print("========")
- print ("[Light:] \t\t %s" % GPIO.input(4))
- print("========")
- print("")
- # Moisture Left: Autowatering ================================
- auto_moisture_reading = str(adc.read_adc(0))
- print("[Auto Moisture:] %s"%auto_moisture_reading)
- if (waterEnabled):
- if(auto_moisutre_reading >= 190): # If we are dry
- print("The plant is currently dry. Redirecting.")
- if (time_since_watered > 96): # If it's been over 24 hours
- print("It has been over 24 hours since the plant was last watered. Watering now.")
- GPIO.output(26, GPIO.LOW)
- GPIO.output(23, GPIO.LOW)
- time.sleep(3)
- GPIO.output(23,GPIO.HIGH)
- time_since_watered = 0
- else: # If it has been less than 24 hours
- print("It has been less than 24 hours and the plant is dry. Aborting and flagging.")
- enabled = False
- GPIO.ouput(26, GPIO.HIGH)
- print("ISSUE WITH AUTO WATERING PUMP")
- time_since_watered = -1
- else: # If we are still wet, do nothing
- print("Plant is still dry. Last watered:")
- print(time_since_watered)
- print("minutes ago.")
- else:
- print("ISSUE WITH AUTO WATERING PUMP")
- time_since_watered = -1
- GPIO.output(26, GPIO.HIGH)
- # Moisture Right: JustReading ================================
- control_moisture_reading = str(adc2.read_adc(0))
- print("[Control Moisture:] %s"%control_moisture_reading)
- # =========[TEMP/HUMIDITY SETUP]==========
- humidity, temperature = Adafruit_DHT.read_retry(11,18)
- print("===============")
- Temp = float("{0:0.1f}".format(temperature))
- Humidity = float("{0:0.1f}".format(humidity))
- if humidity is not None and temperature is not None:
- print("[Temperature:] \t\t Temp={0:0.1f}*C %".format(temperature))
- print("[Humidity:] \t\t Humidity={0:0.1f}*C %".format(humidity))
- # print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
- else:
- print('[Temp/Humidity:] \t\t Failed to get reading. Try again!')
- print("===============")
- print('')
- # Add values to your y array for plotting later
- #temp_values.append(Temp)
- #humidity_values.append(Humidity)
- # =========[MYSQL INFORMATION]============
- val = (str(Light), str(Humidity), str(Temp), str(auto_moisture_reading), str(control_moisture_reading), time_since_watered)
- #valPlotly = (last_water/60, Temp, Humidity)
- #mycursor.execute(sql,val)
- #mycursor.execute(sqlPlotly, valPlotly)
- mycursor.execute("""
- INSERT INTO
- Phase2Data(Light, Humidity, Temp, AutoMoisture, ControlMoisture, TimeSinceWatered)
- VALUES
- (%s, %s, %s, %s, %s, %s)""", val)
- mydb.commit()
- print("========")
- print("[MySQL:] \t\t Records Inserted")
- print("========")
- print("")
- # =========[MATPLOTLIB INFORMATION]===========
- #Fetch the datetimes for each data
- print("=================")
- # print("[Plotly:] X Vals: \t %s" % last_water_x)
- # print("[Plotly:] Y Vals: \t %s" % last_water_y)
- print("=================")
- print("")
- #datetime_values = readXData("DateTime")
- baseArr = []
- i = 1
- for item in light_values:
- baseArr.append(i)
- i+=1
- baseArr = array(baseArr)
- plt.plot(baseArr, array(light_values),'r')
- plt.plot(baseArr, array(humidity_values),'g')
- plt.plot(baseArr, array(temp_values),'y')
- plt.plot(baseArr, array(auto_moisture_values),'b')
- plt.plot(baseArr, array(control_moisture_values),'c')
- #plt.plot(baseArr, light_values, 'b')
- #plt.ylabel('Optimal Soil Moisture Time(Blue), Temperature Over Time (Red), Humidity Over Time (Green)...')
- plt.ion()
- plt.show()
- plt.draw()
- plt.pause(0.0001)
- #REST PERIOD
- time.sleep(900)
- plt.close()
- if (time_since_watered != -1):
- time_since_watered += 15
- run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement