之前有简单介绍阿里云上安装Mosquitto,如果没有服务器也可以在本地机器进行安装。
// mqtt + esp8266
#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <Adafruit_INA219.h>
const char* ssid = "your_wifi_name"; // wifi名称
const char* password = "your_wifi_password"; // wifi密码
const char* mqtt_server = "your_mqtt_server"; // mqtt服务器地址,如本地ip192.168.31.22
WiFiClient espClient;
PubSubClient client(espClient);
const byte ledPin = D4; // 需要控制的led灯
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++) {
char receivedChar = (char)payload[i];
Serial.print(receivedChar); // 打印mqtt接收到消息
if (receivedChar == '1') { // 收到消息是 '1' 点亮LED灯
digitalWrite(ledPin, HIGH);
}
if (receivedChar == '0') // 收到消息是 '0' 关闭LED灯
digitalWrite(ledPin, LOW);
}
Serial.println();
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP8266 Client")) {
Serial.println("connected");
client.subscribe("ledStatus"); // 订阅 'ledStatus' 这个topic
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup()
{
Serial.begin(9600);
client.setServer(mqtt_server, 1883); // 连接mqtt
client.setCallback(callback); // 设置回调,控制led灯
pinMode(ledPin, OUTPUT);
}
void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
}
python发布订阅代码
# python 3.6
import random
import time
import random
from paho.mqtt import client as mqtt_client
broker = '127.0.0.1'
port = 1883
#消息主题
topic = "ledStatus"
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 1000)}'
def connect_mqtt():
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", rc)
client = mqtt_client.Client(client_id)
client.on_connect = on_connect
client.connect(broker, port)
return client
def publish(client):
while True:
time.sleep(3)
# msg = {"ledStatus":random.randint(0,1)}
msg=random.randint(0,1)
print("msg="+str(msg))
result = client.publish(topic, str(msg))
# result: [0, 1]
status = result[0]
if status == 0:
print(f"Send `{msg}` to topic `{topic}`")
else:
print(f"Failed to send message to topic {topic}")
def run():
client = connect_mqtt()
client.loop_start()
publish(client)
if __name__ == '__main__':
run()
esp8266 上传采集数据代码
#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <Adafruit_INA219.h>
#include <ArduinoJson.h> //JSON数据解析
const char* ssid = "yuxuan"; // wifi名称
const char* password = "yuxuan@+"; // wifi密码
const char* mqtt_server = "192.168.0.195"; // mqtt服务器地址,如本地ip192.168.31.22
const char* updata_topic = "updata_test";
StaticJsonDocument<200> json;
String JSONmessageBuffer = "";
WiFiClient espClient;
PubSubClient client(espClient);
const byte ledPin = 2; // 需要控制的led灯
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++) {
char receivedChar = (char)payload[i];
Serial.print(receivedChar); // 打印mqtt接收到消息
if (receivedChar == '1') { // 收到消息是 '1' 点亮LED灯
digitalWrite(ledPin, HIGH);
}
if (receivedChar == '0') // 收到消息是 '0' 关闭LED灯
digitalWrite(ledPin, LOW);
}
Serial.println();
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP8266 Client")) {
Serial.println("connected");
client.subscribe("ledStatus"); // 订阅 'ledStatus' 这个topic
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup()
{
Serial.begin(9600);
client.setServer(mqtt_server, 1883); // 连接mqtt
client.setCallback(callback); // 设置回调,控制led灯
pinMode(ledPin, OUTPUT);
}
void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
//上传设备采集数据
JsonObject json_root = json.to<JsonObject>();
json_root["roomLocation123"] = "LivingRoom123";
JsonObject device_name = json_root.createNestedObject("DeviceName"); //创建Obj
JsonObject DHT11_01_values = device_name.createNestedObject("DHT11_01");
DHT11_01_values["Temperature:"] = random(1,5);;
DHT11_01_values["Humidity:"] = random(11,15);;
JsonObject Relay_01_state = device_name.createNestedObject("Relay_01");
Relay_01_state["State"] = "OFF";
serializeJson(json, JSONmessageBuffer);
Serial.println(JSONmessageBuffer);
client.publish(updata_topic, JSONmessageBuffer.c_str()); // String.c_str() String转化为char[]
JSONmessageBuffer = "";
delay(500);
}