当前位置: 首页>>代码示例>>Python>>正文


Python client.MQTTv311方法代码示例

本文整理汇总了Python中paho.mqtt.client.MQTTv311方法的典型用法代码示例。如果您正苦于以下问题:Python client.MQTTv311方法的具体用法?Python client.MQTTv311怎么用?Python client.MQTTv311使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在paho.mqtt.client的用法示例。


在下文中一共展示了client.MQTTv311方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: connect

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTv311 [as 别名]
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) 
开发者ID:CPFL,项目名称:AMS,代码行数:18,代码来源:event_loop.py

示例2: test_configures_mqtt_websockets

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTv311 [as 别名]
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") 
开发者ID:Azure,项目名称:azure-iot-sdk-python,代码行数:24,代码来源:test_mqtt_transport.py

示例3: __init__

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTv311 [as 别名]
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) 
开发者ID:PacktPublishing,项目名称:Hands-On-MQTT-Programming-with-Python,代码行数:19,代码来源:vehicle_mqtt_client.py

示例4: __init__

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTv311 [as 别名]
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() 
开发者ID:winemug,项目名称:omnipy,代码行数:27,代码来源:mq.py

示例5: __init__

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTv311 [as 别名]
def __init__(self, host, port):
        self.__client = mqtt.Client(protocol=mqtt.MQTTv311)
        self.__client.connect(host, port=port, keepalive=60) 
开发者ID:CPFL,项目名称:AMS,代码行数:5,代码来源:traffic_signal.py

示例6: __init__

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTv311 [as 别名]
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) 
开发者ID:CPFL,项目名称:AMS,代码行数:8,代码来源:graph_monitor.py

示例7: test_instantiates_mqtt_client

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTv311 [as 别名]
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
        ) 
开发者ID:Azure,项目名称:azure-iot-sdk-python,代码行数:11,代码来源:test_mqtt_transport.py

示例8: setup_client

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTv311 [as 别名]
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 
开发者ID:NickWaterton,项目名称:Roomba980-Python,代码行数:43,代码来源:roomba.py

示例9: __init__

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTv311 [as 别名]
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") 
开发者ID:mayaculpa,项目名称:hapi,代码行数:16,代码来源:communicator.py

示例10: setup_client

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTv311 [as 别名]
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 
开发者ID:NickWaterton,项目名称:Roomba980-Python,代码行数:47,代码来源:roomba.py

示例11: on_start

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTv311 [as 别名]
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 
开发者ID:MetPX,项目名称:sarracenia,代码行数:47,代码来源:exp_2mqtt.py

示例12: mqtt_connect

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTv311 [as 别名]
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") 
开发者ID:OctoPrint,项目名称:OctoPrint-MQTT,代码行数:57,代码来源:__init__.py

示例13: single

# 需要导入模块: from paho.mqtt import client [as 别名]
# 或者: from paho.mqtt.client import MQTTv311 [as 别名]
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) 
开发者ID:haynieresearch,项目名称:jarvis,代码行数:63,代码来源:publish.py


注:本文中的paho.mqtt.client.MQTTv311方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。