Authentication and connection

更新时间:
复制 MD 格式

This topic describes how to initialize the Python Link SDK to connect a device to IoT Platform.

Background information

The Python Link SDK supports only the device secret method for device identity authentication. The following authentication methods are available.

Authentication method

Registration method

Description

References

One device, one secret

Not applicable

Each device is programmed with its own device certificate (ProductKey, DeviceName, and DeviceSecret).

One device, one secret

One product, one secret

Pre-registration

  • Devices of the same product are programmed with the same product certificate (ProductKey and ProductSecret).

  • The dynamic registration feature must be enabled for the product.

  • The device obtains a DeviceSecret through dynamic registration.

One product, one secret

Note

For the differences between pre-registration and registration-free mode for the one-product-one-secret method, see Differences between pre-registration and registration-free mode.

Registration-free

  • Devices of the same product are programmed with the same product certificate (ProductKey and ProductSecret).

  • The dynamic registration feature must be enabled for the product.

  • The device obtains a combination of a ClientID and a DeviceToken through dynamic registration.

Limits

  • By default, the Python Link SDK connects devices to IoT Platform using Transport Layer Security (TLS). You cannot use an IP address for a TLS-authenticated connection.

  • If you use an IoT card with a directional traffic plan and your carrier does not support domain name configuration, you can bind a fixed IP address to the access domain name. For more information, see Bind a fixed IP address to an access domain name.

Sample code

  • One device, one secret

    from linkkit import linkkit
    lk = linkkit.LinkKit(
        host_name="YourHostName",
        product_key="YourProductKey",
        device_name="YourDeviceName",
        device_secret="YourDeviceSecret")          
    lk.config_mqtt(endpoint="{Your Mqtt Host Url}")
    lk.config_mqtt(port=8883, protocol="MQTTv311", transport="TCP",
                secure="TLS", keep_alive=60, clean_session=True,
                max_inflight_message=20, max_queued_message=0,
                auto_reconnect_min_sec=1,
                auto_reconnect_max_sec=60,
                check_hostname=True,   
                cadata=None)

    Parameters:

    Parameter

    Example

    Description

    host_name

    cn-shanghai

    The ID of the region where the device is connected.

    product_key

    a18wP******

    The device authentication information. This is the device certificate that you saved locally after you added the device.

    You can also view the device authentication information on the Device Details page in the IoT Platform console. For more information, see Obtain device authentication information.

    device_name

    LightSwitch

    device_secret

    uwMTmVAMnGGHaAkqmeDY6cHxxB******

    endpoint

    iot-cn-6ja******.mqtt.iothub.aliyuncs.com

    The access domain name.

    On the instance details page in the IoT Platform console, click View Developer Configurations to obtain the access domain name for the device. For more information, see View and configure instance endpoints.

    port

    8883

    The port number.

    protocol

    MQTTv311

    The protocol that the device uses to connect to IoT Platform.

    transport

    TCP

    The Transmission Control Protocol.

    secure

    TLS

    The transport-layer security protocol.

    keep_alive

    60

    The keepalive interval. Unit: seconds. Valid values: 60 to 180. If the device heartbeat interval is outside the keepalive interval, IoT Platform rejects the connection request from the device.

    If the network is unstable, increase the value of this parameter. For more information, see MQTT keepalive.

    clean_session

    True

    Specifies whether to receive offline messages. Valid values:

    • True: Yes

    • False: No

    auto_reconnect_min_sec

    1

    The minimum reconnection interval. Unit: seconds. Valid values: 1 to 1,200.

    auto_reconnect_max_sec

    60

    The maximum reconnection interval. Unit: seconds. Valid values: 1 to 1,200.

    check_hostname

    True

    Specifies whether to verify the domain name during the TLS handshake when an MQTT connection is established. The default value is True, which indicates that the domain name is verified.

    If you enter an IP address for the endpoint parameter, set check_hostname to False.

  • One product, one secret (pre-registration)

    Note

    For more sample code, see the dynamic_register.py file in the example code.

    import time
    from linkkit import linkkit
    import logging
    
    # config log
    __log_format = '%(asctime)s-%(process)d-%(thread)d - %(name)s:%(module)s:%(funcName)s - %(levelname)s - %(message)s'
    logging.basicConfig(format=__log_format)
    
    product_key = "${YourProductKey}"
    device_name = "${YourDeviceName}"
    product_secret = "${YourProductSecret}"
    instance_id = "${YourInstanceId}"
    device_secret = ""
    
    lk_auth = linkkit.LinkKit(
        host_name="cn-shanghai",
        product_key=product_key,
        device_name=device_name,
        device_secret="",
        auth_type="register",
        instance_id=instance_id,
        product_secret=product_secret)
    
    
    def on_device_dynamic_register(rc, value, userdata):
        if rc == 0:
            global device_secret
            print("dynamic register device success, rc:%d, value:%s" % (rc, value))
            device_secret = value
        else:
            print("dynamic register device fail,rc:%d, value:%s" % (rc, value))
    
    
    lk_auth.enable_logger(logging.DEBUG)
    lk_auth.on_device_dynamic_register = on_device_dynamic_register
    lk_auth.connect_async()
    
    # Wait for the downstream message. A response is usually returned within 1 second.
    time.sleep(5)
    lk_auth.destroy()

    auth_type="register" in the LinkKit constructor indicates the one-product-one-secret (pre-registration) method. The result is returned in the on_device_dynamic_register callback function. If the value of rc is 0, the dynamic registration is successful. The returned value is the DeviceSecret of the device obtained from IoT Platform. Store this value locally for future device connections. For more information, see One device, one secret.

    If auth_type="", this indicates a deprecated registration method for one-product-one-secret, which is supported only in the China (Shanghai) region. For more information, see the dynamic_register_deprecated.py file.

  • One product, one secret (registration-free)

    Note
    • The Python Link SDK supports the one-product-one-secret (registration-free) authentication method only for devices in the China (Shanghai) and China (Beijing) regions.

    • For more sample code, see the dynamic_register_nwl.py file in the example code.

    import time
    
    from linkkit import linkkit
    import logging
    
    
    # config log
    __log_format = '%(asctime)s-%(process)d-%(thread)d - %(name)s:%(module)s:%(funcName)s - %(levelname)s - %(message)s'
    logging.basicConfig(format=__log_format)
    
    
    product_key = "${YourProductKey}"
    device_name = "${YourDeviceName}"
    product_secret = "${YourProductSecret}"
    instance_id = "${YourInstanceId}"
    
    
    lk_auth = linkkit.LinkKit(
        host_name="cn-shanghai",
        product_key=product_key,
        product_secret=product_secret,
        device_name=device_name,
        device_secret="",
        instance_id=instance_id,
        auth_type="regnwl")
    
    
    def on_device_dynamic_register_nwl_reply(code, client_id_l, user_name_l, password_l):
        print("code:", code)
        if 0 == code:
            print("cid:", client_id_l)
            print("user_name:", user_name_l)
            print("password:", password_l)
    
    
    lk_auth.enable_logger(logging.DEBUG)
    lk_auth.on_device_dynamic_register_nwl_reply = on_device_dynamic_register_nwl_reply
    lk_auth.connect_async()
    # Wait for the downstream message. A response is usually returned within 1 second.
    time.sleep(5)
    lk_auth.destroy()

    auth_type="regnwl" indicates dynamic registration with a per-product secret. An rc value of 0 indicates that the dynamic registration is successful, and the IoT Platform returns the `username`, `clientId`, and `password` for the device.

Callback functions

After a device connects to IoT Platform, you can use the on_connect callback function to check the connection result. If the device disconnects after a successful connection, you can use the on_disconnect callback function to implement the processing logic required for your business scenario.

Note

The Python Link SDK supports automatic reconnection by default. If a device disconnects due to network issues after a successful connection, it automatically initiates a reconnection request based on parameters such as the keepalive interval.

The following is sample code:

def on_connect(session_flag, rc, userdata):
    print("on_connect:%d,rc:%d,userdata:" % (session_flag, rc))
    pass
def on_disconnect(rc, userdata):
    print("on_disconnect:rc:%d,userdata:" % rc)
lk.on_connect = on_connect
lk.on_disconnect = on_disconnect          

(Optional) Configure network interface information

During production, if the same device authentication information is incorrectly programmed into multiple devices, IoT Platform considers them a single device. This causes one device to go online and disconnect another. You can upload the network interface information to IoT Platform to help diagnose this issue.

lk.config_device_info("Eth|03ACDEFF0032|Eth|03ACDEFF0031")

The valid values for the interface are:

Network type

Example value

Description

Wi-Fi

Eth|03ACDEFF0032|Eth|03ACDEFF0031

If the device's upstream network interface is Wi-Fi or Eth (Ethernet), the interface information must include the MAC address. The MAC address must be in uppercase.

Eth (Ethernet)

Cellular

Cellular|imei_001122|iccid_22334455|imsi_234241|msisdn_53212

If the interface is Cellular (a 2G, 3G, or 4G cellular network interface), the interface data must include the following:

  • IMEI

  • ICCID

  • IMSI

  • MSISDN

Start the connection

After you configure MQTT connection parameters, set callback functions, and configure network interface information, you can call connect_async to initiate a connection.

lk.connect_async()
Important

If a device disconnects due to network issues after a successful connection, it automatically initiates a reconnection request based on parameters such as the keepalive interval. Therefore, you do not need to call this interface again.