当前位置:网站首页>学习太极创客 — MQTT(九)ESP8266 同时订阅和发布 MQTT 消息
学习太极创客 — MQTT(九)ESP8266 同时订阅和发布 MQTT 消息
2022-06-27 02:10:00 【xuechanba】
/********************************************************************** 项目名称/Project : 零基础入门学用物联网 程序名称/Program name : pub_and_sub 团队/Team : 太极创客团队 / Taichi-Maker (www.taichi-maker.com) 作者/Author : CYNO朔 日期/Date(YYYYMMDD) : 20200719 程序目的/Purpose : 利用PubSubClient同时订阅和发布信息。 定时向主题发布D3按键的状态 通过订阅主题收到信息是数字1则打开LED,否则关闭LED。 ----------------------------------------------------------------------- 本示例程序为太极创客团队制作的《零基础入门学用物联网》中示例程序。 该教程为对物联网开发感兴趣的朋友所设计和制作。如需了解更多该教程的信息,请参考以下网页: http://www.taichi-maker.com/homepage/esp8266-nodemcu-iot/iot-c/esp8266-nodemcu-web-client/http-request/ ***********************************************************************/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Ticker.h>
// 设置wifi接入信息(请根据您的WiFi信息进行修改)
const char* ssid = "FAST_153C80";
const char* password = "123456798";
const char* mqttServer = "test.ranye-iot.net";
// 如以上MQTT服务器无法正常连接,请前往以下页面寻找解决方案
// http://www.taichi-maker.com/public-mqtt-broker/
Ticker ticker;
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
int count; // Ticker计数用变量
void setup() {
Serial.begin(9600);
pinMode(D3, INPUT);
pinMode(LED_BUILTIN, OUTPUT);
// Ticker定时对象
ticker.attach(1, tickerCount);
//设置ESP8266工作模式为无线终端模式
WiFi.mode(WIFI_STA);
// 连接WiFi
connectWifi();
// 设置MQTT服务器和端口号
mqttClient.setServer(mqttServer, 1883);
mqttClient.setCallback(receiveCallback);
// 连接MQTT服务器
connectMQTTServer();
}
void loop() {
if (mqttClient.connected()) {
// 如果开发板成功连接服务器
// 每隔3秒钟发布一次信息
if (count >= 3){
pubMQTTmsg();
count = 0;
}
// 保持心跳
mqttClient.loop();
} else {
// 如果开发板未能成功连接服务器
connectMQTTServer(); // 则尝试连接服务器
}
}
void tickerCount(){
count++;
}
void connectMQTTServer(){
// 根据ESP8266的MAC地址生成客户端ID(避免与其它ESP8266的客户端ID重名)
String clientId = "esp8266-" + WiFi.macAddress();
// 连接MQTT服务器
if (mqttClient.connect(clientId.c_str())) {
Serial.println("MQTT Server Connected.");
Serial.println("Server Address: ");
Serial.println(mqttServer);
Serial.println("ClientId:");
Serial.println(clientId);
subscribeTopic(); // 订阅指定主题
} else {
Serial.print("MQTT Server Connect Failed. Client State:");
Serial.println(mqttClient.state());
delay(3000);
}
}
// 发布信息
void pubMQTTmsg(){
// 建立发布主题。主题名称以Taichi-Maker-为前缀,后面添加设备的MAC地址。
// 这么做是为确保不同用户进行MQTT信息发布时,ESP8266客户端名称各不相同,
String topicString = "Taichi-Maker-Pub-" + WiFi.macAddress();
char publishTopic[topicString.length() + 1];
strcpy(publishTopic, topicString.c_str());
// 定时向服务器主题发布当前D3引脚状态
String messageString;
if(digitalRead(D3)){
messageString = "on";
} else {
messageString = "off";
}
char publishMsg[messageString.length() + 1];
strcpy(publishMsg, messageString.c_str());
// 实现ESP8266向主题发布信息
if(mqttClient.publish(publishTopic, publishMsg)){
Serial.println("Publish Topic:");Serial.println(publishTopic);
Serial.println("Publish message:");Serial.println(publishMsg);
} else {
Serial.println("Message Publish Failed.");
}
}
// 订阅指定主题
void subscribeTopic(){
// 建立订阅主题。主题名称以Taichi-Maker-Sub为前缀,后面添加设备的MAC地址。
// 这么做是为确保不同设备使用同一个MQTT服务器测试消息订阅时,所订阅的主题名称不同
String topicString = "Taichi-Maker-Sub-" + WiFi.macAddress();
char subTopic[topicString.length() + 1];
strcpy(subTopic, topicString.c_str());
// 通过串口监视器输出是否成功订阅主题以及订阅的主题名称
if(mqttClient.subscribe(subTopic)){
Serial.println("Subscribe Topic:");
Serial.println(subTopic);
} else {
Serial.print("Subscribe Fail...");
}
}
// 收到信息后的回调函数
void receiveCallback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message Received [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println("");
Serial.print("Message Length(Bytes) ");
Serial.println(length);
if ((char)payload[0] == '1') {
// 如果收到的信息以“1”为开始
digitalWrite(LED_BUILTIN, LOW); // 则点亮LED。
} else {
digitalWrite(LED_BUILTIN, HIGH); // 否则熄灭LED。
}
}
// ESP8266连接wifi
void connectWifi(){
WiFi.begin(ssid, password);
//等待WiFi连接,成功连接后输出成功信息
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi Connected!");
Serial.println("");
}
原程序中,少了对 D3 引脚的初始化设置。
pinMode(D3, INPUT);
运行代码如下,
首先,测试上电串口输出信息并向主题 Taichi-Maker-Pub-EC:FA:BC:40:6F:5B 发布信息 on / off

然后,打开 MQTT.fx 软件,订阅该主题,并查看接收到的信息。

接着,通过 MQTT.fx 软件向主题 Taichi-Maker-Sub-EC:FA:BC:40:6F:5B 发布消息,


查看串口监视器看收到的消息,并观察 LED 的变化。


边栏推荐
- 1、项目准备与新建
- ThreadLocal详解
- Oracle/PLSQL: HexToRaw Function
- Oracle/PLSQL: Lpad Function
- Shell脚本系列篇(1) 入门
- Learn the most basic operation of discodiffusion
- Oracle/PLSQL: Soundex Function
- I earned 3W yuan a month from my sideline: the industry you despise really makes money!
- Binary tree OJ problem
- SQLite Reader 插件测试SQLite语法
猜你喜欢

“所有专业都在劝退”,对大学生最友好的竟然是它?

C语言--职工信息管理系统设计

按键控制LED状态翻转

1、项目准备与新建

Parameter estimation -- Chapter 7 study report of probability theory and mathematical statistics (point estimation)

速看!2022年6月编程语言排行榜出炉!第一名太牛啦

Press key to control LED status reversal

Consumers pursue the iPhone because its cost performance exceeds that of domestic mobile phones

Dameng database installation

WiFi-IoT 鸿蒙开发套件样例开发
随机推荐
Memcached basics 11
Detailed explanation of ThreadLocal
Oracle/PLSQL: CharToRowid Function
Svg drag dress Kitty Cat
pytorch 23 hook的使用与介绍 及基于hook实现即插即用的DropBlock
UVM in UVM_ config_ Setting and obtaining DB non-linear
Cvpr2022 | pointdistiller: structured knowledge distillation for efficient and compact 3D detection
Nokov motion capture system makes it possible for multi field cooperative UAV to build independently
dat. gui. JS star circle track animation JS special effect
ConstraintLayout(约束布局)开发指南
perl语言中 fork()、exec()、waitpid() 、 $? >> 8 组合
别被洗脑了,这才是90%中国人的工资真相
numpy 数组运算机制浅探
Memcached Foundation 12
Summary of config mechanism and methods in UVM (2)
Flink Learning 2: Application Scenarios
Oracle/PLSQL: NumToYMInterval Function
WiFi-IoT 鸿蒙开发套件样例开发
d的appendTo包装
Flink学习2:应用场景