项目场景:
提示:这里简述项目相关背景:
新版Onenet之前还是不一样的,之前大部分使用http协议+api-key(现在的access-key)链接,现在常使用Mqtt协议+token验证还是有点不一样,这几天研究一下,主要是硬件上传(我使用的是Esp32)和小程序接入(发送到Onenet改下设备属性应该就可以,需要的话到时候在研究)
问题描述
首先是Onetnet平台数据模型搭建和注册网上都有就懒一下。
参考网站:https://blog.csdn.net/qq_51390570/article/details/136839801
这是Esp32接入Onenet代码,Stm32+ESp8266,使用AT指令网上大部分是这种代码但逻辑都大差不差
@Override
#define MqttServer "mqtts.heclouds.com"
#define MqttPort 1883
#define ProductId "****"
#define DeviceId "****"
#define OnenetTopicSet "$sys/" ProductId "/" DeviceId "/thing/property/set"
#define OnenetTopicPostReply "$sys/" ProductId "/" DeviceId "/thing/property/post/reply"
#define OnenetTopicFormat "{\"id\":\"%u\",\"version\":1.0,\"params\":%s}"
//发送POST数据
void OneNetPostFun()
{
if(Client.connected())
{
char params[256];
char JsonBuff[256];
sprintf(params, "{\"Step\":{\"value\":%d},\"beat\":{\"value\":%d}}", StepNum, beatAvg);
Serial.println(params);
sprintf(JsonBuff,OnenetTopicFormat,PosMessId++,params);
Serial.println(JsonBuff);
if(Client.publish(OnenetTopicPost,JsonBuff))
{
Serial.println("success");
}
else
{
Serial.println("no");
}
}
}
//链接Onenet平台
void OneNetConnect()
{
Client.setServer(MqttServer,MqttPort);
Client.connect(DeviceId,ProductId,token);
if(Client.connected())
{
Serial.println("OneNet is ok");
//OneNetPostFun();
}
else{
Serial.print("sorry");
}
Client.subscribe(OnenetTopicSet);
Client.subscribe(OnenetTopicPostReply);
}
```c
Test随便发了两个数据
串口发送成功
OneNet显示
小程序
微信小程序先放行request
参考
OneNet平台–运维监控–API调试
JS代码
Page({
data: {
firstValue: '', // 初始化为空字符串
secondValue: '' // 初始化为空字符串
},
onLoad: function() {
const that = this; // 保存页面上下文
wx.request({
url: "https://iot-api.heclouds.com/thingmodel/query-device-property",
method: 'GET',
header: {
"Accept": "application/json, text/plain, */*",
"authorization": "token"//修改
},
data: {
"product_id": "product_id",//
"device_name": "Demo"
},
success(res) {
const firstValue = res.data.data[0].value;
const secondValue = res.data.data[1].value;
// 更新页面数据
that.setData({
firstValue: firstValue,
secondValue: secondValue
});
},
fail(err) {
console.error("err", err); // 打印错误信息
}
});
}
});
微信界面
在这里插入代码片
<!-- 在小程序的wxml文件中 -->
<view class="container">
<view class="data-item">
<text class="label">firstValue :</text>
<text class="value">{{ firstValue }}</text>
</view>
<view class="data-item">
<text class="label">secondValue :</text>
<text class="value">{{ secondValue }} </text>
</view>
</view>
Test
正常情况下可以看到刚刚数字,可能测试时间太晚了,刚好406错误
原网页token时间太短了,记得修改
链接:https://pan.baidu.com/s/11-QrNOiH1pH1tw_gyfC-2A
提取码:gnc9