diff --git a/Backend/__init__.py b/Backend/__init__.py index 0d7bc57..80a54d6 100644 --- a/Backend/__init__.py +++ b/Backend/__init__.py @@ -1,3 +1,4 @@ +from app import routes, models from flask import Flask from config import Config from flask_sqlalchemy import SQLAlchemy @@ -7,5 +8,3 @@ app = Flask(__name__) app.config.from_object(Config) db = SQLAlchemy(app) migrate = Migrate(app, db) - -from app import routes, models \ No newline at end of file diff --git a/Backend/app.py b/Backend/app.py index 60e513b..d58a84f 100644 --- a/Backend/app.py +++ b/Backend/app.py @@ -1,3 +1,5 @@ +from utils import Functions +from models import Humidity, Light, Temperature, Moisture from flask import Flask, request from flask_sqlalchemy import SQLAlchemy import os @@ -13,14 +15,14 @@ app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['DEBUG'] = False app.config['TESTING'] = False app.config['SECRET_KEY'] = 'this-really-needs-to-be-changed' -app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://postgres:postgres@127.0.0.1:1001/mode" +app.config[ + 'SQLALCHEMY_DATABASE_URI'] = "postgresql://postgres:postgres@127.0.0.1:1001/mode" db = SQLAlchemy(app) -from models import Humidity, Light, Temperature, Moisture -from utils import Functions funcs = Functions() + @app.route('/', methods=['POST', 'GET']) def callback(): if request.method == "GET": @@ -49,81 +51,83 @@ def callback(): return "True" else: return "False" -@app.route("/ussd", methods = ['GET', 'POST']) -def ussd(): - session_id = request.values.get("sessionId", None) - serviceCode = request.values.get("serviceCode", None) - phone_number = request.values.get("phoneNumber", None) - text = request.values.get("text", "default") - if text == '': - response = "CON What would you want to check \n" + +@app.route("/ussd", methods=['GET', 'POST']) +def ussd(): + session_id = request.values.get("sessionId", None) + serviceCode = request.values.get("serviceCode", None) + phone_number = request.values.get("phoneNumber", None) + text = request.values.get("text", "default") + + if text == '': + response = "CON What would you want to check \n" response += "1. Get current data \n" response += "2. Get today's average data \n" response += "3. Get any day's average data \n" response += "4. Send commands" - elif text == '1': - response = "CON Choose information you want to view \n" + elif text == '1': + response = "CON Choose information you want to view \n" response += "1. Temperature \n" response += "2. Humidity \n" response += "3. Light intensity \n" response += "4. Soil Moisture \n" response += "5. Combined" - elif text == '2': - temp = funcs.today_data()['temperature'] + elif text == '2': + temp = funcs.today_data()['temperature'] humidity = funcs.today_data()['humidity'] light = funcs.today_data()['light'] moisture = funcs.today_data()['moisture'] - response = "END The today's average data is\nTemperature: {}\nHumidity: {}\nSoil moisture: {}\nLight intensity: {}".format(temp, humidity, light, moisture) + response = "END The today's average data is\nTemperature: {}\nHumidity: {}\nSoil moisture: {}\nLight intensity: {}".format( + temp, humidity, light, moisture) - - elif text == '3': + elif text == '3': response = "CON Enter the day, month, year e.g 27,2,2020" - - elif text == '4': + + elif text == '4': response = "CON Irrigation action \n" response += "1. Start irrigation \n" response += "2. Stop irrigation" - elif text == '1*1': - temp = funcs.latest_data()['temperature'] - response = "END The current temperature is " + str(temp) + elif text == '1*1': + temp = funcs.latest_data()['temperature'] + response = "END The current temperature is " + str(temp) - elif text == '1*2': - humidity = funcs.latest_data()['humidity'] - response = "END The current humidity is " + str(humidity) + elif text == '1*2': + humidity = funcs.latest_data()['humidity'] + response = "END The current humidity is " + str(humidity) - elif text == '1*3': - light = funcs.latest_data()['light'] - response = "END The current light intensity is " + str(light) + elif text == '1*3': + light = funcs.latest_data()['light'] + response = "END The current light intensity is " + str(light) - elif text == '1*4': - moisture = funcs.latest_data()['moisture'] - response = "END The current soil moisture is " + str(moisture) + elif text == '1*4': + moisture = funcs.latest_data()['moisture'] + response = "END The current soil moisture is " + str(moisture) - elif text == '1*5': - temp = funcs.latest_data()['temperature'] + elif text == '1*5': + temp = funcs.latest_data()['temperature'] humidity = funcs.latest_data()['humidity'] light = funcs.latest_data()['light'] moisture = funcs.latest_data()['moisture'] - response = "END The current data is\nTemperature: {}\nHumidity: {}\nSoil moisture: {}\nLight intensity: {}".format(temp, humidity, light, moisture) - + response = "END The current data is\nTemperature: {}\nHumidity: {}\nSoil moisture: {}\nLight intensity: {}".format( + temp, humidity, light, moisture) + elif text.__contains__(","): date_data = funcs.get_date_data(text) response = "END {} average is {}".format(text[2:], date_data) - - elif text == '4*1': + elif text == '4*1': funcs.start_irrigation() response = "END Irrigation has started " - elif text == '4*2': + elif text == '4*2': funcs.stop_irrigation() response = "END Irrigation has stoped " - else : + else: response = "END Invalid choice" return response diff --git a/Backend/config.py b/Backend/config.py index 4edd40c..09cfcb9 100644 --- a/Backend/config.py +++ b/Backend/config.py @@ -1,4 +1,5 @@ import os + basedir = os.path.abspath(os.path.dirname(__file__)) diff --git a/Backend/manage.py b/Backend/manage.py index a8ff790..daf2936 100644 --- a/Backend/manage.py +++ b/Backend/manage.py @@ -4,13 +4,10 @@ from flask_migrate import Migrate, MigrateCommand from app import app, db - - migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) - if __name__ == '__main__': - manager.run() \ No newline at end of file + manager.run() diff --git a/Backend/models.py b/Backend/models.py index a74a954..f8d3a92 100644 --- a/Backend/models.py +++ b/Backend/models.py @@ -1,11 +1,12 @@ from app import db from datetime import datetime + class Humidity(db.Model): __tablename__ = 'humidity' id = db.Column(db.Integer, primary_key=True) humidity = db.Column(db.Float(), nullable=False) - updated_on = db.Column(db.DateTime()) + updated_on = db.Column(db.DateTime()) def __init__(self, humidity): self.humidity = humidity @@ -13,16 +14,17 @@ class Humidity(db.Model): def __repr__(self): return ''.format(self.id, self.updated_on) - + def save(self): db.session.add(self) db.session.commit() + class Temperature(db.Model): __tablename__ = 'temperature' id = db.Column(db.Integer, primary_key=True) temperature = db.Column(db.Float(), nullable=False) - updated_on = db.Column(db.DateTime()) + updated_on = db.Column(db.DateTime()) def __init__(self, temperature): self.temperature = temperature @@ -30,16 +32,17 @@ class Temperature(db.Model): def __repr__(self): return ''.format(self.id) - + def save(self): db.session.add(self) db.session.commit() + class Light(db.Model): __tablename__ = 'light' id = db.Column(db.Integer, primary_key=True) light = db.Column(db.Float(), nullable=False) - updated_on = db.Column(db.DateTime()) + updated_on = db.Column(db.DateTime()) def __init__(self, light): self.light = light @@ -47,16 +50,17 @@ class Light(db.Model): def __repr__(self): return ''.format(self.id) - + def save(self): db.session.add(self) db.session.commit() + class Moisture(db.Model): __tablename__ = 'moisture' id = db.Column(db.Integer, primary_key=True) moisture = db.Column(db.Float(), nullable=False) - updated_on = db.Column(db.DateTime()) + updated_on = db.Column(db.DateTime()) def __init__(self, moisture): self.moisture = moisture @@ -64,7 +68,7 @@ class Moisture(db.Model): def __repr__(self): return ''.format(self.id) - + def save(self): db.session.add(self) db.session.commit() diff --git a/Backend/utils.py b/Backend/utils.py index cb80b64..1bcc336 100644 --- a/Backend/utils.py +++ b/Backend/utils.py @@ -6,6 +6,7 @@ import africastalking from datetime import datetime, date from models import Humidity, Light, Temperature, Moisture + class Functions: def __init__(self): load_dotenv(dotenv_path="broker.env") @@ -20,20 +21,43 @@ class Functions: africastalking.initialize(self.username, self.api_key) self.sms = africastalking.SMS - def start_irrigation(self): # starts irrigation - single("rodneyeris/demo2eris/relay", payload='on', qos=1, retain=False, - hostname=self.broker_url, port=self.broker_port, client_id=self.client_id, - keepalive=60, will=None, auth={'username':self.broker_username, 'password':self.broker_password}, - tls=None, protocol=mqtt.MQTTv311, transport="tcp") + single("rodneyeris/demo2eris/relay", + payload='on', + qos=1, + retain=False, + hostname=self.broker_url, + port=self.broker_port, + client_id=self.client_id, + keepalive=60, + will=None, + auth={ + 'username': self.broker_username, + 'password': self.broker_password + }, + tls=None, + protocol=mqtt.MQTTv311, + transport="tcp") def stop_irrigation(self): # Stops irrigation - single("rodneyeris/demo2eris/relay", payload='off', qos=1, retain=False, - hostname=self.broker_url, port=self.broker_port, client_id=self.client_id, - keepalive=60, will=None, auth={'username':self.broker_username, 'password':self.broker_password}, - tls=None, protocol=mqtt.MQTTv311, transport="tcp") + single("rodneyeris/demo2eris/relay", + payload='off', + qos=1, + retain=False, + hostname=self.broker_url, + port=self.broker_port, + client_id=self.client_id, + keepalive=60, + will=None, + auth={ + 'username': self.broker_username, + 'password': self.broker_password + }, + tls=None, + protocol=mqtt.MQTTv311, + transport="tcp") def send_alert(self, data, topic, level): # Sends and sms alert to farmers number @@ -71,10 +95,10 @@ class Functions: if count == 0: count = 1 average = { - "humidity" : humidity_av/count, - "temperature" : temperature_av/count, - "light" : light_av/count, - "moisture" : moisture_av/count + "humidity": humidity_av / count, + "temperature": temperature_av / count, + "light": light_av / count, + "moisture": moisture_av / count } return average @@ -106,10 +130,10 @@ class Functions: def latest_data(): # Gets the latest entries into the database data = { - "humidity" : Humidity.query.all()[-1].humidity, - "temperature" : Temperature.query.all()[-1].temperature, - "light" : Light.query.all()[-1].light, - "moisture" : Moisture.query.all()[-1].moisture + "humidity": Humidity.query.all()[-1].humidity, + "temperature": Temperature.query.all()[-1].temperature, + "light": Light.query.all()[-1].light, + "moisture": Moisture.query.all()[-1].moisture } return data @@ -144,9 +168,9 @@ class Functions: if count == 0: count = 1 average = { - "humidity" : humidity_av/count, - "temperature" : temperature_av/count, - "light" : light_av/count, - "moisture" : moisture_av/count + "humidity": humidity_av / count, + "temperature": temperature_av / count, + "light": light_av / count, + "moisture": moisture_av / count } return average