def __init__(self, port): self.ser = LoggingSerial(port=port) self.ser.flush() self.setLcd("") self.setLcdBrightness(0) self.setYardLight(0)
class ArduinoDesk(object): def __init__(self, ports=['/dev/serial/by-id/usb-FTDI_FT232R_USB_UART_A900gbcG-if00-port0']): self.ser = LoggingSerial(ports=ports, baudrate=115200, timeout=1) def ping(self): self.ser.write("\x60\x00") msg = self.ser.readJson() assert msg == {"ok":"ping"}, msg def shiftbrite(self, colors): """ shift out this sequence of (r,g,b) triples of 10-bit ints """ out = "".join(bitstring.pack("0b00, uint:10, uint:10, uint:10", b, r, g).bytes for r,g,b in colors) self.ser.write("\x60\x01" + chr(len(out)) + out) msg = self.ser.readJson() assert msg == {"ok":1}, msg
class Board(object): """an arduino connected to this computer""" baudrate = 115200 def __init__(self, dev, configGraph, masterGraph, uri): """ each connected thing has some pins. """ self.uri = uri self.configGraph = configGraph self.masterGraph = masterGraph self.dev = dev self.masterGraph.patch(Patch(addQuads=self.staticStmts())) # The order of this list needs to be consistent between the # deployToArduino call and the poll call. self._devs = devices.makeDevices(configGraph, self.uri) self._devCommandNum = dict((dev.uri, ACTION_BASE + devIndex) for devIndex, dev in enumerate(self._devs)) self._polledDevs = [d for d in self._devs if d.generatePollCode()] self._statementsFromInputs = {} # input device uri: latest statements self._lastPollTime = {} # input device uri: time() self._influx = InfluxExporter(self.configGraph) self.open() for d in self._devs: self.syncMasterGraphToHostStatements(d) def description(self): """for web page""" return { 'uri': self.uri, 'dev': self.dev, 'baudrate': self.baudrate, 'devices': [d.description() for d in self._devs], } def open(self): self.ser = LoggingSerial(port=self.dev, baudrate=self.baudrate, timeout=2) def startPolling(self, period=.5): task.LoopingCall(self._poll).start(period) def _poll(self): """ even boards with no inputs need some polling to see if they're still ok """ try: self._pollWork() except serial.SerialException: reactor.crash() raise except Exception as e: import traceback; traceback.print_exc() log.warn("poll: %r" % e) def _pollWork(self): t1 = time.time() self.ser.write("\x60\x00") # "poll everything" for i in self._polledDevs: try: now = time.time() new = i.readFromPoll(self.ser.read) if isinstance(new, dict): # new style oneshot = new['oneshot'] new = new['latest'] else: oneshot = None prev = self._statementsFromInputs.get(i.uri, []) if new or prev: self._statementsFromInputs[i.uri] = new # it's important that quads from different devices # don't clash, since that can lead to inconsistent # patches (e.g. # dev1 changes value from 1 to 2; # dev2 changes value from 2 to 3; # dev1 changes from 2 to 4 but this patch will # fail since the '2' statement is gone) self.masterGraph.patch(Patch.fromDiff(inContext(prev, i.uri), inContext(new, i.uri))) if oneshot: self._sendOneshot(oneshot) self._lastPollTime[i.uri] = now except: log.warn('while polling %r:', i.uri) raise #plus statements about succeeding or erroring on the last poll byte = self.ser.read(1) if byte != 'x': raise ValueError("after poll, got %x instead of 'x'" % byte) elapsed = time.time() - t1 if elapsed > 1.0: log.warn('poll took %.1f seconds' % elapsed) stmts = set() for v in self._statementsFromInputs.values(): stmts.update(v) self._influx.exportToInflux(stmts) def _sendOneshot(self, oneshot): body = (' '.join('%s %s %s .' % (s.n3(), p.n3(), o.n3()) for s,p,o in oneshot)).encode('utf8') bang6 = 'fcb8:4119:fb46:96f8:8b07:1260:0f50:fcfa' fetch(method='POST', url='http://[%s]:9071/oneShot' % bang6, headers={'Content-Type': ['text/n3']}, postdata=body, timeout=5) def outputStatements(self, stmts): unused = set(stmts) for dev in self._devs: stmtsForDev = [] for pat in dev.outputPatterns(): if [term is None for term in pat] != [False, False, True]: raise NotImplementedError for stmt in stmts: if stmt[:2] == pat[:2]: stmtsForDev.append(stmt) unused.discard(stmt) if stmtsForDev: log.info("output goes to action handler for %s" % dev.uri) self.ser.write("\x60" + chr(self._devCommandNum[dev.uri])) dev.sendOutput(stmtsForDev, self.ser.write, self.ser.read) if self.ser.read(1) != 'k': raise ValueError( "%s sendOutput/generateActionCode didn't use " "matching output bytes" % dev.__class__) # Dev *could* change hostStatements at any time, and # we're not currently tracking that, but the usual is # to change them in response to sendOutput so this # should be good enough. The right answer is to give # each dev the masterGraph for it to write to. self.syncMasterGraphToHostStatements(dev) log.info("output and masterGraph sync complete") if unused: log.info("Board %s doesn't care about these statements:", self.uri) for s in unused: log.warn("%r", s) def syncMasterGraphToHostStatements(self, dev): hostStmtCtx = URIRef(dev.uri + '/host') newQuads = inContext(dev.hostStatements(), hostStmtCtx) p = self.masterGraph.patchSubgraph(hostStmtCtx, newQuads) log.debug("patch master with these host stmts %s", p) def staticStmts(self): return [(HOST[hostname], ROOM['connectedTo'], self.uri, CTX)] def generateArduinoCode(self): code = write_arduino_code.writeCode(self.baudrate, self._devs, self._devCommandNum) code = write_arduino_code.indent(code) cksum = hashlib.sha1(code).hexdigest() code = code.replace('CODE_CHECKSUM', cksum) return code, cksum def _readBoardChecksum(self, length): # this is likely right after reset, so it might take 2 seconds for tries in range(6): self.ser.write("\x60\x01") try: return self.ser.read(length) except ValueError: if tries == 5: raise time.sleep(.5) raise ValueError def _boardIsCurrent(self, currentChecksum): try: boardCksum = self._readBoardChecksum(len(currentChecksum)) if boardCksum == currentChecksum: log.info("board has current code (%s)" % currentChecksum) return True else: log.info("board responds with incorrect code version") except Exception as e: log.info("can't get code version from board: %r" % e) return False def deployToArduino(self): code, cksum = self.generateArduinoCode() if self._boardIsCurrent(cksum): return try: if hasattr(self, 'ser'): self.ser.close() workDir = tempfile.mkdtemp(prefix='arduinoNode_board_deploy') try: self._arduinoMake(workDir, code) finally: shutil.rmtree(workDir) finally: self.open() def _arduinoMake(self, workDir, code): with open(workDir + '/makefile', 'w') as makefile: makefile.write(write_arduino_code.writeMakefile( dev=self.dev, tag=self.configGraph.value(self.uri, ROOM['boardTag']), allLibs=sum((d.generateArduinoLibs() for d in self._devs), []))) with open(workDir + '/main.ino', 'w') as main: main.write(code) subprocess.check_call(['make', 'upload'], cwd=workDir) def currentGraph(self): g = Graph() for dev in self._devs: for stmt in dev.hostStatements(): g.add(stmt) return g
def open(self): self.ser = LoggingSerial(port=self.dev, baudrate=self.baudrate, timeout=2)
def __init__(self, port='/dev/ttyACM0'): self.ser = LoggingSerial(port=port, baudrate=115200, timeout=1) time.sleep(2) # wait for a arduino reset to pass self.ser.flush() self.ping()
class ArduinoGarage(object): def __init__(self, port='/dev/ttyACM0'): self.ser = LoggingSerial(port=port, baudrate=115200, timeout=1) time.sleep(2) # wait for a arduino reset to pass self.ser.flush() self.ping() def ping(self): self.ser.write("\x60\x00\x00") msg = self.ser.readJson() assert msg == {"ok":True}, msg def poll(self): self.ser.write("\x60\x01\x00") ret = self.ser.readJson() return ret def lastLevel(self): self.ser.write("\x60\x02\x00") return self.ser.readJson()['z'] def setThreshold(self, t): """set 10-bit threshold""" self.ser.write("\x60\x03"+chr(max(1 << 2, t) >> 2)) return self.ser.readJson()['threshold'] def setGarage(self, level): """set garage door opener pin""" self.ser.write("\x60\x04"+chr(int(bool(level)))) return self.ser.readJson()['garage'] def setVideoSelect(self, chan): """set video select bits from 0..3""" self.ser.write("\x60\x05"+chr(chan)) return self.ser.readJson()['videoSelect'] def shiftbrite(self, colors): """ shift out this sequence of (r,g,b) triples of 10-bit ints """ resetCurrent = "".join(bitstring.pack("0b01, uint:10, uint:10, uint:10", 127, 127, 127).bytes for loop in range(len(colors))) out = "".join(bitstring.pack("0b00, uint:10, uint:10, uint:10", b, r, g).bytes for r,g,b in colors) out = resetCurrent + out self.ser.write("\x60\x06" + chr(len(out)) + out) msg = self.ser.readJson() assert msg == {"ok":1}, msg def virtualwire(self, colors): """ send this sequence of (r,g,b) 8-bit triples """ numLeds = 4 # vw receiver wants data for all leds every time colors = (list(colors) + [(0,0,0)] * numLeds)[:numLeds] msg = "".join("%s%s%s" % (chr(r), chr(g), chr(b)) for r,g,b in colors) self.ser.write("\x60\x07" + chr(len(msg)) + msg) msg = self.ser.readJson() assert msg == {"sent": 12}, msg
def __init__(self, port="/dev/ttyACM0"): self.ser = LoggingSerial(port=port, baudrate=115200, timeout=1) self.ser.flush()
class ArduinoBedroom(object): def __init__(self, port="/dev/ttyACM0"): self.ser = LoggingSerial(port=port, baudrate=115200, timeout=1) self.ser.flush() def ping(self): self.ser.write("\x60\x00\x00") msg = self.ser.readJson() assert msg == {"ok": True}, msg def poll(self): self.ser.write("\x60\x01\x00") ret = self.ser.readJson() ret["motion"] = int(ret["motion"] > 100) return ret def setSpeakerChoice(self, pillow): self.ser.write("\x60\x02" + chr(pillow)) return self.ser.readJson() def setLeds(self, colors): """ shift out this sequence of (r,g,b) triples of 10-bit ints The nearest led gets color[0], etc. """ resetCurrent = "".join( bitstring.pack("0b01, uint:10, uint:10, uint:10", 127, 127, 127).bytes for loop in range(len(colors)) ) out = "".join(bitstring.pack("0b00, uint:10, uint:10, uint:10", b, r, g).bytes for r, g, b in reversed(colors)) out = resetCurrent + out self.ser.write("\x60\x03" + chr(len(out)) + out) msg = self.ser.readJson() assert msg == {"ok": 1}, msg
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
def __init__(self, ports=['/dev/serial/by-id/usb-FTDI_FT232R_USB_UART_A900gbcG-if00-port0']): self.ser = LoggingSerial(ports=ports, baudrate=115200, timeout=1)
class Board(object): """an arduino connected to this computer""" baudrate = 115200 def __init__(self, dev, configGraph, masterGraph, uri): """ each connected thing has some pins. """ self.uri = uri self.configGraph = configGraph self.masterGraph = masterGraph self.dev = dev self.masterGraph.setToGraph(self.staticStmts()) # The order of this list needs to be consistent between the # deployToArduino call and the poll call. self._devs = devices.makeDevices(configGraph, self.uri) self._devCommandNum = dict((dev.uri, ACTION_BASE + devIndex) for devIndex, dev in enumerate(self._devs)) self._polledDevs = [d for d in self._devs if d.generatePollCode()] self._statementsFromInputs = {} # input device uri: latest statements self._lastPollTime = {} # input device uri: time() self._influx = InfluxExporter(self.configGraph) self.open() for d in self._devs: self.syncMasterGraphToHostStatements(d) def description(self): """for web page""" return { 'uri': self.uri, 'dev': self.dev, 'baudrate': self.baudrate, 'devices': [d.description() for d in self._devs], } def open(self): self.ser = LoggingSerial(port=self.dev, baudrate=self.baudrate, timeout=2) def startPolling(self, period=.5): task.LoopingCall(self._poll).start(period) def _poll(self): """ even boards with no inputs need some polling to see if they're still ok """ try: self._pollWork() except serial.SerialException: reactor.crash() raise except Exception as e: import traceback; traceback.print_exc() log.warn("poll: %r" % e) def _pollWork(self): t1 = time.time() self.ser.write("\x60\x00") # "poll everything" for i in self._polledDevs: with i._stats.poll.time(): try: now = time.time() new = i.readFromPoll(self.ser.read) if isinstance(new, dict): # new style oneshot = new['oneshot'] new = new['latest'] else: oneshot = None self._updateMasterWithNewPollStatements(i.uri, new) if oneshot: self._sendOneshot(oneshot) self._lastPollTime[i.uri] = now except: log.warn('while polling %r:', i.uri) raise #plus statements about succeeding or erroring on the last poll byte = self.ser.read(1) if byte != 'x': raise ValueError("after poll, got %x instead of 'x'" % byte) for i in self._devs: if i.wantIdleOutput(): self.ser.write("\x60" + chr(self._devCommandNum[i.uri])) i.outputIdle(self.ser.write) if self.ser.read(1) != 'k': raise ValueError('no ack after outputIdle') elapsed = time.time() - t1 if elapsed > 1.0: log.warn('poll took %.1f seconds' % elapsed) stmts = set() for v in self._statementsFromInputs.values(): stmts.update(v) self._influx.exportToInflux(stmts) def _updateMasterWithNewPollStatements(self, dev, new): prev = self._statementsFromInputs.get(dev, set()) # it's important that quads from different devices # don't clash, since that can lead to inconsistent # patches (e.g. # dev1 changes value from 1 to 2; # dev2 changes value from 2 to 3; # dev1 changes from 2 to 4 but this patch will # fail since the '2' statement is gone) self.masterGraph.patch(Patch.fromDiff(inContext(prev, dev), inContext(new, dev))) self._statementsFromInputs[dev] = new def _sendOneshot(self, oneshot): body = (' '.join('%s %s %s .' % (s.n3(), p.n3(), o.n3()) for s,p,o in oneshot)).encode('utf8') fetch(method='POST', url='http://bang6:9071/oneShot', headers={'Content-Type': ['text/n3']}, postdata=body, timeout=5) def outputStatements(self, stmts): unused = set(stmts) for dev in self._devs: stmtsForDev = [] for pat in dev.outputPatterns(): if [term is None for term in pat] != [False, False, True]: raise NotImplementedError for stmt in stmts: if stmt[:2] == pat[:2]: stmtsForDev.append(stmt) unused.discard(stmt) if stmtsForDev: log.info("output goes to action handler for %s" % dev.uri) with dev._stats.output.time(): self.ser.write("\x60" + chr(self._devCommandNum[dev.uri])) dev.sendOutput(stmtsForDev, self.ser.write, self.ser.read) if self.ser.read(1) != 'k': raise ValueError( "%s sendOutput/generateActionCode didn't use " "matching output bytes" % dev.__class__) # Dev *could* change hostStatements at any time, and # we're not currently tracking that, but the usual is # to change them in response to sendOutput so this # should be good enough. The right answer is to give # each dev the masterGraph for it to write to. self.syncMasterGraphToHostStatements(dev) log.info("output and masterGraph sync complete") if unused: log.info("Board %s doesn't care about these statements:", self.uri) for s in unused: log.info("%r", s) def syncMasterGraphToHostStatements(self, dev): hostStmtCtx = URIRef(dev.uri + '/host') newQuads = inContext(dev.hostStatements(), hostStmtCtx) p = self.masterGraph.patchSubgraph(hostStmtCtx, newQuads) log.debug("patch master with these host stmts %s", p) def staticStmts(self): return [(HOST[hostname], ROOM['connectedTo'], self.uri, CTX)] def generateArduinoCode(self): code = write_arduino_code.writeCode(self.baudrate, self._devs, self._devCommandNum) code = write_arduino_code.indent(code) cksum = hashlib.sha1(code).hexdigest() code = code.replace('CODE_CHECKSUM', cksum) return code, cksum def _readBoardChecksum(self, length): # this is likely right after reset, so it might take 2 seconds for tries in range(6): self.ser.write("\x60\x01") try: return self.ser.read(length) except ValueError: if tries == 5: raise time.sleep(.5) raise ValueError def _boardIsCurrent(self, currentChecksum): try: boardCksum = self._readBoardChecksum(len(currentChecksum)) if boardCksum == currentChecksum: log.info("board has current code (%s)" % currentChecksum) return True else: log.info("board responds with incorrect code version") except Exception as e: log.info("can't get code version from board: %r" % e) return False def deployToArduino(self): code, cksum = self.generateArduinoCode() if self._boardIsCurrent(cksum): return try: if hasattr(self, 'ser'): self.ser.close() workDir = tempfile.mkdtemp(prefix='arduinoNode_board_deploy') try: self._arduinoMake(workDir, code) finally: shutil.rmtree(workDir) finally: self.open() def _arduinoMake(self, workDir, code): with open(workDir + '/makefile', 'w') as makefile: makefile.write(write_arduino_code.writeMakefile( dev=self.dev, tag=self.configGraph.value(self.uri, ROOM['boardTag']), allLibs=sum((d.generateArduinoLibs() for d in self._devs), []))) with open(workDir + '/main.ino', 'w') as main: main.write(code) subprocess.check_call(['make', 'upload'], cwd=workDir) def currentGraph(self): g = Graph() for dev in self._devs: for stmt in dev.hostStatements(): g.add(stmt) return g