peltier_jacket/main.py

273 lines
9.5 KiB
Python

#!/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
import json
import random
import base64
import os.path
from html import escape as html_escape
from collections import deque
from urllib.parse import parse_qs
import serial
max_nr_messages = 25
html = """<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Jacket 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>
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</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]-->
<div class="container">
<h1>Jacket Temperature</h1>
<div class="row">
<div class="col-md-4">
<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>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary btn-lg active" onclick="heat('1');">
<input type="radio" name="options" id="option1" autocomplete="off" checked> ↑
</label>
<label class="btn btn-primary btn-lg" onclick="heat('2');">
<input type="radio" name="options" id="option2" autocomplete="off"> OFF
</label>
<label class="btn btn-primary btn-lg" onclick="heat('0');">
<input type="radio" name="options" id="option3" autocomplete="off"> ↓
</label>
</div>
<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-gauge2"></canvas>
</div>
<div class="col-md-8">
<canvas id="chart" width="600" height="300"></canvas>
</div>
</div>
<hr>
<small><a href="https://git.wut.ee/arti/peltier_jacket" style="color:black;">Source code</a></small>, <small>Good luck!</small>
</div>
<script type="text/javascript" src="/smoothie.js"></script>
<script type="text/javascript" src="/fetch.js"></script>
<script type="text/javascript" src="/gauge.min.js"></script>
<script type="text/javascript" src="/main.js"></script>
</body>
</html>
"""
temps = deque(maxlen=10)
arduino = None
def stream(dev):
while True:
temperature = dev.readline().decode().strip().split()
if not temperature:
continue
print("temperature", temperature)
temps.append(temperature[0])
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]
start_response("200 OK", [('Content-Type', 'application/json')])
print(arduino.write(message.encode()))
arduino.write(b'\n')
return [json.dumps(message).encode()]
if env["PATH_INFO"] == "/temps.json":
start_response('200 OK', [('Content-Type', 'application/json')])
return [json.dumps(list(temps)).encode()]
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()]
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)
arduino = serial.Serial(ser_dev, timeout=2)
import threading
t = threading.Thread(target=stream, args=[arduino])
# classifying as a daemon, so they will die when the main dies
t.daemon = True
# begins, must come after daemon definition
t.start()
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()