Exemplo n.º 1
0
 def __init__(self, host, port, mqtt_client_id, logger):
     self.mqtt_client = aiomqtt.Client(client_id=mqtt_client_id)
     self.mqtt_client.reconnect_delay_set(10, 15)
     self.log = logger
     self.host = host
     self.port = port
     self.router = MqttRouter()
Exemplo n.º 2
0
 def __init__(self, host: str, port: str, mqtt_client_id: str, logger: Logger):
     self.mqtt_client = aiomqtt.Client(client_id=mqtt_client_id)
     self.mqtt_client.reconnect_delay_set(10, 15)
     self.log = logger
     self.host = host
     self.port = port
     self.router = MqttRouter()
     self.response_event = asyncio.Event()
Exemplo n.º 3
0
async def send_mqtt(topic, message):
    mqttc = aiomqtt.Client(asyncio.get_event_loop(), "deconz-to-mqtt")
    await mqttc.connect(cfg['mqtt']['host'], cfg['mqtt']['port'],
                        cfg['mqtt']['timeout'])

    mqttc.publish(topic, json.dumps(message).encode("UTF-8"))

    mqttc.disconnect()
Exemplo n.º 4
0
    def __init__(self, host=None, port=None, clientid=None):
        self.host = host or config.get(MODULE_NAME, 'mqtt_host')
        self.port = port or config.get(MODULE_NAME, 'mqtt_port')

        self.client = aiomqtt.Client(clientid)
        self.client.on_message = self.on_message
        self.client.on_connect = self.on_connect
        self.client.on_publish = self.on_publish
        self.client.on_subscribe = self.on_subscribe
        self.client.on_disconnect = self.on_disconnect
Exemplo n.º 5
0
 def __init__(self, broker_ip, broker_port, device_id, actuator_impl, log):
     self.actuator_type = actuator_impl.get_type()
     self.mqtt_client = aiomqtt.Client(client_id=f"{device_id}{self.actuator_type}")
     self.mqtt_client.reconnect_delay_set(10, 15)
     self.mqtt_client.on_connect = self.on_connect
     self.mqtt_client.on_message = self.on_message
     self.mqtt_client.on_disconnect = self.on_disconnect
     self.actuator_impl = actuator_impl
     self.host = broker_ip
     self.port = broker_port
     self.device_id = device_id
     self._log = log
Exemplo n.º 6
0
async def test_loop_start_stop(server, hostname, port, event_loop):
    """Tests that starting/stopping the loop works as expected."""
    c = aiomqtt.Client(loop=event_loop)

    connect_event = asyncio.Event()
    c.on_connect = Mock(side_effect=lambda *_: connect_event.set())

    # Wait or the client to connect
    c.loop_start()
    c.connect_async(hostname, port)
    await asyncio.wait_for(connect_event.wait(), timeout=5)

    # Wait for shutdown
    await asyncio.wait_for(c.loop_stop(), timeout=5)
Exemplo n.º 7
0
async def test_connect_and_loop_forever(server, hostname, port, event_loop):
    """Tests connecting and then disconnecting from the MQTT server while using
    the loop_forever construct.
    """
    c = aiomqtt.Client(loop=event_loop)

    # Immediately disconnect on connection
    connect_event = asyncio.Event()

    def on_connect(client, userdata, flags, rc):
        assert client is c
        assert userdata is None
        assert isinstance(flags, dict)
        assert rc == aiomqtt.MQTT_ERR_SUCCESS

        connect_event.set()
        c.disconnect()

    c.on_connect = Mock(side_effect=on_connect)

    # Just check disconnect event is as expected
    disconnect_event = asyncio.Event()

    def on_disconnect(client, userdata, rc):
        assert client is c
        assert userdata is None
        assert rc == aiomqtt.MQTT_ERR_SUCCESS

        disconnect_event.set()

    c.on_disconnect = Mock(side_effect=on_disconnect)

    # When the client disconnects, this call should end
    c.connect_async(hostname, port)
    await asyncio.wait_for(c.loop_forever(), timeout=5)

    # Should definately have connected and disconnected
    assert connect_event.is_set()
    assert c.on_connect.called
    assert disconnect_event.is_set()
    assert c.on_disconnect.called
Exemplo n.º 8
0
    def set_mq(self):

        mq = aiomqtt.Client(client_id=self.clientid, loop=self.loop)
        mq.loop_start()
        if DBG > 1: mq.enable_logger(logger)
        if self.ssl_certificate:
            logger.debug("%s: using cert %s", self.name, self.ssl_certificate)
            try:
                mq.tls_set(self.ssl_certificate)
            except FileNotFoundError as e:
                logger.error("Mqtt: tls_set certificate %s: %s",
                             self.ssl_certificate, e)
                sys.exit(1)
            mq.tls_insecure_set(False)
        if self.username and self.password:
            mq.username_pw_set(self.username, self.password)
        mq.on_connect = self.on_connect
        mq.on_subscribe = self.on_subscribe
        mq.on_message = self.on_message
        mq.on_disconnect = self.on_disconnect
        return mq
Exemplo n.º 9
0
async def gateway(loop,
                  host='api1.aleph.im',
                  port=1883,
                  ca_cert=None,
                  pkey=None,
                  keepalive=10,
                  transport='tcp',
                  auth=None):

    if pkey is None:
        pkey = get_fallback_private_key()

    account = ETHAccount(private_key=pkey)
    state = dict()
    userdata = {'account': account, 'state': state, 'received': False}
    client = aiomqtt.Client(loop, userdata=userdata, transport=transport)
    client.on_connect = on_connect
    client.on_disconnect = on_disconnect
    client.on_message = on_message

    if ca_cert is not None:
        client.tls_set(ca_cert)
    if auth is not None:
        client.username_pw_set(**auth)

    asyncio.ensure_future(client.loop_forever())

    await client.connect(host, port, keepalive)
    # client.loop_forever()
    while True:
        await asyncio.sleep(10)
        if not userdata['received']:
            await client.reconnect()

        for key, value in state.items():
            ret = create_aggregate(account, key, value, channel='IOT_TEST')
            print("sent", ret['item_hash'])
            userdata['received'] = False
Exemplo n.º 10
0
async def mqtt(mqttTxQueue, canTxQueue, server, port, user, passwd, ca):
    client = aiomqtt.Client()
    #client = aiomqtt.Client(loop)
    print("mqtt client created")
    client.loop_start()
    print("mqtt client loop started")

    connected = asyncio.Event()

    def on_connect(client, userdata, flags, rc):
        print("mqtt connected")
        connected.set()

    client.on_connect = on_connect

    client.will_set(mqtt_PublishTopic + 'LWT', 'OFF', 0, False)
    if ca:
        client.tls_set(ca)
    if user and passwd:
        client.username_pw_set(user, passwd)

    try:
        await client.connect(server, port)
        await connected.wait()
        print("MQTT connected")
    except ConnectionRefusedError as e:
        print(e)
        await client.loop_stop()
        print("MQTT loop stopped!")
        sys.exit(-1)

    subscribed = asyncio.Event()

    def on_subscribe(client, userdata, mid, granted_qos):
        subscribed.set()

    client.on_subscribe = on_subscribe

    client.subscribe(mqtt_SubscribeTopic)
    await subscribed.wait()
    print("MQTT Subscribed to " + mqtt_SubscribeTopic)

    def on_message(client, userdata, msg):
        # von MQTT an CUL
        payload = str(msg.payload, 'utf-8')  # decode byte to string
        device = msg.topic.rsplit('/', 1)[-1]  # cut device part from topic
        print("MQTT RX: Topic: %-35s >> Message: %-20s [%s]" %
              (device, payload, bool(msg.retain)))
        asyncio.ensure_future(culTxQueue.put(device + '=' + payload))

    client.on_message = on_message

    lwtPublish = client.publish(mqtt_PublishTopic + "LWT", 'ON')
    await lwtPublish.wait_for_publish()
    print("MQTT LWT published!")

    while True:
        msg = await mqttTxQueue.get()
        try:  # von CUL an MQTT
            #msgPublish = client.publish(mqtt_PublishTopic + msg[0], msg[1], retain=msg[2])
            #await msgPublish.wait_for_publish()
            #print("MQTT TX: Topic: %-35s >> Message: %-20s [%s]" % (msg[0], str(msg[1]), str(msg[2])))
            await culDecode(client, str(msg[1]))
        except IndexError:
            print("MQTT publish failed: \t%s" % (msg, ))
Exemplo n.º 11
0
    async def _connect(self, *, cfg):
        logger.debug(f'{self._name} cfg:{cfg}')

        l_connected = asyncio.Event()
        self._conn_success = False

        def on_connect(client, userdata, flags, rc):  # callback
            l_rc_txt = mqtt_aioclient._conn_error[rc] if rc < len(
                mqtt_aioclient._conn_error) else ''
            if not rc:  # 0 = successful
                self._conn_success = True
                logger.debug(f'{self._name} flags:{flags} {l_rc_txt}')
            else:
                self._conn_success = False
                logger.error(f'mqtt connect failed: {l_rc_txt}')
            l_connected.set()

        try:
            l_client = aiomqtt.Client(loop=self._loop,
                                      client_id=self._client_id,
                                      clean_session=cfg.get(
                                          'clean_session',
                                          _def.MQTT_CLEAN_SESSION))
            self.on_log = self._on_log
            l_client.loop_start()
            self._set_lwt(client=l_client,
                          payload=cfg.get('lwtonline', _def.MQTT_LWTONLINE))

            l_username = cfg.get('username', _def.MQTT_USERNAME)
            if l_username:
                l_client.username_pw_set(username=l_username,
                                         password=cfg.get(
                                             'password', _def.MQTT_PASSWORD))
                logger.debug(f'{self._name} username:{l_username}')

            l_host = cfg.get('host', _def.MQTT_HOST)
            l_port = cfg.get('port', _def.MQTT_PORT)
            l_ssl = cfg.get('ssl', _def.MQTT_SSL)
            if l_ssl:
                l_port = cfg.get('port', _def.MQTT_SSLPORT)
                l_cafile = cfg.get('cafile')
                l_cert_reqs = ssl.CERT_REQUIRED if bool(
                    cfg.get('cert_verify',
                            _def.MQTT_CERT_VERIFY)) else ssl.CERT_NONE
                l_client.tls_set(ca_certs=l_cafile,
                                 cert_reqs=l_cert_reqs,
                                 tls_version=ssl.PROTOCOL_TLSv1_2)
                l_ssl_insecure = bool(
                    cfg.get('ssl_insecure', _def.MQTT_SSL_INSECURE))
                l_client.tls_insecure_set(l_ssl_insecure)
                logger.debug(
                    f'{self._name} cert_reqs:{l_cert_reqs} ssl_insecure:{str(l_ssl_insecure)} cafile:{l_cafile}'
                )
            logger.debug(f'''{self._name} host:{l_host} port:{l_port}''')
            l_client.on_connect = on_connect
            await l_client.connect(host=l_host,
                                   port=l_port,
                                   keepalive=cfg.get('keepalive',
                                                     _def.MQTT_KEEPALIVE))
            await l_connected.wait()
            if self._conn_success:
                self._client = l_client
                logger.info(
                    f'{self._name} connected host:{l_host} port:{l_port} client_id:{self._client_id}'
                )
                await self._publish_lwt(
                    payload=self._cfg.get('lwtonline', _def.MQTT_LWTONLINE))
                return True
            else:
                await l_client.loop_stop()
                logger.info(
                    f'{self._name} failed to connected host:{l_host} port:{l_port}'
                )
                return False
        except asyncio.CancelledError:
            logger.warning(f'{self._name} CancelledError')
        except:
            logger.exception(f'*** {self._name}')

        return False
Exemplo n.º 12
0
import asyncio
import json
import aiomqtt

from services.audio import AudioService
from services.boxes import Boxes
from services.stage import Stage
from controllers.state_machine import UnderTheSeaState

loop = asyncio.get_event_loop()
broker_url = "10.0.0.200"
broker_port = 1883

mqtt_c = aiomqtt.Client(loop=loop, client_id="main")

stage = Stage(loop, mqtt_c)
boxes = Boxes(loop, mqtt_c)
audio_service = AudioService(loop, mqtt_c)
state_machine = UnderTheSeaState(loop, stage, boxes, audio_service)


async def subscribe():
    mqtt_c.loop_start()

    connected = asyncio.Event(loop=loop)

    def on_connect(client, userdata, flags, rc):
        #print("Connected With Result Code "(rc))
        connected.set()
        # state_machine.start_state_wait_for_players()
Exemplo n.º 13
0
async def test_pub_sub(server, hostname, port, event_loop):
    """Make sure the full set of publish and subscribe functions and callbacks
    work.
    """
    c = aiomqtt.Client(loop=event_loop)

    connect_event = asyncio.Event()
    c.on_connect = Mock(side_effect=lambda *_: connect_event.set())

    subscribe_event = asyncio.Event()
    c.on_subscribe = Mock(side_effect=lambda *_: subscribe_event.set())

    publish_event = asyncio.Event()
    c.on_publish = Mock(side_effect=lambda *_: publish_event.set())

    message_event = asyncio.Event()
    c.on_message = Mock(side_effect=lambda *_: message_event.set())

    # For message_callback_add
    message_callback_event = asyncio.Event()
    message_callback = Mock(
        side_effect=lambda *_: message_callback_event.set())

    unsubscribe_event = asyncio.Event()
    c.on_unsubscribe = Mock(side_effect=lambda *_: unsubscribe_event.set())

    c.loop_start()
    try:
        c.connect_async(hostname, port)
        await asyncio.wait_for(connect_event.wait(), timeout=5)

        # Test subscription
        result, mid = c.subscribe("test")
        assert result == aiomqtt.MQTT_ERR_SUCCESS
        assert mid is not None
        await asyncio.wait_for(subscribe_event.wait(), timeout=5)
        c.on_subscribe.assert_called_once_with(c, None, mid, (0, ))

        # Test publishing
        message_info = c.publish("test", "Hello, world!")
        result, mid = message_info
        assert result == aiomqtt.MQTT_ERR_SUCCESS
        assert mid is not None
        await asyncio.wait_for(message_info.wait_for_publish(), timeout=5)
        c.on_publish.assert_called_once_with(c, None, mid)

        # Test message arrives
        await asyncio.wait_for(message_event.wait(), timeout=5)
        assert len(c.on_message.mock_calls) == 1
        assert c.on_message.mock_calls[0][1][0] is c
        assert c.on_message.mock_calls[0][1][1] is None
        assert c.on_message.mock_calls[0][1][2].topic == "test"
        assert c.on_message.mock_calls[0][1][2].payload == b"Hello, world!"

        # Now test with alternative message callback
        c.message_callback_add("test", message_callback)

        # Send another message
        message_info = c.publish("test", "Hello, again!")

        # Test message arrives
        await asyncio.wait_for(message_callback_event.wait(), timeout=5)
        assert len(message_callback.mock_calls) == 1
        assert message_callback.mock_calls[0][1][0] is c
        assert message_callback.mock_calls[0][1][1] is None
        assert message_callback.mock_calls[0][1][2].topic == "test"
        assert message_callback.mock_calls[0][1][2].payload == b"Hello, again!"

        # Test un-subscription
        result, mid = c.unsubscribe("test")
        assert result == aiomqtt.MQTT_ERR_SUCCESS
        assert mid is not None
        await asyncio.wait_for(unsubscribe_event.wait(), timeout=5)
        c.on_unsubscribe.assert_called_once_with(c, None, mid)

    finally:
        await asyncio.wait_for(c.loop_stop(), timeout=5)

    assert len(c.on_connect.mock_calls) == 1
    assert len(c.on_subscribe.mock_calls) == 1
    assert len(c.on_publish.mock_calls) == 2
    assert len(c.on_message.mock_calls) == 1
    assert len(message_callback.mock_calls) == 1
    assert len(c.on_unsubscribe.mock_calls) == 1
Exemplo n.º 14
0
async def mqtt(mqttTxQueue, canTxQueue, server, port, topicBase, user, passwd,
               ca):
    client = aiomqtt.Client(loop)
    client.loop_start()

    connected = asyncio.Event(loop=loop)

    def on_connect(client, userdata, flags, rc):
        connected.set()

    client.on_connect = on_connect

    client.will_set(topicBase + '/LWT', 'OFF', 0, False)
    if ca:
        client.tls_set(ca)
    if user and passwd:
        client.username_pw_set(user, passwd)

    await client.connect(server, port)
    await connected.wait()
    print("MQTT connected")

    subscribed = asyncio.Event(loop=loop)

    def on_subscribe(client, userdata, mid, granted_qos):
        subscribed.set()

    client.on_subscribe = on_subscribe

    client.subscribe(topicBase + "/+/set/#")
    await subscribed.wait()
    print("MQTT Subscribed to " + topicBase)

    def on_message(client, userdata, msg):
        print("MQTT RX: " + msg.topic + " = " + str(msg.payload))
        topic = msg.topic
        topic = topic.replace(mqtt_topicBase + "/", '')
        topic = topic.split('/')

        if len(topic) != 3:
            print('MQTT message topic length error')
            return

        if topic[1] != 'set':
            print('MQTT message topic type error')
            return

        topici = int(topic[0], 16)

        if topic[2] == 'switch':
            print(
                asbPkgEncode(0x01, topici, myid, -1,
                             [0x51, int(msg.payload)]))
            asyncio.ensure_future(
                canTxQueue.put(
                    asbPkgEncode(0x01, topici, myid, -1,
                                 [0x51, int(msg.payload)])))
            asyncio.ensure_future(
                mqttTxQueue.put([
                    "/" + topic[0] + "/get/switch",
                    msg.payload.decode(), True
                ]))

        if topic[2] == 'level':
            print(
                asbPkgEncode(0x01, topici, myid, -1,
                             [0x52, int(msg.payload)]))
            asyncio.ensure_future(
                canTxQueue.put(
                    asbPkgEncode(0x01, topici, myid, -1,
                                 [0x52, int(msg.payload)])))
            asyncio.ensure_future(
                mqttTxQueue.put([
                    "/" + topic[0] + "/get/level",
                    msg.payload.decode(), True
                ]))

    client.on_message = on_message

    lwtPublish = client.publish(mqtt_topicBase + "/LWT", 'ON')
    await lwtPublish.wait_for_publish()
    print("MQTT LWT published!")

    while True:
        msg = await mqttTxQueue.get()
        try:
            msgPublish = client.publish(mqtt_topicBase + msg[0],
                                        msg[1],
                                        retain=msg[2])
            await msgPublish.wait_for_publish()
            print("MQTT publish - Retain: " + str(msg[2]) + " Topic: " +
                  mqtt_topicBase + msg[0] + " - Message: " + str(msg[1]))
        except IndexError:
            print("MQTT publish failed: ")
            print(msg)