def mqtt(self): if not hasattr(self, '_mqtt_client'): self.responses = {} self.ready = False client = MQTTClient() client.username_pw_set(self.apikey) client.on_connect = self._on_connect client.on_message = self._on_message client.on_subscribe = self._on_subscribe client.connect(self.client.endpoint.replace('mqtt://', '')) self._mqtt_client = client # Start the loop and wait for the connection to be ready self._mqtt_client.loop_start() while not self.ready: time.sleep(.1) return self._mqtt_client
def __init__(self, topic, host=DEFAULT_HOST, port=DEFAULT_PORT): Client.__init__(self) self.user_data_set({'topic': 'altie/#',}) self.connect(host=host, port=port) self.on_connect = self.on__connect self.on_message = self.on__message self.loop_start()
class MqttClient(TransportClient): def __init__(self, host_name: str, settings: MqttSettings): self.host_name = host_name self.settings = settings self.sub_topic_root = f"label_servers/print/{host_name}" self._callback: Optional[Callable[[PrintRequest], Any]] = None # Configure the client self.client = Client(self.host_name) # TLS settings if we have them if self.settings.tls_cafile is not None and self.settings.tls_cafile.strip( ): self.client.tls_set(self.settings.tls_cafile) self.client.connect(settings.mqtt_broker_host, settings.mqtt_broker_port, 60) self.client.on_connect = self._on_connect self.client.on_message = self._on_message def _on_connect(self, client: Client, user_data, flags, reason_code, properties=None): logger.info(f"Connected with reason code {reason_code}") sub_topic = f"{self.sub_topic_root}/#" logger.info(f"Subscribing to: {sub_topic}") client.subscribe(sub_topic) client.will_set(f"label_servers/status/{self.host_name}", json.dumps({"online": False})) def _on_message(self, client: Client, user_data, message: MQTTMessage): logger.info(f"Received Message: {message.topic}") try: # Remove topic root stripped = message.topic.replace(self.sub_topic_root, "").strip("/") # Print requests should be of the form "<printer_serial>/<mode>" parts = stripped.split("/") if len(parts) >= 2: serial, mode, *_ = parts request = PrintRequest(serial, RequestMode.parse(mode), message.payload) if self._callback: self._callback(request) except Exception as e: logger.error("Error processing received message", exc_info=e) def publish(self, status: HostStatus): self.client.publish(f"label_servers/status/{self.host_name}", json.dumps(status.as_dict())) def start(self, on_message: Callable[[PrintRequest], None]): self._callback = on_message self.client.loop_start()
def __init__(self, mac, host, ca_cert): Thread.__init__(self) self._mac = mac self._host = host self._ca_cert = ca_cert self._running = False self._mutex = Lock() self._client = Client(f"Moody{randint(100, 999)}") self._client.tls_set(ca_certs=ca_cert) # When receiving data with a delegate, you also receive a characteristic handle # This is a mapping of those characteristic for later usage self._handle_mappings = {}
def __init__(self, ip, port, username, password, connection_callback): self.logger = logging.getLogger("mqtt") self.mqtt = Client() if username is not None: self.mqtt.username_pw_set(username, password) self.mqtt.on_connect = self._on_connect self.mqtt.on_message = self._on_message self.ip = ip self.port = port self.connection_callback = connection_callback self.queue = []
def on_message(client: mqtt.Client, userdata, msg: mqtt.MQTTMessage): print("Printing shopping list", flush=True) try: shopping_list = get_shopping_list(userdata) except selenium.common.exceptions.WebDriverException as e: print(e) return data = json.dumps({ "subject": "Shopping List", "message": shopping_list }) client.publish("printer/print", data)
def on_message(self, client: mqtt.Client, userdata, message: mqtt.MQTTMessage): # Check if this is a message that sets the lock if message.topic == self.set_topic or message.topic == self.scheduler_topic: # Read the target state lock: str = message.payload.decode("utf-8") print("Setting the lock to %s" % lock) self.last_state = lock # Echo it back response = lock client.publish(self.state_topic, response, qos=1, retain=True) else: # Pass the message down SIISThing.on_message(self, client, userdata, message)
def __init__(self, app=None): # type: (Flask) -> None self.app = app self._connect_handler = None self._disconnect_handler = None self.client = Client() self.client.on_connect = self._handle_connect self.client.on_disconnect = self._handle_disconnect self.topics = [] # type: List[str] self.connected = False if app is not None: self.init_app(app)
def register(self, discovery_prefix: str, mqtt_client: MqttClient, obd: OBDAsync): def callback(value): logger.debug(f'Incoming value for {self.cmd} -> {value}') try: self._process_value(mqtt_client, value) except Exception as e: logger.error( f'Error while processing value. ({self.cmd} -> {value})', exc_info=e) info = self._get_discovery_info(discovery_prefix) mqtt_client.publish(info.topic, json.dumps(info.payload), retain=True) obd.watch(self._cmd, callback)
class Producer: def __init__(self): self.client = Client("sample-producer") self.client.on_connect = self.on_connect self.client.on_publish = self.on_publish self.client.username_pw_set(username=config.RABBITMQ_USERNAME, password=config.RABBITMQ_PASSWORD) self.client.connect(config.RABBITMQ_HOST, config.RABBITMQ_PORT, 60) def on_connect(self, cli, userdata, flags, rc): logging.debug("Connected: " + str(rc)) def on_publish(self, mqttc, metadata, rc): logging.debug("Published: " + str(rc))
class Command(BaseCommand): help = 'Long-running Daemon Process to Integrate MQTT Messages with Django' def _create_default_user_if_needed(self): # make sure the user account exists that holds all new devices try: User.objects.get(username=settings.DEFAULT_USER) except User.DoesNotExist: print("Creating user {} to own new LAMPI devices".format( settings.DEFAULT_USER)) new_user = User() new_user.username = settings.DEFAULT_USER new_user.password = '******' new_user.is_active = False new_user.save() def _on_connect(self, client, userdata, flags, rc): self.client.message_callback_add('$SYS/broker/connection/+/state', self._device_broker_status_change) self.client.subscribe('$SYS/broker/connection/+/state') def _create_mqtt_client_and_loop_forever(self): self.client = Client() self.client.on_connect = self._on_connect self.client.connect('localhost', port=50001) self.client.loop_forever() def _device_broker_status_change(self, client, userdata, message): print("RECV: '{}' on '{}'".format(message.payload, message.topic)) # message payload has to treated as type "bytes" in Python 3 if message.payload == b'1': # broker connected results = re.search(MQTT_BROKER_RE_PATTERN, message.topic.lower()) device_id = results.group('device_id') try: device = Lampi.objects.get(device_id=device_id) print("Found {}".format(device)) except Lampi.DoesNotExist: # this is a new device - create new record for it new_device = Lampi(device_id=device_id) uname = settings.DEFAULT_USER new_device.user = User.objects.get(username=uname) new_device.save() print("Created {}".format(new_device)) # send association MQTT message new_device.publish_unassociated_msg() def handle(self, *args, **options): self._create_default_user_if_needed() self._create_mqtt_client_and_loop_forever()
def __init__(self, gateway, config, connector_type): super().__init__() self.__log = log self.config = config self.__connector_type = connector_type self.statistics = {'MessagesReceived': 0, 'MessagesSent': 0} self.__gateway = gateway self.__broker = config.get('broker') self.__mapping = config.get('mapping') self.__server_side_rpc = config.get('serverSideRpc') self.__service_config = {"connectRequests": None, "disconnectRequests": None} self.__attribute_updates = [] self.__get_service_config(config) self.__sub_topics = {} client_id = ''.join(random.choice(string.ascii_lowercase) for _ in range(23)) self._client = Client(client_id) self.setName(config.get("name", self.__broker.get("name", 'Mqtt Broker ' + ''.join(random.choice(string.ascii_lowercase) for _ in range(5))))) if "username" in self.__broker["security"]: self._client.username_pw_set(self.__broker["security"]["username"], self.__broker["security"]["password"]) if "caCert" in self.__broker["security"] or self.__broker["security"].get("type", "none").lower() == "tls": ca_cert = self.__broker["security"].get("caCert") private_key = self.__broker["security"].get("privateKey") cert = self.__broker["security"].get("cert") if ca_cert is None: self._client.tls_set_context(ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)) else: try: self._client.tls_set(ca_certs=ca_cert, certfile=cert, keyfile=private_key, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None) except Exception as e: self.__log.error("Cannot setup connection to broker %s using SSL. Please check your configuration.\nError: %s", self.get_name(), e) self._client.tls_insecure_set(False) self._client.on_connect = self._on_connect self._client.on_message = self._on_message self._client.on_subscribe = self._on_subscribe self.__subscribes_sent = {} # For logging the subscriptions self._client.on_disconnect = self._on_disconnect self._client.on_log = self._on_log self._connected = False self.__stopped = False self.daemon = True
class Seller: ''' Set objects for sale and publish them on 'Available-items' topic ''' def __init__(self, number_items, broker='localhost', auth=None): self.number_of_items = number_items self.auth = auth self.client = Client() if auth != None: (usr, pwd) = auth self.client.username_pw_set(usr, pwd) self.client.connect(broker) def sell_process(self, update=False): available_itms = ''.join( [str(x) + ' ' for x in range(1, self.number_of_items + 1)]) self.client.publish('Available-items', available_itms) while update: self.client.publish('Available-items', available_itms) time.sleep(3 * random.random()) def sell(self): Process(target=self.sell_process, args=()).start()
def start_sending(cln: mqtt.Client): # For 0 to infinity for next_value in count(): # Form data payload current_data = datetime.datetime.now() payload = f"Current time is {current_data}. Message #{next_value}" # Publish message cln.publish(topic_name, payload) # Wait a little bit sleep(0.5)
def __init__(self, host: str, token: str): super().__init__(daemon=True) self.host = host self.miio = Device(host, token) self.mqtt = Client() self.mqtt.on_connect = self.on_connect self.mqtt.on_disconnect = self.on_disconnect self.mqtt.on_message = self.on_message self.mqtt.connect_async(host) if isinstance(self.log, str): self.log = utils.get_logger(self.log)
class MoodyBLEWrapper(Thread): def __init__(self, mac, host, ca_cert): Thread.__init__(self) self._mac = mac self._host = host self._ca_cert = ca_cert self._running = False self._mutex = Lock() self._client = Client(f"Moody{randint(100, 999)}") self._client.tls_set(ca_certs=ca_cert) # When receiving data with a delegate, you also receive a characteristic handle # This is a mapping of those characteristic for later usage self._handle_mappings = {} def run(self): self._running = True self._connect(host=self._host) with Peripheral(self._mac) as peripheral: for service in list(peripheral.getServices())[2:]: print(service, service.uuid.getCommonName()) char_uuids = [str(c.uuid) for c in service.getCharacteristics()] name_char = service.getCharacteristics(char_uuids[0])[0] value_char = service.getCharacteristics(char_uuids[1])[0] service_name = name_char.read().decode() self._handle_mappings[value_char.valHandle] = service_name mqtt_delegate = _MQTTDelegate(client=self._client, client_mutex=self._mutex, handle_map=self._handle_mappings) peripheral.withDelegate(mqtt_delegate) peripheral.writeCharacteristic(value_char.valHandle + 1, b"\x01\x00") while self._running: peripheral.waitForNotifications(1) peripheral.disconnect() def _connect(self, host, port=None): if not port: port = 8883 self._client.connect(host=host, port=port) self._client.loop_start() def stop(self): self._running = False self._client.loop_stop() self._client.disconnect()
def __init__( self, *, name: str, port: int, off_cmd: Sequence[str], on_cmd: Sequence[str], mqtt_port: int = 1883, mqtt_pw: str = None, mqtt_user: str = None, mqtt_server: str = "127.0.0.1", mqtt_client_id: str = "", state_cmd: str = None, ) -> None: """Initialize an MQTTPlugin instance. Kwargs: name: device name port: Port for Fauxmo to make this device avail to Echo mqttport: MQTT server port mqttserver: MQTT server address mqttclientid: MQTT client id mqttuser: MQTT username mqttpw: MQTT password off_cmd: [ MQTT Queue, value to be publshed as str ] to turn off on_cmd: [ MQTT Queue, value to be publshed as str ] to turn on state_cmd: MQTT Queue to get state """ self.on_cmd, self.on_value = on_cmd[0], on_cmd[1] self.off_cmd, self.off_value = off_cmd[0], off_cmd[1] self.state_cmd = state_cmd self.status = "unknown" self._subscribed = False self.client = Client(client_id=mqtt_client_id) if mqtt_user or mqtt_pw: self.client.username_pw_set(mqtt_user, mqtt_pw) self.client.on_connect = self.on_connect self.client.on_subscribe = self.on_subscribe self.client.on_message = self.on_message self.client.connect(mqtt_server, mqtt_port, 60) super().__init__(name=name, port=port) # Looping thread only seems necessary for status updates if self.state_cmd is not None: self.client.loop_start()
def set_up(host, port, subscribe_to_topics_func): global _instance, _subscribe_to_topics_func _subscribe_to_topics_func = subscribe_to_topics_func _instance = Client() _instance.on_connect = _on_connect _instance.on_message = _on_message _instance.connect(host, port) _instance.loop_start()
def on_connect(client: Client, userdata, flags, rc, properties=None): """ mqtt连接回调函数 """ global isOk status = ['连接成功', '协议版本错误', '客户端标识符无效', '服务器不可用', '用户名或密码错误', '未授权'] if rc != 0: sys.exit(status[rc]) else: with open('captured_packet.json', encoding='utf-8') as f: packet_info = json.load(f) # 发布信息 print('🙉 代理服务器连接成功!') client.publish(packet_info['topic'], packet_info['msg'], 1) print('🙊 假数据包发送成功!') isOk = True client.disconnect()
def unsubscribe(self, mqttclient: MqttClient) -> None: super().unsubscribe(mqttclient) mqttclient.unsubscribe(self.stateTopic) mqttclient.unsubscribe(self.heatingTopic) mqttclient.unsubscribe(self.setpointTopic) mqttclient.unsubscribe(self.ackAlarmTopic) for topic in self.tempReferences: mqttclient.unsubscribe(topic)
def ensure_mqtt(host): mqtt_client = MQTTClient() mqtt_client.on_connect = mqtt_on_connect mqtt_client.message_callback_add('embrace/sensors', mqtt_on_message_sensor) mqtt_client.message_callback_add('embrace/topology', mqtt_on_message_topology) mqtt_client.connect(host, 1883, 60) return mqtt_client
def __init__(self, host='127.0.0.1', port=1883, username=None, password=None, channel_prefix=None): import uuid from paho.mqtt.client import Client self.host = host self.port = port self.username = username self.password = password self.channel_prefix = channel_prefix clientid = str(uuid.uuid4()) self.mqttclient = Client(client_id=clientid) if self.username: self.mqttclient.username_pw_set(self.username, self.password or None) self.mqttclient.on_connect = self._on_connect self.mqttclient.on_message = self._on_message self._connect()
def onMQTTConnected(client: Client, data, flas, rc): """Mqtt服务器连接成功回调函数 :param client: paho mqtt对象 :type client: obj :param data: 私有用户消息 :type data: obj :param flas: Broker返回的连接标志 :type flas: obj :param rc: 连接结果 :type rc: Int """ # TODO: hardcoded Topic. need make it configuable later client.subscribe("testHome/rpc", qos=2) logger.info('successfully connect to remote mqtt broker')
def __init__(self, broker, topic="iot-1/d/%012x/evt/%s/json", hostname=None, hostport=1883, username=None, password=None, keepalive=60): EventSink.__init__(self, broker) self._client = Paho() self._client.on_connect = \ lambda mosq, obj, rc: self._on_connect(mosq, obj, rc) self._client.on_disconnect = \ lambda mosq, obj, rc: self._on_disconnect(mosq, obj, rc) self._client.on_publish = \ lambda mosq, obj, mid: self._on_publish(mosq, obj, mid) self._topic_format = topic self._topic = self._topic_format % (0, "%s") self._hostname = hostname self._hostport = hostport self._username = username self._password = password self._keepalive = keepalive self._loopflag = False self._neta = None
def connect(self): # A connection to iot is established at the beginning and if publish fails self.azure_iot_comm = Client(client_id=self.device_name, protocol=self.mqtt_version) self.azure_iot_comm.on_connect = self.on_connect self.azure_iot_comm.on_disconnect = self.on_disconnect self.azure_iot_comm.on_message = self.onmsg self.azure_iot_comm.username_pw_set( username=f"{self.iot_broker}/{self.device_name}") self.azure_iot_comm.tls_set(self.iot_ca_cert_path, self.iot_client_cert_path, self.iot_client_key_path, tls_version=self.tls_version, cert_reqs=ssl.CERT_REQUIRED) self.azure_iot_comm.connect(self.iot_broker, self.iot_port) self.azure_iot_comm.loop_start()
def __init__(self, host: str, token: str, config: dict): super().__init__(daemon=True) self.host = host self.miio = Device(host, token) self.mqtt = Client() self.mqtt.on_connect = self.on_connect self.mqtt.on_disconnect = self.on_disconnect self.mqtt.on_message = self.on_message self.mqtt.connect_async(host) self.debug = config['debug'] if 'debug' in config else '' self.devices = config['devices'] if 'devices' in config else {} self.updates = {} self.setups = {}
def _on_connect(self, client: paho_mqtt.Client, user_data: Any, flags: Dict[str, Any], reason_code: Union[int, paho_mqtt.ReasonCodes], properties: Optional[paho_mqtt.Properties] = None) -> None: logging.info("MQTT Client Connected") if reason_code == 0: subs = [(k, v[0]) for k, v in self.subscribed_topics.items()] if subs: res, msg_id = client.subscribe(subs) if msg_id is not None: sub_fut: asyncio.Future = asyncio.Future() topics = list(self.subscribed_topics.keys()) sub_fut.add_done_callback( BrokerAckLogger(topics, "subscribe")) self.pending_acks[msg_id] = sub_fut self.connect_evt.set() else: if isinstance(reason_code, int): err_str = paho_mqtt.connack_string(reason_code) else: err_str = reason_code.getName() self.server.set_failed_component("mqtt") self.server.add_warning(f"MQTT Connection Failed: {err_str}")
def __init__(self, client: mclient.Client, topic: str, callback, logger: logging.Logger, QOS=0): super().__init__() if not callable(callback): raise AttributeError("callback muss aufrufbar sein.") self.name = "MsgThr" self.setDaemon(False) self._cancel_new_when_running = False self._sleeping = True self._callback = callback self._message_queue = queue.Queue() self._logger = logger.getChild("mmThread-{}".format(topic)) self._mutex = thr.Lock() self.start() client.subscribe(topic, qos=QOS) client.message_callback_add(topic, self.__mqtt_callback) self._kill = False
def _create_mqtt_client(params): mqttc = Client( client_id=params.get("client_id", ''), clean_session=params.get('clean_session'), protocol=_to_protocol(params.get('protocol')), transport=_get_transport(params), ) for name in _MQTT_NESTED_PARAMETER: if name not in params: continue logger.debug(f'invoke: {name}({params[name]})') getattr(mqttc, name)(**params[name]) mqttc.enable_logger(logger) return mqttc
def test_run_path_exception(self, isdir_mock): isdir_mock.return_value = False client_mock = Client(MagicMock()) mqtt_client = MQTT(client_mock) with pytest.raises(ValueError, match=r'wrong path'): mqtt_client.run()
def test_run_success(self, load_subscribed_topics_mock, isdir_mock): # mock function call to load subscribed topics load_subscribed_topics_mock.return_value = MagicMock() input = [0, 0, 1] isdir_mock.return_value = True loop_mock = MagicMock() loop_mock.side_effect = input client_mock = Client(MagicMock()) client_mock.connect = MagicMock() client_mock.loop = loop_mock mqtt_client = MQTT(client_mock) mqtt_client.run() self.assertEqual(client_mock.connect.call_count, 1) self.assertEqual(client_mock.loop.call_count, len(input))
def __init__(self, broker, hostname=None, hostport=1883, username=None, password=None, keepalive=60, **kwargs): super(MqttApplication, self).__init__(broker=broker, **kwargs) self._client = MqttClient() self._client.on_connect = \ lambda mqtt_client, obj, rc: self._on_connect(mqtt_client, obj, rc) self._client.on_disconnect = \ lambda mqtt_client, obj, rc: self._on_disconnect(mqtt_client, obj, rc) self._client.on_publish = \ lambda mqtt_client, obj, mid: self._on_publish(mqtt_client, obj, mid) self._client.on_subscribe = \ lambda mqtt_client, userdata, mid, qos: self._on_subscribe(mqtt_client, mid, qos) self._client.on_message = \ lambda mqtt_client, userdata, msg: self._on_message(mqtt_client, msg.payload, msg.topic, msg.qos, msg.retain) self._hostname = hostname self._hostport = hostport self._username = username self._password = password self._keepalive = keepalive self._is_connected = False
def __init__(self, broker, topic="iot-1/d/%012x/evt/%s/json", hostname=None, hostport=1883, username=None, password=None, keepalive=60): super(MQTTEventSink, self).__init__(broker=broker) self._client = Paho() self._client.on_connect = \ lambda mosq, obj, rc: self._on_connect(mosq, obj, rc) self._client.on_disconnect = \ lambda mosq, obj, rc: self._on_disconnect(mosq, obj, rc) self._client.on_publish = \ lambda mosq, obj, mid: self._on_publish(mosq, obj, mid) self._topic_format = topic self._topic = self._topic_format % (0, "%s") self._hostname = hostname self._hostport = hostport self._username = username self._password = password self._keepalive = keepalive self._is_connected = False
class MQTT(Component): def init(self, url): self.url = url host, port = parse_bind(self.url) self.client = Client() self.client.on_connect = self._on_connect self.client.on_message = self._on_message self.client.connect(host, port) self.client.loop_start() def _on_connect(self, client, userdata, flags, rc): print("Connected with result code {0}".format(rc)) def _on_message(self, client, userdata, msg): print("{0} {1}".format(msg.topic, msg.payload))
def init(self, url): self.url = url host, port = parse_bind(self.url) self.client = Client() self.client.on_connect = self._on_connect self.client.on_message = self._on_message self.client.connect(host, port) self.client.loop_start()
def _run(self): ''' The main function of this task. ''' # join function input buffer, it's a shared memory join_in_buf = [None] * len(self.idf_confs) def on_connect(client, userdata, rc): log.info('ESM connect to mqtt broker with return code %s', rc) # create odf publish partial function for conf in self.odf_confs: conf['pub'] = partial(client.publish, conf['topic']) for idx, idf in enumerate(self.idf_confs): topic = idf['topic'] client.subscribe(topic) client.message_callback_add( topic, self._msg_callback( idf.get('func'), self.join_func.get('func'), self.odf_confs, join_in_buf, idx)) mqtt_conn = Client() mqtt_conn.on_connect = on_connect mqtt_conn.connect(config.mqtt_conf['host'], port=config.mqtt_conf['port']) mqtt_conn.loop_forever()
def example_use(): access_key = os.environ["AWS_ACCESS_KEY_ID"] secret_key = os.environ["AWS_SECRET_ACCESS_KEY"] port = 8883 region = "eu-west-1" # This is specific to your AWS account host = "abc123def456.iot.{0:s}.amazonaws.com".format(region) extra_headers = functools.partial( get_amazon_auth_headers, access_key, secret_key, region, host, port, ) client = Client(transport="websockets") client.ws_set_options(headers=extra_headers)
def __init__(self, client_id, host, port=1883, **kwargs): self._logger = logging.getLogger("gsensors.PipaMQTTClient") self._host = host self._port = port self._mqtt_client = Client(client_id=client_id, clean_session=False) self._mqtt_client.on_connect = self.on_connect self._mqtt_client.on_disconnect = self.on_disconnect self._mqtt_client.on_message = self.on_message self.worker = None self.worker_runner = None self.topics_sources = {} self.running = False self.connected = False
def __init__(self, peer): """ Initialize client :param peer: The peer behind the MQTT client. :return: """ self.__peer = peer self.__mqtt = MqttClient() self.__mqtt.on_connect = self._on_connect self.__mqtt.on_disconnect = self._on_disconnect self.__mqtt.on_message = self._on_message self.__callback_handler = None self.__WILL_TOPIC = "/".join( (TOPIC_PREFIX, peer.app_id, RIP_TOPIC))
def __init__(self, verbose=False): """Class constructor Called when the object is initialized Args: verbose (bool): verbose mode """ try: self._mh = MasterHead.get_head() self._client = Client() self._client.on_message = self._on_message self._verbose = verbose if (self._verbose): self._client.on_log = self._on_log except MQTTException as ex: self._mh.demsg('htk_on_error', ex, self._mh.fromhere())
class MQTTEventSink(EventSink): def __init__(self, broker, topic="iot-1/d/%012x/evt/%s/json", hostname=None, hostport=1883, username=None, password=None, keepalive=60): EventSink.__init__(self, broker) self._client = Paho() self._client.on_connect = \ lambda mosq, obj, rc: self._on_connect(mosq, obj, rc) self._client.on_disconnect = \ lambda mosq, obj, rc: self._on_disconnect(mosq, obj, rc) self._client.on_publish = \ lambda mosq, obj, mid: self._on_publish(mosq, obj, mid) self._topic_format = topic self._topic = self._topic_format % (0, "%s") self._hostname = hostname self._hostport = hostport self._username = username self._password = password self._keepalive = keepalive self._loopflag = False self._neta = None def _on_connect(self, mosq, obj, rc): self._topic = self._topic_format % (get_mac(), "%s") log.debug("MQTT publisher connected: " + str(rc)) def _on_disconnect(self, mosq, obj, rc): log.debug("MQTT publisher disconnected: " + str(rc)) def _on_publish(self, mosq, obj, mid): #log.debug("MQTT publisher published: " + str(mid)) pass def _try_connect(self): if self._username is not None and self._password is not None: self._client.username_pw_set(self._username, self._password) try: self._client.connect(self._hostname, self._hostport, self._keepalive) except socket.gaierror: return False self._client.loop_start() self._loopflag = True return True def on_start(self): return self._try_connect() def send(self, encoded_event): # Fill in the blank "%s" left in self._topic import json # extract the actual topic string event = json.loads(encoded_event) topic_event_type = event["d"]["event"] topic = self._topic % topic_event_type # Check to see if event is from neighbors # and need to be published to Mqtt server if "published" in event["d"]: if event["d"]["published"] == 1: return True else: del event["d"]["published"] # Publish message res, mid = self._client.publish(topic, encoded_event) if res == paho.mqtt.client.MQTT_ERR_SUCCESS: log.info("MQTT message published to " + topic) elif res == paho.mqtt.client.MQTT_ERR_NO_CONN: log.error("MQTT publisher failure: No connection") return False else: log.error("MQTT publisher failure: Unknown error") return False return True def check_available(self, event): if self._neta is not None and not self._neta: return False if not self._loopflag: if not self._try_connect(): log.error("MQTT publisher failure: Cannot connect") return False return True def on_event(self, event, topic): et = event.get_type() ed = event.get_raw_data() if et == "internet_access": self._neta = ed def encode_event(self, event): # return event.to_json() return json.dumps({"d": event.to_map()})
from paho.mqtt.client import Client def on_connect(client, userdata, rc): client.subscribe("#") def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) client = Client() client.on_message = on_message client.on_connect = on_connect client.connect("broker.mqttdashboard.com") client.loop_forever()
class JMSClient(object): """Class JMSClient """ _mh = None _client = None _host = None _port = None _user = None _passw = None _verbose = None _is_connected = None _messages = [] def __init__(self, verbose=False): """Class constructor Called when the object is initialized Args: verbose (bool): verbose mode """ try: self._mh = MasterHead.get_head() self._client = Client() self._client.on_message = self._on_message self._verbose = verbose if (self._verbose): self._client.on_log = self._on_log except MQTTException as ex: self._mh.demsg('htk_on_error', ex, self._mh.fromhere()) @property def client(self): """ MQTT client property getter """ return self._client @property def host(self): """ server host property getter """ return self._host @property def port(self): """ server port property getter """ return self._port @property def user(self): """ username property getter """ return self._user @property def passw(self): """ user password property getter """ return self._passw @property def verbose(self): """ verbose property getter """ return self._verbose @property def is_connected(self): """ is_connected property getter """ return self._is_connected def _on_log(self, client, obj, level, string): """ Callback for on_log event """ print(string) def _on_message(self, client, obj, msg): """ Callback for on_message event """ self._messages.append(msg.payload.decode()) def connect(self, host, port=1883, user=None, passw=None, timeout=10): """Method connects to server Args: host (str): hostname port (str): port user (str): username passw (str): password timeout (int): timeout Returns: bool: result Raises: event: jms_before_connect event: jms_after_connected """ try: msg = 'host:{0}, port:{1}, user:{2}, passw:{3}, timeout:{4}'.format( host, port, user, passw, timeout) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_jms_connecting', msg), self._mh.fromhere()) ev = event.Event( 'jms_before_connect', host, port, user, passw, timeout) if (self._mh.fire_event(ev) > 0): host = ev.argv(0) port = ev.argv(1) user = ev.argv(2) passw = ev.argv(3) timeout = ev.argv(4) self._host = host self._port = port self._user = user self._passw = passw if (ev.will_run_default()): if (self._user != None): self._client.username_pw_set(self._user, self._passw) setdefaulttimeout(timeout) self._client.connect(self._host, self._port) self._is_connected = True self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_jms_connected'), self._mh.fromhere()) ev = event.Event('jms_after_connect') self._mh.fire_event(ev) return True except (MQTTException, error, ValueError) as ex: self._mh.demsg('htk_on_error', ex, self._mh.fromhere()) return False def disconnect(self): """Method disconnects from server Args: none Returns: bool: result """ try: self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_jms_disconnecting'), self._mh.fromhere()) if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_jms_not_connected'), self._mh.fromhere()) return False else: self._client.disconnect() self._is_connected = False self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_jms_disconnected'), self._mh.fromhere()) return True except (MQTTException, error, ValueError) as ex: self._mh.demsg('htk_on_error', ex, self._mh.fromhere()) return False def send(self, destination_name, message): """Method sends message Args: destination_name (str): topic name message (str): message Returns: bool: result Raises: event: jms_before_send event: jms_after_send """ try: msg = 'destination_name:{0}, message:{1}'.format( destination_name, message) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_jms_sending_msg', msg), self._mh.fromhere()) if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_jms_not_connected'), self._mh.fromhere()) return False ev = event.Event('jms_before_send', destination_name, message) if (self._mh.fire_event(ev) > 0): destination_name = ev.argv(0) message = ev.argv(1) if (ev.will_run_default()): res, id = self._client.publish(destination_name, message) if (res != 0): self._mh.demsg('htk_on_error', self._mh._trn.msg( 'htk_jms_sending_error'), self._mh.fromhere()) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_jms_msg_sent'), self._mh.fromhere()) ev = event.Event('jms_after_send') self._mh.fire_event(ev) return True except (MQTTException, error, ValueError) as ex: self._mh.demsg('htk_on_error', ex, self._mh.fromhere()) return False def receive(self, destination_name, cnt=1, timeout=10): """Method receives messages Args: destination_name (str): queue name cnt (int): count of messages timeout (int): timeout to receive message Returns: list: messages Raises: event: jms_before_receive event: jms_after_receive """ try: msg = 'destination_name:{0}, count:{1}'.format( destination_name, cnt) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_jms_receiving_msg', msg), self._mh.fromhere()) if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_jms_not_connected'), self._mh.fromhere()) return None ev = event.Event('jms_before_receive', destination_name, cnt) if (self._mh.fire_event(ev) > 0): destination_name = ev.argv(0) cnt = ev.argv(1) if (ev.will_run_default()): res, id = self._client.subscribe(destination_name) if (res != 0): self._mh.demsg('htk_on_error', self._mh._trn.msg( 'htk_jms_sending_error'), self._mh.fromhere()) return None res = 0 cnt_before = 0 start = time() while (res == 0): res = self._client.loop() cnt_after = len(self._messages) if (cnt_after > cnt_before and cnt_after < cnt): cnt_before = cnt_after elif (cnt_after == cnt or time() > start + timeout): res = -1 messages = self._messages self._client.unsubscribe(destination_name) self._messages = [] self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_jms_msg_received', len(messages)), self._mh.fromhere()) ev = event.Event('jms_after_receive') self._mh.fire_event(ev) return messages except (MQTTException, error, ValueError) as ex: self._mh.demsg('htk_on_error', ex, self._mh.fromhere()) return None
class PipaMQTTClient(object): def __init__(self, client_id, host, port=1883, **kwargs): self._logger = logging.getLogger("gsensors.PipaMQTTClient") self._host = host self._port = port self._mqtt_client = Client(client_id=client_id, clean_session=False) self._mqtt_client.on_connect = self.on_connect self._mqtt_client.on_disconnect = self.on_disconnect self._mqtt_client.on_message = self.on_message self.worker = None self.worker_runner = None self.topics_sources = {} self.running = False self.connected = False def publish(self, topic, payload=None, qos=0, retain=False): # check connected if not self.connected: raise RuntimeError("MQTT client not connected ! ") if not self.running: raise RuntimeError("MQTT client not running ! ") self._mqtt_client.publish(topic, payload=payload, qos=qos, retain=retain) def PublishAction(self, topic, payload=None, retain=False): if payload is None: def _action(source, value): data = "%s" % value self._logger.debug("publish %s: %s" % (topic, data)) self.publish(topic, payload=data, retain=retain) else: def _action(*args, **kwargs): self._logger.debug("publish %s: %s" % (topic, payload)) self.publish(topic, payload=payload, retain=retain) return _action def on_disconnect(self, client, userdata, rc): self._logger.error("Disconnected with result code: "+str(rc)) self.connected = False self.connect() def on_connect(self, client, userdata, flags, rc): if rc == 0: self._logger.info("Connected to MQTT broker") self.connected = True # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. #client.subscribe("$SYS/#") #client.subscribe("#") for topic in self.topics_sources.keys(): client.subscribe(topic) else: self._logger.error("Connection fail with error: %s" % rc) def on_message(self, client, userdata, msg): self._logger.debug("get a msg %s: %s" % (msg.topic, msg.payload)) if msg.topic in self.topics_sources: source = self.topics_sources[msg.topic] source.update(msg) def register_source(self, source, topic): # check that topic has no wildcard assert "#" not in topic if topic in self.topics_sources: raise ValueError("topic already monitored") self.topics_sources[topic] = source self._mqtt_client.subscribe(topic) return source def connect(self): self.worker_runner = gevent.spawn(self._connect) def _connect(self): while not self.connected: try: #self._mqtt_client.reinitialise() self._mqtt_client.connect(host=self._host, port=self._port, keepalive=60) except socket.error as err: self._logger.error("Imposible to connect to MQTT: %s" % err) self._logger.info("Will retry in 2 seconds") gevent.sleep(2) def wait_connected(self): while not self.connected: gevent.sleep(1) def start(self): if self.running: return self.running = True self.worker = gevent.spawn(self._mqtt_loop) self.connect() def _mqtt_loop(self): while self.running: self._mqtt_client.loop(timeout=0.02) gevent.sleep(0.01)
from paho.mqtt.client import Client as MQTTClient from client.models import ServerAPIModel from client.core import make_device_client # Init mqtt client mqtt_client = MQTTClient('paho_lol') mqtt_client.connect('mqtt.acandale.com', 1883, 6000) # Create the model model = ServerAPIModel('http://localhost:8000', 'test') # Create the client cl = make_device_client(model, 'my_client', mqtt_client) # Call methods cl.no_argument_handler('payload') cl.one_argument_handler('payload', 'first_arg') cl.two_argument_handler('payload', 'first_arg', 'second_arg')
class MqttApplication(Application): """ An abstract base Application for running some type of MQTT client-based Application. """ def __init__(self, broker, hostname=None, hostport=1883, username=None, password=None, keepalive=60, **kwargs): super(MqttApplication, self).__init__(broker=broker, **kwargs) self._client = MqttClient() self._client.on_connect = \ lambda mqtt_client, obj, rc: self._on_connect(mqtt_client, obj, rc) self._client.on_disconnect = \ lambda mqtt_client, obj, rc: self._on_disconnect(mqtt_client, obj, rc) self._client.on_publish = \ lambda mqtt_client, obj, mid: self._on_publish(mqtt_client, obj, mid) self._client.on_subscribe = \ lambda mqtt_client, userdata, mid, qos: self._on_subscribe(mqtt_client, mid, qos) self._client.on_message = \ lambda mqtt_client, userdata, msg: self._on_message(mqtt_client, msg.payload, msg.topic, msg.qos, msg.retain) self._hostname = hostname self._hostport = hostport self._username = username self._password = password self._keepalive = keepalive self._is_connected = False @property def is_connected(self): return self._is_connected # Your API for pub-sub via MQTT: def mqtt_publish(self, raw_data, topic, **kwargs): """ Publishes the given data to the specified topic. :param raw_data: :type raw_data: str :param topic: :param kwargs: e.g. qos, retain; passed to self._client.publish :return: err_code, msg_id """ return self._client.publish(topic, raw_data, **kwargs) def mqtt_subscribe(self, topic, **kwargs): """ Subscribes to the specified topic. :param topic: :param kwargs: e.g. qos; passed to self._client.publish :return: err_code, msg_id """ return self._client.subscribe(topic, **kwargs) # To make use of either publish or subscribe, make sure to implement these! def _on_publish(self, mqtt_client, obj, mid): log.debug("MQTT app %s published msg %d: %s" % (self.name, mid, obj)) def _on_subscribe(self, mqtt_client, mid, qos): log.debug("MQTT app %s subscribe response msg %d: qos=%s" % (self.name, mid, qos)) def _on_message(self, mqtt_client, payload, topic, qos, retain): """Called when a message arrives on a topic we subscribed to.""" log.debug("MQTT app %s received message on topic %s: %s" % (self.name, topic, payload)) # You may want to override these functions in your concrete Application, but make sure to call super()! def _on_connect(self, mqtt_client, obj, rc): log.debug("MQTT app %s connected: %s" % (self.name, str(rc))) # need to start AFTER connecting, which is async! self._is_connected = True def _on_disconnect(self, mqtt_client, obj, rc): # sink will try reconnecting once EventReporter queries if it's available. self._is_connected = False log.debug("MQTT app %s disconnected: %s" % (self.name, str(rc))) def _try_connect(self): if self._username is not None and self._password is not None: self._client.username_pw_set(self._username, self._password) try: # NOTE: this is an async connection! self._client.connect(self._hostname, self._hostport, self._keepalive) self._client.loop_start() except socket.gaierror: return False return True def on_start(self): super(MqttApplication, self).on_start() return self._try_connect()
class Messenger(object): """ MQTT client for Herald transport. """ def __init__(self, peer): """ Initialize client :param peer: The peer behind the MQTT client. :return: """ self.__peer = peer self.__mqtt = MqttClient() self.__mqtt.on_connect = self._on_connect self.__mqtt.on_disconnect = self._on_disconnect self.__mqtt.on_message = self._on_message self.__callback_handler = None self.__WILL_TOPIC = "/".join( (TOPIC_PREFIX, peer.app_id, RIP_TOPIC)) def __make_uid_topic(self, subtopic): """ Constructs a complete UID topic. :param subtopic: The UID :return: Fully qualified topic :rtype : str """ return "/".join( (TOPIC_PREFIX, self.__peer.app_id, UID_TOPIC, subtopic)) def __make_group_topic(self, subtopic): """ Constructs a complete group topic. :param subtopic: The group name :return: Fully qualified topic :rtype : str """ return "/".join( (TOPIC_PREFIX, self.__peer.app_id, GROUP_TOPIC, subtopic)) def __handle_will(self, message): if self.__callback_handler and self.__callback_handler.on_peer_down: self.__callback_handler.on_peer_down( message.payload.decode('utf-8')) else: _log.debug("Missing callback for on_peer_down.") def _on_connect(self, *args, **kwargs): """ Handles a connection-established event. :param args: unnamed arguments :param kwargs: named arguments :return: """ _log.info("Connection established.") _log.debug("Subscribing for topic %s.", self.__make_uid_topic(self.__peer.uid)) self.__mqtt.subscribe(self.__make_uid_topic(self.__peer.uid)) self.__mqtt.subscribe(self.__make_group_topic("all")) self.__mqtt.subscribe(self.__WILL_TOPIC) for group in self.__peer.groups: _log.debug("Subscribing for topic %s.", self.__make_group_topic(group)) self.__mqtt.subscribe(self.__make_group_topic(group)) if self.__callback_handler and self.__callback_handler.on_connected: self.__callback_handler.on_connected() else: _log.warning("Missing callback for on_connect.") def _on_disconnect(self, *args, **kwargs): """ Handles a connection-lost event. :param args: unnamed arguments :param kwargs: named arguments :return: """ _log.info("Connection lost.") if self.__callback_handler and self.__callback_handler.on_disconnected: self.__callback_handler.on_disconnected() def _on_message(self, client, data, message): """ Handles an incoming message. :param client: the client instance for this callback :param data: the private user data :param message: an instance of MQTTMessage :type message: paho.mqtt.client.MQTTMessage :return: """ _log.info("Message received.") if message.topic == self.__WILL_TOPIC: self.__handle_will(message) return if self.__callback_handler and self.__callback_handler.on_message: self.__callback_handler.on_message(message.payload.decode('utf-8')) else: _log.warning("Missing callback for on_message.") def fire(self, peer_uid, message): """ Sends a message to another peer. :param peer_uid: Peer UID :param message: Message content :return: """ self.__mqtt.publish( self.__make_uid_topic(peer_uid), message, 1 ) def fire_group(self, group, message): """ Sends a message to a group of peers. :param group: Group's name :param message: Message content :return: """ self.__mqtt.publish( self.__make_group_topic(group), message, 1 ) def set_callback_listener(self, listener): """ Sets callback listener. :param listener: the listener :return: """ self.__callback_handler = listener def login(self, username, password): """ Set credentials for an MQTT broker. :param username: Username :param password: Password :return: """ self.__mqtt.username_pw_set(username, password) def connect(self, host, port): """ Connects to an MQTT broker. :param host: broker's host name :param port: broker's port number :return: """ _log.info("Connecting to MQTT broker at %s:%s ...", host, port) self.__mqtt.will_set(self.__WILL_TOPIC, self.__peer.uid, 1) self.__mqtt.connect(host, port) self.__mqtt.loop_start() def disconnect(self): """ Diconnects from an MQTT broker. :return: """ _log.info("Disconnecting from MQTT broker...") self.__mqtt.publish(self.__WILL_TOPIC, self.__peer.uid, 1) self.__mqtt.loop_stop() self.__mqtt.disconnect()
def on_broker_connect(client: mqtt_client.Client, userdata: dict, flags, rc): print('Connected with MQTT broker with result code ' + str(rc)) if userdata[USER_DATA_FIRST_CONNECT]: if int(rc) != 0: raise Exception('Connect to MQTT broker failed.') client.user_data_set({USER_DATA_FIRST_CONNECT: False})