mosquitto官网: http://mosquitto.org/man/mqtt-7.html
在macOS安装mosquitto: https://www.jianshu.com/p/4b545332b495
安装MQTT.Fx:http://www.jensd.de/apps/mqttfx/1.7.1/
MQTT.fx的安装和使用:https://blog.csdn.net/tiantang_1986/article/details/85101366
Arduino Client for MQTT pubsubclient
Arduino Client for MQTTAPI Documentation https://pubsubclient.knolleary.net/api
代码参考: https://gist.github.com/boverby/d391b689ce787f1713d4a409fb43a0a4
arduino, Wemos D1测试订阅topic代码:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "xxx"; // wifi名称
const char* password = "xxxxxx"; // wifi密码
const char* mqtt_server = "192.168.0.3"; // mqtt服务器地址
int status = WL_IDLE_STATUS; // the starting Wifi radio's status
WiFiClient wifiClient;
PubSubClient client(wifiClient);
const byte ledPin = D8; // 需要控制的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("Stormer"))
{
Serial.println("connected");
client.subscribe("light"); // 订阅topic
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup()
{
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
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());
client.setServer(mqtt_server, 1883); // 连接mqtt
client.setCallback(callback); // 设置回调,控制led灯
}
void loop()
{
if (!client.connected())
{
reconnect();
}
client.loop();
}