Initial commit of Arduino libraries

This commit is contained in:
Sam
2025-05-23 10:47:41 +10:00
commit 5bfce5fc3e
2476 changed files with 1108481 additions and 0 deletions

View File

@@ -0,0 +1,79 @@
## Contributing to AsyncMQTT_ESP32
### Reporting Bugs
Please report bugs in [AsyncMQTT_ESP32](https://github.com/khoih-prog/AsyncMQTT_ESP32/issues/new) if you find them.
However, before reporting a bug please check through the following:
* [Existing Open Issues](https://github.com/khoih-prog/AsyncMQTT_ESP32/issues) - someone might have already encountered this.
If you don't find anything, please [open a new issue](https://github.com/khoih-prog/AsyncMQTT_ESP32/issues/new).
### How to submit a bug report
Please ensure to specify the following:
* Arduino IDE version (e.g. 1.8.19) or Platform.io version
* Board Type (e.g. ESP32_DEV, ESP32S3_DEV, ESP32S2_DEV, ESP32C3_DEV)
* Board Core Version (e.g. ESP32 core v2.0.6)
* Contextual information (e.g. what you were trying to achieve)
* Simplest possible steps to reproduce
* Anything that might be relevant in your opinion, such as:
* Operating system (Windows, Ubuntu, etc.) and the output of `uname -a`
* Network configuration
Please be educated, civilized and constructive as you've always been. Disrespective posts against [GitHub Code of Conduct](https://docs.github.com/en/site-policy/github-terms/github-event-code-of-conduct) will be ignored and deleted.
---
### Example
```
Arduino IDE version: 1.8.19
ESP32S3_DEV board
ESP32 core v2.0.6
OS: Ubuntu 20.04 LTS
Linux xy-Inspiron-3593 5.15.0-57-generic #63~20.04.1-Ubuntu SMP Wed Nov 30 13:40:16 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
Context:
I encountered a crash while using this library
Steps to reproduce:
1. ...
2. ...
3. ...
4. ...
```
---
### Sending Feature Requests
Feel free to post feature requests. It's helpful if you can explain exactly why the feature would be useful.
There are usually some outstanding feature requests in the [existing issues list](https://github.com/khoih-prog/AsyncMQTT_ESP32/issues?q=is%3Aopen+is%3Aissue+label%3Aenhancement), feel free to add comments to them.
---
### Sending Pull Requests
Pull Requests with changes and fixes are also welcome!
Please use the `astyle` to reformat the updated library code as follows (demo for Ubuntu Linux)
1. Change directory to the library GitHub
```
xy@xy-Inspiron-3593:~$ cd Arduino/xy/AsyncMQTT_ESP32_GitHub/
xy@xy-Inspiron-3593:~/Arduino/xy/AsyncMQTT_ESP32_GitHub$
```
2. Issue astyle command
```
xy@xy-Inspiron-3593:~/Arduino/xy/AsyncMQTT_ESP32_GitHub$ bash utils/restyle.sh
```

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 352 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 294 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 205 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 209 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

21
AsyncMQTT_ESP32/LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 Khoi Hoang
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

1189
AsyncMQTT_ESP32/README.md Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,39 @@
# AsyncMQTT_ESP32 Library
[![arduino-library-badge](https://www.ardu-badge.com/badge/AsyncMQTT_ESP32.svg?)](https://www.ardu-badge.com/AsyncMQTT_ESP32)
[![GitHub release](https://img.shields.io/github/release/khoih-prog/AsyncMQTT_ESP32.svg)](https://github.com/khoih-prog/AsyncMQTT_ESP32/releases)
[![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](#Contributing)
[![GitHub issues](https://img.shields.io/github/issues/khoih-prog/AsyncMQTT_ESP32.svg)](http://github.com/khoih-prog/AsyncMQTT_ESP32/issues)
<a href="https://www.buymeacoffee.com/khoihprog6" title="Donate to my libraries using BuyMeACoffee"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Donate to my libraries using BuyMeACoffee" style="height: 50px !important;width: 181px !important;" ></a>
<a href="https://www.buymeacoffee.com/khoihprog6" title="Donate to my libraries using BuyMeACoffee"><img src="https://img.shields.io/badge/buy%20me%20a%20coffee-donate-orange.svg?logo=buy-me-a-coffee&logoColor=FFDD00" style="height: 20px !important;width: 200px !important;" ></a>
---
---
## Table of Contents
* [Changelog](#changelog)
* [Releases v1.10.0](#releases-v1100)
* [Releases v1.9.0](#releases-v190)
* [Releases v1.8.0](#releases-v180)
---
---
## Changelog
### Releases v1.10.0
1. Add support to `ESP32` and `ESP32S2/S3/C3` boards using `LwIP W6100 Ethernet`
### Releases v1.9.0
1. Add support to `ESP32S2/C3` boards using `LwIP W5500 or ENC28J60 Ethernet`
### Releases v1.8.0
1. Initial coding to port [AsyncMQTT_Generic](https://github.com/khoih-prog/AsyncMQTT_Generic) to `ESP32/S2/S3/C3` boards using WiFi or `LwIP W5500 / ENC28J60 / LAN8720 Ethernet`
2. Use `allman astyle`
3. Sync with [AsyncMQTT_Generic v1.8.0](https://github.com/khoih-prog/AsyncMQTT_Generic)

View File

@@ -0,0 +1,28 @@
# Getting started
To use AsyncMqttClient, you need:
* An ESP8266 or ESP32
* The Arduino IDE or equivalent IDE for ESP8266/32
* Basic knowledge of the Arduino environment (use the IDE, upload a sketch, import libraries, ...)
## Installing AsyncMqttClient
There are two ways to install AsyncMqttClient.
### 1a. For the Arduino IDE
1. Download the [corresponding release](https://github.com/marvinroger/async-mqtt-client/releases/latest)
2. Load the `.zip` with **Sketch → Include Library → Add .ZIP Library**
AsyncMqttClient has 1 dependency:
* For ESP8266: [ESPAsyncTCP](https://github.com/me-no-dev/ESPAsyncTCP). Download the [.zip](https://github.com/me-no-dev/ESPAsyncTCP/archive/master.zip) and install it with the same method as above.
* Fors ESP32: [AsyncTCP](https://github.com/me-no-dev/AsyncTCP). Download the [.zip](https://github.com/me-no-dev/AsyncTCP/archive/master.zip) and install it with the same method as above.
## Fully-featured sketch
See [examples/FullyFeatured-ESP8266.ino](../examples/FullyFeatured-ESP8266/FullyFeatured-ESP8266.ino)
**<u>Very important:</u> As a rule of thumb, never use blocking functions in the callbacks (don't use `delay()` or `yield()`).** Otherwise, you may very probably experience unexpected behaviors.
You can go to the [API reference](2.-API-reference.md).

View File

@@ -0,0 +1,166 @@
# API reference
#### AsyncMqttClient()
Instantiate a new AsyncMqttClient object.
### Configuration
#### AsyncMqttClient& setKeepAlive(uint16_t `keepAlive`)
Set the keep alive. Defaults to 15 seconds.
* **`keepAlive`**: Keep alive in seconds
#### AsyncMqttClient& setClientId(const char\* `clientId`)
Set the client ID. Defaults to `esp8266<chip ID on 6 hex characters>`.
* **`clientId`**: Client ID
#### AsyncMqttClient& setCleanSession(bool `cleanSession`)
Whether or not to set the CleanSession flag. Defaults to `true`.
* **`cleanSession`**: clean session wanted or not
#### AsyncMqttClient& setMaxTopicLength(uint16_t `maxTopicLength`)
Set the maximum allowed topic length to receive. If an MQTT packet is received
with a topic longer than this maximum, the packet will be ignored. Defaults to `128`.
* **`maxTopicLength`**: Maximum allowed topic length to receive
#### AsyncMqttClient& setCredentials(const char\* `username`, const char\* `password` = nullptr)
Set the username/password. Defaults to non-auth.
* **`username`**: Username
* **`password`**: Password
#### AsyncMqttClient& setWill(const char\* `topic`, uint8_t `qos`, bool `retain`, const char\* `payload` = nullptr, size_t `length` = 0)
Set the Last Will Testament. Defaults to none.
* **`topic`**: Topic of the LWT
* **`qos`**: QoS of the LWT
* **`retain`**: Retain flag of the LWT
* **`payload`**: Payload of the LWT. If unset, the payload will be empty
* **`length`**: Payload length. If unset or set to 0, the payload will be considered as a string and its size will be calculated using `strlen(payload)`
#### AsyncMqttClient& setServer(IPAddress `ip`, uint16_t `port`)
Set the server.
* **`ip`**: IP of the server
* **`port`**: Port of the server
#### AsyncMqttClient& setServer(const char\* `host`, uint16_t `port`)
Set the server.
* **`host`**: Host of the server
* **`port`**: Port of the server
#### AsyncMqttClient& setSecure(bool `secure`)
Whether or not to use SSL. Defaults to `false`.
* **`secure`**: SSL wanted or not.
#### AsyncMqttClient& addServerFingerprint(const uint8_t\* `fingerprint`)
Adds an acceptable server fingerprint (SHA1). This may be called multiple times to permit any one of the specified fingerprints. By default, if no fingerprint is added, any fingerprint is accepted.
* **`fingerprint`**: Fingerprint to add
### Events handlers
#### AsyncMqttClient& onConnect(AsyncMqttClientInternals::OnConnectUserCallback `callback`)
Add a connect event handler.
* **`callback`**: Function to call
#### AsyncMqttClient& onDisconnect(AsyncMqttClientInternals::OnDisconnectUserCallback `callback`)
Add a disconnect event handler.
* **`callback`**: Function to call
#### AsyncMqttClient& onSubscribe(AsyncMqttClientInternals::OnSubscribeUserCallback `callback`)
Add a subscribe acknowledged event handler.
* **`callback`**: Function to call
#### AsyncMqttClient& onUnsubscribe(AsyncMqttClientInternals::OnUnsubscribeUserCallback `callback`)
Add an unsubscribe acknowledged event handler.
* **`callback`**: Function to call
#### AsyncMqttClient& onMessage(AsyncMqttClientInternals::OnMessageUserCallback `callback`)
Add a publish received event handler.
* **`callback`**: Function to call
#### AsyncMqttClient& onPublish(AsyncMqttClientInternals::OnPublishUserCallback `callback`)
Add a publish acknowledged event handler.
* **`callback`**: Function to call
### Operation functions
#### bool connected()
Return if the client is currently connected to the broker or not.
#### void connect()
Connect to the server.
#### void disconnect(bool `force` = false)
Disconnect from the server.
* **`force`**: Whether to force the disconnection. Defaults to `false` (clean disconnection).
#### uint16_t subscribe(const char\* `topic`, uint8_t `qos`)
Subscribe to the given topic at the given QoS.
Return the packet ID or 0 if failed.
* **`topic`**: Topic
* **`qos`**: QoS
#### uint16_t unsubscribe(const char\* `topic`)
Unsubscribe from the given topic.
Return the packet ID or 0 if failed.
* **`topic`**: Topic
#### uint16_t publish(const char\* `topic`, uint8_t `qos`, bool `retain`, const char\* `payload` = nullptr, size_t `length` = 0, bool dup = false, uint16_t message_id = 0)
Publish a packet.
Return the packet ID (or 1 if QoS 0) or 0 if failed.
* **`topic`**: Topic
* **`qos`**: QoS
* **`retain`**: Retain flag
* **`payload`**: Payload. If unset, the payload will be empty
* **`length`**: Payload length. If unset or set to 0, the payload will be considered as a string and its size will be calculated using `strlen(payload)`
* **`dup`**: ~~Duplicate flag. If set or set to 1, the payload will be flagged as a duplicate~~ Setting is not used anymore
* **`message_id`**: ~~The message ID. If unset or set to 0, the message ID will be automtaically assigned. Use this with the DUP flag to identify which message is being duplicated~~ Setting is not used anymore
#### bool clearQueue()
When disconnected, clears all queued messages
Returns true on success, false on failure (client is no disconnected)

View File

@@ -0,0 +1,12 @@
# Memory management
AsyncMqttClient buffers outgoing messages in a queue. On sending data is copied to a raw TCP buffer. Received data is passed directly to the API.
## Outgoing messages
You can send data as long as memory permits. A minimum amount of free memory is set at 4096 bytes. You can lower (or raise) this value by setting `MQTT_MIN_FREE_MEMORY` to your desired value.
If the free memory was sufficient to send your packet, the `publish` method will return a packet ID indicating the packet was queued. Otherwise, a `0` will be returned, and it's your responsibility to resend the packet with `publish`.
## Incoming messages
No incoming data is buffered by this library. Messages received by the TCP library is passed directly to the API. The max receive size is about 1460 bytes per call to your onMessage callback but the amount of data you can receive is unlimited. If you receive, say, a 300kB payload (such as an OTA payload), then your `onMessage` callback will be called about 200 times, with the according len, index and total parameters. Keep in mind the library will call your `onMessage` callbacks with the same topic buffer, so if you change the buffer on one call, the buffer will remain changed on subsequent calls.

View File

@@ -0,0 +1,19 @@
# Limitations and known issues
* The library is spec compliant with one limitation. In case of power loss the following is not honored:
> Must be kept in memory:
* All messages in a QoS 1 or 2 flow, which are not confirmed by the broker
* All received QoS 2 messages, which are not yet confirmed to the broker
This means retransmission is not honored in case of a power failure. This behaviour is like explained in point 4.1.1 of the MQTT specification v3.1.1
* You cannot send payload larger that what can fit on RAM.
## SSL limitations
* SSL requires the build flag -DASYNC_TCP_SSL_ENABLED=1
* SSL only supports fingerprints for server validation.
* If you do not specify one or more acceptable server fingerprints, the SSL connection will be vulnerable to man-in-the-middle attacks.
* Some server certificate signature algorithms do not work. SHA1, SHA224, SHA256, and MD5 are working. SHA384, and SHA512 will cause a crash.
* TLS1.2 is not supported.

View File

@@ -0,0 +1,11 @@
# Troubleshooting
* The payload of incoming messages contains **raw data**. You cannot just print out the data without formatting. This is because Arduino's `print` functions expect a C-string as input and a MQTT payload is not. A simple solution is to print each character of the payload:
```cpp
for (size_t i = 0; i < len; ++i) {
Serial.print(payload[i]);
}
```
Further reading: https://en.wikipedia.org/wiki/C_string_handling

View File

@@ -0,0 +1,4 @@
AsyncMqttClient documentation
=============================
See [index.md](index.md) to view it locally, or http://marvinroger.viewdocs.io/async-mqtt-client/ to view it online.

View File

@@ -0,0 +1,11 @@
Welcome to the AsyncMqttClient for ESP8266 docs.
**<p align="center">This documentation is only valid for the AsyncMqttClient version in this repo/directory</p>**
-----
#### 1. [Getting started](1.-Getting-started.md)
#### 2. [API reference](2.-API-reference.md)
#### 3. [Memory management](3.-Memory-management.md)
#### 4. [Limitations and known issues](4.-Limitations-and-known-issues.md)
#### 5. [Troubleshooting](5.-Troubleshooting.md)

View File

@@ -0,0 +1,262 @@
/****************************************************************************************************************************
FullyFeatureSSL_ESP32.ino
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
// Example project which can be built with SSL enabled or disabled.
// The espressif8266_stage platform must be installed.
// Refer to platformio.ini for the build configuration and platform installation.
#include "defines.h"
#include <WiFi.h>
extern "C"
{
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#define ASYNC_TCP_SSL_ENABLED true
//#define ASYNC_TCP_SSL_ENABLED false
#include <AsyncMQTT_ESP32.h>
//#define MQTT_HOST IPAddress(192, 168, 2, 110)
#define MQTT_HOST "broker.emqx.io" // Broker address
#if ASYNC_TCP_SSL_ENABLED
#define MQTT_SECURE true
const uint8_t MQTT_SERVER_FINGERPRINT[] = {0x7e, 0x36, 0x22, 0x01, 0xf9, 0x7e, 0x99, 0x2f, 0xc5, 0xdb, 0x3d, 0xbe, 0xac, 0x48, 0x67, 0x5b, 0x5d, 0x47, 0x94, 0xd2};
const char *PubTopic = "async-mqtt/ESP32_SSL_Pub"; // Topic to publish
#define MQTT_PORT 8883
#else
const char *PubTopic = "async-mqtt/ESP32_Pub"; // Topic to publish
#define MQTT_PORT 1883
#endif
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;
void connectToWifi()
{
Serial.println("Connecting to Wi-Fi...");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
void connectToMqtt()
{
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void WiFiEvent(WiFiEvent_t event)
{
switch (event)
{
#if USING_CORE_ESP32_CORE_V200_PLUS
case ARDUINO_EVENT_WIFI_READY:
Serial.println("WiFi ready");
break;
case ARDUINO_EVENT_WIFI_STA_START:
Serial.println("WiFi STA starting");
break;
case ARDUINO_EVENT_WIFI_STA_CONNECTED:
Serial.println("WiFi STA connected");
break;
case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_WIFI_STA_LOST_IP:
Serial.println("WiFi lost IP");
break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
xTimerStart(wifiReconnectTimer, 0);
break;
#else
case SYSTEM_EVENT_STA_GOT_IP:
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
xTimerStart(wifiReconnectTimer, 0);
break;
#endif
default:
break;
}
}
void printSeparationLine()
{
Serial.println("************************************************");
}
void onMqttConnect(bool sessionPresent)
{
Serial.print("Connected to MQTT broker: ");
Serial.print(MQTT_HOST);
Serial.print(", port: ");
Serial.println(MQTT_PORT);
Serial.print("PubTopic: ");
Serial.println(PubTopic);
printSeparationLine();
Serial.print("Session present: ");
Serial.println(sessionPresent);
uint16_t packetIdSub = mqttClient.subscribe(PubTopic, 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);
mqttClient.publish(PubTopic, 0, true, "ESP32 Test");
Serial.println("Publishing at QoS 0");
uint16_t packetIdPub1 = mqttClient.publish(PubTopic, 1, true, "test 2");
Serial.print("Publishing at QoS 1, packetId: ");
Serial.println(packetIdPub1);
uint16_t packetIdPub2 = mqttClient.publish(PubTopic, 2, true, "test 3");
Serial.print("Publishing at QoS 2, packetId: ");
Serial.println(packetIdPub2);
printSeparationLine();
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason)
{
(void) reason;
Serial.println("Disconnected from MQTT.");
if (WiFi.isConnected())
{
xTimerStart(mqttReconnectTimer, 0);
}
}
void onMqttSubscribe(const uint16_t& packetId, const uint8_t& qos)
{
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(const uint16_t& packetId)
{
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void onMqttMessage(char* topic, char* payload, const AsyncMqttClientMessageProperties& properties,
const size_t& len, const size_t& index, const size_t& total)
{
(void) payload;
Serial.println("Publish received.");
Serial.print(" topic: ");
Serial.println(topic);
Serial.print(" qos: ");
Serial.println(properties.qos);
Serial.print(" dup: ");
Serial.println(properties.dup);
Serial.print(" retain: ");
Serial.println(properties.retain);
Serial.print(" len: ");
Serial.println(len);
Serial.print(" index: ");
Serial.println(index);
Serial.print(" total: ");
Serial.println(total);
}
void onMqttPublish(const uint16_t& packetId)
{
Serial.println("Publish acknowledged");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
delay(500);
Serial.print("\nStarting FullyFeatureSSL_ESP32 on ");
Serial.println(ARDUINO_BOARD);
Serial.println(ASYNC_MQTT_ESP32_VERSION);
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0,
reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0,
reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));
WiFi.onEvent(WiFiEvent);
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
#if ASYNC_TCP_SSL_ENABLED
mqttClient.setSecure(MQTT_SECURE);
if (MQTT_SECURE)
{
//mqttClient.addServerFingerprint((const uint8_t[])MQTT_SERVER_FINGERPRINT);
mqttClient.addServerFingerprint((const uint8_t *)MQTT_SERVER_FINGERPRINT);
}
#endif
connectToWifi();
}
void loop()
{
}

View File

@@ -0,0 +1,21 @@
/****************************************************************************************************************************
defines.h
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
***************************************************************************************************************************************/
#ifndef defines_h
#define defines_h
#define _ASYNC_MQTT_LOGLEVEL_ 1
#define WIFI_SSID "yourSSID"
#define WIFI_PASSWORD "yourpass"
#endif //defines_h

View File

@@ -0,0 +1,232 @@
/****************************************************************************************************************************
FullyFeature_ESP32.ino
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
/*
This example uses FreeRTOS softwaretimers as there is no built-in Ticker library
*/
#include "defines.h"
#include <WiFi.h>
extern "C"
{
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#include <AsyncMQTT_ESP32.h>
//#define MQTT_HOST IPAddress(192, 168, 2, 110)
#define MQTT_HOST "broker.emqx.io" // Broker address
#define MQTT_PORT 1883
const char *PubTopic = "async-mqtt/ESP32_Pub"; // Topic to publish
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;
void connectToWifi()
{
Serial.println("Connecting to Wi-Fi...");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
void connectToMqtt()
{
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void WiFiEvent(WiFiEvent_t event)
{
switch (event)
{
#if USING_CORE_ESP32_CORE_V200_PLUS
case ARDUINO_EVENT_WIFI_READY:
Serial.println("WiFi ready");
break;
case ARDUINO_EVENT_WIFI_STA_START:
Serial.println("WiFi STA starting");
break;
case ARDUINO_EVENT_WIFI_STA_CONNECTED:
Serial.println("WiFi STA connected");
break;
case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_WIFI_STA_LOST_IP:
Serial.println("WiFi lost IP");
break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
xTimerStart(wifiReconnectTimer, 0);
break;
#else
case SYSTEM_EVENT_STA_GOT_IP:
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
xTimerStart(wifiReconnectTimer, 0);
break;
#endif
default:
break;
}
}
void printSeparationLine()
{
Serial.println("************************************************");
}
void onMqttConnect(bool sessionPresent)
{
Serial.print("Connected to MQTT broker: ");
Serial.print(MQTT_HOST);
Serial.print(", port: ");
Serial.println(MQTT_PORT);
Serial.print("PubTopic: ");
Serial.println(PubTopic);
printSeparationLine();
Serial.print("Session present: ");
Serial.println(sessionPresent);
uint16_t packetIdSub = mqttClient.subscribe(PubTopic, 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);
mqttClient.publish(PubTopic, 0, true, "ESP32 Test");
Serial.println("Publishing at QoS 0");
uint16_t packetIdPub1 = mqttClient.publish(PubTopic, 1, true, "test 2");
Serial.print("Publishing at QoS 1, packetId: ");
Serial.println(packetIdPub1);
uint16_t packetIdPub2 = mqttClient.publish(PubTopic, 2, true, "test 3");
Serial.print("Publishing at QoS 2, packetId: ");
Serial.println(packetIdPub2);
printSeparationLine();
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason)
{
(void) reason;
Serial.println("Disconnected from MQTT.");
if (WiFi.isConnected())
{
xTimerStart(mqttReconnectTimer, 0);
}
}
void onMqttSubscribe(const uint16_t& packetId, const uint8_t& qos)
{
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(const uint16_t& packetId)
{
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void onMqttMessage(char* topic, char* payload, const AsyncMqttClientMessageProperties& properties,
const size_t& len, const size_t& index, const size_t& total)
{
(void) payload;
Serial.println("Publish received.");
Serial.print(" topic: ");
Serial.println(topic);
Serial.print(" qos: ");
Serial.println(properties.qos);
Serial.print(" dup: ");
Serial.println(properties.dup);
Serial.print(" retain: ");
Serial.println(properties.retain);
Serial.print(" len: ");
Serial.println(len);
Serial.print(" index: ");
Serial.println(index);
Serial.print(" total: ");
Serial.println(total);
}
void onMqttPublish(const uint16_t& packetId)
{
Serial.println("Publish acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
delay(500);
Serial.print("\nStarting FullyFeature_ESP32 on ");
Serial.println(ARDUINO_BOARD);
Serial.println(ASYNC_MQTT_ESP32_VERSION);
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0,
reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0,
reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));
WiFi.onEvent(WiFiEvent);
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
connectToWifi();
}
void loop()
{
}

View File

@@ -0,0 +1,21 @@
/****************************************************************************************************************************
defines.h
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
***************************************************************************************************************************************/
#ifndef defines_h
#define defines_h
#define _ASYNC_MQTT_LOGLEVEL_ 1
#define WIFI_SSID "yourSSID"
#define WIFI_PASSWORD "yourpass"
#endif //defines_h

View File

@@ -0,0 +1,280 @@
/****************************************************************************************************************************
FullyFeatureSSL_ESP32_ENC.ino
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "defines.h"
extern "C"
{
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#define ASYNC_TCP_SSL_ENABLED true
//#define ASYNC_TCP_SSL_ENABLED false
#include <AsyncMQTT_ESP32.h>
//#define MQTT_HOST IPAddress(192, 168, 2, 110)
#define MQTT_HOST "broker.emqx.io" // Broker address
#if ASYNC_TCP_SSL_ENABLED
#define MQTT_SECURE true
const uint8_t MQTT_SERVER_FINGERPRINT[] = {0x7e, 0x36, 0x22, 0x01, 0xf9, 0x7e, 0x99, 0x2f, 0xc5, 0xdb, 0x3d, 0xbe, 0xac, 0x48, 0x67, 0x5b, 0x5d, 0x47, 0x94, 0xd2};
const char *PubTopic = "async-mqtt/ESP32_ENC_SSL_Pub"; // Topic to publish
#define MQTT_PORT 8883
#else
const char *PubTopic = "async-mqtt/ESP32_ENC_Pub"; // Topic to publish
#define MQTT_PORT 1883
#endif
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
void connectToMqtt()
{
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void ETH_event(WiFiEvent_t event)
{
switch (event)
{
#if USING_CORE_ESP32_CORE_V200_PLUS
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH starting");
break;
case ARDUINO_EVENT_ETH_CONNECTED:
Serial.println("ETH connected");
break;
case ARDUINO_EVENT_ETH_GOT_IP:
Serial.println("ETH got IP");
Serial.print("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH stops");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#else
case SYSTEM_EVENT_ETH_CONNECTED:
erial.println(F("ETH Connected"));
break;
case SYSTEM_EVENT_ETH_GOT_IP:
Serial.println("ETH connected");
Serial.println("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_ETH_DISCONNECTED:
case SYSTEM_EVENT_ETH_STOP:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#endif
default:
break;
}
}
void printSeparationLine()
{
Serial.println("************************************************");
}
void onMqttConnect(bool sessionPresent)
{
Serial.print("Connected to MQTT broker: ");
Serial.print(MQTT_HOST);
Serial.print(", port: ");
Serial.println(MQTT_PORT);
Serial.print("PubTopic: ");
Serial.println(PubTopic);
printSeparationLine();
Serial.print("Session present: ");
Serial.println(sessionPresent);
uint16_t packetIdSub = mqttClient.subscribe(PubTopic, 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);
mqttClient.publish(PubTopic, 0, true, "ESP32_ENC Test");
Serial.println("Publishing at QoS 0");
uint16_t packetIdPub1 = mqttClient.publish(PubTopic, 1, true, "test 2");
Serial.print("Publishing at QoS 1, packetId: ");
Serial.println(packetIdPub1);
uint16_t packetIdPub2 = mqttClient.publish(PubTopic, 2, true, "test 3");
Serial.print("Publishing at QoS 2, packetId: ");
Serial.println(packetIdPub2);
printSeparationLine();
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason)
{
(void) reason;
Serial.println("Disconnected from MQTT.");
if (ESP32_ENC_isConnected())
{
xTimerStart(mqttReconnectTimer, 0);
}
}
void onMqttSubscribe(const uint16_t& packetId, const uint8_t& qos)
{
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(const uint16_t& packetId)
{
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void onMqttMessage(char* topic, char* payload, const AsyncMqttClientMessageProperties& properties,
const size_t& len, const size_t& index, const size_t& total)
{
(void) payload;
Serial.println("Publish received.");
Serial.print(" topic: ");
Serial.println(topic);
Serial.print(" qos: ");
Serial.println(properties.qos);
Serial.print(" dup: ");
Serial.println(properties.dup);
Serial.print(" retain: ");
Serial.println(properties.retain);
Serial.print(" len: ");
Serial.println(len);
Serial.print(" index: ");
Serial.println(index);
Serial.print(" total: ");
Serial.println(total);
}
void onMqttPublish(const uint16_t& packetId)
{
Serial.println("Publish acknowledged");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
Serial.print("\nStarting FullyFeatureSSL_ESP32_ENC on ");
Serial.print(ARDUINO_BOARD);
Serial.println(" with " + String(SHIELD_TYPE));
Serial.println(WEBSERVER_ESP32_ENC_VERSION);
Serial.println(ASYNC_MQTT_ESP32_VERSION);
AMQTT_LOGWARN(F("Default SPI pinout:"));
AMQTT_LOGWARN1(F("MOSI:"), MOSI_GPIO);
AMQTT_LOGWARN1(F("MISO:"), MISO_GPIO);
AMQTT_LOGWARN1(F("SCK:"), SCK_GPIO);
AMQTT_LOGWARN1(F("CS:"), CS_GPIO);
AMQTT_LOGWARN1(F("INT:"), INT_GPIO);
AMQTT_LOGWARN1(F("SPI Clock (MHz):"), SPI_CLOCK_MHZ);
AMQTT_LOGWARN(F("========================="));
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0,
reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
#if ASYNC_TCP_SSL_ENABLED
mqttClient.setSecure(MQTT_SECURE);
if (MQTT_SECURE)
{
//mqttClient.addServerFingerprint((const uint8_t[])MQTT_SERVER_FINGERPRINT);
mqttClient.addServerFingerprint((const uint8_t *)MQTT_SERVER_FINGERPRINT);
}
#endif
///////////////////////////////////
// To be called before ETH.begin()
WiFi.onEvent(ETH_event);
// start the ethernet connection and the server:
// Use DHCP dynamic IP and random mac
//bool begin(int MISO_GPIO, int MOSI_GPIO, int SCLK_GPIO, int CS_GPIO, int INT_GPIO, int SPI_CLOCK_MHZ,
// int SPI_HOST, uint8_t *ENC28J60_Mac = ENC28J60_Default_Mac);
//ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, SPI_HOST );
ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, SPI_HOST, mac[millis() % NUMBER_OF_MAC] );
// Static IP, leave without this line to get IP via DHCP
//bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0);
//ETH.config(myIP, myGW, mySN, myDNS);
ESP32_ENC_waitForConnect();
///////////////////////////////////
}
void loop()
{
}

View File

@@ -0,0 +1,75 @@
/****************************************************************************************************************************
defines.h
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
***************************************************************************************************************************************/
#ifndef defines_h
#define defines_h
// Debug Level from 0 to 4
#define _ETHERNET_WEBSERVER_LOGLEVEL_ 1
#define _ASYNC_MQTT_LOGLEVEL_ 1
/////////////////////////////////////////////
// Optional values to override default settings
//#define SPI_HOST 1
//#define SPI_CLOCK_MHZ 8
// Must connect INT to GPIOxx or not working
//#define INT_GPIO 4
//#define MISO_GPIO 19
//#define MOSI_GPIO 23
//#define SCK_GPIO 18
//#define CS_GPIO 5
/////////////////////////////////////////////
#include <WebServer_ESP32_ENC.h> // https://github.com/khoih-prog/WebServer_ESP32_ENC
/////////////////////////////////////////////
// Enter a MAC address and IP address for your controller below.
#define NUMBER_OF_MAC 20
byte mac[][NUMBER_OF_MAC] =
{
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x01 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x02 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x03 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x04 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x05 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x06 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x07 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x08 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x09 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0A },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0B },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0C },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0D },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0E },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0F },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x10 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x11 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x12 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x13 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x14 },
};
// Select the IP address according to your local network
IPAddress myIP(192, 168, 2, 232);
IPAddress myGW(192, 168, 2, 1);
IPAddress mySN(255, 255, 255, 0);
// Google DNS Server IP
IPAddress myDNS(8, 8, 8, 8);
#endif //defines_h

View File

@@ -0,0 +1,257 @@
/****************************************************************************************************************************
FullyFeature-ESP32_ENC.ino
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
/*
This example uses FreeRTOS softwaretimers as there is no built-in Ticker library
*/
#include "defines.h"
extern "C"
{
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#include <AsyncMQTT_ESP32.h>
//#define MQTT_HOST IPAddress(192, 168, 2, 110)
#define MQTT_HOST "broker.emqx.io" // Broker address
#define MQTT_PORT 1883
const char *PubTopic = "async-mqtt/ESP32_ENC_Pub"; // Topic to publish
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
void connectToMqtt()
{
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void ETH_event(WiFiEvent_t event)
{
switch (event)
{
#if USING_CORE_ESP32_CORE_V200_PLUS
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH starting");
break;
case ARDUINO_EVENT_ETH_CONNECTED:
Serial.println("ETH connected");
break;
case ARDUINO_EVENT_ETH_GOT_IP:
Serial.println("ETH got IP");
Serial.print("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH stops");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#else
case SYSTEM_EVENT_ETH_CONNECTED:
erial.println(F("ETH Connected"));
break;
case SYSTEM_EVENT_ETH_GOT_IP:
Serial.println("ETH connected");
Serial.println("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_ETH_DISCONNECTED:
case SYSTEM_EVENT_ETH_STOP:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#endif
default:
break;
}
}
void printSeparationLine()
{
Serial.println("************************************************");
}
void onMqttConnect(bool sessionPresent)
{
Serial.print("Connected to MQTT broker: ");
Serial.print(MQTT_HOST);
Serial.print(", port: ");
Serial.println(MQTT_PORT);
Serial.print("PubTopic: ");
Serial.println(PubTopic);
printSeparationLine();
Serial.print("Session present: ");
Serial.println(sessionPresent);
uint16_t packetIdSub = mqttClient.subscribe(PubTopic, 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);
mqttClient.publish(PubTopic, 0, true, "ESP32_ENC Test");
Serial.println("Publishing at QoS 0");
uint16_t packetIdPub1 = mqttClient.publish(PubTopic, 1, true, "test 2");
Serial.print("Publishing at QoS 1, packetId: ");
Serial.println(packetIdPub1);
uint16_t packetIdPub2 = mqttClient.publish(PubTopic, 2, true, "test 3");
Serial.print("Publishing at QoS 2, packetId: ");
Serial.println(packetIdPub2);
printSeparationLine();
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason)
{
(void) reason;
Serial.println("Disconnected from MQTT.");
if (ESP32_ENC_isConnected())
{
xTimerStart(mqttReconnectTimer, 0);
}
}
void onMqttSubscribe(const uint16_t& packetId, const uint8_t& qos)
{
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(const uint16_t& packetId)
{
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void onMqttMessage(char* topic, char* payload, const AsyncMqttClientMessageProperties& properties,
const size_t& len, const size_t& index, const size_t& total)
{
(void) payload;
Serial.println("Publish received.");
Serial.print(" topic: ");
Serial.println(topic);
Serial.print(" qos: ");
Serial.println(properties.qos);
Serial.print(" dup: ");
Serial.println(properties.dup);
Serial.print(" retain: ");
Serial.println(properties.retain);
Serial.print(" len: ");
Serial.println(len);
Serial.print(" index: ");
Serial.println(index);
Serial.print(" total: ");
Serial.println(total);
}
void onMqttPublish(const uint16_t& packetId)
{
Serial.println("Publish acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
delay(500);
Serial.print("\nStarting FullyFeature_ESP32_ENC on ");
Serial.print(ARDUINO_BOARD);
Serial.println(" with " + String(SHIELD_TYPE));
Serial.println(WEBSERVER_ESP32_ENC_VERSION);
Serial.println(ASYNC_MQTT_ESP32_VERSION);
AMQTT_LOGWARN(F("Default SPI pinout:"));
AMQTT_LOGWARN1(F("MOSI:"), MOSI_GPIO);
AMQTT_LOGWARN1(F("MISO:"), MISO_GPIO);
AMQTT_LOGWARN1(F("SCK:"), SCK_GPIO);
AMQTT_LOGWARN1(F("CS:"), CS_GPIO);
AMQTT_LOGWARN1(F("INT:"), INT_GPIO);
AMQTT_LOGWARN1(F("SPI Clock (MHz):"), SPI_CLOCK_MHZ);
AMQTT_LOGWARN(F("========================="));
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0,
reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
///////////////////////////////////
// To be called before ETH.begin()
WiFi.onEvent(ETH_event);
// start the ethernet connection and the server:
// Use DHCP dynamic IP and random mac
//bool begin(int MISO_GPIO, int MOSI_GPIO, int SCLK_GPIO, int CS_GPIO, int INT_GPIO, int SPI_CLOCK_MHZ,
// int SPI_HOST, uint8_t *ENC28J60_Mac = ENC28J60_Default_Mac);
//ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, SPI_HOST );
ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, SPI_HOST, mac[millis() % NUMBER_OF_MAC] );
// Static IP, leave without this line to get IP via DHCP
//bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0);
//ETH.config(myIP, myGW, mySN, myDNS);
ESP32_ENC_waitForConnect();
///////////////////////////////////
}
void loop()
{
}

View File

@@ -0,0 +1,75 @@
/****************************************************************************************************************************
defines.h
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
***************************************************************************************************************************************/
#ifndef defines_h
#define defines_h
// Debug Level from 0 to 4
#define _ETHERNET_WEBSERVER_LOGLEVEL_ 1
#define _ASYNC_MQTT_LOGLEVEL_ 1
/////////////////////////////////////////////
// Optional values to override default settings
//#define SPI_HOST 1
//#define SPI_CLOCK_MHZ 8
// Must connect INT to GPIOxx or not working
//#define INT_GPIO 4
//#define MISO_GPIO 19
//#define MOSI_GPIO 23
//#define SCK_GPIO 18
//#define CS_GPIO 5
/////////////////////////////////////////////
#include <WebServer_ESP32_ENC.h> // https://github.com/khoih-prog/WebServer_ESP32_ENC
/////////////////////////////////////////////
// Enter a MAC address and IP address for your controller below.
#define NUMBER_OF_MAC 20
byte mac[][NUMBER_OF_MAC] =
{
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x01 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x02 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x03 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x04 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x05 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x06 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x07 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x08 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x09 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0A },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0B },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0C },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0D },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0E },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0F },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x10 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x11 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x12 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x13 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x14 },
};
// Select the IP address according to your local network
IPAddress myIP(192, 168, 2, 232);
IPAddress myGW(192, 168, 2, 1);
IPAddress mySN(255, 255, 255, 0);
// Google DNS Server IP
IPAddress myDNS(8, 8, 8, 8);
#endif //defines_h

View File

@@ -0,0 +1,283 @@
/****************************************************************************************************************************
FullyFeatureSSL_ESP32_SC_ENC.ino
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "defines.h"
extern "C"
{
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#define ASYNC_TCP_SSL_ENABLED true
//#define ASYNC_TCP_SSL_ENABLED false
#include <AsyncMQTT_ESP32.h>
//#define MQTT_HOST IPAddress(192, 168, 2, 110)
#define MQTT_HOST "broker.emqx.io" // Broker address
#if ASYNC_TCP_SSL_ENABLED
#define MQTT_SECURE true
const uint8_t MQTT_SERVER_FINGERPRINT[] = {0x7e, 0x36, 0x22, 0x01, 0xf9, 0x7e, 0x99, 0x2f, 0xc5, 0xdb, 0x3d, 0xbe, 0xac, 0x48, 0x67, 0x5b, 0x5d, 0x47, 0x94, 0xd2};
const char *PubTopic = "async-mqtt/ESP32_SC_ENC_SSL_Pub"; // Topic to publish
#define MQTT_PORT 8883
#else
const char *PubTopic = "async-mqtt/ESP32_SC_ENC_Pub"; // Topic to publish
#define MQTT_PORT 1883
#endif
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
void connectToMqtt()
{
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void ETH_event(WiFiEvent_t event)
{
switch (event)
{
#if USING_CORE_ESP32_CORE_V200_PLUS
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH starting");
break;
case ARDUINO_EVENT_ETH_CONNECTED:
Serial.println("ETH connected");
break;
case ARDUINO_EVENT_ETH_GOT_IP:
Serial.println("ETH got IP");
Serial.print("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH stops");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#else
case SYSTEM_EVENT_ETH_CONNECTED:
erial.println(F("ETH Connected"));
break;
case SYSTEM_EVENT_ETH_GOT_IP:
Serial.println("ETH connected");
Serial.println("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_ETH_DISCONNECTED:
case SYSTEM_EVENT_ETH_STOP:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#endif
default:
break;
}
}
void printSeparationLine()
{
Serial.println("************************************************");
}
void onMqttConnect(bool sessionPresent)
{
Serial.print("Connected to MQTT broker: ");
Serial.print(MQTT_HOST);
Serial.print(", port: ");
Serial.println(MQTT_PORT);
Serial.print("PubTopic: ");
Serial.println(PubTopic);
printSeparationLine();
Serial.print("Session present: ");
Serial.println(sessionPresent);
uint16_t packetIdSub = mqttClient.subscribe(PubTopic, 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);
mqttClient.publish(PubTopic, 0, true, "ESP32_SC_ENC Test");
Serial.println("Publishing at QoS 0");
uint16_t packetIdPub1 = mqttClient.publish(PubTopic, 1, true, "test 2");
Serial.print("Publishing at QoS 1, packetId: ");
Serial.println(packetIdPub1);
uint16_t packetIdPub2 = mqttClient.publish(PubTopic, 2, true, "test 3");
Serial.print("Publishing at QoS 2, packetId: ");
Serial.println(packetIdPub2);
printSeparationLine();
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason)
{
(void) reason;
Serial.println("Disconnected from MQTT.");
if (ESP32_ENC_isConnected())
{
xTimerStart(mqttReconnectTimer, 0);
}
}
void onMqttSubscribe(const uint16_t& packetId, const uint8_t& qos)
{
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(const uint16_t& packetId)
{
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void onMqttMessage(char* topic, char* payload, const AsyncMqttClientMessageProperties& properties,
const size_t& len, const size_t& index, const size_t& total)
{
(void) payload;
Serial.println("Publish received.");
Serial.print(" topic: ");
Serial.println(topic);
Serial.print(" qos: ");
Serial.println(properties.qos);
Serial.print(" dup: ");
Serial.println(properties.dup);
Serial.print(" retain: ");
Serial.println(properties.retain);
Serial.print(" len: ");
Serial.println(len);
Serial.print(" index: ");
Serial.println(index);
Serial.print(" total: ");
Serial.println(total);
}
void onMqttPublish(const uint16_t& packetId)
{
Serial.println("Publish acknowledged");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
delay(500);
Serial.print("\nStarting FullyFeatureSSL_ESP32_SC_ENC on ");
Serial.print(ARDUINO_BOARD);
Serial.println(" with " + String(SHIELD_TYPE));
Serial.println(WEBSERVER_ESP32_SC_ENC_VERSION);
Serial.println(ASYNC_MQTT_ESP32_VERSION);
AMQTT_LOGWARN(F("Default SPI pinout:"));
AMQTT_LOGWARN1(F("SPI_HOST:"), ETH_SPI_HOST);
AMQTT_LOGWARN1(F("MOSI:"), MOSI_GPIO);
AMQTT_LOGWARN1(F("MISO:"), MISO_GPIO);
AMQTT_LOGWARN1(F("SCK:"), SCK_GPIO);
AMQTT_LOGWARN1(F("CS:"), CS_GPIO);
AMQTT_LOGWARN1(F("INT:"), INT_GPIO);
AMQTT_LOGWARN1(F("SPI Clock (MHz):"), SPI_CLOCK_MHZ);
AMQTT_LOGWARN(F("========================="));
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0,
reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
#if ASYNC_TCP_SSL_ENABLED
mqttClient.setSecure(MQTT_SECURE);
if (MQTT_SECURE)
{
//mqttClient.addServerFingerprint((const uint8_t[])MQTT_SERVER_FINGERPRINT);
mqttClient.addServerFingerprint((const uint8_t *)MQTT_SERVER_FINGERPRINT);
}
#endif
///////////////////////////////////
// To be called before ETH.begin()
WiFi.onEvent(ETH_event);
// start the ethernet connection and the server:
// Use DHCP dynamic IP and random mac
//bool begin(int MISO_GPIO, int MOSI_GPIO, int SCLK_GPIO, int CS_GPIO, int INT_GPIO, int SPI_CLOCK_MHZ,
// int SPI_HOST, uint8_t *ENC28J60_Mac = ENC28J60_Default_Mac);
//ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST );
ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST, mac[millis() % NUMBER_OF_MAC] );
// Static IP, leave without this line to get IP via DHCP
//bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0);
//ETH.config(myIP, myGW, mySN, myDNS);
ESP32_ENC_waitForConnect();
///////////////////////////////////
}
void loop()
{
}

View File

@@ -0,0 +1,90 @@
/****************************************************************************************************************************
defines.h
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
***************************************************************************************************************************************/
#ifndef defines_h
#define defines_h
// Debug Level from 0 to 4
#define _ETHERNET_WEBSERVER_LOGLEVEL_ 1
#define _ASYNC_MQTT_LOGLEVEL_ 1
/////////////////////////////////////////////
// For ESP32-S3
// Optional values to override default settings
//#define ETH_SPI_HOST SPI2_HOST
//#define SPI_CLOCK_MHZ 8
// Must connect INT to GPIOxx or not working
//#define INT_GPIO 4
//#define MISO_GPIO 13
//#define MOSI_GPIO 11
//#define SCK_GPIO 12
//#define CS_GPIO 10
// For ESP32_C3
// Optional values to override default settings
// Don't change unless you know what you're doing
//#define ETH_SPI_HOST SPI2_HOST
//#define SPI_CLOCK_MHZ 8
// Must connect INT to GPIOxx or not working
//#define INT_GPIO 10
//#define MISO_GPIO 5
//#define MOSI_GPIO 6
//#define SCK_GPIO 4
//#define CS_GPIO 7
/////////////////////////////////////////////
#include <WebServer_ESP32_SC_ENC.h> // https://github.com/khoih-prog/WebServer_ESP32_SC_ENC
/////////////////////////////////////////////
// Enter a MAC address and IP address for your controller below.
#define NUMBER_OF_MAC 20
byte mac[][NUMBER_OF_MAC] =
{
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x01 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x02 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x03 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x04 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x05 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x06 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x07 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x08 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x09 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0A },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0B },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0C },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0D },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0E },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0F },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x10 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x11 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x12 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x13 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x14 },
};
// Select the IP address according to your local network
IPAddress myIP(192, 168, 2, 232);
IPAddress myGW(192, 168, 2, 1);
IPAddress mySN(255, 255, 255, 0);
// Google DNS Server IP
IPAddress myDNS(8, 8, 8, 8);
#endif //defines_h

View File

@@ -0,0 +1,258 @@
/****************************************************************************************************************************
FullyFeature_ESP32_SC_ENC.ino
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
/*
This example uses FreeRTOS softwaretimers as there is no built-in Ticker library
*/
#include "defines.h"
extern "C"
{
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#include <AsyncMQTT_ESP32.h>
//#define MQTT_HOST IPAddress(192, 168, 2, 110)
#define MQTT_HOST "broker.emqx.io" // Broker address
#define MQTT_PORT 1883
const char *PubTopic = "async-mqtt/ESP32_SC_ENC_Pub"; // Topic to publish
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
void connectToMqtt()
{
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void ETH_event(WiFiEvent_t event)
{
switch (event)
{
#if USING_CORE_ESP32_CORE_V200_PLUS
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH starting");
break;
case ARDUINO_EVENT_ETH_CONNECTED:
Serial.println("ETH connected");
break;
case ARDUINO_EVENT_ETH_GOT_IP:
Serial.println("ETH got IP");
Serial.print("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH stops");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#else
case SYSTEM_EVENT_ETH_CONNECTED:
erial.println(F("ETH Connected"));
break;
case SYSTEM_EVENT_ETH_GOT_IP:
Serial.println("ETH connected");
Serial.println("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_ETH_DISCONNECTED:
case SYSTEM_EVENT_ETH_STOP:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#endif
default:
break;
}
}
void printSeparationLine()
{
Serial.println("************************************************");
}
void onMqttConnect(bool sessionPresent)
{
Serial.print("Connected to MQTT broker: ");
Serial.print(MQTT_HOST);
Serial.print(", port: ");
Serial.println(MQTT_PORT);
Serial.print("PubTopic: ");
Serial.println(PubTopic);
printSeparationLine();
Serial.print("Session present: ");
Serial.println(sessionPresent);
uint16_t packetIdSub = mqttClient.subscribe(PubTopic, 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);
mqttClient.publish(PubTopic, 0, true, "ESP32_ENC Test");
Serial.println("Publishing at QoS 0");
uint16_t packetIdPub1 = mqttClient.publish(PubTopic, 1, true, "test 2");
Serial.print("Publishing at QoS 1, packetId: ");
Serial.println(packetIdPub1);
uint16_t packetIdPub2 = mqttClient.publish(PubTopic, 2, true, "test 3");
Serial.print("Publishing at QoS 2, packetId: ");
Serial.println(packetIdPub2);
printSeparationLine();
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason)
{
(void) reason;
Serial.println("Disconnected from MQTT.");
if (ESP32_ENC_isConnected())
{
xTimerStart(mqttReconnectTimer, 0);
}
}
void onMqttSubscribe(const uint16_t& packetId, const uint8_t& qos)
{
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(const uint16_t& packetId)
{
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void onMqttMessage(char* topic, char* payload, const AsyncMqttClientMessageProperties& properties,
const size_t& len, const size_t& index, const size_t& total)
{
(void) payload;
Serial.println("Publish received.");
Serial.print(" topic: ");
Serial.println(topic);
Serial.print(" qos: ");
Serial.println(properties.qos);
Serial.print(" dup: ");
Serial.println(properties.dup);
Serial.print(" retain: ");
Serial.println(properties.retain);
Serial.print(" len: ");
Serial.println(len);
Serial.print(" index: ");
Serial.println(index);
Serial.print(" total: ");
Serial.println(total);
}
void onMqttPublish(const uint16_t& packetId)
{
Serial.println("Publish acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
delay(500);
Serial.print("\nStarting FullyFeature_ESP32_SC_ENC on ");
Serial.print(ARDUINO_BOARD);
Serial.println(" with " + String(SHIELD_TYPE));
Serial.println(WEBSERVER_ESP32_SC_ENC_VERSION);
Serial.println(ASYNC_MQTT_ESP32_VERSION);
AMQTT_LOGWARN(F("Default SPI pinout:"));
AMQTT_LOGWARN1(F("SPI_HOST:"), ETH_SPI_HOST);
AMQTT_LOGWARN1(F("MOSI:"), MOSI_GPIO);
AMQTT_LOGWARN1(F("MISO:"), MISO_GPIO);
AMQTT_LOGWARN1(F("SCK:"), SCK_GPIO);
AMQTT_LOGWARN1(F("CS:"), CS_GPIO);
AMQTT_LOGWARN1(F("INT:"), INT_GPIO);
AMQTT_LOGWARN1(F("SPI Clock (MHz):"), SPI_CLOCK_MHZ);
AMQTT_LOGWARN(F("========================="));
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0,
reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
///////////////////////////////////
// To be called before ETH.begin()
WiFi.onEvent(ETH_event);
// start the ethernet connection and the server:
// Use DHCP dynamic IP and random mac
//bool begin(int MISO_GPIO, int MOSI_GPIO, int SCLK_GPIO, int CS_GPIO, int INT_GPIO, int SPI_CLOCK_MHZ,
// int SPI_HOST, uint8_t *ENC28J60_Mac = ENC28J60_Default_Mac);
//ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST );
ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST, mac[millis() % NUMBER_OF_MAC] );
// Static IP, leave without this line to get IP via DHCP
//bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0);
//ETH.config(myIP, myGW, mySN, myDNS);
ESP32_ENC_waitForConnect();
///////////////////////////////////
}
void loop()
{
}

View File

@@ -0,0 +1,90 @@
/****************************************************************************************************************************
defines.h
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
***************************************************************************************************************************************/
#ifndef defines_h
#define defines_h
// Debug Level from 0 to 4
#define _ETHERNET_WEBSERVER_LOGLEVEL_ 1
#define _ASYNC_MQTT_LOGLEVEL_ 1
/////////////////////////////////////////////
// For ESP32-S3
// Optional values to override default settings
//#define ETH_SPI_HOST SPI2_HOST
//#define SPI_CLOCK_MHZ 8
// Must connect INT to GPIOxx or not working
//#define INT_GPIO 4
//#define MISO_GPIO 13
//#define MOSI_GPIO 11
//#define SCK_GPIO 12
//#define CS_GPIO 10
// For ESP32_C3
// Optional values to override default settings
// Don't change unless you know what you're doing
//#define ETH_SPI_HOST SPI2_HOST
//#define SPI_CLOCK_MHZ 8
// Must connect INT to GPIOxx or not working
//#define INT_GPIO 10
//#define MISO_GPIO 5
//#define MOSI_GPIO 6
//#define SCK_GPIO 4
//#define CS_GPIO 7
/////////////////////////////////////////////
#include <WebServer_ESP32_SC_ENC.h> // https://github.com/khoih-prog/WebServer_ESP32_SC_ENC
/////////////////////////////////////////////
// Enter a MAC address and IP address for your controller below.
#define NUMBER_OF_MAC 20
byte mac[][NUMBER_OF_MAC] =
{
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x01 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x02 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x03 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x04 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x05 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x06 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x07 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x08 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x09 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0A },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0B },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0C },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0D },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0E },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0F },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x10 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x11 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x12 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x13 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x14 },
};
// Select the IP address according to your local network
IPAddress myIP(192, 168, 2, 232);
IPAddress myGW(192, 168, 2, 1);
IPAddress mySN(255, 255, 255, 0);
// Google DNS Server IP
IPAddress myDNS(8, 8, 8, 8);
#endif //defines_h

View File

@@ -0,0 +1,283 @@
/****************************************************************************************************************************
FullyFeatureSSL_ESP32_SC_W5500.ino
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "defines.h"
extern "C"
{
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#define ASYNC_TCP_SSL_ENABLED true
//#define ASYNC_TCP_SSL_ENABLED false
#include <AsyncMQTT_ESP32.h>
//#define MQTT_HOST IPAddress(192, 168, 2, 110)
#define MQTT_HOST "broker.emqx.io" // Broker address
#if ASYNC_TCP_SSL_ENABLED
#define MQTT_SECURE true
const uint8_t MQTT_SERVER_FINGERPRINT[] = {0x7e, 0x36, 0x22, 0x01, 0xf9, 0x7e, 0x99, 0x2f, 0xc5, 0xdb, 0x3d, 0xbe, 0xac, 0x48, 0x67, 0x5b, 0x5d, 0x47, 0x94, 0xd2};
const char *PubTopic = "async-mqtt/ESP32_W5500_SSL_Pub"; // Topic to publish
#define MQTT_PORT 8883
#else
const char *PubTopic = "async-mqtt/ESP32_SC_W5500_Pub"; // Topic to publish
#define MQTT_PORT 1883
#endif
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
void connectToMqtt()
{
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void ETH_event(WiFiEvent_t event)
{
switch (event)
{
#if USING_CORE_ESP32_CORE_V200_PLUS
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH starting");
break;
case ARDUINO_EVENT_ETH_CONNECTED:
Serial.println("ETH connected");
break;
case ARDUINO_EVENT_ETH_GOT_IP:
Serial.println("ETH got IP");
Serial.print("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH stops");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#else
case SYSTEM_EVENT_ETH_CONNECTED:
erial.println(F("ETH Connected"));
break;
case SYSTEM_EVENT_ETH_GOT_IP:
Serial.println("ETH connected");
Serial.println("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_ETH_DISCONNECTED:
case SYSTEM_EVENT_ETH_STOP:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#endif
default:
break;
}
}
void printSeparationLine()
{
Serial.println("************************************************");
}
void onMqttConnect(bool sessionPresent)
{
Serial.print("Connected to MQTT broker: ");
Serial.print(MQTT_HOST);
Serial.print(", port: ");
Serial.println(MQTT_PORT);
Serial.print("PubTopic: ");
Serial.println(PubTopic);
printSeparationLine();
Serial.print("Session present: ");
Serial.println(sessionPresent);
uint16_t packetIdSub = mqttClient.subscribe(PubTopic, 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);
mqttClient.publish(PubTopic, 0, true, "ESP32_W5500 Test");
Serial.println("Publishing at QoS 0");
uint16_t packetIdPub1 = mqttClient.publish(PubTopic, 1, true, "test 2");
Serial.print("Publishing at QoS 1, packetId: ");
Serial.println(packetIdPub1);
uint16_t packetIdPub2 = mqttClient.publish(PubTopic, 2, true, "test 3");
Serial.print("Publishing at QoS 2, packetId: ");
Serial.println(packetIdPub2);
printSeparationLine();
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason)
{
(void) reason;
Serial.println("Disconnected from MQTT.");
if (ESP32_W5500_isConnected())
{
xTimerStart(mqttReconnectTimer, 0);
}
}
void onMqttSubscribe(const uint16_t& packetId, const uint8_t& qos)
{
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(const uint16_t& packetId)
{
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void onMqttMessage(char* topic, char* payload, const AsyncMqttClientMessageProperties& properties,
const size_t& len, const size_t& index, const size_t& total)
{
(void) payload;
Serial.println("Publish received.");
Serial.print(" topic: ");
Serial.println(topic);
Serial.print(" qos: ");
Serial.println(properties.qos);
Serial.print(" dup: ");
Serial.println(properties.dup);
Serial.print(" retain: ");
Serial.println(properties.retain);
Serial.print(" len: ");
Serial.println(len);
Serial.print(" index: ");
Serial.println(index);
Serial.print(" total: ");
Serial.println(total);
}
void onMqttPublish(const uint16_t& packetId)
{
Serial.println("Publish acknowledged");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
delay(500);
Serial.print("\nStarting FullyFeatureSSL_ESP32_SC_W5500 on ");
Serial.print(ARDUINO_BOARD);
Serial.println(" with " + String(SHIELD_TYPE));
Serial.println(WEBSERVER_ESP32_SC_W5500_VERSION);
Serial.println(ASYNC_MQTT_ESP32_VERSION);
AMQTT_LOGWARN(F("Default SPI pinout:"));
AMQTT_LOGWARN1(F("SPI_HOST:"), ETH_SPI_HOST);
AMQTT_LOGWARN1(F("MOSI:"), MOSI_GPIO);
AMQTT_LOGWARN1(F("MISO:"), MISO_GPIO);
AMQTT_LOGWARN1(F("SCK:"), SCK_GPIO);
AMQTT_LOGWARN1(F("CS:"), CS_GPIO);
AMQTT_LOGWARN1(F("INT:"), INT_GPIO);
AMQTT_LOGWARN1(F("SPI Clock (MHz):"), SPI_CLOCK_MHZ);
AMQTT_LOGWARN(F("========================="));
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0,
reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
#if ASYNC_TCP_SSL_ENABLED
mqttClient.setSecure(MQTT_SECURE);
if (MQTT_SECURE)
{
//mqttClient.addServerFingerprint((const uint8_t[])MQTT_SERVER_FINGERPRINT);
mqttClient.addServerFingerprint((const uint8_t *)MQTT_SERVER_FINGERPRINT);
}
#endif
///////////////////////////////////
// To be called before ETH.begin()
WiFi.onEvent(ETH_event);
// start the ethernet connection and the server:
// Use DHCP dynamic IP and random mac
//bool begin(int MISO_GPIO, int MOSI_GPIO, int SCLK_GPIO, int CS_GPIO, int INT_GPIO, int SPI_CLOCK_MHZ,
// int SPI_HOST, uint8_t *W5500_Mac = W5500_Default_Mac);
ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST );
//ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST, mac[millis() % NUMBER_OF_MAC] );
// Static IP, leave without this line to get IP via DHCP
//bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0);
//ETH.config(myIP, myGW, mySN, myDNS);
ESP32_W5500_waitForConnect();
///////////////////////////////////
}
void loop()
{
}

View File

@@ -0,0 +1,90 @@
/****************************************************************************************************************************
defines.h
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
***************************************************************************************************************************************/
#ifndef defines_h
#define defines_h
// Debug Level from 0 to 4
#define _ETHERNET_WEBSERVER_LOGLEVEL_ 1
#define _ASYNC_MQTT_LOGLEVEL_ 1
//////////////////////////////////////////////////////////
// For ESP32-S3
// Optional values to override default settings
//#define ETH_SPI_HOST SPI2_HOST
//#define SPI_CLOCK_MHZ 25
// Must connect INT to GPIOxx or not working
//#define INT_GPIO 4
//#define MISO_GPIO 13
//#define MOSI_GPIO 11
//#define SCK_GPIO 12
//#define CS_GPIO 10
// For ESP32_C3
// Optional values to override default settings
// Don't change unless you know what you're doing
//#define ETH_SPI_HOST SPI2_HOST
//#define SPI_CLOCK_MHZ 25
// Must connect INT to GPIOxx or not working
//#define INT_GPIO 10
//#define MISO_GPIO 5
//#define MOSI_GPIO 6
//#define SCK_GPIO 4
//#define CS_GPIO 7
//////////////////////////////////////////////////////////
#include <WebServer_ESP32_SC_W5500.h>
/////////////////////////////////////////////
// Enter a MAC address and IP address for your controller below.
#define NUMBER_OF_MAC 20
byte mac[][NUMBER_OF_MAC] =
{
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x01 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x02 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x03 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x04 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x05 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x06 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x07 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x08 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x09 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0A },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0B },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0C },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0D },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0E },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0F },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x10 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x11 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x12 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x13 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x14 },
};
// Select the IP address according to your local network
IPAddress myIP(192, 168, 2, 232);
IPAddress myGW(192, 168, 2, 1);
IPAddress mySN(255, 255, 255, 0);
// Google DNS Server IP
IPAddress myDNS(8, 8, 8, 8);
#endif //defines_h

View File

@@ -0,0 +1,258 @@
/****************************************************************************************************************************
FullyFeature_ESP32_SC_W5500.ino
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
/*
This example uses FreeRTOS softwaretimers as there is no built-in Ticker library
*/
#include "defines.h"
extern "C"
{
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#include <AsyncMQTT_ESP32.h>
//#define MQTT_HOST IPAddress(192, 168, 2, 110)
#define MQTT_HOST "broker.emqx.io" // Broker address
#define MQTT_PORT 1883
const char *PubTopic = "async-mqtt/ESP32_SC_W5500_Pub"; // Topic to publish
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
void connectToMqtt()
{
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void ETH_event(WiFiEvent_t event)
{
switch (event)
{
#if USING_CORE_ESP32_CORE_V200_PLUS
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH starting");
break;
case ARDUINO_EVENT_ETH_CONNECTED:
Serial.println("ETH connected");
break;
case ARDUINO_EVENT_ETH_GOT_IP:
Serial.println("ETH got IP");
Serial.print("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH stops");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#else
case SYSTEM_EVENT_ETH_CONNECTED:
erial.println(F("ETH Connected"));
break;
case SYSTEM_EVENT_ETH_GOT_IP:
Serial.println("ETH connected");
Serial.println("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_ETH_DISCONNECTED:
case SYSTEM_EVENT_ETH_STOP:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#endif
default:
break;
}
}
void printSeparationLine()
{
Serial.println("************************************************");
}
void onMqttConnect(bool sessionPresent)
{
Serial.print("Connected to MQTT broker: ");
Serial.print(MQTT_HOST);
Serial.print(", port: ");
Serial.println(MQTT_PORT);
Serial.print("PubTopic: ");
Serial.println(PubTopic);
printSeparationLine();
Serial.print("Session present: ");
Serial.println(sessionPresent);
uint16_t packetIdSub = mqttClient.subscribe(PubTopic, 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);
mqttClient.publish(PubTopic, 0, true, "ESP32_W5500 Test");
Serial.println("Publishing at QoS 0");
uint16_t packetIdPub1 = mqttClient.publish(PubTopic, 1, true, "test 2");
Serial.print("Publishing at QoS 1, packetId: ");
Serial.println(packetIdPub1);
uint16_t packetIdPub2 = mqttClient.publish(PubTopic, 2, true, "test 3");
Serial.print("Publishing at QoS 2, packetId: ");
Serial.println(packetIdPub2);
printSeparationLine();
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason)
{
(void) reason;
Serial.println("Disconnected from MQTT.");
if (ESP32_W5500_isConnected())
{
xTimerStart(mqttReconnectTimer, 0);
}
}
void onMqttSubscribe(const uint16_t& packetId, const uint8_t& qos)
{
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(const uint16_t& packetId)
{
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void onMqttMessage(char* topic, char* payload, const AsyncMqttClientMessageProperties& properties,
const size_t& len, const size_t& index, const size_t& total)
{
(void) payload;
Serial.println("Publish received.");
Serial.print(" topic: ");
Serial.println(topic);
Serial.print(" qos: ");
Serial.println(properties.qos);
Serial.print(" dup: ");
Serial.println(properties.dup);
Serial.print(" retain: ");
Serial.println(properties.retain);
Serial.print(" len: ");
Serial.println(len);
Serial.print(" index: ");
Serial.println(index);
Serial.print(" total: ");
Serial.println(total);
}
void onMqttPublish(const uint16_t& packetId)
{
Serial.println("Publish acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
delay(500);
Serial.print("\nStarting FullyFeature_ESP32_SC_W5500 on ");
Serial.print(ARDUINO_BOARD);
Serial.println(" with " + String(SHIELD_TYPE));
Serial.println(WEBSERVER_ESP32_SC_W5500_VERSION);
Serial.println(ASYNC_MQTT_ESP32_VERSION);
AMQTT_LOGWARN(F("Default SPI pinout:"));
AMQTT_LOGWARN1(F("SPI_HOST:"), ETH_SPI_HOST);
AMQTT_LOGWARN1(F("MOSI:"), MOSI_GPIO);
AMQTT_LOGWARN1(F("MISO:"), MISO_GPIO);
AMQTT_LOGWARN1(F("SCK:"), SCK_GPIO);
AMQTT_LOGWARN1(F("CS:"), CS_GPIO);
AMQTT_LOGWARN1(F("INT:"), INT_GPIO);
AMQTT_LOGWARN1(F("SPI Clock (MHz):"), SPI_CLOCK_MHZ);
AMQTT_LOGWARN(F("========================="));
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0,
reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
///////////////////////////////////
// To be called before ETH.begin()
WiFi.onEvent(ETH_event);
// start the ethernet connection and the server:
// Use DHCP dynamic IP and random mac
//bool begin(int MISO_GPIO, int MOSI_GPIO, int SCLK_GPIO, int CS_GPIO, int INT_GPIO, int SPI_CLOCK_MHZ,
// int SPI_HOST, uint8_t *W5500_Mac = W5500_Default_Mac);
ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST );
//ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST, mac[millis() % NUMBER_OF_MAC] );
// Static IP, leave without this line to get IP via DHCP
//bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0);
//ETH.config(myIP, myGW, mySN, myDNS);
ESP32_W5500_waitForConnect();
///////////////////////////////////
}
void loop()
{
}

View File

@@ -0,0 +1,90 @@
/****************************************************************************************************************************
defines.h
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
***************************************************************************************************************************************/
#ifndef defines_h
#define defines_h
// Debug Level from 0 to 4
#define _ETHERNET_WEBSERVER_LOGLEVEL_ 1
#define _ASYNC_MQTT_LOGLEVEL_ 1
//////////////////////////////////////////////////////////
// For ESP32-S3
// Optional values to override default settings
//#define ETH_SPI_HOST SPI2_HOST
//#define SPI_CLOCK_MHZ 25
// Must connect INT to GPIOxx or not working
//#define INT_GPIO 4
//#define MISO_GPIO 13
//#define MOSI_GPIO 11
//#define SCK_GPIO 12
//#define CS_GPIO 10
// For ESP32_C3
// Optional values to override default settings
// Don't change unless you know what you're doing
//#define ETH_SPI_HOST SPI2_HOST
//#define SPI_CLOCK_MHZ 25
// Must connect INT to GPIOxx or not working
//#define INT_GPIO 10
//#define MISO_GPIO 5
//#define MOSI_GPIO 6
//#define SCK_GPIO 4
//#define CS_GPIO 7
//////////////////////////////////////////////////////////
#include <WebServer_ESP32_SC_W5500.h>
/////////////////////////////////////////////
// Enter a MAC address and IP address for your controller below.
#define NUMBER_OF_MAC 20
byte mac[][NUMBER_OF_MAC] =
{
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x01 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x02 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x03 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x04 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x05 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x06 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x07 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x08 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x09 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0A },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0B },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0C },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0D },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0E },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0F },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x10 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x11 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x12 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x13 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x14 },
};
// Select the IP address according to your local network
IPAddress myIP(192, 168, 2, 232);
IPAddress myGW(192, 168, 2, 1);
IPAddress mySN(255, 255, 255, 0);
// Google DNS Server IP
IPAddress myDNS(8, 8, 8, 8);
#endif //defines_h

View File

@@ -0,0 +1,283 @@
/****************************************************************************************************************************
FullyFeatureSSL_ESP32_SC_W6100.ino
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W6100 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "defines.h"
extern "C"
{
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#define ASYNC_TCP_SSL_ENABLED true
//#define ASYNC_TCP_SSL_ENABLED false
#include <AsyncMQTT_ESP32.h>
//#define MQTT_HOST IPAddress(192, 168, 2, 110)
#define MQTT_HOST "broker.emqx.io" // Broker address
#if ASYNC_TCP_SSL_ENABLED
#define MQTT_SECURE true
const uint8_t MQTT_SERVER_FINGERPRINT[] = {0x7e, 0x36, 0x22, 0x01, 0xf9, 0x7e, 0x99, 0x2f, 0xc5, 0xdb, 0x3d, 0xbe, 0xac, 0x48, 0x67, 0x5b, 0x5d, 0x47, 0x94, 0xd2};
const char *PubTopic = "async-mqtt/ESP32_W6100_SSL_Pub"; // Topic to publish
#define MQTT_PORT 8883
#else
const char *PubTopic = "async-mqtt/ESP32_SC_W6100_Pub"; // Topic to publish
#define MQTT_PORT 1883
#endif
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
void connectToMqtt()
{
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void ETH_event(WiFiEvent_t event)
{
switch (event)
{
#if USING_CORE_ESP32_CORE_V200_PLUS
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH starting");
break;
case ARDUINO_EVENT_ETH_CONNECTED:
Serial.println("ETH connected");
break;
case ARDUINO_EVENT_ETH_GOT_IP:
Serial.println("ETH got IP");
Serial.print("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH stops");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#else
case SYSTEM_EVENT_ETH_CONNECTED:
erial.println(F("ETH Connected"));
break;
case SYSTEM_EVENT_ETH_GOT_IP:
Serial.println("ETH connected");
Serial.println("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_ETH_DISCONNECTED:
case SYSTEM_EVENT_ETH_STOP:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#endif
default:
break;
}
}
void printSeparationLine()
{
Serial.println("************************************************");
}
void onMqttConnect(bool sessionPresent)
{
Serial.print("Connected to MQTT broker: ");
Serial.print(MQTT_HOST);
Serial.print(", port: ");
Serial.println(MQTT_PORT);
Serial.print("PubTopic: ");
Serial.println(PubTopic);
printSeparationLine();
Serial.print("Session present: ");
Serial.println(sessionPresent);
uint16_t packetIdSub = mqttClient.subscribe(PubTopic, 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);
mqttClient.publish(PubTopic, 0, true, "ESP32_W6100 Test");
Serial.println("Publishing at QoS 0");
uint16_t packetIdPub1 = mqttClient.publish(PubTopic, 1, true, "test 2");
Serial.print("Publishing at QoS 1, packetId: ");
Serial.println(packetIdPub1);
uint16_t packetIdPub2 = mqttClient.publish(PubTopic, 2, true, "test 3");
Serial.print("Publishing at QoS 2, packetId: ");
Serial.println(packetIdPub2);
printSeparationLine();
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason)
{
(void) reason;
Serial.println("Disconnected from MQTT.");
if (ESP32_W6100_isConnected())
{
xTimerStart(mqttReconnectTimer, 0);
}
}
void onMqttSubscribe(const uint16_t& packetId, const uint8_t& qos)
{
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(const uint16_t& packetId)
{
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void onMqttMessage(char* topic, char* payload, const AsyncMqttClientMessageProperties& properties,
const size_t& len, const size_t& index, const size_t& total)
{
(void) payload;
Serial.println("Publish received.");
Serial.print(" topic: ");
Serial.println(topic);
Serial.print(" qos: ");
Serial.println(properties.qos);
Serial.print(" dup: ");
Serial.println(properties.dup);
Serial.print(" retain: ");
Serial.println(properties.retain);
Serial.print(" len: ");
Serial.println(len);
Serial.print(" index: ");
Serial.println(index);
Serial.print(" total: ");
Serial.println(total);
}
void onMqttPublish(const uint16_t& packetId)
{
Serial.println("Publish acknowledged");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
delay(500);
Serial.print("\nStarting FullyFeatureSSL_ESP32_SC_W6100 on ");
Serial.print(ARDUINO_BOARD);
Serial.println(" with " + String(SHIELD_TYPE));
Serial.println(WEBSERVER_ESP32_SC_W6100_VERSION);
Serial.println(ASYNC_MQTT_ESP32_VERSION);
AMQTT_LOGWARN(F("Default SPI pinout:"));
AMQTT_LOGWARN1(F("SPI_HOST:"), ETH_SPI_HOST);
AMQTT_LOGWARN1(F("MOSI:"), MOSI_GPIO);
AMQTT_LOGWARN1(F("MISO:"), MISO_GPIO);
AMQTT_LOGWARN1(F("SCK:"), SCK_GPIO);
AMQTT_LOGWARN1(F("CS:"), CS_GPIO);
AMQTT_LOGWARN1(F("INT:"), INT_GPIO);
AMQTT_LOGWARN1(F("SPI Clock (MHz):"), SPI_CLOCK_MHZ);
AMQTT_LOGWARN(F("========================="));
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0,
reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
#if ASYNC_TCP_SSL_ENABLED
mqttClient.setSecure(MQTT_SECURE);
if (MQTT_SECURE)
{
//mqttClient.addServerFingerprint((const uint8_t[])MQTT_SERVER_FINGERPRINT);
mqttClient.addServerFingerprint((const uint8_t *)MQTT_SERVER_FINGERPRINT);
}
#endif
///////////////////////////////////
// To be called before ETH.begin()
WiFi.onEvent(ETH_event);
// start the ethernet connection and the server:
// Use DHCP dynamic IP and random mac
//bool begin(int MISO_GPIO, int MOSI_GPIO, int SCLK_GPIO, int CS_GPIO, int INT_GPIO, int SPI_CLOCK_MHZ,
// int SPI_HOST, uint8_t *W6100_Mac = W6100_Default_Mac);
ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST );
//ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST, mac[millis() % NUMBER_OF_MAC] );
// Static IP, leave without this line to get IP via DHCP
//bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0);
//ETH.config(myIP, myGW, mySN, myDNS);
ESP32_W6100_waitForConnect();
///////////////////////////////////
}
void loop()
{
}

View File

@@ -0,0 +1,90 @@
/****************************************************************************************************************************
defines.h
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
***************************************************************************************************************************************/
#ifndef defines_h
#define defines_h
// Debug Level from 0 to 4
#define _ETHERNET_WEBSERVER_LOGLEVEL_ 1
#define _ASYNC_MQTT_LOGLEVEL_ 1
//////////////////////////////////////////////////////////
// For ESP32-S3
// Optional values to override default settings
//#define ETH_SPI_HOST SPI2_HOST
//#define SPI_CLOCK_MHZ 25
// Must connect INT to GPIOxx or not working
//#define INT_GPIO 4
//#define MISO_GPIO 13
//#define MOSI_GPIO 11
//#define SCK_GPIO 12
//#define CS_GPIO 10
// For ESP32_C3
// Optional values to override default settings
// Don't change unless you know what you're doing
//#define ETH_SPI_HOST SPI2_HOST
//#define SPI_CLOCK_MHZ 25
// Must connect INT to GPIOxx or not working
//#define INT_GPIO 10
//#define MISO_GPIO 5
//#define MOSI_GPIO 6
//#define SCK_GPIO 4
//#define CS_GPIO 7
//////////////////////////////////////////////////////////
#include <WebServer_ESP32_SC_W6100.h>
/////////////////////////////////////////////
// Enter a MAC address and IP address for your controller below.
#define NUMBER_OF_MAC 20
byte mac[][NUMBER_OF_MAC] =
{
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x01 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x02 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x03 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x04 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x05 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x06 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x07 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x08 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x09 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0A },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0B },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0C },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0D },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0E },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0F },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x10 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x11 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x12 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x13 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x14 },
};
// Select the IP address according to your local network
IPAddress myIP(192, 168, 2, 232);
IPAddress myGW(192, 168, 2, 1);
IPAddress mySN(255, 255, 255, 0);
// Google DNS Server IP
IPAddress myDNS(8, 8, 8, 8);
#endif //defines_h

View File

@@ -0,0 +1,258 @@
/****************************************************************************************************************************
FullyFeature_ESP32_SC_W6100.ino
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W6100 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
/*
This example uses FreeRTOS softwaretimers as there is no built-in Ticker library
*/
#include "defines.h"
extern "C"
{
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#include <AsyncMQTT_ESP32.h>
//#define MQTT_HOST IPAddress(192, 168, 2, 110)
#define MQTT_HOST "broker.emqx.io" // Broker address
#define MQTT_PORT 1883
const char *PubTopic = "async-mqtt/ESP32_SC_W6100_Pub"; // Topic to publish
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
void connectToMqtt()
{
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void ETH_event(WiFiEvent_t event)
{
switch (event)
{
#if USING_CORE_ESP32_CORE_V200_PLUS
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH starting");
break;
case ARDUINO_EVENT_ETH_CONNECTED:
Serial.println("ETH connected");
break;
case ARDUINO_EVENT_ETH_GOT_IP:
Serial.println("ETH got IP");
Serial.print("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH stops");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#else
case SYSTEM_EVENT_ETH_CONNECTED:
erial.println(F("ETH Connected"));
break;
case SYSTEM_EVENT_ETH_GOT_IP:
Serial.println("ETH connected");
Serial.println("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_ETH_DISCONNECTED:
case SYSTEM_EVENT_ETH_STOP:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#endif
default:
break;
}
}
void printSeparationLine()
{
Serial.println("************************************************");
}
void onMqttConnect(bool sessionPresent)
{
Serial.print("Connected to MQTT broker: ");
Serial.print(MQTT_HOST);
Serial.print(", port: ");
Serial.println(MQTT_PORT);
Serial.print("PubTopic: ");
Serial.println(PubTopic);
printSeparationLine();
Serial.print("Session present: ");
Serial.println(sessionPresent);
uint16_t packetIdSub = mqttClient.subscribe(PubTopic, 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);
mqttClient.publish(PubTopic, 0, true, "ESP32_W6100 Test");
Serial.println("Publishing at QoS 0");
uint16_t packetIdPub1 = mqttClient.publish(PubTopic, 1, true, "test 2");
Serial.print("Publishing at QoS 1, packetId: ");
Serial.println(packetIdPub1);
uint16_t packetIdPub2 = mqttClient.publish(PubTopic, 2, true, "test 3");
Serial.print("Publishing at QoS 2, packetId: ");
Serial.println(packetIdPub2);
printSeparationLine();
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason)
{
(void) reason;
Serial.println("Disconnected from MQTT.");
if (ESP32_W6100_isConnected())
{
xTimerStart(mqttReconnectTimer, 0);
}
}
void onMqttSubscribe(const uint16_t& packetId, const uint8_t& qos)
{
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(const uint16_t& packetId)
{
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void onMqttMessage(char* topic, char* payload, const AsyncMqttClientMessageProperties& properties,
const size_t& len, const size_t& index, const size_t& total)
{
(void) payload;
Serial.println("Publish received.");
Serial.print(" topic: ");
Serial.println(topic);
Serial.print(" qos: ");
Serial.println(properties.qos);
Serial.print(" dup: ");
Serial.println(properties.dup);
Serial.print(" retain: ");
Serial.println(properties.retain);
Serial.print(" len: ");
Serial.println(len);
Serial.print(" index: ");
Serial.println(index);
Serial.print(" total: ");
Serial.println(total);
}
void onMqttPublish(const uint16_t& packetId)
{
Serial.println("Publish acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
delay(500);
Serial.print("\nStarting FullyFeature_ESP32_SC_W6100 on ");
Serial.print(ARDUINO_BOARD);
Serial.println(" with " + String(SHIELD_TYPE));
Serial.println(WEBSERVER_ESP32_SC_W6100_VERSION);
Serial.println(ASYNC_MQTT_ESP32_VERSION);
AMQTT_LOGWARN(F("Default SPI pinout:"));
AMQTT_LOGWARN1(F("SPI_HOST:"), ETH_SPI_HOST);
AMQTT_LOGWARN1(F("MOSI:"), MOSI_GPIO);
AMQTT_LOGWARN1(F("MISO:"), MISO_GPIO);
AMQTT_LOGWARN1(F("SCK:"), SCK_GPIO);
AMQTT_LOGWARN1(F("CS:"), CS_GPIO);
AMQTT_LOGWARN1(F("INT:"), INT_GPIO);
AMQTT_LOGWARN1(F("SPI Clock (MHz):"), SPI_CLOCK_MHZ);
AMQTT_LOGWARN(F("========================="));
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0,
reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
///////////////////////////////////
// To be called before ETH.begin()
WiFi.onEvent(ETH_event);
// start the ethernet connection and the server:
// Use DHCP dynamic IP and random mac
//bool begin(int MISO_GPIO, int MOSI_GPIO, int SCLK_GPIO, int CS_GPIO, int INT_GPIO, int SPI_CLOCK_MHZ,
// int SPI_HOST, uint8_t *W6100_Mac = W6100_Default_Mac);
ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST );
//ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST, mac[millis() % NUMBER_OF_MAC] );
// Static IP, leave without this line to get IP via DHCP
//bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0);
//ETH.config(myIP, myGW, mySN, myDNS);
ESP32_W6100_waitForConnect();
///////////////////////////////////
}
void loop()
{
}

View File

@@ -0,0 +1,90 @@
/****************************************************************************************************************************
defines.h
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
***************************************************************************************************************************************/
#ifndef defines_h
#define defines_h
// Debug Level from 0 to 4
#define _ETHERNET_WEBSERVER_LOGLEVEL_ 1
#define _ASYNC_MQTT_LOGLEVEL_ 1
//////////////////////////////////////////////////////////
// For ESP32-S3
// Optional values to override default settings
//#define ETH_SPI_HOST SPI2_HOST
//#define SPI_CLOCK_MHZ 25
// Must connect INT to GPIOxx or not working
//#define INT_GPIO 4
//#define MISO_GPIO 13
//#define MOSI_GPIO 11
//#define SCK_GPIO 12
//#define CS_GPIO 10
// For ESP32_C3
// Optional values to override default settings
// Don't change unless you know what you're doing
//#define ETH_SPI_HOST SPI2_HOST
//#define SPI_CLOCK_MHZ 25
// Must connect INT to GPIOxx or not working
//#define INT_GPIO 10
//#define MISO_GPIO 5
//#define MOSI_GPIO 6
//#define SCK_GPIO 4
//#define CS_GPIO 7
//////////////////////////////////////////////////////////
#include <WebServer_ESP32_SC_W6100.h>
/////////////////////////////////////////////
// Enter a MAC address and IP address for your controller below.
#define NUMBER_OF_MAC 20
byte mac[][NUMBER_OF_MAC] =
{
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x01 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x02 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x03 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x04 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x05 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x06 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x07 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x08 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x09 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0A },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0B },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0C },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0D },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0E },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0F },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x10 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x11 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x12 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x13 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x14 },
};
// Select the IP address according to your local network
IPAddress myIP(192, 168, 2, 232);
IPAddress myGW(192, 168, 2, 1);
IPAddress mySN(255, 255, 255, 0);
// Google DNS Server IP
IPAddress myDNS(8, 8, 8, 8);
#endif //defines_h

View File

@@ -0,0 +1,281 @@
/****************************************************************************************************************************
FullyFeatureSSL_ESP32_W5500.ino
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "defines.h"
extern "C"
{
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#define ASYNC_TCP_SSL_ENABLED true
//#define ASYNC_TCP_SSL_ENABLED false
#include <AsyncMQTT_ESP32.h>
//#define MQTT_HOST IPAddress(192, 168, 2, 110)
#define MQTT_HOST "broker.emqx.io" // Broker address
#if ASYNC_TCP_SSL_ENABLED
#define MQTT_SECURE true
const uint8_t MQTT_SERVER_FINGERPRINT[] = {0x7e, 0x36, 0x22, 0x01, 0xf9, 0x7e, 0x99, 0x2f, 0xc5, 0xdb, 0x3d, 0xbe, 0xac, 0x48, 0x67, 0x5b, 0x5d, 0x47, 0x94, 0xd2};
const char *PubTopic = "async-mqtt/ESP32_W5500_SSL_Pub"; // Topic to publish
#define MQTT_PORT 8883
#else
const char *PubTopic = "async-mqtt/ESP32_W5500_Pub"; // Topic to publish
#define MQTT_PORT 1883
#endif
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
void connectToMqtt()
{
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void ETH_event(WiFiEvent_t event)
{
switch (event)
{
#if USING_CORE_ESP32_CORE_V200_PLUS
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH starting");
break;
case ARDUINO_EVENT_ETH_CONNECTED:
Serial.println("ETH connected");
break;
case ARDUINO_EVENT_ETH_GOT_IP:
Serial.println("ETH got IP");
Serial.print("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH stops");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#else
case SYSTEM_EVENT_ETH_CONNECTED:
erial.println(F("ETH Connected"));
break;
case SYSTEM_EVENT_ETH_GOT_IP:
Serial.println("ETH connected");
Serial.println("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_ETH_DISCONNECTED:
case SYSTEM_EVENT_ETH_STOP:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#endif
default:
break;
}
}
void printSeparationLine()
{
Serial.println("************************************************");
}
void onMqttConnect(bool sessionPresent)
{
Serial.print("Connected to MQTT broker: ");
Serial.print(MQTT_HOST);
Serial.print(", port: ");
Serial.println(MQTT_PORT);
Serial.print("PubTopic: ");
Serial.println(PubTopic);
printSeparationLine();
Serial.print("Session present: ");
Serial.println(sessionPresent);
uint16_t packetIdSub = mqttClient.subscribe(PubTopic, 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);
mqttClient.publish(PubTopic, 0, true, "ESP32_W5500 Test");
Serial.println("Publishing at QoS 0");
uint16_t packetIdPub1 = mqttClient.publish(PubTopic, 1, true, "test 2");
Serial.print("Publishing at QoS 1, packetId: ");
Serial.println(packetIdPub1);
uint16_t packetIdPub2 = mqttClient.publish(PubTopic, 2, true, "test 3");
Serial.print("Publishing at QoS 2, packetId: ");
Serial.println(packetIdPub2);
printSeparationLine();
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason)
{
(void) reason;
Serial.println("Disconnected from MQTT.");
if (ESP32_W5500_isConnected())
{
xTimerStart(mqttReconnectTimer, 0);
}
}
void onMqttSubscribe(const uint16_t& packetId, const uint8_t& qos)
{
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(const uint16_t& packetId)
{
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void onMqttMessage(char* topic, char* payload, const AsyncMqttClientMessageProperties& properties,
const size_t& len, const size_t& index, const size_t& total)
{
(void) payload;
Serial.println("Publish received.");
Serial.print(" topic: ");
Serial.println(topic);
Serial.print(" qos: ");
Serial.println(properties.qos);
Serial.print(" dup: ");
Serial.println(properties.dup);
Serial.print(" retain: ");
Serial.println(properties.retain);
Serial.print(" len: ");
Serial.println(len);
Serial.print(" index: ");
Serial.println(index);
Serial.print(" total: ");
Serial.println(total);
}
void onMqttPublish(const uint16_t& packetId)
{
Serial.println("Publish acknowledged");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
Serial.print("\nStarting FullyFeatureSSL_ESP32_W5500 on ");
Serial.print(ARDUINO_BOARD);
Serial.println(" with " + String(SHIELD_TYPE));
Serial.println(WEBSERVER_ESP32_W5500_VERSION);
Serial.println(ASYNC_MQTT_ESP32_VERSION);
AMQTT_LOGWARN(F("Default SPI pinout:"));
AMQTT_LOGWARN1(F("SPI_HOST:"), ETH_SPI_HOST);
AMQTT_LOGWARN1(F("MOSI:"), MOSI_GPIO);
AMQTT_LOGWARN1(F("MISO:"), MISO_GPIO);
AMQTT_LOGWARN1(F("SCK:"), SCK_GPIO);
AMQTT_LOGWARN1(F("CS:"), CS_GPIO);
AMQTT_LOGWARN1(F("INT:"), INT_GPIO);
AMQTT_LOGWARN1(F("SPI Clock (MHz):"), SPI_CLOCK_MHZ);
AMQTT_LOGWARN(F("========================="));
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0,
reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
#if ASYNC_TCP_SSL_ENABLED
mqttClient.setSecure(MQTT_SECURE);
if (MQTT_SECURE)
{
//mqttClient.addServerFingerprint((const uint8_t[])MQTT_SERVER_FINGERPRINT);
mqttClient.addServerFingerprint((const uint8_t *)MQTT_SERVER_FINGERPRINT);
}
#endif
///////////////////////////////////
// To be called before ETH.begin()
WiFi.onEvent(ETH_event);
// start the ethernet connection and the server:
// Use DHCP dynamic IP and random mac
//bool begin(int MISO_GPIO, int MOSI_GPIO, int SCLK_GPIO, int CS_GPIO, int INT_GPIO, int SPI_CLOCK_MHZ,
// int SPI_HOST, uint8_t *W5500_Mac = W5500_Default_Mac);
ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST );
//ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST, mac[millis() % NUMBER_OF_MAC] );
// Static IP, leave without this line to get IP via DHCP
//bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0);
//ETH.config(myIP, myGW, mySN, myDNS);
ESP32_W5500_waitForConnect();
///////////////////////////////////
}
void loop()
{
}

View File

@@ -0,0 +1,76 @@
/****************************************************************************************************************************
defines.h
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
***************************************************************************************************************************************/
#ifndef defines_h
#define defines_h
// Debug Level from 0 to 4
#define _ETHERNET_WEBSERVER_LOGLEVEL_ 1
#define _ASYNC_MQTT_LOGLEVEL_ 1
//////////////////////////////////////////////////////////
// Optional values to override default settings
// Don't change unless you know what you're doing
//#define ETH_SPI_HOST SPI3_HOST
//#define SPI_CLOCK_MHZ 25
// Must connect INT to GPIOxx or not working
//#define INT_GPIO 4
//#define MISO_GPIO 19
//#define MOSI_GPIO 23
//#define SCK_GPIO 18
//#define CS_GPIO 5
//////////////////////////////////////////////////////////
#include <WebServer_ESP32_W5500.h>
/////////////////////////////////////////////
// Enter a MAC address and IP address for your controller below.
#define NUMBER_OF_MAC 20
byte mac[][NUMBER_OF_MAC] =
{
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x01 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x02 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x03 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x04 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x05 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x06 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x07 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x08 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x09 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0A },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0B },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0C },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0D },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0E },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0F },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x10 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x11 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x12 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x13 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x14 },
};
// Select the IP address according to your local network
IPAddress myIP(192, 168, 2, 232);
IPAddress myGW(192, 168, 2, 1);
IPAddress mySN(255, 255, 255, 0);
// Google DNS Server IP
IPAddress myDNS(8, 8, 8, 8);
#endif //defines_h

View File

@@ -0,0 +1,258 @@
/****************************************************************************************************************************
FullyFeature_ESP32_W5500.ino
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
/*
This example uses FreeRTOS softwaretimers as there is no built-in Ticker library
*/
#include "defines.h"
extern "C"
{
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#include <AsyncMQTT_ESP32.h>
//#define MQTT_HOST IPAddress(192, 168, 2, 110)
#define MQTT_HOST "broker.emqx.io" // Broker address
#define MQTT_PORT 1883
const char *PubTopic = "async-mqtt/ESP32_W5500_Pub"; // Topic to publish
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
void connectToMqtt()
{
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void ETH_event(WiFiEvent_t event)
{
switch (event)
{
#if USING_CORE_ESP32_CORE_V200_PLUS
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH starting");
break;
case ARDUINO_EVENT_ETH_CONNECTED:
Serial.println("ETH connected");
break;
case ARDUINO_EVENT_ETH_GOT_IP:
Serial.println("ETH got IP");
Serial.print("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH stops");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#else
case SYSTEM_EVENT_ETH_CONNECTED:
erial.println(F("ETH Connected"));
break;
case SYSTEM_EVENT_ETH_GOT_IP:
Serial.println("ETH connected");
Serial.println("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_ETH_DISCONNECTED:
case SYSTEM_EVENT_ETH_STOP:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#endif
default:
break;
}
}
void printSeparationLine()
{
Serial.println("************************************************");
}
void onMqttConnect(bool sessionPresent)
{
Serial.print("Connected to MQTT broker: ");
Serial.print(MQTT_HOST);
Serial.print(", port: ");
Serial.println(MQTT_PORT);
Serial.print("PubTopic: ");
Serial.println(PubTopic);
printSeparationLine();
Serial.print("Session present: ");
Serial.println(sessionPresent);
uint16_t packetIdSub = mqttClient.subscribe(PubTopic, 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);
mqttClient.publish(PubTopic, 0, true, "ESP32_W5500 Test");
Serial.println("Publishing at QoS 0");
uint16_t packetIdPub1 = mqttClient.publish(PubTopic, 1, true, "test 2");
Serial.print("Publishing at QoS 1, packetId: ");
Serial.println(packetIdPub1);
uint16_t packetIdPub2 = mqttClient.publish(PubTopic, 2, true, "test 3");
Serial.print("Publishing at QoS 2, packetId: ");
Serial.println(packetIdPub2);
printSeparationLine();
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason)
{
(void) reason;
Serial.println("Disconnected from MQTT.");
if (ESP32_W5500_isConnected())
{
xTimerStart(mqttReconnectTimer, 0);
}
}
void onMqttSubscribe(const uint16_t& packetId, const uint8_t& qos)
{
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(const uint16_t& packetId)
{
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void onMqttMessage(char* topic, char* payload, const AsyncMqttClientMessageProperties& properties,
const size_t& len, const size_t& index, const size_t& total)
{
(void) payload;
Serial.println("Publish received.");
Serial.print(" topic: ");
Serial.println(topic);
Serial.print(" qos: ");
Serial.println(properties.qos);
Serial.print(" dup: ");
Serial.println(properties.dup);
Serial.print(" retain: ");
Serial.println(properties.retain);
Serial.print(" len: ");
Serial.println(len);
Serial.print(" index: ");
Serial.println(index);
Serial.print(" total: ");
Serial.println(total);
}
void onMqttPublish(const uint16_t& packetId)
{
Serial.println("Publish acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
delay(500);
Serial.print("\nStarting FullyFeature_ESP32_W5500 on ");
Serial.print(ARDUINO_BOARD);
Serial.println(" with " + String(SHIELD_TYPE));
Serial.println(WEBSERVER_ESP32_W5500_VERSION);
Serial.println(ASYNC_MQTT_ESP32_VERSION);
AMQTT_LOGWARN(F("Default SPI pinout:"));
AMQTT_LOGWARN1(F("SPI_HOST:"), ETH_SPI_HOST);
AMQTT_LOGWARN1(F("MOSI:"), MOSI_GPIO);
AMQTT_LOGWARN1(F("MISO:"), MISO_GPIO);
AMQTT_LOGWARN1(F("SCK:"), SCK_GPIO);
AMQTT_LOGWARN1(F("CS:"), CS_GPIO);
AMQTT_LOGWARN1(F("INT:"), INT_GPIO);
AMQTT_LOGWARN1(F("SPI Clock (MHz):"), SPI_CLOCK_MHZ);
AMQTT_LOGWARN(F("========================="));
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0,
reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
///////////////////////////////////
// To be called before ETH.begin()
WiFi.onEvent(ETH_event);
// start the ethernet connection and the server:
// Use DHCP dynamic IP and random mac
//bool begin(int MISO_GPIO, int MOSI_GPIO, int SCLK_GPIO, int CS_GPIO, int INT_GPIO, int SPI_CLOCK_MHZ,
// int SPI_HOST, uint8_t *W5500_Mac = W5500_Default_Mac);
ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST );
//ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST, mac[millis() % NUMBER_OF_MAC] );
// Static IP, leave without this line to get IP via DHCP
//bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0);
//ETH.config(myIP, myGW, mySN, myDNS);
ESP32_W5500_waitForConnect();
///////////////////////////////////
}
void loop()
{
}

View File

@@ -0,0 +1,76 @@
/****************************************************************************************************************************
defines.h
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
***************************************************************************************************************************************/
#ifndef defines_h
#define defines_h
// Debug Level from 0 to 4
#define _ETHERNET_WEBSERVER_LOGLEVEL_ 1
#define _ASYNC_MQTT_LOGLEVEL_ 1
//////////////////////////////////////////////////////////
// Optional values to override default settings
// Don't change unless you know what you're doing
//#define ETH_SPI_HOST SPI3_HOST
//#define SPI_CLOCK_MHZ 25
// Must connect INT to GPIOxx or not working
//#define INT_GPIO 4
//#define MISO_GPIO 19
//#define MOSI_GPIO 23
//#define SCK_GPIO 18
//#define CS_GPIO 5
//////////////////////////////////////////////////////////
#include <WebServer_ESP32_W5500.h>
/////////////////////////////////////////////
// Enter a MAC address and IP address for your controller below.
#define NUMBER_OF_MAC 20
byte mac[][NUMBER_OF_MAC] =
{
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x01 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x02 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x03 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x04 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x05 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x06 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x07 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x08 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x09 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0A },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0B },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0C },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0D },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0E },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0F },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x10 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x11 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x12 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x13 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x14 },
};
// Select the IP address according to your local network
IPAddress myIP(192, 168, 2, 232);
IPAddress myGW(192, 168, 2, 1);
IPAddress mySN(255, 255, 255, 0);
// Google DNS Server IP
IPAddress myDNS(8, 8, 8, 8);
#endif //defines_h

View File

@@ -0,0 +1,281 @@
/****************************************************************************************************************************
FullyFeatureSSL_ESP32_W6100.ino
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W6100 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "defines.h"
extern "C"
{
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#define ASYNC_TCP_SSL_ENABLED true
//#define ASYNC_TCP_SSL_ENABLED false
#include <AsyncMQTT_ESP32.h>
//#define MQTT_HOST IPAddress(192, 168, 2, 110)
#define MQTT_HOST "broker.emqx.io" // Broker address
#if ASYNC_TCP_SSL_ENABLED
#define MQTT_SECURE true
const uint8_t MQTT_SERVER_FINGERPRINT[] = {0x7e, 0x36, 0x22, 0x01, 0xf9, 0x7e, 0x99, 0x2f, 0xc5, 0xdb, 0x3d, 0xbe, 0xac, 0x48, 0x67, 0x5b, 0x5d, 0x47, 0x94, 0xd2};
const char *PubTopic = "async-mqtt/ESP32_W6100_SSL_Pub"; // Topic to publish
#define MQTT_PORT 8883
#else
const char *PubTopic = "async-mqtt/ESP32_W6100_Pub"; // Topic to publish
#define MQTT_PORT 1883
#endif
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
void connectToMqtt()
{
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void ETH_event(WiFiEvent_t event)
{
switch (event)
{
#if USING_CORE_ESP32_CORE_V200_PLUS
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH starting");
break;
case ARDUINO_EVENT_ETH_CONNECTED:
Serial.println("ETH connected");
break;
case ARDUINO_EVENT_ETH_GOT_IP:
Serial.println("ETH got IP");
Serial.print("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH stops");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#else
case SYSTEM_EVENT_ETH_CONNECTED:
erial.println(F("ETH Connected"));
break;
case SYSTEM_EVENT_ETH_GOT_IP:
Serial.println("ETH connected");
Serial.println("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_ETH_DISCONNECTED:
case SYSTEM_EVENT_ETH_STOP:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#endif
default:
break;
}
}
void printSeparationLine()
{
Serial.println("************************************************");
}
void onMqttConnect(bool sessionPresent)
{
Serial.print("Connected to MQTT broker: ");
Serial.print(MQTT_HOST);
Serial.print(", port: ");
Serial.println(MQTT_PORT);
Serial.print("PubTopic: ");
Serial.println(PubTopic);
printSeparationLine();
Serial.print("Session present: ");
Serial.println(sessionPresent);
uint16_t packetIdSub = mqttClient.subscribe(PubTopic, 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);
mqttClient.publish(PubTopic, 0, true, "ESP32_W6100 Test");
Serial.println("Publishing at QoS 0");
uint16_t packetIdPub1 = mqttClient.publish(PubTopic, 1, true, "test 2");
Serial.print("Publishing at QoS 1, packetId: ");
Serial.println(packetIdPub1);
uint16_t packetIdPub2 = mqttClient.publish(PubTopic, 2, true, "test 3");
Serial.print("Publishing at QoS 2, packetId: ");
Serial.println(packetIdPub2);
printSeparationLine();
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason)
{
(void) reason;
Serial.println("Disconnected from MQTT.");
if (ESP32_W6100_isConnected())
{
xTimerStart(mqttReconnectTimer, 0);
}
}
void onMqttSubscribe(const uint16_t& packetId, const uint8_t& qos)
{
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(const uint16_t& packetId)
{
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void onMqttMessage(char* topic, char* payload, const AsyncMqttClientMessageProperties& properties,
const size_t& len, const size_t& index, const size_t& total)
{
(void) payload;
Serial.println("Publish received.");
Serial.print(" topic: ");
Serial.println(topic);
Serial.print(" qos: ");
Serial.println(properties.qos);
Serial.print(" dup: ");
Serial.println(properties.dup);
Serial.print(" retain: ");
Serial.println(properties.retain);
Serial.print(" len: ");
Serial.println(len);
Serial.print(" index: ");
Serial.println(index);
Serial.print(" total: ");
Serial.println(total);
}
void onMqttPublish(const uint16_t& packetId)
{
Serial.println("Publish acknowledged");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
Serial.print("\nStarting FullyFeatureSSL_ESP32_W6100 on ");
Serial.print(ARDUINO_BOARD);
Serial.println(" with " + String(SHIELD_TYPE));
Serial.println(WEBSERVER_ESP32_W6100_VERSION);
Serial.println(ASYNC_MQTT_ESP32_VERSION);
AMQTT_LOGWARN(F("Default SPI pinout:"));
AMQTT_LOGWARN1(F("SPI_HOST:"), ETH_SPI_HOST);
AMQTT_LOGWARN1(F("MOSI:"), MOSI_GPIO);
AMQTT_LOGWARN1(F("MISO:"), MISO_GPIO);
AMQTT_LOGWARN1(F("SCK:"), SCK_GPIO);
AMQTT_LOGWARN1(F("CS:"), CS_GPIO);
AMQTT_LOGWARN1(F("INT:"), INT_GPIO);
AMQTT_LOGWARN1(F("SPI Clock (MHz):"), SPI_CLOCK_MHZ);
AMQTT_LOGWARN(F("========================="));
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0,
reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
#if ASYNC_TCP_SSL_ENABLED
mqttClient.setSecure(MQTT_SECURE);
if (MQTT_SECURE)
{
//mqttClient.addServerFingerprint((const uint8_t[])MQTT_SERVER_FINGERPRINT);
mqttClient.addServerFingerprint((const uint8_t *)MQTT_SERVER_FINGERPRINT);
}
#endif
///////////////////////////////////
// To be called before ETH.begin()
WiFi.onEvent(ETH_event);
// start the ethernet connection and the server:
// Use DHCP dynamic IP and random mac
//bool begin(int MISO_GPIO, int MOSI_GPIO, int SCLK_GPIO, int CS_GPIO, int INT_GPIO, int SPI_CLOCK_MHZ,
// int SPI_HOST, uint8_t *W6100_Mac = W6100_Default_Mac);
ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST );
//ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST, mac[millis() % NUMBER_OF_MAC] );
// Static IP, leave without this line to get IP via DHCP
//bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0);
//ETH.config(myIP, myGW, mySN, myDNS);
ESP32_W6100_waitForConnect();
///////////////////////////////////
}
void loop()
{
}

View File

@@ -0,0 +1,76 @@
/****************************************************************************************************************************
defines.h
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
***************************************************************************************************************************************/
#ifndef defines_h
#define defines_h
// Debug Level from 0 to 4
#define _ETHERNET_WEBSERVER_LOGLEVEL_ 1
#define _ASYNC_MQTT_LOGLEVEL_ 1
//////////////////////////////////////////////////////////
// Optional values to override default settings
// Don't change unless you know what you're doing
//#define ETH_SPI_HOST SPI3_HOST
//#define SPI_CLOCK_MHZ 25
// Must connect INT to GPIOxx or not working
//#define INT_GPIO 4
//#define MISO_GPIO 19
//#define MOSI_GPIO 23
//#define SCK_GPIO 18
//#define CS_GPIO 5
//////////////////////////////////////////////////////////
#include <WebServer_ESP32_W6100.h>
/////////////////////////////////////////////
// Enter a MAC address and IP address for your controller below.
#define NUMBER_OF_MAC 20
byte mac[][NUMBER_OF_MAC] =
{
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x01 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x02 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x03 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x04 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x05 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x06 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x07 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x08 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x09 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0A },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0B },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0C },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0D },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0E },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0F },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x10 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x11 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x12 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x13 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x14 },
};
// Select the IP address according to your local network
IPAddress myIP(192, 168, 2, 232);
IPAddress myGW(192, 168, 2, 1);
IPAddress mySN(255, 255, 255, 0);
// Google DNS Server IP
IPAddress myDNS(8, 8, 8, 8);
#endif //defines_h

View File

@@ -0,0 +1,258 @@
/****************************************************************************************************************************
FullyFeature_ESP32_W6100.ino
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
/*
This example uses FreeRTOS softwaretimers as there is no built-in Ticker library
*/
#include "defines.h"
extern "C"
{
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#include <AsyncMQTT_ESP32.h>
//#define MQTT_HOST IPAddress(192, 168, 2, 110)
#define MQTT_HOST "broker.emqx.io" // Broker address
#define MQTT_PORT 1883
const char *PubTopic = "async-mqtt/ESP32_W6100_Pub"; // Topic to publish
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
void connectToMqtt()
{
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void ETH_event(WiFiEvent_t event)
{
switch (event)
{
#if USING_CORE_ESP32_CORE_V200_PLUS
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH starting");
break;
case ARDUINO_EVENT_ETH_CONNECTED:
Serial.println("ETH connected");
break;
case ARDUINO_EVENT_ETH_GOT_IP:
Serial.println("ETH got IP");
Serial.print("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH stops");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#else
case SYSTEM_EVENT_ETH_CONNECTED:
erial.println(F("ETH Connected"));
break;
case SYSTEM_EVENT_ETH_GOT_IP:
Serial.println("ETH connected");
Serial.println("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_ETH_DISCONNECTED:
case SYSTEM_EVENT_ETH_STOP:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#endif
default:
break;
}
}
void printSeparationLine()
{
Serial.println("************************************************");
}
void onMqttConnect(bool sessionPresent)
{
Serial.print("Connected to MQTT broker: ");
Serial.print(MQTT_HOST);
Serial.print(", port: ");
Serial.println(MQTT_PORT);
Serial.print("PubTopic: ");
Serial.println(PubTopic);
printSeparationLine();
Serial.print("Session present: ");
Serial.println(sessionPresent);
uint16_t packetIdSub = mqttClient.subscribe(PubTopic, 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);
mqttClient.publish(PubTopic, 0, true, "ESP32_W6100 Test");
Serial.println("Publishing at QoS 0");
uint16_t packetIdPub1 = mqttClient.publish(PubTopic, 1, true, "test 2");
Serial.print("Publishing at QoS 1, packetId: ");
Serial.println(packetIdPub1);
uint16_t packetIdPub2 = mqttClient.publish(PubTopic, 2, true, "test 3");
Serial.print("Publishing at QoS 2, packetId: ");
Serial.println(packetIdPub2);
printSeparationLine();
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason)
{
(void) reason;
Serial.println("Disconnected from MQTT.");
if (ESP32_W6100_isConnected())
{
xTimerStart(mqttReconnectTimer, 0);
}
}
void onMqttSubscribe(const uint16_t& packetId, const uint8_t& qos)
{
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(const uint16_t& packetId)
{
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void onMqttMessage(char* topic, char* payload, const AsyncMqttClientMessageProperties& properties,
const size_t& len, const size_t& index, const size_t& total)
{
(void) payload;
Serial.println("Publish received.");
Serial.print(" topic: ");
Serial.println(topic);
Serial.print(" qos: ");
Serial.println(properties.qos);
Serial.print(" dup: ");
Serial.println(properties.dup);
Serial.print(" retain: ");
Serial.println(properties.retain);
Serial.print(" len: ");
Serial.println(len);
Serial.print(" index: ");
Serial.println(index);
Serial.print(" total: ");
Serial.println(total);
}
void onMqttPublish(const uint16_t& packetId)
{
Serial.println("Publish acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
delay(500);
Serial.print("\nStarting FullyFeature_ESP32_W6100 on ");
Serial.print(ARDUINO_BOARD);
Serial.println(" with " + String(SHIELD_TYPE));
Serial.println(WEBSERVER_ESP32_W6100_VERSION);
Serial.println(ASYNC_MQTT_ESP32_VERSION);
AMQTT_LOGWARN(F("Default SPI pinout:"));
AMQTT_LOGWARN1(F("SPI_HOST:"), ETH_SPI_HOST);
AMQTT_LOGWARN1(F("MOSI:"), MOSI_GPIO);
AMQTT_LOGWARN1(F("MISO:"), MISO_GPIO);
AMQTT_LOGWARN1(F("SCK:"), SCK_GPIO);
AMQTT_LOGWARN1(F("CS:"), CS_GPIO);
AMQTT_LOGWARN1(F("INT:"), INT_GPIO);
AMQTT_LOGWARN1(F("SPI Clock (MHz):"), SPI_CLOCK_MHZ);
AMQTT_LOGWARN(F("========================="));
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0,
reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
///////////////////////////////////
// To be called before ETH.begin()
WiFi.onEvent(ETH_event);
// start the ethernet connection and the server:
// Use DHCP dynamic IP and random mac
//bool begin(int MISO_GPIO, int MOSI_GPIO, int SCLK_GPIO, int CS_GPIO, int INT_GPIO, int SPI_CLOCK_MHZ,
// int SPI_HOST, uint8_t *W6100_Mac = W6100_Default_Mac);
ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST );
//ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST, mac[millis() % NUMBER_OF_MAC] );
// Static IP, leave without this line to get IP via DHCP
//bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0);
//ETH.config(myIP, myGW, mySN, myDNS);
ESP32_W6100_waitForConnect();
///////////////////////////////////
}
void loop()
{
}

View File

@@ -0,0 +1,76 @@
/****************************************************************************************************************************
defines.h
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
***************************************************************************************************************************************/
#ifndef defines_h
#define defines_h
// Debug Level from 0 to 4
#define _ETHERNET_WEBSERVER_LOGLEVEL_ 1
#define _ASYNC_MQTT_LOGLEVEL_ 1
//////////////////////////////////////////////////////////
// Optional values to override default settings
// Don't change unless you know what you're doing
//#define ETH_SPI_HOST SPI3_HOST
//#define SPI_CLOCK_MHZ 25
// Must connect INT to GPIOxx or not working
//#define INT_GPIO 4
//#define MISO_GPIO 19
//#define MOSI_GPIO 23
//#define SCK_GPIO 18
//#define CS_GPIO 5
//////////////////////////////////////////////////////////
#include <WebServer_ESP32_W6100.h>
/////////////////////////////////////////////
// Enter a MAC address and IP address for your controller below.
#define NUMBER_OF_MAC 20
byte mac[][NUMBER_OF_MAC] =
{
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x01 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x02 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x03 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x04 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x05 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x06 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x07 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x08 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x09 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0A },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0B },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0C },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0D },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x0E },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x0F },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x10 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x11 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x12 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x13 },
{ 0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0x14 },
};
// Select the IP address according to your local network
IPAddress myIP(192, 168, 2, 232);
IPAddress myGW(192, 168, 2, 1);
IPAddress mySN(255, 255, 255, 0);
// Google DNS Server IP
IPAddress myDNS(8, 8, 8, 8);
#endif //defines_h

View File

@@ -0,0 +1,271 @@
/****************************************************************************************************************************
FullyFeatureSSL_WT32_ETH01.ino
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "defines.h"
extern "C"
{
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#define ASYNC_TCP_SSL_ENABLED true
//#define ASYNC_TCP_SSL_ENABLED false
#include <AsyncMQTT_ESP32.h>
//#define MQTT_HOST IPAddress(192, 168, 2, 110)
#define MQTT_HOST "broker.emqx.io" // Broker address
#if ASYNC_TCP_SSL_ENABLED
#define MQTT_SECURE true
const uint8_t MQTT_SERVER_FINGERPRINT[] = {0x7e, 0x36, 0x22, 0x01, 0xf9, 0x7e, 0x99, 0x2f, 0xc5, 0xdb, 0x3d, 0xbe, 0xac, 0x48, 0x67, 0x5b, 0x5d, 0x47, 0x94, 0xd2};
const char *PubTopic = "async-mqtt/WT32_ETH01_SSL_Pub"; // Topic to publish
#define MQTT_PORT 8883
#else
const char *PubTopic = "async-mqtt/WT32_ETH01_Pub"; // Topic to publish
#define MQTT_PORT 1883
#endif
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
void connectToMqtt()
{
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void ETH_event(WiFiEvent_t event)
{
switch (event)
{
#if USING_CORE_ESP32_CORE_V200_PLUS
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH starting");
break;
case ARDUINO_EVENT_ETH_CONNECTED:
Serial.println("ETH connected");
break;
case ARDUINO_EVENT_ETH_GOT_IP:
Serial.println("ETH got IP");
Serial.print("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH stops");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#else
case SYSTEM_EVENT_ETH_CONNECTED:
erial.println(F("ETH Connected"));
break;
case SYSTEM_EVENT_ETH_GOT_IP:
Serial.println("ETH connected");
Serial.println("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_ETH_DISCONNECTED:
case SYSTEM_EVENT_ETH_STOP:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#endif
default:
break;
}
}
void printSeparationLine()
{
Serial.println("************************************************");
}
void onMqttConnect(bool sessionPresent)
{
Serial.print("Connected to MQTT broker: ");
Serial.print(MQTT_HOST);
Serial.print(", port: ");
Serial.println(MQTT_PORT);
Serial.print("PubTopic: ");
Serial.println(PubTopic);
printSeparationLine();
Serial.print("Session present: ");
Serial.println(sessionPresent);
uint16_t packetIdSub = mqttClient.subscribe(PubTopic, 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);
mqttClient.publish(PubTopic, 0, true, "WT32_ETH01 Test");
Serial.println("Publishing at QoS 0");
uint16_t packetIdPub1 = mqttClient.publish(PubTopic, 1, true, "test 2");
Serial.print("Publishing at QoS 1, packetId: ");
Serial.println(packetIdPub1);
uint16_t packetIdPub2 = mqttClient.publish(PubTopic, 2, true, "test 3");
Serial.print("Publishing at QoS 2, packetId: ");
Serial.println(packetIdPub2);
printSeparationLine();
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason)
{
(void) reason;
Serial.println("Disconnected from MQTT.");
if (WT32_ETH01_isConnected())
{
xTimerStart(mqttReconnectTimer, 0);
}
}
void onMqttSubscribe(const uint16_t& packetId, const uint8_t& qos)
{
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(const uint16_t& packetId)
{
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void onMqttMessage(char* topic, char* payload, const AsyncMqttClientMessageProperties& properties,
const size_t& len, const size_t& index, const size_t& total)
{
(void) payload;
Serial.println("Publish received.");
Serial.print(" topic: ");
Serial.println(topic);
Serial.print(" qos: ");
Serial.println(properties.qos);
Serial.print(" dup: ");
Serial.println(properties.dup);
Serial.print(" retain: ");
Serial.println(properties.retain);
Serial.print(" len: ");
Serial.println(len);
Serial.print(" index: ");
Serial.println(index);
Serial.print(" total: ");
Serial.println(total);
}
void onMqttPublish(const uint16_t& packetId)
{
Serial.println("Publish acknowledged");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
delay(500);
Serial.print("\nStarting FullyFeatureSSL_WT32_ETH01 on ");
Serial.print(ARDUINO_BOARD);
Serial.println(" with " + String(SHIELD_TYPE));
Serial.println(WEBSERVER_WT32_ETH01_VERSION);
Serial.println(ASYNC_MQTT_ESP32_VERSION);
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0,
reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
#if ASYNC_TCP_SSL_ENABLED
mqttClient.setSecure(MQTT_SECURE);
if (MQTT_SECURE)
{
//mqttClient.addServerFingerprint((const uint8_t[])MQTT_SERVER_FINGERPRINT);
mqttClient.addServerFingerprint((const uint8_t *)MQTT_SERVER_FINGERPRINT);
}
#endif
//////////////////////////////////////////////
// To be called before ETH.begin()
WiFi.onEvent(ETH_event);
//bool begin(uint8_t phy_addr=ETH_PHY_ADDR, int power=ETH_PHY_POWER, int mdc=ETH_PHY_MDC, int mdio=ETH_PHY_MDIO,
// eth_phy_type_t type=ETH_PHY_TYPE, eth_clock_mode_t clk_mode=ETH_CLK_MODE);
//ETH.begin(ETH_PHY_ADDR, ETH_PHY_POWER, ETH_PHY_MDC, ETH_PHY_MDIO, ETH_PHY_TYPE, ETH_CLK_MODE);
ETH.begin(ETH_PHY_ADDR, ETH_PHY_POWER);
// Static IP, leave without this line to get IP via DHCP
//bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0);
//ETH.config(myIP, myGW, mySN, myDNS);
WT32_ETH01_waitForConnect();
//////////////////////////////////////////////
}
void loop()
{
}

View File

@@ -0,0 +1,30 @@
/****************************************************************************************************************************
defines.h
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
***************************************************************************************************************************************/
#ifndef defines_h
#define defines_h
// Debug Level from 0 to 4
#define _ETHERNET_WEBSERVER_LOGLEVEL_ 1
#define _ASYNC_MQTT_LOGLEVEL_ 4
#include <WebServer_WT32_ETH01.h>
// Select the IP address according to your local network
IPAddress myIP(192, 168, 2, 232);
IPAddress myGW(192, 168, 2, 1);
IPAddress mySN(255, 255, 255, 0);
// Google DNS Server IP
IPAddress myDNS(8, 8, 8, 8);
#endif //defines_h

View File

@@ -0,0 +1,244 @@
/****************************************************************************************************************************
FullyFeatureWT32_ETH01_ESP32.ino
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
/*
This example uses FreeRTOS softwaretimers as there is no built-in Ticker library
*/
#include "defines.h"
extern "C"
{
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#include <AsyncMQTT_ESP32.h>
//#define MQTT_HOST IPAddress(192, 168, 2, 110)
#define MQTT_HOST "broker.emqx.io" // Broker address
#define MQTT_PORT 1883
const char *PubTopic = "async-mqtt/WT32_ETH01_Pub"; // Topic to publish
AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
void connectToMqtt()
{
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void ETH_event(WiFiEvent_t event)
{
switch (event)
{
#if USING_CORE_ESP32_CORE_V200_PLUS
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH starting");
break;
case ARDUINO_EVENT_ETH_CONNECTED:
Serial.println("ETH connected");
break;
case ARDUINO_EVENT_ETH_GOT_IP:
Serial.println("ETH got IP");
Serial.print("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH stops");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#else
case SYSTEM_EVENT_ETH_CONNECTED:
erial.println(F("ETH Connected"));
break;
case SYSTEM_EVENT_ETH_GOT_IP:
Serial.println("ETH connected");
Serial.println("IP address: ");
Serial.println(ETH.localIP());
connectToMqtt();
break;
case SYSTEM_EVENT_ETH_DISCONNECTED:
case SYSTEM_EVENT_ETH_STOP:
Serial.println("ETH lost connection");
// ensure we don't reconnect to MQTT when no ETH
xTimerStop(mqttReconnectTimer, 0);
break;
#endif
default:
break;
}
}
void printSeparationLine()
{
Serial.println("************************************************");
}
void onMqttConnect(bool sessionPresent)
{
Serial.print("Connected to MQTT broker: ");
Serial.print(MQTT_HOST);
Serial.print(", port: ");
Serial.println(MQTT_PORT);
Serial.print("PubTopic: ");
Serial.println(PubTopic);
printSeparationLine();
Serial.print("Session present: ");
Serial.println(sessionPresent);
uint16_t packetIdSub = mqttClient.subscribe(PubTopic, 2);
Serial.print("Subscribing at QoS 2, packetId: ");
Serial.println(packetIdSub);
mqttClient.publish(PubTopic, 0, true, "WT32_ETH01 Test");
Serial.println("Publishing at QoS 0");
uint16_t packetIdPub1 = mqttClient.publish(PubTopic, 1, true, "test 2");
Serial.print("Publishing at QoS 1, packetId: ");
Serial.println(packetIdPub1);
uint16_t packetIdPub2 = mqttClient.publish(PubTopic, 2, true, "test 3");
Serial.print("Publishing at QoS 2, packetId: ");
Serial.println(packetIdPub2);
printSeparationLine();
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason)
{
(void) reason;
Serial.println("Disconnected from MQTT.");
if (WT32_ETH01_isConnected())
{
xTimerStart(mqttReconnectTimer, 0);
}
}
void onMqttSubscribe(const uint16_t& packetId, const uint8_t& qos)
{
Serial.println("Subscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
Serial.print(" qos: ");
Serial.println(qos);
}
void onMqttUnsubscribe(const uint16_t& packetId)
{
Serial.println("Unsubscribe acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void onMqttMessage(char* topic, char* payload, const AsyncMqttClientMessageProperties& properties,
const size_t& len, const size_t& index, const size_t& total)
{
(void) payload;
Serial.println("Publish received.");
Serial.print(" topic: ");
Serial.println(topic);
Serial.print(" qos: ");
Serial.println(properties.qos);
Serial.print(" dup: ");
Serial.println(properties.dup);
Serial.print(" retain: ");
Serial.println(properties.retain);
Serial.print(" len: ");
Serial.println(len);
Serial.print(" index: ");
Serial.println(index);
Serial.print(" total: ");
Serial.println(total);
}
void onMqttPublish(const uint16_t& packetId)
{
Serial.println("Publish acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
Serial.print("\nStarting FullyFeature_WT32_ETH01 on ");
Serial.print(ARDUINO_BOARD);
Serial.println(" with " + String(SHIELD_TYPE));
Serial.println(WEBSERVER_WT32_ETH01_VERSION);
Serial.println(ASYNC_MQTT_ESP32_VERSION);
mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0,
reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onSubscribe(onMqttSubscribe);
mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onMessage(onMqttMessage);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
//////////////////////////////////////////////
// To be called before ETH.begin()
WiFi.onEvent(ETH_event);
//bool begin(uint8_t phy_addr=ETH_PHY_ADDR, int power=ETH_PHY_POWER, int mdc=ETH_PHY_MDC, int mdio=ETH_PHY_MDIO,
// eth_phy_type_t type=ETH_PHY_TYPE, eth_clock_mode_t clk_mode=ETH_CLK_MODE);
//ETH.begin(ETH_PHY_ADDR, ETH_PHY_POWER, ETH_PHY_MDC, ETH_PHY_MDIO, ETH_PHY_TYPE, ETH_CLK_MODE);
ETH.begin(ETH_PHY_ADDR, ETH_PHY_POWER);
// Static IP, leave without this line to get IP via DHCP
//bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0);
//ETH.config(myIP, myGW, mySN, myDNS);
WT32_ETH01_waitForConnect();
//////////////////////////////////////////////
}
void loop()
{
}

View File

@@ -0,0 +1,30 @@
/****************************************************************************************************************************
defines.h
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) async-mqtt-client (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
***************************************************************************************************************************************/
#ifndef defines_h
#define defines_h
// Debug Level from 0 to 4
#define _ETHERNET_WEBSERVER_LOGLEVEL_ 1
#define _ASYNC_MQTT_LOGLEVEL_ 1
#include <WebServer_WT32_ETH01.h>
// Select the IP address according to your local network
IPAddress myIP(192, 168, 2, 232);
IPAddress myGW(192, 168, 2, 1);
IPAddress mySN(255, 255, 255, 0);
// Google DNS Server IP
IPAddress myDNS(8, 8, 8, 8);
#endif //defines_h

View File

@@ -0,0 +1,69 @@
#######################################
# Datatypes (KEYWORD1)
#######################################
AsyncMqttClient KEYWORD1
AsyncMqttClientDisconnectReason KEYWORD1
AsyncMqttClientMessageProperties KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
setKeepAlive KEYWORD2
setClientId KEYWORD2
setCleanSession KEYWORD2
setMaxTopicLength KEYWORD2
setCredentials KEYWORD2
setWill KEYWORD2
setServer KEYWORD2
setSecure KEYWORD2
addServerFingerprint KEYWORD2
onConnect KEYWORD2
onDisconnect KEYWORD2
onSubscribe KEYWORD2
onUnsubscribe KEYWORD2
onMessage KEYWORD2
onPublish KEYWORD2
connected KEYWORD2
connect KEYWORD2
disconnect KEYWORD2
subscribe KEYWORD2
unsubscribe KEYWORD2
publish KEYWORD2
clearQueue KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
ASYNC_MQTT_ESP32_SHORT_VERSION LITERAL1
ASYNC_MQTT_ESP32_VERSION LITERAL1
ASYNC_MQTT_ESP32_VERSION_MAJOR LITERAL1
ASYNC_MQTT_ESP32_VERSION_MINOR LITERAL1
ASYNC_MQTT_ESP32_VERSION_PATCH LITERAL1
ASYNC_MQTT_ESP32_VERSION_INT LITERAL1
_ASYNC_MQTT_LOGLEVEL_ LITERAL1
DBG_PORT_AMQTT LITERAL1
ASYNC_TCP_SSL_ENABLED LITERAL1
TCP_DISCONNECTED LITERAL1
MQTT_UNACCEPTABLE_PROTOCOL_VERSION LITERAL1
MQTT_IDENTIFIER_REJECTED LITERAL1
MQTT_SERVER_UNAVAILABLE LITERAL1
MQTT_MALFORMED_CREDENTIALS LITERAL1
MQTT_NOT_AUTHORIZED LITERAL1
USING_CORE_ESP32_CORE_V200_PLUS LITERAL1
MQTT_MIN_FREE_MEMORY LITERAL1
SHA1_SIZE LITERAL1

View File

@@ -0,0 +1,86 @@
{
"name": "AsyncMQTT_ESP32",
"version": "1.10.0",
"keywords": "communication, iot, automation, async, async-tcp, async-tcp-ssl, async-mqtt, mqtt, async-mqtt-client, esp32, esp32-s2, esp32-s3, esp32-c3, wt32-eth01, ethernet, w5500, w6100, enc28j60, lan8720, lwip, lwip-ethernet, lwip-enc28j60, lwip-w5500, lwip-w6100, lwip-lan8720",
"description": "Arduino Library for ESP32/S2/S3/C3 asynchronous MQTT client implementation. This library, ported to support ESP32/S2/S3/C3, WT32_ETH01 (ESP32 + LAN8720), ESP32 using LwIP ENC28J60, W5500, W6100 or LAN8720. Supporting TLS/SSL for MQTTS Client",
"authors":
[
{
"name": "Marvin ROGER",
"url": "https://www.marvinroger.fr"
},
{
"name": "Khoi Hoang",
"url": "https://github.com/khoih-prog",
"email": "khoih.prog@gmail.com",
"maintainer": true
}
],
"repository":
{
"type": "git",
"url": "https://github.com/khoih-prog/AsyncMQTT_ESP32.git"
},
"dependencies":
[
{
"owner": "me-no-dev",
"name": "AsyncTCP",
"version": ">=1.1.1",
"platforms": ["espressif32"]
},
{
"owner": "khoih-prog",
"name": "AsyncTCP_SSL",
"version": ">=1.3.1",
"platforms": "espressif32"
},
{
"owner": "khoih-prog",
"name": "WebServer_WT32_ETH01",
"version": ">=1.5.1",
"platforms": ["espressif32"]
},
{
"owner": "khoih-prog",
"name": "WebServer_ESP32_ENC",
"version": ">=1.5.1",
"platforms": ["espressif32"]
},
{
"owner": "khoih-prog",
"name": "WebServer_ESP32_SC_ENC",
"version": ">=1.2.0",
"platforms": ["espressif32"]
},
{
"owner": "khoih-prog",
"name": "WebServer_ESP32_W5500",
"version": ">=1.5.2",
"platforms": ["espressif32"]
},
{
"owner": "khoih-prog",
"name": "WebServer_ESP32_SC_W5500",
"version": ">=1.2.1",
"platforms": ["espressif32"]
},
{
"owner": "khoih-prog",
"name": "WebServer_ESP32_W6100",
"version": ">=1.5.2",
"platforms": ["espressif32"]
},
{
"owner": "khoih-prog",
"name": "WebServer_ESP32_SC_W6100",
"version": ">=1.2.1",
"platforms": ["espressif32"]
}
],
"license": "MIT",
"frameworks": "*",
"platforms": ["espressif32"],
"examples": "examples/*/*/*.ino",
"headers": ["AsyncMQTT_ESP32.h"]
}

View File

@@ -0,0 +1,12 @@
name=AsyncMQTT_ESP32
version=1.10.0
author=Marvin ROGER,Khoi Hoang <khoih.prog@gmail.com>
maintainer=Khoi Hoang <khoih.prog@gmail.com>
sentence=Arduino Library for ESP32/S2/S3/C3 asynchronous MQTT client implementation
paragraph=This library, ported to support ESP32/S2/S3/C3, WT32_ETH01 (ESP32 + LAN8720), ESP32 using LwIP ENC28J60, W5500, W6100 or LAN8720. Supporting TLS/SSL for MQTTS Client
category=Communication
url=https://github.com/khoih-prog/AsyncMQTT_ESP32
architectures=*
license=MIT
depends=AsyncTCP_SSL, WebServer_WT32_ETH01, WebServer_ESP32_ENC, WebServer_ESP32_W5500, WebServer_ESP32_SC_ENC, WebServer_ESP32_SC_W5500, WebServer_ESP32_W6100, WebServer_ESP32_SC_W6100
includes=AsyncMQTT_ESP32.h

View File

@@ -0,0 +1,183 @@
;PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
platformio]
; ============================================================
; chose environment:
; ESP32
; esp32s2
; esp32s3
; esp32c3
; ============================================================
default_envs = esp32s3
; ============================================================
[env]
; ============================================================
; Serial configuration
; choose upload speed, serial-monitor speed
; ============================================================
upload_speed = 921600
;upload_port = COM11
;monitor_speed = 9600
;monitor_port = COM11
; ============================================================
; Checks for the compatibility with frameworks and dev/platforms
lib_compat_mode = strict
lib_ldf_mode = chain+
;lib_ldf_mode = deep+
; ============================================================
lib_deps =
; PlatformIO 4.x
; AsyncTCP@>=1.1.1
; AsyncTCP_SSL@>=1.3.1
; WebServer_WT32_ETH01@>=1.5.1
; WebServer_ESP32_ENC@>=1.5.1
; WebServer_ESP32_SC_ENC@>=1.2.0
; WebServer_ESP32_W5500@>=1.5.2
; WebServer_ESP32_SC_W5500@>=1.2.1
; WebServer_ESP32_W6100@>=1.5.2
; WebServer_ESP32_SC_W6100@>=1.2.1
; PlatformIO 5.x
me-no-dev/AsyncTCP@>=1.1.1
khoih-prog/AsyncTCP_SSL@>=1.3.1
khoih-prog/WebServer_WT32_ETH01@>=1.5.1
khoih-prog/WebServer_ESP32_ENC@>=1.5.1
khoih-prog/WebServer_ESP32_SC_ENC@>=1.2.0
khoih-prog/WebServer_ESP32_W5500@>=1.5.2
khoih-prog/WebServer_ESP32_SC_W5500@>=1.2.1
khoih-prog/WebServer_ESP32_W6100@>=1.5.2
khoih-prog/WebServer_ESP32_SC_W6100@>=1.2.1
build_flags =
; set your debug output (default=Serial)
; -D DEBUG_ESP_PORT=Serial
; comment the following line to enable WiFi debugging
; -D NDEBUG
; ============================================================
; ============================================================
[env:ESP32]
platform = espressif32
framework = arduino
; ============================================================
; Board configuration
; choose your board by uncommenting one of the following lines
; ============================================================
;board = esp32cam
;board = alksesp32
;board = featheresp32
;board = espea32
;board = bpi-bit
;board = d-duino-32
board = esp32doit-devkit-v1
;board = pocket_32
;board = fm-devkit
;board = pico32
;board = esp32-evb
;board = esp32-gateway
;board = esp32-pro
;board = esp32-poe
;board = oroca_edubot
;board = onehorse32dev
;board = lopy
;board = lopy4
;board = wesp32
;board = esp32thing
;board = sparkfun_lora_gateway_1-channel
;board = ttgo-lora32-v1
;board = ttgo-t-beam
;board = turta_iot_node
;board = lolin_d32
;board = lolin_d32_pro
;board = lolin32
;board = wemosbat
;board = widora-air
;board = xinabox_cw02
;board = iotbusio
;board = iotbusproteus
;board = nina_w10
; ============================================================
[env:esp32s2]
platform = espressif32
framework = arduino
; toolchain download links see
; refer "name": "xtensa-esp32s2-elf-gcc","version": "gcc8_4_0-esp-2021r1" section of
; https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_dev_index.json
; e.g. Windows: https://github.com/espressif/crosstool-NG/releases/download/esp-2021r1/xtensa-esp32s2-elf-gcc8_4_0-esp-2021r1-win32.zip
platform_packages =
toolchain-xtensa32s2@file://C:\Users\Max\Downloads\xtensa-esp32s2-elf
framework-arduinoespressif32@https://github.com/espressif/arduino-esp32.git#a4118ea88987c28aac3a49bcb9cc5d6c0acc6f3f
platformio/tool-esptoolpy @ ~1.30100
framework = arduino
board = esp32dev
board_build.mcu = esp32s2
board_build.partitions = huge_app.csv
board_build.variant = esp32s2
board_build.f_cpu = 240000000L
board_build.f_flash = 80000000L
board_build.flash_mode = qio
board_build.arduino.ldscript = esp32s2_out.ld
build_unflags =
-DARDUINO_ESP32_DEV
-DARDUINO_VARIANT="esp32"
build_flags =
-DARDUINO_ESP32S2_DEV
-DARDUINO_VARIANT="esp32s2"
; ============================================================
[env:esp32s3]
platform = espressif32
framework = arduino
board_build.mcu = esp32s3
board_build.partitions = huge_app.csv
board_build.variant = esp32s3
board_build.f_cpu = 240000000L
board_build.f_flash = 80000000L
board_build.flash_mode = qio
board_build.arduino.ldscript = esp32s3_out.ld
build_unflags =
-DARDUINO_ESP32_DEV
-DARDUINO_VARIANT="esp32"
build_flags =
-DARDUINO_ESP32S3_DEV
-DARDUINO_VARIANT="esp32s3"
; ============================================================
[env:esp32c3]
platform = espressif32
framework = arduino
board_build.mcu = esp32c3
board_build.partitions = huge_app.csv
board_build.variant = esp32c3
board_build.f_cpu = 160000000L
board_build.f_flash = 80000000L
board_build.flash_mode = qio
board_build.arduino.ldscript = esp32c3_out.ld
build_unflags =
-DARDUINO_ESP32_DEV
-DARDUINO_VARIANT="esp32"
build_flags =
-DARDUINO_ESP32S3_DEV
-DARDUINO_VARIANT="esp32c3"
; ============================================================

View File

@@ -0,0 +1,49 @@
#!/bin/bash
#pip install -U platformio
#platformio update
platformio lib -g install AsyncTCP
platformio lib -g install ESPAsyncTCP
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m'
lines=$(find ./examples/ -maxdepth 1 -mindepth 1 -type d)
retval=0
while read line; do
if [[ "$line" != *ESP8266 && "$line" != *ESP32 ]]
then
echo -e "========================== BUILDING $line =========================="
echo -e "${YELLOW}SKIPPING${NC}"
continue
fi
echo -e "========================== BUILDING $line =========================="
if [[ -e "$line/platformio.ini" ]]
then
# skipping
#output=$(platformio ci --lib="." --project-conf="$line/platformio.ini" $line 2>&1)
:
else
if [[ "$line" == *ESP8266 ]]
then
output=$(platformio ci --lib="." --project-conf="scripts/CI/platformio_esp8266.ini" $line 2>&1)
else
output=$(platformio ci --lib="." --project-conf="scripts/CI/platformio_esp32.ini" $line 2>&1)
fi
fi
if [ $? -ne 0 ]; then
echo "$output"
echo -e "Building $line ${RED}FAILED${NC}"
retval=1
else
echo -e "${GREEN}SUCCESS${NC}"
fi
done <<< "$lines"
# cleanup
platformio lib -g uninstall AsyncTCP
platformio lib -g uninstall ESPAsyncTCP
exit "$retval"

View File

@@ -0,0 +1,16 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:esp32]
platform = espressif32
board = esp32dev
framework = arduino
build_flags =
-Wall

View File

@@ -0,0 +1,16 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:esp8266]
platform = espressif8266
board = esp01_1m
framework = arduino
build_flags =
-Wall

View File

@@ -0,0 +1,28 @@
#!/usr/bin/env python
import argparse
import ssl
import hashlib
parser = argparse.ArgumentParser(description='Compute SSL/TLS fingerprints.')
parser.add_argument('--host', required=True)
parser.add_argument('--port', default=8883)
args = parser.parse_args()
print(args.host)
cert_pem = ssl.get_server_certificate((args.host, args.port))
cert_der = ssl.PEM_cert_to_DER_cert(cert_pem)
md5 = hashlib.md5(cert_der).hexdigest()
sha1 = hashlib.sha1(cert_der).hexdigest()
sha256 = hashlib.sha256(cert_der).hexdigest()
print("MD5: " + md5)
print("SHA1: " + sha1)
print("SHA256: " + sha256)
print("\nSHA1 as array initializer:")
print("const uint8_t fingerprint[] = {0x" + ", 0x".join([sha1[i:i+2] for i in range(0, len(sha1), 2)]) + "};")
print("\nSHA1 as function call:")
print("mqttClient.addServerFingerprint((const uint8_t[]){0x" + ", 0x".join([sha1[i:i+2] for i in range(0, len(sha1), 2)]) + "});")

View File

@@ -0,0 +1,30 @@
/****************************************************************************************************************************
AsyncMQTT_ESP32.h
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
Version: 1.10.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.8.0 K Hoang 17/12/2022 Initial coding to port to ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
1.9.0 K Hoang 21/12/2022 Add support to ESP32S2/C3 boards using LwIP W5500 or ENC28J60 Ethernet
1.10.0 K Hoang 09/01/2023 Add support to ESP32 and ESP32S2/S3/C3 boards using LwIP W6100
*****************************************************************************************************************************/
#pragma once
#ifndef ASYNC_MQTT_ESP32_H
#define ASYNC_MQTT_ESP32_H
#include "AsyncMQTT_ESP32.hpp"
#include "AsyncMQTT_ESP32_Impl.h"
#endif // ASYNC_MQTT_ESP32_H

View File

@@ -0,0 +1,277 @@
/****************************************************************************************************************************
AsyncMQTT_ESP32.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
Version: 1.10.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.8.0 K Hoang 17/12/2022 Initial coding to port to ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
1.9.0 K Hoang 21/12/2022 Add support to ESP32S2/C3 boards using LwIP W5500 or ENC28J60 Ethernet
1.10.0 K Hoang 09/01/2023 Add support to ESP32 and ESP32S2/S3/C3 boards using LwIP W6100
*****************************************************************************************************************************/
#pragma once
#ifndef ASYNC_MQTT_ESP32_HPP
#define ASYNC_MQTT_ESP32_HPP
#include <functional>
#include <vector>
#include "Arduino.h"
#ifndef MQTT_MIN_FREE_MEMORY
#define MQTT_MIN_FREE_MEMORY 4096
#endif
/////////////////////////////////////////////////////////
#define ASYNC_MQTT_ESP32_SHORT_VERSION "AsyncMQTT_ESP32 v1.10.0"
/////////////////////////////////////////////////////////
#define ASYNC_MQTT_ESP32_VERSION_MAJOR 1
#define ASYNC_MQTT_ESP32_VERSION_MINOR 10
#define ASYNC_MQTT_ESP32_VERSION_PATCH 0
#define ASYNC_MQTT_ESP32_VERSION_INT 1010000
/////////////////////////////////////////////////////////
#if defined(ESP32)
#if ( ( defined(ESP_ARDUINO_VERSION_MAJOR) && (ESP_ARDUINO_VERSION_MAJOR >= 2) ) && ( ARDUINO_ESP32_GIT_VER != 0x46d5afb1 ) )
#define USING_CORE_ESP32_CORE_V200_PLUS true
#if (_ASYNC_MQTT_LOGLEVEL_ > 3)
#warning Using code for ESP32 core v2.0.0+ in AsyncMQTT_ESP32.hpp
#endif
#define ASYNC_MQTT_ESP32_VERSION (ASYNC_MQTT_ESP32_SHORT_VERSION " for ESP32 core v2.0.0+")
#else
#if (_ASYNC_MQTT_LOGLEVEL_ > 3)
#warning Using code for ESP32 core v1.0.6- in AsyncMQTT_ESP32.hpp
#endif
#define ASYNC_MQTT_ESP32_VERSION (ASYNC_MQTT_ESP32_SHORT_VERSION " for ESP32 core v1.0.6-")
#endif
#if ASYNC_TCP_SSL_ENABLED
#include <AsyncTCP_SSL.h>
#warning ESP32 ASYNC_TCP_SSL_ENABLED
#else
#include <AsyncTCP.h>
#endif
#include <freertos/semphr.h>
/////////////////////////////////////////////////////////
#else
#error This library is currently supporting only ESP32 using WiFi or LwIP Ethernet
#endif
/////////////////////////////////////////////////////////
#if ASYNC_TCP_SSL_ENABLED
#include <tcp_mbedtls.h>
#define SHA1_SIZE 20
#endif
/////////////////////////////////////////////////////////
#define SEMAPHORE_TAKE() xSemaphoreTake(_xSemaphore, portMAX_DELAY)
#define SEMAPHORE_GIVE() xSemaphoreGive(_xSemaphore)
#define GET_FREE_MEMORY() ESP.getMaxAllocHeap()
#include <esp32-hal-log.h>
/////////////////////////////////////////////////////////
#include "AsyncMQTT_ESP32_Debug.h"
#include "AsyncMqttClient/Flags.hpp"
#include "AsyncMqttClient/ParsingInformation.hpp"
#include "AsyncMqttClient/MessageProperties.hpp"
#include "AsyncMqttClient/Helpers.hpp"
#include "AsyncMqttClient/Callbacks.hpp"
#include "AsyncMqttClient/DisconnectReasons.hpp"
#include "AsyncMqttClient/Storage.hpp"
#include "AsyncMqttClient/Packets/Packet.hpp"
#include "AsyncMqttClient/Packets/ConnAckPacket.hpp"
#include "AsyncMqttClient/Packets/PingRespPacket.hpp"
#include "AsyncMqttClient/Packets/SubAckPacket.hpp"
#include "AsyncMqttClient/Packets/UnsubAckPacket.hpp"
#include "AsyncMqttClient/Packets/PublishPacket.hpp"
#include "AsyncMqttClient/Packets/PubRelPacket.hpp"
#include "AsyncMqttClient/Packets/PubAckPacket.hpp"
#include "AsyncMqttClient/Packets/PubRecPacket.hpp"
#include "AsyncMqttClient/Packets/PubCompPacket.hpp"
#include "AsyncMqttClient/Packets/Out/Connect.hpp"
#include "AsyncMqttClient/Packets/Out/PingReq.hpp"
#include "AsyncMqttClient/Packets/Out/PubAck.hpp"
#include "AsyncMqttClient/Packets/Out/Disconn.hpp"
#include "AsyncMqttClient/Packets/Out/Subscribe.hpp"
#include "AsyncMqttClient/Packets/Out/Unsubscribe.hpp"
#include "AsyncMqttClient/Packets/Out/Publish.hpp"
/////////////////////////////////////////////////////////
class AsyncMqttClient
{
public:
AsyncMqttClient();
~AsyncMqttClient();
AsyncMqttClient& setKeepAlive(uint16_t keepAlive);
AsyncMqttClient& setClientId(const char* clientId);
AsyncMqttClient& setCleanSession(bool cleanSession);
AsyncMqttClient& setMaxTopicLength(uint16_t maxTopicLength);
AsyncMqttClient& setCredentials(const char* username, const char* password = nullptr);
AsyncMqttClient& setWill(const char* topic, uint8_t qos, bool retain, const char* payload = nullptr, size_t length = 0);
AsyncMqttClient& setServer(IPAddress ip, uint16_t port);
AsyncMqttClient& setServer(const char* host, uint16_t port);
#if ASYNC_TCP_SSL_ENABLED
AsyncMqttClient& setSecure(bool secure);
AsyncMqttClient& addServerFingerprint(const uint8_t* fingerprint);
#endif
AsyncMqttClient& onConnect(AsyncMqttClientInternals::OnConnectUserCallback callback);
AsyncMqttClient& onDisconnect(AsyncMqttClientInternals::OnDisconnectUserCallback callback);
AsyncMqttClient& onSubscribe(AsyncMqttClientInternals::OnSubscribeUserCallback callback);
AsyncMqttClient& onUnsubscribe(AsyncMqttClientInternals::OnUnsubscribeUserCallback callback);
AsyncMqttClient& onMessage(AsyncMqttClientInternals::OnMessageUserCallback callback);
AsyncMqttClient& onPublish(AsyncMqttClientInternals::OnPublishUserCallback callback);
bool connected() const;
void connect();
void disconnect(bool force = false);
uint16_t subscribe(const char* topic, uint8_t qos);
uint16_t unsubscribe(const char* topic);
uint16_t publish(const char* topic, uint8_t qos, bool retain, const char* payload = nullptr,
size_t length = 0, bool dup = false, uint16_t message_id = 0);
bool clearQueue(); // Not MQTT compliant!
const char* getClientId() const;
private:
#if ASYNC_TCP_SSL_ENABLED
AsyncSSLClient _client;
#else
AsyncClient _client;
#endif
AsyncMqttClientInternals::OutPacket* _head;
AsyncMqttClientInternals::OutPacket* _tail;
size_t _sent;
enum
{
CONNECTING,
CONNECTED,
DISCONNECTING,
DISCONNECTED
} _state;
AsyncMqttClientDisconnectReason _disconnectReason;
uint32_t _lastClientActivity;
uint32_t _lastServerActivity;
uint32_t _lastPingRequestTime;
char _generatedClientId[18 + 1]; // esp8266-abc123, esp32-abcdef123456 or stm32-abcdef123456
IPAddress _ip;
const char* _host;
bool _useIp;
#if ASYNC_TCP_SSL_ENABLED
bool _secure;
#endif
uint16_t _port;
uint16_t _keepAlive;
bool _cleanSession;
const char* _clientId;
const char* _username;
const char* _password;
const char* _willTopic;
const char* _willPayload;
uint16_t _willPayloadLength;
uint8_t _willQos;
bool _willRetain;
#if ASYNC_TCP_SSL_ENABLED
std::vector<std::array<uint8_t, SHA1_SIZE>> _secureServerFingerprints;
#endif
std::vector<AsyncMqttClientInternals::OnConnectUserCallback> _onConnectUserCallbacks;
std::vector<AsyncMqttClientInternals::OnDisconnectUserCallback> _onDisconnectUserCallbacks;
std::vector<AsyncMqttClientInternals::OnSubscribeUserCallback> _onSubscribeUserCallbacks;
std::vector<AsyncMqttClientInternals::OnUnsubscribeUserCallback> _onUnsubscribeUserCallbacks;
std::vector<AsyncMqttClientInternals::OnMessageUserCallback> _onMessageUserCallbacks;
std::vector<AsyncMqttClientInternals::OnPublishUserCallback> _onPublishUserCallbacks;
AsyncMqttClientInternals::ParsingInformation _parsingInformation;
AsyncMqttClientInternals::Packet* _currentParsedPacket;
uint8_t _remainingLengthBufferPosition;
char _remainingLengthBuffer[4];
std::vector<AsyncMqttClientInternals::PendingPubRel> _pendingPubRels;
SemaphoreHandle_t _xSemaphore = nullptr;
void _clear();
void _freeCurrentParsedPacket();
// TCP
void _onConnect();
void _onDisconnect();
// void _onError(int8_t error);
// void _onTimeout();
void _onAck(size_t len);
void _onData(char* data, size_t len);
void _onPoll();
// QUEUE
void _insert(AsyncMqttClientInternals::OutPacket* packet); // for PUBREL
void _addFront(AsyncMqttClientInternals::OutPacket* packet); // for CONNECT
void _addBack(AsyncMqttClientInternals::OutPacket* packet); // all the rest
void _handleQueue();
void _clearQueue(bool keepSessionData);
// MQTT
void _onPingResp();
void _onConnAck(bool sessionPresent, uint8_t connectReturnCode);
void _onSubAck(uint16_t packetId, char status);
void _onUnsubAck(uint16_t packetId);
void _onMessage(char* topic, char* payload, uint8_t qos, bool dup, bool retain, size_t len,
size_t index, size_t total, uint16_t packetId);
void _onPublish(uint16_t packetId, uint8_t qos);
void _onPubRel(uint16_t packetId);
void _onPubAck(uint16_t packetId);
void _onPubRec(uint16_t packetId);
void _onPubComp(uint16_t packetId);
void _sendPing();
#if ASYNC_MQTT_USING_TEENSY41_QNETHERNET
uint8_t* getTeensyMac(uint8_t* _macAddress);
#endif
};
#endif // ASYNC_MQTT_ESP32_HPP

View File

@@ -0,0 +1,103 @@
/****************************************************************************************************************************
AsyncMQTT_ESP32_Debug.h
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
Version: 1.10.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.8.0 K Hoang 17/12/2022 Initial coding to port to ESP32 boards using WiFi or LwIP W5500, LAN8720 or ENC28J60
1.9.0 K Hoang 21/12/2022 Add support to ESP32S2/C3 boards using LwIP W5500 or ENC28J60 Ethernet
1.10.0 K Hoang 09/01/2023 Add support to ESP32 and ESP32S2/S3/C3 boards using LwIP W6100
*****************************************************************************************************************************/
#pragma once
#ifndef ASYNC_MQTT_ESP32_DEBUG_H
#define ASYNC_MQTT_ESP32_DEBUG_H
#ifdef ASYNC_MQTT_DEBUG_PORT
#define DBG_PORT_AMQTT ASYNC_MQTT_DEBUG_PORT
#else
#define DBG_PORT_AMQTT Serial
#endif
// Change _ASYNC_MQTT_LOGLEVEL_ to set tracing and logging verbosity
// 0: DISABLED: no logging
// 1: ERROR: errors
// 2: WARN: errors and warnings
// 3: INFO: errors, warnings and informational (default)
// 4: DEBUG: errors, warnings, informational and debug
#ifndef _ASYNC_MQTT_LOGLEVEL_
#define _ASYNC_MQTT_LOGLEVEL_ 1
#endif
/////////////////////////////////////////////////////////
#define AMQTT_PRINT_MARK AMQTT_PRINT("[AMQTT] ")
#define AMQTT_PRINT_SP DBG_PORT_AMQTT.print(" ")
#define AMQTT_PRINT_SP0X DBG_PORT_AMQTT.print(" 0x")
#define AMQTT_PRINT DBG_PORT_AMQTT.print
#define AMQTT_PRINTLN DBG_PORT_AMQTT.println
#define AMQTT_PRINTF DBG_PORT_AMQTT.printf
/////////////////////////////////////////////////////////
#define AMQTT_DEBUG(...) if(_ASYNC_MQTT_LOGLEVEL_>3) { AMQTT_PRINTF(__VA_ARGS__); }
#define AMQTT_SSL_DEBUG(...) if(_ASYNC_MQTT_LOGLEVEL_>3) { AMQTT_PRINTF(__VA_ARGS__); }
#define AMQTT_ASSERT( a ) do{ if(!(a)){AMQTT_PRINTF("ASSERT: %s %u \n", __FILE__, __LINE__);}}while(0)
/////////////////////////////////////////////////////////
#define AMQTT_LOGERROR(x) if(_ASYNC_MQTT_LOGLEVEL_>0) { AMQTT_PRINT_MARK; AMQTT_PRINTLN(x); }
#define AMQTT_LOGERROR0(x) if(_ASYNC_MQTT_LOGLEVEL_>0) { AMQTT_PRINT(x); }
#define AMQTT_LOGERROR1(x,y) if(_ASYNC_MQTT_LOGLEVEL_>0) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP; AMQTT_PRINTLN(y); }
#define AMQTT_HEXLOGERROR1(x,y) if(_ASYNC_MQTT_LOGLEVEL_>0) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP0X; AMQTT_PRINTLN(y, HEX); }
#define AMQTT_LOGERROR2(x,y,z) if(_ASYNC_MQTT_LOGLEVEL_>0) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP; AMQTT_PRINT(y); AMQTT_PRINT_SP; AMQTT_PRINTLN(z); }
#define AMQTT_HEXLOGERROR2(x,y,z) if(_ASYNC_MQTT_LOGLEVEL_>0) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP0X; AMQTT_PRINT(y, HEX); AMQTT_PRINT_SP0X; AMQTT_PRINTLN(z, HEX); }
#define AMQTT_LOGERROR3(x,y,z,w) if(_ASYNC_MQTT_LOGLEVEL_>0) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP; AMQTT_PRINT(y); AMQTT_PRINT_SP; AMQTT_PRINT(z); AMQTT_PRINT_SP; AMQTT_PRINTLN(w); }
/////////////////////////////////////////////////////////
#define AMQTT_LOGWARN(x) if(_ASYNC_MQTT_LOGLEVEL_>1) { AMQTT_PRINT_MARK; AMQTT_PRINTLN(x); }
#define AMQTT_LOGWARN0(x) if(_ASYNC_MQTT_LOGLEVEL_>1) { AMQTT_PRINT(x); }
#define AMQTT_LOGWARN1(x,y) if(_ASYNC_MQTT_LOGLEVEL_>1) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP; AMQTT_PRINTLN(y); }
#define AMQTT_HEXLOGWARN1(x,y) if(_ASYNC_MQTT_LOGLEVEL_>1) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP0X; AMQTT_PRINTLN(y, HEX); }
#define AMQTT_LOGWARN2(x,y,z) if(_ASYNC_MQTT_LOGLEVEL_>1) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP; AMQTT_PRINT(y); AMQTT_PRINT_SP; AMQTT_PRINTLN(z); }
#define AMQTT_HEXLOGWARN2(x,y,z) if(_ASYNC_MQTT_LOGLEVEL_>1) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP0X; AMQTT_PRINT(y, HEX); AMQTT_PRINT_SP0X; AMQTT_PRINTLN(z, HEX); }
#define AMQTT_LOGWARN3(x,y,z,w) if(_ASYNC_MQTT_LOGLEVEL_>1) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP; AMQTT_PRINT(y); AMQTT_PRINT_SP; AMQTT_PRINT(z); AMQTT_PRINT_SP; AMQTT_PRINTLN(w); }
/////////////////////////////////////////////////////////
#define AMQTT_LOGINFO(x) if(_ASYNC_MQTT_LOGLEVEL_>2) { AMQTT_PRINT_MARK; AMQTT_PRINTLN(x); }
#define AMQTT_LOGINFO0(x) if(_ASYNC_MQTT_LOGLEVEL_>2) { AMQTT_PRINT(x); }
#define AMQTT_LOGINFO1(x,y) if(_ASYNC_MQTT_LOGLEVEL_>2) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP; AMQTT_PRINTLN(y); }
#define AMQTT_HEXLOGINFO1(x,y) if(_ASYNC_MQTT_LOGLEVEL_>2) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP0X; AMQTT_PRINTLN(y, HEX); }
#define AMQTT_LOGINFO2(x,y,z) if(_ASYNC_MQTT_LOGLEVEL_>2) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP; AMQTT_PRINT(y); AMQTT_PRINT_SP; AMQTT_PRINTLN(z); }
#define AMQTT_HEXLOGINFO2(x,y,z) if(_ASYNC_MQTT_LOGLEVEL_>2) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP0X; AMQTT_PRINT(y, HEX); AMQTT_PRINT_SP0X; AMQTT_PRINTLN(z, HEX); }
#define AMQTT_LOGINFO3(x,y,z,w) if(_ASYNC_MQTT_LOGLEVEL_>2) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP; AMQTT_PRINT(y); AMQTT_PRINT_SP; AMQTT_PRINT(z); AMQTT_PRINT_SP; AMQTT_PRINTLN(w); }
/////////////////////////////////////////////////////////
#define AMQTT_LOGDEBUG(x) if(_ASYNC_MQTT_LOGLEVEL_>3) { AMQTT_PRINT_MARK; AMQTT_PRINTLN(x); }
#define AMQTT_LOGDEBUG0(x) if(_ASYNC_MQTT_LOGLEVEL_>3) { AMQTT_PRINT(x); }
#define AMQTT_LOGDEBUG1(x,y) if(_ASYNC_MQTT_LOGLEVEL_>3) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP; AMQTT_PRINTLN(y); }
#define AMQTT_HEXLOGDEBUG1(x,y) if(_ASYNC_MQTT_LOGLEVEL_>3) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP0X; AMQTT_PRINTLN(y, HEX); }
#define AMQTT_LOGDEBUG2(x,y,z) if(_ASYNC_MQTT_LOGLEVEL_>3) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP; AMQTT_PRINT(y); AMQTT_PRINT_SP; AMQTT_PRINTLN(z); }
#define AMQTT_HEXLOGDEBUG2(x,y,z) if(_ASYNC_MQTT_LOGLEVEL_>3) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP0X; AMQTT_PRINT(y, HEX); AMQTT_PRINT_SP0X; AMQTT_PRINTLN(z, HEX); }
#define AMQTT_LOGDEBUG3(x,y,z,w) if(_ASYNC_MQTT_LOGLEVEL_>3) { AMQTT_PRINT_MARK; AMQTT_PRINT(x); AMQTT_PRINT_SP; AMQTT_PRINT(y); AMQTT_PRINT_SP; AMQTT_PRINT(z); AMQTT_PRINT_SP; AMQTT_PRINTLN(w); }
/////////////////////////////////////////////////////////
#endif //ASYNC_MQTT_ESP32_DEBUG_H

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,49 @@
/****************************************************************************************************************************
Callbacks.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef CALLBACKS_HPP
#define CALLBACKS_HPP
#include <functional>
#include "DisconnectReasons.hpp"
#include "MessageProperties.hpp"
#include "Errors.hpp"
namespace AsyncMqttClientInternals
{
// user callbacks
typedef std::function<void(bool sessionPresent)> OnConnectUserCallback;
typedef std::function<void(AsyncMqttClientDisconnectReason reason)> OnDisconnectUserCallback;
typedef std::function<void(uint16_t packetId, uint8_t qos)> OnSubscribeUserCallback;
typedef std::function<void(uint16_t packetId)> OnUnsubscribeUserCallback;
typedef std::function<void(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total)> OnMessageUserCallback;
typedef std::function<void(uint16_t packetId)> OnPublishUserCallback;
typedef std::function<void(uint16_t packetId, AsyncMqttClientError error)> OnErrorUserCallback;
// internal callbacks
typedef std::function<void(bool sessionPresent, uint8_t connectReturnCode)> OnConnAckInternalCallback;
typedef std::function<void()> OnPingRespInternalCallback;
typedef std::function<void(uint16_t packetId, char status)> OnSubAckInternalCallback;
typedef std::function<void(uint16_t packetId)> OnUnsubAckInternalCallback;
typedef std::function<void(char* topic, char* payload, uint8_t qos, bool dup, bool retain, size_t len, size_t index, size_t total, uint16_t packetId)> OnMessageInternalCallback;
typedef std::function<void(uint16_t packetId, uint8_t qos)> OnPublishInternalCallback;
typedef std::function<void(uint16_t packetId)> OnPubRelInternalCallback;
typedef std::function<void(uint16_t packetId)> OnPubAckInternalCallback;
typedef std::function<void(uint16_t packetId)> OnPubRecInternalCallback;
typedef std::function<void(uint16_t packetId)> OnPubCompInternalCallback;
} // namespace AsyncMqttClientInternals
#endif // CALLBACKS_HPP

View File

@@ -0,0 +1,34 @@
/****************************************************************************************************************************
DisconnectReasons.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef DISCONNECT_REASONS_HPP
#define DISCONNECT_REASONS_HPP
enum class AsyncMqttClientDisconnectReason : uint8_t
{
TCP_DISCONNECTED = 0,
MQTT_UNACCEPTABLE_PROTOCOL_VERSION = 1,
MQTT_IDENTIFIER_REJECTED = 2,
MQTT_SERVER_UNAVAILABLE = 3,
MQTT_MALFORMED_CREDENTIALS = 4,
MQTT_NOT_AUTHORIZED = 5,
ESP8266_NOT_ENOUGH_SPACE = 6,
TLS_BAD_FINGERPRINT = 7
};
#endif // DISCONNECT_REASONS_HPP

View File

@@ -0,0 +1,25 @@
/****************************************************************************************************************************
Errors.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef ERRORS_HPP
#define ERRORS_HPP
enum class AsyncMqttClientError : uint8_t
{
MAX_RETRIES = 0,
OUT_OF_MEMORY = 1
};
#endif // ERRORS_HPP

View File

@@ -0,0 +1,79 @@
/****************************************************************************************************************************
Flags.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef FLAGS_HPP
#define FLAGS_HPP
namespace AsyncMqttClientInternals
{
constexpr struct
{
const uint8_t RESERVED = 0;
const uint8_t CONNECT = 1;
const uint8_t CONNACK = 2;
const uint8_t PUBLISH = 3;
const uint8_t PUBACK = 4;
const uint8_t PUBREC = 5;
const uint8_t PUBREL = 6;
const uint8_t PUBCOMP = 7;
const uint8_t SUBSCRIBE = 8;
const uint8_t SUBACK = 9;
const uint8_t UNSUBSCRIBE = 10;
const uint8_t UNSUBACK = 11;
const uint8_t PINGREQ = 12;
const uint8_t PINGRESP = 13;
const uint8_t DISCONNECT = 14;
const uint8_t RESERVED2 = 15;
} PacketType;
constexpr struct
{
const uint8_t CONNECT_RESERVED = 0x00;
const uint8_t CONNACK_RESERVED = 0x00;
const uint8_t PUBLISH_DUP = 0x08;
const uint8_t PUBLISH_QOS0 = 0x00;
const uint8_t PUBLISH_QOS1 = 0x02;
const uint8_t PUBLISH_QOS2 = 0x04;
const uint8_t PUBLISH_QOSRESERVED = 0x06;
const uint8_t PUBLISH_RETAIN = 0x01;
const uint8_t PUBACK_RESERVED = 0x00;
const uint8_t PUBREC_RESERVED = 0x00;
const uint8_t PUBREL_RESERVED = 0x02;
const uint8_t PUBCOMP_RESERVED = 0x00;
const uint8_t SUBSCRIBE_RESERVED = 0x02;
const uint8_t SUBACK_RESERVED = 0x00;
const uint8_t UNSUBSCRIBE_RESERVED = 0x02;
const uint8_t UNSUBACK_RESERVED = 0x00;
const uint8_t PINGREQ_RESERVED = 0x00;
const uint8_t PINGRESP_RESERVED = 0x00;
const uint8_t DISCONNECT_RESERVED = 0x00;
const uint8_t RESERVED2_RESERVED = 0x00;
} HeaderFlag;
constexpr struct
{
const uint8_t USERNAME = 0x80;
const uint8_t PASSWORD = 0x40;
const uint8_t WILL_RETAIN = 0x20;
const uint8_t WILL_QOS0 = 0x00;
const uint8_t WILL_QOS1 = 0x08;
const uint8_t WILL_QOS2 = 0x10;
const uint8_t WILL = 0x04;
const uint8_t CLEAN_SESSION = 0x02;
const uint8_t RESERVED = 0x00;
} ConnectFlag;
} // namespace AsyncMqttClientInternals
#endif // FLAGS_HPP

View File

@@ -0,0 +1,66 @@
/****************************************************************************************************************************
Helpers.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef HELPERS_HPP
#define HELPERS_HPP
namespace AsyncMqttClientInternals
{
class Helpers
{
public:
static uint32_t decodeRemainingLength(char* bytes)
{
uint32_t multiplier = 1;
uint32_t value = 0;
uint8_t currentByte = 0;
uint8_t encodedByte;
do
{
encodedByte = bytes[currentByte++];
value += (encodedByte & 127) * multiplier;
multiplier *= 128;
} while ((encodedByte & 128) != 0);
return value;
}
static uint8_t encodeRemainingLength(uint32_t remainingLength, char* destination)
{
uint8_t currentByte = 0;
uint8_t bytesNeeded = 0;
do
{
uint8_t encodedByte = remainingLength % 128;
remainingLength /= 128;
if (remainingLength > 0)
{
encodedByte = encodedByte | 128;
}
destination[currentByte++] = encodedByte;
bytesNeeded++;
} while (remainingLength > 0);
return bytesNeeded;
}
};
} // namespace AsyncMqttClientInternals
#endif // HELPERS_HPP

View File

@@ -0,0 +1,26 @@
/****************************************************************************************************************************
MessageProperties.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef MESSAGE_PROPERTIES_HPP
#define MESSAGE_PROPERTIES_HPP
struct AsyncMqttClientMessageProperties
{
uint8_t qos;
bool dup;
bool retain;
};
#endif // MESSAGE_PROPERTIES_HPP

View File

@@ -0,0 +1,54 @@
/****************************************************************************************************************************
ConnAckPacket.cpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "ConnAckPacket.hpp"
using AsyncMqttClientInternals::ConnAckPacket;
ConnAckPacket::ConnAckPacket(ParsingInformation* parsingInformation, OnConnAckInternalCallback callback)
: _parsingInformation(parsingInformation)
, _callback(callback)
, _bytePosition(0)
, _sessionPresent(false)
, _connectReturnCode(0)
{
}
ConnAckPacket::~ConnAckPacket()
{
}
void ConnAckPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition)
{
(void)len;
char currentByte = data[(*currentBytePosition)++];
if (_bytePosition++ == 0)
{
_sessionPresent = (currentByte << 7) >> 7;
}
else
{
_connectReturnCode = currentByte;
_parsingInformation->bufferState = BufferState::NONE;
_callback(_sessionPresent, _connectReturnCode);
}
}
void ConnAckPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition)
{
(void)data;
(void)len;
(void)currentBytePosition;
}

View File

@@ -0,0 +1,45 @@
/****************************************************************************************************************************
ConnAckPacket.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef CONN_ACK_PACKET_HPP
#define CONN_ACK_PACKET_HPP
#include "Arduino.h"
#include "Packet.hpp"
#include "../ParsingInformation.hpp"
#include "../Callbacks.hpp"
namespace AsyncMqttClientInternals
{
class ConnAckPacket : public Packet
{
public:
explicit ConnAckPacket(ParsingInformation* parsingInformation, OnConnAckInternalCallback callback);
~ConnAckPacket();
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
private:
ParsingInformation* _parsingInformation;
OnConnAckInternalCallback _callback;
uint8_t _bytePosition;
bool _sessionPresent;
uint8_t _connectReturnCode;
};
} // namespace AsyncMqttClientInternals
#endif // CONN_ACK_PACKET_HPP

View File

@@ -0,0 +1,223 @@
/****************************************************************************************************************************
Connect.cpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "Connect.hpp"
using AsyncMqttClientInternals::ConnectOutPacket;
ConnectOutPacket::ConnectOutPacket(bool cleanSession,
const char* username,
const char* password,
const char* willTopic,
bool willRetain,
uint8_t willQos,
const char* willPayload,
uint16_t willPayloadLength,
uint16_t keepAlive,
const char* clientId)
{
char fixedHeader[5];
fixedHeader[0] = AsyncMqttClientInternals::PacketType.CONNECT;
fixedHeader[0] = fixedHeader[0] << 4;
fixedHeader[0] = fixedHeader[0] | AsyncMqttClientInternals::HeaderFlag.CONNECT_RESERVED;
uint16_t protocolNameLength = 4;
char protocolNameLengthBytes[2];
protocolNameLengthBytes[0] = protocolNameLength >> 8;
protocolNameLengthBytes[1] = protocolNameLength & 0xFF;
char protocolLevel[1];
protocolLevel[0] = 0x04;
char connectFlags[1];
connectFlags[0] = 0;
if (cleanSession)
connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.CLEAN_SESSION;
if (username != nullptr)
connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.USERNAME;
if (password != nullptr)
connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.PASSWORD;
if (willTopic != nullptr)
{
connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.WILL;
if (willRetain)
connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.WILL_RETAIN;
switch (willQos)
{
case 0:
connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.WILL_QOS0;
break;
case 1:
connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.WILL_QOS1;
break;
case 2:
connectFlags[0] |= AsyncMqttClientInternals::ConnectFlag.WILL_QOS2;
break;
}
}
char keepAliveBytes[2];
keepAliveBytes[0] = keepAlive >> 8;
keepAliveBytes[1] = keepAlive & 0xFF;
uint16_t clientIdLength = strlen(clientId);
char clientIdLengthBytes[2];
clientIdLengthBytes[0] = clientIdLength >> 8;
clientIdLengthBytes[1] = clientIdLength & 0xFF;
// Optional fields
uint16_t willTopicLength = 0;
char willTopicLengthBytes[2];
char willPayloadLengthBytes[2];
if (willTopic != nullptr)
{
willTopicLength = strlen(willTopic);
willTopicLengthBytes[0] = willTopicLength >> 8;
willTopicLengthBytes[1] = willTopicLength & 0xFF;
if (willPayload != nullptr && willPayloadLength == 0)
willPayloadLength = strlen(willPayload);
willPayloadLengthBytes[0] = willPayloadLength >> 8;
willPayloadLengthBytes[1] = willPayloadLength & 0xFF;
}
uint16_t usernameLength = 0;
char usernameLengthBytes[2];
if (username != nullptr)
{
usernameLength = strlen(username);
usernameLengthBytes[0] = usernameLength >> 8;
usernameLengthBytes[1] = usernameLength & 0xFF;
}
uint16_t passwordLength = 0;
char passwordLengthBytes[2];
if (password != nullptr)
{
passwordLength = strlen(password);
passwordLengthBytes[0] = passwordLength >> 8;
passwordLengthBytes[1] = passwordLength & 0xFF;
}
uint32_t remainingLength = 2 + protocolNameLength + 1 + 1 + 2 + 2 + clientIdLength; // always present
if (willTopic != nullptr)
remainingLength += 2 + willTopicLength + 2 + willPayloadLength;
if (username != nullptr)
remainingLength += 2 + usernameLength;
if (password != nullptr)
remainingLength += 2 + passwordLength;
uint8_t remainingLengthLength = AsyncMqttClientInternals::Helpers::encodeRemainingLength(remainingLength,
fixedHeader + 1);
uint32_t neededSpace = 1 + remainingLengthLength;
neededSpace += 2;
neededSpace += protocolNameLength;
neededSpace += 1;
neededSpace += 1;
neededSpace += 2;
neededSpace += 2;
neededSpace += clientIdLength;
if (willTopic != nullptr)
{
neededSpace += 2;
neededSpace += willTopicLength;
neededSpace += 2;
if (willPayload != nullptr)
neededSpace += willPayloadLength;
}
if (username != nullptr)
{
neededSpace += 2;
neededSpace += usernameLength;
}
if (password != nullptr)
{
neededSpace += 2;
neededSpace += passwordLength;
}
_data.reserve(neededSpace);
_data.insert(_data.end(), fixedHeader, fixedHeader + 1 + remainingLengthLength);
_data.push_back(protocolNameLengthBytes[0]);
_data.push_back(protocolNameLengthBytes[1]);
_data.push_back('M');
_data.push_back('Q');
_data.push_back('T');
_data.push_back('T');
_data.push_back(protocolLevel[0]);
_data.push_back(connectFlags[0]);
_data.push_back(keepAliveBytes[0]);
_data.push_back(keepAliveBytes[1]);
_data.push_back(clientIdLengthBytes[0]);
_data.push_back(clientIdLengthBytes[1]);
_data.insert(_data.end(), clientId, clientId + clientIdLength);
if (willTopic != nullptr)
{
_data.insert(_data.end(), willTopicLengthBytes, willTopicLengthBytes + 2);
_data.insert(_data.end(), willTopic, willTopic + willTopicLength);
_data.insert(_data.end(), willPayloadLengthBytes, willPayloadLengthBytes + 2);
if (willPayload != nullptr)
_data.insert(_data.end(), willPayload, willPayload + willPayloadLength);
}
if (username != nullptr)
{
_data.insert(_data.end(), usernameLengthBytes, usernameLengthBytes + 2);
_data.insert(_data.end(), username, username + usernameLength);
}
if (password != nullptr)
{
_data.insert(_data.end(), passwordLengthBytes, passwordLengthBytes + 2);
_data.insert(_data.end(), password, password + passwordLength);
}
}
const uint8_t* ConnectOutPacket::data(size_t index) const
{
return &_data.data()[index];
}
size_t ConnectOutPacket::size() const
{
return _data.size();
}

View File

@@ -0,0 +1,49 @@
/****************************************************************************************************************************
Connect.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef CONNECT_HPP
#define CONNECT_HPP
#include <vector>
#include <cstring> // strlen
#include "OutPacket.hpp"
#include "../../Flags.hpp"
#include "../../Helpers.hpp"
namespace AsyncMqttClientInternals
{
class ConnectOutPacket : public OutPacket
{
public:
ConnectOutPacket(bool cleanSession,
const char* username,
const char* password,
const char* willTopic,
bool willRetain,
uint8_t willQos,
const char* willPayload,
uint16_t willPayloadLength,
uint16_t keepAlive,
const char* clientId);
const uint8_t* data(size_t index = 0) const;
size_t size() const;
private:
std::vector<uint8_t> _data;
};
} // namespace AsyncMqttClientInternals
#endif // CONNECT_HPP

View File

@@ -0,0 +1,34 @@
/****************************************************************************************************************************
Disconn.cpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "Disconn.hpp"
using AsyncMqttClientInternals::DisconnOutPacket;
DisconnOutPacket::DisconnOutPacket()
{
_data[0] = AsyncMqttClientInternals::PacketType.DISCONNECT;
_data[0] = _data[0] << 4;
_data[0] = _data[0] | AsyncMqttClientInternals::HeaderFlag.DISCONNECT_RESERVED;
_data[1] = 0;
}
const uint8_t* DisconnOutPacket::data(size_t index) const
{
return &_data[index];
}
size_t DisconnOutPacket::size() const
{
return 2;
}

View File

@@ -0,0 +1,37 @@
/****************************************************************************************************************************
Disconn.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef DISCONN_HPP
#define DISCONN_HPP
#include "OutPacket.hpp"
#include "../../Flags.hpp"
#include "../../Helpers.hpp"
namespace AsyncMqttClientInternals
{
class DisconnOutPacket : public OutPacket
{
public:
DisconnOutPacket();
const uint8_t* data(size_t index = 0) const;
size_t size() const;
private:
uint8_t _data[2];
};
} // namespace AsyncMqttClientInternals
#endif // DISCONN_HPP

View File

@@ -0,0 +1,67 @@
/****************************************************************************************************************************
OutPacket.cpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "OutPacket.hpp"
using AsyncMqttClientInternals::OutPacket;
OutPacket::OutPacket()
: next(nullptr)
, timeout(0)
, noTries(0)
, _released(true)
, _packetId(0) {}
OutPacket::~OutPacket() {}
bool OutPacket::released() const
{
return _released;
}
uint8_t OutPacket::packetType() const
{
return data(0)[0] >> 4;
}
uint16_t OutPacket::packetId() const
{
return _packetId;
}
uint8_t OutPacket::qos() const
{
if (packetType() == AsyncMqttClientInternals::PacketType.PUBLISH)
{
return (data()[1] & 0x06) >> 1;
}
return 0;
}
void OutPacket::release()
{
_released = true;
}
uint16_t OutPacket::_nextPacketId = 0;
uint16_t OutPacket::_getNextPacketId()
{
if (++_nextPacketId == 0)
{
++_nextPacketId;
}
return _nextPacketId;
}

View File

@@ -0,0 +1,55 @@
/****************************************************************************************************************************
OutPacket.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef OUT_PACKET_HPP
#define OUT_PACKET_HPP
#include <stdint.h> // uint*_t
#include <stddef.h> // size_t
#include <algorithm> // std::min
#include "../../Flags.hpp"
namespace AsyncMqttClientInternals
{
class OutPacket
{
public:
OutPacket();
virtual ~OutPacket();
virtual const uint8_t* data(size_t index = 0) const = 0;
virtual size_t size() const = 0;
bool released() const;
uint8_t packetType() const;
uint16_t packetId() const;
uint8_t qos() const;
void release();
public:
OutPacket* next;
uint32_t timeout;
uint8_t noTries;
protected:
static uint16_t _getNextPacketId();
bool _released;
uint16_t _packetId;
private:
static uint16_t _nextPacketId;
};
} // namespace AsyncMqttClientInternals
#endif // OUT_PACKET_HPP

View File

@@ -0,0 +1,34 @@
/****************************************************************************************************************************
PingReq.cpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "PingReq.hpp"
using AsyncMqttClientInternals::PingReqOutPacket;
PingReqOutPacket::PingReqOutPacket()
{
_data[0] = AsyncMqttClientInternals::PacketType.PINGREQ;
_data[0] = _data[0] << 4;
_data[0] = _data[0] | AsyncMqttClientInternals::HeaderFlag.PINGREQ_RESERVED;
_data[1] = 0;
}
const uint8_t* PingReqOutPacket::data(size_t index) const
{
return &_data[index];;
}
size_t PingReqOutPacket::size() const
{
return 2;
}

View File

@@ -0,0 +1,37 @@
/****************************************************************************************************************************
PingReq.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef PING_REQ_HPP
#define PING_REQ_HPP
#include "OutPacket.hpp"
#include "../../Flags.hpp"
#include "../../Helpers.hpp"
namespace AsyncMqttClientInternals
{
class PingReqOutPacket : public OutPacket
{
public:
PingReqOutPacket();
const uint8_t* data(size_t index = 0) const;
size_t size() const;
private:
uint8_t _data[2];
};
} // namespace AsyncMqttClientInternals
#endif // PING_REQ_HPP

View File

@@ -0,0 +1,43 @@
/****************************************************************************************************************************
PubAck.cpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "PubAck.hpp"
using AsyncMqttClientInternals::PubAckOutPacket;
PubAckOutPacket::PubAckOutPacket(PendingAck pendingAck)
{
_data[0] = pendingAck.packetType;
_data[0] = _data[0] << 4;
_data[0] = _data[0] | pendingAck.headerFlag;
_data[1] = 2;
_packetId = pendingAck.packetId;
_data[2] = pendingAck.packetId >> 8;
_data[3] = pendingAck.packetId & 0xFF;
if (packetType() == AsyncMqttClientInternals::PacketType.PUBREL ||
packetType() == AsyncMqttClientInternals::PacketType.PUBREC)
{
_released = false;
}
}
const uint8_t* PubAckOutPacket::data(size_t index) const
{
return &_data[index];
}
size_t PubAckOutPacket::size() const
{
return 4;
}

View File

@@ -0,0 +1,38 @@
/****************************************************************************************************************************
PubAck.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef PUB_ACK_HPP
#define PUB_ACK_HPP
#include "OutPacket.hpp"
#include "../../Flags.hpp"
#include "../../Helpers.hpp"
#include "../../Storage.hpp"
namespace AsyncMqttClientInternals
{
class PubAckOutPacket : public OutPacket
{
public:
explicit PubAckOutPacket(PendingAck pendingAck);
const uint8_t* data(size_t index = 0) const;
size_t size() const;
private:
uint8_t _data[4];
};
} // namespace AsyncMqttClientInternals
#endif // PUB_ACK_HPP

View File

@@ -0,0 +1,106 @@
/****************************************************************************************************************************
Publish.cpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "Publish.hpp"
using AsyncMqttClientInternals::PublishOutPacket;
PublishOutPacket::PublishOutPacket(const char* topic, uint8_t qos, bool retain, const char* payload, size_t length)
{
char fixedHeader[5];
fixedHeader[0] = AsyncMqttClientInternals::PacketType.PUBLISH;
fixedHeader[0] = fixedHeader[0] << 4;
// if (dup) fixedHeader[0] |= AsyncMqttClientInternals::HeaderFlag.PUBLISH_DUP;
if (retain)
fixedHeader[0] |= AsyncMqttClientInternals::HeaderFlag.PUBLISH_RETAIN;
switch (qos)
{
case 0:
fixedHeader[0] |= AsyncMqttClientInternals::HeaderFlag.PUBLISH_QOS0;
break;
case 1:
fixedHeader[0] |= AsyncMqttClientInternals::HeaderFlag.PUBLISH_QOS1;
break;
case 2:
fixedHeader[0] |= AsyncMqttClientInternals::HeaderFlag.PUBLISH_QOS2;
break;
}
uint16_t topicLength = strlen(topic);
char topicLengthBytes[2];
topicLengthBytes[0] = topicLength >> 8;
topicLengthBytes[1] = topicLength & 0xFF;
uint32_t payloadLength = length;
if (payload != nullptr && payloadLength == 0)
payloadLength = strlen(payload);
uint32_t remainingLength = 2 + topicLength + payloadLength;
if (qos != 0)
remainingLength += 2;
uint8_t remainingLengthLength = AsyncMqttClientInternals::Helpers::encodeRemainingLength(remainingLength,
fixedHeader + 1);
size_t neededSpace = 0;
neededSpace += 1 + remainingLengthLength;
neededSpace += 2;
neededSpace += topicLength;
if (qos != 0)
neededSpace += 2;
if (payload != nullptr)
neededSpace += payloadLength;
_data.reserve(neededSpace);
_packetId = (qos != 0) ? _getNextPacketId() : 1;
char packetIdBytes[2];
packetIdBytes[0] = _packetId >> 8;
packetIdBytes[1] = _packetId & 0xFF;
_data.insert(_data.end(), fixedHeader, fixedHeader + 1 + remainingLengthLength);
_data.insert(_data.end(), topicLengthBytes, topicLengthBytes + 2);
_data.insert(_data.end(), topic, topic + topicLength);
if (qos != 0)
{
_data.insert(_data.end(), packetIdBytes, packetIdBytes + 2);
_released = false;
}
if (payload != nullptr)
_data.insert(_data.end(), payload, payload + payloadLength);
}
const uint8_t* PublishOutPacket::data(size_t index) const
{
return &_data.data()[index];
}
size_t PublishOutPacket::size() const
{
return _data.size();
}
void PublishOutPacket::setDup()
{
_data[0] |= AsyncMqttClientInternals::HeaderFlag.PUBLISH_DUP;
}

View File

@@ -0,0 +1,43 @@
/****************************************************************************************************************************
Publish.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef PUBLISH_HPP
#define PUBLISH_HPP
#include <cstring> // strlen
#include <vector>
#include "OutPacket.hpp"
#include "../../Flags.hpp"
#include "../../Helpers.hpp"
#include "../../Storage.hpp"
namespace AsyncMqttClientInternals
{
class PublishOutPacket : public OutPacket
{
public:
PublishOutPacket(const char* topic, uint8_t qos, bool retain, const char* payload, size_t length);
const uint8_t* data(size_t index = 0) const;
size_t size() const;
void setDup(); // you cannot unset dup
private:
std::vector<uint8_t> _data;
};
} // namespace AsyncMqttClientInternals
#endif // PUBLISH_HPP

View File

@@ -0,0 +1,66 @@
/****************************************************************************************************************************
Subscribe.cpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "Subscribe.hpp"
using AsyncMqttClientInternals::SubscribeOutPacket;
SubscribeOutPacket::SubscribeOutPacket(const char* topic, uint8_t qos)
{
char fixedHeader[5];
fixedHeader[0] = AsyncMqttClientInternals::PacketType.SUBSCRIBE;
fixedHeader[0] = fixedHeader[0] << 4;
fixedHeader[0] = fixedHeader[0] | AsyncMqttClientInternals::HeaderFlag.SUBSCRIBE_RESERVED;
uint16_t topicLength = strlen(topic);
char topicLengthBytes[2];
topicLengthBytes[0] = topicLength >> 8;
topicLengthBytes[1] = topicLength & 0xFF;
char qosByte[1];
qosByte[0] = qos;
uint8_t remainingLengthLength = AsyncMqttClientInternals::Helpers::encodeRemainingLength(2 + 2 + topicLength + 1,
fixedHeader + 1);
size_t neededSpace = 0;
neededSpace += 1 + remainingLengthLength;
neededSpace += 2;
neededSpace += 2;
neededSpace += topicLength;
neededSpace += 1;
_data.reserve(neededSpace);
_packetId = _getNextPacketId();
char packetIdBytes[2];
packetIdBytes[0] = _packetId >> 8;
packetIdBytes[1] = _packetId & 0xFF;
_data.insert(_data.end(), fixedHeader, fixedHeader + 1 + remainingLengthLength);
_data.insert(_data.end(), packetIdBytes, packetIdBytes + 2);
_data.insert(_data.end(), topicLengthBytes, topicLengthBytes + 2);
_data.insert(_data.end(), topic, topic + topicLength);
_data.push_back(qosByte[0]);
_released = false;
}
const uint8_t* SubscribeOutPacket::data(size_t index) const
{
return &_data.data()[index];
}
size_t SubscribeOutPacket::size() const
{
return _data.size();
}

View File

@@ -0,0 +1,41 @@
/****************************************************************************************************************************
Subscribe.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef SUBSCRIBE_HPP
#define SUBSCRIBE_HPP
#include <cstring> // strlen
#include <vector>
#include "OutPacket.hpp"
#include "../../Flags.hpp"
#include "../../Helpers.hpp"
#include "../../Storage.hpp"
namespace AsyncMqttClientInternals
{
class SubscribeOutPacket : public OutPacket
{
public:
SubscribeOutPacket(const char* topic, uint8_t qos);
const uint8_t* data(size_t index = 0) const;
size_t size() const;
private:
std::vector<uint8_t> _data;
};
} // namespace AsyncMqttClientInternals
#endif // SUBSCRIBE_HPP

View File

@@ -0,0 +1,59 @@
/****************************************************************************************************************************
Unsubscribe.cpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "Unsubscribe.hpp"
using AsyncMqttClientInternals::UnsubscribeOutPacket;
UnsubscribeOutPacket::UnsubscribeOutPacket(const char* topic)
{
char fixedHeader[5];
fixedHeader[0] = AsyncMqttClientInternals::PacketType.UNSUBSCRIBE;
fixedHeader[0] = fixedHeader[0] << 4;
fixedHeader[0] = fixedHeader[0] | AsyncMqttClientInternals::HeaderFlag.UNSUBSCRIBE_RESERVED;
uint16_t topicLength = strlen(topic);
char topicLengthBytes[2];
topicLengthBytes[0] = topicLength >> 8;
topicLengthBytes[1] = topicLength & 0xFF;
uint8_t remainingLengthLength = AsyncMqttClientInternals::Helpers::encodeRemainingLength(2 + 2 + topicLength,
fixedHeader + 1);
size_t neededSpace = 0;
neededSpace += 1 + remainingLengthLength;
neededSpace += 2;
neededSpace += 2;
neededSpace += topicLength;
_packetId = _getNextPacketId();
char packetIdBytes[2];
packetIdBytes[0] = _packetId >> 8;
packetIdBytes[1] = _packetId & 0xFF;
_data.insert(_data.end(), fixedHeader, fixedHeader + 1 + remainingLengthLength);
_data.insert(_data.end(), packetIdBytes, packetIdBytes + 2);
_data.insert(_data.end(), topicLengthBytes, topicLengthBytes + 2);
_data.insert(_data.end(), topic, topic + topicLength);
_released = false;
}
const uint8_t* UnsubscribeOutPacket::data(size_t index) const
{
return &_data.data()[index];
}
size_t UnsubscribeOutPacket::size() const
{
return _data.size();
}

View File

@@ -0,0 +1,41 @@
/****************************************************************************************************************************
Unsubscribe.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef UNSUBSCRIBE_HPP
#define UNSUBSCRIBE_HPP
#include <cstring> // strlen
#include <vector>
#include "OutPacket.hpp"
#include "../../Flags.hpp"
#include "../../Helpers.hpp"
#include "../../Storage.hpp"
namespace AsyncMqttClientInternals
{
class UnsubscribeOutPacket : public OutPacket
{
public:
explicit UnsubscribeOutPacket(const char* topic);
const uint8_t* data(size_t index = 0) const;
size_t size() const;
private:
std::vector<uint8_t> _data;
};
} // namespace AsyncMqttClientInternals
#endif // UNSUBSCRIBE_HPP

View File

@@ -0,0 +1,29 @@
/****************************************************************************************************************************
Packet.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#ifndef PACKET_HPP
#define PACKET_HPP
namespace AsyncMqttClientInternals
{
class Packet
{
public:
virtual ~Packet() {}
virtual void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition) = 0;
virtual void parsePayload(char* data, size_t len, size_t* currentBytePosition) = 0;
};
} // namespace AsyncMqttClientInternals
#endif // PACKET_HPP

View File

@@ -0,0 +1,40 @@
/****************************************************************************************************************************
PingRespPacket.cpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "PingRespPacket.hpp"
using AsyncMqttClientInternals::PingRespPacket;
PingRespPacket::PingRespPacket(ParsingInformation* parsingInformation, OnPingRespInternalCallback callback)
: _parsingInformation(parsingInformation)
, _callback(callback)
{
}
PingRespPacket::~PingRespPacket()
{
}
void PingRespPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition)
{
(void)data;
(void)len;
(void)currentBytePosition;
}
void PingRespPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition)
{
(void)data;
(void)len;
(void)currentBytePosition;
}

View File

@@ -0,0 +1,41 @@
/****************************************************************************************************************************
PingRespPacket.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef PING_RESP_PACKET_HPP
#define PING_RESP_PACKET_HPP
#include "Arduino.h"
#include "Packet.hpp"
#include "../ParsingInformation.hpp"
#include "../Callbacks.hpp"
namespace AsyncMqttClientInternals
{
class PingRespPacket : public Packet
{
public:
explicit PingRespPacket(ParsingInformation* parsingInformation, OnPingRespInternalCallback callback);
~PingRespPacket();
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
private:
ParsingInformation* _parsingInformation;
OnPingRespInternalCallback _callback;
};
} // namespace AsyncMqttClientInternals
#endif // PING_RESP_PACKET_HPP

View File

@@ -0,0 +1,54 @@
/****************************************************************************************************************************
PubAckPacket.cpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "PubAckPacket.hpp"
using AsyncMqttClientInternals::PubAckPacket;
PubAckPacket::PubAckPacket(ParsingInformation* parsingInformation, OnPubAckInternalCallback callback)
: _parsingInformation(parsingInformation)
, _callback(callback)
, _bytePosition(0)
, _packetIdMsb(0)
, _packetId(0)
{
}
PubAckPacket::~PubAckPacket()
{
}
void PubAckPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition)
{
(void)len;
char currentByte = data[(*currentBytePosition)++];
if (_bytePosition++ == 0)
{
_packetIdMsb = currentByte;
}
else
{
_packetId = currentByte | _packetIdMsb << 8;
_parsingInformation->bufferState = BufferState::NONE;
_callback(_packetId);
}
}
void PubAckPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition)
{
(void)data;
(void)len;
(void)currentBytePosition;
}

View File

@@ -0,0 +1,45 @@
/****************************************************************************************************************************
PubAckPacket.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef PUB_ACK_PACKET_HPP
#define PUB_ACK_PACKET_HPP
#include "Arduino.h"
#include "Packet.hpp"
#include "../ParsingInformation.hpp"
#include "../Callbacks.hpp"
namespace AsyncMqttClientInternals
{
class PubAckPacket : public Packet
{
public:
explicit PubAckPacket(ParsingInformation* parsingInformation, OnPubAckInternalCallback callback);
~PubAckPacket();
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
private:
ParsingInformation* _parsingInformation;
OnPubAckInternalCallback _callback;
uint8_t _bytePosition;
char _packetIdMsb;
uint16_t _packetId;
};
} // namespace AsyncMqttClientInternals
#endif // PUB_ACK_PACKET_HPP

View File

@@ -0,0 +1,54 @@
/****************************************************************************************************************************
PubCompPacket.cpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "PubCompPacket.hpp"
using AsyncMqttClientInternals::PubCompPacket;
PubCompPacket::PubCompPacket(ParsingInformation* parsingInformation, OnPubCompInternalCallback callback)
: _parsingInformation(parsingInformation)
, _callback(callback)
, _bytePosition(0)
, _packetIdMsb(0)
, _packetId(0)
{
}
PubCompPacket::~PubCompPacket()
{
}
void PubCompPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition)
{
(void)len;
char currentByte = data[(*currentBytePosition)++];
if (_bytePosition++ == 0)
{
_packetIdMsb = currentByte;
}
else
{
_packetId = currentByte | _packetIdMsb << 8;
_parsingInformation->bufferState = BufferState::NONE;
_callback(_packetId);
}
}
void PubCompPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition)
{
(void)data;
(void)len;
(void)currentBytePosition;
}

View File

@@ -0,0 +1,45 @@
/****************************************************************************************************************************
PubCompPacket.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef PUB_COMP_PACKET_HPP
#define PUB_COMP_PACKET_HPP
#include "Arduino.h"
#include "Packet.hpp"
#include "../ParsingInformation.hpp"
#include "../Callbacks.hpp"
namespace AsyncMqttClientInternals
{
class PubCompPacket : public Packet
{
public:
explicit PubCompPacket(ParsingInformation* parsingInformation, OnPubCompInternalCallback callback);
~PubCompPacket();
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
private:
ParsingInformation* _parsingInformation;
OnPubCompInternalCallback _callback;
uint8_t _bytePosition;
char _packetIdMsb;
uint16_t _packetId;
};
} // namespace AsyncMqttClientInternals
#endif // PUB_COMP_PACKET_HPP

View File

@@ -0,0 +1,54 @@
/****************************************************************************************************************************
PubRecPacket.cpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "PubRecPacket.hpp"
using AsyncMqttClientInternals::PubRecPacket;
PubRecPacket::PubRecPacket(ParsingInformation* parsingInformation, OnPubRecInternalCallback callback)
: _parsingInformation(parsingInformation)
, _callback(callback)
, _bytePosition(0)
, _packetIdMsb(0)
, _packetId(0)
{
}
PubRecPacket::~PubRecPacket()
{
}
void PubRecPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition)
{
(void)len;
char currentByte = data[(*currentBytePosition)++];
if (_bytePosition++ == 0)
{
_packetIdMsb = currentByte;
}
else
{
_packetId = currentByte | _packetIdMsb << 8;
_parsingInformation->bufferState = BufferState::NONE;
_callback(_packetId);
}
}
void PubRecPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition)
{
(void)data;
(void)len;
(void)currentBytePosition;
}

View File

@@ -0,0 +1,45 @@
/****************************************************************************************************************************
PubRecPacket.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef PUB_REC_PACKET_HPP
#define PUB_REC_PACKET_HPP
#include "Arduino.h"
#include "Packet.hpp"
#include "../ParsingInformation.hpp"
#include "../Callbacks.hpp"
namespace AsyncMqttClientInternals
{
class PubRecPacket : public Packet
{
public:
explicit PubRecPacket(ParsingInformation* parsingInformation, OnPubRecInternalCallback callback);
~PubRecPacket();
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
private:
ParsingInformation* _parsingInformation;
OnPubRecInternalCallback _callback;
uint8_t _bytePosition;
char _packetIdMsb;
uint16_t _packetId;
};
} // namespace AsyncMqttClientInternals
#endif // PUB_REC_PACKET_HPP

View File

@@ -0,0 +1,54 @@
/****************************************************************************************************************************
PubRelPacket.cpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "PubRelPacket.hpp"
using AsyncMqttClientInternals::PubRelPacket;
PubRelPacket::PubRelPacket(ParsingInformation* parsingInformation, OnPubRelInternalCallback callback)
: _parsingInformation(parsingInformation)
, _callback(callback)
, _bytePosition(0)
, _packetIdMsb(0)
, _packetId(0)
{
}
PubRelPacket::~PubRelPacket()
{
}
void PubRelPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition)
{
(void)len;
char currentByte = data[(*currentBytePosition)++];
if (_bytePosition++ == 0)
{
_packetIdMsb = currentByte;
}
else
{
_packetId = currentByte | _packetIdMsb << 8;
_parsingInformation->bufferState = BufferState::NONE;
_callback(_packetId);
}
}
void PubRelPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition)
{
(void)data;
(void)len;
(void)currentBytePosition;
}

View File

@@ -0,0 +1,45 @@
/****************************************************************************************************************************
PubRelPacket.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef PUB_REL_PACKET_HPP
#define PUB_REL_PACKET_HPP
#include "Arduino.h"
#include "Packet.hpp"
#include "../ParsingInformation.hpp"
#include "../Callbacks.hpp"
namespace AsyncMqttClientInternals
{
class PubRelPacket : public Packet
{
public:
explicit PubRelPacket(ParsingInformation* parsingInformation, OnPubRelInternalCallback callback);
~PubRelPacket();
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
private:
ParsingInformation* _parsingInformation;
OnPubRelInternalCallback _callback;
uint8_t _bytePosition;
char _packetIdMsb;
uint16_t _packetId;
};
} // namespace AsyncMqttClientInternals
#endif // PUB_REL_PACKET_HPP

View File

@@ -0,0 +1,149 @@
/****************************************************************************************************************************
PublishPacket.cpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "PublishPacket.hpp"
using AsyncMqttClientInternals::PublishPacket;
PublishPacket::PublishPacket(ParsingInformation* parsingInformation, OnMessageInternalCallback dataCallback,
OnPublishInternalCallback completeCallback)
: _parsingInformation(parsingInformation)
, _dataCallback(dataCallback)
, _completeCallback(completeCallback)
, _dup(false)
, _qos(0)
, _retain(0)
, _bytePosition(0)
, _topicLengthMsb(0)
, _topicLength(0)
, _ignore(false)
, _packetIdMsb(0)
, _packetId(0)
, _payloadLength(0)
, _payloadBytesRead(0)
{
_dup = _parsingInformation->packetFlags & HeaderFlag.PUBLISH_DUP;
_retain = _parsingInformation->packetFlags & HeaderFlag.PUBLISH_RETAIN;
char qosMasked = _parsingInformation->packetFlags & 0x06;
switch (qosMasked)
{
case HeaderFlag.PUBLISH_QOS0:
_qos = 0;
break;
case HeaderFlag.PUBLISH_QOS1:
_qos = 1;
break;
case HeaderFlag.PUBLISH_QOS2:
_qos = 2;
break;
}
}
PublishPacket::~PublishPacket()
{
}
void PublishPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition)
{
(void)len;
char currentByte = data[(*currentBytePosition)++];
if (_bytePosition == 0)
{
_topicLengthMsb = currentByte;
}
else if (_bytePosition == 1)
{
_topicLength = currentByte | _topicLengthMsb << 8;
if (_topicLength > _parsingInformation->maxTopicLength)
{
_ignore = true;
}
else
{
_parsingInformation->topicBuffer[_topicLength] = '\0';
}
}
else if (_bytePosition >= 2 && _bytePosition < 2 + _topicLength)
{
// Starting from here, _ignore might be true
if (!_ignore)
_parsingInformation->topicBuffer[_bytePosition - 2] = currentByte;
if (_bytePosition == 2 + _topicLength - 1 && _qos == 0)
{
_preparePayloadHandling(_parsingInformation->remainingLength - (_bytePosition + 1));
return;
}
}
else if (_bytePosition == 2 + _topicLength)
{
_packetIdMsb = currentByte;
}
else
{
_packetId = currentByte | _packetIdMsb << 8;
_preparePayloadHandling(_parsingInformation->remainingLength - (_bytePosition + 1));
}
_bytePosition++;
}
void PublishPacket::_preparePayloadHandling(uint32_t payloadLength)
{
_payloadLength = payloadLength;
if (payloadLength == 0)
{
_parsingInformation->bufferState = BufferState::NONE;
if (!_ignore)
{
_dataCallback(_parsingInformation->topicBuffer, nullptr, _qos, _dup, _retain, 0, 0, 0, _packetId);
_completeCallback(_packetId, _qos);
}
}
else
{
_parsingInformation->bufferState = BufferState::PAYLOAD;
}
}
void PublishPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition)
{
size_t remainToRead = len - (*currentBytePosition);
if (_payloadBytesRead + remainToRead >
_payloadLength)
remainToRead = _payloadLength - _payloadBytesRead;
if (!_ignore)
_dataCallback(_parsingInformation->topicBuffer, data + (*currentBytePosition),
_qos, _dup, _retain, remainToRead, _payloadBytesRead, _payloadLength, _packetId);
_payloadBytesRead += remainToRead;
(*currentBytePosition) += remainToRead;
if (_payloadBytesRead == _payloadLength)
{
_parsingInformation->bufferState = BufferState::NONE;
if (!_ignore)
_completeCallback(_packetId, _qos);
}
}

View File

@@ -0,0 +1,58 @@
/****************************************************************************************************************************
PublishPacket.hpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#pragma once
#ifndef PUBLISH_PACKET_HPP
#define PUBLISH_PACKET_HPP
#include "Arduino.h"
#include "Packet.hpp"
#include "../Flags.hpp"
#include "../ParsingInformation.hpp"
#include "../Callbacks.hpp"
namespace AsyncMqttClientInternals
{
class PublishPacket : public Packet
{
public:
explicit PublishPacket(ParsingInformation* parsingInformation, OnMessageInternalCallback dataCallback, OnPublishInternalCallback completeCallback);
~PublishPacket();
void parseVariableHeader(char* data, size_t len, size_t* currentBytePosition);
void parsePayload(char* data, size_t len, size_t* currentBytePosition);
private:
ParsingInformation* _parsingInformation;
OnMessageInternalCallback _dataCallback;
OnPublishInternalCallback _completeCallback;
void _preparePayloadHandling(uint32_t payloadLength);
bool _dup;
uint8_t _qos;
bool _retain;
uint8_t _bytePosition;
char _topicLengthMsb;
uint16_t _topicLength;
bool _ignore;
char _packetIdMsb;
uint16_t _packetId;
uint32_t _payloadLength;
uint32_t _payloadBytesRead;
};
} // namespace AsyncMqttClientInternals
#endif // PUBLISH_PACKET_HPP

View File

@@ -0,0 +1,70 @@
/****************************************************************************************************************************
SubAckPacket.cpp
AsyncMQTT_ESP32 is a library for ESP32 boards using WiFi or LwIP W5500 / W6100 / ENC28J60 / LAN8720 Ethernet
Based on and modified from :
1) async-mqtt-client (https://github.com/marvinroger/async-mqtt-client)
2) AsyncMQTT_Generic (https://github.com/khoih-prog/AsyncMQTT_Generic)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncMQTT_ESP32
*****************************************************************************************************************************/
#include "SubAckPacket.hpp"
using AsyncMqttClientInternals::SubAckPacket;
SubAckPacket::SubAckPacket(ParsingInformation* parsingInformation, OnSubAckInternalCallback callback)
: _parsingInformation(parsingInformation)
, _callback(callback)
, _bytePosition(0)
, _packetIdMsb(0)
, _packetId(0)
{
}
SubAckPacket::~SubAckPacket()
{
}
void SubAckPacket::parseVariableHeader(char* data, size_t len, size_t* currentBytePosition)
{
(void)len;
char currentByte = data[(*currentBytePosition)++];
if (_bytePosition++ == 0)
{
_packetIdMsb = currentByte;
}
else
{
_packetId = currentByte | _packetIdMsb << 8;
_parsingInformation->bufferState = BufferState::PAYLOAD;
}
}
void SubAckPacket::parsePayload(char* data, size_t len, size_t* currentBytePosition)
{
(void)len;
char status = data[(*currentBytePosition)++];
/* switch (status) {
case 0:
Serial.println("Success QoS 0");
break;
case 1:
Serial.println("Success QoS 1");
break;
case 2:
Serial.println("Success QoS 2");
break;
case 0x80:
Serial.println("Failure");
break;
} */
_parsingInformation->bufferState = BufferState::NONE;
_callback(_packetId, status);
}

Some files were not shown because too many files have changed in this diff Show More