查看: 1403|回复: 2

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

[复制链接]
  • TA的每日心情
    奋斗
    2018-11-16 21:49
  • 签到天数: 5 天

    [LV.2]偶尔看看I

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

    kittenblock中小学创客名师推荐的图形化编程软件

    
    /*
     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);
      }
      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);
         sprintf(debug_buf,"0x%02x ",packet_p);
         Serial.print(debug_buf);
        }
        Serial.println();
        for(i = 0 ; i< 200;i++)
        {
         sprintf(debug_buf,"0x%02x ",msg_buf);
         //sprintf(debug_buf,"0x%02x ",packet_p);
         Serial.print(debug_buf);
        }
        Serial.println();
        debug_buffer_start_index=client.getDebugVar();
        Serial.println(debug_buffer_start_index);
      }
    }


    附带略有修改publish方法的PubSubClient 库文件。
    pubsubclient-xiaohezyd.zip (38.3 KB, 下载次数: 32)
  • TA的每日心情

    2019-2-26 21:15
  • 签到天数: 66 天

    [LV.6]常住居民II

    发表于 2019-2-15 22:00 | 显示全部楼层
    //debug one_net packet 后面是做什么用的?
  • TA的每日心情
    奋斗
    2018-11-16 21:49
  • 签到天数: 5 天

    [LV.2]偶尔看看I

     楼主| 发表于 2019-4-14 21:36 | 显示全部楼层
    997497869 发表于 2019-2-15 22:00
    //debug one_net packet 后面是做什么用的?

    用来测试发送到onenet 的数据包的内容
    您需要登录后才可以回帖 登录 | 立即注册  

    本版积分规则

    热门推荐

    arduino温湿度串口监视器显示问题
    arduino温湿度串口监视器
    本人刚学arduino,遇到一些技术问题,希望大佬们帮我看一下程序,具体就是温湿度开始
    全过程展示:PWM自定义、测速、PID调速、PID自整定
    全过程展示:PWM自定义、
    有一天,电控小白在某宝上买来了一块Arduino Mega2560、一款直流电机。小白想:“这款
    关于数据同步遇到的问题
    关于数据同步遇到的问题
    首先,下载了DHT-sensor-library-master.zip 并解压到libraries文件夹中(图1) 其次
    blinker设备连接一会后自动断开
    blinker设备连接一会后自
    [mw_shl_code=arduino,true]#define BLINKER_WIFI #define BLINKER_PRINT Serial #
    学生智能打卡系统(接入blinker)
    学生智能打卡系统(接入bl
    【项目名称】学生智能打卡系统(接入blinker) 一.感谢各位大佬 首先感谢社区的管理员
    Copyright   ©2015-2016  Arduino中文社区  Powered by©Discuz!   ( 蜀ICP备14017632号-3 )
    快速回复 返回顶部 返回列表