Python paho.mqtt.client.MQTTv311() Examples

The following are 18 code examples of paho.mqtt.client.MQTTv311(). 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 also want to check out all available functions/classes of the module paho.mqtt.client , or try the search function .
Example #1
Source File: mq.py    From omnipy with MIT License 6 votes vote down vote up
def __init__(self):
        configureLogging()
        self.logger = getLogger(with_console=True)
        get_packet_logger(with_console=True)
        self.logger.info("mq operator is starting")

        with open("settings.json", "r") as stream:
            lines = stream.read()
            txt = ""
            for line in lines:
                txt = txt + line
        self.configuration = jsonpickle.decode(txt)
        self.client = mqtt.Client(client_id=self.configuration.mqtt_clientid, protocol=mqtt.MQTTv311)
        self.client.on_connect = self.on_connect
        self.client.on_disconnect = self.on_disconnect
        self.client.on_message = self.on_message
        self.client.tls_set(ca_certs="/etc/ssl/certs/DST_Root_CA_X3.pem")
        self.i_pdm = None
        self.i_pod = None
        self.g_pdm = None
        self.g_pod = None
        self.rate_requested = None
        self.rate_request_lock = Lock()
        self.rate_check_lock = Lock()
        self.rate_check_event = Event() 
Example #2
Source File: event_loop.py    From AMS with 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 #3
Source File: vehicle_mqtt_client.py    From Hands-On-MQTT-Programming-with-Python with MIT License 6 votes vote down vote up
def __init__(self, name, vehicle):
        self.name = name
        self.vehicle = vehicle
        VehicleCommandProcessor.commands_topic = \
            "vehicles/{}/commands".format(self.name)
        VehicleCommandProcessor.processed_commands_topic = \
            "vehicles/{}/executedcommands".format(self.name)
        self.client = mqtt.Client(protocol=mqtt.MQTTv311)
        VehicleCommandProcessor.active_instance = self
        self.client.on_connect = VehicleCommandProcessor.on_connect
        self.client.on_message = VehicleCommandProcessor.on_message
        self.client.tls_set(ca_certs = ca_certificate,
            certfile=client_certificate,
            keyfile=client_key)
        self.client.connect(host=mqtt_server_host,
                            port=mqtt_server_port,
                            keepalive=mqtt_keepalive) 
Example #4
Source File: test_mqtt_transport.py    From azure-iot-sdk-python with MIT License 6 votes vote down vote up
def test_configures_mqtt_websockets(self, mocker):
        mock_mqtt_client_constructor = mocker.patch.object(mqtt, "Client")
        mock_mqtt_client = mock_mqtt_client_constructor.return_value

        MQTTTransport(
            client_id=fake_device_id,
            hostname=fake_hostname,
            username=fake_username,
            websockets=True,
        )

        assert mock_mqtt_client_constructor.call_count == 1
        assert mock_mqtt_client_constructor.call_args == mocker.call(
            client_id=fake_device_id,
            clean_session=False,
            protocol=mqtt.MQTTv311,
            transport="websockets",
        )

        # Verify websockets options have been set
        assert mock_mqtt_client.ws_set_options.call_count == 1
        assert mock_mqtt_client.ws_set_options.call_args == mocker.call(path="/$iothub/websocket") 
Example #5
Source File: vehicle_mqtt_client.py    From Hands-On-MQTT-Programming-with-Python with MIT License 6 votes vote down vote up
def __init__(self, name, vehicle):
        self.name = name
        self.vehicle = vehicle
        VehicleCommandProcessor.commands_topic = \
            "vehicles/{}/commands".format(self.name)
        VehicleCommandProcessor.processed_commands_topic = \
            "vehicles/{}/executedcommands".format(self.name)
        self.client = mqtt.Client(protocol=mqtt.MQTTv311)
        VehicleCommandProcessor.active_instance = self
        self.client.on_connect = VehicleCommandProcessor.on_connect
        self.client.on_message = VehicleCommandProcessor.on_message
        self.client.tls_set(ca_certs = ca_certificate,
            certfile=client_certificate,
            keyfile=client_key)
        self.client.connect(host=mqtt_server_host,
                            port=mqtt_server_port,
                            keepalive=mqtt_keepalive) 
Example #6
Source File: vehicle_mqtt_client.py    From Hands-On-MQTT-Programming-with-Python with MIT License 6 votes vote down vote up
def __init__(self, name, vehicle):
        self.name = name
        self.vehicle = vehicle
        VehicleCommandProcessor.commands_topic = \
            "vehicles/{}/commands".format(self.name)
        VehicleCommandProcessor.processed_commands_topic = \
            "vehicles/{}/executedcommands".format(self.name)
        self.client = mqtt.Client(protocol=mqtt.MQTTv311)
        VehicleCommandProcessor.active_instance = self
        self.client.on_connect = VehicleCommandProcessor.on_connect
        self.client.on_message = VehicleCommandProcessor.on_message
        self.client.tls_set(ca_certs = ca_certificate,
            certfile=client_certificate,
            keyfile=client_key)
        self.client.connect(host=mqtt_server_host,
                            port=mqtt_server_port,
                            keepalive=mqtt_keepalive) 
Example #7
Source File: vehicle_mqtt_client.py    From Hands-On-MQTT-Programming-with-Python with MIT License 6 votes vote down vote up
def __init__(self, name, vehicle):
        self.name = name
        self.vehicle = vehicle
        VehicleCommandProcessor.commands_topic = \
            "vehicles/{}/commands".format(self.name)
        VehicleCommandProcessor.processed_commands_topic = \
            "vehicles/{}/executedcommands".format(self.name)
        self.client = mqtt.Client(protocol=mqtt.MQTTv311)
        VehicleCommandProcessor.active_instance = self
        self.client.on_connect = VehicleCommandProcessor.on_connect
        self.client.on_message = VehicleCommandProcessor.on_message
        self.client.tls_set(ca_certs = ca_certificate,
            certfile=client_certificate,
            keyfile=client_key)
        self.client.connect(host=mqtt_server_host,
                            port=mqtt_server_port,
                            keepalive=mqtt_keepalive) 
Example #8
Source File: vehicle_mqtt_client.py    From Hands-On-MQTT-Programming-with-Python with MIT License 6 votes vote down vote up
def __init__(self, name, vehicle):
        self.name = name
        self.vehicle = vehicle
        VehicleCommandProcessor.commands_topic = \
            "vehicles/{}/commands".format(self.name)
        VehicleCommandProcessor.processed_commands_topic = \
            "vehicles/{}/executedcommands".format(self.name)
        self.client = mqtt.Client(protocol=mqtt.MQTTv311)
        VehicleCommandProcessor.active_instance = self
        self.client.on_connect = VehicleCommandProcessor.on_connect
        self.client.on_message = VehicleCommandProcessor.on_message
        self.client.tls_set(ca_certs = ca_certificate,
            certfile=client_certificate,
            keyfile=client_key)
        self.client.connect(host=mqtt_server_host,
                            port=mqtt_server_port,
                            keepalive=mqtt_keepalive) 
Example #9
Source File: graph_monitor.py    From AMS with Apache License 2.0 5 votes vote down vote up
def __init__(self, host=env["MQTT_BROKER_HOST"], port=int(env["MQTT_BROKER_PORT"])):
        self.__relations = {}

        self.__client = mqtt.Client(protocol=mqtt.MQTTv311)
        self.__client.on_message = self.__on_message
        self.__client.connect(host, port=port, keepalive=60) 
Example #10
Source File: communicator.py    From hapi with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, sm):
        self.rtuid = ""
        self.name = ""
        self.broker_name = None
        self.broker_ip = None
        self.client = mqtt.Client(clean_session=True, userdata=None, protocol=mqtt.MQTTv311)
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.on_disconnect = self.on_disconnect
        self.smart_module = sm
        self.is_connected = False
        self.scheduler_found = False
        self.broker_connections = -1
        Log.info("Communicator initialized") 
Example #11
Source File: roomba.py    From Roomba980-Python with MIT License 5 votes vote down vote up
def setup_client(self):
        if self.client is None:
            if not HAVE_MQTT:
                print("Please install paho-mqtt 'pip install paho-mqtt' "
                      "to use this library")
                return False
            self.client = mqtt.Client(
                client_id=self.blid, clean_session=self.clean,
                protocol=mqtt.MQTTv311)
            # Assign event callbacks
            self.client.on_message = self.on_message
            self.client.on_connect = self.on_connect
            self.client.on_publish = self.on_publish
            self.client.on_subscribe = self.on_subscribe
            self.client.on_disconnect = self.on_disconnect

            # Uncomment to enable debug messages
            # client.on_log = self.on_log

            # set TLS, self.cert_name is required by paho-mqtt, even if the
            # certificate is not used...
            # but v1.3 changes all this, so have to do the following:

            self.log.info("Seting TLS")
            try:
                self.client.tls_set(
                    self.cert_name, cert_reqs=ssl.CERT_NONE,
                    tls_version=ssl.PROTOCOL_TLSv1)
            except ValueError:   # try V1.3 version
                self.log.warn("TLS Setting failed - trying 1.3 version")
                self.client._ssl_context = None
                context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
                context.verify_mode = ssl.CERT_NONE
                context.load_default_certs()
                self.client.tls_set_context(context)

            # disables peer verification
            self.client.tls_insecure_set(True)
            self.client.username_pw_set(self.blid, self.password)
            return True
        return False 
Example #12
Source File: test_mqtt_transport.py    From azure-iot-sdk-python-preview with MIT License 5 votes vote down vote up
def test_instantiates_mqtt_client(self, mocker):
        mock_mqtt_client_constructor = mocker.patch.object(mqtt, "Client")

        MQTTTransport(client_id=fake_device_id, hostname=fake_hostname, username=fake_username)

        assert mock_mqtt_client_constructor.call_count == 1
        assert mock_mqtt_client_constructor.call_args == mocker.call(
            client_id=fake_device_id, clean_session=False, protocol=mqtt.MQTTv311
        ) 
Example #13
Source File: test_mqtt_transport.py    From azure-iot-sdk-python with MIT License 5 votes vote down vote up
def test_instantiates_mqtt_client(self, mocker):
        mock_mqtt_client_constructor = mocker.patch.object(mqtt, "Client")

        MQTTTransport(client_id=fake_device_id, hostname=fake_hostname, username=fake_username)

        assert mock_mqtt_client_constructor.call_count == 1
        assert mock_mqtt_client_constructor.call_args == mocker.call(
            client_id=fake_device_id, clean_session=False, protocol=mqtt.MQTTv311
        ) 
Example #14
Source File: traffic_signal.py    From AMS with Apache License 2.0 5 votes vote down vote up
def __init__(self, host, port):
        self.__client = mqtt.Client(protocol=mqtt.MQTTv311)
        self.__client.connect(host, port=port, keepalive=60) 
Example #15
Source File: __init__.py    From OctoPrint-MQTT with GNU Affero General Public License v3.0 4 votes vote down vote up
def mqtt_connect(self):
		broker_url = self._settings.get(["broker", "url"])
		broker_port = self._settings.get_int(["broker", "port"])
		broker_username = self._settings.get(["broker", "username"])
		broker_password = self._settings.get(["broker", "password"])
		broker_keepalive = self._settings.get_int(["broker", "keepalive"])
		broker_tls = self._settings.get(["broker", "tls"], asdict=True)
		broker_tls_insecure = self._settings.get_boolean(["broker", "tls_insecure"])
		broker_protocol = self._settings.get(["broker", "protocol"])
		client_id = self._settings.get(["client", "client_id"])
		clean_session = self._settings.get_boolean(["broker", "clean_session"])

		lw_active = self._settings.get_boolean(["publish", "lwActive"])
		lw_topic = self._get_topic("lw")

		if broker_url is None:
			self._logger.warn("Broker URL is None, can't connect to broker")
			return

		import paho.mqtt.client as mqtt

		protocol_map = dict(MQTTv31=mqtt.MQTTv31, MQTTv311=mqtt.MQTTv311)
		if broker_protocol in protocol_map:
			protocol = protocol_map[broker_protocol]
		else:
			protocol = mqtt.MQTTv31

		if self._mqtt is None:
			self._mqtt = mqtt.Client(client_id=client_id, protocol=protocol, clean_session=clean_session)

		if broker_username is not None:
			self._mqtt.username_pw_set(broker_username, password=broker_password)

		tls_active = False
		if broker_tls:
			tls_args = dict((key, value) for key, value in broker_tls.items() if value)
			ca_certs = tls_args.pop("ca_certs", None)
			if ca_certs:  # cacerts must not be None for tls_set to work
				self._mqtt.tls_set(ca_certs, **tls_args)
				tls_active = True

		if broker_tls_insecure and tls_active:
			self._mqtt.tls_insecure_set(broker_tls_insecure)

		_retain = self._settings.get_boolean(["broker", "retain"])
		if lw_active and lw_topic:
			self._mqtt.will_set(lw_topic, self.LWT_DISCONNECTED, qos=1, retain=_retain)

		self._mqtt.on_connect = self._on_mqtt_connect
		self._mqtt.on_disconnect = self._on_mqtt_disconnect
		self._mqtt.on_message = self._on_mqtt_message

		self._mqtt.connect_async(broker_url, broker_port, keepalive=broker_keepalive)
		if self._mqtt.loop_start() == mqtt.MQTT_ERR_INVAL:
			self._logger.error("Could not start MQTT connection, loop_start returned MQTT_ERR_INVAL") 
Example #16
Source File: exp_2mqtt.py    From sarracenia with GNU General Public License v2.0 4 votes vote down vote up
def on_start(self,parent):

      import paho.mqtt.client as mqtt
      import time

      if not hasattr(parent,'exp_2mqtt_post_broker'):
         parent.exp_2mqtt_post_broker= [ 'mqtt://localhost' ]
 
      logger=parent.logger

      if parent.no < 1: # randomize broker used in foreground testing.
         i = int( nowflt() % len(parent.exp_2mqtt_post_broker) )
      else:
         i = (parent.no-1) % len(parent.exp_2mqtt_post_broker)

      logger.info( "using: %s parent.no=%d exp_2mqtt_broker=%s" % \
           (parent.exp_2mqtt_post_broker[i], parent.no, parent.exp_2mqtt_post_broker) )

      ok, details = parent.credentials.get(parent.exp_2mqtt_post_broker[i])
      if ok:
           parent.mqtt_bs = details
      else:
           logger.error( "exp_2mqtt: post_broker credential lookup failed for %s" % parent.exp_2mqtt_post_broker )
           return

      if not hasattr(parent, 'post_exchange'):
         logger.error("exp_2mqtt: defaulting post_exchange to xpublic")
         parent.post_exchange='xpublic'
         
      u = parent.mqtt_bs.url
      if u.port == None:
            port = 1883
      else:
            port = u.port

      # https://www.iso.org/standard/69466.html - ISO standard v3.1.1 is most common.
      parent.mqtt_client = mqtt.Client( protocol=mqtt.MQTTv311 )

      if u.username != None:
          logger.error("exp_2mqtt: authenticating as %s " % (u.username) )
          parent.mqtt_client.username_pw_set( u.username, u.password )

      parent.mqtt_client.connect( u.hostname, port )
      parent.mqtt_client.loop_start()
      return True 
Example #17
Source File: roomba.py    From Roomba980-Python with MIT License 4 votes vote down vote up
def setup_client(self):
        if self.client is None:
            if not HAVE_MQTT:
                print("Please install paho-mqtt 'pip install paho-mqtt' "
                      "to use this library")
                return False
            self.client = mqtt.Client(
                client_id=self.blid, clean_session=self.clean,
                protocol=mqtt.MQTTv311)
            # Assign event callbacks
            self.client.on_message = self.on_message
            self.client.on_connect = self.on_connect
            self.client.on_publish = self.on_publish
            self.client.on_subscribe = self.on_subscribe
            self.client.on_disconnect = self.on_disconnect

            # Uncomment to enable debug messages
            # client.on_log = self.on_log

            # set TLS, self.cert_name is required by paho-mqtt, even if the
            # certificate is not used...
            # but v1.3 changes all this, so have to do the following:

            self.log.info("Setting TLS")
            try:
                self.client.tls_set(
                    self.cert_name, cert_reqs=ssl.CERT_NONE,
                    tls_version=ssl.PROTOCOL_TLS, ciphers='DEFAULT@SECLEVEL=1')
            except (ValueError, FileNotFoundError):   # try V1.3 version
                self.log.warn("TLS Setting failed - trying 1.3 version")
                self.client._ssl_context = None
                context = ssl.SSLContext(ssl.PROTOCOL_TLS)
                context.verify_mode = ssl.CERT_NONE
                context.load_default_certs()
                context.set_ciphers('DEFAULT@SECLEVEL=1')  # NW added 12/11/2019
                self.client.tls_set_context(context)
            except:
                self.log.error("Error setting TLS: %s" % traceback.format_exc())

            # disables peer verification
            self.client.tls_insecure_set(True)
            self.client.username_pw_set(self.blid, self.password)
            self.log.info("Setting TLS - OK")
            return True
        return False 
Example #18
Source File: publish.py    From jarvis with GNU General Public License v2.0 4 votes vote down vote up
def single(topic, payload=None, qos=0, retain=False, hostname="localhost",
           port=1883, client_id="", keepalive=60, will=None, auth=None,
           tls=None, protocol=paho.MQTTv311, transport="tcp"):
    """Publish a single message to a broker, then disconnect cleanly.

    This function creates an MQTT client, connects to a broker and publishes a
    single message. Once the message has been delivered, it disconnects cleanly
    from the broker.

    topic : the only required argument must be the topic string to which the
            payload will be published.

    payload : the payload to be published. If "" or None, a zero length payload
              will be published.

    qos : the qos to use when publishing,  default to 0.

    retain : set the message to be retained (True) or not (False).

    hostname : a string containing the address of the broker to connect to.
               Defaults to localhost.

    port : the port to connect to the broker on. Defaults to 1883.

    client_id : the MQTT client id to use. If "" or None, the Paho library will
                generate a client id automatically.

    keepalive : the keepalive timeout value for the client. Defaults to 60
                seconds.

    will : a dict containing will parameters for the client: will = {'topic':
           "<topic>", 'payload':"<payload">, 'qos':<qos>, 'retain':<retain>}.
           Topic is required, all other parameters are optional and will
           default to None, 0 and False respectively.
           Defaults to None, which indicates no will should be used.

    auth : a dict containing authentication parameters for the client:
           auth = {'username':"<username>", 'password':"<password>"}
           Username is required, password is optional and will default to None
           if not provided.
           Defaults to None, which indicates no authentication is to be used.

    tls : a dict containing TLS configuration parameters for the client:
          dict = {'ca_certs':"<ca_certs>", 'certfile':"<certfile>",
          'keyfile':"<keyfile>", 'tls_version':"<tls_version>",
          'ciphers':"<ciphers">}
          ca_certs is required, all other parameters are optional and will
          default to None if not provided, which results in the client using
          the default behaviour - see the paho.mqtt.client documentation.
          Defaults to None, which indicates that TLS should not be used.
          Alternatively, tls input can be an SSLContext object, which will be
          processed using the tls_set_context method.

    transport : set to "tcp" to use the default setting of transport which is
          raw TCP. Set to "websockets" to use WebSockets as the transport.
    """

    msg = {'topic':topic, 'payload':payload, 'qos':qos, 'retain':retain}

    multiple([msg], hostname, port, client_id, keepalive, will, auth, tls,
             protocol, transport)