Skip to content
This repository was archived by the owner on Jan 29, 2023. It is now read-only.

Commit 63ac506

Browse files
authored
Merge pull request #9 from PockyBum522/main
Added MQTT and OTA over Ethernet example to examples folder
2 parents ea16602 + 8b906ff commit 63ac506

File tree

1 file changed

+188
-0
lines changed

1 file changed

+188
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
/****************************************************************************************************************************
2+
MQTT_And_OTA_Ethernet.ino
3+
- Dead simple MQTT Client for Ethernet shields
4+
- Allows for new sketch compiled bin to be uploaded over HTTP using AsyncElegantOTA
5+
6+
Based on MQTTClient_Auth
7+
*****************************************************************************************************************************/
8+
9+
/*
10+
Basic MQTT example (without SSL!) with Authentication
11+
This sketch demonstrates the basic capabilities of the library.
12+
It connects to an MQTT server then:
13+
- providing username and password
14+
- publishes "hello world" to the topic "outTopic"
15+
- subscribes to the topic "inTopic", printing out any messages
16+
it receives. NB - it assumes the received payloads are strings not binary
17+
It will reconnect to the server if the connection is lost using a blocking
18+
reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
19+
achieve the same result without blocking the main loop.
20+
21+
To use OTA:
22+
- Take note of what IP the board is on, you should be able to see this both in the serial monitor and in the MQTT messages when the board first starts.
23+
- In the Arduino IDE, go to Sketch > Export compiled binary
24+
- You should now see a build folder next to the MQTT_And_OTA_Ethernet.ino file
25+
- Go into build\esp32.esp32.esp32 folder
26+
- The file you will be uploading to do an OTA update is MQTT_And_OTA_Ethernet.ino.bin in that folder
27+
- Go to http://192.168.X.X/update with a browser (whatever your board IP is that you noted earlier.)
28+
- Click "Choose file" and browse to the MQTT_And_OTA_Ethernet.ino.bin that you made earlier when you clicked Export compiled binary
29+
*/
30+
31+
#define DEBUG_ETHERNET_WEBSERVER_PORT Serial
32+
#define _ETHERNET_WEBSERVER_LOGLEVEL_ 3 // Debug Level from 0 to 4
33+
34+
#include <WebServer_WT32_ETH01.h> // https://github.com/khoih-prog/WebServer_WT32_ETH01/
35+
#include <AsyncTCP.h> // https://github.com/me-no-dev/AsyncTCP
36+
#include <ESPAsyncWebServer.h> // https://github.com/me-no-dev/ESPAsyncWebServer
37+
#include <AsyncElegantOTA.h> // https://github.com/ayushsharma82/AsyncElegantOTA
38+
39+
// Libraries also needed: https://github.com/knolleary/pubsubclient
40+
41+
AsyncWebServer server(80);
42+
43+
// Set according to your local network if you need static IP
44+
// IPAddress myIP(192, 168, 1, 232);
45+
// IPAddress myGW(192, 168, 1, 1);
46+
// IPAddress mySN(255, 255, 255, 0);
47+
// IPAddress myDNS(8, 8, 8, 8);
48+
49+
#include <PubSubClient.h>
50+
51+
// MQTT Settings
52+
const char *mqttServer = "192.168.1.25"; // Broker address
53+
const char *mqttBrokerUser = "YOUR_MQTT_USERNAME"; // Username to connect to your MQTT broker
54+
const char *mqttBrokerPass = "YOUR_MQTT_PASSWORD"; // Password to connect to your MQTT broker
55+
const char *ID = "MQTTClient_SSL-Client"; // Name of our device, must be unique
56+
const char *TOPIC = "topics/test/esp32"; // Topic to publish to
57+
const char *subTopic = "topics/MQTT_Sub"; // Topic to subcribe to
58+
59+
WiFiClient ethClient;
60+
61+
void setup()
62+
{
63+
Serial.begin(115200);
64+
while (!Serial);
65+
66+
// Using this if Serial debugging is not necessary or not using Serial port
67+
//while (!Serial && (millis() < 3000));
68+
69+
Serial.print("\nStarting MQTT_And_OTA_Ethernet on " + String(ARDUINO_BOARD));
70+
Serial.println(" with " + String(SHIELD_TYPE));
71+
Serial.println(WEBSERVER_WT32_ETH01_VERSION);
72+
73+
// To be called before ETH.begin()
74+
WT32_ETH01_onEvent();
75+
76+
ETH.begin(ETH_PHY_ADDR, ETH_PHY_POWER);
77+
78+
// Static IP, leave without this line to get IP via DHCP
79+
// ETH.config(myIP, myGW, mySN, myDNS);
80+
81+
WT32_ETH01_waitForConnect();
82+
83+
// Note - the default maximum packet size is 128 bytes. If the
84+
// combined length of clientId, username and password exceed this use the
85+
// following to increase the buffer size:
86+
// client.setBufferSize(255);
87+
88+
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
89+
request->send(200, "text/plain", "Hi! I am ESP32.");
90+
});
91+
92+
AsyncElegantOTA.begin(&server); // Start ElegantOTA
93+
server.begin();
94+
95+
Serial.println();
96+
Serial.println("HTTP server started with MAC: " + ETH.macAddress() + ", at IPv4: " + ETH.localIP().toString());
97+
Serial.println();
98+
}
99+
100+
void callback(char* topic, byte* payload, unsigned int length)
101+
{
102+
Serial.print("Message arrived [");
103+
Serial.print(topic);
104+
Serial.print("] ");
105+
106+
for (unsigned int i = 0; i < length; i++)
107+
{
108+
Serial.print((char)payload[i]);
109+
}
110+
111+
Serial.println();
112+
}
113+
114+
PubSubClient client(mqttServer, 1883, callback, ethClient);
115+
116+
void reconnect()
117+
{
118+
// Loop until we're reconnected
119+
while (!client.connected())
120+
{
121+
Serial.print("Attempting MQTT connection to ");
122+
Serial.print(mqttServer);
123+
124+
// Attempt to connect
125+
if (client.connect("arduino", mqttBrokerUser, mqttBrokerPass))
126+
{
127+
Serial.println("...connected");
128+
129+
// Once connected, publish an announcement...
130+
String data = "Hello from MQTTClient_SSL on " + String(BOARD_NAME) + ", at IPv4: " + ETH.localIP().toString();
131+
132+
client.publish(TOPIC, data.c_str());
133+
134+
//Serial.println("Published connection message successfully!");
135+
//Serial.print("Subcribed to: ");
136+
//Serial.println(subTopic);
137+
138+
// ... and resubscribe
139+
client.subscribe(subTopic);
140+
// for loopback testing
141+
client.subscribe(TOPIC);
142+
}
143+
else
144+
{
145+
Serial.print("...failed, rc=");
146+
Serial.print(client.state());
147+
Serial.println(" try again in 5 seconds");
148+
149+
// Wait 5 seconds before retrying
150+
delay(5000);
151+
}
152+
}
153+
}
154+
155+
#define MQTT_PUBLISH_INTERVAL_MS 5000L
156+
157+
unsigned long lastMsg = 0;
158+
159+
void loop()
160+
{
161+
String data = "Hello from v00 MQTT_And_OTA_Ethernet on: " + String(BOARD_NAME) + " with " + String(SHIELD_TYPE);
162+
const char *pubData = data.c_str();
163+
164+
static unsigned long now;
165+
166+
if (!client.connected())
167+
{
168+
reconnect();
169+
}
170+
171+
// Sending Data
172+
now = millis();
173+
174+
if (now - lastMsg > MQTT_PUBLISH_INTERVAL_MS)
175+
{
176+
lastMsg = now;
177+
178+
if (!client.publish(TOPIC, pubData))
179+
{
180+
Serial.println("Message failed to send.");
181+
}
182+
183+
Serial.print("Message Send : " + String(TOPIC) + " => ");
184+
Serial.println(data);
185+
}
186+
187+
client.loop();
188+
}

0 commit comments

Comments
 (0)