diff --git a/app/actions/fruxepi.py b/app/actions/fruxepi.py index cdce2d0..37d916c 100755 --- a/app/actions/fruxepi.py +++ b/app/actions/fruxepi.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 #FruxePi - CLI @@ -11,6 +11,11 @@ import pymysql import subprocess from time import strftime +import requests +import board +import busio +import adafruit_ads1x15.ads1015 as ADS +from adafruit_ads1x15.analog_in import AnalogIn # Script Arguments action = None @@ -50,152 +55,153 @@ # CLI Menu Function def CLI_menu(): # Climate - if action == "climate": + if action == "climate": # Return Temperature - if action_option == "-t" and action_GPIO is not None: + if action_option == "-t" and action_GPIO is not None: fetchTemperature(action_GPIO) # Return Raw Temperature elif action_option == "-tr" and action_GPIO is not None: fetchRawTemperature(action_GPIO) - # Return Humidity - elif action_option == "-h" and action_GPIO is not None: - fetchHumidity(action_GPIO) - # Return Raw Humidity - elif action_option == "-hr" and action_GPIO is not None: + # Return Humidity + elif action_option == "-h" and action_GPIO is not None: + fetchHumidity(action_GPIO) + # Return Raw Humidity + elif action_option == "-hr" and action_GPIO is not None: fetchRawHumidity(action_GPIO) # Diagnostics - elif action_option == "-d" and action_GPIO is not None: + elif action_option == "-d" and action_GPIO is not None: diagnosticsClimate(action_GPIO) else: print("Invalid Command!") # Lights - elif action == "lights": + elif action == "lights": # Lights ON - if action_option == "-ON" and action_GPIO is not None: - lightsON(action_GPIO, action_interval) + if action_option == "-ON": + lightsON() # Lights OFF - elif action_option == "-OFF" and action_GPIO is not None: - lightsOFF(action_GPIO, action_interval) - # Light Relay State - elif action_option == "-s" and action_GPIO is not None: - print(getRelayGPIOState(action_GPIO, action_interval)) - # Diagnostics - elif action_option == "-d" and action_GPIO is not None: + elif action_option == "-OFF": + lightsOFF() + # Light Relay State + elif action_option == "-s": + print(getRelayGPIOState(action_GPIO, action_interval)) + # Diagnostics + elif action_option == "-d": relayDiagnostics(action_GPIO, True) else: print("Invalid Command!") # Fan - elif action == "fan": + elif action == "fan": # Fan ON - if action_option == "-ON" and action_GPIO is not None: + if action_option == "-ON" and action_GPIO is not None: fanON(action_GPIO, action_interval) # Fan OFF elif action_option == "-OFF" and action_GPIO is not None: fanOFF(action_GPIO, action_interval) - # Fan Relay State + # Fan Relay State elif action_option == "-s" and action_GPIO is not None: print(getRelayGPIOState(action_GPIO, action_interval)) - # Run Fan Program + # Run Fan Program elif action_option == "-RUN" and action_GPIO is not None and action_interval is not None and relay_type is not None: - fanProgram(action_GPIO, action_interval, relay_type) - # Diagnostics + fanProgram(action_GPIO, action_interval, relay_type) + # Diagnostics elif action_option == "-d" and action_GPIO is not None: relayDiagnostics(action_GPIO, True) else: print("Invalid Command!") # Pump - elif action == "pump": + elif action == "pump": # Pump ON - if action_option == "-ON" and action_GPIO is not None: - pumpON(action_GPIO, action_interval) + if action_option == "-ON": + pumpON() # Pump OFF - elif action_option == "-OFF" and action_GPIO is not None: - pumpOFF(action_GPIO, action_interval) - # Pump Relay State - elif action_option == "-s" and action_GPIO is not None: + elif action_option == "-OFF": + pumpOFF() + # Pump Relay State + elif action_option == "-s": print(getRelayGPIOState(action_GPIO, action_interval)) - # Run Pump Program - elif action_option == "-RUN" and action_GPIO is not None and action_interval is not None and relay_type is not None: - pumpProgram(action_GPIO, action_interval, relay_type) - # Diagnostics + # Run Pump Program + elif action_option == "-RUN": + pumpProgram() + # Diagnostics elif action_option == "-d" and action_GPIO is not None: relayDiagnostics(action_GPIO, True) else: print("Invalid Command!") # Moisture - elif action == "moisture": + elif action == "moisture": # Get Moisture - if action_option == "-m" and action_GPIO is not None: + if action_option == "-m" and action_GPIO is not None: fetchMoisture(action_GPIO) # Pump Moisture Raw - elif action_option == "-mr" and action_GPIO is not None: - fetchRawMoisture(action_GPIO) - # Moisture State + elif action_option == "-mr" and action_GPIO is not None: + fetchRawMoisture() + # Moisture State elif action_option == "-s" and action_GPIO is not None: - getGPIOState(action_GPIO) - # Diagnostics + getGPIOState(action_GPIO) + # Diagnostics elif action_option == "-d" and action_GPIO is not None: diagnosticsMoisture(action_GPIO) else: print("Invalid Command!") - + # Heater - elif action == "heater": + elif action == "heater": # Heater ON - if action_option == "-ON" and action_GPIO is not None: + if action_option == "-ON" and action_GPIO is not None: heaterON(action_GPIO) # Heater OFF elif action_option == "-OFF" and action_GPIO is not None: heaterOFF(action_GPIO) - # Heater Relay State + # Heater Relay State elif action_option == "-s" and action_GPIO is not None: print(getGPIOState(action_GPIO)) - # Run Heater Program + # Run Heater Program elif action_option == "-RUN" and action_GPIO is not None and action_interval is not None: - heaterProgram(action_GPIO, action_interval) - # Diagnostics + heaterProgram(action_GPIO, action_interval) + # Diagnostics elif action_option == "-d" and action_GPIO is not None: relayDiagnostics(action_GPIO) else: print("Invalid Command!") - + # Fetch Grow Data - elif action == "update": + elif action == "update": # Update grow data - if action_option == "-growdata": + if action_option == "-growdata": growData = getGrowData() growDataUpdate(growData) # Update chart - elif action_option == "-chart": - update_chart() + elif action_option == "-chart": + print("Nope") else: print("Invalid Command!") # Maintenance - elif action == "maint": + elif action == "maint": # Cleanup old data from database - if action_option == "-cleanup": - deleteOldGrowData() + if action_option == "-cleanup": + print("Ignore") + # Do nothing because I want historical data else: print("Invalid Command!") - + # Camera - elif action == "camera": + elif action == "camera": # Capture Photo - if action_option == "-capture": + if action_option == "-capture": capturePhoto("candid") elif action_option == "-crop": capturePhoto("crop") - # Diagnostics + # Diagnostics elif action_option == "-d": cameraDiagnostics() else: print("Invalid Command!") - + else: print("Invalid Command!") @@ -210,37 +216,34 @@ def fetchMoisture(gpioPIN): status = GPIO.input(int(gpioPIN)) if status is not None: - + if status == 0: print("Soil Dry") elif status == 1: print("Soil Moist") - + else: print('Failed to get reading. Try again!') - + except: print('Sensor Error!') # Fetch Moisture Raw -def fetchRawMoisture(gpioPIN): +def fetchRawMoisture(): try: - # Set our GPIO numbering to BCM - GPIO.setmode(GPIO.BCM) - - # Set the GPIO pin to an input - GPIO.setup(int(gpioPIN), GPIO.IN) + i2c = busio.I2C(board.SCL, board.SDA) + ads = ADS.ADS1015(i2c) + chan = AnalogIn(ads, ADS.P0) - # Get Data - status = GPIO.input(int(gpioPIN)) + moisture = int(chan.voltage / 3.85 * 100) - if status is not None: - print(status) + if moisture is not None: + print(moisture) + return moisture else: print('Failed to get reading. Try again!') - except: - print('Sensor Error!') + print("Sensor Error!") def diagnosticsMoisture(gpioPIN): @@ -265,7 +268,7 @@ def diagnosticsMoisture(gpioPIN): # Fetch Temperature def fetchTemperature(gpioPIN): try: - humidity,temperature = dht.read_retry(dht.DHT22, int(gpioPIN)) + humidity,temperature = dht.read_retry(dht.DHT11, int(gpioPIN)) if temperature is not None: data_output = str(round(temperature, 2)) + "*C" @@ -279,7 +282,7 @@ def fetchTemperature(gpioPIN): # Fetch Raw Temperature def fetchRawTemperature(gpioPIN): try: - humidity,temperature = dht.read_retry(dht.DHT22, int(gpioPIN)) + humidity,temperature = dht.read_retry(dht.DHT11, int(gpioPIN)) if temperature is not None: data_output = round(temperature, 2) @@ -293,7 +296,7 @@ def fetchRawTemperature(gpioPIN): # Fetch Humidity def fetchHumidity(gpioPIN): try: - humidity,temperature = dht.read_retry(dht.DHT22, int(gpioPIN)) + humidity,temperature = dht.read_retry(dht.DHT11, int(gpioPIN)) if humidity is not None and humidity <= 100: data_output = str(round(humidity, 2)) + "%" @@ -307,7 +310,7 @@ def fetchHumidity(gpioPIN): # Fetch Raw Humidity def fetchRawHumidity(gpioPIN): try: - humidity,temperature = dht.read_retry(dht.DHT22, int(gpioPIN)) + humidity,temperature = dht.read_retry(dht.DHT11, int(gpioPIN)) if humidity is not None and humidity <= 100: data_output = round(humidity, 2) @@ -322,7 +325,7 @@ def fetchRawHumidity(gpioPIN): def diagnosticsClimate(gpioPIN): try: - humidity,temperature = dht.read_retry(dht.DHT22, int(gpioPIN)) + humidity,temperature = dht.read_retry(dht.DHT11, int(gpioPIN)) raw_temp = int(temperature) raw_humidity = int(humidity) @@ -364,12 +367,12 @@ def fetchFanThresholdDBData(): # Connect to the database connection = pymysql.connect(host, user, password, database, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) - + try: with connection.cursor() as cursor: # Fetch DB Query cursor.execute(sql) - result = cursor.fetchall() + result = cursor.fetchall() finally: connection.close() @@ -377,7 +380,7 @@ def fetchFanThresholdDBData(): data = {} data['temp'] = result[0]['fan_temp_threshold'] data['humid'] = result[0]['fan_humid_threshold'] - + return data @@ -390,7 +393,7 @@ def checkThresholds(curTemperature, curHumidity): # if curTemp or curHumidity exceed threshold if curTemperature > float(threshold_data['temp']) or curHumidity > float(threshold_data['humid']): return True - else: + else: return False @@ -426,55 +429,35 @@ def heaterProgram(gpioPIN, timeInterval): heaterOFF(gpioPIN) # Lights ON -def lightsON(gpioPIN, reverseRelay): +def lightsON(): print("Lights ON") - if reverseRelay: - os.system("gpio -g mode " + str(gpioPIN) + " out") - os.system("gpio -g write " + str(gpioPIN) + " 0") - else: - os.system("gpio -g mode " + str(gpioPIN) + " out") - os.system("gpio -g write " + str(gpioPIN) + " 1") + requests.get('https://maker.ifttt.com/trigger/lights_on/with/key/cR__hYdSLgON9Bs73de0ed') # Lights OFF -def lightsOFF(gpioPIN, reverseRelay): +def lightsOFF(): print("Lights OFF") - if reverseRelay: - os.system("gpio -g mode " + str(gpioPIN) + " out") - os.system("gpio -g write " + str(gpioPIN) + " 1") - else: - os.system("gpio -g mode " + str(gpioPIN) + " out") - os.system("gpio -g write " + str(gpioPIN) + " 0") + requests.get('https://maker.ifttt.com/trigger/lights_off/with/key/cR__hYdSLgON9Bs73de0ed') # Pump ON -def pumpON(gpioPIN, reverseRelay): +def pumpON(): print("Pump ON") - if reverseRelay: - os.system("gpio -g mode " + str(gpioPIN) + " out") - os.system("gpio -g write " + str(gpioPIN) + " 0") - else: - os.system("gpio -g mode " + str(gpioPIN) + " out") - os.system("gpio -g write " + str(gpioPIN) + " 1") + requests.get('https://maker.ifttt.com/trigger/pump_on/with/key/cR__hYdSLgON9Bs73de0ed') # Pummp OFF -def pumpOFF(gpioPIN, reverseRelay): +def pumpOFF(): print("Pump OFF") - if reverseRelay: - os.system("gpio -g mode " + str(gpioPIN) + " out") - os.system("gpio -g write " + str(gpioPIN) + " 1") - else: - os.system("gpio -g mode " + str(gpioPIN) + " out") - os.system("gpio -g write " + str(gpioPIN) + " 0") + requests.get('https://maker.ifttt.com/trigger/pump_off/with/key/cR__hYdSLgON9Bs73de0ed') # Pump run program -def pumpProgram(gpioPIN, timeInterval, reverseRelay): - pumpON(gpioPIN, reverseRelay) - time.sleep(int(timeInterval)) - pumpOFF(gpioPIN, reverseRelay) +def pumpProgram(): + pumpON() + time.sleep(20) + pumpOFF() # Get GPIO state def getGPIOState(gpioPIN): state = os.popen("gpio -g read " + str(gpioPIN)).read() - + return state @@ -513,12 +496,12 @@ def fetchSensorGPIO(): # Connect to the database connection = pymysql.connect(host, user, password, database, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) - + try: with connection.cursor() as cursor: # Fetch DB Query cursor.execute(sql) - result = cursor.fetchall() + result = cursor.fetchall() finally: connection.close() @@ -529,9 +512,11 @@ def fetchSensorGPIO(): data['light_GPIO'] = result[2]['gpio_pin'] data['fan_GPIO'] = result[3]['gpio_pin'] data['pump_GPIO'] = result[4]['gpio_pin'] - + return data + + def getGrowData(): GPIO = fetchSensorGPIO() @@ -542,6 +527,7 @@ def getGrowData(): data['humidity'] = fetchRawHumidity(GPIO['climate_GPIO']) data['light_status'] = getGPIOState(GPIO['light_GPIO']) data['moisture_status'] = getGPIOState(GPIO['moisture_GPIO']) + data['moisture'] = fetchRawMoisture() data['fan_status'] = getGPIOState(GPIO['fan_GPIO']) data['pump_status'] = getGPIOState(GPIO['pump_GPIO']) @@ -550,13 +536,13 @@ def getGrowData(): def growDataUpdate(data): - dbData = [data['timestamp'], data['temperature'], data['humidity'], data['light_status'], data['moisture_status'], data['fan_status'], data['pump_status']] + dbData = [data['timestamp'], data['temperature'], data['humidity'], data['light_status'], data['moisture_status'], data['fan_status'], data['pump_status'], data['moisture']] db = pymysql.connect(host, user, password, database) cursor = db.cursor() try: - cursor.execute("INSERT INTO grow_data (date_time, temperature, humidity, light_status, moisture_status, fan_status, pump_status) VALUES(%s, %s, %s, %s, %s, %s, %s)", dbData) + cursor.execute("INSERT INTO grow_data (date_time, temperature, humidity, light_status, moisture_status, fan_status, pump_status, moisture) VALUES(%s, %s, %s, %s, %s, %s, %s, %s)", dbData) db.commit() print("Grow Data Updated!") except: @@ -572,7 +558,7 @@ def deleteOldGrowData(): # Connect to the database connection = pymysql.connect(host, user, password, database, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) - + try: with connection.cursor() as cursor: # Fetch DB Query @@ -590,7 +576,7 @@ def takePhoto(imgPath, imgName): filePath = str(imgPath) + str(imgName) # Take Photo - os.system("raspistill -w 1920 -h 1720 -o " + filePath) + os.system("fswebcam -r 1920x1080 --no-banner --png 9 " + filePath) return imgName @@ -601,21 +587,21 @@ def capturePhoto(usage): if usage == "crop": # Image Details - imgName = "crop_bg.jpg" + imgName = "crop_bg.png" imgPath = "/var/www/html/assets/img/" # Filepath filePath = imgPath + imgName - + # Take photo - os.system("raspistill -w 800 -h 600 -o " + filePath) + os.system("fswebcam -r 1920x1080 --no-banner --png 9 " + filePath) elif usage == "candid": # Image Details timestamp = "{:%Y%m%d%H%M}".format(datetime.now()) - imgName = "FruxePi_capture_" + str(timestamp) + ".jpg" + imgName = "FruxePi_capture_" + str(timestamp) + ".png" imgPath = "/var/www/html/assets/tmp/" - + # Take photo print(takePhoto(imgPath, imgName)) @@ -626,7 +612,7 @@ def capturePhoto(usage): # Filepath filePath = imgPath + imgName - + # Take photo os.system("raspistill -w 800 -h 600 -o " + filePath) @@ -637,7 +623,7 @@ def capturePhoto(usage): def cameraDiagnostics(): status = os.popen('vcgencmd get_camera').read() print(status) - + # Chart # Fetch from sql based on string @@ -654,48 +640,5 @@ def fetchData(sql): finally: connection.close() - -# update chart history function -def update_history(data): - - # Connect to the database - connection = pymysql.connect(host,user,password,database,charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor) - - try: - with connection.cursor() as cursor: - # Create a new record - sql = "INSERT INTO climate_history (date_time, temperature, humidity) VALUES (%s, %s, %s)" - cursor.execute(sql, (data['date_time'], round(data['temperature']), round(data['humidity']))) - - connection.commit() - print("Success!") - finally: - connection.close() - - -def fetch_history(): - - tempQueryString = "SELECT AVG(temperature) as temperature, AVG(humidity) as humidity, date_time FROM grow_data WHERE date_time >= now() - interval 1 hour" - tempData = fetchData(tempQueryString) - - return tempData - - -# Update Chart -def update_chart(): - - try: - # fetch chart data - hourlyData = fetch_history() - - #update chart - update_history(hourlyData) - - print("Chart Updated!") - except Exception as e: - print("Chart Update Error!") - print(e) - - # RUN -CLI_menu() \ No newline at end of file +CLI_menu() diff --git a/app/application/controllers/Dashboard.php b/app/application/controllers/Dashboard.php old mode 100755 new mode 100644 index 30690a5..ec1a531 --- a/app/application/controllers/Dashboard.php +++ b/app/application/controllers/Dashboard.php @@ -1,11 +1,11 @@ -Crop_model->getAllCropsInfo(); $data['crop_activity'] = $this->Crop_model->get_cropActivity(); - $data['temperature_chart'] = $this->Dashboard_model->get_temperature_chart_data(); $data['temperature_format'] = $this->Climate_model->getTemperatureFormat(); - $data['humidity_chart'] = $this->Dashboard_model->get_humidity_chart_data(); - $data['chart_legend'] = $this->Dashboard_model->get_chart_legend(); - + + $data['temperature_chart7'] = $this->Dashboard_model->get_temperature_chart7_data(); + $data['humidity_chart7'] = $this->Dashboard_model->get_humidity_chart7_data(); + $data['moisture_chart7'] = $this->Dashboard_model->get_moisture_chart7_data(); + $data['chart_legend7'] = $this->Dashboard_model->get_chart_legend7(); + $data['pump_schedule'] = $this->Pump_model->getPumpSchedule(); $data['fan_schedule'] = $this->Fan_model->getFanSchedule(); $data['fan_status'] = $this->Fan_model->getFanStatus(); @@ -65,9 +67,14 @@ public function index() $data['cropConditions'] = $this->Dashboard_model->get_cropConditions(); $data['soil_status'] = $this->Moisture_model->readMoistureSensor(); + $data['temperature_chart'] = $this->Dashboard_model->get_temperature_chart_data(); + $data['temperature_format'] = $this->Climate_model->getTemperatureFormat(); + $data['humidity_chart'] = $this->Dashboard_model->get_humidity_chart_data(); + $data['moisture_chart'] = $this->Dashboard_model->get_moisture_chart_data(); + $data['chart_legend'] = $this->Dashboard_model->get_chart_legend(); // Page View $this->load->view('dashboard/index', $data); - + } else { // Redirect to login. redirect('/login'); @@ -81,11 +88,11 @@ public function editGrowRoomSettings() { // Set climate threshold $this->Climate_model->setClimateThreshold(); - + // Change lighting schedule in DB $lightsON = $this->Lights_model->setLightTimerON(); $lightsOFF = $this->Lights_model->setLightTimerOFF(); - + // Edit lighting CRON $this->Scheduler_model->editLightsCRON($lightsON, $lightsOFF); @@ -94,9 +101,9 @@ public function editGrowRoomSettings() // Set Pump schedule $this->Pump_model->setPumpSchedule(); - + redirect($_SERVER['HTTP_REFERER']); - + } else { // Redirect to login. redirect('/login'); @@ -112,7 +119,7 @@ public function latestPhoto() $filename = $this->Camera_model->takePhoto(); redirect(asset_url() . "tmp/". $filename); - + } else { // Redirect to login. redirect('/login'); @@ -124,7 +131,7 @@ public function reset() { // Page View $this->load->view('auth/reset'); - + } } diff --git a/app/application/models/Dashboard_model.php b/app/application/models/Dashboard_model.php old mode 100755 new mode 100644 index f7cea89..98e227f --- a/app/application/models/Dashboard_model.php +++ b/app/application/models/Dashboard_model.php @@ -21,23 +21,23 @@ public function get_user_info() // Get user ID for current user logged in $user = $this->ion_auth->user()->row(); $id = $user->id; - + // Fetch user record from the database $this->db->select('*'); $this->db->from('users'); $this->db->where(array('users.id' => $id)); - + // Return the result as array $query = $this->db->get(); return $query->result(); } - + // Get latest grow data public function get_latest_grow_data() { $this->db->select("*"); $this->db->from("grow_data"); - $this->db->order_by("id","DESC"); + $this->db->order_by("id DESC"); $this->db->limit(1); $query = $this->db->get(); @@ -55,6 +55,7 @@ public function get_latest_grow_data() "moisture_status" => $grow_data["moisture_status"], "fan_status" => $grow_data["fan_status"], "pump_status" => $grow_data["pump_status"], + "moisture" => $grow_data["moisture"], ); return $data; @@ -76,15 +77,127 @@ public function get_sensor_activation_state() return $data; } + + // Get 24-hr temperature chart data + public function get_temperature_chart7_data() + { + $tempFormat = $this->Climate_model->getTemperatureFormat(); + + $this->db->select("date_time, round(avg(temperature)) as temperature"); + $this->db->from("grow_data"); + $this->db->group_by("day( date_time )"); + $this->db->order_by("date_time"); + $this->db->limit(7); + $query = $this->db->get(); + $results = $query->result_array(); + + $output = ""; + $count = 1; + foreach($results as $result) { + if ($count == count($results)) { + if ($tempFormat == "F") { + $output .= celsiusToFahrenheit($result["temperature"]); + } else { + $output .= $result["temperature"]; + } + } else { + if ($tempFormat == "F") { + $output .= celsiusToFahrenheit($result["temperature"]) . ", "; + } else { + $output .= $result["temperature"] . ", "; + } + } + $count++; + } + + return $output; + } + + // Get 24-hr humidity chart data + public function get_humidity_chart7_data() + { + $this->db->select("date_time, round(avg(humidity)) as humidity"); + $this->db->from("grow_data"); + $this->db->group_by("day( date_time )"); + $this->db->order_by("date_time"); + $this->db->limit(7); + $query = $this->db->get(); + $results = $query->result_array(); + + $output = ""; + $count = 1; + foreach($results as $result) { + if ($count == count($results)) { + $output .= $result["humidity"]; + } else { + $output .= $result["humidity"] . ", "; + } + $count++; + } + + return $output; + } + + // Get 24-hr moisture chart data + public function get_moisture_chart7_data() + { + $this->db->select("date_time, round(avg(moisture)) as moisture"); + $this->db->from("grow_data"); + $this->db->group_by("day( date_time )"); + $this->db->order_by("date_time"); + $this->db->limit(7); + $query = $this->db->get(); + $results = $query->result_array(); + + $output = ""; + $count = 1; + foreach($results as $result) { + if ($count == count($results)) { + $output .= $result["moisture"]; + } else { + $output .= $result["moisture"] . ", "; + } + $count++; + } + + return $output; + } + + // Get chart legend + public function get_chart_legend7() + { + $this->db->select("date_time"); + $this->db->from("grow_data"); + $this->db->group_by("day( date_time )"); + $this->db->order_by("date_time"); + $this->db->limit(7); + $query = $this->db->get(); + $results = $query->result_array(); + + $output = ""; + $count = 1; + foreach($results as $result) { + if ($count == count($results)) { + $output .= "\"" . date_format(date_create($result["date_time"]), "M d") . "\""; + } else { + $output .= "\"" . date_format(date_create($result["date_time"]), "M d") . "\"" . ", "; + } + $count++; + } + + return $output; + } + // Get 24-hr temperature chart data public function get_temperature_chart_data() { $tempFormat = $this->Climate_model->getTemperatureFormat(); - $this->db->select("*"); - $this->db->from("climate_history"); - $this->db->order_by("id","DESC"); - $this->db->limit(24); + $this->db->select("date_time, round(avg(temperature)) as temperature"); + $this->db->from("grow_data"); + $this->db->group_by("hour( date_time ), day( date_time )"); + $this->db->order_by("date_time"); + $this->db->limit(48); $query = $this->db->get(); $results = $query->result_array(); @@ -114,10 +227,11 @@ public function get_temperature_chart_data() // Get 24-hr humidity chart data public function get_humidity_chart_data() { - $this->db->select("*"); - $this->db->from("climate_history"); - $this->db->order_by("id","DESC"); - $this->db->limit(24); + $this->db->select("date_time, round(avg(humidity)) as humidity"); + $this->db->from("grow_data"); + $this->db->group_by("hour( date_time ), day( date_time )"); + $this->db->order_by("date_time"); + $this->db->limit(48); $query = $this->db->get(); $results = $query->result_array(); @@ -136,13 +250,39 @@ public function get_humidity_chart_data() return $output; } + // Get 24-hr moisture chart data + public function get_moisture_chart_data() + { + $this->db->select("date_time, round(avg(moisture)) as moisture"); + $this->db->from("grow_data"); + $this->db->group_by("hour( date_time ), day( date_time )"); + $this->db->order_by("date_time"); + $this->db->limit(48); + $query = $this->db->get(); + $results = $query->result_array(); + + $output = ""; + $count = 1; + foreach($results as $result) { + if ($count == count($results)) { + $output .= $result["moisture"]; + } else { + $output .= $result["moisture"] . ", "; + } + $count++; + } + + return $output; + } + // Get chart legend public function get_chart_legend() { - $this->db->select("*"); - $this->db->from("climate_history"); - $this->db->order_by("id","DESC"); - $this->db->limit(24); + $this->db->select("date_time"); + $this->db->from("grow_data"); + $this->db->group_by("hour( date_time ), day( date_time )"); + $this->db->order_by("date_time"); + $this->db->limit(48); $query = $this->db->get(); $results = $query->result_array(); @@ -256,8 +396,8 @@ public function get_cropThresholds() // Current Crop Conditions public function get_cropConditions() { - - $sql = "SELECT * FROM grow_data WHERE DATE(date_time) = CURDATE() ORDER BY date_time DESC"; + + $sql = "SELECT * FROM grow_data WHERE DATE(date_time) = CURDATE() ORDER BY date_time ASC"; $query = $this->db->query($sql); $tempData = $query->result_array(); @@ -271,7 +411,7 @@ public function get_cropConditions() // Loop through tempData $total_records = sizeof($tempData); $positive_records = 0; - + foreach ($tempData as $item) { $temp = $item['temperature']; $humid = $item['humidity']; @@ -289,7 +429,7 @@ public function get_cropConditions() } } - + } -?> \ No newline at end of file +?> diff --git a/app/application/models/Lights_model.php b/app/application/models/Lights_model.php index 45d1219..c514c36 100755 --- a/app/application/models/Lights_model.php +++ b/app/application/models/Lights_model.php @@ -68,7 +68,7 @@ public function setGPIO() { // Set GPIO pin value and update database $data = array( - "gpio_pin" => $this->input->post('GPIO') + "gpio_pin" => $this->input->post('GPIO') ); $this->db->where('id', $this->sensorID); @@ -95,7 +95,7 @@ public function getGPIO() /** * Get Lights Activation State - * Get the activation state of the lights. + * Get the activation state of the lights. * @return boolean */ public function lightsActivationState() @@ -108,21 +108,21 @@ public function lightsActivationState() $result = $query->result(); $activationState = $result[0]->enabled; - // Return True or False + // Return True or False return $activationState; } /** * Enable Lights - * Enable the light module. + * Enable the light module. * @return void */ public function enableLights() { // Set enabled field to TRUE and update database $data = array( - "enabled" => TRUE + "enabled" => TRUE ); $this->db->where('id', $this->sensorID); @@ -139,7 +139,7 @@ public function disableLights() { // Set enabled field to FALSE and update database $data = array( - "enabled" => FALSE + "enabled" => FALSE ); $this->db->where('id', $this->sensorID); @@ -155,7 +155,7 @@ public function setRelayType() { // Set relay type value and update database $data = array( - "type" => $this->input->post('relayType') + "type" => $this->input->post('relayType') ); $this->db->where('technical_id', $this->sensorID); @@ -186,29 +186,22 @@ public function getRelayType() */ public function getLightsStatus() { - // GPIO pin - $gpioPIN = $this->Lights_model->getGPIO(); - - // Relay Type - $relayType = $this->Lights_model->getRelayType(); - - // Command string - $command_string = "sudo /var/www/html/actions/fruxepi.py lights -s " . $gpioPIN . " " . $relayType; - - // Execute command - exec($command_string, $command_callback); - - // Return True or False based on $command_callback value - if (!empty($command_callback)){ - if ($command_callback[0] == 1) { - return 1; - } + $current_time = date("H:i:s a"); + $on = "8 pm"; + $off = "2 pm"; + $date_now = DateTime::createFromFormat('H:i a', $current_time); + $date_on = DateTime::createFromFormat('H:i a', $on); + $date_off = DateTime::createFromFormat('H:i a', $off); + if ($date_now > $date_on && $date_now < $date_off) + { + return 0; + } + else + { + return 1; } - - return 0; } - /** * Set Light Timer ON * Set the ON light timer as HH:MM in 24-hour format. @@ -218,7 +211,7 @@ public function setLightTimerON() { // Set time for Timer ON $data = array( - "lights_ON" => $this->input->post('lightsON') + "lights_ON" => $this->input->post('lightsON') ); $this->db->where("process_id", "lights"); @@ -237,7 +230,7 @@ public function setLightTimerOFF() { // Set time for Timer ON $data = array( - "lights_OFF" => $this->input->post('lightsOFF') + "lights_OFF" => $this->input->post('lightsOFF') ); $this->db->where("process_id", "lights"); @@ -280,7 +273,7 @@ public function getLightTimerOFF() return $result[0]->lights_OFF; } - + /** * Light Diagnostics * A diagnostics function to determine the light's health and operability. @@ -293,7 +286,7 @@ public function lightsDiagnostics() // Command string $command_string = "sudo /var/www/html/actions/fruxepi.py lights -d " . $gpioPIN; - + // Execute command $command_callback = shell_exec($command_string); @@ -303,7 +296,7 @@ public function lightsDiagnostics() // Get Light Status public function getLightStatusMessage() { - + $data = array(); $timeNow = new DateTime(); $lightsON = new DateTime($this->Lights_model->getLightTimerON()); @@ -311,19 +304,19 @@ public function getLightStatusMessage() $lightHours = $lightsON->diff($lightsOFF)->format("%h"); $light_status = $this->Lights_model->getLightsStatus(); - + if ($light_status == 1) { $interval = $lightsOFF->diff($timeNow); $data['lights'] = 'ON'; $data['lightHours'] = $lightHours; - + if ($interval->format("%h") == "0"){ $data['status'] = $interval->format("%i minutes until lights off."); } else { $data['status'] = $interval->format("%h hours, %i minutes until lights off."); } - + } else { $interval = $lightsON->diff($timeNow); $data['lights'] = 'OFF'; @@ -334,12 +327,11 @@ public function getLightStatusMessage() $data['status'] = $interval->format("%h hours, %i minutes until lights on."); } } - + return $data; - + } } - diff --git a/app/application/views/dashboard/dashboard_scripts.php b/app/application/views/dashboard/dashboard_scripts.php old mode 100755 new mode 100644 index d5ad5f9..2a204f2 --- a/app/application/views/dashboard/dashboard_scripts.php +++ b/app/application/views/dashboard/dashboard_scripts.php @@ -4,8 +4,8 @@ - - + + \ No newline at end of file + diff --git a/app/application/views/dashboard/index.php b/app/application/views/dashboard/index.php old mode 100755 new mode 100644 index 2869afe..b59d748 --- a/app/application/views/dashboard/index.php +++ b/app/application/views/dashboard/index.php @@ -1,6 +1,6 @@ load->view('core/header'); ?> - + @@ -20,7 +20,7 @@ @@ -29,7 +29,7 @@
-
+
° @@ -39,10 +39,14 @@ C
-
+
% rH.
+
+ + % θs. +
@@ -68,7 +72,7 @@
- +
@@ -93,7 +97,7 @@