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()
def __init__(self, host, port, subscribe_topic, publish_topic, **kwargs): self.host = host self.port = port # topics self.subscribe_topic = subscribe_topic self.publish_topic = publish_topic # connection self.connection_id = uuid.uuid4().hex[:8] self.is_connected = False self.client = MQTTClient(self.connection_id) # callbacks self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.on_disconnect = self.on_disconnect self.client.on_subscribe = self.on_subscribe self.STOP = asyncio.Event() # options self.ack_topic = kwargs.get('ack_topic') self.enable_ssl = kwargs.get('enable_ssl', False) self.enable_auth = kwargs.get('enable_auth', False) self.username = kwargs.get('username') self.password = kwargs.get('password') self.client_cert = kwargs.get('client_cert') self.client_key = kwargs.get('client_key') self.qos = kwargs.get('qos', 2)
async def connect_output_mqtt(self): self.output_client = MQTTClient(None) # auto-generate client id self.output_client.on_connect = self.output_on_connect self.output_client.on_message = self.output_on_message self.output_client.on_disconnect = self.output_on_disconnect self.output_client.on_subscribe = self.output_on_subscribe user = self.settings["output_mqtt"]["user"] password = self.settings["output_mqtt"]["password"] host = self.settings["output_mqtt"]["host"] port = self.settings["output_mqtt"]["port"] self.output_client.set_auth_credentials(user, password) try: await self.output_client.connect(host, port, keepalive=60, version=MQTTv311) except Exception as e: if hasattr(e, 'args') and e.args[0] == 5: print( "{}\033[1;31m FAIL: Connect output_mqtt auth (as {} )\033[0;0m" .format(self.ts_string(), user), file=sys.stderr, flush=True) else: print( "{}\033[1;31m FAIL gmqtt connect exception\n{}\n{}\033[0;0m" .format(self.ts_string(), e), file=sys.stderr, flush=True) self.ask_exit()
async def _connect(self): GmqttClient.counter += 1 client_id = f'client-id/{platform.node()}/pid_{os.getpid()}/{uuid.getnode()}/{GmqttClient.counter}' self.client = MQTTClient(client_id) self.PROCESS = asyncio.Event() self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.on_disconnect = self.on_disconnect self.client.on_subscribe = self.on_subscribe # print('set') self.client.set_auth_credentials(self.config.username, self.config.password) while True: try: await self.client.connect(self.config.hostname, port=self.config.port, ssl=self.config.ssl, version=self.config.mqtt_version) break except Exception as ex: print('connect failed', ex) time.sleep(1) self.ready.set() while True: await self.PROCESS.wait() self.PROCESS.clear() # print('process signaled') self._sync_subscriptions() # await self.STOP.wait() await self.client.disconnect()
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()
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()
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")
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()
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()
async def publish_mqtt(): client = MQTTClient("client-id") await client.connect("maggie-kafka-1.thenetcircle.lab", port=1883, version=MQTTv50) client.publish("1972", str(time.time()), qos=1, message_expiry_interval=10) await client.disconnect()
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)
def __init__(self, loop: asyncio.AbstractEventLoop, device_registry): self.loop = loop self.device_registry = device_registry self.client = MQTTClient("client-id") self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.on_disconnect = self.on_disconnect self.client.on_subscribe = self.on_subscribe
async def init_mqtt(self): if self.args.mqtt_broker is not None: self.mqtt = MQTTClient('deepdish') if self.args.mqtt_user is not None: self.mqtt.set_auth_credentials(self.args.mqtt_user, self.args.mqtt_pass) await self.mqtt.connect(self.args.mqtt_broker) if self.topic is None: self.topic = 'default/topic'
def __init__(self, their_vk, endpoint): self.client = MQTTClient("client-id") self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.on_disconnect = self.on_disconnect self.client.on_subscribe = self.on_subscribe self.did_conn = StaticConnection(crypto.create_keypair(), their_vk=their_vk, endpoint=endpoint)
def __init__(self, settings=None): print("LinkGMQTT __init__()") self.settings = settings self.client = MQTTClient(None) # None => autogenerated client id self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.on_disconnect = self.on_disconnect self.client.on_subscribe = self.on_subscribe self.subscription_queue = asyncio.Queue() print("LinkGMQTT __init__ completed")
async def connect(self): self.client = MQTTClient(self.asm.name) self.client.on_message = on_message self.client.set_auth_credentials( os.getenv('MQTT_USER', "arcus"), os.getenv('MQTT_PASSWORD', "arcusarcus")) await self.client.connect(os.getenv('MQTT_HOST', "mqtt"), 1883, keepalive=60, version=MQTTv311) _LOGGER.info("Connected to MQTT")
def __init__( self, broker: str, port: int = 1883, keepalive: int = 60, auth: List[str] = [None, None], event_functions=None, client_id: str = "client_id", event_loop=None, **kwargs, ) -> None: default_events = { "on_connect": self.on_connect, "on_message": self.on_message, "on_disconnect": self.on_disconnect, "on_subscribe": self.on_subscribe, } if event_functions is None: event_functions = {} self.event_functions = default_events self.event_functions.update(event_functions) # self.client = MQTTClient(client_id) self.auth = auth self.broker = broker self.port = port self.keepalive = keepalive self.stop = asyncio.Event() if event_loop is None: loop = asyncio.get_event_loop() else: loop = event_loop loop.add_signal_handler(signal.SIGINT, self.ask_exit) loop.add_signal_handler(signal.SIGTERM, self.ask_exit) # passing any extra kwargs to the call to be used for e.g. on_connect self.client = MQTTClient(client_id, **kwargs) for _ in [k for k, v in self.event_functions.items() if v is None]: logger.warning(f"mqtt no function assigned to {_}") self.event_functions.pop(k) for k, v in self.event_functions.items(): setattr(self.client, k, v) if any(self.auth): self.client.set_auth_credentials(*self.auth) loop.create_task(self.start(self.broker))
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
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()
def __init__(self, config: MQQTConfig, *, client_id: Optional[Type[str]] = None, clean_session: bool = True, optimistic_acknowledgement: bool = True, **kwargs: Any) -> None: ''' FastMQTT client object to establish connection parametrs beforeconnect and manipulate MQTT service. The class object holds session information necesseary to connect MQTT broker. param :: config : Config parameters for gmqtt.Client type :: config: MQQTConfig param :: client_id : client_id should be unique identfiyer for connection to MQQT broker type :: client_id: Any param :: clean_session : The clean session flag tells the broker whether the client wants to establish a persistent session or not. In a persistent session clean_session = False, the broker stores all subscriptions for the client and all missed messages for the client that subscribed with a Quality of Service (QoS) level 1 or 2. If the session is not persistent (clean_session = True), the broker does not store anything for the client and purges all information from any previous persistent session. The client_id that the client provides when it establishes connection to the broker identifies the session. type :: clean_session: bool param :: optimistic_acknowledgement : #TODO more info needed type :: optimistic_acknowledgement: bool ''' if not client_id: client_id = uuid.uuid4().hex self.client: MQTTClient = MQTTClient(client_id) self.config: Dict[Any, Any] = config self.client._clean_session = clean_session self.client._username: Optional[str] = config.username or None self.client._password: Optional[str] = config.password or None self.client._host: str = config.host self.client._port: int = config.port self.client._keepalive: int = config.keepalive self.client._ssl: Union[bool, SSLContext] = config.ssl self.client.optimistic_acknowledgement: bool = optimistic_acknowledgement self.client._connect_properties: Any = kwargs self.executor = ThreadPoolExecutor() self.loop = asyncio.get_event_loop() if self.config.will_message_topic and self.config.will_message_payload and self.config.will_delay_interval: print("WILL MESSAGE INITILAZIED") self.client._will_message = Message( self.config.will_message_topic, self.config.will_message_payload, self.config.will_delay_interval)
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()
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()
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()
async def Main(self, aHost, aToken, aTopic): print('Main()', aHost, aToken) self.Topic = aTopic self.Last = time.time() client = MQTTClient('asdfghjk') client.on_message = self.on_message client.on_connect = self.on_connect #client.set_auth_credentials(aToken, None) await client.connect(aHost, 1883, keepalive=60) #client.publish(TOPIC, 'Message payload', response_topic='RESPONSE/TOPIC') #client.publish(TOPIC, 'Message payload', response_topic=TOPIC) await AEvent.wait() await client.disconnect()
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()
def __init__(self, sensor_id=None, event_buffer=None, settings=None): print("SmartPlug init()", sensor_id) #debug will put these in settings self.broker_host = 'localhost' self.broker_port = 1883 self.sensor_id = sensor_id self.STOP = asyncio.Event() self.client = MQTTClient(self.sensor_id + "_node") self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.client.on_disconnect = self.on_disconnect self.client.on_subscribe = self.on_subscribe
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')
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()
def connect(self): MQTT_Base.connect(self) self.mqtt_client = MQTTClient( 'gmqtt' #self.mqtt_settings["MQTT_CLIENT_ID"] ) self.mqtt_client.on_connect = self._on_connect self.mqtt_client.on_message = self._on_message self.mqtt_client.on_disconnect = self._on_disconnect if self.mqtt_settings["MQTT_USERNAME"]: self.mqtt_client.set_auth_credentials( self.mqtt_settings["MQTT_USERNAME"], self.mqtt_settings["MQTT_PASSWORD"], ) def start(): try: logger.warning('Connecting to MQTT') asyncio.set_event_loop(self.event_loop) # self.event_loop.run_until_complete( # self.mqtt_client.connect(self.mqtt_settings["MQTT_BROKER"], self.mqtt_settings["MQTT_PORT"],keepalive=self.mqtt_settings["MQTT_KEEPALIVE"], version=MQTTv311) # ) logger.warning('Looping forever') self.event_loop.run_forever() logger.warning('Event loop stopped') #self.session.close() except Exception as e: logger.error('Error in event loop {}'.format(e)) self.event_loop = asyncio.new_event_loop() logger.warning("Starting MQTT thread") self._ws_thread = threading.Thread(target=start, args=()) self._ws_thread.daemon = True self._ws_thread.start() future = asyncio.run_coroutine_threadsafe( self.mqtt_client.connect( self.mqtt_settings["MQTT_BROKER"], self.mqtt_settings["MQTT_PORT"], keepalive=self.mqtt_settings["MQTT_KEEPALIVE"], version=MQTTv311), self.event_loop)
async def main(broker_host): client = MQTTClient(client_id) assign_callbacks_to_client(client) await client.connect(broker_host) print('Subscribe topic for the Last Will and Testament (LWT)...') client.subscribe(status_topic) print('Subscribe response topic...') client.subscribe(res_topic) print('Publish request message with response topic...') client.publish(teds_topic, req_msg, response_topic=res_topic) await STOP.wait() await client.disconnect()