设备接入 IOTDA-Python Demo使用说明:建立连接
建立连接
设备或网关在接入 物联网平台 时首先需要和平台建立连接,从而将设备或网关与平台进行关联。开发者通过传入设备信息,将设备或网关连接到物联网平台。
- IoTClientConfig类主要提供配置客户端相关信息的功能,在建立连接之前,先修改以下参数。
1 2 3 4
# 客户端配置 client_cfg = IoTClientConfig(server_ip='iot-mqtts.cn-north-4.myhuaweicloud.com', device_id='5e85a55f60b7b804c51ce15c_py123', secret='******', is_ssl=True) # 创建设备 iot_client = IotClient(client_cfg)
- 调用 connect 方法进行连接。
iot_client.connect()
如果连接成功会打印:
-----------------Connection successful !!!
注:如果连接失败,在retreat_reconnection函数中已实现退避重连,代码样例如下:
# 退避重连 def retreat_reconnection(self): print("---- 退避重连") global retryTimes minBackoff = 1 maxBackoff = 30 defaultBackoff = 1 low_bound = (int)(defaultBackoff * 0.8) high_bound = (int)(defaultBackoff * 1.2) random_backoff = random.randint(0, high_bound - low_bound) backoff_with_jitter = math.pow(2.0, retryTimes) * (random_backoff + low_bound) wait_time_until_next_retry = min(minBackoff + backoff_with_jitter, maxBackoff) print("the next retry time is ", wait_time_until_next_retry, " seconds") retryTimes += 1 time.sleep(wait_time_until_next_retry) self.connect()