Skip to content

Commit

Permalink
Website
Browse files Browse the repository at this point in the history
  • Loading branch information
gwennan eliezer committed Jan 10, 2023
1 parent eab3b97 commit f187363
Show file tree
Hide file tree
Showing 6 changed files with 192 additions and 28 deletions.
7 changes: 0 additions & 7 deletions serv/file.csv

This file was deleted.

84 changes: 77 additions & 7 deletions serv/main.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,92 @@
import os
import csv
import poller
import json
import mushroom_controller
from flask import Flask, render_template
from datetime import datetime
from flask import Flask, render_template, request


from threading import Thread
from threading import Lock


# create a shared lock
lock = Lock()
conn = mushroom_controller.get_connection()
print(">>>", conn is None)
filename = "file.csv"

if os.fork() == 0:
poller.run(conn, filename)
os._exit(1) # unreachable
Thread(target=poller.run, args=(conn, filename, lock)).start()
# if os.fork() == 0:
# poller.run(conn, filename)
# os._exit(1) # unreachable


app = Flask(__name__)


@app.route("/")
def hello_world():
def homepage():
return render_template('index.html')


@app.route("/data")
def get_data():
with open(filename, "r") as file:
data = [x for i, x in enumerate(csv.reader(file)) if i > 0]
return "<br/>".join([str(x) for x in data])
raw = [v for v in csv.reader(file)]
data = [
[raw[i][j] for i in range(len(raw))]
for j in range(len(raw[0]))]
return {
"data": [
{
"name": line[0],
"x": data[0][1:],
"y": line[1:],
}
for line in data[1:]],
"time": datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
}


@app.route("/set_settings", methods=['POST'])
def send_settings():
data = request.get_json()
with lock:
mushroom_controller.set_hygro(conn, data["hygro"])
print("set hydro")
mushroom_controller.set_temperature(conn, data["temp"])
print("set temp")
return "Ok"


@app.route("/program", methods=['POST'])
def program():
data = request.get_json()
try:
with open("prog.json", "r") as file:
jsondata = json.load(file)
except Exception:
jsondata = []
for val in data:
try:
date = datetime.strptime(val["date"], '%Y-%m-%dT%H:%M:%S')
except Exception:
return "Bad program data", 400
if type(val["hygro"]) != float or type(val["temp"]) != float:
return "Bad program data", 400
jsondata.append([
date.strftime("%Y-%m-%dT%H:%M:%S"),
{"hygro": val["hygro"], "temp": val["temp"]}])
jsondata.sort(reverse=True)
with open("prog.json", "w+") as file:
json.dump(jsondata, file)
return "Ok"


@app.route("/program", methods=['DELETE'])
def clear_program():
with open("prog.json", "w+") as file:
file.write("[]")
return "Ok"
33 changes: 27 additions & 6 deletions serv/mushroom_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,47 +10,68 @@ def get_connection():
try:
ser = serial.Serial(PORT, baudrate=9600, timeout=10)
time.sleep(5)
if ser is None:
raise Exception("Could not connect to hardware")
return ser
except Exception as e:
print(e)
raise Exception("Could not connect to hardware")


def set_temperature(conn, temp):
to_send = '1 '+str(temp)+"\r\n"
conn.write(to_send.encode())
c = conn.readline().rstrip()
return float(c)
try:
return float(c)
except Exception:
return None


def set_hygro(conn, hygro):
to_send = '2 '+str(hygro)+"\r\n"
conn.write(to_send.encode())
c = conn.readline().rstrip()
return float(c)
try:
return float(c)
except Exception:
return None


def get_expected_tmp(conn):
conn.write(b"3\n")
c = conn.readline().rstrip()
return float(c)
try:
return float(c)
except Exception:
return None


def get_expected_hygro(conn):
conn.write(b"4\n")
c = conn.readline().rstrip()
return float(c)
try:
return float(c)
except Exception:
return None


def get_actual_tmp(conn):
conn.write(b"5\n")
c = conn.readline().rstrip()
return float(c)
try:
return float(c)
except Exception:
return None


def get_actual_hygro(conn):
conn.write(b"6\n")
c = conn.readline().rstrip()
return float(c)
try:
return float(c)
except Exception:
return None


# Testing connection
Expand Down
34 changes: 26 additions & 8 deletions serv/poller.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,39 @@
from datetime import datetime
import time
import json
import mushroom_controller


def run(conn, filename):
def run(conn, filename, lock):
with open(filename, "w") as file:
print("erasing file")
file.write("date, time, expected temp, actual temp, expected hygro, actual hygro\n")
file.write("date time, Temp. attendue, Temp. effective, Humidité attendue, Humidité effective\n")
while True:
data = []
exp_tmp = str(mushroom_controller.get_expected_tmp(conn))
exp_hygro = str(mushroom_controller.get_expected_hygro(conn))
actual_tmp = str(mushroom_controller.get_actual_tmp(conn))
actual_hygro = str(mushroom_controller.get_actual_hygro(conn))
stamp = datetime.now().strftime("%d/%m/%Y, %H:%M:%S")
with lock:
exp_tmp = str(mushroom_controller.get_expected_tmp(conn))
exp_hygro = str(mushroom_controller.get_expected_hygro(conn))
actual_tmp = str(mushroom_controller.get_actual_tmp(conn))
actual_hygro = str(mushroom_controller.get_actual_hygro(conn))
stamp = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
data = ", ".join((stamp, exp_tmp, actual_tmp, exp_hygro, actual_hygro))
with open(filename, "a") as file:
file.write(data + "\n")
print("writing", data)

try:
with open("prog.json", "r") as file:
jsondata = json.load(file)
except Exception as e:
pass
else:
to_do = None
while len(jsondata) > 0 and jsondata[-1][0] < stamp: # if should be applied
to_do = jsondata.pop()
with open("prog.json", "w") as file:
json.dump(jsondata, file)
if to_do is not None:
with lock:
mushroom_controller.set_hygro(conn, to_do[1]["hygro"])
mushroom_controller.set_temperature(conn, to_do[1]["temp"])

time.sleep(1)
5 changes: 5 additions & 0 deletions serv/static/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
body {
display: flex;
flex-direction: column;
align-items: center;
}
57 changes: 57 additions & 0 deletions serv/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<!doctype html>
<head>
<title>blblblbl</title>
<script src="https://cdn.plot.ly/plotly-2.17.0.min.js"></script>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<div id="gd"></div>
<form action="/set_settings" method="POST">
<label for="temp">Température:</label>
<input id="temp" type="number" name="temp"></input>

<label for="hygro">Humidité:</label>
<input id="hygro" type="number" name="hygro"></input>
<input type="submit" value="Envoyer">
</form>
<script>
let form = document.querySelector("form");
let timeout;
form.addEventListener("submit", e => {
e.preventDefault();
fetch('/set_settings', {
method: 'POST',
body: JSON.stringify({
temp: parseInt(document.querySelector("#temp").value),
hygro: parseInt(document.querySelector("#hygro").value),
}),
headers: {
'Content-Type': 'application/json',
},
});
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(main, 500);
}, false);

async function main() {
let {data, time} = await (await fetch('/data', {
method: 'GET',
headers: {
'Accept': 'application/json',
},
})).json();
console.log(data);
Plotly.newPlot("gd", {
"data": data.map(o => {
o.x = o.x.map(v => new Date(v));
return o;
}),
"layout": { "width": 800, "height": 450}
});
timeout = setTimeout(main, 5000);
}
main();
</script>
</body>

0 comments on commit f187363

Please sign in to comment.