Unverified Commit 8467fad4 authored by Kristian Tan's avatar Kristian Tan Committed by GitHub

Inputs (#2)

Added ability to add new device and change cost per kWh
parent 095a5350
...@@ -16,6 +16,7 @@ GPIO.setmode(GPIO.BCM) ...@@ -16,6 +16,7 @@ GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False) GPIO.setwarnings(False)
db = SQLAlchemy(app) db = SQLAlchemy(app)
os.environ['cost_per_kWh'] = '0.1622'
# TODO: Move this into daily_usage class file # TODO: Move this into daily_usage class file
...@@ -34,21 +35,54 @@ class DailyUsage(db.Model): ...@@ -34,21 +35,54 @@ class DailyUsage(db.Model):
return '<DailyUsage %r, %r, %r>' % (self.id, self.date, self.kwhUsed) return '<DailyUsage %r, %r, %r>' % (self.id, self.date, self.kwhUsed)
db.create_all() def get_todays_usage():
latest_entry = db.session.query(DailyUsage).order_by(DailyUsage.id.desc()).first()
if latest_entry:
latest_entry_date = date(latest_entry.date.year, latest_entry.date.month, latest_entry.date.day)
if latest_entry_date == datetime.today().date():
return format(latest_entry.kwhUsed, '.7f')
return 0
def get_todays_cost():
return format(float(get_todays_usage()) * float(os.environ['cost_per_kWh']), '0.5f')
def create_entry(change_pin):
latest_entry = db.session.query(DailyUsage).order_by(DailyUsage.id.desc()).first()
start_time = pins[change_pin]['on_time']
# Get the elapsed time and strip away milliseconds
elapsed = int((datetime.now() - start_time).total_seconds())
start_date = pins[change_pin]['on_date']
# Formula to calculate kWh based on time and wattage
kwh = pins[change_pin]['Wattage'] * (elapsed / 3600) / 1000
# If there is already an entry for today, update on time
# if latest_entry:
if latest_entry:
latest_entry_date = date(latest_entry.date.year, latest_entry.date.month, latest_entry.date.day)
if latest_entry_date == start_date:
latest_entry.kwhUsed += kwh
else:
# If no entry for today, make one
entry = DailyUsage(date=start_date, kwhUsed=kwh)
db.session.add(entry)
db.session.commit()
pins[change_pin]['on_time'] = None
pins[change_pin]['on_date'] = None
# TODO: be able to query db by date db.create_all()
daily_total = 0
latest_entry = db.session.query(DailyUsage).order_by(DailyUsage.id.desc()).first()
if latest_entry:
latest_entry_date = date(latest_entry.date.year, latest_entry.date.month, latest_entry.date.day)
if latest_entry_date == datetime.today().date():
daily_total = format(latest_entry.kwhUsed, '.7f')
todays_cost = format(float(daily_total) * 0.1622, '0.5f') daily_total = get_todays_usage()
todays_cost = get_todays_cost()
# Create dictionary to store pin info # Create dictionary to store pin info
pins = { pins = {
25: {'name': 'Light', 'state': GPIO.LOW, 'on_time': None, 'on_date': None, 'Wattage': 15} 25: {'name': 'Light', 'state': GPIO.LOW, 'on_time': None, 'on_date': None, 'Wattage': 15},
8: {'name': None, 'state': GPIO.LOW, 'on_time': None, 'on_date': None, 'Wattage': 0},
7: {'name': None, 'state': GPIO.LOW, 'on_time': None, 'on_date': None, 'Wattage': 0},
12: {'name': None, 'state': GPIO.LOW, 'on_time': None, 'on_date': None, 'Wattage': 0}
} }
...@@ -68,7 +102,10 @@ def main(): ...@@ -68,7 +102,10 @@ def main():
template_data = { template_data = {
'pins': pins, 'pins': pins,
'daily_total': daily_total, 'daily_total': daily_total,
'todays_cost': todays_cost 'todays_cost': todays_cost,
'cost_per_kWh': os.environ['cost_per_kWh'],
'display_new_device_form': False,
'display_change_kWh': False
} }
return render_template('main.html', **template_data) return render_template('main.html', **template_data)
...@@ -92,60 +129,72 @@ def toggle_pin(change_pin): ...@@ -92,60 +129,72 @@ def toggle_pin(change_pin):
for pin in pins: for pin in pins:
pins[pin]['state'] = GPIO.input(pin) pins[pin]['state'] = GPIO.input(pin)
latest_entry = db.session.query(DailyUsage).order_by(DailyUsage.id.desc()).first() template_data = {
if latest_entry: 'pins': pins,
latest_entry_date = date(latest_entry.date.year, latest_entry.date.month, latest_entry.date.day) 'daily_total': get_todays_usage(),
if latest_entry_date == datetime.today().date(): 'todays_cost': get_todays_cost(),
daily_total = format(latest_entry.kwhUsed, '.7f') 'cost_per_kWh': os.environ['cost_per_kWh']
else: }
daily_total = 0
return render_template('main.html', **template_data)
todays_cost = format(float(daily_total) * 0.1622, '0.5f')
@app.route('/handle_change_kWh', methods=['POST'])
def handle_change_kWh():
new_price = request.form['kWhprice']
os.environ['cost_per_kWh'] = str(new_price)
template_data = { template_data = {
'pins': pins, 'pins': pins,
'daily_total': daily_total, 'daily_total': daily_total,
'todays_cost': todays_cost 'todays_cost': todays_cost,
'cost_per_kWh': os.environ['cost_per_kWh']
} }
return render_template('main.html', **template_data)
@app.route("/devices/add_device")
def add_new_device():
template_data = {
'pins': pins,
'daily_total': daily_total,
'todays_cost': todays_cost,
'cost_per_kWh': os.environ['cost_per_kWh'],
'display_new_device_form': True
}
return render_template('main.html', **template_data) return render_template('main.html', **template_data)
def create_entry(change_pin): @app.route('/handle_new_device', methods=['POST'])
latest_entry = db.session.query(DailyUsage).order_by(DailyUsage.id.desc()).first() def handle_new_device():
start_time = pins[change_pin]['on_time'] new_name = request.form['new_device_name']
# Get the elapsed time and strip away milliseconds new_wattage = float(request.form['new_device_wattage'])
elapsed = int((datetime.now() - start_time).total_seconds()) for key in pins:
start_date = pins[change_pin]['on_date'] if pins[key]['name'] is None:
pins[key]['name'] = new_name
pins[key]['Wattage'] = new_wattage
break
# Formula to calculate kWh based on time and wattage template_data = {
kwh = pins[change_pin]['Wattage'] * (elapsed / 3600) / 1000 'pins': pins,
'daily_total': daily_total,
'todays_cost': todays_cost,
'cost_per_kWh': os.environ['cost_per_kWh'],
}
return render_template('main.html', **template_data)
# If there is already an entry for today, update on time
# if latest_entry:
if latest_entry:
latest_entry_date = date(latest_entry.date.year, latest_entry.date.month, latest_entry.date.day)
if latest_entry_date == start_date:
latest_entry.kwhUsed += kwh
else:
# If no entry for today, make one
entry = DailyUsage(date=start_date, kwhUsed=kwh)
db.session.add(entry)
db.session.commit()
pins[change_pin]['on_time'] = None
pins[change_pin]['on_date'] = None
@app.route('/handle_data', methods=['POST']) @app.route("/update_info/kWh")
def handle_data(): def change_kWh():
projectpath = request.form['kWhprice']
print(projectpath)
template_data = { template_data = {
'pins': pins, 'pins': pins,
'daily_total': daily_total, 'daily_total': daily_total,
'todays_cost': todays_cost 'todays_cost': todays_cost,
'cost_per_kWh': os.environ['cost_per_kWh'],
'display_change_kWh': True
} }
return render_template('main.html', **template_data) return render_template('main.html', **template_data)
if __name__ == '__main__': if __name__ == '__main__':
app.run(host='0.0.0.0', port=8090) app.run(host='0.0.0.0', port=8090)
...@@ -9,11 +9,24 @@ body { ...@@ -9,11 +9,24 @@ body {
/*background-color: aqua;*/ /*background-color: aqua;*/
} }
.container { .inputs {
display: flex;
flex-direction: column;
margin-right: 5%;
margin-left: 5%;
margin-bottom: 2%;
border-top-style: solid;
border-top-width: 1px;
border-top: black;
/*background-color: green;*/
/*height: 10%;*/
}
.containerRows {
display: flex; display: flex;
flex-direction: row; flex-direction: row;
/*background-color: darkkhaki;*/ /*background-color: darkkhaki;*/
height: 100%; /*height: 90%;*/
} }
.device_list { .device_list {
...@@ -31,6 +44,7 @@ body { ...@@ -31,6 +44,7 @@ body {
width: 65%; width: 65%;
margin-right: 5%; margin-right: 5%;
margin-left: 5%; margin-left: 5%;
margin-bottom: 2%;
/*background-color: coral;*/ /*background-color: coral;*/
border-style: solid; border-style: solid;
border-color: black; border-color: black;
......
...@@ -9,29 +9,33 @@ ...@@ -9,29 +9,33 @@
</div> </div>
<body> <body>
<div class="container"> <div class="containerRows">
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="kWhprice">
<input type="submit">
</form>
<div class="device_list"> <div class="device_list">
<h3 class="device_list_title">Device Listing and Status</h3> <h3 class="device_list_title">Device Listing and Status</h3>
{% for pin in pins %} {% for pin in pins %}
<p>{{ pins[pin].name }} : {% if pins[pin].name != None %}
{% if pins[pin].state == true %} <p>
(<a href="/toggle/{{pin}}">turn off</a>) {{ pins[pin].name }} :
{% else %} {% if pins[pin].state == true %}
(<a href="/toggle/{{pin}}">turn on</a>) (<a href="/toggle/{{pin}}">turn off</a>)
{% endif %} {% else %}
</p> (<a href="/toggle/{{pin}}">turn on</a>)
{% endfor %} </p>
{% endif %}
{% endif %}
{% endfor %}
<p><a href="/devices/add_device">Add device</a></p>
</div> </div>
<div class="smart_meter"> <div class="smart_meter">
<div class="smart_meter_info"> <div class="smart_meter_info">
{# Implement some way to display "No devices" message if none are in use#}
<p> Cost per kWh: £{{ cost_per_kWh }} <a href="/update_info/kWh"> (Update)</a></p>
<p> Total energy used today: {{ daily_total }} kWh.</p>
<p> Total cost of today's energy usage: £{{ todays_cost }}</p>
<p> Devices currently in use: </p> <p> Devices currently in use: </p>
<ul> <ul>
{% for pin in pins %} {% for pin in pins %}
...@@ -40,13 +44,28 @@ ...@@ -40,13 +44,28 @@
{% endif %} {% endif %}
{% endfor %} {% endfor %}
</ul> </ul>
{# Implement some way to display "No devices" message if none are in use#}
<p> Total energy used today: {{ daily_total }} kWh.</p>
<p> Total cost of today's energy usage: £{{ todays_cost }}</p>
</div> </div>
</div> </div>
</div> </div>
<div class="inputs">
{% if display_change_kWh == True %}
<form action="{{ url_for('handle_change_kWh') }}" method="post">
Change cost per kWh: <input type="text" name="kWhprice">
<input type="submit">
</form>
{% endif %}
{% if display_new_device_form == True %}
<div class=".add_new_device_form">
<form action="{{ url_for('handle_new_device') }}" method="post">
New device name: <input type="text" name="new_device_name"> <br>
New device wattage: <input type="number" name="new_device_wattage"> <br>
<input type="submit">
</form>
</div>
{% endif %}
</div>
</body> </body>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment