Exemplo n.º 1
0
 def test_pacman(self):
     config = Config()
     image_size = config.get('DISPLAY_SIZE')
     prev_frame = Frame(bytearray(b'0' * image_size), 1)
     next_frame = Frame(bytearray(b'1' * image_size), 1)
     seq = IntermezzoPacman(prev_frame, next_frame)
     verify_length(seq, image_size)
Exemplo n.º 2
0
 def test_fram_length(self):
     config = Config()
     image_size = config.get('DISPLAY_SIZE')
     prev_frame = Frame(bytearray([0x66]*image_size), 100)
     next_frame = Frame(bytearray([0x66]*image_size), 100)
     seq = IntermezzoInvaders(prev_frame, next_frame)
     verify_length(seq, image_size)
Exemplo n.º 3
0

class FakeSerialPort(object):
    def __init__(self, protocol):
        log.warn("Starting the FakeSerialPort")
        self.protocol = protocol
        self.protocol.transport = self

    def write(self, data):
        log.info("FAKE WRITING #%d bytes" % len(data))


if __name__ == '__main__':
    log = Logger(__file__)
    config = Config(envvar_silent=False)
    scheduler = CreateService(Scheduler)
    scheduler.add_intermezzo(IntermezzoWipe)
    scheduler.add_intermezzo(IntermezzoInvaders)
    scheduler.add_intermezzo(IntermezzoPacman)
    led_screen = LEDScreen()
    serial_port = config.get('SERIAL_PORT')
    if serial_port == 'fake':
        log.warn("FAKE SERIAL SELECTED.")
        FakeSerialPort(led_screen)
    else:
        baudrate = config.get('SERIAL_BAUDRATE')
        log.info("REAL Serialport %s @ %s" % (serial_port, baudrate))
        RealSerialPort(led_screen, serial_port, reactor, baudrate=baudrate)
    scheduler.led_screen = led_screen
    reactor.run()
Exemplo n.º 4
0
class GenericContent(ClientService):
    def __init__(self, endpoint, factory, reactor=None):
        super().__init__(endpoint, factory)
        if reactor is None:
            from twisted.internet import reactor
        self.reactor = reactor
        self.config = Config()
        self.protocol = None
        self._system_name = None

    def startService(self, name):
        log.info("starting MQTT Content Publisher Service")
        # invoke whenConnected() inherited method
        self._system_name = name
        self.whenConnected().addCallback(self.connectToBroker)
        ClientService.startService(self)

    @inlineCallbacks
    def connectToBroker(self, protocol):
        '''
        Connect to MQTT broker
        '''
        self.protocol = protocol
        self.protocol.onDisconnection = self.onDisconnection
        self.protocol.setWindowSize(3)
        try:
            yield self.protocol.connect(self._system_name, keepalive=60)
        except Exception as e:
            self.log.error("Connecting to {broker} raised {excp!s}",
                      broker=self.config.get('MQTT_BROKER_CONN_STRING'), excp=e)
        else:
            self.log.info("Connected to {broker}", broker=self.config.get('MQTT_BROKER_CONN_STRING'))
            self.reactor.callLater(0, self.onBrokerConnected)
        self_name = self.__class__.__name__
        self.publish(topic=LEDSLIE_TOPIC_STATS_BASE+self_name, message="%s now (re-)connected" % self_name)

    def onBrokerConnected(self):
        log.info("onBrokerConnected called")

    def onDisconnection(self, reason):
        '''
        get notfied of disconnections
        and get a deferred for a new protocol object (next retry)
        '''
        log.debug("<Connection was lost !> <reason={r}>", r=reason)
        self.whenConnected().addCallback(self.connectToBroker)

    def publish(self, topic, message, qos=0, retain=False):
        if hasattr(message, 'serialize'):
            message = message.serialize()
        self.log.debug("To '{topic}', Published: '{data}'", topic=topic, data=message)
        return self.protocol.publish(topic, message, qos, retain)

    def remove_display(self, program_name):
        """
        Remove the program from the display.
        :param program_name: The name of the program to remove
        :type program_name: str
        :return: The deferred that's called when the command has been send.
        :rtype: deferred
        """
        return self.publish(LEDSLIE_TOPIC_SEQUENCES_PROGRAMS[:-1] + program_name, "")
Exemplo n.º 5
0
class GenericProcessor(ClientService):
    subscriptions = ()

    def __init__(self, endpoint, factory, reactor=None):
        super().__init__(endpoint,
                         factory,
                         retryPolicy=backoffPolicy(),
                         clock=reactor)
        self.reactor = _maybeGlobalReactor(reactor)
        self.config = Config()
        self.protocol = None
        self._system_name = None

    def startService(self, name):
        log.info("starting MQTT Client Subscriber&Publisher Service")
        # invoke whenConnected() inherited method
        self.whenConnected().addCallback(self.connectToBroker)
        ClientService.startService(self)
        self._system_name = name

    @inlineCallbacks
    def connectToBroker(self, protocol):
        '''
        Connect to MQTT broker
        '''
        self.protocol = protocol
        self.protocol.onPublish = self.onPublish
        self.protocol.onDisconnection = self.onDisconnection
        self.protocol.setWindowSize(3)
        self.stats_task = task.LoopingCall(self.publish_vital_stats)
        self.stats_task.start(5.0, now=False)
        try:
            yield self.protocol.connect(self._system_name, keepalive=60)
            yield self.subscribe()
        except Exception as e:
            log.error("Connecting to {broker} raised {excp!s}",
                      broker=self.config.get('MQTT_BROKER_CONN_STRING'),
                      excp=e)
        else:
            log.info("Connected and subscribed to {broker}",
                     broker=self.config.get('MQTT_BROKER_CONN_STRING'))
            self.reactor.callLater(0, self.onBrokerConnected)
        self_name = self.__class__.__name__
        self.publish(topic=LEDSLIE_TOPIC_STATS_BASE + self_name,
                     message="%s (re-)connected" % self_name)

    def onBrokerConnected(self):
        log.info("onBrokerConnected called")

    def subscribe(self):
        def _logFailure(failure):
            log.debug("subscriber reported {message}",
                      message=failure.getErrorMessage())
            return failure

        def _logGrantedQoS(value):
            log.debug("subscriber response {value!r}", value=value)
            return True

        def _subscribe_topic(response, topic, qos):
            log.info("subscriber response {value!r}", value=response)
            return self.protocol.subscribe(topic, qos)

        d = Deferred()
        for topic, qos in self.subscriptions:
            d.addCallback(_subscribe_topic, topic, qos)
            d.addErrback(_logFailure)
        d.callback("Start")
        return d

    def onPublish(self, topic, payload, qos, dup, retain, msgId):
        raise NotImplemented()

    def publish(self, topic, message, qos=0, retain=False):
        if isinstance(message, bytes):
            message = bytearray(message)
        elif isinstance(message, GenericMessage):
            message = message.serialize()
        return self.protocol.publish(topic, message, qos, retain=retain)

    def _logPublishFailure(self, failure):
        log.debug("publisher reported {message}",
                  message=failure.getErrorMessage())
        return failure

    def publish_vital_stats(self):
        pass

    def onDisconnection(self, reason):
        '''
        get notfied of disconnections
        and get a deferred for a new protocol object (next retry)
        '''
        log.info("<Connection was lost !> <reason={r}>", r=reason)
        self.whenConnected().addCallback(self.connectToBroker)