使用esp32-Arduino+PubSubClient+mqtt 上传数据到中移动OneNet
使用esp32-doit-dev-v1开发板,测试mqtt协议, 发布(publish)到onenet 平台。
注意:
1.使用的mqtt arduino 客户端是 pubsubclient 库。其默认是ESP8266, 所以例子例包换文件“Wifi8266.h”,可以改为"Wifi.h"就可以。
2.关键是按照mqtt的onenet文档,编制payload数据包。其具体格式有多种类型。调试的是最简单的type3, json数据2 形式。
/*
Basic ESP8266 MQTT example This sketch demonstrates the capabilities of the pubsub library in combination
with the ESP8266 board/library. It connects to an MQTT server then:
- publishes "hello world" to the topic "outTopic" every two seconds
- subscribes to the topic "inTopic", printing out any messages
it receives. NB - it assumes the received payloads are strings not binary
- If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
else switch it off It will reconnect to the server if the connection is lost using a blocking
reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
achieve the same result without blocking the main loop. To install the ESP8266 board, (using Arduino 1.6.4+):
- Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
http://arduino.esp8266.com/stable/package_esp8266com_index.json
- Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
- Select your ESP8266 in "Tools -> Board" */
//改为<WiFi.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h> //#define BUILTIN_LED 2 // Update these with values suitable for your network. const char* ssid = "热点ssid";
const char* password = "连接密码";
const char* mqtt_server = "183.230.40.39"; WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg_buf[200];
int value = 0; //
//char one_type3_header[] = {'0x03','0x00','0x46'};
char dataTemplete[]="{"temperature":25.5,"time":%d}";
char msgJson[75];
char debug_buf[200];
int i;
unsigned short json_len=0;
uint8_t* packet_p;
uint8_t debug_buffer_start_index = 0; void setup_wifi() { delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
} randomSeed(micros()); Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
} void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println(); // Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else {
digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
} } void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
//String clientId = "设备_id";
//clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect("设备id","产品_id","API_key")) { //One net user name as product ID , and password as APIKey
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic", "hello world");
// ... and resubscribe
client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
} void setup() {
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output, where do it esp32 get gpio2 as led
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 6002); //not 1883 , one net use the port of 6002 as mqtt server
client.connect("设备Id","产品id","API_key");
client.setCallback(callback);
} void loop() { if (!client.connected()) {
reconnect();
}
client.loop(); long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
//snprintf (msgJson, 75, "hello world #%ld", value);
snprintf(msgJson,40,dataTemplete,22);
json_len=strlen(msgJson); //packet length count the end char '\0'
msg_buf[0]=char(0x03); //palyLoad packet byte 1, one_net mqtt Publish packet payload byte 1, type3 , json type2
msg_buf[1]=char(json_len>>8); //high 8 bits of json_len (16bits as short int type)
msg_buf[2]=char(json_len&0xff); //low 8 bits of json_len (16bits as short int type)
// snprintf(msg_buf+3,40,dataTemplete,value); memcpy(msg_buf+3,msgJson,strlen(msgJson));
msg_buf[3+strlen(msgJson)] = 0;
Serial.print("Publish message: ");
Serial.println(msgJson);
client.publish("$dp",msg_buf,3+strlen(msgJson),false); // msg_buf as payload length which may have a "0x00"byte //debug one_net packet
packet_p = client.getBufferPointer();
for(i = 0 ; i< 200;i++)
{
//sprintf(debug_buf,"0x%02x ",msg_buf[i]);
sprintf(debug_buf,"0x%02x ",packet_p[i]);
Serial.print(debug_buf);
}
Serial.println();
for(i = 0 ; i< 200;i++)
{
sprintf(debug_buf,"0x%02x ",msg_buf[i]);
//sprintf(debug_buf,"0x%02x ",packet_p[i]);
Serial.print(debug_buf);
}
Serial.println();
debug_buffer_start_index=client.getDebugVar();
Serial.println(debug_buffer_start_index);
}
}
使用esp32-Arduino+PubSubClient+mqtt 上传数据到中移动OneNet的更多相关文章
- ajaxFileUpload 异步上传数据
AjaxFileUpload.js并不是一个很出名的插件,只是别人写好的放出来供大家用,原理都是创建隐藏的表单和iframe然后用JS去提交,获得返回值. 它的配置方式比较像jQuery的AJAX,使 ...
- 重新想象 Windows 8.1 Store Apps (89) - 通信的新特性: 下载数据, 上传数据, 上传文件
[源码下载] 重新想象 Windows 8.1 Store Apps (89) - 通信的新特性: 下载数据, 上传数据, 上传文件 作者:webabcd 介绍重新想象 Windows 8.1 Sto ...
- TortoiseGit和msysGit安装及使用笔记(windows下使用上传数据到GitHub)[转]
TortoiseGit和msysGit安装及使用笔记(windows下使用上传数据到GitHub) Git-1.7.11-preview+GitExtensions244SetupComplete+T ...
- Amzon MWS API开发之 上传数据
亚马逊上传数据,现有能操作的功能有很多:库存数量.跟踪号.价格.商品....... 我们可以设置FeedType值,根据需要,再上传对应的xml文件即可. 下面可以看看FeedType类型 这次我们拿 ...
- Amazon MWS 上传数据 (三) 提交请求
前面介绍了设置服务和构造请求,现在介绍提交请求. 上传数据,查询上传操作的工作状态,和处理上传操作返回的报告操作使用的Amazon API 分别为:SubmitFeed(),FeedSubmissio ...
- Amazon MWS 上传数据 (二) 构造请求
上一篇文章提到了Amazon 上传数据有三个步骤,但是每个步骤都需要构造服务和构造请求,服务是一样的,请求各不相同:这个很容易理解,这三个步骤都需要和Amazon服务器交互,所以他们的服务构造是一样的 ...
- Amazon MWS 上传数据 (一) 设置服务
Amazon 上传数据的流程为: 通过 SubmitFeed 操作.加密标头和所有必需的元数据(包括 FeedType 的值在内),来提交 XML 或文本型数据文件.正如亚马逊 MWS的所有提交内容一 ...
- 上传数据插件 Easy Populate 遇到问题 ?langer=remove
批量上传,出现如下错误提示: ADD NEW PRODUCT FAILED! – Model: no200 – SQL error. Check Easy Populate error log in ...
- 说说ajax上传数据和接收数据
我是一个脑袋不太灵光的人,所以遇到问题,厚着脸皮去请教大神的时候,害怕被大神鄙视,但是还是被鄙视了.我说自己不要点脸面,那是不可能的,但是,为了能让自己的技术生涯能走的更长远一些,受点白眼,受点嘲笑也 ...
随机推荐
- 微信开发准备(一)--Maven仓库管理新建WEB项目
转自:http://www.cuiyongzhi.com/post/13.html 在我们的项目开发中经常会遇到项目周期很长,项目依赖jar包特别多的情况,所以我们经常会在项目中引入Maven插件,建 ...
- Delphi BLE 控件
TBluetoothLEDevice LDevice.Address;//"00:11:22:DD:EE:FF". LDevice.DeviceName//Mi LDevice.I ...
- awk简要使用
1 前言 awk是Unix环境下一种非常好的语言,适合于文本处理和报表生成,它还有许多精心设计的特性,允许进行特殊技巧程序设计.对于短消息来说,比如处理话单文件,使用awk就非常方便 ...
- java.sql.SQLException: Error while processing statement: FAILED: Execution Error, return code 2 from org.apache.hadoop.hive.ql.exec.mr.MapRedTask
执行Hive查询: Console是这样报错的 java.sql.SQLException: Error from org.apache.hadoop.hive.ql.exec.mr.MapRedTa ...
- Xcode快捷
- Codeforces 719E (线段树教做人系列) 线段树维护矩阵
题面简洁明了,一看就懂 做了这个题之后,才知道怎么用线段树维护递推式.递推式的递推过程可以看作两个矩阵相乘,假设矩阵A是初始值矩阵,矩阵B是变换矩阵,求第n项相当于把矩阵B乘了n - 1次. 那么我们 ...
- Blender 安装
Blender 安装 Blender 安装 windows 上安装 Blender 搞定 Ubuntu Linux 上安装 Blender 搞定 windows 上安装 Blender Step 1 ...
- Luogu 3626 [APIO2009]会议中心
很优美的解法. 推荐大佬博客 如果没有保证字典序最小这一个要求,这题就是一个水题了,但是要保证字典序最小,然后我就不会了…… 如果一条线段能放入一个区间$[l', r']$并且不影响最优答案,那么对于 ...
- [译]Javascipt中的Strings
本文翻译youtube上的up主kudvenkat的javascript tutorial播放单 源地址在此: https://www.youtube.com/watch?v=PMsVM7rjupU& ...
- C#socket通信时,怎样判断socket双方是否断开连接
我在Server端new了一个socket,然后bind,开了一个线程来accept前来连接的client,每接到一个client前来连接就新开一个线程和它进行通信.我把Server端得到的socke ...