# HG changeset patch # User drewp # Date 1555841356 25200 # Node ID 03591ffd08f40b11df40b4d12ea0a182861ba879 # Parent 2ffffcc7d0a4d9369bb5daca78aaf42ebe4cbf9a rm old code for arduino that drove shiftbrite leds and read barcords. plus, a program to generate barcodes for music tracks so they can be scanned Ignore-this: f379b105a8eb2596c9e3b6cfd1855d79 darcs-hash:47105a95de327af43ae9530f7ee11c5a562c00c1 diff -r 2ffffcc7d0a4 -r 03591ffd08f4 service/starArduino/BCS-84.pdf Binary file service/starArduino/BCS-84.pdf has changed diff -r 2ffffcc7d0a4 -r 03591ffd08f4 service/starArduino/barcode.css --- a/service/starArduino/barcode.css Sun Apr 21 03:08:43 2019 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,63 +0,0 @@ -body { - width: 8.5in; - margin: 1in 1in; -font-family: sans-serif; -font-size: 10pt; -} - -.card { - border: 1pt solid black; - height: 2.472in; - overflow: hidden; - width: 4in; - - position: relative; - float:left; - margin: 0 0.2in 0.2in 0; - -} - -.pgbr { - clear: both; - height: 0.5in; - page-break-after: always; -} - -.bc { - height: 140px; - left: 0.6in; - margin-left: auto; - margin-right: auto; - margin-top: 0.05in; - overflow: hidden; - position: absolute; - top: 0.6in; - width: 250px; - z-index: 0; -} - -.artist { - border-color: gray; - border-style: solid; - border-width: 0 1pt 1pt 0; - display: inline; - font-size: 18pt; - margin: 0; - padding: 0 5pt; -} - -.album { - margin: 0; - padding: 5pt; - height: 0.6in; - font-size: 14pt; - position: relative; - z-index: 2; -} - -.song { - left: 0.1in; - position: absolute; - top: 2.2in; - font-size: 14pt; -} \ No newline at end of file diff -r 2ffffcc7d0a4 -r 03591ffd08f4 service/starArduino/barcodePlayer.py --- a/service/starArduino/barcodePlayer.py Sun Apr 21 03:08:43 2019 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,52 +0,0 @@ -#!bin/python -""" -receives POSTs about barcodes that are scanned, plays songs on mpd -""" - -from __future__ import division - -import cyclone.web, cyclone.httpclient, sys, json, urllib -from twisted.python import log as twlog -from twisted.internet import reactor -from twisted.internet.defer import inlineCallbacks -sys.path.append("/my/proj/homeauto/lib") -from cycloneerr import PrettyErrorHandler -from logsetup import log - -from pymongo import Connection -mpdPaths = Connection("bang", 27017)['barcodePlayer']['mpdPaths'] - -class Index(PrettyErrorHandler, cyclone.web.RequestHandler): - def get(self): - self.write("barcode player. POST to /barcodeScan") - -class BarcodeScan(PrettyErrorHandler, cyclone.web.RequestHandler): - @inlineCallbacks - def post(self): - code = json.loads(self.request.body) - - if not code['code'].startswith("music "): - raise ValueError("this service only knows music barcodes, not %r" % - code) - - rows = list(mpdPaths.find({'_id' : int(code['code'].split()[1])})) - if not rows: - raise ValueError("code %r unknown" % code) - - song = rows[0]['mpdPath'] - - post = "http://star:9009/addAndPlay/%s" % urllib.quote(song, safe='') - result = (yield cyclone.httpclient.fetch( - method="POST", url=post)).body - log.info("post result: %r", result) - self.write(result) - - -if __name__ == '__main__': - app = cyclone.web.Application([ - (r'/', Index), - (r'/barcodeScan', BarcodeScan), - ], ) - twlog.startLogging(sys.stdout) - reactor.listenTCP(9011, app) - reactor.run() diff -r 2ffffcc7d0a4 -r 03591ffd08f4 service/starArduino/makeBarcodes.py --- a/service/starArduino/makeBarcodes.py Sun Apr 21 03:08:43 2019 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,97 +0,0 @@ -import os, re -from subprocess import check_call -from tempfile import NamedTemporaryFile -from pymongo import Connection - -def makeCode(s): - #return 'code' - psFile = NamedTemporaryFile(suffix='.ps') - check_call(['barcode', - '-b', s, - '-E', - '-o', psFile.name]) - svgFile = NamedTemporaryFile(suffix='.svg') - check_call(['pstoedit', - '-f', 'plot-svg', - '-yshift', '580', - '-xshift', '20', - psFile.name, svgFile.name]) - lines = open(svgFile.name).readlines() - return ''.join(lines[2:]) - -def codeElem(s): - return '
%s
' % makeCode(s) - -mpdPaths = Connection("bang", 27017)['barcodePlayer']['mpdPaths'] -# {mpdPath:"music/path/to/album/or/song", "_id":12} -mpdPaths.ensure_index([('mpdPath', 1)]) -def idForMpdPath(p): - match = mpdPaths.find_one({"mpdPath" : p}) - if match: - return match['_id'] - - top = list(mpdPaths.find().sort([('_id', -1)]).limit(1)) - newId = top[0]['_id'] + 1 if top else 0 - mpdPaths.insert({"mpdPath" : p, "_id" : newId}) - return newId - - -out = open("out.xhtml", "w") -out.write(""" - - - - barcodes - - - -
-""") - - -mpdRoot = "/my/music" - -paths = open("mpdPaths.txt").read().strip().splitlines() - -cardsSeen = 0 -for path in paths: - if os.path.isdir(os.path.join(mpdRoot, path)): - albumDir = path.split('/')[-1] - songFile = None - else: - albumDir, songFile = path.split('/')[-2:] - - if '-' in albumDir: - artistName, albumName = albumDir.replace('_', ' ').split('-', 1) - else: - artistName, albumName = '', albumDir - - if artistName in ['', 'Original Soundtrack', 'Various']: - artistName = albumName - albumName = '' - - if songFile: - songName = re.sub(r'(^\d+\.)|(^\d+\s*-)', '', songFile) - songName = songName.rsplit('.',1)[0].replace('_', ' ') - - out.write('
') - out.write('
%s
' % artistName) - out.write('
%s
' % albumName) - - print (albumName, songName if songFile else '') - out.write(codeElem("music %s" % idForMpdPath(path))) - - if songFile: - out.write('
%s
' % songName) - - out.write('
') - cardsSeen += 1 - if cardsSeen % 8 == 0: - out.write('
') - -out.write(""" -
- - -""") diff -r 2ffffcc7d0a4 -r 03591ffd08f4 service/starArduino/sample-barcode.svg --- a/service/starArduino/sample-barcode.svg Sun Apr 21 03:08:43 2019 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,341 +0,0 @@ - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - music 12516 - - - - - Fiddle-de-dee - Kindermusik - - - diff -r 2ffffcc7d0a4 -r 03591ffd08f4 service/starArduino/star/star.pde --- a/service/starArduino/star/star.pde Sun Apr 21 03:08:43 2019 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,241 +0,0 @@ -/* -board is like diecimila with atmega168 - -*/ -#include -int datapin = 10; // DI -int latchpin = 11; // LI -int enablepin = 12; // EI -int clockpin = 13; // CI - -unsigned long SB_CommandPacket; -int SB_CommandMode; -int SB_BlueCommand; -int SB_RedCommand; -int SB_GreenCommand; - -#define MAXCHANS 16 -int vals[MAXCHANS * 3]; - -int addr = 0; // which vals element to set next -int currentChans = MAXCHANS; - -unsigned char rotation = 0; // position of knob -unsigned char lastRotPosition = 0; // 2*A+1*B - -#define TEMP_ENABLED 1 - -#if TEMP_ENABLED -#include -#include - -OneWire oneWire(4); // digital IO 4 -DallasTemperature sensors(&oneWire); -DeviceAddress tempSensorAddress; -#endif - -/* -barcode red: +5V -barcode white: gnd - */ -SoftwareSerial barcode = SoftwareSerial(/* rx pin, green */ 3, - /* tx pin, black */ 2, - /* inverse */ true); - -void shiftOutLocal(uint8_t dataPin, uint8_t clockPin, byte val) -{ - int i; - - for (i = 0; i < 8; i++) { - digitalWrite(dataPin, !!(val & (1 << (7 - i)))); - - digitalWrite(clockPin, HIGH); - digitalWrite(clockPin, LOW); - } -} - -void SB_SendPacket() { - SB_CommandPacket = SB_CommandMode & B11; - SB_CommandPacket = (SB_CommandPacket << 10) | (SB_BlueCommand & 1023); - SB_CommandPacket = (SB_CommandPacket << 10) | (SB_RedCommand & 1023); - SB_CommandPacket = (SB_CommandPacket << 10) | (SB_GreenCommand & 1023); - - shiftOutLocal(datapin, clockpin, SB_CommandPacket >> 24); - shiftOutLocal(datapin, clockpin, SB_CommandPacket >> 16); - shiftOutLocal(datapin, clockpin, SB_CommandPacket >> 8); - shiftOutLocal(datapin, clockpin, SB_CommandPacket); - -} -void latch() { - delayMicroseconds(100); - digitalWrite(latchpin,HIGH); // latch data into registers - delayMicroseconds(100); - digitalWrite(latchpin,LOW); -} -void refresh() { - /* send all pixels */ - SB_CommandMode = B00; - for (int pixel=0; pixel < currentChans; pixel++) { - SB_RedCommand = vals[pixel * 3 + 0]; - SB_GreenCommand = vals[pixel * 3 + 1]; - SB_BlueCommand = vals[pixel * 3 + 2]; - SB_SendPacket(); - } - latch(); -} -#define F 1023 -#define PIXEL(i, r, g, b) { vals[i*3+0] = r; vals[i*3+1] = g; vals[i*3+2] = b; } - -void setCurrent(unsigned char r, unsigned char g, unsigned char b) { - /* 127 = max */ - SB_CommandMode = B01; // Write to current control registers - SB_RedCommand = r; - SB_GreenCommand = g; - SB_BlueCommand = b; - SB_SendPacket(); - latch(); -} -void setup() { - pinMode(datapin, OUTPUT); - pinMode(latchpin, OUTPUT); - pinMode(enablepin, OUTPUT); - pinMode(clockpin, OUTPUT); - - digitalWrite(latchpin, LOW); - digitalWrite(enablepin, LOW); - - for (int i=0; i < MAXCHANS; i++) { - setCurrent(127, 127, 127); - } - - PIXEL(0, F, 0, 0); - PIXEL(1, 0, F, 0); - PIXEL(2, 0, 0, F); - PIXEL(3, F, F, 0); - PIXEL(4, 0, F, F); - refresh(); - -#if TEMP_ENABLED - sensors.begin(); - sensors.getAddress(tempSensorAddress, 0); - sensors.setResolution(tempSensorAddress, 12); -#endif - - Serial.begin(9600); - Serial.flush(); - - pinMode(5, INPUT); - pinMode(6, INPUT); - pinMode(7, INPUT); - pinMode(8, INPUT); - pinMode(9, INPUT); - digitalWrite(6, HIGH); - digitalWrite(8, HIGH); - digitalWrite(9, HIGH); - - - barcode.begin(1200); - digitalWrite(2, 0); // inverse logic: don't hold this high - - /* - barcode.write("\x1b\x42\x0d"); // blink - */ - /* - barcode.write("\x1b\x46\x0d"); // off - */ -} - -void loop() { - /* - send 0xff, - then a byte for the number of channels you're going to send, - then nchans*3 bytes of r-g-b levels from 0x00-0xfe. - - second byte 0xfe means to return temp in F, followed by \n - second byte 0xfd means to return a line describing the state of buttons - second byte 0xfc means to beep the barcode scanner - second byte 0xfb means to fetch any recent scanned barcode - */ - - unsigned char curPos = (digitalRead(8) << 1) | digitalRead(9); - - if (curPos == 0 && lastRotPosition == 2) { rotation--; } - if (curPos == 0 && lastRotPosition == 1) { rotation++; } - if (curPos == 1 && lastRotPosition == 0) { rotation--; } - if (curPos == 1 && lastRotPosition == 3) { rotation++; } - if (curPos == 3 && lastRotPosition == 1) { rotation--; } - if (curPos == 3 && lastRotPosition == 2) { rotation++; } - if (curPos == 2 && lastRotPosition == 3) { rotation--; } - if (curPos == 2 && lastRotPosition == 0) { rotation++; } - - lastRotPosition = curPos; - - int inb = Serial.read(); - if (inb == -1) { - return; - } - if (inb == 0xff) { - addr = -1; - return; - } - if (addr == -1) { - if (inb == 0xfe) { -#if TEMP_ENABLED - sensors.requestTemperatures(); - float tempF = sensors.getTempF(tempSensorAddress); - Serial.print(tempF); - Serial.print("\n"); -#endif - addr = -1; - return; - } - if (inb == 0xfb) { - if (barcode.available() < 1) { - Serial.print("{\"barcode\":\"\"}\n"); - } else { - Serial.print("{\"barcode\":\""); - char last=1; - while (barcode.available() > 0) { - last = barcode.read(); - Serial.print((int)last); - Serial.print(" "); - } - Serial.print("\"}\n"); - } - return; - } - if (inb == 0xfc) { - barcode.write("\x1b\x54\x0d");// beep - barcode.write("\x1b\x3f\x0d"); // requisition - Serial.print("{\"ok\":1}\n"); - } - - if (inb == 0xfd) { - // read ariremote buttons, where some buttons are combined on - // the same pins - digitalWrite(5, HIGH); Serial.print(digitalRead(5)); - Serial.print(" "); - digitalWrite(5, LOW); Serial.print(!digitalRead(5)); - Serial.print(" "); - digitalWrite(7, HIGH); Serial.print(digitalRead(7)); - Serial.print(" "); - digitalWrite(7, LOW); Serial.print(!digitalRead(7)); - Serial.print(" "); - Serial.print(!digitalRead(6)); - Serial.print(" "); - Serial.print((int)rotation); - Serial.print("\n"); - } - currentChans = inb; - addr = 0; - return; - } - - vals[addr] = inb * 4; // SB levels are 10-bit. log scale might be better - addr ++; - if (addr >= currentChans * 3) { - refresh(); - addr = 0; - } - -} diff -r 2ffffcc7d0a4 -r 03591ffd08f4 service/starArduino/starArduino.py --- a/service/starArduino/starArduino.py Sun Apr 21 03:08:43 2019 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,143 +0,0 @@ -""" -arduino driver for the nightlight+buttons+temp setup running on star - -""" -from __future__ import division - -import sys,json -from twisted.internet import reactor, task -from rdflib import Namespace -import cyclone.web -from cyclone.httpclient import fetch - -sys.path.append("/my/proj/pixel/shiftweb") -from drvarduino import ShiftbriteArduino -from shiftweb import hexFromRgb, rgbFromHex - -sys.path.append("/my/proj/homeauto/lib") -from cycloneerr import PrettyErrorHandler -from logsetup import log - -sys.path.append("/my/proj/ariremote") -from oscserver import ArduinoWatcher -ROOM = Namespace("http://projects.bigasterisk.com/room/") - - -class Index(PrettyErrorHandler, cyclone.web.RequestHandler): - def get(self): - self.settings.arduino.ping() - - self.set_header("Content-Type", "application/xhtml+xml") - self.write(open("index.html").read()) - -class Temperature(PrettyErrorHandler, cyclone.web.RequestHandler): - def get(self): - f = self.settings.arduino.getTemperature() - self.set_header("Content-Type", "application/json") - self.write(json.dumps({"temp" : f})) - -class Brite(PrettyErrorHandler, cyclone.web.RequestHandler): - def get(self, pos): - self.set_header("Content-Type", "text/plain") - self.write(hexFromRgb(self.settings.colors[int(pos)])) - - def put(self, pos): - channel = int(pos) - colors = self.settings.colors - colors[channel] = rgbFromHex(self.request.body) - self.settings.arduino.update(colors) - self.set_header("Content-Type", "text/plain") - self.write("updated %r" % colors) - -class Barcode(PrettyErrorHandler, cyclone.web.RequestHandler): - def get(self): - self.set_header("Content-Type", "text/plain") - ard = self.settings.arduino - ard.ser.write("\x60\x02") - self.write(str(ard.readJson())) - -class BarcodeBeep(PrettyErrorHandler, cyclone.web.RequestHandler): - def put(self): - self.set_header("Content-Type", "text/plain") - ard = self.settings.arduino - ard.ser.write("\x60\x03") - self.write(str(ard.readJson())) - -def barcodeWatch(arduino, postBarcode): - arduino.ser.write("\xff\xfb") - ret = arduino.readJson() - if not ret['barcode']: - return - if ret['barcode'] == "27 80 48 13 ": - return # scanner's beep response - - arduino.ser.write("\xff\xfc") - arduino.readJson() # my beep response - s = ''.join(chr(int(x)) for x in ret['barcode'].split()) - for code in s.split('\x02'): - if not code: - continue - if not code.endswith('\x03'): - log.warn("couldn't read %r", code) - return - codeType = {'A':'UPC-A', - 'B':'JAN-8', - 'E':'UPC-E', - 'N':'NW-7', - 'C':'CODE39', - 'I':'ITF', - 'K':'CODE128', - }[code[0]] - code = code[1:-1] - body = "%s %s %s ." % ( - ROOM['barcodeScan'].n3(), - ROOM['read'].n3(), - ROOM['barcode/%s/%s' % (codeType, code)].n3()) - body = body.encode('utf8') - print "body: %r" % body - fetch("http://bang:9071/oneShot", - method='POST', - timeout=1, - postdata=body, - headers={"content-type" : ["text/n3"]}, - ).addErrback(log.error) - -class Graph(PrettyErrorHandler, cyclone.web.RequestHandler): - def get(self): - raise NotImplementedError - -if __name__ == '__main__': - class A(ShiftbriteArduino): - # from loggingserial.py - def readJson(self): - line = '' - while True: - c = self.ser.read(1) - #print "gotchar", repr(c) - if c: - line += c - if c == "\n": - break - else: - raise ValueError("timed out waiting for chars") - return json.loads(line) - - sb = A(numChannels=3) - - colors = [(0,0,0)] * sb.numChannels - - aw = ArduinoWatcher(sb) - task.LoopingCall(aw.poll).start(1.0/20) - - postBarcode = 'http://star:9011/barcodeScan' - task.LoopingCall(barcodeWatch, sb, postBarcode).start(interval=.5) - - reactor.listenTCP(9014, cyclone.web.Application([ - (r'/', Index), - (r'/temperature', Temperature), - (r'/brite/(\d+)', Brite), - (r'/barcode', Barcode), - (r'/barcode/beep', BarcodeBeep), - (r'/graph', Graph), - ], arduino=sb, colors=colors)) - reactor.run()