文档

物模型透传开发

更新时间:

本文介绍设备如何使用二进制数据完成物模型数据的上报和下发。

背景信息

物模型是阿里云物联网平台为产品定义的数据模型,数据模型的原生数据编码格式基于JSON协议。对于资源受限设备,使用二进制格式进行编码可以解决JSON格式的序列化开销大,生成报文长等问题。

前提条件

使用流程

如下功能时序图,以设备的应用程序./demos/data_model_raw_demo.c为例,介绍物模型二进制数据通信的基础使用流程。更多API的详细信息,请参考aiot_dm_api.h

image

步骤1: 初始化设备

创建设备句柄,完成设备建连。

static void* demo_device_init(char *product_key, char *device_name, char *device_secret, char *host, uint16_t port)
{
    int32_t res = STATE_SUCCESS;
    /* 创建设备 */
    void *device = aiot_device_create(product_key, device_name);
    if (device == NULL) {
        printf("device create failed\n");
        return NULL;
    }
    /* 设置设备密钥 */
    aiot_device_set_device_secret(device, device_secret);

    /* 连接配置参数初始化 */
    aiot_linkconfig_t* config = aiot_linkconfig_init(protocol);
    /* 设置服务器的host、port */
    aiot_linkconfig_host(config, host, port);

    /* 设置设备连接参数 */
    aiot_device_set_linkconfig(device, config);
    
    /* 设备建连 */
    res = aiot_device_connect(device);
    if (res < STATE_SUCCESS) {
        /* 尝试建立连接失败, 销毁MQTT实例, 回收资源 */
        aiot_linkconfig_deinit(&config);
        aiot_device_delete(&device);
        printf("aiot_device_connect failed: -0x%04X\n\r\n", -res);
        return NULL;
    }

    /* 建连成功返回设备对象 */
    aiot_linkconfig_deinit(&config);
    return device;
}

步骤2: 上报二进制数据

用户可以使用该接口自定义数据格式进行属性上报、事件上报、消息回复。

 /* 上报二进制数据 */
    uint8_t raw_data[] = { 0x01, 0x02 };
    aiot_device_dm_raw_post(device_client, raw_data, sizeof(raw_data));

步骤3: 接收处理二进制数据

二进制消息回调中包含属性设置、服务调用、云端消息回复,消息类型包含AIOT_DMRECV_RAW_REPLY云端消息回复,AIOT_DMRECV_RAW_DOWN云端主动下发,示例中设置属性仅做打印处理,用户可解析数据执行响应的业务处理。

/* 物模型消息的回调函数 */
static void demo_dm_msg_callback(void *device, const aiot_dm_msg_t *dm_msg, void *userdata)
{
    if(dm_msg == NULL) {
        return;
    }
    printf("[thing-message] recv msg type %d\r\n", dm_msg->type);
    switch(dm_msg->type){
        case AIOT_DMRECV_RAW_REPLY:
        case AIOT_DMRECV_RAW_DOWN:
            demo_dm_msg_down_raw_callback(device, dm_msg, userdata);
        break;
        default:
            break;
    }
}

步骤4: 反初始化设备

 /* 断开设备连接,并回收设备资源 */
    demo_device_deinit(device_client);
  • 本页导读 (1)
文档反馈