esp8266是一個小型的開發模組,因為便宜且支援wifi功能,所以通常用來做一些比較單純的動作,也能夠降低開發的成本,這次將esp8266拿來做一個小型的MQTT broker。
不過作為一個輕量級的MQTT broker,雖然沒有辦法用TLS但也夠用了
使用arduino的IDE,並且要安裝uMQTTBroker.h
這個標頭檔,可以在這裡抓到
/*
* uMQTTBroker demo for Arduino
*
* Minimal Demo: the program simply starts a broker and waits for any client to connect.
*/
#include
#include "uMQTTBroker.h"
uMQTTBroker myBroker;
/*
* Your WiFi config here
*/
char ssid[] = "REVERSE"; // Replace with your network SSID (name)
char pass[] = "YAGAMI"; // Replace with your network password
/*
* WiFi init stuff
*/
void startWiFiClient()
{
Serial.println("Connecting to "+(String)ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: " + WiFi.localIP().toString());
}
void startWiFiAP()
{
WiFi.softAP(ssid, pass);
Serial.println("AP started");
Serial.println("IP address: " + WiFi.softAPIP().toString());
}
void setup()
{
Serial.begin(115200);
Serial.println();
Serial.println();
// Connect to a WiFi network
startWiFiClient();
// Or start the ESP as AP
//startWiFiAP();
// Start the broker
Serial.println("Starting MQTT broker");
myBroker.init();
}
void loop()
{
// do anything here
delay(1000);
}
這樣會連上一個SSID為REVERSE
的wifi,並且作為一個station來做MQTT的broker,若要把esp8266當AP的話,可以註解掉startWiFiClient();
,並取消註解//startWiFiAP();
就可以了