-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathesp_mqtt_broker.ino
93 lines (71 loc) · 2.41 KB
/
esp_mqtt_broker.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <ESP8266WiFi.h>
#include "uMQTTBroker.h"
// WiFi config
#ifndef WIFI_NETWORK_NAME
#define WIFI_NETWORK_NAME "***"
#define WIFI_PASSWORD "***"
#endif
// AP config
#ifndef AP_NETWORK_NAME
#define AP_NETWORK_NAME "***"
#define AP_PASSWORD "***"
#endif
// MQTT config
#ifndef MQTT_USERNAME
#define MQTT_USERNAME "***"
#define MQTT_PASSWORD "***"
#endif
#define QOS 1
// Mac address of this device (optional)
String apMacAddress;
// Custom Broker class with overwritten callback functions
class myMQTTBroker: public uMQTTBroker {
public:
virtual bool onConnect(IPAddress addr, uint16_t client_count) {
Serial.println(addr.toString() + " connected");
return true;
}
virtual bool onAuth(String username, String password) {
Serial.println("Username/Password: " + username + "/********");
return (username == MQTT_USERNAME && password == MQTT_PASSWORD);
}
virtual void onData(String topic, const char *data, uint32_t length) {
char data_str[length + 1];
os_memcpy(data_str, data, length);
data_str[length] = '\0';
Serial.println("received topic '" + topic + "' with data '" + String(data_str) + "'");
}
};
myMQTTBroker myBroker;
void startWiFiClient() {
Serial.println("Connecting to " + String(WIFI_NETWORK_NAME));
WiFi.begin(WIFI_NETWORK_NAME, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: " + WiFi.localIP().toString());
apMacAddress = WiFi.macAddress();
}
void startWiFiAP() {
WiFi.softAP(AP_NETWORK_NAME, AP_PASSWORD, 1, false, 8); // name, password, channel, hidden, max clients
Serial.println("AP started");
Serial.println("IP address: " + WiFi.softAPIP().toString());
}
void setup() {
Serial.begin(115200);
pinMode(0, OUTPUT); // Initialize GIO0 pin as an output (optional)
pinMode(2, INPUT); // Initialize GIO2 pin as an input (optional)
startWiFiClient();
startWiFiAP();
// Start the broker
Serial.println("Starting MQTT broker");
myBroker.init();
}
void loop() {
myBroker.publish("broker/free_heap", (String) ESP.getFreeHeap(), QOS, false); // topic, data, QoS, retain
myBroker.publish("broker/running_time", (String) millis(), QOS, false);
delay(5000);
}