Python umqtt.simple.MQTTClient() Examples

The following are 19 code examples of umqtt.simple.MQTTClient(). 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 umqtt.simple , or try the search function .
Example #1
Source File: main.py    From xbee-micropython with MIT License 7 votes vote down vote up
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") 
Example #2
Source File: handler.py    From ulnoiot-upy with MIT License 7 votes vote down vote up
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.") 
Example #3
Source File: rgb_handler.py    From ulnoiot-upy with MIT License 6 votes vote down vote up
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.") 
Example #4
Source File: _mgr.py    From ulnoiot-upy with MIT License 6 votes vote down vote up
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 
Example #5
Source File: _mgr.py    From ulnoiot-upy with MIT License 6 votes vote down vote up
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 
Example #6
Source File: _mgr.py    From ulnoiot-upy with MIT License 6 votes vote down vote up
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 
Example #7
Source File: _mgr.py    From ulnoiot-upy with MIT License 6 votes vote down vote up
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 
Example #8
Source File: _mgr.py    From ulnoiot-upy with MIT License 6 votes vote down vote up
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 
Example #9
Source File: mqtt_log.py    From micropython-async with MIT License 5 votes vote down vote up
def publish(s):
    c = MQTTClient('umqtt_client', SERVER)
    c.connect()
    c.publish(b'result', s.encode('UTF8'))
    c.disconnect() 
Example #10
Source File: main.py    From xbee-micropython with MIT License 5 votes vote down vote up
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) 
Example #11
Source File: main.py    From xbee-micropython with MIT License 5 votes vote down vote up
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") 
Example #12
Source File: handler.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
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.") 
Example #13
Source File: lock_handler.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
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.") 
Example #14
Source File: servo_switch_handler.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
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.") 
Example #15
Source File: main.py    From iot-core-micropython with Apache License 2.0 5 votes vote down vote up
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 
Example #16
Source File: main.py    From sonoff-mqtt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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)) 
Example #17
Source File: iotfoundation.py    From developer-badge-2018-apps with Apache License 2.0 5 votes vote down vote up
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') 
Example #18
Source File: main.py    From xbee-micropython with MIT License 4 votes vote down vote up
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"]) 
Example #19
Source File: rpsmain.py    From developer-badge-2018-apps with Apache License 2.0 4 votes vote down vote up
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()