Skip to content

Commit

Permalink
Merge pull request #10 from plapointe6/dev
Browse files Browse the repository at this point in the history
1.4.1 to 1.5 changes
  • Loading branch information
Patrick Lapointe authored Apr 19, 2019
2 parents b03120d + 82ea130 commit cdffb57
Show file tree
Hide file tree
Showing 8 changed files with 370 additions and 103 deletions.
26 changes: 22 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
# MQTT and Wifi handling for ESP8266
# MQTT and Wifi handling for ESP8266 and ESP32

This library is intended to encapsulate the handling of WiFi and MQTT connections of an ESP8266.
This library is intended to encapsulate the handling of WiFi and MQTT connections of an ESP8266/ESP32.
You just need to provide your credentials and it will manage the following things:
- Connecting to a WiFi network.
- Connecting to a MQTT broker.
- Automatically detecting connection lost either from the WiFi client or the MQTT broker and it will retry a connection automatically.
- Subscrubing/unsubscrubing to/from MQTT topics by a friendly callback system.
- Provide a callback handling to advise once everything is connected (Wifi and MQTT).
- Provide a function to enable an HTTP Update server secured by a password to allow remote update.
- Provide a function to enable printing of usefull debug informations related to MQTT and Wifi connections.
- Provide some other useful utilities for MQTT and Wifi management.
- Provide a function to enable an HTTP Update server secured by a password to allow remote update.

## Dependency

Expand All @@ -21,6 +21,8 @@ From PubSubClient:
## Documentation

### Construction

For Wifi and MQTT connection handling (Recommended) :
```c++
EspMQTTClient(
const char* wifiSsid,
Expand All @@ -32,6 +34,16 @@ From PubSubClient:
const short mqttServerPort = 1883);
```
MQTT connection handling only :
```c++
EspMQTTClient(
const char* mqttServerIp,
const short mqttServerPort, // It is mandatory here to allow these constructors to be distinct from thoses with the Wifi handling parameters
const char* mqttUsername, // Omit this parameter to disable MQTT authentification
const char* mqttPassword, // Omit this parameter to disable MQTT authentification
const char* mqttClientName = "ESP8266");
```

### Functions

IMPORTANT : Must be called at each loop() of your sketch
Expand Down Expand Up @@ -85,6 +97,12 @@ void onConnectionEstablished()
}
```

In some special cases, like if you want to handle more than one MQTT connection in the same sketch, you can override this callback to another one for the second MQTT client using this function :
```c++
void setOnConnectionEstablishedCallback(ConnectionEstablishedCallback callback);
```
See exemple "twoMQTTClientHandling.ino" for more details.
## Example
```c++
Expand Down Expand Up @@ -115,4 +133,4 @@ void loop() {
}
```

See "Esp8266MQTTClient.ino" for the complete exemple.
See "SimpleMQTTClient.ino" for the complete exemple.
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
/*
SimpleMQTTClient.ino
The purpose of this exemple is to illustrate a simple handling of MQTT and Wifi connection.
Once it connects successfully to a Wifi network and a MQTT broker, it subscribe to a topic and send a message to it.
It will also send a message delayed 5 seconds later.
*/

#include "EspMQTTClient.h"

EspMQTTClient client(
Expand Down
61 changes: 61 additions & 0 deletions examples/twoMQTTClientHandling/twoMQTTClientHandling.ino
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
twoMQTTClientHandling.ino
The purpose of this exemple is to illustrate how to handle more than one MQTT connection a the same time in the same sketch.
Getting into "SimpleMQTTClient.ino" before this one is recommended (there is more comments)
*/

#include "EspMQTTClient.h"

void onConnectionEstablishedClient2();

// The client #1 will handle wifi connection (connecting, retrying, etc) and MQTT connection to 192.168.1.100
EspMQTTClient client1(
"WifiSSID",
"WifiPassword",
"192.168.1.100",
"MQTTUsername",
"MQTTPassword",
"TestClient1"
);

// The client #2 will handle MQTT connection to 192.168.1.101.
EspMQTTClient client2(
"192.168.1.101",
1883,
"MQTTUsername",
"MQTTPassword",
"TestClient2"
);

void setup()
{
Serial.begin(115200);

// We redirect the connection established callback of client2 to onConnectionEstablishedClient2.
// This will prevent the two client from calling the same callback (default to onConnectionEstablished)
client2.setOnConnectionEstablishedCallback(onConnectionEstablishedClient2);
}

// For client1
void onConnectionEstablished()
{
client1.subscribe("mytopic/test", [](const String & payload) {
Serial.println(payload);
});
client1.publish("mytopic/test", "This is a message from client1");
}

// For client2
void onConnectionEstablishedClient2()
{
client2.subscribe("mytopic/test", [](const String & payload) {
Serial.println(payload);
});
client2.publish("mytopic/test", "This is a message from client2");
}

void loop()
{
client1.loop();
client2.loop();
}
1 change: 1 addition & 0 deletions keywords.txt
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@ executeDelayed KEYWORD2
enableHTTPWebUpdater KEYWORD2
enableLastWillMessage KEYWORD2
enableDebuggingMessages KEYWORD2
setOnConnectionEstablishedCallback KEYWORD2

onConnectionEstablished KEYWORD2
6 changes: 3 additions & 3 deletions library.properties
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
name=EspMQTTClient
version=1.4
version=1.5
author=Patrick Lapointe <[email protected]>
maintainer=Patrick Lapointe <[email protected]>
sentence=A library that provides a wifi and MQTT connection to an ESP8266
paragraph=This library allow to connect and manage the connection to a wifi network and a MQTT broker. Also, it implement the secure HTTP updater. Intended to be used with an ESP8266. Dependecy : PubSubClient library
sentence=A library that provides a wifi and MQTT connection to an ESP8266/ESP32
paragraph=This library allow to connect and manage the connection to a wifi network and a MQTT broker. Intended to be used with an ESP8266 an ESP32. Dependecy : PubSubClient library
category=Communication
url=https://github.com/plapointe6/EspMQTTClient
architectures=*
103 changes: 103 additions & 0 deletions src/ESP32HTTPUpdateServer.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
#ifndef ESP32_HTTP_UPDATE_SERVER_H
#define ESP32_HTTP_UPDATE_SERVER_H

/*
Based on the HTTP update exemple of ESP32 core
*/

#include <WebServer.h>
#include <Update.h>

#define ESP32_WEB_UPDATE_HTML "<form method='POST' action='' enctype='multipart/form-data'><input type='file' name='update'><input type='submit' value='Update'></form>"
#define ESP32_WEB_UPDATE_SUCCESS_RESPONSE "<META http-equiv=\"refresh\" content=\"10;URL=/\">Update Success! Rebooting...\n"

class ESP32HTTPUpdateServer
{
private:
WebServer*_server;

char* _username;
char* _password;
bool _serialDebugging;

public:
ESP32HTTPUpdateServer(bool serialDebugging = false)
{
_server = NULL;
_username = "";
_password = "";
}

void setup(WebServer* server, char* path = "/", char* username = "", char* password = "")
{
_server = server;
_username = username;
_password = password;

// Get of the index handling
_server->on(path, HTTP_GET, [&]() {
// Force authentication if a user and password are defined
if (_username != "" && _password != "" && !_server->authenticate(_username, _password))
return _server->requestAuthentication();

_server->sendHeader("Connection", "close");
_server->send(200, "text/html", ESP32_WEB_UPDATE_HTML);
});

// Post of the file handling
_server->on(path, HTTP_POST, [&]() {
_server->client().setNoDelay(true);
_server->send_P(200, "text/html", (Update.hasError()) ? "FAIL" : ESP32_WEB_UPDATE_SUCCESS_RESPONSE);
delay(100);
_server->client().stop();
ESP.restart();
}, [&]() {
HTTPUpload& upload = _server->upload();

if (upload.status == UPLOAD_FILE_START)
{
// Check if we are authenticated
if (_username == "" || _password == "" || _server->authenticate(_username, _password))
{
if (_serialDebugging)
Serial.printf("Unauthenticated Update\n");

return;
}

// Debugging message for upload start
if (_serialDebugging)
{
Serial.setDebugOutput(true);
Serial.printf("Update: %s\n", upload.filename.c_str());
}

// Starting update
bool error = Update.begin();
if (_serialDebugging && error)
Update.printError(Serial);
}
else if (upload.status == UPLOAD_FILE_WRITE)
{
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize && _serialDebugging)
Update.printError(Serial);
}
else if (upload.status == UPLOAD_FILE_END)
{
if (Update.end(true) && _serialDebugging)
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
else if(_serialDebugging)
Update.printError(Serial);

if(_serialDebugging)
Serial.setDebugOutput(false);
}
else if(_serialDebugging)
Serial.printf("Update Failed Unexpectedly (likely broken connection): status=%d\n", upload.status);
});

_server->begin();
}
};

#endif
Loading

0 comments on commit cdffb57

Please sign in to comment.