Ejemplo 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()
Ejemplo n.º 2
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()
Ejemplo n.º 3
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()
Ejemplo n.º 4
0
    def post(self):
        """
        payload is an rdf graph. The statements are momentarily added
        to the input graph for exactly one update.

        todo: how do we go from a transition like doorclosed-to-open
        to a oneshot event? the upstream shouldn't have to do it. Do
        we make those oneshot events here? for every object change?
        there are probably special cases regarding startup time when
        everything appears to be a 'change'.
        """
        try:
            dt = self.settings.reasoning.inputGraph.addOneShotFromString(
                self.request.body, self.request.headers['content-type'])
            self.set_header('x-graph-ms', str(1000 * dt))
        except Exception as e:
            traceback.print_exc()
            log.error(e)
            raise
Ejemplo n.º 5
0
    def poll(self):

        connectedField = 'connected'
        now = int(time.time())
        
        # UVA mode:
        addDhcpData = lambda *args: None
        
        try:
            newAddrs = yield self.wifi.getPresentMacAddrs()
            addDhcpData(newAddrs)
            
            newWithSignal = [a for a in newAddrs if a.get('connected')]

            actions = self.computeActions(newWithSignal)
            points = []
            for action in actions:
                log.info("action: %s", action)
                action['created'] = datetime.datetime.now(tz.gettz('UTC'))
                mongo.save(action)
                points.append(
                    self.influxPoint(now, action['address'].lower(),
                                     1 if action['action'] == 'arrive' else 0))
                try:
                    self.doEntranceMusic(action)
                except Exception, e:
                    log.error("entrancemusic error: %r", e)

            if now // 3600 > self.lastPollTime // 3600:
                log.info('hourly writes')
                for addr in newWithSignal:
                    points.append(self.influxPoint(now, addr['mac'].lower(), 1))
                    
            influx.write_points(points, time_precision='s')
            self.lastWithSignal = newWithSignal
            if actions: # this doesn't currently include signal strength changes
                fetch(reasoning + "immediateUpdate",
                      method='PUT',
                      timeout=2,
                      headers={'user-agent': ['tomatoWifi']}).addErrback(log.warn)
            self.lastAddrs = newAddrs
            self.lastPollTime = now
Ejemplo n.º 6
0
    def poll(self):
        ret = None
        startTime = time.time()
        try:
            resp = yield fetch(
                'http://{deviceIp}/cgi-bin/cgi_manager'.format(deviceIp=deviceIp),
                method='POST',
                headers={'Authorization': ['Basic %s' % auth]},
                postdata='''<LocalCommand>
                              <Name>get_usage_data</Name>
                              <MacId>0x{macId}</MacId>
                            </LocalCommand>
                            <LocalCommand>
                              <Name>get_price_blocks</Name>
                              <MacId>0x{macId}</MacId>
                            </LocalCommand>'''.format(macId=macId))
            ret = json.loads(resp.body)
            if ret['demand_units'] != 'kW':
                raise ValueError
            if ret['summation_units'] != 'kWh':
                raise ValueError
            influx.write_points([
                dict(measurement='housePowerW',
                     fields=dict(value=float(ret['demand']) * 1000),
                     tags=dict(house='berkeley'),
                     time=int(startTime)),
                dict(measurement='housePowerSumDeliveredKwh',
                     fields=dict(value=float(ret['summation_delivered'])),
                     tags=dict(house='berkeley'),
                     time=int(startTime)),
                ], time_precision='s')
        except Exception as e:
            log.error("failed: %r", e)
            log.error(repr(ret))

        now = time.time()
        goal = startTime + periodSec - .2
        reactor.callLater(max(1, goal - now), self.poll)
Ejemplo n.º 7
0
        self.carbon = carbon
        self.lastPollTime = 0
        self.reset()
        LoopingCall(self.poll).start(interval=10)

    def reset(self):
        log.info("reopening serial port")
        for port in ['/dev/serial/by-id/usb-0557_2008-if00-port0']:
            try:
                self.comm = Comm(port)
                break
            except SerialException, e:
                pass
        else:
            # among other things, a serial exception for too many open files 
            log.error(e)
            os.abort()
        log.info("version: %r", self.comm.request(device=1, number=0,
                                                  command="getVersion"))

    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:
Ejemplo n.º 8
0
 def poll(self):
     try:
         self._poll()
     except Exception, e:
         log.error("during poll:", exc_info=1)
Ejemplo n.º 9
0
 def reportPostError(self, fail, pin, value, url):
     log.error("failed to send pin %s update (now %s) to %r: %r" % (pin, value, url, fail))