极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 23168|回复: 2

使用esp32-Arduino+PubSubClient+mqtt 上传数据到中移动OneNet

[复制链接]
发表于 2018-10-20 15:04:51 | 显示全部楼层 |阅读模式
使用esp32-doit-dev-v1开发板,测试mqtt协议, 发布(publish)到onenet 平台。
注意:
1.使用的mqtt arduino 客户端是 pubsubclient 库。其默认是ESP8266, 所以例子例包换文件“Wifi8266.h”,可以改为"Wifi.h"就可以。
2.关键是按照mqtt的onenet文档,编制payload数据包。其具体格式有多种类型。调试的是最简单的type3, json数据2 形式。
  1. /*
  2. Basic ESP8266 MQTT example

  3. This sketch demonstrates the capabilities of the pubsub library in combination
  4. with the ESP8266 board/library.

  5. It connects to an MQTT server then:
  6.   - publishes "hello world" to the topic "outTopic" every two seconds
  7.   - subscribes to the topic "inTopic", printing out any messages
  8.     it receives. NB - it assumes the received payloads are strings not binary
  9.   - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
  10.     else switch it off

  11. It will reconnect to the server if the connection is lost using a blocking
  12. reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
  13. achieve the same result without blocking the main loop.

  14. To install the ESP8266 board, (using Arduino 1.6.4+):
  15.   - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
  16.        http://arduino.esp8266.com/stable/package_esp8266com_index.json
  17.   - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
  18.   - Select your ESP8266 in "Tools -> Board"

  19. */
  20. //改为<WiFi.h>
  21. #include <WiFi.h>
  22. #include <PubSubClient.h>
  23. #include <ArduinoJson.h>

  24. //#define BUILTIN_LED 2

  25. // Update these with values suitable for your network.

  26. const char* ssid = "热点ssid";
  27. const char* password = "连接密码";
  28. const char* mqtt_server = "183.230.40.39";

  29. WiFiClient espClient;
  30. PubSubClient client(espClient);
  31. long lastMsg = 0;
  32. char msg_buf[200];
  33. int value = 0;  //
  34. //char one_type3_header[] = {'0x03','0x00','0x46'};
  35. char dataTemplete[]="{"temperature":25.5,"time":%d}";
  36. char msgJson[75];
  37. char debug_buf[200];
  38. int i;
  39. unsigned short json_len=0;
  40. uint8_t* packet_p;
  41. uint8_t debug_buffer_start_index = 0;


  42. void setup_wifi() {

  43.   delay(10);
  44.   // We start by connecting to a WiFi network
  45.   Serial.println();
  46.   Serial.print("Connecting to ");
  47.   Serial.println(ssid);

  48.   WiFi.begin(ssid, password);

  49.   while (WiFi.status() != WL_CONNECTED) {
  50.     delay(500);
  51.     Serial.print(".");
  52.   }

  53.   randomSeed(micros());

  54.   Serial.println("");
  55.   Serial.println("WiFi connected");
  56.   Serial.println("IP address: ");
  57.   Serial.println(WiFi.localIP());
  58. }

  59. void callback(char* topic, byte* payload, unsigned int length) {
  60.   Serial.print("Message arrived [");
  61.   Serial.print(topic);
  62.   Serial.print("] ");
  63.   for (int i = 0; i < length; i++) {
  64.     Serial.print((char)payload[i]);
  65.   }
  66.   Serial.println();

  67.   // Switch on the LED if an 1 was received as first character
  68.   if ((char)payload[0] == '1') {
  69.     digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
  70.     // but actually the LED is on; this is because
  71.     // it is active low on the ESP-01)
  72.   } else {
  73.     digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  74.   }

  75. }

  76. void reconnect() {
  77.   // Loop until we're reconnected
  78.   while (!client.connected()) {
  79.     Serial.print("Attempting MQTT connection...");
  80.     // Create a random client ID
  81.     //String clientId = "设备_id";
  82.     //clientId += String(random(0xffff), HEX);
  83.     // Attempt to connect
  84.     if (client.connect("设备id","产品_id","API_key")) {  //One net user name as product ID , and password as APIKey
  85.       Serial.println("connected");
  86.       // Once connected, publish an announcement...
  87.       client.publish("outTopic", "hello world");
  88.       // ... and resubscribe
  89.       client.subscribe("inTopic");
  90.     } else {
  91.       Serial.print("failed, rc=");
  92.       Serial.print(client.state());
  93.       Serial.println(" try again in 5 seconds");
  94.       // Wait 5 seconds before retrying
  95.       delay(5000);
  96.     }
  97.   }
  98. }

  99. void setup() {
  100.   pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output, where do it esp32 get gpio2 as led
  101.   Serial.begin(115200);
  102.   setup_wifi();
  103.   client.setServer(mqtt_server, 6002);  //not 1883 , one net use the port of 6002 as mqtt server
  104.   client.connect("设备Id","产品id","API_key");
  105.   client.setCallback(callback);
  106. }

  107. void loop() {

  108.   if (!client.connected()) {
  109.     reconnect();
  110.   }
  111.   client.loop();

  112.   long now = millis();
  113.   if (now - lastMsg > 2000) {
  114.     lastMsg = now;
  115.     ++value;
  116.     //snprintf (msgJson, 75, "hello world #%ld", value);
  117.     snprintf(msgJson,40,dataTemplete,22);
  118.     json_len=strlen(msgJson); //packet length count the end char '\0'
  119.     msg_buf[0]=char(0x03);  //palyLoad packet byte 1, one_net mqtt Publish packet payload byte 1, type3 , json type2
  120.     msg_buf[1]=char(json_len>>8);  //high 8 bits of json_len (16bits as short int type)
  121.     msg_buf[2]=char(json_len&0xff); //low 8 bits of json_len (16bits as short int type)
  122.    // snprintf(msg_buf+3,40,dataTemplete,value);
  123.   
  124.    memcpy(msg_buf+3,msgJson,strlen(msgJson));
  125.    msg_buf[3+strlen(msgJson)] = 0;
  126.     Serial.print("Publish message: ");
  127.     Serial.println(msgJson);
  128.     client.publish("$dp",msg_buf,3+strlen(msgJson),false); // msg_buf as payload length which may have a "0x00"byte
  129.    
  130.     //debug one_net packet
  131.     packet_p = client.getBufferPointer();
  132.     for(i = 0 ; i< 200;i++)
  133.     {
  134.      //sprintf(debug_buf,"0x%02x ",msg_buf[i]);
  135.      sprintf(debug_buf,"0x%02x ",packet_p[i]);
  136.      Serial.print(debug_buf);
  137.     }
  138.     Serial.println();
  139.     for(i = 0 ; i< 200;i++)
  140.     {
  141.      sprintf(debug_buf,"0x%02x ",msg_buf[i]);
  142.      //sprintf(debug_buf,"0x%02x ",packet_p[i]);
  143.      Serial.print(debug_buf);
  144.     }
  145.     Serial.println();
  146.     debug_buffer_start_index=client.getDebugVar();
  147.     Serial.println(debug_buffer_start_index);
  148.   }
  149. }
复制代码


附带略有修改publish方法的PubSubClient 库文件。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?注册

x
回复

使用道具 举报

发表于 2018-10-24 08:34:00 | 显示全部楼层
厉害啊,兄弟有空来个详细教程呢
回复 支持 反对

使用道具 举报

发表于 2019-11-13 14:40:02 | 显示全部楼层
学习一下啊,WIFI模块开发这块可以交流
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 需要先绑定手机号

Archiver|联系我们|极客工坊

GMT+8, 2024-4-20 20:20 , Processed in 0.069380 second(s), 21 queries .

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表