peltier_jacket/main.py

221 lines
7.7 KiB
Python
Raw Normal View History

2016-10-14 01:58:31 +03:00
#!/usr/bin/env python3
"""The MIT License
Copyright (c) 2016 Arti Zirk <arti.zirk@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from pprint import pprint
import sys
2016-10-14 01:58:31 +03:00
import json
import random
import base64
import os.path
2016-10-14 01:58:31 +03:00
from html import escape as html_escape
from collections import deque
from urllib.parse import parse_qs
2016-10-14 02:34:01 +03:00
import serial
2016-10-14 01:58:31 +03:00
max_nr_messages = 25
html = """<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Temperature</title>
<meta name="description" content="A simple message board written in python">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<style>
body {{
margin: 10px auto;
max-width: 650px;
line-height: 1.6;
font-size: 18px;
color: #444;
padding: 0 10px
}}
h1,h2,h3 {{
line-height: 1.2
}}
hr {{
display: block;
height: 1px;
border: 0;
border-top: 1px solid #ccc;
margin: 1em 0;
padding: 0;
}}
.temp_container {{
display: inline-block;
}}
</style>
</head>
<body>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<h1>Temperature</h1>
<div style="display: flex;flex-direction: row;flex-wrap: wrap;justify-content: center;align-items: center;">
<div id="temp_container">
<!--div style="display: inline-block; position: relative; top: -24px;">
<input type="text" style="display: block; width: 46px; font-size: 20px; padding: 0; margin: 20px 0;">
<button style="display:block; height:50px; width:50px;padding:10px;">set</button>
</div-->
2016-10-14 20:13:31 +03:00
<canvas data-width="100"
data-height="300"
data-type="linear-gauge"
data-min-value="15"
data-max-value="35"
data-animation-rule="elastic"
data-animation-duration="500"
data-minor-ticks="5"
data-major-ticks="15,20,25,30,35"
data-highlights=""
id="temp-gauge"></canvas>
2016-10-14 01:58:31 +03:00
</div>
</div>
2016-10-14 20:13:31 +03:00
<canvas id="chart" width="650" height="200"></canvas>
2016-10-14 01:58:31 +03:00
<hr>
<small><a href="https://git.wut.ee/arti/peltier_jacket" style="color:black;">Source code</a></small>, <small>Good luck!</small>
<script type="text/javascript" src="/smoothie.js"></script>
2016-10-14 19:30:00 +03:00
<script type="text/javascript" src="/fetch.js"></script>
2016-10-14 01:58:31 +03:00
<script type="text/javascript" src="/gauge.min.js"></script>
<script type="text/javascript" src="/main.js"></script>
</body>
</html>
"""
2016-10-14 02:34:01 +03:00
temps = deque(maxlen=10)
def stream(dev):
with serial.Serial(dev, timeout=1) as s:
while True:
temperature = s.readline().decode().strip()
2016-10-14 02:52:46 +03:00
if not temperature:
continue
2016-10-14 02:34:01 +03:00
print("temperature", temperature)
temps.append(temperature)
2016-10-14 01:58:31 +03:00
def application(env, start_response):
if env["REQUEST_METHOD"] == "POST":
try:
l = int(env.get('CONTENT_LENGTH', 0))
except KeyError:
start_response('411 Length Required', [('Content-Type', 'application/json')])
return [json.dumps({"error":{"code":411, "message": "Content-Length header missing"}}).encode()]
if l > 150:
start_response('413 Payload Too Large', [('Content-Type', 'application/json')])
return [json.dumps({"error":{"code":413, "message": "Payload Too Large"}}).encode()]
message = env['wsgi.input'].read(l).decode()
if not message:
start_response('400 Bad Request', [('Content-Type', 'application/json')])
return [json.dumps({"error":{"code":400, "message": "message not provided"}}).encode()]
try:
message = json.loads(message)["message"]
except json.decoder.JSONDecodeError:
pass
except KeyError:
start_response('400 Bad Request', [('Content-Type', 'application/json')])
return [json.dumps({"error":{"code":400, "message": "message key missing from json payload data"}}).encode()]
if message.startswith("message="):
message = parse_qs(message)["message"][0]
messages.appendleft(html_escape(message.strip()))
#start_response("200 OK", [('Content-Type', 'application/json')])
2016-10-14 02:34:01 +03:00
if env["PATH_INFO"] == "/temps.json":
start_response('200 OK', [('Content-Type', 'application/json')])
return [json.dumps(list(temps)).encode()]
2016-10-14 01:58:31 +03:00
if env["PATH_INFO"] == "/favicon.ico":
start_response('200 OK', [('Content-Type', 'image/x-icon')])
return []
elif env["PATH_INFO"] == "/smoothie.js":
start_response('200 OK', [('Content-Type', 'application/javascript')])
with open("smoothie.js", "rb") as f:
return [f.read()]
elif env["PATH_INFO"] == "/gauge.min.js":
start_response('200 OK', [('Content-Type', 'application/javascript')])
with open("gauge.min.js", "rb") as f:
return [f.read()]
elif env["PATH_INFO"] == "/fetch.js":
start_response('200 OK', [('Content-Type', 'application/javascript')])
with open("fetch.js", "rb") as f:
return [f.read()]
2016-10-14 01:58:31 +03:00
elif env["PATH_INFO"] == "/main.js":
start_response('200 OK', [('Content-Type', 'application/javascript')])
with open("main.js", "rb") as f:
return [f.read()]
start_response('200 OK', [('Content-Type', 'text/html')])
return [html.format().encode()]
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python3 main.py /dev/<arduinodev>")
exit(1)
ser_dev = sys.argv[1]
if not os.path.exists(ser_dev):
print("{} is not a valid tty device".format(ser_dev))
exit(1)
2016-10-14 02:34:01 +03:00
import threading
t = threading.Thread(target=stream, args=[ser_dev])
2016-10-14 02:34:01 +03:00
# classifying as a daemon, so they will die when the main dies
t.daemon = True
# begins, must come after daemon definition
t.start()
2016-10-14 01:58:31 +03:00
from wsgiref.simple_server import make_server
httpd = make_server('0.0.0.0', 8080, application)
print("Serving on http://0.0.0.0:8080/")
httpd.serve_forever()