Python paho.mqtt.client.Client() Examples

The following are 30 code examples for showing how to use paho.mqtt.client.Client(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module paho.mqtt.client , or try the search function .

Example 1
Project: mqtt2sql   Author: curzon01   File: mqtt2sql.py    License: GNU General Public License v3.0 6 votes vote down vote up
def on_connect(self, client, userdata, message, return_code):
        """
        Called when the broker responds to our connection request.

        @param client:
            the client instance for this callback
        @param userdata:
            the private user data as set in Client() or userdata_set()
        @param message:
            response message sent by the broker
        @param return_code:
            the connection result
        """
        debuglog(1, "MQTT on_connect({},{},{},{}): {}".format(client, userdata, message, return_code, mqtt.error_string(return_code)))
        for topic in self._args.mqtt_topic:
            debuglog(1, "subscribe to topic {}".format(topic))
            client.subscribe(topic, 0) 
Example 2
Project: mqtt2sql   Author: curzon01   File: mqtt2sql.py    License: GNU General Public License v3.0 6 votes vote down vote up
def on_message(self, client, userdata, message):
        """
        Called when a message has been received on a topic that the client subscribes to.
        This callback will be called for every message received.

        @param client:
            the client instance for this callback
        @param userdata:
            the private user data as set in Client() or userdata_set()
        @param message:
            an instance of MQTTMessage.
            This is a class with members topic, payload, qos, retain.
        """
        global EXIT_CODE    # pylint: disable=global-statement

        if EXIT_CODE != ExitCode.OK:
            sys.exit(EXIT_CODE)
        log(2, '{} {} [QOS {} Retain {}]'.format(message.topic, message.payload, message.qos, message.retain))

        debuglog(2, "on_message({},{},{})".format(client, userdata, message))
        if EXIT_CODE == ExitCode.OK:
            self.pool_sqlconnections.acquire()
            self.write2sql_thread = Thread(target=self.write2sql, args=(message,))
            self.write2sql_thread.start() 
Example 3
Project: mqtt2sql   Author: curzon01   File: mqtt2sql.py    License: GNU General Public License v3.0 6 votes vote down vote up
def on_publish(self, client, userdata, mid):
        """
        Called when a message that was to be sent using the publish() call
        has completed transmission to the broker.
        For messages with QoS levels 1 and 2, this means that the appropriate
        handshakes have completed. For QoS 0, this simply means that the
        message has left the client. The mid variable matches the mid
        variable returned from the corresponding publish() call, to allow
        outgoing messages to be tracked.

        @param client:
            the client instance for this callback
        @param userdata:
            the private user data as set in Client() or userdata_set()
        @param mid:
            matches the mid variable returned from the corresponding
            publish() call, to allow outgoing messages to be tracked.
        """
        debuglog(2, "on_publish({},{},{})".format(client, userdata, mid)) 
Example 4
Project: mqtt2sql   Author: curzon01   File: mqtt2sql.py    License: GNU General Public License v3.0 6 votes vote down vote up
def on_subscribe(self, client, userdata, mid, granted_qos):
        """
        Called when the broker responds to a subscribe request.

        @param client:
            the client instance for this callback
        @param userdata:
            the private user data as set in Client() or userdata_set()
        @param mid:
            Matches the mid variable returned from the corresponding
            subscribe() call.
        @param granted_qos:
            a list of integers that give the QoS level the broker has
            granted for each of the different subscription requests.
        """
        debuglog(2, "on_subscribe({},{},{},{})".format(client, userdata, mid, granted_qos)) 
Example 5
Project: mqtt2sql   Author: curzon01   File: mqtt2sql.py    License: GNU General Public License v3.0 6 votes vote down vote up
def on_log(self, client, userdata, level, string):
        """
        Called when the client has log information.

        @param client:
            the client instance for this callback
        @param userdata:
            the private user data as set in Client() or userdata_set()
        @param level:
            gives the severity of the message and will be one of
            MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING, MQTT_LOG_ERR,
            and MQTT_LOG_DEBUG. The message itself is in string.
        @param string:
            The message itself
        """
        debuglog(2, "on_log({},{},{},{})".format(client, userdata, level, string)) 
Example 6
Project: PokemonGo-Bot   Author: PokemonGoF   File: social_handler.py    License: MIT License 6 votes vote down vote up
def initialize(self):
        try:
            if DEBUG_ON:
                print('connect again')

            self._mqttc = mqtt.Client(None)
            self._mqttc.on_message = self.mqtt_on_message
            self._mqttc.on_connect = self.mqtt_on_connect
            self._mqttc.on_subscribe = self.mqtt_on_subscribe
            self._mqttc.on_publish = self.mqtt_on_publish
            self._mqttc.on_disconnect = self.on_disconnect

            # Enable this line if you are doing the snip code, off stress
            # self._mqttc.loop_start()
        except TypeError:
            print('Connect to mqtter error')
            return 
Example 7
Project: hermes-audio-server   Author: koenvervloesem   File: mqtt.py    License: MIT License 6 votes vote down vote up
def __init__(self, config, verbose, logger):
        """Initialize an MQTT client.

        Args:
            config (:class:`.ServerConfig`): The configuration of
                the MQTT client.
            verbose (bool): Whether or not the MQTT client runs in verbose
                mode.
            logger (:class:`logging.Logger`): The Logger object for logging
                messages.
        """
        self.config = config
        self.verbose = verbose
        self.logger = logger
        self.mqtt = Client()
        self.logger.debug('Using %s', pyaudio.get_portaudio_version_text())
        self.logger.debug('Creating PyAudio object...')
        self.audio = pyaudio.PyAudio()

        self.initialize()

        self.mqtt.on_connect = self.on_connect
        self.mqtt.on_disconnect = self.on_disconnect
        self.connect() 
Example 8
Project: AMS   Author: CPFL   File: event_loop.py    License: Apache License 2.0 6 votes vote down vote up
def connect(self, host, port, ca_path=None, client_path=None, key_path=None):
        self.__client = mqtt.Client(protocol=mqtt.MQTTv311, userdata=self.__user_data)

        if ca_path is not None and client_path is not None and key_path is not None:
            self.ssl_setting(ca_path, client_path, key_path)

        will = self.__user_will
        if will is None:
            event_loop_message = EventLoop.get_message(EVENT_LOOP.STATE.WILL, self.__pid)
            payload = self.__topicPub.serialize(event_loop_message)
            will = {"topic": self.__topicPub.get_path(), "payload": payload}
        self.__client.will_set(will["topic"], payload=will["payload"], qos=2, retain=False)

        self.__client.on_connect = self.__on_connect
        self.__client.on_message = self.__on_message
        self.__client.connect(host=host, port=port, keepalive=EVENT_LOOP.KEEP_ALIVE) 
Example 9
Project: mqtt-pwn   Author: akamai-threat-research   File: sonoff.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, host=DEFAULT_BROKER_HOST, port=DEFAULT_BROKER_PORT):
        self._mqtt_client = mqtt.Client()

        self.host = host
        self.port = port
        self.timeout = 10
        self.prefix = TOPIC_PREFIX
        self.listen_timeout = 5
        self.cli = None

        self.should_stop = False
        self.keyboard_interrupt_occurred = False

        self.loop_lock = Lock()

        self._mqtt_client.on_message = self.mqtt_on_message
        self._mqtt_client.on_connect = self.mqtt_on_connect 
Example 10
Project: mqtt-pwn   Author: akamai-threat-research   File: active_scanner.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, client_id=None, host=DEFAULT_BROKER_HOST, port=DEFAULT_BROKER_PORT, timeout=60, topics=None,
                 listen_timeout=60, scan_instance=None, cli=None):
        """Active Scanner object initiation"""

        self._mqtt_client = mqtt.Client(client_id)
        self.cli = cli

        if cli:
            self.host = cli.mqtt_client.host
            self.port = cli.mqtt_client.port
        else:
            self.host = host
            self.port = port

        self.timeout = timeout
        self.topics = topics
        self.listen_timeout = int(listen_timeout)
        self.scan_instance = scan_instance

        self._base_topic = '$SYS/test123'
        self._mqtt_client.on_message = self.mqtt_on_message 
Example 11
Project: thingflow-python   Author: mpi-sws-rse   File: mqtt.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, host, port=1883, client_id="", client_username="", client_password=None, server_tls=False, server_cert=None, topics=[], mock_class=None):
        self.host = host
        self.port = port
        self.client_id = client_id
        self.client_username = client_id
        self.client_password = client_password
        self.topics = topics

        self.server_tls =  server_tls
        self.server_cert = server_cert

        if mock_class:
            self.client = MockMQTTClient(self.client_id)
        else:
            self.client = paho.Client(self.client_id)

        if self.client_username:
            self.client.username_pw_set(self.client_username, password=self.client_password)

        self._connect() 
Example 12
Project: HermesLedControl   Author: project-alice-assistant   File: HermesLedControl.py    License: GNU General Public License v3.0 6 votes vote down vote up
def connectMqtt(self):
		try:
			mqttClient = mqtt.Client()

			if self._mqttUsername and self._mqttPassword:
				mqttClient.username_pw_set(self._mqttUsername, self._mqttPassword)

			mqttClient.on_log = self.onLog
			mqttClient.on_connect = self.onConnect
			mqttClient.on_message = self.onMessage

			if self._tlsFile:
				mqttClient.tls_set(certfile=self._tlsFile)
				mqttClient.tls_insecure_set(False)

			mqttClient.connect(self._mqttServer, int(self._mqttPort))
			mqttClient.loop_start()
			return mqttClient
		except:
			self._logger.fatal("Couldn't connect to mqtt, aborting")
			self.onStop()


	# noinspection PyUnusedLocal 
Example 13
Project: Internet-of-Things-with-Python   Author: PacktPublishing   File: iot_python_chapter_09_06.py    License: MIT License 6 votes vote down vote up
def on_connect(client, userdata, flags, rc):
    print("Connected to the {0} topic".
          format(topic))
    subscribe_result = client.subscribe(topic)
    publish_result_1 = client.publish(
        topic=topic,
        payload="Listening to messages in the Paho Python Client")
    publish_result_2 = publish_command(
        client,
        topic,
        "print_temperature_fahrenheit",
        "temperature_fahrenheit",
        45)
    publish_result_3 = publish_command(
        client,
        topic,
        "print_information_message",
        "text",
        "Python IoT") 
Example 14
Project: kim-voice-assistant   Author: tenstone   File: iot_mqtt_client.py    License: MIT License 6 votes vote down vote up
def __init__(self, message_callback = None):
        """
        初始化mqtt客户端
        """
        self._logger = logging.getLogger()
        self.mqtt_path = device.product_key + ".iot-as-mqtt.cn-shanghai.aliyuncs.com"  # MQTT地址
        self._topic = topic

        # 获取签名
        self.sign_dict = Sign.get_sign({
            "deviceName": device.device_name,
            "productKey": device.product_key
        }, device.device_secret)
        self.mqtt_client_id = self.sign_dict['iot_client_id'] + \
                                            "|securemode=3,signmethod=hmacsha1,timestamp=" + \
                                            self.sign_dict['timestamp'] + "|"

        self._logger.info('use mqtt device id:"%s"', self.mqtt_client_id)
        # 实例化mqtt客户端
        self.mqttc = mqtt.Client(transport="tcp", client_id=self.mqtt_client_id)
        self._iot_server = IotServer.get_instance() 
Example 15
Project: PokemonGo-Bot-Backup   Author: PokemonGoF   File: social_handler.py    License: MIT License 6 votes vote down vote up
def connect_to_mqtt(self):
        try:
            if DEBUG_ON:
                print 'connect again'
            self._mqttc = mqtt.Client(None)
            self._mqttc.on_message = self.mqtt_on_message
            self._mqttc.on_connect = self.mqtt_on_connect
            self._mqttc.on_subscribe = self.mqtt_on_subscribe
            self._mqttc.on_publish = self.mqtt_on_publish
            self._mqttc.on_disconnect = self.on_disconnect

            self._mqttc.connect("broker.pikabot.org", 1883, 60)
            # Enable this line if you are doing the snip code, off stress
            # self._mqttc.loop_start()
        except TypeError:
            print 'Connect to mqtter error'
            return 
Example 16
Project: mqtt_bridge   Author: groove-x   File: bridge.py    License: MIT License 6 votes vote down vote up
def _callback_mqtt(self, client, userdata, mqtt_msg):
        u""" callback from MQTT

        :param mqtt.Client client: MQTT client used in connection
        :param userdata: user defined data
        :param mqtt.MQTTMessage mqtt_msg: MQTT message
        """
        rospy.logdebug("MQTT received from {}".format(mqtt_msg.topic))
        now = rospy.get_time()

        if self._interval is None or now - self._last_published >= self._interval:
            try:
                ros_msg = self._create_ros_message(mqtt_msg)
                self._publisher.publish(ros_msg)
                self._last_published = now
            except Exception as e:
                rospy.logerr(e) 
Example 17
Project: microgear-python   Author: netpieio   File: client.py    License: ISC License 5 votes vote down vote up
def connect(block=False):
    global block_loop
    block_loop = block
    global current_subscribe_list
    global current_id
    times = 1
    while not microgear.accesstoken:
        get_token()
        time.sleep(times)
        times = times+10
    microgear.mqtt_client = mqtt.Client(microgear.accesstoken["token"])
    current_id = '/&id/'+str(microgear.accesstoken["token"])+'/#'
    current_subscribe_list.append('/&id/'+str(microgear.accesstoken["token"])+'/#')
    endpoint = microgear.accesstoken["endpoint"].split("//")[1].split(":")
    username = microgear.gearkey+"%"+str(int(time.time()))
    password = hmac(microgear.accesstoken["secret"]+"&"+microgear.gearsecret,microgear.accesstoken["token"]+"%"+username)
    microgear.mqtt_client.username_pw_set(username,password)
    if microgear.securemode:
        microgear.mqtt_client.tls_set(certifi.where())
        microgear.mqtt_client.connect(endpoint[0],int(microgear.gbsport), 60)
    else:
        microgear.mqtt_client.connect(endpoint[0],int(microgear.gbport), 60)
    microgear.mqtt_client.on_connect = client_on_connect
    microgear.mqtt_client.on_message = client_on_message
    microgear.mqtt_client.on_publish = client_on_publish
    microgear.mqtt_client.on_subscribe = client_on_subscribe
    microgear.mqtt_client.on_disconnect = client_on_disconnect

    if(block):
        microgear.mqtt_client.loop_forever()
    else:
        microgear.mqtt_client.loop_start()
        while True:
            time.sleep(2)
            break 
Example 18
Project: plantgateway   Author: ChristianKuehnel   File: plantgw.py    License: Apache License 2.0 5 votes vote down vote up
def _start_client(self):
        self.mqtt_client = mqtt.Client(self.config.mqtt_client_id)
        if self.config.mqtt_user is not None:
            self.mqtt_client.username_pw_set(self.config.mqtt_user, self.config.mqtt_password)
        if self.config.mqtt_ca_cert is not None:
            self.mqtt_client.tls_set(self.config.mqtt_ca_cert, cert_reqs=mqtt.ssl.CERT_REQUIRED)

        def _on_connect(client, _, flags, return_code):
            self.connected = True
            logging.info("MQTT connection returned result: %s", mqtt.connack_string(return_code))
        self.mqtt_client.on_connect = _on_connect

        self.mqtt_client.connect(self.config.mqtt_server, self.config.mqtt_port, 60)
        self.mqtt_client.loop_start() 
Example 19
Project: thingsboard-gateway   Author: thingsboard   File: tb_device_mqtt.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, host, port=1883, token=None):
        self._client = paho.Client()
        self.__host = host
        self.__port = port
        if token == "":
            log.warning("token is not set, connection without tls wont be established")
        else:
            self._client.username_pw_set(token)
        self._lock = RLock()

        self._attr_request_dict = {}
        self.stopped = False
        self.__timeout_queue = queue.Queue()
        self.__timeout_thread = Thread(target=self.__timeout_check)
        self.__timeout_thread.daemon = True
        self.__timeout_thread.start()
        self.__is_connected = False
        self.__device_on_server_side_rpc_response = None
        self.__connect_callback = None
        self.__device_max_sub_id = 0
        self.__device_client_rpc_number = 0
        self.__device_sub_dict = {}
        self.__device_client_rpc_dict = {}
        self.__attr_request_number = 0
        self._client.on_connect = self._on_connect
        # self._client.on_log = self._on_log
        self._client.on_publish = self._on_publish
        self._client.on_message = self._on_message
        self._client.on_disconnect = self._on_disconnect

    # def _on_log(self, client, userdata, level, buf):
    #     if isinstance(buf, Exception):
    #         log.exception(buf)
    #     else:
    #         log.debug("%s - %s - %s - %s", client, userdata, level, buf) 
Example 20
Project: IPDC   Author: yenkuanlee   File: deploy.py    License: MIT License 5 votes vote down vote up
def Publish(target, channel, message, mqtt_port):
	import paho.mqtt.client as mqtt
	Pclient = mqtt.Client()
        Pclient.max_inflight_messages_set(200000)
        Pclient.connect(target, int(mqtt_port))
        Pclient.loop_start()
        msg_info = Pclient.publish(channel, message, qos=1)
        #if msg_info.is_published() == False:
        #        msg_info.wait_for_publish()
        Pclient.disconnect() 
Example 21
Project: IPDC   Author: yenkuanlee   File: Dmqtt.py    License: MIT License 5 votes vote down vote up
def Publish(target,channel,message):
	client = mqtt.Client()
	client.max_inflight_messages_set(200000)
	client.connect(target, 1883)
	(rc, mid) = client.publish(channel, message, qos=1)
	#time.sleep(0.01)
	print "DMQTT RESULT : "+str(rc) 
Example 22
Project: IPDC   Author: yenkuanlee   File: Dmqtt.py    License: MIT License 5 votes vote down vote up
def Publish(target,channel,message):
	client = mqtt.Client()
	client.max_inflight_messages_set(200000)
	client.connect(target, 1883)
	(rc, mid) = client.publish(channel, message, qos=1)
	#time.sleep(0.01)
	print "DMQTT RESULT : "+str(rc) 
Example 23
Project: IPDC   Author: yenkuanlee   File: control.py    License: MIT License 5 votes vote down vote up
def Publish(self, target, channel, message):
                client = mqtt.Client()
		client.max_inflight_messages_set(200000)
                client.connect(target, 1883)
                client.loop_start()
                msg_info = client.publish(channel, message, qos=1)
                if msg_info.is_published() == False:
                        msg_info.wait_for_publish()
                client.disconnect() 
Example 24
Project: IPDC   Author: yenkuanlee   File: Dmqtt.py    License: MIT License 5 votes vote down vote up
def Publish(target,channel,message):
	client = mqtt.Client()
	#client.on_publish = on_publish
	client.max_inflight_messages_set(200000)
	client.connect(target, 1883)
	(rc, mid) = client.publish(channel, message, qos=1)
	#time.sleep(0.01)
	print "DMQTT RESULT : "+str(rc) 
Example 25
Project: IPDC   Author: yenkuanlee   File: Reduce.py    License: MIT License 5 votes vote down vote up
def Publish(self, target, channel, message):
                client = mqtt.Client()
                #client.on_publish = self.on_publish
		client.max_inflight_messages_set(200000)
                client.connect(target, 1883)
                msg_info = client.publish(channel, message, qos=0)
		###msg_info.wait_for_publish()
		time.sleep(0.1) 
Example 26
Project: IPDC   Author: yenkuanlee   File: control.py    License: MIT License 5 votes vote down vote up
def Publish(self, target, channel, message):
                client = mqtt.Client()
                #client.on_publish = self.on_publish
		client.max_inflight_messages_set(200000)
                client.connect(target, 1883)
                client.loop_start()
                msg_info = client.publish(channel, message, qos=1)
                if msg_info.is_published() == False:
                        msg_info.wait_for_publish()
                client.disconnect()
                #time.sleep(0.01) 
Example 27
Project: IPDC   Author: yenkuanlee   File: Dmqtt.py    License: MIT License 5 votes vote down vote up
def Publish(target,channel,message):
	client = mqtt.Client()
	client.max_inflight_messages_set(200000)
	client.connect(target, 1883)
	(rc, mid) = client.publish(channel, message, qos=1)
	#time.sleep(0.01)
	print("DMQTT RESULT : "+str(rc)) 
Example 28
Project: IPDC   Author: yenkuanlee   File: LocalVigilante.py    License: MIT License 5 votes vote down vote up
def Publish(target, channel, message):
	client = mqtt.Client()
	client.max_inflight_messages_set(200000)
        client.connect(target, 1883)
        client.loop_start()
        msg_info = client.publish(channel, message, qos=1)
        if msg_info.is_published() == False:
        	msg_info.wait_for_publish()
	client.disconnect() 
Example 29
Project: IPDC   Author: yenkuanlee   File: control.py    License: MIT License 5 votes vote down vote up
def Publish(self, target, channel, message):
                client = mqtt.Client()
                client.max_inflight_messages_set(200000)
                client.connect(target, 1883)
                client.loop_start()
                msg_info = client.publish(channel, message, qos=1)
                if msg_info.is_published() == False:
                        msg_info.wait_for_publish()
                client.disconnect() 
Example 30
Project: IPDC   Author: yenkuanlee   File: control.py    License: MIT License 5 votes vote down vote up
def Publish(self, target, channel, message):
                client = mqtt.Client()
		client.max_inflight_messages_set(200000)
                client.connect(target, 1883)
                client.loop_start()
                msg_info = client.publish(channel, message, qos=1)
                if msg_info.is_published() == False:
                        msg_info.wait_for_publish()
                client.disconnect()