Ejemplo n.º 1
0
def uptime_coro():

    try:
        while True:
            C = MQTTClient()

            yield from C.connect('mqtt://127.0.0.1:8080')
            # Subscribe to '$SYS/broker/uptime' with QOS=1
            yield from C.subscribe([
                ('bd/#', QOS_1),

            ])
            logger.info("Subscribed")
            message = yield from C.deliver_message()
            packet = message.publish_packet
            get_request = packet.payload.data
            header = packet.variable_header.topic_name.split('/')
            if  get_request == b'bot':
                print("%d: %s => %s" % (1, packet.variable_header.topic_name, str))
                db_maybe.bot_session(C, packet.variable_header.topic_name, packet.payload.data)
            if header[1] == 'two':
                print("%d: %s => %s" % (1, packet.variable_header.topic_name, str))
                db_maybe.two_players_session(C, packet.variable_header.topic_name, packet.payload.data)

        yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
        logger.info("UnSubscribed")
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)

    yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
    logger.info("UnSubscribed")

    yield from C.disconnect()
Ejemplo n.º 2
0
def uptime_coro():
    global answer
    try:
        while True:
            answer = ''
            C = MQTTClient()

            yield from C.connect('mqtt://127.0.0.1:8080')
            # Subscribe to '$SYS/broker/uptime' with QOS=1
            yield from C.subscribe([('bot/#', QOS_1)])
            logger.info("Subscribed")
            message = yield from C.deliver_message()
            packet = message.publish_packet
            str = packet.payload.data.decode('utf-8')
            header = packet.variable_header.topic_name.split('/')[1:-1]
            topic = ''
            for s in header:
                topic += s + '/'
            answer = ''
            if str == 'starting':
                asyncio.ensure_future(
                    bot_answer(C, 'game/bot/' + topic, b'makerandompole'))
                asyncio.ensure_future(get_answer(C, 'bot/', topic))
                print('here3')
                answer = ''
            answer = ''
            coord = 0
            if header[len(header) - 1] == 'shoot':
                coord = random_coord()
                send = bytearray(coord + '//' + str, encoding='utf-8')
                asyncio.ensure_future(
                    bot_answer(C, 'game/bot/' + topic + 'checkshoot/', send))
                asyncio.ensure_future(
                    get_answer(C, 'bot/', topic + 'checkshoot/', coord))
                answer = answer.encode('utf-8')

            answer = ''

        yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
        logger.info("UnSubscribed")
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)

    yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
    logger.info("UnSubscribed")

    yield from C.disconnect()
Ejemplo n.º 3
0
def run(arguments):
    with open(arguments['--output'], 'a') as outfile:
        retry = True
        while retry:
            C = MQTTClient(
                BASE_TOPIC + "/sensorlogger",
                config=CLIENT_CONFIG,
            )
            yield from C.connect(arguments['--uri'])
            yield from C.subscribe(SUBSCRIPTIONS)
            try:
                while True:
                    message = yield from C.deliver_message()
                    packet = message.publish_packet
                    outfile.write("{},{}\n".format(
                        packet.payload.data.decode('utf-8'),
                        packet.variable_header.topic_name))
                    outfile.flush()
            except KeyboardInterrupt:
                retry = False
            except ClientException as ce:
                logging.error("Client exception: %s" % ce)
                yield from C.unsubscribe([s[0] for s in SUBSCRIPTIONS])
            finally:
                yield from C.disconnect()
Ejemplo n.º 4
0
 def test_coro():
     try:
         broker = Broker(broker_config, plugin_namespace="hbmqtt.test.plugins")
         yield from broker.start()
         client = MQTTClient()
         yield from client.connect('mqtt://127.0.0.1/')
         self.assertIsNotNone(client.session)
         ret = yield from client.subscribe([
             ('test_topic', QOS_0),
         ])
         self.assertEqual(ret[0], QOS_0)
         client_pub = MQTTClient()
         yield from client_pub.connect('mqtt://127.0.0.1/')
         yield from client_pub.publish('test_topic', data, QOS_0)
         yield from client_pub.disconnect()
         message = yield from client.deliver_message()
         self.assertIsNotNone(message)
         self.assertIsNotNone(message.publish_packet)
         self.assertEqual(message.data, data)
         yield from client.unsubscribe(['$SYS/broker/uptime'])
         yield from client.disconnect()
         yield from broker.shutdown()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Ejemplo n.º 5
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://localhost/')
    # Subscribe to '/vjoy/#' with QOS=2
    yield from C.subscribe(myoptions)
    logger.info("Subscribed")
    try:
        mybool = True
        while True:
            message = yield from C.deliver_message()
            packet = message.publish_packet
            # Work starts here
            jstr = json.loads(packet.payload.data.decode("utf-8"))
            if jstr['type'] == "j":
                print("%s => %d => %d" %
                      (jstr['type'], getattr(
                          pyvjoy, jstr['index']), int(jstr['value'])))
                j.set_axis(getattr(pyvjoy, jstr['index']), int(jstr['value']))
                pass
            elif jstr['type'] == "b":
                print("%s => %s => %d" %
                      (jstr['type'], jstr['index'], int(jstr['value'])))
                j.set_button(int(jstr['index']), jstr['value'])
            pass
        yield from C.unsubscribe(myoptions)
        logger.info("UnSubscribed")
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Ejemplo n.º 6
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://krzyzak.duckdns.org/')
    # Subscribe to '$SYS/broker/uptime' with QOS=1
    yield from C.subscribe([
        ('test/#', QOS_1),
        ('stacja/#', QOS_2),
    ])
    logger.info("Subscribed")
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet 
            pub = str(packet.payload.data.decode('utf-8'))
            print("%d: %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data.decode('utf-8'))))
            if (pub == 'siema'):
              task = [asyncio.create_task(C.publish('a/b', b'TEST MESSAGE WITH QOS_0', qos=0x00)),
                      asyncio.create_task(C.publish('a/c', b'TEST MESSAGE WITH QOS_1', qos=QOS_1)),
                      asyncio.create_task(C.publish('a/d', b'TEST MESSAGE WITH QOS_2', qos=QOS_2)),]
              yield from asyncio.wait(task)

        yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
        logger.info("UnSubscribed")
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Ejemplo n.º 7
0
 def test_coro():
     try:
         broker = Broker(broker_config,
                         plugin_namespace="hbmqtt.test.plugins")
         yield from broker.start()
         client = MQTTClient()
         yield from client.connect('mqtt://127.0.0.1/')
         self.assertIsNotNone(client.session)
         ret = yield from client.subscribe([
             ('test_topic', QOS_0),
         ])
         self.assertEqual(ret[0], QOS_0)
         client_pub = MQTTClient()
         yield from client_pub.connect('mqtt://127.0.0.1/')
         yield from client_pub.publish('test_topic', data, QOS_0)
         yield from client_pub.disconnect()
         message = yield from client.deliver_message()
         self.assertIsNotNone(message)
         self.assertIsNotNone(message.publish_packet)
         self.assertEqual(message.data, data)
         yield from client.unsubscribe(['$SYS/broker/uptime'])
         yield from client.disconnect()
         yield from broker.shutdown()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Ejemplo n.º 8
0
def run(arguments):
    alive = True
    while alive:
        C = MQTTClient(
            "hassio/test",
            config=CLIENT_CONFIG,
        )
        yield from C.connect(arguments['--uri'])
        yield from C.subscribe(SUBSCRIPTIONS)
        for settings in HANDLERS.values():
            if settings['active']:
                yield from publishConfig(C, settings)
        try:
            while True:
                message = yield from C.deliver_message()
                packet = message.publish_packet
                topic = packet.topic_name
                if topic in HANDLERS:
                    settings = HANDLERS[topic]
                    yield from settings['handler'](settings, C, packet)
                    row = packet.payload.data.decode('utf-8').split(',', 1)
                    print(packet.topic_name, row)
        except KeyboardInterrupt:
            alive = False
        except ClientException as ce:
            print("Client exception: %s" % ce)
            yield from C.unsubscribe([s[0] for s in SUBSCRIPTIONS])
        finally:
            yield from C.disconnect()
Ejemplo n.º 9
0
 def get_led_vals_coro(self):
     try:
         C = MQTTClient()
         yield from C.connect(self.MQTT_BROKER_ADDR)
         yield from C.subscribe([('%s/%s/%s' % (thingy, self.THNGY_USR_INTERF_UUID, self.THNGY_USR_INTERF_LED_UUID), QOS_1)])
         message = yield from C.publish('%s/%s/%s/read' % (thingy, self.THNGY_USR_INTERF_UUID, self.THNGY_USR_INTERF_LED_UUID), b'read', qos=QOS_1)
         response = yield from C.deliver_message()
         print(list(response.data))
         yield from C.unsubscribe([('%s/%s/%s' % (thingy, self.THNGY_USR_INTERF_UUID, self.THNGY_USR_INTERF_LED_UUID))])
         yield from C.disconnect()
     except ClientException as ce:
         pass
Ejemplo n.º 10
0
 def test_coro():
     try:
         client = MQTTClient()
         yield from client.connect('mqtt://test.mosquitto.org/')
         self.assertIsNotNone(client.session)
         ret = yield from client.subscribe([
             ('$SYS/broker/uptime', QOS_0),
         ])
         self.assertEquals(ret[0], QOS_0)
         yield from client.unsubscribe(['$SYS/broker/uptime'])
         yield from client.disconnect()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Ejemplo n.º 11
0
def subscriber():
    C = MQTTClient()
    yield from C.connect(get_endpoint())
    yield from C.subscribe([(TOPIC_NAME, QOS_0)])
    try:
        for i in range(NUM_MESSAGES):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            print("%d: %s => %s" % (i, packet.variable_header.topic_name,
                                    str(packet.payload.data)))
        yield from C.unsubscribe([TOPIC_NAME])
        yield from C.disconnect()
    except ClientException as ce:
        print("Client exception: %s" % ce)
Ejemplo n.º 12
0
 def test_coro():
     try:
         client = MQTTClient()
         yield from client.connect('mqtt://test.mosquitto.org/')
         self.assertIsNotNone(client.session)
         ret = yield from client.subscribe([
             ('$SYS/broker/uptime', QOS_0),
         ])
         self.assertEquals(ret[0], QOS_0)
         yield from client.unsubscribe(['$SYS/broker/uptime'])
         yield from client.disconnect()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Ejemplo n.º 13
0
    def get_thingy_name(self, thingy):
        try:
            C = MQTTClient()
            yield from C.connect(self.MQTT_BROKER_ADDR)
            yield from C.subscribe([('%s/%s/%s' % (thingy, self.THNGY_CONFIG_UUID, self.THNGY_CONFIG_NAME_UUID), QOS_1)])
            message = yield from C.publish('%s/%s/%s/read' % (thingy, self.THNGY_CONFIG_UUID, self.THNGY_CONFIG_NAME_UUID), b'read', qos=QOS_1)
            response = yield from C.deliver_message()
            packet = response.publish_packet

            print("%s => %s" % (packet.variable_header.topic_name, response.data.decode("ascii")))
            yield from C.unsubscribe([('%s/%s/%s' % (thingy, self.THNGY_CONFIG_UUID, self.THNGY_CONFIG_NAME_UUID))])
            yield from C.disconnect()
        except ClientException as ce:
            pass
Ejemplo n.º 14
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://localhost/')
    yield from C.subscribe([
            ('sputnik/test', QOS_1),
         ])
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            print("%d:  %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data)))
        yield from C.unsubscribe(['sputnik/test'])
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Ejemplo n.º 15
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtts://*****:*****@0.0.0.0:8883', cafile='ca.crt')
    yield from C.subscribe([
            ('vaibhavagg2/test', QOS_1),
            ('vaibhavagg2/device2/test', QOS_1)
         ])
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            print("%d:  %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data)))
        yield from C.unsubscribe(['a/b', 'test_topic'])
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Ejemplo n.º 16
0
def run(arguments):
    global SUBSCRIPTIONS
    readSettings()
    loop_time = int(arguments['--loop-time'])
    retry = True
    while retry:
        C = MQTTClient(
            BASE_TOPIC + "/regler",
            config=CLIENT_CONFIG,
        )
        yield from C.connect(arguments['--uri'])
        yield from C.subscribe([(s[0], QOS_2) for s in SUBSCRIPTIONS])
        try:
            push_state['heat_pump'].setValue(state['heat_pump'])
            yield from C.publish(*push_state['heat_pump'].publish())
            yield from C.publish(*push_state['state'].publish())
            start = time.time()
            while True:
                packet = None
                wait_time = max(loop_time - (time.time() - start), 0)
                logging.debug("wait_time= %s", wait_time)
                try:
                    message = yield from C.deliver_message(timeout=wait_time)
                    packet = message.publish_packet
                except asyncio.TimeoutError:
                    pass
                if packet:
                    executePacket(packet)
                if (time.time() - start) > loop_time:
                    start = time.time()
                    calculateNominal()
                    calulateHeatPumpState()
                    push_state['heat_pump'].setValue(state['heat_pump'])
                    yield from C.publish(*push_state['heat_pump'].publish())
                    yield from C.publish(*push_state['state'].publish())
        except KeyboardInterrupt:
            retry = False
        except ClientException as e:
            logging.exception("Client exception: %s" % e)
        except Exception as e:
            logging.exception("Unknown exception: %s" % e)
        finally:
            yield from C.unsubscribe([s[0] for s in SUBSCRIPTIONS])
            yield from C.disconnect()
        if retry:
            print("retry")
Ejemplo n.º 17
0
 def main(self):
     client = MQTTClient()
     yield from client.connect('mqtt://localhost:1883/')
     for key in self.__registry.keys():
         yield from client.subscribe([{'filter': key, 'qos': 0x00}])
     while True:
         packet = yield from client.deliver_message()
         log.debug("%s : %s" % (packet.variable_header.topic_name, str(packet.payload.data)))
         try:
             #yield from self.getSensor("pressure-main").setValue(float(packet.payload.data))
             self.update(packet.variable_header.topic_name, packet.payload.data)
         except Exception as exception:
             log.exception(exception)
         yield from client.acknowledge_delivery(packet.variable_header.packet_id)
     for key in self.__registry.keys():
         yield from client.unsubscribe([key])
     yield from client.disconnect()
Ejemplo n.º 18
0
 def test_coro():
     try:
         broker = Broker(broker_config, plugin_namespace="hbmqtt.test.plugins")
         yield from broker.start()
         client = MQTTClient()
         yield from client.connect('mqtt://127.0.0.1/')
         self.assertIsNotNone(client.session)
         ret = yield from client.subscribe([
             ('$SYS/broker/uptime', QOS_0),
         ])
         self.assertEqual(ret[0], QOS_0)
         yield from client.unsubscribe(['$SYS/broker/uptime'])
         yield from client.disconnect()
         yield from broker.shutdown()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Ejemplo n.º 19
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://127.0.0.1:1883/')
    # Subscribe to '$SYS/broker/uptime' with QOS=1
    # Subscribe to '$SYS/broker/load/#' with QOS=2
    yield from C.subscribe([
            ('/slack_in', QOS_1),
         ])
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            print("%d:  %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data.decode())))
        yield from C.unsubscribe(['/slack_in'])
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Ejemplo n.º 20
0
 def test_coro():
     try:
         broker = Broker(broker_config,
                         plugin_namespace="hbmqtt.test.plugins")
         yield from broker.start()
         client = MQTTClient()
         yield from client.connect('mqtt://127.0.0.1/')
         self.assertIsNotNone(client.session)
         ret = yield from client.subscribe([
             ('$SYS/broker/uptime', QOS_0),
         ])
         self.assertEqual(ret[0], QOS_0)
         yield from client.unsubscribe(['$SYS/broker/uptime'])
         yield from client.disconnect()
         yield from broker.shutdown()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Ejemplo n.º 21
0
    def recv_mqtt(self):

        C = MQTTClient()
        yield from C.connect('mqtt://' + str(self.arg.server_ip))

        yield from C.subscribe([(self.arg.topic, QOS_1)])
        try:
            while True:
                message = yield from C.deliver_message()
                packet = message.publish_packet
                print("%s" % (str(packet.payload.data).split("'")[1]))
                v = str(packet.payload.data).split("'")[1]
                self.db.writeDB("node1", int(v))

            yield from C.unsubscribe([self.arg.topic])
            yield from C.disconnect()
        except ClientException as ce:
            logger.error("Client exception: %s" % ce)
Ejemplo n.º 22
0
    def button_coro(self, thingy):
        try:
            C = MQTTClient()
            yield from C.connect(self.MQTT_BROKER_ADDR)
            yield from C.subscribe([('%s/%s/%s' % (thingy, self.THNGY_USR_INTERF_UUID, self.THNGY_USR_INTERF_BUTTON_UUID), QOS_1)])

            for i in range(10):
                message = yield from C.deliver_message()
                packet = message.publish_packet
                if packet.payload.data:
                    print("Button pressed")
                else:
                    print("Button not pressed")

            yield from C.unsubscribe([('%s/%s/%s' % (thingy, self.THNGY_USR_INTERF_UUID, self.THNGY_USR_INTERF_BUTTON_UUID))])
            yield from C.disconnect()
        except ClientException as ce:
            print(ce)
Ejemplo n.º 23
0
    def light_coro(self, database, thingy, key):
        """
        Get light intensity readings from Thingy and store in database
        """
        try:
            C = MQTTClient()
            yield from C.connect(self.MQTT_BROKER_ADDR)
            yield from C.subscribe([('%s/%s/%s' % (thingy, self.THNGY_ENV_UUID, self.THNGY_ENV_LIGHT_UUID), QOS_1)])

            # yield from C.subscribe([('#', QOS_1)])

            while True:
                # Remove expires entries in database
                database.del_expired_items(key, datetime.now().timestamp())
                message = yield from C.deliver_message()
                packet = message.publish_packet
                color = {
                'red':  packet.payload.data[0],
                'green': packet.payload.data[2],
                'blue': packet.payload.data[4],
                'clear': packet.payload.data[6]
                }
                date = str(datetime.now())

                print("%s => %s" % (packet.variable_header.topic_name, str(color)))

                data = {
                    'color': color,
                    'date': date
                }
                print(data)
                score = datetime.now().timestamp()
                print(score)
                
                database.enqueue(key, data, score)

            yield from C.unsubscribe([('%s/%s/%s' % (thingy, self.THNGY_ENV_UUID, self.THNGY_ENV_LIGHT_UUID))])
            yield from C.disconnect()
        except ClientException as ce:
            print(ce)
        
        readings = database.get_set('light_series', 0, -1)
        for read in readings:
            print("IM BAKK ", read)
Ejemplo n.º 24
0
def run(arguments):
    retry = True
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(heatPumpPin, GPIO.OUT)
    GPIO.setup(waterPumpPin, GPIO.OUT)
    GPIO.output(heatPumpPin, HEAT_PUMP_OFF)
    GPIO.output(waterPumpPin, WATER_PUMP_ON)
    while retry:
        C = MQTTClient(
            BASE_TOPIC + "/pumpswitch",
            config=CLIENT_CONFIG,
        )
        yield from C.connect(arguments['--uri'])
        yield from C.subscribe(SUBSCRIPTIONS)
        try:
            while True:
                message = yield from C.deliver_message()
                packet = message.publish_packet
                topic = packet.variable_header.topic_name
                state = packet.payload.data.decode('utf-8').split(',')[-1]
                state = pinStateFromMQTTState(state)
                if state == UNKNOWN:
                    continue
                if topic.endswith('heat_pump'):
                    if state == ON:
                        GPIO.output(heatPumpPin, HEAT_PUMP_ON)
                    else:
                        GPIO.output(heatPumpPin, HEAT_PUMP_OFF)
                    if state == ON:
                        GPIO.output(waterPumpPin, WATER_PUMP_ON)
                elif topic.endswith('water_pump'):
                    if state == ON:
                        GPIO.output(heatPumpPin, WATER_PUMP_ON)
                    else:
                        GPIO.output(heatPumpPin, WATER_PUMP_OFF)
        except KeyboardInterrupt:
            retry = False
        except ClientException as e:
            logging.error("Client exception: %s" % e)
        except:
            yield from C.unsubscribe(SUBSCRIPTIONS)
        finally:
            yield from C.disconnect()
Ejemplo n.º 25
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://test.mosquitto.org/')
    # Subscribe to '$SYS/broker/uptime' with QOS=1
    yield from C.subscribe([
                ('$SYS/broker/uptime', QOS_1),
                ('$SYS/broker/load/#', QOS_2),
             ])
    logger.info("Subscribed")
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            print("%d: %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data)))
        yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
        logger.info("UnSubscribed")
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Ejemplo n.º 26
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://test.mosquitto.org/')
    # Subscribe to '$SYS/broker/uptime' with QOS=1
    yield from C.subscribe([
        ('$SYS/broker/uptime', QOS_1),
        ('$SYS/broker/load/#', QOS_2),
    ])
    logger.info("Subscribed")
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            print("%d: %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data)))
        yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
        logger.info("UnSubscribed")
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Ejemplo n.º 27
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect(url)
    yield from C.subscribe([(topic, QOS_1), (topic, QOS_2)], )
    logger.info("Subscribed")
    i = 1
    try:
        while i:
            message = yield from C.deliver_message()
            packet = message.publish_packet
            j = json.loads(packet.payload.data.decode())
            print(j)
            #print("%d: %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data)))
            i = i + 1
        yield from C.unsubscribe([topic, topic])
        logger.info("UnSubscribed")
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Ejemplo n.º 28
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://*****:*****@0.0.0.0:1883')
    # Subscribe to '$SYS/broker/uptime' with QOS=1
    yield from C.subscribe([
        ('data/memes', QOS_1),  # Topic allowed
        ('data/classified', QOS_1),  # Topic forbidden
    ])
    logger.info("Subscribed")
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            print("%d: %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data)))
        yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
        logger.info("UnSubscribed")
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Ejemplo n.º 29
0
    def pressure_coro(self, database, thingy, key):
        """
        Get pressure readings from Thingy and store in database
        """
        try:
            C = MQTTClient()
            yield from C.connect(self.MQTT_BROKER_ADDR)
            yield from C.subscribe([('%s/%s/%s' % (thingy, self.THNGY_ENV_UUID, self.THNGY_ENV_PRESS_UUID), QOS_1)])

            # yield from C.subscribe([('#', QOS_1)])

            while True:
                # Remove expires entries in database
                database.del_expired_items(key, datetime.now().timestamp())
                message = yield from C.deliver_message()
                packet = message.publish_packet
                # TODO: check the parsing of pressure data - it seems like wrong values (~180 instead of ~1000)

                integer = packet.payload.data[0]
                decimal = packet.payload.data[4]
                pressure = integer + (decimal / 100.0)
                date = str(datetime.now())

                print("%s => %s" % (packet.variable_header.topic_name, str(pressure)))

                data = {
                    'pressure': pressure,
                    'date': date
                }
                print(data)
                score = datetime.now().timestamp()
                print(score)
                
                database.enqueue(key, data, score)

            yield from C.unsubscribe([('%s/%s/%s' % (thingy, self.THNGY_ENV_UUID, self.THNGY_ENV_PRESS_UUID))])
            yield from C.disconnect()
        except ClientException as ce:
            print(ce)
        
        readings = database.get_set('pressure_series', 0, -1)
        for read in readings:
            print("IM BAKK ", read)
Ejemplo n.º 30
0
def mqtt_listener():
    C = MQTTClient()
    yield from C.connect(mqtt_broker)

    yield from C.subscribe([(mqtt_topic, QOS_1)])
    try:
        while True:
            message = yield from C.deliver_message()
            packet = message.publish_packet
            logger.debug(
                "%s => %s" %
                (packet.variable_header.topic_name, str(packet.payload.data)))
            text = packet.payload.data.decode()
            logging.debug(text)
            sign.write_text(text, font_name=display_font)
        yield from C.unsubscribe([mqtt_topic])
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Ejemplo n.º 31
0
    def temp_coro(self, database, thingy, key):
        """
        Get temperature readings from Thingy and store in database
        """
        
        try:
            C = MQTTClient()
            yield from C.connect(self.MQTT_BROKER_ADDR)
            yield from C.subscribe([('%s/%s/%s' % (thingy, self.THNGY_ENV_UUID, self.THNGY_ENV_TMP_UUID), QOS_1)])

            # yield from C.subscribe([('#', QOS_1)])
            
            while True:
                # Remove expires entries in database
                database.del_expired_items('key', datetime.now().timestamp())
                message = yield from C.deliver_message()
                packet = message.publish_packet
                integer = packet.payload.data[0]
                decimal = packet.payload.data[1]
                temperature = integer + (decimal / 100)
                date = str(datetime.now())

                print("%s => %s" % (packet.variable_header.topic_name, str(temperature)))
                data = {
                    'temperature': temperature,
                    'date': date
                }
                print(data)
                score = datetime.now().timestamp()
                print(score)
                
                database.enqueue(key, data, score)

            yield from C.unsubscribe([('%s/%s/%s' % (thingy, self.THNGY_ENV_UUID, self.THNGY_ENV_TMP_UUID))])
            yield from C.disconnect()

        except ClientException as ce:
            print(ce)

        readings = database.get_set('temperature_series', 0, -1)
        for read in readings:
            print("IM BAKK ", read)
Ejemplo n.º 32
0
    def gas_coro(self, database, thingy, key):
        """
        Get CO2 readings from Thingy and store in database
        """
        try:
            C = MQTTClient()
            yield from C.connect(self.MQTT_BROKER_ADDR)
            yield from C.subscribe([('%s/%s/%s' % (thingy, self.THNGY_ENV_UUID, self.THNGY_ENV_GAS_UUID), QOS_1)])

            # yield from C.subscribe([('#', QOS_1)])

            while True:
                # Remove expires entries in database
                database.del_expired_items(key, datetime.now().timestamp())
                message = yield from C.deliver_message()
                packet = message.publish_packet
                gas = {
                'eco2': packet.payload.data[0],
                'tvoc': packet.payload.data[2]
                }
                date = str(datetime.now())

                print("%s => %s" % (packet.variable_header.topic_name, str(gas)))

                data = {
                    'gas': gas,
                    'date': date
                }
                print(data)
                score = datetime.now().timestamp()
                print(score)
                
                database.enqueue(key, data, score)

            yield from C.unsubscribe([('%s/%s/%s' % (thingy, self.THNGY_ENV_UUID, self.THNGY_ENV_GAS_UUID))])
            yield from C.disconnect()
        except ClientException as ce:
            print(ce)
        
        readings = database.get_set('gas_series', 0, -1)
        for read in readings:
            print("IM BAKK ", read)
Ejemplo n.º 33
0
 def test_coro():
     try:
         broker = Broker(broker_config,
                         plugin_namespace="hbmqtt.test.plugins")
         yield from broker.start()
         client = MQTTClient()
         yield from client.connect('mqtt://localhost/')
         self.assertIsNotNone(client.session)
         ret = yield from client.subscribe([
             ('test_topic', QOS_0),
         ])
         self.assertEqual(ret[0], QOS_0)
         with self.assertRaises(asyncio.TimeoutError):
             yield from client.deliver_message(timeout=2)
         yield from client.unsubscribe(['$SYS/broker/uptime'])
         yield from client.disconnect()
         yield from broker.shutdown()
         future.set_result(True)
     except Exception as ae:
         future.set_exception(ae)
Ejemplo n.º 34
0
def uptime():
    C = MQTTClient()
    yield from C.connect(url)
    yield from C.subscribe([(uid+"/#", QOS_1)],)
    logger.info("Subscribed %s/%s" %(url,uid))
    print("Subscribed %s/%s" %(url,uid))
    i=1
    try:
        while i:
            message = yield from C.deliver_message()
            packet = message.publish_packet
            command( packet.variable_header.topic_name, packet.payload.data)
            print("%d: %s => %s" %(i,packet.variable_header.topic_name,str(packet.payload.data)))
            logger.info("%d: %s => %s" %(i,packet.variable_header.topic_name,str(packet.payload.data)))
            i=i+1
        yield from C.unsubscribe([uid,uid])
        logger.info("UnSubscribed %s/%s" %(url,uid))
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Ejemplo n.º 35
0
def uptime_coro(url, cafile):
    C = MQTTClient()
    yield from C.connect(url, cafile=cafile)

    # Subscribe to '$SYS/broker/uptime' with QOS=1
    # Subscribe to '$SYS/broker/load/#' with QOS=2
    yield from C.subscribe([
        ('$SYS/broker/uptime', QOS_1),
        ('$SYS/broker/load/#', QOS_2),
    ])
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            print("%d:  %s => %s" % (i, packet.variable_header.topic_name,
                                     str(packet.payload.data)))
        yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Ejemplo n.º 36
0
 def main(self):
     client = MQTTClient()
     yield from client.connect('mqtt://localhost:1883/')
     for key in self.__registry.keys():
         yield from client.subscribe([{'filter': key, 'qos': 0x00}])
     while True:
         packet = yield from client.deliver_message()
         log.debug(
             "%s : %s" %
             (packet.variable_header.topic_name, str(packet.payload.data)))
         try:
             #yield from self.getSensor("pressure-main").setValue(float(packet.payload.data))
             self.update(packet.variable_header.topic_name,
                         packet.payload.data)
         except Exception as exception:
             log.exception(exception)
         yield from client.acknowledge_delivery(
             packet.variable_header.packet_id)
     for key in self.__registry.keys():
         yield from client.unsubscribe([key])
     yield from client.disconnect()
Ejemplo n.º 37
0
def uptime_coro():
    C = MQTTClient()
    yield from C.connect('mqtt://*****:*****@0.0.0.0:1883')
    # yield from C.connect('mqtt://0.0.0.0:1883')
    # Subscribe to '$SYS/broker/uptime' with QOS=1
    yield from C.subscribe([
        ('data/memes', QOS_1),  # Topic allowed
        ('data/classified', QOS_1),  # Topic forbidden
        ('repositories/hbmqtt/master', QOS_1),  # Topic allowed
        ('repositories/hbmqtt/devel', QOS_1),  # Topic forbidden
        ('calendar/hbmqtt/releases', QOS_1),  # Topic allowed
    ])
    logger.info("Subscribed")
    try:
        for i in range(1, 100):
            message = yield from C.deliver_message()
            packet = message.publish_packet
            print("%d: %s => %s" % (i, packet.variable_header.topic_name, str(packet.payload.data)))
        yield from C.unsubscribe(['$SYS/broker/uptime', '$SYS/broker/load/#'])
        logger.info("UnSubscribed")
        yield from C.disconnect()
    except ClientException as ce:
        logger.error("Client exception: %s" % ce)
Ejemplo n.º 38
0
        def test_coro():
            try:
                broker = Broker(test_config, plugin_namespace="hbmqtt.test.plugins")
                yield from broker.start()
                self.assertTrue(broker.transitions.is_started())
                client = MQTTClient()
                ret = yield from client.connect('mqtt://127.0.0.1/')
                self.assertEqual(ret, 0)
                yield from client.subscribe([('/topic', QOS_0)])

                # Test if the client test client subscription is registered
                self.assertIn('/topic', broker._subscriptions)
                subs = broker._subscriptions['/topic']
                self.assertEqual(len(subs), 1)
                (s, qos) = subs[0]
                self.assertEqual(s, client.session)
                self.assertEqual(qos, QOS_0)

                yield from client.unsubscribe(['/topic'])
                yield from asyncio.sleep(0.1)
                self.assertEqual(broker._subscriptions['/topic'], [])
                yield from client.disconnect()
                yield from asyncio.sleep(0.1)
                yield from broker.shutdown()
                self.assertTrue(broker.transitions.is_stopped())
                MockPluginManager.assert_has_calls(
                    [
                        call().fire_event(EVENT_BROKER_CLIENT_SUBSCRIBED,
                                          client_id=client.session.client_id,
                                          topic='/topic', qos=QOS_0),
                        call().fire_event(EVENT_BROKER_CLIENT_UNSUBSCRIBED,
                                          client_id=client.session.client_id,
                                          topic='/topic')
                    ], any_order=True)
                future.set_result(True)
            except Exception as ae:
                future.set_exception(ae)