基于ESP32和OneNET的温湿度物联网系统设计
系统概述:使用ESP32+DHT11采集温湿度信息,通过mqtt协议将数据传输至OneNET云平台,软件界面通过调用API获取云平台最新数据;
步骤:1云平台设置、2esp32程序编写、3API获取、4JSON数据获取
1.云平台设置:
s1:创建产品和设备
S2:设置物模型数据
S3:记录:产品ID、access_key、设备名称
S4:使用token工具使用(时间戳,产品ID,access_key,设备名称)计算密码
token工具在最下方网盘链接中!

时间戳工具(请将时间改到一年后生成结果)https://tool.lu/timestamp/
2.esp32代码编写
#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include <Ticker.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#define DHTPIN 6
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
#define ONENET_TOPIC_PROP_POST "$sys/" product_id "/" device_id "/thing/property/post" // 设备属性上报请求
#define ONENET_TOPIC_PROP_SET "$sys/" product_id "/" device_id "/thing/property/set" // 设备属性设置请求
#define ONENET_TOPIC_PROP_POST_REPLY "$sys/" product_id "/" device_id "/thing/property/post/reply" // 设备属性上报响应
#define ONENET_TOPIC_PROP_SET_REPLY "$sys/" product_id "/" device_id "/thing/property/set_reply" // 设备属性设置响应
#define ONENET_TOPIC_PROP_FORMAT "{\"id\":\"%u\", \"version\":\"1.0\", \"params\":%s}"// 设备属性格式模板
const char* ssid = "Jiahui";
const char* password = "88886666";
const char* mqtt_server = "mqtts.heclouds.com"; // MQTT服务器地址
const int mqtt_port = 1883; // MQTT服务器端口
#define product_id "Bcp299K98x"
#define device_id "esp32"
#define token "version=" // 替换成自己的token
int postMsgId = 0; // 消息ID初始值为0
int temp = 0; // 温度
int humi = 0; // 湿度
//这里定义自己要传输的数据
WiFiClient espclient; // 创建一个WiFiClient对象
PubSubClient client(espclient); // 创建一个PubSubClient对象
Ticker ticker;
void WiFiConnect();
void OneNet_Connect();
void OneNet_Prop_Post();
void setup() {
pinMode(6,INPUT); //温度传感器
analogReadResolution(10); // 设置采样分辨率为10bit 范围可以是9-12之间
dht.begin();
Serial.begin(9600); // 串口初始化,波特率9600,用于输出调试信息
WiFiConnect(); // 连接WiFi
ticker.attach(0.01, OneNet_Prop_Post); // 定时器,每10毫秒执行一次OneNetPropPost函数
}
void loop() {
temp = dht.readTemperature();
humi = dht.readHumidity();
delay(2000);
if (WiFi.status() != WL_CONNECTED) {
// 如果WiFi连接断开,重新连接WiFi
WiFiConnect();
}
if (!client.connected()) {
// 如果MQTT连接断开,重新连接OneNet
OneNet_Connect();
}
// 保持MQTT连接
client.loop();
}
void WiFiConnect() {
WiFi.begin(ssid, password); // 连接WiFi
while (WiFi.status() != WL_CONNECTED) { // 等待WiFi连接,WiFi.status()返回当前WiFi连接状态,WL_CONNECTED为连接成功状态
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to the WiFi network"); // WiFi连接成功
Serial.println(WiFi.localIP()); // 输出设备IP地址
}
void OneNet_Connect() {
client.setServer(mqtt_server, mqtt_port); // 设置MQTT服务器地址和端口
if (client.connect(device_id, product_id, token)) { // 连接到OneNet
//LED_Flash(500);
Serial.println("Connected to OneNet!");
} else {
Serial.println("Failed to connect to OneNet!");
}
client.subscribe(ONENET_TOPIC_PROP_SET); // 订阅设备属性设置请求
client.subscribe(ONENET_TOPIC_PROP_POST_REPLY); // 订阅设备属性上报响应
}
void OneNet_Prop_Post() {
if (client.connected()) {
char params[256];
char jsonBuf[256];
sprintf(params, "{\"temp\": {\"value\": %d}, \"humi\": {\"value\": %d}}", temp, humi);
Serial.println(params);
sprintf(jsonBuf, ONENET_TOPIC_PROP_FORMAT, postMsgId++, params);
Serial.println(jsonBuf);
if (client.publish(ONENET_TOPIC_PROP_POST, jsonBuf)) {
Serial.println("Post property success!");
} else {
Serial.println("Post property failed!");
}
}
}
硬件与云平台联调,能收到数据即为成功(注意ESP32只能连接2.4GHz 的WIFI热点)
3API获取
OneNET平台API文档https://www.postman.com/
使用token工具获取安全鉴权,注意时间必须为2022-05-01
使用Postman成功调取API获得JSON格式温湿度数据
4使用JAVA调用API获取JSON数据
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
/*import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;*/
public class getclass {
public static void main(String[] args) {
//调用方法
doGet("http://api.heclouds.com/devices/{devices_id}/datapoints?datastream_id={humidity}&start=2017-01-01T00:00:00&limit=100");
}
public static String doGet(String url) {
HttpURLConnection httpURLConnection = null;
InputStream in = null;
BufferedReader br = null;
String result = null;// 返回结果字符串
try {
// 创建远程url连接对象
URL url1 = new URL(url);
// 通过远程url连接对象打开一个连接,强转成httpURLConnection类
httpURLConnection = (HttpURLConnection) url1.openConnection();
// 设置连接方式:get
httpURLConnection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:15000毫秒
httpURLConnection.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
httpURLConnection.setReadTimeout(60000);
//设置格式
httpURLConnection.setRequestProperty("Content-type", "application/json");
// 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0 OneNet平台使用的是Authorization+token
httpURLConnection.setRequestProperty("authorization","你的token");
// 发送请求
httpURLConnection.connect();
// 通过connection连接,获取输入流
if (httpURLConnection.getResponseCode() == 200) {
in = httpURLConnection.getInputStream();
// 封装输入流is,并指定字符集
br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
// 存放数据
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
System.out.println("response="+result);
}
} catch (UnsupportedEncodingException unsupportedEncodingException) {
unsupportedEncodingException.printStackTrace();
} catch (ProtocolException protocolException) {
protocolException.printStackTrace();
} catch (MalformedURLException malformedURLException) {
malformedURLException.printStackTrace();
} catch (IOException ioException) {
ioException.printStackTrace();
}finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
httpURLConnection.disconnect();// 关闭远程连接
}
return result;
}
成功获取,再通过解析JSON数据提取温湿度数值就成功啦!
解析数据使用的fastjson包和token工具下方百度网盘链接获取!FASTJSON和token工具https://pan.baidu.com/s/1OgjykTmGKa8_uv8yu9IAsA?pwd=hrwl
参考文献:
http://t.csdnimg.cn/HdbE7
http://t.csdnimg.cn/dN3rh
https://www.bilibili.com/video/BV1Lt421n78N/share_source=copy_web&vd_source=c789d81439e409e867811e5bce117b80
致谢:
本文所介绍的系统是在以上作者的成果基础上经过整合和优化后形成的,在此向他们表示感谢!
感谢阅读!
获取单片机软硬件PCB工程设计帮助与成品服务可通过:
闲鱼搜索用户“辉睿物联网”
电子邮件:lijiahui.shine@foxmail.com
作者:善点灯者