玩转 ESP32 + Arduino(三十) onenet5.

2020-12-21  本文已影响0人  熊爸天下_56c7

一. 体验新版更新内容

onenet5.0是一个大改版, 连用了多年的LOGO都换掉了, 现在的logo更简约美观了

1. OneNET Studio

更新后推出了一个OneNET Studio 的概念, 所有接入服务放在了这里面

进入 OneNET Studio 发现其整合相当一部分的业务, 而且分的非常明晰

2. 设备接入

现在, 我们关心的主要内容是设备接入

3. 产品管理和创建产品

产品管理界面简介美观

添加产品很容易

这里有了第一个概念 OneJson

4. OneJson概念

OneJson 就是OneNet能自动解析的JSON, 如果你按照这个格式上传json数据, 会省略上传数据解析过程.

参考文档: https://open.iot.10086.cn/doc/iot_platform/book/device-connect&manager/thing-model/protocol/OneJSON/OneJSON-introduce.html

5. 创建物模型

创建完产品后, 要开始创建物模型

关于物模型, 请参考以下文档:

https://open.iot.10086.cn/doc/iot_platform/book/device-connect&manager/thing-model/introduce.html

创建物模型分为 系统功能点 和 自定义功能点组

5.1 系统功能点(如果不需要定位服务,可以忽略此节)

目前只有两个

这个功能点已经完全定死, 我们只能提交符合它的格式的数据,

根据官方的SDK, 其结构如下:

5.2 自定义功能点组

自定义功能点分为3类

很容易明白这三类的意思, 本次试验我们只用属性类

创建功能点很简单:

和阿里云IOT一样, 创建完保存才能更新

6. 添加设备

添加设备还是那么的无脑 😂我喜欢

添加完设备后, 我们就得到了设备的关键信息了!!!

7. 计算token

和之前一样, 参考文章: https://www.jianshu.com/p/1c8dccc35b61
或者看文档: https://open.iot.10086.cn/doc/iot_platform/book/device-connect&manager/device-auth.html

通过 产品ID 设备名 和token 我们就可以接入新版OneNet了

8. 接入地址

和之前不一样了
参考文档: https://open.iot.10086.cn/doc/iot_platform/book/device-connect&manager/MQTT/mqtt-device-development.html

现在我们要接入的是: 218.201.45.7 : 1883 了!!

9. 通讯主题

原先OneNet可以说只有两个主题 , 现在终于把主题的概念发展开了, 越看越像阿里IOT了

参考文档 : https://open.iot.10086.cn/doc/iot_platform/book/device-connect&manager/MQTT/topic.html

10. 新版MQTT通讯限制

文档把通讯限制写的非常明确, 这很好!
https://open.iot.10086.cn/doc/iot_platform/book/device-connect&manager/MQTT/mqtt-limit.html

二. 上传温湿度至新版ONENET示例

#include <Arduino.h>
#include "WiFi.h"
#include "PubSubClient.h"
#include "Ticker.h"
#include "uFire_SHT20.h"

uFire_SHT20 sht20;

const char *ssid = "anleng";              //wifi名
const char *password = "al77776666";      //wifi密码
const char *mqtt_server = "218.201.45.7"; //onenet 的 IP地址
const int port = 1883;                    //端口号

#define mqtt_pubid "IaiJ9078ZN"    //产品ID
#define mqtt_devid "esp_mqtts_001" //设备名称
//鉴权信息
#define mqtt_password "version=2018-10-31&res=products%2FIaiJ9078ZN%2Fdevices%2Fesp_mqtts_001&et=4092599349&method=md5&sign=nvhmyIawpRbUyAojvL8CRA%3D%3D" //鉴权信息

WiFiClient espClient;           //创建一个WIFI连接客户端
PubSubClient client(espClient); // 创建一个PubSub客户端, 传入创建的WIFI客户端
Ticker tim1;                    //定时器,用来循环上传数据
//设备下发命令的set主题
#define ONENET_TOPIC_PROP_SET "$sys/" mqtt_pubid "/" mqtt_devid "/thing/property/set"
//设备上传数据的post主题
#define ONENET_TOPIC_PROP_POST "$sys/" mqtt_pubid "/" mqtt_devid "/thing/property/post"

//这是post上传数据使用的模板
#define ONENET_POST_BODY_FORMAT "{\"id\":\"%u\",\"params\":%s}"
int postMsgId = 0; //记录已经post了多少条

//连接WIFI相关函数
void setupWifi()
{
  delay(10);
  Serial.println("connect WIFI");
  WiFi.begin(ssid, password);
  while (!WiFi.isConnected())
  {
    Serial.print(".");
    delay(500);
  }
  Serial.println("OK");
  Serial.println("Wifi connected!");
}

//向主题发送模拟的温湿度数据
void sendTempAndHumi()
{
  if (client.connected())
  {
    //先拼接出json字符串
    char param[82];
    char jsonBuf[178];
    sprintf(param, "{\"temp\":{\"value\":%.2f},\"humi\":{\"value\":%.2f}}", sht20.temperature(), sht20.humidity()); //我们把要上传的数据写在param里
    postMsgId += 1;
    sprintf(jsonBuf, ONENET_POST_BODY_FORMAT, postMsgId, param);
    //再从mqtt客户端中发布post消息
    if (client.publish(ONENET_TOPIC_PROP_POST, jsonBuf))
    {
      Serial.print("Post message to cloud: ");
      Serial.println(jsonBuf);
    }
    else
    {
      Serial.println("Publish message to cloud failed!");
    }
  }
}

//重连函数, 如果客户端断线,可以通过此函数重连
void clientReconnect()
{
  while (!client.connected()) //再重连客户端
  {
    Serial.println("reconnect MQTT...");
    if (client.connect(mqtt_devid, mqtt_pubid, mqtt_password))
    {
      Serial.println("connected");
    }
    else
    {
      Serial.println("failed");
      Serial.println(client.state());
      Serial.println("try again in 5 sec");
      delay(5000);
    }
  }
}

void setup()
{
  Serial.begin(115200); //初始化串口
  Wire.begin();
  sht20.begin();
  delay(3000);                                           //这个延时是为了让我打开串口助手
  setupWifi();                                           //调用函数连接WIFI
  client.setServer(mqtt_server, port);                   //设置客户端连接的服务器,连接Onenet服务器, 使用6002端口
  client.connect(mqtt_devid, mqtt_pubid, mqtt_password); //客户端连接到指定的产品的指定设备.同时输入鉴权信息
  if (client.connected())
  {
    Serial.println("OneNet is connected!"); //判断以下是不是连好了.
  }
  tim1.attach(10, sendTempAndHumi); //定时每10秒调用一次发送数据函数sendTempAndHumi
}

void loop()
{
  if (!WiFi.isConnected()) //先看WIFI是否还在连接
  {
    setupWifi();
  }
  if (!client.connected()) //如果客户端没连接ONENET, 重新连接
  {
    clientReconnect();
    delay(100);
  }
  client.loop(); //客户端循环检测
}

三. 下面的版本更全面,配合onenet5.0 API调用的章节

参考文章:

https://www.jianshu.com/p/902a73b4a758
https://www.jianshu.com/p/cdf03171346e
https://www.jianshu.com/p/c5bb7a63b4cb

#include <Arduino.h>
#include "WiFi.h"
#include "PubSubClient.h"
#include "Ticker.h"
#include "uFire_SHT20.h"
#include "ArduinoJson.h"

uFire_SHT20 sht20;

const char *ssid = "anleng";              //wifi名
const char *password = "al77776666";      //wifi密码
const char *mqtt_server = "218.201.45.7"; //onenet 的 IP地址
const int port = 1883;                    //端口号

#define mqtt_pubid "IaiJ9078ZN"    //产品ID
#define mqtt_devid "esp_mqtts_001" //设备名称
//鉴权信息
#define mqtt_password "version=2018-10-31&res=products%2FIaiJ9078ZN%2Fdevices%2Fesp_mqtts_001&et=4092599349&method=md5&sign=nvhmyIawpRbUyAojvL8CRA%3D%3D" //鉴权信息

WiFiClient espClient;           //创建一个WIFI连接客户端
PubSubClient client(espClient); // 创建一个PubSub客户端, 传入创建的WIFI客户端
Ticker tim1;                    //定时器,用来循环上传数据
float temp;
float humi;

//设备上传数据的post主题
#define ONENET_TOPIC_PROP_POST "$sys/" mqtt_pubid "/" mqtt_devid "/thing/property/post"
//接收下发属性设置主题
#define ONENET_TOPIC_PROP_SET "$sys/" mqtt_pubid "/" mqtt_devid "/thing/property/set"
//接收下发属性设置成功的回复主题
#define ONENET_TOPIC_PROP_SET_REPLY "$sys/" mqtt_pubid "/" mqtt_devid "/thing/property/set_reply"

//接收设备属性获取命令主题
#define ONENET_TOPIC_PROP_GET "$sys/" mqtt_pubid "/" mqtt_devid "/thing/property/get"
//接收设备属性获取命令成功的回复主题
#define ONENET_TOPIC_PROP_GET_REPLY "$sys/" mqtt_pubid "/" mqtt_devid "/thing/property/get_reply"

//这是post上传数据使用的模板
#define ONENET_POST_BODY_FORMAT "{\"id\":\"%u\",\"params\":%s}"
int postMsgId = 0; //记录已经post了多少条

//连接WIFI相关函数
void setupWifi()
{
  delay(10);
  Serial.println("connect WIFI");
  WiFi.begin(ssid, password);
  while (!WiFi.isConnected())
  {
    Serial.print(".");
    delay(500);
  }
  Serial.println("OK");
  Serial.println("Wifi connected!");
}

//向主题发送模拟的温湿度数据
void sendTempAndHumi()
{
  if (client.connected())
  {
    //先拼接出json字符串
    char param[82];
    char jsonBuf[178];
    sprintf(param, "{\"temp\":{\"value\":%.2f},\"humi\":{\"value\":%.2f}}", temp, humi); //我们把要上传的数据写在param里
    postMsgId += 1;
    sprintf(jsonBuf, ONENET_POST_BODY_FORMAT, postMsgId, param);
    //再从mqtt客户端中发布post消息
    if (client.publish(ONENET_TOPIC_PROP_POST, jsonBuf))
    {
      Serial.print("Post message to cloud: ");
      Serial.println(jsonBuf);
    }
    else
    {
      Serial.println("Publish message to cloud failed!");
    }
  }
}

//重连函数, 如果客户端断线,可以通过此函数重连
void clientReconnect()
{
  while (!client.connected()) //再重连客户端
  {
    Serial.println("reconnect MQTT...");
    if (client.connect(mqtt_devid, mqtt_pubid, mqtt_password))
    {
      Serial.println("connected");
    }
    else
    {
      Serial.println("failed");
      Serial.println(client.state());
      Serial.println("try again in 5 sec");
      delay(5000);
    }
  }
}

void callback(char *topic, byte *payload, unsigned int length)
{
  Serial.println("message rev:");
  Serial.println(topic);
  for (size_t i = 0; i < length; i++)
  {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  if (strstr(topic, ONENET_TOPIC_PROP_SET))
  {
    DynamicJsonDocument doc(100);
    DeserializationError error = deserializeJson(doc, payload);
    if (error)
    {
      Serial.println("parse json failed");
      return;
    }
    JsonObject setAlinkMsgObj = doc.as<JsonObject>();
    serializeJsonPretty(setAlinkMsgObj, Serial);
    String str = setAlinkMsgObj["id"];
    Serial.println(str);
    char sendbuf[100];
    sprintf(sendbuf, "{\"id\": \"%s\",\"code\":200,\"msg\":\"success\"}", str.c_str());
    Serial.println(sendbuf);
    client.publish(ONENET_TOPIC_PROP_SET_REPLY, sendbuf);
  }
  if (strstr(topic, ONENET_TOPIC_PROP_GET))
  {
    DynamicJsonDocument doc(100);
    DeserializationError error = deserializeJson(doc, payload);
    if (error)
    {
      Serial.println("parse json failed");
      return;
    }
    JsonObject setAlinkMsgObj = doc.as<JsonObject>();
    serializeJsonPretty(setAlinkMsgObj, Serial);
    String str = setAlinkMsgObj["id"];
    Serial.println(str);
    char sendbuf[100];
    sprintf(sendbuf, "{\"id\": \"%s\",\"code\":200,\"msg\":\"success\",\"data\":{\"temp\":%.2f,\"humi\":%.2f}}", str.c_str(), sht20.temperature(), sht20.humidity());
    Serial.println(sendbuf);
    client.publish(ONENET_TOPIC_PROP_GET_REPLY, sendbuf);
  }
}

void setup()
{
  Serial.begin(115200); //初始化串口
  Wire.begin();
  sht20.begin();
  delay(3000);
  setupWifi();                                           //调用函数连接WIFI
  client.setServer(mqtt_server, port);                   //设置客户端连接的服务器,连接Onenet服务器, 使用6002端口
  client.connect(mqtt_devid, mqtt_pubid, mqtt_password); //客户端连接到指定的产品的指定设备.同时输入鉴权信息
  if (client.connected())
  {
    Serial.println("OneNet is connected!"); //判断以下是不是连好了.
  }
  client.subscribe(ONENET_TOPIC_PROP_SET);
  client.subscribe(ONENET_TOPIC_PROP_GET);
  client.setCallback(callback);
  tim1.attach(20, sendTempAndHumi); //定时每20秒调用一次发送数据函数sendTempAndHumi
}

void loop()
{
  temp = sht20.temperature();
  humi = sht20.humidity();
  if (!WiFi.isConnected()) //先看WIFI是否还在连接
  {
    setupWifi();
  }
  if (!client.connected()) //如果客户端没连接ONENET, 重新连接
  {
    clientReconnect();
    delay(100);
  }
  client.loop(); //客户端循环检测
}

四. 期望值获取

#include <Arduino.h>
#include "WiFi.h"
#include "PubSubClient.h"
#include "Ticker.h"
#include "uFire_SHT20.h"
#include "ArduinoJson.h"

uFire_SHT20 sht20;

const char *ssid = "anlengkj";            //wifi名
const char *password = "al77776666";      //wifi密码
const char *mqtt_server = "218.201.45.7"; //onenet 的 IP地址
const int port = 1883;                    //端口号

#define mqtt_pubid "Ygy2xf0iYx"    //产品ID
#define mqtt_devid "al00002lk0004" //设备名称
//鉴权信息
#define mqtt_password "version=2018-10-31&res=products%2FYgy2xf0iYx%2Fdevices%2Fal00002lk0004&et=4083930061&method=md5&sign=LF58PMK3%2FRgB8n9CLVuhfA%3D%3D"

WiFiClient espClient;           //创建一个WIFI连接客户端
PubSubClient client(espClient); // 创建一个PubSub客户端, 传入创建的WIFI客户端
Ticker tim1;                    //定时器,用来循环上传数据
float temp;
float humi;

//设备期望值获取请求主题
#define ONENET_TOPIC_DESIRED_GET "$sys/" mqtt_pubid "/" mqtt_devid "/thing/property/desired/get"

//设备期望值获取响应主题
#define ONENET_TOPIC_DESIRED_GET_RE "$sys/" mqtt_pubid "/" mqtt_devid "/thing/property/desired/get/reply"

//设备期望值删除请求主题
#define ONENET_TOPIC_DESIRED_DEL "$sys/" mqtt_pubid "/" mqtt_devid "/thing/property/desired/delete"

//设备期望值删除响应主题
#define ONENET_TOPIC_DESIRED_DEL_RE "$sys/" mqtt_pubid "/" mqtt_devid "/thing/property/desired/delete/reply"

//这是post上传数据使用的模板
#define ONENET_POST_BODY_FORMAT "{\"id\":\"%u\",\"params\":%s}"
int postMsgId = 0; //记录已经post了多少条

//连接WIFI相关函数
void setupWifi()
{
  delay(10);
  Serial.println("connect WIFI");
  WiFi.begin(ssid, password);
  while (!WiFi.isConnected())
  {
    Serial.print(".");
    delay(500);
  }
  Serial.println("OK");
  Serial.println("Wifi connected!");
}
void getDesired()
{
  if (client.connected())
  {
    //先拼接出json字符串
    char param[82];
    char jsonBuf[178];
    sprintf(param, "[\"set_flag\",\"temp_alarm\"]"); //我们把要上传的数据写在param里
    // sprintf(param, "[\"set_flag\",\"tempL\",\"tempLA\",\"tempU\",\"tempUA\"]"); //我们把要上传的数据写在param里
    postMsgId += 1;
    sprintf(jsonBuf, ONENET_POST_BODY_FORMAT, postMsgId, param);
    //再从mqtt客户端中发布post消息
    if (client.publish(ONENET_TOPIC_DESIRED_GET, jsonBuf))
    {
      Serial.print("Post message to cloud: ");
      Serial.println(jsonBuf);
    }
    else
    {
      Serial.println("Publish message to cloud failed!");
    }
  }
}

//重连函数, 如果客户端断线,可以通过此函数重连
void clientReconnect()
{
  while (!client.connected()) //再重连客户端
  {
    Serial.println("reconnect MQTT...");
    if (client.connect(mqtt_devid, mqtt_pubid, mqtt_password))
    {
      Serial.println("connected");
    }
    else
    {
      Serial.println("failed");
      Serial.println(client.state());
      Serial.println("try again in 5 sec");
      delay(5000);
    }
  }
}

void callback(char *topic, byte *payload, unsigned int length)
{
  Serial.println("message rev:");
  Serial.println(topic);
  for (size_t i = 0; i < length; i++)
  {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  if (strstr(topic, ONENET_TOPIC_DESIRED_GET))
  {
    DynamicJsonDocument doc(512);
    DeserializationError error = deserializeJson(doc, payload);
    if (error)
    {
      Serial.println("parse json failed");
      return;
    }
    JsonObject setAlinkMsgObj = doc.as<JsonObject>();
    serializeJsonPretty(setAlinkMsgObj, Serial);
    String str = setAlinkMsgObj["data"]["set_flag"]["value"];
    Serial.println(str);
  }
}

void setup()
{
  Serial.begin(115200); //初始化串口
  Wire.begin();
  sht20.begin();
  delay(3000);
  setupWifi();                                           //调用函数连接WIFI
  client.setServer(mqtt_server, port);                   //设置客户端连接的服务器,连接Onenet服务器, 使用6002端口
  client.connect(mqtt_devid, mqtt_pubid, mqtt_password); //客户端连接到指定的产品的指定设备.同时输入鉴权信息
  if (client.connected())
  {
    Serial.println("OneNet is connected!"); //判断以下是不是连好了.
  }
  client.subscribe(ONENET_TOPIC_DESIRED_GET);
  client.subscribe(ONENET_TOPIC_DESIRED_GET_RE);
  client.setCallback(callback);
  tim1.attach(20, getDesired); //定时每20秒调用一次发送数据函数sendTempAndHumi
}

void loop()
{
  temp = sht20.temperature();
  humi = sht20.humidity();
  if (!WiFi.isConnected()) //先看WIFI是否还在连接
  {
    setupWifi();
  }
  if (!client.connected()) //如果客户端没连接ONENET, 重新连接
  {
    clientReconnect();
    delay(100);
  }
  client.loop(); //客户端循环检测
}
上一篇下一篇

猜你喜欢

热点阅读