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


Python simple.MQTTClient方法代码示例

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


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

示例1: init_client

# 需要导入模块: from umqtt import simple [as 别名]
# 或者: from umqtt.simple import MQTTClient [as 别名]
def init_client():
    global client

    print("Trying to connect to mqtt broker.")
    wifi.connect()
    try:
        client = MQTTClient(config.mqtt_client_id, config.mqtt_broker, user=config.mqtt_user,
                            password=config.mqtt_password)
        client.set_callback(callback)
        client.connect()
        print("Connected to {}".format(config.mqtt_broker))
        t = config.mqtt_topic + b"/#"
        client.subscribe(t)
        print("Subscribed to %s topic" % t)
    except:
        print("Trouble to init mqtt.") 
开发者ID:ulno,项目名称:ulnoiot-upy,代码行数:18,代码来源:handler.py

示例2: init_client

# 需要导入模块: from umqtt import simple [as 别名]
# 或者: from umqtt.simple import MQTTClient [as 别名]
def init_client():
    global client

    print("Trying to connect to mqtt broker.")
    wifi.connect()
    try:
        client = MQTTClient(config.mqtt_client_id, config.mqtt_broker, user=config.mqtt_user,
                            password=config.mqtt_password)
        client.set_callback(callback)
        client.connect()
        print("Connected to {}".format(config.mqtt_broker))
        t = config.mqtt_topic + b"/#"
        client.subscribe(t)
        print("Subscribed to %s topic" % t)
    #        client.subscribe(command_topic)
    #        client.subscribe(brightness_command_topic)
    #        client.subscribe(rgb_command_topic)
    except:
        print("Trouble to init mqtt.") 
开发者ID:ulno,项目名称:ulnoiot-upy,代码行数:21,代码来源:rgb_handler.py

示例3: _init_mqtt

# 需要导入模块: from umqtt import simple [as 别名]
# 或者: from umqtt.simple import MQTTClient [as 别名]
def _init_mqtt():
    global _client, _port
    #    global _ssl
    global _broker, _topic, _user, _password, _client_id

    print("Trying to connect to mqtt broker.")
    gc.collect()
    try:
        _client = _MQTTClient(_client_id, _broker, user=_user,
                              password=_password, port=_port, ssl=False)
        _client.set_callback(_subscription_cb)
        _client.connect()
        print("Connected to", _broker)
        t = _topic.encode() + b"/#"
        _client.subscribe(t)
        print("Subscribed to topic and subtopics of", _topic)
        _publish_ip()
    except Exception as e:
        print("Trouble to init mqtt. Exception:", e)
        _client = None 
开发者ID:ulno,项目名称:ulnoiot-upy,代码行数:22,代码来源:_mgr.py

示例4: publish_test

# 需要导入模块: from umqtt import simple [as 别名]
# 或者: from umqtt.simple import MQTTClient [as 别名]
def publish_test(client_id=CLIENT_ID, hostname=AWS_ENDPOINT, sslp=SSL_PARAMS):
    """
    Connects to AWS, publishes a message and disconnects.

    :param client_id: Unique identifier for the device connected.
    :param hostname: AWS hostname to connect to.
    :param sslp: SSL certificate parameters.
    """

    # Connect to AWS.
    client = MQTTClient(client_id, hostname, ssl=True, ssl_params=sslp)
    print("- Connecting to AWS... ", end="")
    client.connect()
    print("[OK]")
    # Publish message.
    print("- Publishing message... ", end="")
    client.publish(TOPIC, '{"message": "%s"}' % MESSAGE)
    print("[OK]")
    # Disconnect.
    client.disconnect()
    print("- Done") 
开发者ID:digidotcom,项目名称:xbee-micropython,代码行数:23,代码来源:main.py

示例5: init_client

# 需要导入模块: from umqtt import simple [as 别名]
# 或者: from umqtt.simple import MQTTClient [as 别名]
def init_client():
    global client

    print("Trying to connect to mqtt broker.")
    wifi.connect()
    try:
        client = MQTTClient(config.mqtt_client_id, config.mqtt_broker, user=config.mqtt_user,
                            password=config.mqtt_password)
        client.set_callback(set_callback)
        client.connect()
        print("Connected to {}".format(config.mqtt_broker))
        client.subscribe(topic_set)
        print("Subscribed to %s topic" % topic_set)
    except:
        print("Trouble to init mqtt.") 
开发者ID:ulno,项目名称:ulnoiot-upy,代码行数:17,代码来源:servo_switch_handler.py

示例6: init_iotf

# 需要导入模块: from umqtt import simple [as 别名]
# 或者: from umqtt.simple import MQTTClient [as 别名]
def init_iotf(self):
        # Check for network availability
        print('Waiting for network')
        if not util.wait_network(3):
            print('Cannot connect WiFi')
            raise Exception('Cannot connect WiFi')
        
        sta_if = network.WLAN(network.STA_IF)
        mac_addr = ''.join('{:02X}'.format(c) for c in sta_if.config('mac'))

        orgId = iotfcfg.orgId
        deviceType = iotfcfg.deviceType
        deviceId = iotfcfg.deviceId if hasattr(iotfcfg, 'deviceId') else mac_addr
        user = 'use-token-auth'
        authToken = iotfcfg.authToken

        clientID = 'd:' + orgId + ':' + deviceType + ':' + deviceId
        broker = orgId + '.messaging.internetofthings.ibmcloud.com'

        self.deviceId = deviceId

        if orgId == 'quickstart':
            self.mqtt = simple.MQTTClient(clientID, broker)
        else:
            self.mqtt = simple.MQTTClient(clientID, broker, user=user, password=authToken, ssl=True)
        self.mqtt.set_callback(self.sub_cb)
        self.mqtt.connect()

        if orgId == 'quickstart':
            print('https://quickstart.internetofthings.ibmcloud.com/?deviceId=test#/device/{}'.format(deviceId))
        else:
            self.mqtt.subscribe(self.COMMAND_TOPIC_LED)
            self.mqtt.subscribe(self.COMMAND_TOPIC_BUZZER)

        print('DeviceID is {}'.format(deviceId))
        print('IoT Ready') 
开发者ID:IBM-Developer-Korea,项目名称:developer-badge-2018-apps,代码行数:38,代码来源:iotfoundation.py

示例7: connect_and_subscribe

# 需要导入模块: from umqtt import simple [as 别名]
# 或者: from umqtt.simple import MQTTClient [as 别名]
def connect_and_subscribe():
    global client
    client = MQTTClient(machine_id, broker)
    client.set_callback(callback)
    client.connect()
    print("Connected to {}".format(broker))
    for topic in (b'config', b'control'):
        t = topic_name(topic)
        client.subscribe(t)
        print("Subscribed to {}".format(t)) 
开发者ID:davea,项目名称:sonoff-mqtt,代码行数:12,代码来源:main.py

示例8: get_mqtt_client

# 需要导入模块: from umqtt import simple [as 别名]
# 或者: from umqtt.simple import MQTTClient [as 别名]
def get_mqtt_client(project_id, cloud_region, registry_id, device_id, jwt):
    """Create our MQTT client. The client_id is a unique string that identifies
    this device. For Google Cloud IoT Core, it must be in the format below."""
    client_id = 'projects/{}/locations/{}/registries/{}/devices/{}'.format(project_id, cloud_region, registry_id, device_id)
    print('Sending message with password {}'.format(jwt))
    client = MQTTClient(client_id.encode('utf-8'),server=config.google_cloud_config['mqtt_bridge_hostname'],port=config.google_cloud_config['mqtt_bridge_port'],user=b'ignored',password=jwt.encode('utf-8'),ssl=True)
    client.set_callback(on_message)
    client.connect()
    client.subscribe('/devices/{}/config'.format(device_id), 1)
    client.subscribe('/devices/{}/commands/#'.format(device_id), 1)
    return client 
开发者ID:GoogleCloudPlatform,项目名称:iot-core-micropython,代码行数:13,代码来源:main.py

示例9: init_client

# 需要导入模块: from umqtt import simple [as 别名]
# 或者: from umqtt.simple import MQTTClient [as 别名]
def init_client():
    global client

    print("Trying to connect to mqtt broker.")
    wifi.connect()
    try:
        client = MQTTClient(config.mqtt_client_id, config.mqtt_broker, user=config.mqtt_user,
                            password=config.mqtt_password)
        client.set_callback(callback)
        client.connect()
        print("Connected to {}".format(config.mqtt_broker))
        client.subscribe(command_topic)
        print("Subscribed to %s topic" % t)
    except:
        print("Trouble to init mqtt.") 
开发者ID:ulno,项目名称:ulnoiot-upy,代码行数:17,代码来源:lock_handler.py

示例10: init_client

# 需要导入模块: from umqtt import simple [as 别名]
# 或者: from umqtt.simple import MQTTClient [as 别名]
def init_client():
    global client

    print("Trying to connect to mqtt broker.")
    wifi.connect()
    try:
        client = MQTTClient(config.mqtt_client_id, config.mqtt_broker, user=config.mqtt_user,
                            password=config.mqtt_password)
        client.connect()
        print("Connected to {}".format(config.mqtt_broker))
        t = config.mqtt_topic + b"/#"
        client.subscribe(t)
        print("Subscribed to %s topic" % t)
    except:
        print("Trouble to init mqtt.") 
开发者ID:ulno,项目名称:ulnoiot-upy,代码行数:17,代码来源:handler.py

示例11: subscribe_test

# 需要导入模块: from umqtt import simple [as 别名]
# 或者: from umqtt.simple import MQTTClient [as 别名]
def subscribe_test(client_id=CLIENT_ID, hostname=AWS_ENDPOINT, sslp=SSL_PARAMS,
                   msg_limit=2):
    """
    Connects to AWS, subscribes to a topic and starts listening for messages.

    :param client_id: Unique identifier for the device connected.
    :param hostname: AWS hostname to connect to.
    :param sslp: SSL certificate parameters.
    :param msg_limit: Maximum number of messages to receive before
        disconnecting from AWS..
    """

    global msgs_received

    # Connect to AWS.
    client = MQTTClient(client_id, hostname, ssl=True, ssl_params=sslp)
    client.set_callback(sub_cb)
    print("- Connecting to AWS... ", end="")
    client.connect()
    print("[OK]")
    # Subscribe to topic.
    print("- Subscribing to topic '%s'... " % TOPIC, end="")
    client.subscribe(TOPIC)
    print("[OK]")
    # Wait for messages.
    msgs_received = 0
    print('- Waiting for messages...')
    while msgs_received < msg_limit:
        client.check_msg()
        time.sleep(1)
    # Disconnect.
    client.disconnect()
    print("- Done") 
开发者ID:digidotcom,项目名称:xbee-micropython,代码行数:35,代码来源:main.py

示例12: subscribe_test

# 需要导入模块: from umqtt import simple [as 别名]
# 或者: from umqtt.simple import MQTTClient [as 别名]
def subscribe_test(client_id=CLIENT_ID, hostname=SERVER, topic=TOPIC,
                   blocking=True):
    """
    Connects to the MQTT server subscribes to a topic and waits for messages
    coming from that topic.

    :param client_id: Unique identifier for the device connected.
    :param hostname: Host name to connect to.
    :param topic: Name of the topic to subscribe.
    :param blocking: `True` to block the client waiting for messages, `False`
        to poll for messages.
    """

    # Connect to the MQTT server.
    client = MQTTClient(client_id, hostname)
    client.set_callback(sub_cb)
    print("- Connecting to '%s'... " % hostname, end="")
    client.connect()
    print("[OK]")
    # Subscribe to topic.
    print("- Subscribing to topic '%s'... " % topic, end="")
    client.subscribe(topic)
    print("[OK]")
    # Wait for messages.
    print("- Press D0 to publish a message.")
    while True:
        if blocking:
            # Blocking wait for message.
            client.wait_msg()
        else:
            # Non-blocking wait for message.
            client.check_msg()
            # Check if the button is pressed to publish a message.
            if input_pin.value() == 0:
                publish_message(client, topic, MESSAGE)
                # Wait some time to avoid button bounces.
                time.sleep(1)
            # Need to sleep to avoid 100% CPU usage.
            time.sleep(0.2) 
开发者ID:digidotcom,项目名称:xbee-micropython,代码行数:41,代码来源:main.py

示例13: __init__

# 需要导入模块: from umqtt import simple [as 别名]
# 或者: from umqtt.simple import MQTTClient [as 别名]
def __init__(self, connection_string: str, policy_name=None, expiry: int = 36000):
        self.params = dict(field.split('=', 1) for field in connection_string.split(';'))
        required_keys = ["HostName", "DeviceId", "SharedAccessKey"]
        if any(k not in self.params for k in required_keys):
            raise ValueError("connection_string is invalid, should be in the following format:",
                             "HostName=foo.bar;DeviceId=Fo0B4r;SharedAccessKey=Base64FooBar")
        self.sas_token = generate_sas_token(self.params["HostName"], self.params["SharedAccessKey"],
                                            policy_name=policy_name, expiry=expiry)
        self.username = "{host_name}/{device_id}/?api-version=2018-06-30".format(host_name=self.params["HostName"],
                                                                                 device_id=self.params["DeviceId"])
        self.password = self.sas_token

        self.mqtt_client = MQTTClient(client_id=self.params["DeviceId"], server=self.params["HostName"],
                                      user=self.username, password=self.password, ssl=True)
        self._default_subscribe_string = "devices/{device_id}/messages/devicebound/#".format(device_id=self.params["DeviceId"]) 
开发者ID:digidotcom,项目名称:xbee-micropython,代码行数:17,代码来源:main.py

示例14: publish

# 需要导入模块: from umqtt import simple [as 别名]
# 或者: from umqtt.simple import MQTTClient [as 别名]
def publish(s):
    c = MQTTClient('umqtt_client', SERVER)
    c.connect()
    c.publish(b'result', s.encode('UTF8'))
    c.disconnect() 
开发者ID:peterhinch,项目名称:micropython-async,代码行数:7,代码来源:mqtt_log.py

示例15: init_iotf

# 需要导入模块: from umqtt import simple [as 别名]
# 或者: from umqtt.simple import MQTTClient [as 别名]
def init_iotf(self):
        # Show
        self.view_manager.open_status_box()

        # Check for network availability
        self.view_manager.set_status_text('Waiting for network')
        if not util.wait_network():
            self.view_manager.set_status_text('Cannot connect WiFi')
            raise Exception('Cannot connect WiFi')
        
        sta_if = network.WLAN(network.STA_IF)
        mac_addr = ''.join('{:02X}'.format(c) for c in sta_if.config('mac'))

        orgId = iotfcfg.orgId
        deviceType = iotfcfg.deviceType
        deviceId = iotfcfg.deviceId if hasattr(iotfcfg, 'deviceId') else mac_addr
        user = 'use-token-auth'
        authToken = iotfcfg.authToken

        clientID = 'd:' + orgId + ':' + deviceType + ':' + deviceId
        broker = orgId + '.messaging.internetofthings.ibmcloud.com'

        # Check for device registration
        url = 'https://hongjs-nodered.mybluemix.net/api/badge2018/type/{}/register'.format(deviceType)
        payload = {
            'deviceId': deviceId,
            'authToken': authToken,
            'deviceInfo': {},
            'groups': [],
            'location': {},
            'metadata': {}
        }
        headers = {'token':'helloiot'}
        r = urequests.post(url, json=payload, headers=headers)
        if r.status_code == 201:
          print('OK')
        elif r.status_code == 409:
          print('Already Exists')
        else:
          print(r.text)
          raise Exception(r.text)
        r.close()

        self.deviceId = deviceId

        self.mqtt = simple.MQTTClient(clientID, broker, user=user, password=authToken, ssl=True)
        self.mqtt.set_callback(self.sub_cb)
        self.mqtt.connect()
        self.mqtt.subscribe(self.COMMAND_TOPIC_RPS)

        # Close Popup
        self.view_manager.close_status_box() 
开发者ID:IBM-Developer-Korea,项目名称:developer-badge-2018-apps,代码行数:54,代码来源:rpsmain.py


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