Mercurial > code > home > repos > homeauto
changeset 1180:47c35e6765e2
drop old code for front door
Ignore-this: cfb732e66f0c410443c1b2f4e4620c78
darcs-hash:3afaaf01b8680c04bd0f4db82d383327850e5e60
author | drewp <drewp@bigasterisk.com> |
---|---|
date | Tue, 11 Dec 2018 15:02:56 -0800 |
parents | 0a4bf144c956 |
children | 0c366a029c49 |
files | service/frontDoorArduino/frontDoor/frontDoor.pde service/frontDoorArduino/frontDoorArduino.py service/frontDoorArduino/index.html |
diffstat | 3 files changed, 0 insertions(+), 498 deletions(-) [+] |
line wrap: on
line diff
--- a/service/frontDoorArduino/frontDoor/frontDoor.pde Tue Dec 11 12:31:18 2018 -0800 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,154 +0,0 @@ -/* - note that the chip in this arduino has been replaced with a '328 - */ -#include "ST7565.h" -#include <OneWire.h> -#include <DallasTemperature.h> - -#define BACKLIGHT_LED 10 - -ST7565 glcd(9, 8, 7, 6, 5); - -OneWire oneWire(3); // digital IO 3 -DallasTemperature sensors(&oneWire); -DeviceAddress tempSensorAddress; -#define NUM_TEMPERATURE_RETRIES 5 - -char newtxt[21*8+1]; -unsigned int written; -unsigned char cmd; - -#define GETHEADER -2 -#define GETCOMMAND -1 - -void setup() { - Serial.begin(9600); - Serial.flush(); - - pinMode(11, INPUT); // low means door is closed - digitalWrite(11, HIGH); - - pinMode(12, OUTPUT); - digitalWrite(12, LOW); - - pinMode(BACKLIGHT_LED, OUTPUT); - analogWrite(BACKLIGHT_LED, 200); - - glcd.st7565_init(); - glcd.st7565_command(CMD_DISPLAY_ON); - glcd.st7565_command(CMD_SET_ALLPTS_NORMAL); - glcd.st7565_set_brightness(0x18); - - glcd.display(); // show splashscreen - - newtxt[21*8] = 0; - written = GETHEADER; // GETHEADER --recv 0xff--> GETCOMMAND --recv 0x00--> 0 -} - -void initSensors() { - sensors.begin(); - sensors.getAddress(tempSensorAddress, 0); - sensors.setResolution(tempSensorAddress, 12); -} - -void loop() { - /* - send 0xff 0x00, - then up to 21*8 bytes of text to replace the display, with a null terminator. - - or 0xff 0x01, then get back '0\n' or '1\n' for the door sensor - - or 0xff 0x02, then get back temperature followed by newline - - or 0xff 0x03 then a byte for the screen brightness - - or 0xff 0x0f then 00 or 01 to set the front lights on pin 12 - */ - float newTemp; - int i, printed; - int inb = Serial.read(); - if (inb == -1) { - return; - } - - if (written == GETHEADER) { - if (inb == 0xff) { - written = GETCOMMAND; - } - } - else if(written == GETCOMMAND) { - cmd = inb; - - switch(cmd) { - case 0: - written = 0; // get chars below - return; - - case 1: - Serial.print(digitalRead(11) ? - "{\"door\":\"open\"}\n" : - "{\"door\":\"closed\"}\n"); - written = GETHEADER; - return; - - case 2: - - for (i=0; i<NUM_TEMPERATURE_RETRIES; i++) { - - sensors.requestTemperatures(); - newTemp = sensors.getTempF(tempSensorAddress); - if (i < NUM_TEMPERATURE_RETRIES-1 && - (newTemp < -100 || newTemp > 180)) { - // too many errors that were fixed by restarting arduino. - // trying repeating this much init - initSensors(); - continue; - } - Serial.print("{\"temp\":"); - Serial.print(newTemp); - Serial.print(", \"retries\":"); - Serial.print(i); - Serial.print("}\n"); - break; - } - written = GETHEADER; - return; - - case 3: - case 4: - written = 0; // these are handled below - return; - - // otherwise take chars - } - } - else { - if (cmd == 3) { - analogWrite(BACKLIGHT_LED, 255 - inb); - written = GETHEADER; - return; - } - if (cmd == 4) { - digitalWrite(12, inb); - written = GETHEADER; - return; - } - newtxt[written] = inb; - written++; - - if (inb == 0 || (written > 21 * 8)) { - glcd.clear(); - glcd.drawstring(0,0, newtxt); - glcd.display(); - - written = GETHEADER; - return; - } - } -} - - - - - -
--- a/service/frontDoorArduino/frontDoorArduino.py Tue Dec 11 12:31:18 2018 -0800 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,230 +0,0 @@ -""" -talks to the arduino outside the front door. Don't write straight to -this LCD; use frontDoorMessage for that. - -lcd is this wide -|-------------------| -22:05 85F in, 71F out - -pin 11 senses the door -pin 12 activates the front yard lights ('out yard') - -""" - -from __future__ import division - -import cyclone.web, json, traceback, os, sys -from twisted.python import log -from twisted.internet import reactor, task -from twisted.web.client import getPage -from rdflib import Namespace, Literal, URIRef - -sys.path.append("/my/proj/house/frontdoor") -from loggingserial import LoggingSerial - -sys.path.append("/my/proj/homeauto/lib") -from cycloneerr import PrettyErrorHandler - -sys.path.append("/my/site/magma") -from stategraph import StateGraph - -DEV = Namespace("http://projects.bigasterisk.com/device/") -ROOM = Namespace("http://projects.bigasterisk.com/room/") - -class Board(object): - """ - arduino board actions, plus the last values we wrote to it - """ - def __init__(self, port): - self.ser = LoggingSerial(port=port) - self.ser.flush() - - self.setLcd("") - self.setLcdBrightness(0) - self.setYardLight(0) - - def ping(self): - self.getDoor() - - def getDoor(self): - self.ser.write("\xff\x01") - ret = self.ser.readJson() - return ret['door'] - - def setYardLight(self, level): - self.currentYardLight = bool(level) - self.ser.write("\xff\x04" + chr(bool(self.currentYardLight))) - - def getYardLight(self): - return self.currentYardLight - - def getLcd(self): - return self.currentText - - def setLcd(self, txt): - """ - up to 8*21 chars - """ - self.currentText = txt - self.ser.write("\xff\x00" + txt + "\x00") - - def getLcdBrightness(self): - return self.currentBrightness - - def setLcdBrightness(self, b): - """b in 0 to 255""" - self.currentBrightness = b - self.ser.write("\xff\x03" + chr(b)) - - def getTemperature(self): - """returns parsed json from the board""" - self.ser.write("\xff\x02") - # this can take 1.25 seconds per retry - f = self.ser.readJson() - - if f['temp'] > 184 or f['temp'] < -100: - # this fails a lot, maybe 50% of the time. retry if - # you want - raise ValueError("out of range temp value (%s)" % f) - return f - -class index(PrettyErrorHandler, cyclone.web.RequestHandler): - def get(self): - self.settings.board.ping() - - self.set_header("Content-Type", "application/xhtml+xml") - self.write(open("index.html").read()) - -class GraphResource(PrettyErrorHandler, cyclone.web.RequestHandler): - def get(self): - g = StateGraph(ctx=DEV['frontDoorArduino']) - - board = self.settings.board - g.add((DEV['frontDoorOpen'], ROOM['state'], - ROOM['open'] if board.getDoor() == 'open' else ROOM['closed'])) - g.add((DEV['frontYardLight'], ROOM['state'], - ROOM['on'] if board.getYardLight() else ROOM['off'])) - g.add((DEV['frontDoorLcd'], ROOM['text'], - Literal(board.getLcd()))) - g.add((DEV['frontDoorLcd'], ROOM['brightness'], - Literal(board.getLcdBrightness()))) - - # not temperature yet because it's slow and should be cached from - # the last poll - - self.set_header('Content-type', 'application/x-trig') - self.write(g.asTrig()) - -class Lcd(PrettyErrorHandler, cyclone.web.RequestHandler): - def get(self): - self.set_header("Content-Type", "text/plain") - self.write(self.settings.board.getLcd()) - - def put(self): - self.settings.board.setLcd(self.request.body) - self.set_status(204) - -class Backlight(PrettyErrorHandler, cyclone.web.RequestHandler): - def get(self): - self.set_header("Content-Type", "application/json") - self.write(json.dumps({ - "backlight" : self.settings.board.getLcdBrightness()})) - - def put(self): - """param brightness=0 to brightness=255""" - self.settings.board.setLcdBrightness( - int(self.get_argument('brightness'))) - self.write("ok") - post = put - - -class YardLight(PrettyErrorHandler, cyclone.web.RequestHandler): - def get(self): - self.set_header("Content-Type", "application/json") - self.write(json.dumps({ - "yardLight" : self.settings.board.getYardLight()})) - - def put(self): - """text true or false or 0 or 1""" - self.settings.board.setYardLight( - self.request.body.strip() in ['true', '1']) - self.write("ok") - post = put - - -class Door(PrettyErrorHandler, cyclone.web.RequestHandler): - def get(self): - self.set_header("Content-Type", "text/plain") - self.write(self.settings.board.getDoor()) - -class Temperature(PrettyErrorHandler, cyclone.web.RequestHandler): - def get(self): - f = self.settings.board.getTemperature() - self.set_header("Content-Type", "application/json") - self.write(f) - -class Application(cyclone.web.Application): - def __init__(self, board): - handlers = [ - (r"/", index), - (r"/graph", GraphResource), - (r'/lcd', Lcd), - (r'/door', Door), - (r'/temperature', Temperature), - (r'/lcd/backlight', Backlight), - (r'/yardLight', YardLight), - ] - settings = {"board" : board} - cyclone.web.Application.__init__(self, handlers, **settings) - - -class Poller(object): - def __init__(self, board, postUrl, boardName): - self.board = board - self.postUrl = postUrl - self.boardName = boardName - self.last = None - - def poll(self): - try: - # this should be fetching everything and pinging reasoning - # if anything is new - new = self.board.getDoor() - if new != self.last: - msg = json.dumps(dict(board=self.boardName, - name="frontDoor", state=new)) - getPage(self.postUrl, - method="POST", - postdata=msg, - headers={'Content-Type' : 'application/json'} - ).addErrback(self.reportError, msg) - - self.last = new - except (IOError, OSError): - os.abort() - except Exception, e: - print "poll error", e - traceback.print_exc() - - def reportError(self, msg, *args): - print "post error", msg, args - -if __name__ == '__main__': - - config = { # to be read from a file - 'arduinoPort': '/dev/serial/by-id/usb-FTDI_FT232R_USB_UART_A6004bUG-if00-port0', - 'servePort' : 9080, - 'pollFrequency' : 1, - 'boardName' : 'frontDoor', # gets sent with updates - 'doorChangePost' : 'http://bang.bigasterisk.com:9069/inputChange', - # todo: need options to preset inputs/outputs at startup - } - - #log.startLogging(sys.stdout) - - board = Board(port=config['arduinoPort']) - - p = Poller(board, config['doorChangePost'], config['boardName']) - task.LoopingCall(p.poll).start(1/config['pollFrequency']) - reactor.listenTCP(config['servePort'], Application(board)) - reactor.run()
--- a/service/frontDoorArduino/index.html Tue Dec 11 12:31:18 2018 -0800 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,114 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" -"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> - <head> - <title>front door</title> - <link rel="Stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.0/themes/ui-lightness/jquery-ui.css" media="all"/> - <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script> - <style type="text/css" media="all"> - /* <![CDATA[ */ - #message, #lastLine { -background: #C5F180; color: #0A08A2; font-weight: bold; -font-family: monospace; -} -section { - background: none repeat scroll 0 0 #E1E1DF; - border: 1px solid #595555; - float: left; - margin: 5px; - padding: 10px; -} - /* ]]> */ -</style> - <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script> - </head> - <body> - <section> - <h1>lcd</h1> - <div> - set message: - <div> - <textarea cols="21" rows="7" id="message"/> - </div> - </div> - <div> - backlight: - <div id="backlightSlider" style="width: 300px;"/> - </div> - </section> - <section> - <h1>temperature</h1> - <div>Current: <span id="temperature"/> - <button id="getTemperature">refresh</button> - </div> - </section> - <section> - <h1>door</h1> - <div>Current: <span id="door"/> - <button id="getDoor">refresh</button> - </div> - </section> - <section> - <h1>yard light</h1> - <div>Current: <span id="yardLight"/> - <button id="toggleYardLight">toggle</button> - </div> - </section> - - <script type="text/javascript"> - // <![CDATA[ - $(function () { - - $.get("lcd", function (data){ $("#message").val(data) }); - $("#message").keyup(function() { - $.ajax({ - type: "PUT", - url: "lcd", - data: $("#message").val() - }); - }); - - $.getJSON("lcd/backlight", function (data) { - $("#backlightSlider").slider({value: data.backlight}); - }); - $("#backlightSlider").slider({ - min: 0, max: 255, - slide: function (ev, ui) { - $.post("lcd/backlight", {brightness: ui.value}); - }}); - - function getTemperature() { - $.get("temperature", function (data) { - $("#temperature").text(data); - }); - } - getTemperature(); - $("#getTemperature").click(getTemperature); - - function getDoor() { - $.get("door", function (x) { $("#door").text(x) }); - } - getDoor(); - $("#getDoor").click(getDoor); - - function refreshYardLight() { - $.getJSON("yardLight", function (data) { - $("#yardLight").text(data.yardLight); - }); - } - refreshYardLight(); - $("#toggleYardLight").click(function () { - $.getJSON("yardLight", function (data) { - $.ajax({ - type: "PUT", - url: "yardLight", - data: JSON.stringify(!data.yardLight), - success: refreshYardLight - }); - }); - }); - }); - // ]]> -</script> - </body> -</html>