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): 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()
class MQTTCli: 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 connect(): user = "******" pw = "oochi8eengehuYohgeBu1foobooceeZ7to5ieng7pis8saephaetah0hoaphiK3F" broker_host = "192.168.50.95" self.client.set_auth_credentials(user, pw) await self.client.connect(broker_host) def on_connect(client, flags, rc, properties): print('Connected') self.client.subscribe('home-assistant/command', qos=0) def on_message(client, topic, payload, qos, properties): print('RECV MSG:', payload) device_registry.bluetooth_devices.send_message(payload, True, False) publish('home-assistant/response', payload, qos=1) def on_disconnect(client, packet, exc=None): print('Disconnected') def on_subscribe(client, mid, qos, properties): print('SUBSCRIBED') def ask_exit(*args): STOP.set()
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()
class SmartPlug(object): 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 begin(self): #client.set_auth_credentials(token, None) await self.client.connect(self.broker_host, self.broker_port, version=MQTTv311) async def finish(self): #await self.STOP.wait() await self.client.disconnect() def on_connect(self, client, flags, rc, properties): print('{} Connected to {}'.format( self.sensor_id, self.broker_host + ':' + str(self.broker_port))) #print("{} Publishing".format(self.sensor_id)) #self.client.publish('TEST/TIME', "{:.3f} {} {}".format(time.time(),self.sensor_id,'connected mqtt'), qos=1) subscribe_str = '{}/tele/SENSOR'.format(self.sensor_id) print("{} Subscribing to {}".format(self.sensor_id, subscribe_str)) self.client.subscribe(subscribe_str, qos=0) def on_message(self, client, topic, payload, qos, properties): self.handle_input(payload) def on_disconnect(self, client, packet, exc=None): print('{} Disconnected'.format(self.sensor_id)) def on_subscribe(self, client, mid, qos): print("{} Subscribed".format(self.sensor_id)) def ask_exit(self, *args): self.STOP.set() def handle_input(self, input): print("{} got input {}".format(self.sensor_id, input))
def __init__(self, client_id): """ Initializes the MQTT client. :param client_id: MQTT client id """ MQTTClient.__init__(self, client_id) self.message_handler = ... self.running = False self.topics = [] self._STARTED = asyncio.Event() self._STOP = asyncio.Event()
def __init__(self, host: str, port: int, user: str, password: typing.Optional[str] = None): self.subscriptions: typing.Dict[str, typing.List[ValueCallback]] = {} self.host = host self.port = port self.client = Client('sorokdva-dialogs') self.client.set_auth_credentials(user, password) self.client.on_connect = self._on_connect self.client.on_message = self._on_message
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(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 initialize(self, auth: RequestAuth) -> None: """Initialize MQTT.""" if self._client is not None: self.disconnect() client_id = f"{auth.user_id}@ecouser/{auth.resource}" self._client = Client(client_id) self._client.on_message = self.__on_message self._client.set_auth_credentials(auth.user_id, auth.token) ssl_ctx = ssl.create_default_context() ssl_ctx.check_hostname = False ssl_ctx.verify_mode = ssl.CERT_NONE await self._client.connect(self._hostname, self._port, ssl=ssl_ctx, version=MQTTv311)
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 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")
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'
async def main(broker_host, token): 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) client.publish('TEST/TIME', str(time.time()), qos=0) await STOP.wait() await client.disconnect()
class DIDCommTeeMQTTClient: 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) async def mqtt_connect(self, broker_host): await self.client.connect(broker_host) async def mqtt_disconnect(self): await self.client.disconnect() def on_connect(self, client, flags, rc, properties): print('Connected') async def on_message(self, client, topic, payload, qos, properties): await self.did_conn.send_async({ '@type': 'https://didcomm.dbluhm.com/mqtt/0.1/msg', 'topic': topic, 'payload': payload.decode('ascii'), 'properties': properties }) print('RECV MSG:', payload) def on_disconnect(self, client, packet, exc=None): print('Disconnected') def on_subscribe(self, client, mid, qos): print('SUBSCRIBED') def publish(self, *args, **kwargs): self.client.publish(*args, **kwargs) def subscribe(self, *args, **kwargs): self.client.subscribe(*args, **kwargs)
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")
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))
async def connect_to_mqtt(self): """Connect to MQTT Server""" # Create an instance of the REST client. if self.MQTT_USERNAME is None or self.MQTT_PASS is None: print("MQTT keys not found, aborting connection") return False try: print("Atempting to connect to MQTT as " + self.MQTT_USERNAME) self.__client = Client(client_id=self.client_id) self.__client.set_auth_credentials(self.MQTT_USERNAME, self.MQTT_PASS) await self.__client.connect(self.hostname, port=1883) print("Connected to MQTT") self.MQTT_CONNECTION_STATE = True return True except Exception as e: print("Failed to connect to MQTT, disabling it") print(e) self.MQTT_CONNECTION_STATE = False return False
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")
async def main(broker_host, token, loop): global MQTTClient, QueuePersister, CustomMicroUser, logging, after_get, STOP, asyncio logging.info("Client ID %s", os.environ.get('MQTT_CLIENT_ID')) client = MQTTClient(os.environ.get('MQTT_CLIENT_ID')) client.set_auth_credentials(token, None) await client.connect(broker_host) queuePersist = QueuePersister(client, loop) users_to_get = [] for i in range(1, 10000): users_to_get.append(asyncio.create_task(queuePersist.get(CustomMicroUser(pk=1), after_get))) await asyncio.gather( *users_to_get ) await STOP.wait() 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()
class Mqtt(Connector): def __init__(self, config, asm=None): self.name = "mqtt" self.config = config self.asm = asm self.default_room = "MyDefaultRoom" self.client = None 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") async def listen(self): self.client.subscribe(self.asm.name + "/#", qos=1) stop = asyncio.Event() await stop.wait() @register_event(Message) async def respond(self, message): self.client.publish(self.asm.name, 'Message payload', response_topic='RESPONSE/TOPIC') async def disconnect(self): # Disconnect from the service await self.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)
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)
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)
class MQTTClient(Client): ''' Client for subscribing to a broker and pipe incomming messages to configured producer. ''' def __init__( self, **kwargs: Any, ) -> None: super().__init__(**kwargs) self._inner_client = GMQTTClient(None) self._inner_client.on_connect = self.on_connect self._inner_client.on_message = self.on_message self._inner_client.on_disconnect = self.on_disconnect self._inner_client.on_subscribe = self.on_subscribe self._inner_client.pipe_message = self.pipe_message if not self.username is None: self._inner_client.set_auth_credentials(self.username, self.password) async def connect(self, topics: Tuple[str, int]) -> None: ''' Connects to broker. ''' LOG.debug('Connecting to MQTT broker.') try: await self._inner_client.connect(self.uri, 1883, keepalive=60, version=MQTTv311) subscriptions = [Subscription(t[0], qos=t[1]) for t in topics] self._inner_client.subscribe(subscriptions, subscription_identifier=1) await self.producer.connect() self.connected = True except: self.connected = False async def disconnect(self) -> None: await self._inner_client.disconnect() await self.producer.disconnect() self.connected = False