Example #1
0
static int MqttSample_CmdPublish(struct MqttSampleContext *ctx)
{
    int err = 0;
    int64_t ts;

    ts = (int64_t)time(NULL) * 1000;

    err |= Mqtt_PackDataPointStart(ctx->mqttbuf, 1, MQTT_QOS_LEVEL2, 0, 1);
    err |= Mqtt_AppendDPStartObject(ctx->mqttbuf, "test-1", ts);
    err |= Mqtt_AppendDPSubvalueInt(ctx->mqttbuf, "subvalue", 23);
    err |= Mqtt_AppendDPSubvalueDouble(ctx->mqttbuf, "sub2", 23.167);
    err |= Mqtt_AppendDPSubvalueString(ctx->mqttbuf, "str3", "strvalue");
    err |= Mqtt_AppendDPFinishObject(ctx->mqttbuf);
    err |= Mqtt_PackDataPointFinish(ctx->mqttbuf);
    if(err) {
        printf("Failed to pack data point package.\n");
        return -1;
    }

    return 0;
}
/**
  * @brief 周期性发布数据,暂时没有使用,因为采用JSON发布,前端暂时不支持Json显示,但可以正常发布
  * @param  ctx:上下文变量
  * @retval ret:0,成功,<0 失败
  **/
static int MqttSample_CmdPublish(struct MqttSampleContext *ctx)
{
    uint8_t cause = 0; //only for test
    int err = 0;
    int bytes = 0;
    static unsigned char count = 0;
    int64_t ts = 0; //no time
    uint16_t temprature[1], rh[1];
    printf("%s %d,count=%d,cause=%d\n", __func__, __LINE__, count, cause);
    // ts = (int64_t)time(NULL) * 1000;

    SHT2x_MeasureHM(SHT20_Measurement_RH_HM, temprature);
    mDelay(1500);
    SHT2x_MeasureHM(SHT20_Measurement_T_HM, rh);

    err |= Mqtt_PackDataPointStart(ctx->mqttbuf, 1, MQTT_QOS_LEVEL2, 0, 1);
    if((count == 0) || (cause == EVENT))
    {
        err |= Mqtt_AppendDPStartObject(ctx->mqttbuf, DS_TO_PUBLISH, ts);
        if(cause == TIME_OUT)
        {
            ir_state = !ir_state;
        }
        if(ir_state == 0x1)
        {
            err |= Mqtt_AppendDPSubvalueString(ctx->mqttbuf, DS_TO_PUBLISH, "设备在位");
        }
        else if(ir_state == 0)
        {
            err |= Mqtt_AppendDPSubvalueString(ctx->mqttbuf, DS_TO_PUBLISH, "设备离位");
        }
        else
        {
            err |= Mqtt_AppendDPSubvalueString(ctx->mqttbuf, DS_TO_PUBLISH, "未知初始状态");
        }
        if(count != 2)
        {
            count++;
        }
    }
    else if(count == 1)
    {
        err |= Mqtt_AppendDPStartObject(ctx->mqttbuf, DS_TO_PUBLISH_T, ts);
        err |= Mqtt_AppendDPSubvalueInt(ctx->mqttbuf, DS_TO_PUBLISH_T, temprature[0]);
        count++;
    }
    else if(count == 2)
    {
        err |= Mqtt_AppendDPStartObject(ctx->mqttbuf, DS_TO_PUBLISH_RH, ts);
        err |= Mqtt_AppendDPSubvalueInt(ctx->mqttbuf, DS_TO_PUBLISH_RH, rh[0]);
        count = 0;

    }
    err |= Mqtt_AppendDPFinishObject(ctx->mqttbuf);
    err |= Mqtt_PackDataPointFinish(ctx->mqttbuf);
    if(err)
    {
        printf("Failed to pack data point package.err=%d\n", err);
        return -1;
    }
    bytes = Mqtt_SendPkt(ctx->mqttctx, ctx->mqttbuf, 0);
    MqttBuffer_Reset(ctx->mqttbuf);
    return 0;
}