Esempio n. 1
0
    def poll(self):
        now = time.time()

        self.flushOldReads(now)

        try:
            for tag in self.reader.getTags(): # blocks for a bit
                uid = tag.uid()
                log.debug('detected tag uid=%r', uid)
                cardIdUri = uidUri(uid)

                is_new = cardIdUri not in self.log
                self.log[cardIdUri] = now
                if is_new:
                    STATS.newCardReads += 1
                    tag.connect()
                    try:
                        textLit = Literal(tag.readBlock(1).rstrip('\x00'))
                        if self.overwrite_any_tag and not looksLikeBigasterisk(textLit):
                            log.info("block 1 was %r; rewriting it", textLit)
                            tag.writeBlock(1, randomBody())
                            textLit = Literal(tag.readBlock(1).rstrip('\x00'))
                    finally:
                        # This might not be appropriate to call after
                        # readBlock fails. I am getting double
                        # exceptions.
                        tag.disconnect()
                    self.startCardRead(cardIdUri, textLit)
        except AuthFailedError as e:
            log.error(e)
        except (NfcError, OSError) as e:
            traceback.print_exc()
            log.error(e)
            reactor.stop()
Esempio n. 2
0
    def getCompleteTemps(self, maxTime=120):
        ret = {}
        tries = 0
        now = time.time()
        giveUp = now + maxTime

        self.requestTemps()
        sensors = set(self.allSensors())
        
        while now < giveUp:
            tries += 1
            ret.update(self.getTemps(sensors - set(ret.keys())))

            if len(ret) >= self.expectedSensors:
                log.info("after %s tries, temps=%s" % (tries, ret))
                break

            log.debug("..only have %s measurements; still trying for %d secs" %
                      (len(ret), giveUp - now))
            self.initOnewire()
            self.requestTemps()
            yield deferLater(reactor, .5, lambda: None)
            now = time.time()
        else:
            log.info("giving up after %s secs, only got %s measurements" %
                     (maxTime, len(ret)))
        returnValue(dict([(s.address,val) for s, val in ret.items()]))
Esempio n. 3
0
    def poll(self):
        now = time.time()

        self.flushOldReads(now)

        try:
            for tag in self.reader.getTags():  # blocks for a bit
                uid = tag.uid()
                log.debug('detected tag uid=%r', uid)
                cardIdUri = uidUri(uid)

                is_new = cardIdUri not in self.log
                self.log[cardIdUri] = now
                if is_new:
                    STATS.newCardReads += 1
                    tag.connect()
                    try:
                        textLit = Literal(tag.readBlock(1).rstrip('\x00'))
                        if self.overwrite_any_tag and not looksLikeBigasterisk(
                                textLit):
                            log.info("block 1 was %r; rewriting it", textLit)
                            tag.writeBlock(1, randomBody())
                            textLit = Literal(tag.readBlock(1).rstrip('\x00'))
                    finally:
                        # This might not be appropriate to call after
                        # readBlock fails. I am getting double
                        # exceptions.
                        tag.disconnect()
                    self.startCardRead(cardIdUri, textLit)
        except AuthFailedError as e:
            log.error(e)
        except (NfcError, OSError) as e:
            traceback.print_exc()
            log.error(e)
            reactor.stop()
Esempio n. 4
0
    def poll(self):
        log.debug("get devices")
        devs = deferToThread(getNearbyDevices)

        devs.addCallback(self.compare)
        devs.addErrback(log.error)
        return devs
Esempio n. 5
0
def getOk(url, timeout=1):
    """can we get a successful status from this url in a short time?"""
    log.debug("testing %s" % url)
    try:
        resp = yield getPage(url, timeout=timeout)
    except Exception, e:
        log.warn("getPage %s", e)
        returnValue(False)
Esempio n. 6
0
 def writeMsg(self, device, number, command, data=""):
     length = len(data)
     commandVal = getattr(Command, command)
     checksum = sum(x for x in [length, device, number, commandVal] +
                    [ord(x) for x in data]) & 0xff
     args = 0x80, 0x80, 0x80, length, device, number, commandVal, data, checksum
     log.debug("Sending: %s %r", command, args)
     self.ser.write(struct.pack("!BBBBBBBsB", *args))
Esempio n. 7
0
def haveDevice(usbId):
    try:
        log.debug("checking for %s", usbId)
        dev = hubDevice(usbId)
        # sometimes the dev will exist but fail to open
        open(dev, "r")
        return True
    except (ValueError, IOError):
        return False
Esempio n. 8
0
    def endCardRead(self, cardUri):
        log.debug(f'{cardUri} has been gone for {self.expireSecs} sec')
        delQuads = []
        for spo in self.masterGraph._graph.triples(
            (sensor, ROOM['reading'], cardUri)):
            delQuads.append(spo + (ctx, ))
        for spo in self.masterGraph._graph.triples(
            (cardUri, ROOM['cardText'], None)):
            delQuads.append(spo + (ctx, ))

        self.masterGraph.patch(Patch(addQuads=[], delQuads=delQuads))
Esempio n. 9
0
def getNearbyDevices():
    addrs = discover_devices()

    for a in addrs:
        if a not in nameCache:
            n = lookup_name(a) or lookupPastName(a)
            if n is not None:
                nameCache[a] = n

    log.debug("discover found %r", addrs)
    return addrs
Esempio n. 10
0
 def endCardRead(self, cardUri):
     log.debug(f'{cardUri} has been gone for {self.expireSecs} sec')
     delQuads = []
     for spo in self.masterGraph._graph.triples(
             (sensor, ROOM['reading'], cardUri)):
         delQuads.append(spo + (ctx,))
     for spo in self.masterGraph._graph.triples(
             (cardUri, ROOM['cardText'], None)):
         delQuads.append(spo + (ctx,))
         
     self.masterGraph.patch(Patch(addQuads=[], delQuads=delQuads))
Esempio n. 11
0
def resetDevice(dev):
    """
    send USBDEVFS_RESET to the given /dev address
    """
    d = Deferred()
    log.debug("resetting %s" % dev)
    f=os.open(dev, os.O_WRONLY)
    ret = fcntl.ioctl(f, USBDEVFS_RESET, 0)
    if ret != 0:
        raise ValueError("ioctl failed with %s" % ret)
    reactor.callLater(3, d.callback, None)
    return d
Esempio n. 12
0
 def doEntranceMusic(self, action):
     import restkit, jsonlib
     dt = self.deltaSinceLastArrive(action['name'])
     log.debug("dt=%s", dt)
     if dt > datetime.timedelta(hours=1):
         hub = restkit.Resource(
             # PSHB not working yet; "http://bang:9030/"
             "http://slash:9049/"
             )
         action = action.copy()
         del action['created']
         del action['_id']
         log.info("post to %s", hub)
         hub.post("visitorNet", payload=jsonlib.dumps(action))
Esempio n. 13
0
 def poll(self):
     try:
         watts = self.comm.requestNumeric(device=1, number=0,
                                          command="getPowerNow")
         self.carbon.send('system.house.solar.power_w', watts)
     except Sleeping:
         log.debug("sleeping")
     except ValueError:
         log.error(traceback.format_exc())
         self.reset()
     except Exception:
         traceback.print_exc()
         os.abort()
     self.lastPollTime = time.time()
Esempio n. 14
0
 def _sendUpdatePatch(self, handler=None):
     """
     send a patch event out this handler to bring it up to date with
     self.statements
     """
     # reduce loops here- prepare all patches at once
     for h in (self.handlers if handler is None else [handler]):
         p = self.statements.makeSyncPatch(h, self._sourcesForHandler(h))
         if not p.isNoop():
             log.debug("send patch %s to %s", p.shortSummary(), h)
             # This can be a giant line, which was a problem once. Might be 
             # nice for this service to try to break it up into multiple sends,
             # although there's no guarantee at all since any single stmt 
             # could be any length.
             h.sendEvent(message=jsonFromPatch(p), event='patch')
Esempio n. 15
0
 def getHttpTemps(self):
     ret = {}
     
     for url, name in [("http://star:9014/", "ariroom"),
                       ("http://slash:9080/", "frontDoor"),
                       ]:
         for tries in range(3):
             try:
                 res = restkit.Resource(url, timeout=5)
                 temp = json.loads(res.get("temperature").body_string(), 
                                   )['temp']
                 log.debug("got http temp %s = %r", name, temp)
                 ret[name] = temp
                 break
             except Exception, e:
                 log.warn(e)
Esempio n. 16
0
    def replaceSourceStatements(self, source, stmts):
        log.debug('replaceSourceStatements with %s stmts', len(stmts))
        newStmts = set(stmts)

        with self._postDeleteStatements() as garbage:
            for stmt, (sources, handlers) in self.statements.iteritems():
                if source in sources:
                    if stmt not in stmts:
                        sources.remove(source)
                        if not sources and not handlers:
                            garbage.add(stmt)
                else:
                    if stmt in stmts:
                        sources.add(source)
                newStmts.discard(stmt)

        self.applySourcePatch(source, Patch(addQuads=newStmts, delQuads=[]))
Esempio n. 17
0
 def getTemps(self, sensors):
     ret = {}
     try:
         for sens in sensors:
             if self.firstSensorLoop:
                 log.debug("found sensor address %r, type=%r" %
                           (sens.address, sens.type))
             if sens.type != 'DS18S20':
                 continue
             try:
                 t = sens.temperature.strip()
                 if t == '85':
                     log.debug(
                         "  sensor %s says 85 (C), power-on reset value" %
                         sens.address)
                     continue
                 tFar = float(t) * 9/5 + 32
                 log.debug("  %s reports temp %r F" % (sens.address, tFar))
             except ow.exUnknownSensor, e:
                 log.warn(e)
                 continue
             ret[sens] = tFar
     except KeyboardInterrupt: raise
     except Exception, e:
         traceback.print_exc()
Esempio n. 18
0
 def readMsg(self):
     log.debug("Read header..")
     (s1, s2, s3, length, device, number, command) = struct.unpack(
         "!BBBBBBB", self.ser.read(7))
     if not s1 == s2 == s3 == 0x80:
         raise ValueError("incorrect header in response: %r" % vars())
     log.debug("Read %d bytes of data", length)
     data = self.ser.read(length)
     cksum = self.ser.read(1)
     log.debug("  -> %r", data)
     return data
Esempio n. 19
0
    def step(self):
        now = time.time()
        try:
            if hostname == 'bang':
                if (not haveDevice(Id.bedroomCam) or
                    not haveDevice(Id.bedroomArduino)):
                    if haveDevice(Id.bedroomHub3):
                        yield resetDevice(hubDevice(Id.bedroomHub3))
                    else:
                        if haveDevice(Id.bedroomHub2):
                            yield resetDevice(hubDevice(Id.bedroomHub2))
                        else:
                            if haveDevice(Id.bedroomHub1):
                                yield resetDevice(hubDevice(Id.bedroomHub1))
                            else:
                                if haveDevice(Id.bedroomHub0):
                                    yield resetDevice(hubDevice(Id.bedroomHub0))
                                else:
                                    raise ValueError(
                                        "don't even have the first hub")
                    resetModules(['gspca_zc3xx'])
                    #supervisorRestart(['webcam_9053'])
                else:
                    log.debug("usb devices look ok")

            elif hostname == 'slash':
                haveFrontHub0 = haveDevice(Id.frontDoorHub0)
                haveFrontHub1 = haveDevice(Id.frontDoorHub1)
                haveFrontHub2 = haveDevice(Id.frontDoorHub2)
                haveFrontHub3 = haveDevice(Id.frontDoorHub3)
                haveGarageHub0 = haveDevice(Id.garageHub0)
                haveGarageHub1 = haveDevice(Id.garageHub1)
                haveFrontDoorCam = haveDevice(Id.frontDoorCam)
                haveV4lDevice = os.path.exists(
                    "/dev/v4l/by-id/usb-Vimicro_Corp._PC_Camera-video-index0")
                haveFrontArduinoServe = (yield getOk('http://slash:9080/'))
                haveFrontWebcamImage = (yield getOk(
                    "http://slash:9023/frontDoor", timeout=10))
                
                log.info(str(vars()))

                if not haveDevice(Id.ftdi):
                    if haveFrontHub3:
                        yield resetDevice(hubDevice(Id.frontDoorHub3))
                    else:
                        if haveFrontHub2:
                            yield resetDevice(hubDevice(Id.frontDoorHub2))
                        else:
                            if haveFrontHub1:
                                yield resetDevice(hubDevice(Id.frontDoorHub1))
                            else:
                                if haveFrontHub0:
                                    yield resetDevice(hubDevice(Id.frontDoorHub0))
                                else:
                                    raise ValueError("don't have the first hub")
                else:
                    log.debug("front door chain looks ok")

                if not haveDevice(Id.garagePowerSerial):
                    if haveGarageHub1:
                        yield resetDevice(hubDevice(Id.garageHub1))
                    else:
                        if haveGarageHub0:
                            yield resetDevice(hubDevice(Id.garageHub0))
                        else:
                            raise ValueError("don't have the first hub")
                else:
                    log.debug("garage chain looks ok")
                    
                if not haveDevice(Id.garageArduino):
                    if haveGarageHub1:
                        yield resetDevice(hubDevice(Id.garageHub1))
                    else:
                        raise ValueError("don't even have the first hub")
                    resetModules(['gspca_zc3xx'])
                    supervisorRestart(['frontDoorArduino_9080'])
                else:
                    if not haveFrontArduinoServe:
                        yield resetDevice(hubDevice(Id.frontDoorHub3))
                        supervisorRestart(['frontDoorArduino_9080'])
                        time.sleep(10)
                    else:
                        log.debug("frontDoorArduino looks ok")

                if not haveFrontWebcamImage:
                    supervisorRestart(['webcam_frontDoor_9023'])
                else:
                    log.debug("front webcam looks ok")

            elif hostname == 'dash':
                if not os.path.exists("/dev/serial/by-id/usb-FTDI_FT232R_USB_UART_A900gbcG-if00-port0"):
                    yield resetDevice(hubDevice("/dev/bus/usb/003/001"))

            else:
                raise NotImplementedError

            log.debug(" -- finished")
            self.lastPollTime = now

        except Exception, e:
            print "poll error", e
            traceback.print_exc()
Esempio n. 20
0
 def put(self, name):
     t1 = time.time()
     self.settings.arduino.digital[_num(name)].write(int(self.request.body))
     log.debug("arduino write in %.1f ms" % (1000 * (time.time() - t1)))