| 2 |
raymond |
1 |
/*
|
|
|
2 |
Basic ESP32 MQTT example:
|
|
|
3 |
It connects to an MQTT server then:
|
|
|
4 |
- publishes "hello world" to the topic "output" every two seconds
|
|
|
5 |
- subscribes to the topic "input", printing out any (string) messages it receives.
|
|
|
6 |
- If the first character of the topic "input" is an 1, switch ON the ESP Led, else switch it off
|
|
|
7 |
It will reconnect to the server using a NON blocking reconnect function.
|
|
|
8 |
*/
|
|
|
9 |
|
|
|
10 |
#include <WiFi.h>
|
|
|
11 |
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient/
|
|
|
12 |
#include <AsyncFsWebServer.h> // https://github.com/cotestatnt/esp-fs-webserver
|
|
|
13 |
|
|
|
14 |
#include <FS.h>
|
|
|
15 |
#include <LittleFS.h>
|
|
|
16 |
|
|
|
17 |
// Define built-in LED if not defined by board (eg. generic dev boards)
|
|
|
18 |
#ifndef LED_BUILTIN
|
|
|
19 |
#define LED_BUILTIN 2
|
|
|
20 |
#endif
|
|
|
21 |
|
|
|
22 |
AsyncFsWebServer myWebServer(LittleFS, 80, "myServer");
|
|
|
23 |
|
|
|
24 |
// Update these with values suitable for your network.
|
|
|
25 |
const char* mqtt_server = "broker.mqtt-dashboard.com";
|
|
|
26 |
|
|
|
27 |
WiFiClient espClient;
|
|
|
28 |
PubSubClient mqttClient(espClient);
|
|
|
29 |
|
|
|
30 |
// Let'use our unique clientID and topics (tied to cliendId in setup())
|
|
|
31 |
char clientId[16];
|
|
|
32 |
char inTopic[24];
|
|
|
33 |
char outTopic[24];
|
|
|
34 |
|
|
|
35 |
//////////////////////////////// Filesystem /////////////////////////////////////////
|
|
|
36 |
bool startFilesystem() {
|
|
|
37 |
if (LittleFS.begin()) {
|
|
|
38 |
myWebServer.printFileList(LittleFS, "/", 1, Serial);
|
|
|
39 |
return true;
|
|
|
40 |
} else {
|
|
|
41 |
Serial.println("ERROR on mounting filesystem. It will be reformatted!");
|
|
|
42 |
LittleFS.format();
|
|
|
43 |
ESP.restart();
|
|
|
44 |
}
|
|
|
45 |
return false;
|
|
|
46 |
}
|
|
|
47 |
|
|
|
48 |
/////////////////////////// MQTT callback function ///////////////////////////////////
|
|
|
49 |
void mqttCallback(char* topic, byte* payload, unsigned int length) {
|
|
|
50 |
Serial.printf("Message arrived [%s] ", topic);
|
|
|
51 |
for (int i = 0; i < length; i++) {
|
|
|
52 |
Serial.print((char)payload[i]);
|
|
|
53 |
}
|
|
|
54 |
Serial.println();
|
|
|
55 |
|
|
|
56 |
// Switch on the LED if an 1 was received as first character (LED on with LOW signal on most boards)
|
|
|
57 |
digitalWrite(LED_BUILTIN, (char)payload[0] == '1' ? LOW : HIGH);
|
|
|
58 |
}
|
|
|
59 |
|
|
|
60 |
/////////////////////////// MQTT reconnect function ///////////////////////////////////
|
|
|
61 |
void mqttReconnect() {
|
|
|
62 |
|
|
|
63 |
if (WiFi.status() != WL_CONNECTED) // Check connection
|
|
|
64 |
return;
|
|
|
65 |
|
|
|
66 |
static uint32_t lastConnectionTime = 5000;
|
|
|
67 |
if (millis() - lastConnectionTime < 5000) // Wait 5 seconds before retrying
|
|
|
68 |
return;
|
|
|
69 |
lastConnectionTime = millis();
|
|
|
70 |
|
|
|
71 |
Serial.print("Attempting MQTT connection...");
|
|
|
72 |
if (mqttClient.connect(clientId)) { // Attempt to connect
|
|
|
73 |
Serial.println("connected");
|
|
|
74 |
|
|
|
75 |
String payload = "Hello World from ";
|
|
|
76 |
payload += clientId;
|
|
|
77 |
mqttClient.publish(outTopic, payload.c_str()); // Once connected, publish an announcement...
|
|
|
78 |
mqttClient.subscribe(inTopic); // ... and resubscribe
|
|
|
79 |
} else {
|
|
|
80 |
Serial.printf("failed, rc=%d, try again in 5 seconds\n", mqttClient.state());
|
|
|
81 |
}
|
|
|
82 |
}
|
|
|
83 |
|
|
|
84 |
|
|
|
85 |
|
|
|
86 |
void setup() {
|
|
|
87 |
pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output
|
|
|
88 |
Serial.begin(115200);
|
|
|
89 |
|
|
|
90 |
// LittleFS filesystem init
|
|
|
91 |
startFilesystem();
|
|
|
92 |
|
|
|
93 |
// Try to connect to flash stored SSID, start AP if fails after timeout
|
|
|
94 |
if (!myWebServer.startWiFi(10000)) {
|
|
|
95 |
Serial.println("\nWiFi not connected! Starting AP mode...");
|
|
|
96 |
myWebServer.startCaptivePortal("ESP_AP", "123456789", "/setup");
|
|
|
97 |
}
|
|
|
98 |
|
|
|
99 |
// Enable ACE FS file web editor and add FS info callback function
|
|
|
100 |
myWebServer.enableFsCodeEditor();
|
|
|
101 |
|
|
|
102 |
// Start webserver
|
|
|
103 |
myWebServer.init();
|
|
|
104 |
Serial.print("Async ESP Web Server started on IP Address: ");
|
|
|
105 |
Serial.println(myWebServer.getServerIP());
|
|
|
106 |
Serial.println(
|
|
|
107 |
"This is \"simpleServer.ino\" example.\n"
|
|
|
108 |
"Open /setup page to configure optional parameters.\n"
|
|
|
109 |
"Open /edit page to view, edit or upload example or your custom webserver source files."
|
|
|
110 |
);
|
|
|
111 |
|
|
|
112 |
// Create a unique mqttClient ID and in/out topics
|
|
|
113 |
snprintf(clientId, sizeof(clientId), "ESP-%llX", ESP.getEfuseMac());
|
|
|
114 |
snprintf(inTopic, sizeof(inTopic), "%s/input", clientId);
|
|
|
115 |
snprintf(outTopic, sizeof(outTopic), "%s/output", clientId);
|
|
|
116 |
|
|
|
117 |
Serial.print("MQTT CLiend ID: ");
|
|
|
118 |
Serial.println(clientId);
|
|
|
119 |
Serial.print("Publish output topic: ");
|
|
|
120 |
Serial.println(outTopic);
|
|
|
121 |
Serial.print("Subscribe input topic: ");
|
|
|
122 |
Serial.println(inTopic);
|
|
|
123 |
|
|
|
124 |
// Set MQTT server and callback function
|
|
|
125 |
mqttClient.setServer(mqtt_server, 1883);
|
|
|
126 |
mqttClient.setCallback(mqttCallback);
|
|
|
127 |
}
|
|
|
128 |
|
|
|
129 |
void loop() {
|
|
|
130 |
|
|
|
131 |
// Handle MQTT client
|
|
|
132 |
if (!mqttClient.connected()) {
|
|
|
133 |
// Client not connected, try to reconnect every 5 seconds
|
|
|
134 |
mqttReconnect();
|
|
|
135 |
} else {
|
|
|
136 |
// Client connected
|
|
|
137 |
mqttClient.loop();
|
|
|
138 |
// Publish a new message every 5 seconds
|
|
|
139 |
static uint32_t lastMsgTime = millis();
|
|
|
140 |
static uint16_t value = 0;
|
|
|
141 |
if (millis() - lastMsgTime > 5000) {
|
|
|
142 |
lastMsgTime = millis();
|
|
|
143 |
|
|
|
144 |
char payload[64];
|
|
|
145 |
snprintf(payload, sizeof(payload), "Hello World from %s #%d", clientId, ++value);
|
|
|
146 |
|
|
|
147 |
Serial.print("Publish message: ");
|
|
|
148 |
Serial.println(payload);
|
|
|
149 |
mqttClient.publish(outTopic, payload);
|
|
|
150 |
}
|
|
|
151 |
}
|
|
|
152 |
|
|
|
153 |
// Nothing to do in main loop for Async Web Server
|
|
|
154 |
delay(10);
|
|
|
155 |
}
|