コード例 #1
0
async def main(broker_host, token):
    client = MQTTClient(__name__)
    client.on_connect = on_connect
    client.on_disconnect = on_disconnect
    client.on_message = on_message
    client.on_subscribe = on_subscribe

    if token:
        client.set_auth_credentials(token)
    log.debug(f'Connecting to {broker_host}')
    await client.connect(broker_host)

    def on_app_changed(status, payload):
        client.publish(BASETOPIC + "/app", payload)

    def on_volume_changed(status, payload):
        client.publish(BASETOPIC + "/volume", payload)

    lg = LGClient()
    lg.ac.subscribe_get_current(on_app_changed)
    lg.mc.subscribe_get_volume(on_volume_changed)

    # Periodic heartbeat from the bridge
    def heartbeat():
        while True:
            client.publish(f"{BASETOPIC}/heartbeat/{client._client_id}",
                           str(datetime.datetime.now()))
            time.sleep(1)

    threading.Thread(target=heartbeat, daemon=True).start()

    await stopEvent.wait()
    await client.disconnect()
コード例 #2
0
async def main(broker_host, username, password):
    client = MQTTClient("client-id-mitch", user_property=('hello', 'there'))
    # client = MQTTClient("client-id-mitch")

    client.on_connect = on_connect
    client.on_message = on_message
    client.on_disconnect = on_disconnect
    client.on_subscribe = on_subscribe

    client.set_auth_credentials(username, password.encode())
    await client.connect(host=broker_host, port=1883)
    # await client.connect()
    print("connected, now ready to send...")
    data = f"This is a test! {str(time.time())}"
    hash = hashlib.sha256(data.encode()).hexdigest()
    client.publish('test/time1',
                   "hello test/time1..",
                   qos=1,
                   message_expiry_interval=5,
                   content_type="json",
                   response_topic='RESPONSE/TOPIC2',
                   user_property=[('hash', hash), ('time', str(time.time()))])
    client.publish('test/time2',
                   "hello test/time2..",
                   qos=1,
                   message_expiry_interval=5,
                   content_type="json",
                   response_topic='RESPONSE/TOPIC',
                   user_property=[('hash', hash), ('time', str(time.time()))])

    await STOP.wait()
    await client.disconnect()
コード例 #3
0
async def main(broker_host):
    print("creating client")

    client = MQTTClient("client1")

    client.on_connect = on_connect
    client.on_message = on_message
    client.on_disconnect = on_disconnect
    client.on_subscribe = on_subscribe
    client.on_publish = on_publish

    await client.connect(broker_host)
    client.subscribe('org/common', no_local=True)

    await asyncio.sleep(5)

    print("Publish response topic")
    msg_out1 = "test message"
    client.publish('org/common', "aa", response_topic="org/responses/client1")
    await asyncio.sleep(50)  #wait to receive message
    if len(messages) == 0:
        print("test failed")
    else:
        msg = messages.pop()
        if msg == msg_out1:
            print("test succeeded")

    await client.disconnect()
コード例 #4
0
async def main(broker_host, token):

    print("main started")

    client = MQTTClient(None)

    client.on_connect = on_connect
    client.on_message = on_message
    client.on_disconnect = on_disconnect
    client.on_subscribe = on_subscribe

    print("connecting")

    # client.set_auth_credentials(token, None)
    await client.connect(broker_host, version=MQTTv311)

    print("connected... publishing")

    client.publish('foo', str(time.time()), qos=1)

    print("published")

    await STOP.wait()
    await client.disconnect()

    print("finished")
コード例 #5
0
    async def connect(self):

        try:
            print(
                '""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""'
            )
            print('Attempting MQTT connection...')
            print('MQTT host : ', self.broker_host)
            print('MQTT user : '******'MQTT error, restarting in 8s...')
            await asyncio.sleep(8)
            await self.connect()
コード例 #6
0
async def main(broker_host):
    print("creating client2")

    client = MQTTClient("client2")

    client.on_connect = on_connect
    client.on_message = on_message
    client.on_disconnect = on_disconnect
    client.on_subscribe = on_subscribe
    client.on_publish = on_publish

    await client.connect(broker_host)

    client.subscribe("org/responses/client2")

    await asyncio.sleep(5)




    client.publish('org/common',"client2 message",\
                   response_topic="org/responses/client2")
    await asyncio.sleep(50)  #wait to receive message

    await client.disconnect()
コード例 #7
0
async def main(broker_host, username, password):
    client = MQTTClient(client_id="pub-client-id", receive_maximum=24000)
    client.on_disconnect = on_disconnect
    client.set_auth_credentials(username=username, password=password)
    await client.connect(broker_host)

    for i in range(10000):
        client.publish(message_or_topic='TEST/T1', payload=str(i), qos=1, retain=True, message_expiry_interval=60)
コード例 #8
0
def prepare_client(token):
    CLIENT_ID = create_uid()

    client = MQTTClient(CLIENT_ID)

    client.on_connect = on_connect
    client.on_message = on_message
    client.on_disconnect = on_disconnect
    client.on_subscribe = on_subscribe

    client.set_auth_credentials(token, None)

    return client
コード例 #9
0
async def main():
    client = MQTTClient(mqtt_client_id,
                        session_expiry_interval=86400 * 10,
                        clean_session=False)

    client.on_connect = on_connect
    client.on_message = on_message
    client.on_disconnect = on_disconnect
    client.on_subscribe = on_subscribe

    client.set_auth_credentials(username, None)
    await client.connect(broker_host)
    await STOP.wait()
    await client.disconnect()
コード例 #10
0
async def main(broker_host, token):
    client = MQTTClient("vscode-client")

    client.on_connect = on_connect
    client.on_message = on_message
    client.on_disconnect = on_disconnect
    client.on_subscribe = on_subscribe
    
    client.set_auth_credentials(token, None)
    await client.connect(broker_host)

    # client.publish('TEST/TIME', str(time.time()), qos=0)

    await STOP.wait()
    await client.disconnect()
コード例 #11
0
async def main(broker_host, username, password):
    client = MQTTClient(client_id="sub-client-id",
                        receive_maximum=24000,
                        clean_session=False,
                        session_expiry_interval=60)

    client.on_connect = on_connect
    client.on_message = on_message
    client.on_disconnect = on_disconnect
    client.on_subscribe = on_subscribe

    client.set_auth_credentials(username=username, password=password)
    await client.connect(broker_host)
    await STOP.wait()
    await client.disconnect()
コード例 #12
0
ファイル: test.py プロジェクト: admirf/mqtt-tests
async def main(broker_host):
    client = MQTTClient('client-id')

    client.on_connect = on_connect
    client.on_message = on_message
    client.on_disconnect = on_disconnect
    client.on_subscribe = on_subscribe

    await client.connect(broker_host, 1883)

    for x in range(100):
        client.publish('TEST/TIME', time.time(), qos=1)

    await STOP.wait()
    await client.disconnect()
コード例 #13
0
ファイル: client.py プロジェクト: ecebotarosh/TUIASI_RCP
async def main(broker_host):
    client = MQTTClient("client-id")

    client.on_connect = on_connect
    client.on_message = on_message
    client.on_disconnect = on_disconnect
    client.on_subscribe = on_subscribe

    client.set_auth_credentials('admin', 'admin')
    await client.connect(broker_host, 8080, keepalive=60, version=MQTTv50)

    #client.publish('TEST/TIME', str(time.time()), qos=1)

    time.sleep(30)
    await STOP.wait()
    await client.disconnect()
コード例 #14
0
async def main():
    client = MQTTClient('flespi-examples-mqtt-client-python',
                        clean_session=True)

    client.on_connect = on_connect
    client.on_message = on_message
    client.on_disconnect = on_disconnect
    client.on_subscribe = on_subscribe

    # see https://flespi.com/kb/tokens-access-keys-to-flespi-platform to read about flespi tokens
    client.set_auth_credentials(
        'FlespiToken {}'.format(os.environ.get("FlespiToken")), None)
    print('mqtt client created, connecting...')
    await client.connect('mqtt.flespi.io', port=8883, ssl=True)
    await STOP.wait()
    await client.disconnect()
    print('disconnected')
コード例 #15
0
ファイル: readcsv.py プロジェクト: westlab/Plugfest
async def main(host):
    client = MQTTClient("smart-agri-data-publisher")
    #    client.on_connect = on_connect
    #    client.on_message = on_message
    client.on_disconnect = on_disconnect
    #    client.on_subscribe = on_subscribe

    #client.set_auth_credentials(token, None)
    #await client.connect(broker_host)
    await client.connect(host)
    with open('./20200701_0830_Outdoor-utf8.csv') as fo:
        with open('./20200701_0830_South-utf8.csv') as fs:
            readero = csv.reader(fo)
            readerio = iter(readero)
            next(readerio)
            headero = next(readerio)
            print(headero)
            next(readerio)
            readers = csv.reader(fs)
            readeris = iter(readers)
            next(readeris)
            headers = next(readeris)
            print(headers)
            next(readeris)
            while True:
                try:
                    for rowo, rows in zip(readero, readers):
                        print(rowo)
                        for ent in (1, 6, 21, 26, 31, 36, 41, 46, 51):
                            pubtopic = TOPIC+'outdoor/'+headero[ent]
                            pubdata = str(rowo[ent])
                            print(pubtopic, pubdata)
                            client.publish(pubtopic, pubdata, qos=1)
                        for ent in (1, 6, 11, 16, 21, 26):
                            pubtopic = TOPIC+'south/'+headers[ent]
                            pubdata = str(rows[ent])
                            print(pubtopic, pubdata)
                            client.publish(pubtopic, pubdata, qos=1)
                        time.sleep(1)
                except StopIteration:
                        fo.close()
                        fs.close()
                        return

#    await STOP.wait()
    await client.disconnect()
コード例 #16
0
ファイル: runtime.py プロジェクト: squishykid/glue
async def main(broker_host, actor_name, loop):
    actor = load_actor(actor_name).Actor()
    client_name = f'{os.getpid()}:{actor_name}'
    client = MQTTClient(client_name)
    aa = ActorAdapter(actor, client)

    client.on_connect = aa.on_connect
    client.on_message = aa.on_message
    client.on_disconnect = aa.on_disconnect
    client.on_subscribe = aa.on_subscribe

    await client.connect(broker_host)
    await actor._hook_loop(loop)

    client.publish('TEST/TIME', str(time.time()), qos=1)

    await STOP.wait()
    await client.disconnect()
コード例 #17
0
async def main(broker_host, token):
    global con
    con = pymysql.connect(host=mysql_host,
                          user=mysql_user,
                          passwd=mysql_passwd,
                          db=mysql_db,
                          autocommit=True)
    client = MQTTClient('message_listener')

    client.on_connect = on_connect
    client.on_message = on_message
    client.on_disconnect = on_disconnect
    client.on_subscribe = on_subscribe

    client.set_auth_credentials(token, None)
    await client.connect(broker_host)

    await STOP.wait()
    await client.disconnect()
コード例 #18
0
async def main(broker_host, token):
    client_id = create_uid()
    client = MQTTClient(client_id)

    client.on_connect = on_connect
    client.on_message = on_message
    client.on_disconnect = on_disconnect
    client.on_subscribe = on_subscribe

    client.set_auth_credentials(token, None)
    await client.connect(broker_host)

    # Watchdog print out online_clients every 5s
    t = threading.Thread(target=watchdog_clients)
    t.setDaemon(True)
    t.start()

    await STOP.wait()
    await client.disconnect()
コード例 #19
0
async def main(loop, broker_host, token):
    engine = create_engine(SQLALCHEMY_DATABASE_URI)

    conn = engine.connect()

    Session = sessionmaker(bind=engine)
    session = Session()

    client = MQTTClient("client-id")

    client.on_connect = on_connect
    client.on_message = partial(on_message, conn, session)
    client.on_disconnect = on_disconnect
    client.on_subscribe = on_subscribe

    client.set_auth_credentials(token, None)
    await client.connect(broker_host)

    await STOP.wait()
    await client.disconnect()
コード例 #20
0
    async def startup(self):
        conf = self.config
        client = MQTTC("client-id")
        client.set_config(
            dict(
                reconnect_retries=conf.reconnect_retries,
                reconnect_delay=conf.reconnect_delay,
            ))
        client.on_connect = self._on_connect
        client.on_message = self._on_message
        client.on_disconnect = self._on_disconnect
        client.on_subscribe = self._on_subscribe
        client.on_unsubscribe = self._on_unsubscribe

        try:
            await client.connect(conf.host, conf.port, conf.ssl,
                                 conf.keepalive, conf.version)
        except MQTTConnectError as error:
            print(error)
        self.client = client
コード例 #21
0
async def mqttconnection(mqtt_client_id, broker_host, user, password):
    try:
        global hassio
        if (hassio == None):
            print('Attempting MQTT connection...')
            client = MQTTClient(mqtt_client_id)

            client.on_connect = on_connect
            client.on_disconnect = on_disconnect
            client.on_subscribe = on_subscribe
            client.on_message = on_message

            if user is not None and password is not None:
                client.set_auth_credentials(user, password)

            await client.connect(broker_host, port=mqtt_port, ssl=mqtt_ssl)
            hassio = client

    except Exception as err:
        print(f"Error : {err}")
        print('MQTT error, restarting in 8s...')
        await asyncio.sleep(8)
        await mqttconnection(mqtt_client_id, mqtt_host, mqtt_user, mqtt_pass)
コード例 #22
0
ファイル: command.py プロジェクト: morelab/toad_sp_command
async def main(broker_host):

    global cached_ips

    update_ip_cache()
    client = MQTTClient("client-id")

    client.on_connect = on_connect
    client.on_message = on_message
    client.on_disconnect = on_disconnect
    client.on_subscribe = on_subscribe

    await client.connect(broker_host)

    while True:
        try:
            update_ip_cache()
        except Exception:
            pass
        if STOP.is_set():
            await client.disconnect()
            exit(0)
        await asyncio.sleep(config.SLEEP_TIME)
コード例 #23
0
async def main(broker_host):
    print("creating server")

    client = MQTTClient("server")


    client.on_connect = on_connect
    client.on_message = on_message
    client.on_disconnect = on_disconnect
    client.on_subscribe = on_subscribe
    client.on_publish = on_publish

    await client.connect(broker_host)
    client.subscribe('org/common',no_local=True)
    
    await asyncio.sleep(5)

    print("subscribed to common topic")


    await asyncio.sleep(500) #wait to receive message


    await client.disconnect()
コード例 #24
0
async def main(args):
    """
    Main function of the program. Initiates the publishing process of the Client.
    :param args: arguments provided via CLI
    """

    logging.info(
        f"Connecting you to {args.host} on Port {args.port}. Your clientID: '{args.client_id}'. "
        f"Multilateral Security for all messages {'is' if args.multilateral else 'is not'} enabled."
    )

    user_property = ('multilateral', '1') if args.multilateral else None
    if user_property:
        client = MQTTClient(args.client_id, user_property=user_property)
    else:
        client = MQTTClient(args.client_id)
    client.on_connect = on_connect
    client.on_disconnect = on_disconnect

    # if both, cert and key, are specified, try to establish TLS connection to broker
    if args.cert and args.key:
        try:
            context = create_tls_context(args.cert, args.key)
            await client.connect(host=args.host, port=args.port, ssl=context)
        except FileNotFoundError as e:
            logging.error(e)
            exit(0)
        except ssl.SSLError:
            logging.error(
                f"SSL Error. Either your key/cert is not valid or the Broker does not support TLS on Port {args.port}."
            )
            exit(0)

    # if both are not specified, then connect via insecure channel
    elif not args.cert and not args.key:
        await client.connect(host=args.host, port=args.port)

    # if only one of them is specified, print error and exit
    else:
        logging.error(
            f"Client certificate and client private key must be specified if connection should be secure. You have only specified {'the certificate' if args.cert else 'the private key'}."
        )
        exit(0)

    # Once connected, publish the specified message to the specified topic with specified user properties (multilateral)
    if len(args.multilateral_message) > 0:
        for i, multilateral_security_index in enumerate(
                args.multilateral_message):
            i += 1
            if multilateral_security_index:
                logging.info(
                    f"Message {i} sent with enforced Multilateral Security")
                user_property_message = ('multilateral', '1')
                client.publish(args.topic,
                               args.message + f" {i}",
                               user_property=user_property_message,
                               qos=0)
            else:
                logging.info(f"Message {i} sent without Multilateral Security")
                client.publish(args.topic, args.message + f" {i}", qos=0)
    else:
        logging.info(
            f"Publishing '{args.topic}:{args.message}', Multilateral Security: {'on' if args.multilateral else 'off'}"
        )
        client.publish(args.topic, args.message, qos=0)

    await STOP.wait()
    try:
        await client.disconnect(session_expiry_interval=0)
    except ConnectionResetError:
        logging.info("Broker successfully closed the connection.")