This topic describes how to initialize Link SDK for Python and connect a device to IoT Platform.
Background information
Link SDK for Python supports only device verification based on the device certificate. The following table describes the verification methods.
Verification method | Registration method | Description | References |
Unique-certificate-per-device verification | N/A | A device certificate that includes a ProductKey, DeviceName, and DeviceSecret is burned to each device. | |
Unique-certificate-per-product verification | Pre-registration |
| Unique-certificate-per-product verification Note For information about the differences between pre-registration unique-certificate-per-product verification and preregistration-free unique-certificate-per-product verification, see Differences between the verification methods. |
Preregistration-free |
|
Sample code
Unique-certificate-per-device verification
from linkkit import linkkit lk = linkkit.LinkKit( host_name="YourHostName", product_key="YourProductKey", device_name="YourDeviceName", device_secret="YourDeviceSecret") 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, cadata=None)
The following table describes the parameters.
Parameter
Example
Description
host_name
cn-shanghai
The ID of the region in which the device that you want to connect to IoT Platform resides.
product_key
a18wP******
The device certificate that is used for verification. The certificate is saved on your on-premises server after you add the device.
You can also view the device certificate on the Device Details page in the IoT Platform console. For more information, see Obtain device verification information.
device_name
LightSwitch
device_secret
uwMTmVAMnGGHaAkqmeDY6cHxxB******
endpoint
iot-cn-6ja******.mqtt.iothub.aliyuncs.com
The endpoint of the IoT Platform instance.
This parameter is required only for Enterprise Edition instances and public instances of the new version.
NoteIf you use an Enterprise Edition instance or a public instance of the new version, delete the number sign (#) before the code.
port
8883
The port number.
protocol
MQTTv311
The protocol that is used to establish a connection between the device and IoT Platform.
transport
TCP
The Transmission Control Protocol (TCP).
secure
TLS
The Transport Layer Security (TLS) protocol.
keep_alive
60
The keep-alive period. Unit: seconds. Valid values: 60 to 180. If IoT Platform does not detect the heartbeat of the device connection within the keep-alive period, IoT Platform rejects the device connection.
If the network connection is unstable, we recommend that you increase the value of this parameter. For more information, see MQTT keep-alive mechanism.
clean_session
True
Specifies whether to receive offline messages. Valid values:
True: The device receives offline messages.
False: The device does not receive offline messages.
auto_reconnect_min_sec
1
The minimum interval between the connection failure and reconnection. Unit: seconds. Valid values: 1 to 1200.
auto_reconnect_max_sec
60
The maximum interval between the connection failure and reconnection. Unit: seconds. Valid values: 1 to 1200.
Pre-registration unique-certificate-per-product verification
NoteFor more information, see the
dynamic_register.py
file in the sample code package.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 a downstream message. In most cases, the downstream message is returned within 1 second. time.sleep(5) lk_auth.destroy()
If you specify
auth_type="register"
for the LinkKit function, the system uses the pre-registration unique-certificate-per-product verification method to verify the device. The verification result is returned by theon_device_dynamic_register
callback function. If the value of therc
parameter is0
, the device passes the pre-registration unique-certificate-per-product verification. The DeviceSecret that is obtained from IoT Platform is returned. Save the DeviceSecret to your on-premises server. You can use the DeviceSecret to connect your device to IoT Platform. For more information, see Unique-certificate-per-device verification.If you specify
auth_type=""
, the system uses adeprecated
verification method that is available only in the China (Shanghai) region. For more information, see thedynamic_register_deprecated.py
file.Preregistration-free unique-certificate-per-product verification
NoteYou can use Link SDK for Python to perform preregistration-free unique-certificate-per-product verification on devices only in the China (Beijing) and China (Shanghai) regions.
For more information, see the
dynamic_register_nwl.py
file in the sample code package.
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 a downstream message. In most cases, the downstream message is returned within 1 second. time.sleep(5) lk_auth.destroy()
If you specify
auth_type="regnwl"
, the system uses the preregistration-free unique-certificate-per-product verification method to verify the device. If the value of therc
parameter is0
, the device passes the preregistration-free unique-certificate-per-product verification. Theusername
,ClientID
, andpassword
that are obtained from IoT Platform are returned.
Callback function
After you connect a device to IoT Platform, you can use the on_connect
callback function to view the connection status. If the device is disconnected, you can write the processing logic in the on_disconnect
callback function based on your business scenario.
By default, Link SDK for Python supports reconnection. If a device is disconnected due to network instability or other exceptions, the device automatically initiates a reconnection request based on the configured parameters, such as the keep-alive parameter.
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 the network connection interface
If the same device certificate that contains the ProductKey, DeviceName, and DeviceSecret is burned to multiple devices, IoT Platform considers the devices as the same device. In this case, one device is disconnected when another device goes online. You can upload information about your connection interfaces to IoT Platform for troubleshooting.
lk.config_device_info("Eth|03ACDEFF0032|Eth|03ACDEFF0031")
The following table describes the network connection interfaces.
Network type | Example | Description |
WiFi |
| If your device is connected to WiFi or Ethernet over the upstream network interface, set the network type to WiFi or Eth and specify a Media Access Control (MAC) address. The MAC address must be in uppercase letters. |
Ethernet (Eth) | ||
Cellular network (Cellular) | Cellular|imei_001122|iccid_22334455|imsi_234241|msisdn_53212 | If your device is connected to a cellular network, such as 2G, 3G, or 4G, over the upstream network interface, set the network type to Cellular and configure the following parameters:
|
Establish a connection
After you configure the parameters for the Message Queuing Telemetry Transport (MQTT) connection, callback function, and network connection interface, call the connect_async
method to initiate a connection.
lk.connect_async()
If a device is disconnected due to network instability or other exceptions, the device automatically initiates a reconnection request based on the configured parameters, such as the keep-alive parameter. You need to only call the method once.