配置设备端SDK后,可以实现网关设备连接物联网平台。
配置网关设备端SDK
本示例Demo中,java/src/main/java/com/aliyun/iot/api/common/deviceApi目录下的DeviceTopoManager文件中包含网关接入物联网平台的代码示例。
- 设置网关连接信息。
private static String regionId = "cn-shanghai"; private static final String TAG = "TOPO"; //网关设备。 private static String GWproductKey = "a1BxptK***"; private static String GWdeviceName = "XMtrv3yvftEHAzrTfX1U"; private static String GWdeviceSecret = "19xJNybifnmgcK057vYhazYK4b64****"; public static void main(String[] args) { /** * mqtt连接信息。 */ DeviceTopoManager manager = new DeviceTopoManager(); /** * 服务器端的java http客户端使用TSLv1.2。 */ System.setProperty("https.protocols", "TLSv2"); manager.init(); }
- 建立连接。
public void init() { LinkKitInitParams params = new LinkKitInitParams(); /** * 设置mqtt初始化参数。 */ IoTMqttClientConfig config = new IoTMqttClientConfig(); config.productKey = GWproductKey; config.deviceName = GWdeviceName; config.deviceSecret = GWdeviceSecret; config.channelHost = GWproductKey + ".iot-as-mqtt." + regionId + ".aliyuncs.com:1883"; /** * 是否接受离线消息。 * 对应mqtt的cleanSession字段。 */ config.receiveOfflineMsg = false; params.mqttClientConfig = config; ALog.setLevel(LEVEL_DEBUG); ALog.i(TAG, "mqtt connetcion info=" + params); /** * 设置初始化,传入设备证书信息。 */ DeviceInfo deviceInfo = new DeviceInfo(); deviceInfo.productKey = GWproductKey; deviceInfo.deviceName = GWdeviceName; deviceInfo.deviceSecret = GWdeviceSecret; params.deviceInfo = deviceInfo; /**建立连接。**/ LinkKit.getInstance().init(params, new ILinkKitConnectListener() { public void onError(AError aError) { ALog.e(TAG, "Init Error error=" + aError); } public void onInitDone(InitResult initResult) { ALog.i(TAG, "onInitDone result=" + initResult); //获取网关下topo关系,查询网关与子设备是否已经存在topo关系。 //如果已经存在,则直接上线子设备。 getGWDeviceTopo(); //子设备动态注册获取设备deviceSecret,如果设备已知设备证书则忽略此步,直接添加topo关系。 //预注册设备时,可以使用设备的MAC地址或SN序列号等作为DeviceName。 gatewaySubDevicRegister(); //待添加拓扑关系的子设备信息。 gatewayAddSubDevice(); } }); }
测试
在设备端SDK中,配置完网关设备信息后,测试SDK是否能连接物联网平台。
- 运行DeviceTopoManager。
- 在物联网平台控制台对应实例下的左侧导航栏中,选择 。
- 在设备列表中,找到网关设备,查看其状态。如果状态显示为在线,说明网关设备已连接物联网平台。