玩转OneNET物联网平台之MQTT服务② —— 远程控制LED

知识共享许可协议 版权声明:署名,允许他人基于本文进行创作,且必须基于与原先许可协议相同的许可协议分发本文 (Creative Commons

1.理论基础

    参考博主线上博文:

  • 玩转PubSubClient MQTT库
  • 玩转OneNET物联网平台之简介
  • 玩转OneNET物联网平台之MQTT服务①

2.远程控制LED

2.1 实验材料

  • ESP8266 NodeMcu
  • OneNet Mqtt调试工具
  • OneNet平台

2.2 实验步骤

2.2.1 创建 ESP8266智能灯系统 产品(MQTT协议)

image

注意点

  • 务必选择MQTT协议

    创建完毕后,我们点击查看具体的产品信息:

image

注意点

  • 需要记录产品ID,其用来区分产品唯一标识符
  • Master-APIkey,网络请求鉴权信息,接口调用需要带入

2.2.2 API调试创建 deviceA和deviceB两个设备

API接口定义

操作步骤

  • 通过API调试工具创建deviceA

image

http body

{
    "title": "mqtt_device_A",
    "desc": "mqtt_device_A",
    "tags": ["china", "mobile"],
    "location": {
        "lon": 109,
        "lat": 23.54
    },
    "auth_info": "mqtt_device_A",
    "other": {
        "version": "1.0.0",
        "manufacturer": "china mobile"
    }
}
  • 通过API调试工具创建deviceB

image

http body

{
    "title": "mqtt_device_B",
    "desc": "mqtt_device_B",
    "tags": ["china", "mobile"],
    "location": {
        "lon": 109,
        "lat": 23.54
    },
    "auth_info": "mqtt_device_B",
    "other": {
        "version": "1.0.0",
        "manufacturer": "china mobile"
    }
}
  • 查看设备列表

image

2.2.2 NodeMcu烧录代码 —— deviceA

    为了明确区分代码功能,博哥命名工程名为P_OneNet_Exam01:

  • P_OneNet_Exam01.ino文件:
/**
 *  功能:ESP8266 Mqtt客户端调试主题功能,订阅OneNet Mqtt工具发过来的控制Led消息
 *  作者:单片机菜鸟
 *  时间:2019-06-25
 *  描述:
 *      1.OneNet平台端:提前在OneNet平台创建DeviceA,DeviceB两个设备点,DeviceA属于NodeMcu,DeviceB属于OneNet Mqtt调试工具
 *      2.初始化工作:初始化网络配置,Mqtt客户端配置,连接鉴权,订阅主题
 *      3.订阅消息:获取发送过来的消息(json格式),解析消息,实现控制亮灭灯
*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Ticker.h>
#include "H_project.h"

int state;
WiFiClient espClient;

//声明方法
void initSystem();
void initOneNetMqtt();
void callback(char* topic, byte* payload, unsigned int length);

/**
 * 初始化
 */
void setup() {
  initSystem();
  initOneNetMqtt();
}

void loop() {
  ESP.wdtFeed();
  state = connectToOneNetMqtt();
  if(state == ONENET_RECONNECT){
     //重连成功 需要重新注册
     mqttClient.subscribe(TOPIC,1);
     mqttClient.loop();
  }else if(state == ONENET_CONNECTED){
     mqttClient.loop();
  }
  delay(2000);
}

void initSystem(){
    int cnt = 0;
    Serial.begin (115200);
    Serial.println("\r\n\r\nStart ESP8266 MQTT");
    Serial.print("Firmware Version:");
    Serial.println(VER);
    Serial.print("SDK Version:");
    Serial.println(ESP.getSdkVersion());
    wifi_station_set_auto_connect(0);//关闭自动连接
    ESP.wdtEnable(5000);
    WiFi.disconnect();
    delay(100);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
          delay(500);
          cnt++;
          Serial.print(".");
          if(cnt>=40){
            cnt = 0;
            //重启系统
            delayRestart(1);
          }
    }
    pinMode(LED_BUILTIN, OUTPUT); 
}

void initOneNetMqtt(){
    mqttClient.setServer(mqttServer,mqttPort);
    mqttClient.setClient(espClient);
    mqttClient.setCallback(callback);

    initOneNet(PRODUCT_ID,API_KEY,DEVICE_ID);
}

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();

  if ((char)payload[0] == '1') {
    digitalWrite(LED_BUILTIN, LOW);
  } else {
    digitalWrite(LED_BUILTIN, HIGH);
  }
}
  • H_project.h 代码:
#ifndef _MAIN_H__
#define _MAIN_H__


extern "C" {
#include "user_interface.h"
#include "smartconfig.h"
}

/************** ESP8266相关操作 **************************/
void delayRestart(float t);
void delayNs(uint8_t m);
/*********************************************************/

/*************** OneNet MQTT相关操作 ****************************/
void initOneNet(uint8_t *productId,uint8_t *apiKey,uint8_t *deviceId);
int connectToOneNetMqtt();
/*********************************************************/

#define ONENET_DISCONNECTED 1 //已经断开
#define ONENET_CONNECTED 2    //已经连接上
#define ONENET_RECONNECT 3    //重连成功

//常量
#define VER             "MQTT_LED_V1.0"
const char* ssid = "xxxx";//wifi账号
const char* password = "xxxx";//wifi秘密

//OneNet相关
PubSubClient mqttClient;
const char* mqttServer = "183.230.40.39";//mqtt服务器
const uint16_t mqttPort = 6002;
#define PRODUCT_ID    "xxxx" //此为博哥自己的产品id 请新建自己的
#define API_KEY    "xxxx"
#define DEVICE_ID "xxxx"
#define TOPIC     "xxxx"

unsigned long lastWiFiCheckTick = 0;
bool ledState = 0;

#endif

    全部工程代码,博哥放在个人QQ群里。

image

    把工程烧进NodeMcu,然后可以看到串口打印内容,如下:

image

    同时,也可以在OneNet平台看到设备在线情况,如下:

image

2.2.3 官方调试工具发送控制灯消息 —— deviceB

  • 配置deviceB

image

注意点

  • 重点关注博主标红的地方,DeviceID和ProductID、AuthInfo需要填写读者自身创建的

  • 配置完毕连接服务器

  • 发布控制信息

image

2.2.4 远程控制灯

  • 串口打印控制信息

image

  • NodeMcu效果图
    image

3.总结

在理解MQTT协议的基础上,本篇是非常容易操作的,但是也需要注意几点:

  • 创建自己的OneNet产品,不要用博哥创建的
  • 理解订阅主题含义

下一篇,博哥将结合App实现真正的远程灯控制。

猜你喜欢

转载自blog.csdn.net/dpjcn1990/article/details/93839603