使用MQTT先要有一个MQTT服务器,具体如何搭建可以看上一篇文章
这一篇主要讲下NodeMCU的使用,以及MQTT介绍和如何接发消息
NodeMCU
1. ESP8266介绍
介绍NodeMCU前需要先了解ESP8266,它是一个完整自称体系的WiFi网络解决方案,能独立运行也可为从部件连接单片机运行
具有以下特点:
- 超小尺寸
- 低功耗
- 内置TCP/IP协议
- 可编程
- 低成本
2. NodeMCU介绍
NodeMCU是一款基于ESP8266模块的开源硬件,符合Arduino框架。同时可使用Node.js编程
NodeMCU引脚:
3. WiFi测试
先要安装Arduino IDE For ESP8266
Arduino IDE For ESP8266是根据Arduino修改的专门烧写ESP8266开发板的IDE。在装好Arduino IDE后:
- 打开Arduino 文件->首选项,在 附加开发管理网站 中填入http://arduino.esp8266.com/stable/package_esp8266com_index.json,然后点击确定保存
- 重启IDE后,打开 工具->开发板->开发板管理器;搜索ESP8266,选择esp 8266 by ESP8266 Community安装
- 下载完成后可以在开发板选项中看到ESP8266 Module,以及NodeMCU等可选开发板
- 将NodeMCU通过usb连接到电脑,在工具下选择相应配置
波特率越大烧录程序速度越快但有可能出错
端口选择NodeMCU对应端口,如果没看到端口,那是驱动没有装,装驱动可以看这里
http://www.arduino.cn/thread-1008-1-1.html
- 打开示例选择ESP8266WiFi中的WiFiScan
烧到板子上打开窗口监视器可以看到扫描出来的附近热点
MQTT
1. MQTT介绍
消息队列遥测传输(MQTT)是IBM开发的即时通讯协议,为计算能力有限且工作在低带宽、不可靠网络的传感器或控制设备而设计。比如对于移动开发,它可以用于消息推送,即时通讯等等
特性:
- 发布/订阅的消息模式,提供一对多的消息发布
- 使用TCP/IP提供网络连接
- 有三种消息发布服务质量,至多一次,至少一次,只有一次
- 传输小、开销小
- LastWill通知中断机制
2. MQTT原理介绍
- 客户端:发布者(Publish)、订阅者(SubScribe),客户端有ID,ID冲突会挤掉先连接客户端。
- 服务器端:代理(Broker)
- 消息:主题(Topic)+负载(payload)
举个场景为例:
QQ用户2(账号QQ1000)向QQ用户1(QQ9999)发送消息“Hello World”.
发送者:QQ用户2
订阅者:QQ用户1
消息:QQ9999+”Hello World”.
消息发送至服务器,服务器查找QQ9999对应的用户后,发送信息给QQ用户2.
3. MQTT ESP8266库
菜单“项目”-“加载库”-“管理库”,搜索安装“PubSubClient”
PubSubClient有一些示例可以打开mqtt_esp8266看下
4. MQTT接发消息体验
这里做两个示例
1. NodeMCU接受消息:服务器来控制LED灯状态
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "******";
const char* password = "******";
const char* mqtt_server = "******";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
int LED = 5; // LED引脚
void setup() {
pinMode(LED, OUTPUT); // Initialize the pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
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(".");
}
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(LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is acive low on the ESP-01)
} else {
digitalWrite(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...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
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 loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, 75, "hello world #%ld", value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("outTopic", msg);
}
}
2. NodeMCU发送消息:向服务器上传温度湿度信息
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <SimpleDHT.h>
WiFiClient espClient;
PubSubClient client(espClient);
int pinDHT11 = 5;
SimpleDHT11 dht11(pinDHT11);
const char* ssid = "1705";
const char* password = "Zoor170302";
const char* mqtt_server = "*****";
long lastMsg = 0;
char msg[50];
int value = 0;
int LedStatus = 4;
int LedOutPut = 14;
void setup() {
pinMode(LedStatus, OUTPUT);
pinMode(LedOutPut, OUTPUT);
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
// 连接wifi
void setup_wifi() {
delay(10);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
digitalWrite(LedStatus, HIGH);
delay(500);
digitalWrite(LedStatus, LOW);
Serial.print(".");
}
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(LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// // but actually the LED is on; this is because
// // it is acive low on the ESP-01)
// } else {
// digitalWrite(LED, HIGH); // Turn the LED off by making the voltage HIGH
// }
}
void reconnect() {
while (!client.connected()) {
if (client.connect("ESP8266Client")) {
client.subscribe("inTopic");
digitalWrite(LedStatus, HIGH);
} else {
Serial.println("mqtt failed");
digitalWrite(LedStatus, HIGH);
delay(5000);
digitalWrite(LedStatus, LOW);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 10000) {
lastMsg = now;
byte temperature = 0;
byte humidity = 0;
int err = SimpleDHTErrSuccess;
if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
delay(1000);
return;
}
float tep = formatFloat((float)temperature);
float hum = formatFloat((float)humidity);
snprintf(msg, 75, "{Tep: %ld,Hum: %ld}", temperature, humidity);
client.publish("outputDHT11", msg);
Serial.println(msg);
digitalWrite(LedOutPut, HIGH);
delay(50);
digitalWrite(LedOutPut, LOW);
}
}
float formatFloat(float f)
{
int temp = (f * 100);
return float(temp / 100);
}
3、向阿里云Iot平台上传数据
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <SimpleDHT.h>
WiFiClient espClient;
PubSubClient client(espClient);
int pinDHT11 = 5;
SimpleDHT11 dht11(pinDHT11);
const char* ssid = "1705";
const char* password = "Zoor170302";
const char* mqtt_server = "a1PifWnko4O.iot-as-mqtt.cn-shanghai.aliyuncs.com";
const char* mqtt_username = "vCgnBR7ax2AQIFFjo8mf&a1PifWnko4O";
const char* mqtt_password = "******";
const char* mqtt_clientId = "FESA234FBDS24|securemode=3,signmethod=hmacsha1,timestamp=789|";
const char* body = "{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}"
const char* inTopic = "/sys/a1PifWnko4O/vCgnBR7ax2AQIFFjo8mf/thing/service/property/set";
#define ALINK_BODY_FORMAT "{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}"
#define ALINK_TOPIC_PROP_POST "/sys/a1PifWnko4O/vCgnBR7ax2AQIFFjo8mf/thing/event/property/post"
long lastMsg = 0;
char msg[50];
int value = 0;
int LedStatus = 4;
int LedOutPut = 14;
void setup() {
pinMode(LedStatus, OUTPUT);
pinMode(LedOutPut, OUTPUT);
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
// 连接wifi
void setup_wifi() {
delay(10);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
digitalWrite(LedStatus, HIGH);
delay(500);
digitalWrite(LedStatus, LOW);
Serial.print(".");
}
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(LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// // but actually the LED is on; this is because
// // it is acive low on the ESP-01)
// } else {
// digitalWrite(LED, HIGH); // Turn the LED off by making the voltage HIGH
// }
}
void reconnect() {
while (!client.connected()) {
if (client.connect(mqtt_clientId,mqtt_username , mqtt_password)) {
// client.subscribe("inTopic");
digitalWrite(LedStatus, HIGH);
} else {
Serial.println("mqtt failed");
digitalWrite(LedStatus, HIGH);
delay(5000);
digitalWrite(LedStatus, LOW);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 10000) {
lastMsg = now;
byte temperature = 0;
byte humidity = 0;
int err = SimpleDHTErrSuccess;
if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
delay(1000);
return;
}
char param[32];
char jsonBuf[128];
sprintf(param, "{\"CurrentTemperature\":%d},\"RelativeHumidity:%d\"",temperature,humidity);
sprintf(jsonBuf, ALINK_BODY_FORMAT, param);
Serial.println(jsonBuf);
boolean d = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
Serial.print("publish:0 失败;1成功");
Serial.println(d);
digitalWrite(LedOutPut, HIGH);
delay(50);
digitalWrite(LedOutPut, LOW);
}
}
float formatFloat(float f)
{
int temp = (f * 100);
return float(temp / 100);
}
阿里云栗子:
https://help.aliyun.com/document_detail/104070.html?spm=a2c4g.11186623.6.773.5d2578dc2DCPeE