IoTSDK接入
更新时间:2025-04-25 18:01:31
IoTSDK主要维护和服务器之间的信令连接,采用纯C实现,主要支持设备绑定、解绑、信令解析、物模型处理相关的操作。
IoTSDK-API 列表
IoTSDK 相关的 API 功能说明如下:
API 接口 | 功能说明 |
---|---|
xs_iot_init | SDK 初始化 |
xs_iot_unInit | SDK 反初始化 |
xs_iot_setLogLevel | 设置日志级别 |
xs_iot_open | 创建设备(包含主设备和子设备) |
xs_iot_connect | 建立设备连接 |
xs_iot_disconnect | 断开设备连接 |
xs_iot_close | 销毁设备 |
xs_iot_report | 上报物模型定义的属性和状态信息 |
xs_iot_setBindInfo | 设备绑定过程中使用,设置绑定信息 |
xs_iot_handleExternalMsg | 处理外部消息(streamsdk 回调的消息) |
xs_iot_notifyHostStatus | SDK分离模式下:用于告知 主控芯片(streamsdk 运行的芯片) 的运行状态 |
xs_iot_get_version | 获取SDK版本号 |
xs_iot_set_timezone | 设置时区信息,海外设备需要使用此接口,SDK内部会根据设置的时区信息处理夏令时切换机制 |
SDK接口调用流程
以普通长电IPC为例,SDK接口调用流程以及示例代码如下:
步骤1:初始化SDK
int initSdk()
{
/*初始化iotsdk回调函数指针*/
xs_iot_callbackFun_st cbFun;
initIotCallbackFun(&cbFun);
/*设置初始化参数*/
xs_iotInitParam_st initParam;
memset(&initParam, 0, sizeof(initParam));
initParam.configPath = "/etc/config"; //设置配置文件路径,flash中可读写路径
initParam.workMode = XS_IOT_WORK_MODE_LONG_TIME_POWER;
initParam.maxSubDeviceNum = 0; //没有子设备
initParam.regionType = 0; //国内设备
initParam.heartbeatInterval = 15; //最小15
/*初始化iotsdk*/
ret = xs_iot_init(&cbFun, &initParam);
return ret;
}
步骤2:创建设备并启动连接
int connectDevice()
{
int devId = xs_iot_open(XS_IOT_DEV_TYPE_MASTER, &deviceInfo);
if (devId < 0) {
LOG_PRINT("open device failed, err=%d\n", g_devId);
return -1;
}
LOG_PRINT("open device success, id=%d\n", g_devId);
/*创建设备连接*/
ret = xs_iot_connect(g_devId);
if (ret != XSIOT_EC_SUCCESS) {
LOG_PRINT("xs_iot_connect failed, code=%d\n", ret);
return -1;
}
return ret;
}
设备上 线后,会将在线状态和绑定状态回调出来,具体可以参考设备上线章节
步骤3: 绑定设备
此步骤在设备配网绑定过程中才需要触发,一般是APP生成二维码、或者通过蓝牙、局域网等方式将绑定信息传到设备端,设备端解析出绑定信息(目前有bindToken以及regionId,regionId是可选字段),然后将绑定信息传入到SDK,
int bindDevice()
{
xs_bindInfo_st bindInfo;
bindInfo.bindToken = "797B05";
bindInfo.regionId = -1; //如果没有regionId,填为 -1
xs_iot_setBindInfo(&bindInfo);
return 0;
}
绑定结果通过回调函数通知设备层,具体细节参数设备绑定章节。
步骤4: 上报物模型属性&消息&固件版本号等
注意以下上报消息的动作,必须是设备在线且已经绑定过的状态下才能上报,否则直接返回失败
/*测试上报属性值*/
void testReportProperty()
{
/*此处模拟上报声音侦测灵敏度*/
const char* property = "{\"VoiceDetectionSensitivity\":2,\"SoundDetectionSensitivity\":3,\"time\":\"1732691271662\"}"; //time字段不填默认为当前时间
xs_uint32 serviceId = 0;
xs_iot_report(g_devId, XS_IOT_MSG_POST_PROPERTY, property, strlen(property), &serviceId);
}
/*测试上报物模型自定义的事件消息*/
void testReportTslEvent()
{
/*此处模拟上报物模型自定义事件消息*/
char* eventId = "LockAllEvent"; /*物模型中定义的event Identifier*/
char* payload = (char*)malloc(512);
strcpy(payload, "{\"lockEvent\":[-59],\"type\":9}"); /*事件内容*/
xs_uint32 serviceId = 0;
xs_iot_report_event(g_devId, eventId, getCurrentUtcMs(), payload, strlen(payload), &serviceId);
free(payload);
}
/*设备上报版本号*/
void testOtaInform()
{
const char* inform = "{\"version\": \"1.1.0\",\"module\": \"MCU\"}";
xs_uint32 serviceId = 0;
xs_iot_report(g_devId, XS_IOT_MSG_OTA_INFORM, inform, strlen(inform), &serviceId);
}