diff --git a/lib/espMqttClient/README.md b/lib/espMqttClient/README.md index 586d3339e..c897d3d35 100644 --- a/lib/espMqttClient/README.md +++ b/lib/espMqttClient/README.md @@ -3,50 +3,16 @@ MQTT client library for the Espressif devices ESP8266 and ESP32 on the Arduino framework. Aims to be a non-blocking, fully compliant MQTT 3.1.1 client. -![platformio](https://github.com/bertmelis/espMqttClient/actions/workflows/build_platformio.yml/badge.svg) -![cpplint](https://github.com/bertmelis/espMqttClient/actions/workflows/cpplint.yml/badge.svg) -![cppcheck](https://github.com/bertmelis/espMqttClient/actions/workflows/cppcheck.yml/badge.svg) -[![PlatformIO Registry](https://badges.registry.platformio.org/packages/bertmelis/library/espMqttClient.svg)](https://registry.platformio.org/libraries/bertmelis/espMqttClient) +Copy of -# Features +Based on Version 1.7.0 - -- MQTT 3.1.1 compliant library -- Sending and receiving at all QoS levels -- TCP and TCP/TLS using standard WiFiClient and WiFiClientSecure connections -- Virtually unlimited incoming and outgoing payload sizes -- Readable and understandable code -- Fully async clients available via [AsyncTCP](https://github.com/me-no-dev/AsyncTCP) or [ESPAsnycTCP](https://github.com/me-no-dev/ESPAsyncTCP) (no TLS supported) -- Supported platforms: - - Espressif ESP8266 and ESP32 using the Arduino framework -- Basic Linux compatibility*. This includes WSL on Windows +with additional changes to support EMS-ESP such as compiling with Tasmota and not using `SecureWifiClient` in these two files: - > Linux compatibility is mainly for automatic testing. It relies on a quick and dirty Arduino-style `Client` with a POSIX TCP client underneath and Arduino-style `IPAddress` class. These are lacking many features needed for proper Linux support. - -# Documentation - -See [documentation](https://www.emelis.net/espMqttClient/) and the [examples](examples/). - -## Limitations - -### MQTT 3.1.1 Compliancy - -Outgoing messages and session data are not stored in non-volatile memory. Any events like loss of power or sudden resets result in loss of data. Despite this limitation, one could still consider this library as fully complaint based on the non normative remark in point 4.1.1 of the specification. - -### Non-blocking - -This library aims to be fully non-blocking. It is however limited by the underlying `WiFiClient` library which is part of the Arduino framework and has a blocking `connect` method. This is not an issue on ESP32 because the call is offloaded to a separate task. On ESP8266 however, connecting will block until succesful or until the connection timeouts. - -If you need a fully asynchronous MQTT client, you can use `espMqttClientAsync` which uses AsyncTCP/ESPAsyncTCP under the hood. These underlying libraries do not support TLS (anymore). I will not provide support TLS for the async client. - -# Bugs and feature requests - -Please use Github's facilities to get in touch. - -# About this library - -This client wouldn't exist without [Async-mqtt-client](https://github.com/marvinroger/async-mqtt-client). It has been my go-to MQTT client for many years. It was fast, reliable and had features that were non-existing in alternative libraries. However, the underlying async TCP libraries are lacking updates, especially updates related to secure connections. Adapting this library to use up-to-date TCP clients would not be trivial. I eventually decided to write my own MQTT library, from scratch. - -The result is an almost non-blocking library with no external dependencies. The library is almost a drop-in replacement for the async-mqtt-client except a few parameter type changes (eg. `uint8_t*` instead of `char*` for payloads). +``` + src/espMqttClient.cpp + src/Transport/ClientSecureSync.h +``` # License diff --git a/lib/espMqttClient/src/Config.h b/lib/espMqttClient/src/Config.h index d6d1a0e63..935f7e1f5 100644 --- a/lib/espMqttClient/src/Config.h +++ b/lib/espMqttClient/src/Config.h @@ -8,12 +8,8 @@ the LICENSE file. #pragma once -#ifndef TASMOTA_SDK -#define EMC_CLIENT_SECURE -#endif - #ifndef EMC_TX_TIMEOUT -#define EMC_TX_TIMEOUT 2000 +#define EMC_TX_TIMEOUT 10000 #endif #ifndef EMC_RX_BUFFER_SIZE @@ -64,3 +60,16 @@ the LICENSE file. #ifndef EMC_USE_WATCHDOG #define EMC_USE_WATCHDOG 0 #endif + +#ifndef EMC_USE_MEMPOOL +#define EMC_USE_MEMPOOL 0 +#endif + +#if EMC_USE_MEMPOOL + #ifndef EMC_NUM_POOL_ELEMENTS + #define EMC_NUM_POOL_ELEMENTS 32 + #endif + #ifndef EMC_SIZE_POOL_ELEMENTS + #define EMC_SIZE_POOL_ELEMENTS 128 + #endif +#endif diff --git a/lib/espMqttClient/src/MemoryPool/LICENSE b/lib/espMqttClient/src/MemoryPool/LICENSE new file mode 100644 index 000000000..526a0c7cf --- /dev/null +++ b/lib/espMqttClient/src/MemoryPool/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Bert Melis + +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. diff --git a/lib/espMqttClient/src/MemoryPool/README.md b/lib/espMqttClient/src/MemoryPool/README.md new file mode 100644 index 000000000..81b6fd43a --- /dev/null +++ b/lib/espMqttClient/src/MemoryPool/README.md @@ -0,0 +1,105 @@ +# Memory Pool + +EARLY VERSION. USE AT OWN RISK. + +### Description + +This is a simple memory pool that doesn't solve the fragmentation problem but contains it. Inside the pool you will still suffer memory fragmentation. The upside is that you're not restricted on memory size. As long as it fits in the pool, you can request any size! + +For applications where the (maximum) size to allocate is known, a simple fixed block size memory pool is available. There is no memory fragmentation happening in this case. The downside is wastage of memory if you need less then the specified blocksize. + +#### Features + +- pool memory is statically allocated +- pool size adjusts on architecture +- no size calculation required: input number of blocks and size of block +- header-only library +- Variable size pool: no restriction on allocated size +- Variable size pool: malloc and free are O(n); The number of allocated blocks affects lookup. +- Fixed size pool: malloc and free are O(1). + +[![Test with Platformio](https://github.com/bertmelis/MemoryPool/actions/workflows/test-platformio.yml/badge.svg)](https://github.com/bertmelis/MemoryPool/actions/workflows/test-platformio.yml) +[![cpplint](https://github.com/bertmelis/MemoryPool/actions/workflows/cpplint.yml/badge.svg)](https://github.com/bertmelis/MemoryPool/actions/workflows/cpplint.yml) + + +### Usage + +#### Variable size pool + +```cpp +#include + +Struct MyStruct { + unsigned int id; + std::size_t size; + unsigned char data[256]; +}; + +// pool will be able to hold 10 blocks the size of MyStruct +MemoryPool::Variable<10, sizeof(MyStruct)> pool; + +// you can allocate the specified blocksize +// allocation is done in number of 'unsigned char' +MyStruct* s = reinterpret_cast(pool.malloc(sizeof(MyStruct))); + +// you can allocate less than the specified blocksize +int* i = reinterpret_cast(pool.malloc(sizeof(int))); + +// you can allocate more than the specified blocksize +unsigned char* m = reinterpret_cast(pool.malloc(400)); + +pool.free(s); +pool.free(i); +pool.free(m); +``` + +#### Fixed size pool + +```cpp +#include + +Struct MyStruct { + unsigned int id; + std::size_t size; + unsigned char data[256]; +}; + +// pool will be able to hold 10 blocks the size of MyStruct +MemoryPool::Fixed<10, sizeof(MyStruct)> pool; + +// there is no size argument in the malloc function! +MyStruct* s = reinterpret_cast(pool.malloc()); + +// you can allocate less than the specified blocksize +int* i = reinterpret_cast(pool.malloc()); + +pool.free(s); +pool.free(i); +``` + +#### How it works + +##### Variable size pool + +Free blocks are organized as a linked list with their header (contains pointer to next and size). An allocated block also has this header with it's pointer set to `nullptr`. Therefore, each allocation wastes memory the size of the header (`sizeof(void*) + sizeof(std::size_t)`). On creation, the pool calculations the needed space to store the number of blocks wich each their header. + +However, memory allocation isn't restricted the the specified blocksize. So in reality, you can allocate more if you allocate larger chunks because less memory blocks means less headers. After all, memory needs to be contiguous. + +If you inspect the pool you'll see that a free pool only has one big block. + +Allocation is linear: the pool is iterated until a suitable spot is found. +Freeing is also linear as the pool is traversed to insert the chunk in the linked list of free blocks + +When freeing, free blocks which are adjacent are combined into one. + +##### Fixed size pool + +The fixed size pool is implemented as an array. Free blocks are saved as a linked list in this array. + +### Bugs and feature requests + +Please use Github's facilities to get in touch. + +### License + +This library is released under the MIT Licence. A copy is included in the repo. diff --git a/lib/espMqttClient/src/MemoryPool/keywords.txt b/lib/espMqttClient/src/MemoryPool/keywords.txt new file mode 100644 index 000000000..ef87ce227 --- /dev/null +++ b/lib/espMqttClient/src/MemoryPool/keywords.txt @@ -0,0 +1,16 @@ +# Datatypes (KEYWORD1) +Fixed KEYWORD1 +Variable KEYWORD1 + +# Methods and Functions (KEYWORD2) +malloc KEYWORD2 +free KEYWORD2 +freeMemory KEYWORD2 +maxBlockSize KEYWORD2 +print KEYWORD2 + +# Structures (KEYWORD3) +# structure KEYWORD3 + +# Constants (LITERAL1) +MemoryPool LITERAL1 diff --git a/lib/espMqttClient/src/MemoryPool/library.json b/lib/espMqttClient/src/MemoryPool/library.json new file mode 100644 index 000000000..f9e61165d --- /dev/null +++ b/lib/espMqttClient/src/MemoryPool/library.json @@ -0,0 +1,21 @@ +{ + "name": "MemoryPool", + "keywords": "memory", + "description": "A simple memory pool for fixed and variable sizes", + "authors": + { + "name": "Bert Melis", + "url": "https://github.com/bertmelis" + }, + "license": "MIT", + "homepage": "https://github.com/bertmelis/MemoryPool", + "repository": + { + "type": "git", + "url": "https://github.com/bertmelis/MemoryPool.git" + }, + "version": "0.1.0", + "frameworks": "*", + "platforms": "*", + "headers": ["MemoryPool.h"] + } \ No newline at end of file diff --git a/lib/espMqttClient/src/MemoryPool/library.properties b/lib/espMqttClient/src/MemoryPool/library.properties new file mode 100644 index 000000000..a46b50f9a --- /dev/null +++ b/lib/espMqttClient/src/MemoryPool/library.properties @@ -0,0 +1,10 @@ +name=MemoryPool +version=0.1.0 +author=Bert Melis +maintainer=Bert Melis +sentence=A simple memory pool for fixed and variable sizes +paragraph= +category=Other +url=https://github.com/bertmelis/MemoryPool +architectures=* +includes=MemoryPool.h \ No newline at end of file diff --git a/lib/espMqttClient/src/MemoryPool/src/Fixed.h b/lib/espMqttClient/src/MemoryPool/src/Fixed.h new file mode 100644 index 000000000..b68dbd136 --- /dev/null +++ b/lib/espMqttClient/src/MemoryPool/src/Fixed.h @@ -0,0 +1,119 @@ +/* +Copyright (c) 2024 Bert Melis. All rights reserved. + +This work is licensed under the terms of the MIT license. +For a copy, see or +the LICENSE file. +*/ + +#pragma once + +#include // std::size_t +#include // assert +#if _GLIBCXX_HAS_GTHREADS +#include // NOLINT [build/c++11] std::mutex, std::lock_guard +#else +#warning "The memory pool is not thread safe" +#endif + +#ifdef MEMPOL_DEBUG +#include +#endif + +namespace MemoryPool { + +template +class Fixed { + public: + Fixed() // cppcheck-suppress uninitMemberVar + : _buffer{0} + , _head(_buffer) { + unsigned char* b = _head; + std::size_t adjustedBlocksize = sizeof(std::size_t) > blocksize ? sizeof(std::size_t) : blocksize; + for (std::size_t i = 0; i < nrBlocks - 1; ++i) { + *reinterpret_cast(b) = b + adjustedBlocksize; + b += adjustedBlocksize; + } + *reinterpret_cast(b) = nullptr; + } + + // no copy nor move + Fixed (const Fixed&) = delete; + Fixed& operator= (const Fixed&) = delete; + + void* malloc() { + #if _GLIBCXX_HAS_GTHREADS + const std::lock_guard lockGuard(_mutex); + #endif + if (_head) { + void* retVal = _head; + _head = *reinterpret_cast(_head); + return retVal; + } + return nullptr; + } + + void free(void* ptr) { + if (!ptr) return; + #if _GLIBCXX_HAS_GTHREADS + const std::lock_guard lockGuard(_mutex); + #endif + *reinterpret_cast(ptr) = _head; + _head = reinterpret_cast(ptr); + } + + std::size_t freeMemory() { + #if _GLIBCXX_HAS_GTHREADS + const std::lock_guard lockGuard(_mutex); + #endif + unsigned char* i = _head; + std::size_t retVal = 0; + while (i) { + retVal += blocksize; + i = reinterpret_cast(i)[0]; + } + return retVal; + } + + #ifdef MEMPOL_DEBUG + void print() { + std::size_t adjustedBlocksize = sizeof(std::size_t) > blocksize ? sizeof(std::size_t) : blocksize; + std::cout << "+--------------------" << std::endl; + std::cout << "|start:" << reinterpret_cast(_buffer) << std::endl; + std::cout << "|blocks:" << nrBlocks << std::endl; + std::cout << "|blocksize:" << adjustedBlocksize << std::endl; + std::cout << "|head: " << reinterpret_cast(_head) << std::endl; + unsigned char* currentBlock = _buffer; + + for (std::size_t i = 0; i < nrBlocks; ++i) { + std::cout << "|" << i + 1 << ": " << reinterpret_cast(currentBlock) << std::endl; + if (_isFree(currentBlock)) { + std::cout << "| free" << std::endl; + std::cout << "| next: " << reinterpret_cast(*reinterpret_cast(currentBlock)) << std::endl; + } else { + std::cout << "| allocated" << std::endl; + } + currentBlock += adjustedBlocksize; + } + std::cout << "+--------------------" << std::endl; + } + + bool _isFree(const unsigned char* ptr) { + unsigned char* b = _head; + while (b) { + if (b == ptr) return true; + b = *reinterpret_cast(b); + } + return false; + } + #endif + + private: + unsigned char _buffer[nrBlocks * (sizeof(std::size_t) > blocksize ? sizeof(std::size_t) : blocksize)]; + unsigned char* _head; + #if _GLIBCXX_HAS_GTHREADS + std::mutex _mutex; + #endif +}; + +} // end namespace MemoryPool diff --git a/lib/espMqttClient/src/MemoryPool/src/MemoryPool.h b/lib/espMqttClient/src/MemoryPool/src/MemoryPool.h new file mode 100644 index 000000000..5b198eaf2 --- /dev/null +++ b/lib/espMqttClient/src/MemoryPool/src/MemoryPool.h @@ -0,0 +1,12 @@ +/* +Copyright (c) 2024 Bert Melis. All rights reserved. + +This work is licensed under the terms of the MIT license. +For a copy, see or +the LICENSE file. +*/ + +#pragma once + +#include "Variable.h" +#include "Fixed.h" diff --git a/lib/espMqttClient/src/MemoryPool/src/Variable.h b/lib/espMqttClient/src/MemoryPool/src/Variable.h new file mode 100644 index 000000000..563bf4978 --- /dev/null +++ b/lib/espMqttClient/src/MemoryPool/src/Variable.h @@ -0,0 +1,242 @@ +/* +Copyright (c) 2024 Bert Melis. All rights reserved. + +This work is licensed under the terms of the MIT license. +For a copy, see or +the LICENSE file. +*/ + +#pragma once + +#include // std::size_t +#include // assert +#if _GLIBCXX_HAS_GTHREADS +#include // NOLINT [build/c++11] std::mutex, std::lock_guard +#else +#warning "The memory pool is not thread safe" +#endif + +#ifdef MEMPOL_DEBUG +#include +#endif + +namespace MemoryPool { + +template +class Variable { + public: + Variable() + : _buffer{0} + , _head(nullptr) + #ifdef MEMPOL_DEBUG + , _bufferSize(0) + #endif + { + std::size_t _normBlocksize = blocksize / sizeof(BlockHeader) + ((blocksize % sizeof(BlockHeader)) ? 1 : 0); + size_t nrBlocksToAlloc = nrBlocks * (_normBlocksize + 1); + BlockHeader* h = reinterpret_cast(_buffer); + h->next = nullptr; + h->size = nrBlocksToAlloc; + _head = h; + + #ifdef MEMPOL_DEBUG + _bufferSize = nrBlocksToAlloc; + #endif + } + + // no copy nor move + Variable (const Variable&) = delete; + Variable& operator= (const Variable&) = delete; + + void* malloc(size_t size) { + #if _GLIBCXX_HAS_GTHREADS + const std::lock_guard lockGuard(_mutex); + #endif + if (size == 0) return nullptr; + + size = (size / sizeof(BlockHeader) + (size % sizeof(BlockHeader) != 0)) + 1; // count by BlockHeader size, add 1 for header + + #ifdef MEMPOL_DEBUG + std::cout << "malloc (raw) " << size << std::endl; + std::cout << "malloc (adj) " << size << " - "; + #endif + + BlockHeader* currentBlock = _head; + BlockHeader* previousBlock = nullptr; + void* retVal = nullptr; + + // iterate through linked free blocks + while (currentBlock) { + // consume whole block is size equals required size + if (currentBlock->size == size) { + if (previousBlock) previousBlock->next = currentBlock->next; + break; + + // split block if size is larger and add second part to list of free blocks + } else if (currentBlock->size > size) { + BlockHeader* newBlock = currentBlock + size; + if (previousBlock) previousBlock->next = newBlock; + newBlock->next = currentBlock->next; + newBlock->size = currentBlock->size - size; + currentBlock->next = newBlock; + break; + } + previousBlock = currentBlock; + currentBlock = currentBlock->next; + } + + if (currentBlock) { + if (currentBlock == _head) { + _head = currentBlock->next; + } + currentBlock->size = size; + currentBlock->next = nullptr; // used when freeing memory + retVal = currentBlock + 1; + #ifdef MEMPOL_DEBUG + std::cout << "ok" << std::endl; + #endif + } else { + #ifdef MEMPOL_DEBUG + std::cout << "nok" << std::endl; + #endif + (void)0; + } + + return retVal; + } + + void free(void* ptr) { + if (!ptr) return; + // check if ptr points to region in _buffer + + #ifdef MEMPOL_DEBUG + std::cout << "free " << static_cast(reinterpret_cast(ptr) - 1) << std::endl; + #endif + + #if _GLIBCXX_HAS_GTHREADS + const std::lock_guard lockGuard(_mutex); + #endif + + BlockHeader* toFree = reinterpret_cast(ptr) - 1; + BlockHeader* previous = reinterpret_cast(_buffer); + BlockHeader* next = _head; + + // toFree is the only free block + if (!next) { + _head = toFree; + return; + } + + while (previous) { + if (!next || toFree < next) { + // 1. add block to linked list of free blocks + if (toFree < _head) { + toFree->next = _head; + _head = toFree; + } else { + previous->next = toFree; + toFree->next = next; + } + + // 2. merge with previous if adjacent + if (toFree > _head && toFree == previous + previous->size) { + previous->size += toFree->size; + previous->next = toFree->next; + toFree = previous; // used in next check + } + + // 3. merge with next if adjacent + if (toFree + toFree->size == next) { + toFree->size += next->size; + toFree->next = next->next; + } + + // 4. done + return; + } + previous = next; + next = next->next; + } + } + + std::size_t freeMemory() { + #if _GLIBCXX_HAS_GTHREADS + const std::lock_guard lockGuard(_mutex); + #endif + size_t retVal = 0; + BlockHeader* currentBlock = reinterpret_cast(_head); + + while (currentBlock) { + retVal += currentBlock->size - 1; + currentBlock = currentBlock->next; + } + + return retVal * sizeof(BlockHeader); + } + + std::size_t maxBlockSize() { + #if _GLIBCXX_HAS_GTHREADS + const std::lock_guard lockGuard(_mutex); + #endif + size_t retVal = 0; + BlockHeader* currentBlock = reinterpret_cast(_head); + + while (currentBlock) { + retVal = (currentBlock->size - 1 > retVal) ? currentBlock->size - 1 : retVal; + currentBlock = currentBlock->next; + } + + return retVal * sizeof(BlockHeader); + } + + #ifdef MEMPOL_DEBUG + void print() { + std::cout << "+--------------------" << std::endl; + std::cout << "|start:" << static_cast(_buffer) << std::endl; + std::cout << "|size:" << _bufferSize << std::endl; + std::cout << "|headersize:" << sizeof(BlockHeader) << std::endl; + std::cout << "|head: " << static_cast(_head) << std::endl; + BlockHeader* nextFreeBlock = _head; + BlockHeader* currentBlock = reinterpret_cast(_buffer); + size_t blockNumber = 1; + while (currentBlock < reinterpret_cast(_buffer) + _bufferSize) { + std::cout << "|" << blockNumber << ": " << static_cast(currentBlock) << std::endl; + std::cout << "| " << static_cast(currentBlock->next) << std::endl; + std::cout << "| " << currentBlock->size << std::endl; + if (currentBlock == nextFreeBlock) { + std::cout << "| free" << std::endl; + nextFreeBlock = nextFreeBlock->next; + } else { + std::cout << "| allocated" << std::endl; + } + ++blockNumber; + currentBlock += currentBlock->size; + } + std::cout << "+--------------------" << std::endl; + } + #endif + + private: + struct BlockHeader { + BlockHeader* next; + std::size_t size; + }; + /* + pool size is aligned to sizeof(BlockHeader). + requested blocksize is therefore multiple of blockheader (rounded up) + total size = nr requested blocks * multiplier * blockheadersize + + see constructor for calculation + */ + unsigned char _buffer[(nrBlocks * ((blocksize / sizeof(BlockHeader) + ((blocksize % sizeof(BlockHeader)) ? 1 : 0)) + 1)) * sizeof(BlockHeader)]; + BlockHeader* _head; + #if _GLIBCXX_HAS_GTHREADS + std::mutex _mutex; + #endif + + #ifdef MEMPOL_DEBUG + std::size_t _bufferSize; + #endif +}; + +} // end namespace MemoryPool diff --git a/lib/espMqttClient/src/MqttClient.cpp b/lib/espMqttClient/src/MqttClient.cpp index 8b780cf3f..dc21f7456 100644 --- a/lib/espMqttClient/src/MqttClient.cpp +++ b/lib/espMqttClient/src/MqttClient.cpp @@ -14,721 +14,733 @@ using espMqttClientTypes::DisconnectReason; using espMqttClientTypes::Error; MqttClient::MqttClient(espMqttClientTypes::UseInternalTask useInternalTask, uint8_t priority, uint8_t core) - : _useInternalTask(useInternalTask) - , _transport(nullptr) - , _onConnectCallback(nullptr) - , _onDisconnectCallback(nullptr) - , _onSubscribeCallback(nullptr) - , _onUnsubscribeCallback(nullptr) - , _onMessageCallback(nullptr) - , _onPublishCallback(nullptr) - , _onErrorCallback(nullptr) - , _clientId(nullptr) - , _ip() - , _host(nullptr) - , _port(1883) - , _useIp(false) - , _keepAlive(15000) - , _cleanSession(true) - , _username(nullptr) - , _password(nullptr) - , _willTopic(nullptr) - , _willPayload(nullptr) - , _willPayloadLength(0) - , _willQos(0) - , _willRetain(false) - , _timeout(EMC_TX_TIMEOUT) - , _state(State::disconnected) - , _generatedClientId{0} - , _packetId(0) +: _useInternalTask(useInternalTask) +, _transport(nullptr) +, _onConnectCallback(nullptr) +, _onDisconnectCallback(nullptr) +, _onSubscribeCallback(nullptr) +, _onUnsubscribeCallback(nullptr) +, _onMessageCallback(nullptr) +, _onPublishCallback(nullptr) +, _onErrorCallback(nullptr) +, _clientId(nullptr) +, _ip() +, _host(nullptr) +, _port(1883) +, _useIp(false) +, _keepAlive(15000) +, _cleanSession(true) +, _username(nullptr) +, _password(nullptr) +, _willTopic(nullptr) +, _willPayload(nullptr) +, _willPayloadLength(0) +, _willQos(0) +, _willRetain(false) +, _timeout(EMC_TX_TIMEOUT) +, _state(State::disconnected) +, _generatedClientId{0} +, _packetId(0) #if defined(ARDUINO_ARCH_ESP32) - , _xSemaphore(nullptr) - , _taskHandle(nullptr) +, _xSemaphore(nullptr) +, _taskHandle(nullptr) #endif - , _rxBuffer{0} - , _outbox() - , _bytesSent(0) - , _parser() - , _lastClientActivity(0) - , _lastServerActivity(0) - , _pingSent(false) - , _disconnectReason(DisconnectReason::TCP_DISCONNECTED) +, _rxBuffer{0} +, _outbox() +, _bytesSent(0) +, _parser() +, _lastClientActivity(0) +, _lastServerActivity(0) +, _pingSent(false) +, _disconnectReason(DisconnectReason::TCP_DISCONNECTED) #if defined(ARDUINO_ARCH_ESP32) && ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO - , _highWaterMark(4294967295) +, _highWaterMark(4294967295) #endif -{ - EMC_GENERATE_CLIENTID(_generatedClientId); + { + EMC_GENERATE_CLIENTID(_generatedClientId); #if defined(ARDUINO_ARCH_ESP32) - _xSemaphore = xSemaphoreCreateMutex(); - EMC_SEMAPHORE_GIVE(); // release before first use - if (_useInternalTask == espMqttClientTypes::UseInternalTask::YES) { - xTaskCreatePinnedToCore((TaskFunction_t)_loop, "mqttclient", EMC_TASK_STACK_SIZE, this, priority, &_taskHandle, core); - } + _xSemaphore = xSemaphoreCreateMutex(); + EMC_SEMAPHORE_GIVE(); // release before first use + if (_useInternalTask == espMqttClientTypes::UseInternalTask::YES) { + xTaskCreatePinnedToCore((TaskFunction_t)_loop, "mqttclient", EMC_TASK_STACK_SIZE, this, priority, &_taskHandle, core); + } #else - (void)useInternalTask; - (void)priority; - (void)core; + (void) useInternalTask; + (void) priority; + (void) core; #endif - _clientId = _generatedClientId; + _clientId = _generatedClientId; } MqttClient::~MqttClient() { - disconnect(true); - _clearQueue(2); + disconnect(true); + _clearQueue(2); #if defined(ARDUINO_ARCH_ESP32) - vSemaphoreDelete(_xSemaphore); - if (_useInternalTask == espMqttClientTypes::UseInternalTask::YES) { -#if EMC_USE_WATCHDOG - esp_task_wdt_delete(_taskHandle); // not sure if this is really needed -#endif - vTaskDelete(_taskHandle); - } + vSemaphoreDelete(_xSemaphore); + if (_useInternalTask == espMqttClientTypes::UseInternalTask::YES) { + #if EMC_USE_WATCHDOG + esp_task_wdt_delete(_taskHandle); // not sure if this is really needed + #endif + vTaskDelete(_taskHandle); + } #endif } bool MqttClient::connected() const { - if (_state == State::connected) - return true; - return false; + if (_state == State::connected) return true; + return false; } bool MqttClient::disconnected() const { - if (_state == State::disconnected) - return true; - return false; + if (_state == State::disconnected) return true; + return false; } bool MqttClient::connect() { - bool result = false; - if (_state == State::disconnected) { - EMC_SEMAPHORE_TAKE(); - if (_addPacketFront(_cleanSession, - _username, - _password, - _willTopic, - _willRetain, - _willQos, - _willPayload, - _willPayloadLength, - (uint16_t)(_keepAlive / 1000), // 32b to 16b doesn't overflow because it comes from 16b orignally - _clientId)) { - result = true; - _state = State::connectingTcp1; -#if defined(ARDUINO_ARCH_ESP32) - if (_useInternalTask == espMqttClientTypes::UseInternalTask::YES) { - vTaskResume(_taskHandle); - } -#endif - } else { - EMC_SEMAPHORE_GIVE(); - emc_log_e("Could not create CONNECT packet"); - _onError(0, Error::OUT_OF_MEMORY); - } - EMC_SEMAPHORE_GIVE(); + bool result = false; + if (_state == State::disconnected) { + EMC_SEMAPHORE_TAKE(); + if (_addPacketFront(_cleanSession, + _username, + _password, + _willTopic, + _willRetain, + _willQos, + _willPayload, + _willPayloadLength, + (uint16_t)(_keepAlive / 1000), // 32b to 16b doesn't overflow because it comes from 16b orignally + _clientId)) { + result = true; + _setState(State::connectingTcp1); + #if defined(ARDUINO_ARCH_ESP32) + if (_useInternalTask == espMqttClientTypes::UseInternalTask::YES) { + vTaskResume(_taskHandle); + } + #endif + } else { + emc_log_e("Could not create CONNECT packet"); + EMC_SEMAPHORE_GIVE(); + _onError(0, Error::OUT_OF_MEMORY); + EMC_SEMAPHORE_TAKE(); } - return result; + EMC_SEMAPHORE_GIVE(); + } + return result; } bool MqttClient::disconnect(bool force) { - if (force && _state != State::disconnected && _state != State::disconnectingTcp1 && _state != State::disconnectingTcp2) { - _state = State::disconnectingTcp1; - return true; - } - if (!force && _state == State::connected) { - _state = State::disconnectingMqtt1; - return true; - } - return false; + if (force && _state != State::disconnected && _state != State::disconnectingTcp1 && _state != State::disconnectingTcp2) { + _setState(State::disconnectingTcp1); + return true; + } + if (!force && _state == State::connected) { + _setState(State::disconnectingMqtt1); + return true; + } + return false; } -uint16_t MqttClient::publish(const char * topic, uint8_t qos, bool retain, const uint8_t * payload, size_t length) { -#if !EMC_ALLOW_NOT_CONNECTED_PUBLISH - if (_state != State::connected) { -#else - if (_state > State::connected) { -#endif - return 0; - } - EMC_SEMAPHORE_TAKE(); - uint16_t packetId = (qos > 0) ? _getNextPacketId() : 1; - if (!_addPacket(packetId, topic, payload, length, qos, retain)) { - emc_log_e("Could not create PUBLISH packet"); - _onError(packetId, Error::OUT_OF_MEMORY); - packetId = 0; - } +uint16_t MqttClient::publish(const char* topic, uint8_t qos, bool retain, const uint8_t* payload, size_t length) { + #if !EMC_ALLOW_NOT_CONNECTED_PUBLISH + if (_state != State::connected) { + #else + if (_state > State::connected) { + #endif + return 0; + } + EMC_SEMAPHORE_TAKE(); + uint16_t packetId = (qos > 0) ? _getNextPacketId() : 1; + if (!_addPacket(packetId, topic, payload, length, qos, retain)) { + emc_log_e("Could not create PUBLISH packet"); EMC_SEMAPHORE_GIVE(); - return packetId; -} - -uint16_t MqttClient::publish(const char * topic, uint8_t qos, bool retain, const char * payload) { - size_t len = strlen(payload); - return publish(topic, qos, retain, reinterpret_cast(payload), len); -} - -uint16_t MqttClient::publish(const char * topic, uint8_t qos, bool retain, espMqttClientTypes::PayloadCallback callback, size_t length) { -#if !EMC_ALLOW_NOT_CONNECTED_PUBLISH - if (_state != State::connected) { -#else - if (_state > State::connected) { -#endif - return 0; - } + _onError(packetId, Error::OUT_OF_MEMORY); EMC_SEMAPHORE_TAKE(); - uint16_t packetId = (qos > 0) ? _getNextPacketId() : 1; - if (!_addPacket(packetId, topic, callback, length, qos, retain)) { - emc_log_e("Could not create PUBLISH packet"); - _onError(packetId, Error::OUT_OF_MEMORY); - packetId = 0; - } + packetId = 0; + } + EMC_SEMAPHORE_GIVE(); + return packetId; +} + +uint16_t MqttClient::publish(const char* topic, uint8_t qos, bool retain, const char* payload) { + size_t len = strlen(payload); + return publish(topic, qos, retain, reinterpret_cast(payload), len); +} + +uint16_t MqttClient::publish(const char* topic, uint8_t qos, bool retain, espMqttClientTypes::PayloadCallback callback, size_t length) { + #if !EMC_ALLOW_NOT_CONNECTED_PUBLISH + if (_state != State::connected) { + #else + if (_state > State::connected) { + #endif + return 0; + } + EMC_SEMAPHORE_TAKE(); + uint16_t packetId = (qos > 0) ? _getNextPacketId() : 1; + if (!_addPacket(packetId, topic, callback, length, qos, retain)) { + emc_log_e("Could not create PUBLISH packet"); EMC_SEMAPHORE_GIVE(); - return packetId; + _onError(packetId, Error::OUT_OF_MEMORY); + EMC_SEMAPHORE_TAKE(); + packetId = 0; + } + EMC_SEMAPHORE_GIVE(); + return packetId; } void MqttClient::clearQueue(bool deleteSessionData) { - _clearQueue(deleteSessionData ? 2 : 0); + EMC_SEMAPHORE_TAKE(); + _clearQueue(deleteSessionData ? 2 : 0); + EMC_SEMAPHORE_GIVE(); } -const char * MqttClient::getClientId() const { - return _clientId; +const char* MqttClient::getClientId() const { + return _clientId; } size_t MqttClient::queueSize() { - size_t ret = 0; - EMC_SEMAPHORE_TAKE(); - ret = _outbox.size(); - EMC_SEMAPHORE_GIVE(); - return ret; + size_t ret = 0; + EMC_SEMAPHORE_TAKE(); + ret = _outbox.size(); + EMC_SEMAPHORE_GIVE(); + return ret; } void MqttClient::loop() { - switch ((State)_state) { // modified by proddy for EMS-ESP compiling standalone + switch (_state) { case State::disconnected: -#if defined(ARDUINO_ARCH_ESP32) - if (_useInternalTask == espMqttClientTypes::UseInternalTask::YES) { - vTaskSuspend(_taskHandle); - } -#endif - break; + #if defined(ARDUINO_ARCH_ESP32) + if (_useInternalTask == espMqttClientTypes::UseInternalTask::YES) { + vTaskSuspend(_taskHandle); + } + #endif + break; case State::connectingTcp1: - if (_useIp ? _transport->connect(_ip, _port) : _transport->connect(_host, _port)) { - _state = State::connectingTcp2; - } else { - _state = State::disconnectingTcp1; - _disconnectReason = DisconnectReason::TCP_DISCONNECTED; - break; - } - // Falling through to speed up connecting on blocking transport 'connect' implementations - [[fallthrough]]; + if (_useIp ? _transport->connect(_ip, _port) : _transport->connect(_host, _port)) { + _setState(State::connectingTcp2); + } else { + _setState(State::disconnectingTcp1); + _disconnectReason = DisconnectReason::TCP_DISCONNECTED; + break; + } + // Falling through to speed up connecting on blocking transport 'connect' implementations + [[fallthrough]]; case State::connectingTcp2: - if (_transport->connected()) { - _parser.reset(); - _lastClientActivity = _lastServerActivity = millis(); - _state = State::connectingMqtt; - } - break; + if (_transport->connected()) { + _parser.reset(); + _lastClientActivity = _lastServerActivity = millis(); + _setState(State::connectingMqtt); + } else if (_transport->disconnected()) { // sync: implemented as "not connected"; async: depending on state of pcb in underlying lib + _setState(State::disconnectingTcp1); + _disconnectReason = DisconnectReason::TCP_DISCONNECTED; + } + break; case State::connectingMqtt: -#if EMC_WAIT_FOR_CONNACK - if (_transport->connected()) { - _sendPacket(); - _checkIncoming(); - _checkPing(); - } else { - _state = State::disconnectingTcp1; - _disconnectReason = DisconnectReason::TCP_DISCONNECTED; - } - break; -#else - // receipt of CONNACK packet will set state to CONNECTED - // client however is allowed to send packets before CONNACK is received - // so we fall through to 'connected' - [[fallthrough]]; -#endif - case State::connected: - [[fallthrough]]; - case State::disconnectingMqtt2: - if (_transport->connected()) { - // CONNECT packet is first in the queue - _checkOutbox(); - _checkIncoming(); - _checkPing(); - _checkTimeout(); - } else { - _state = State::disconnectingTcp1; - _disconnectReason = DisconnectReason::TCP_DISCONNECTED; - } - break; - case State::disconnectingMqtt1: + #if EMC_WAIT_FOR_CONNACK + if (_transport->connected()) { EMC_SEMAPHORE_TAKE(); - if (_outbox.empty()) { - if (!_addPacket(PacketType.DISCONNECT)) { - EMC_SEMAPHORE_GIVE(); - emc_log_e("Could not create DISCONNECT packet"); - _onError(0, Error::OUT_OF_MEMORY); - } else { - _state = State::disconnectingMqtt2; - } - } + _sendPacket(); + _checkIncoming(); + _checkPing(); EMC_SEMAPHORE_GIVE(); + } else { + _setState(State::disconnectingTcp1); + _disconnectReason = DisconnectReason::TCP_DISCONNECTED; + } + break; + #else + // receipt of CONNACK packet will set state to CONNECTED + // client however is allowed to send packets before CONNACK is received + // so we fall through to 'connected' + [[fallthrough]]; + #endif + case State::connected: + [[fallthrough]]; + case State::disconnectingMqtt2: + if (_transport->connected()) { + // CONNECT packet is first in the queue + EMC_SEMAPHORE_TAKE(); _checkOutbox(); _checkIncoming(); _checkPing(); _checkTimeout(); - break; - case State::disconnectingTcp1: - _transport->stop(); - _state = State::disconnectingTcp2; - break; // keep break to accomodate async clients - case State::disconnectingTcp2: - if (_transport->disconnected()) { - _clearQueue(0); - _bytesSent = 0; - _state = State::disconnected; - if (_onDisconnectCallback) - _onDisconnectCallback(_disconnectReason); + EMC_SEMAPHORE_GIVE(); + } else { + _setState(State::disconnectingTcp1); + _disconnectReason = DisconnectReason::TCP_DISCONNECTED; + } + break; + case State::disconnectingMqtt1: + EMC_SEMAPHORE_TAKE(); + if (_outbox.empty()) { + if (!_addPacket(PacketType.DISCONNECT)) { + EMC_SEMAPHORE_GIVE(); + emc_log_e("Could not create DISCONNECT packet"); + _onError(0, Error::OUT_OF_MEMORY); + EMC_SEMAPHORE_TAKE(); + } else { + _setState(State::disconnectingMqtt2); } - break; - // all cases covered, no default case - } - EMC_YIELD(); -#if defined(ARDUINO_ARCH_ESP32) && ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO - size_t waterMark = uxTaskGetStackHighWaterMark(NULL); - if (waterMark < _highWaterMark) { - _highWaterMark = waterMark; - emc_log_i("Stack usage: %zu/%i", EMC_TASK_STACK_SIZE - _highWaterMark, EMC_TASK_STACK_SIZE); - } -#endif + } + _checkOutbox(); + _checkIncoming(); + _checkPing(); + _checkTimeout(); + EMC_SEMAPHORE_GIVE(); + break; + case State::disconnectingTcp1: + _transport->stop(); + _setState(State::disconnectingTcp2); + break; // keep break to accomodate async clients + case State::disconnectingTcp2: + if (_transport->disconnected()) { + EMC_SEMAPHORE_TAKE(); + _clearQueue(0); + EMC_SEMAPHORE_GIVE(); + _bytesSent = 0; + _setState(State::disconnected); + if (_onDisconnectCallback) { + _onDisconnectCallback(_disconnectReason); + } + } + break; + // all cases covered, no default case + } + EMC_YIELD(); + #if defined(ARDUINO_ARCH_ESP32) && ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO + size_t waterMark = uxTaskGetStackHighWaterMark(NULL); + if (waterMark < _highWaterMark) { + _highWaterMark = waterMark; + emc_log_i("Stack usage: %zu/%i", EMC_TASK_STACK_SIZE - _highWaterMark, EMC_TASK_STACK_SIZE); + } + #endif } #if defined(ARDUINO_ARCH_ESP32) -void MqttClient::_loop(MqttClient * c) { -#if EMC_USE_WATCHDOG - if (esp_task_wdt_add(NULL) != ESP_OK) { - emc_log_e("Failed to add async task to WDT"); - } -#endif - for (;;) { - c->loop(); -#if EMC_USE_WATCHDOG - esp_task_wdt_reset(); -#endif - } +void MqttClient::_loop(MqttClient* c) { + #if EMC_USE_WATCHDOG + if (esp_task_wdt_add(NULL) != ESP_OK) { + emc_log_e("Failed to add async task to WDT"); + } + #endif + for (;;) { + c->loop(); + #if EMC_USE_WATCHDOG + esp_task_wdt_reset(); + #endif + } } #endif +inline void MqttClient::_setState(State newState) { + emc_log_i("state %i --> %i", static_cast::type>(_state.load()), static_cast::type>(newState)); + _state = newState; +} + uint16_t MqttClient::_getNextPacketId() { - ++_packetId; - if (_packetId == 0) - ++_packetId; - return _packetId; + ++_packetId; + if (_packetId == 0) ++_packetId; + return _packetId; } void MqttClient::_checkOutbox() { - while (_sendPacket() > 0) { - if (!_advanceOutbox()) { - break; - } + while (_sendPacket() > 0) { + if (!_advanceOutbox()) { + break; } + } } int MqttClient::_sendPacket() { - EMC_SEMAPHORE_TAKE(); - OutgoingPacket * packet = _outbox.getCurrent(); + OutgoingPacket* packet = _outbox.getCurrent(); - size_t written = 0; - if (packet) { - size_t wantToWrite = packet->packet.available(_bytesSent); - if (wantToWrite == 0) { - EMC_SEMAPHORE_GIVE(); - return 0; - } - written = _transport->write(packet->packet.data(_bytesSent), wantToWrite); - packet->timeSent = millis(); - _lastClientActivity = millis(); - _bytesSent += written; - emc_log_i("tx %zu/%zu (%02x)", _bytesSent, packet->packet.size(), packet->packet.packetType()); + size_t written = 0; + if (packet) { + size_t wantToWrite = packet->packet.available(_bytesSent); + if (wantToWrite == 0) { + return 0; } - EMC_SEMAPHORE_GIVE(); - return written; + written = _transport->write(packet->packet.data(_bytesSent), wantToWrite); + packet->timeSent = millis(); + _lastClientActivity = millis(); + _bytesSent += written; + emc_log_i("tx %zu/%zu (%02x)", _bytesSent, packet->packet.size(), packet->packet.packetType()); + } + return written; } bool MqttClient::_advanceOutbox() { - EMC_SEMAPHORE_TAKE(); - OutgoingPacket * packet = _outbox.getCurrent(); - if (packet && _bytesSent == packet->packet.size()) { - if ((packet->packet.packetType()) == PacketType.DISCONNECT) { - _state = State::disconnectingTcp1; - _disconnectReason = DisconnectReason::USER_OK; - } - if (packet->packet.removable()) { - _outbox.removeCurrent(); - } else { - // we already set 'dup' here, in case we have to retry - if ((packet->packet.packetType()) == PacketType.PUBLISH) - packet->packet.setDup(); - _outbox.next(); - } - packet = _outbox.getCurrent(); - _bytesSent = 0; + OutgoingPacket* packet = _outbox.getCurrent(); + if (packet && _bytesSent == packet->packet.size()) { + if ((packet->packet.packetType()) == PacketType.DISCONNECT) { + _setState(State::disconnectingTcp1); + _disconnectReason = DisconnectReason::USER_OK; } - EMC_SEMAPHORE_GIVE(); - return packet; + if (packet->packet.removable()) { + _outbox.removeCurrent(); + } else { + // we already set 'dup' here, in case we have to retry + if ((packet->packet.packetType()) == PacketType.PUBLISH) packet->packet.setDup(); + _outbox.next(); + } + packet = _outbox.getCurrent(); + _bytesSent = 0; + } + return packet; } void MqttClient::_checkIncoming() { - int32_t remainingBufferLength = _transport->read(_rxBuffer, EMC_RX_BUFFER_SIZE); - if (remainingBufferLength > 0) { - _lastServerActivity = millis(); - emc_log_i("rx len %i", remainingBufferLength); - size_t bytesParsed = 0; - size_t index = 0; - while (remainingBufferLength > 0) { - espMqttClientInternals::ParserResult result = _parser.parse(&_rxBuffer[index], remainingBufferLength, &bytesParsed); - if (result == espMqttClientInternals::ParserResult::packet) { - espMqttClientInternals::MQTTPacketType packetType = _parser.getPacket().fixedHeader.packetType & 0xF0; - if (_state == State::connectingMqtt && packetType != PacketType.CONNACK) { - emc_log_w("Disconnecting, expected CONNACK - protocol error"); - _state = State::disconnectingTcp1; - return; - } - switch (packetType & 0xF0) { - case PacketType.CONNACK: - _onConnack(); - if (_state != State::connected) { - return; - } - break; - case PacketType.PUBLISH: - if (_state >= State::disconnectingMqtt1) - break; // stop processing incoming once user has called disconnect - _onPublish(); - break; - case PacketType.PUBACK: - _onPuback(); - break; - case PacketType.PUBREC: - _onPubrec(); - break; - case PacketType.PUBREL: - _onPubrel(); - break; - case PacketType.PUBCOMP: - _onPubcomp(); - break; - case PacketType.SUBACK: - _onSuback(); - break; - case PacketType.UNSUBACK: - _onUnsuback(); - break; - case PacketType.PINGRESP: - _pingSent = false; - break; - } - } else if (result == espMqttClientInternals::ParserResult::protocolError) { - emc_log_w("Disconnecting, protocol error"); - _state = State::disconnectingTcp1; - _disconnectReason = DisconnectReason::TCP_DISCONNECTED; - return; - } - remainingBufferLength -= bytesParsed; - index += bytesParsed; - emc_log_i("Parsed %zu - remaining %i", bytesParsed, remainingBufferLength); - bytesParsed = 0; + int32_t remainingBufferLength = _transport->read(_rxBuffer, EMC_RX_BUFFER_SIZE); + if (remainingBufferLength > 0) { + _lastServerActivity = millis(); + emc_log_i("rx len %i", remainingBufferLength); + size_t bytesParsed = 0; + size_t index = 0; + while (remainingBufferLength > 0) { + espMqttClientInternals::ParserResult result = _parser.parse(&_rxBuffer[index], remainingBufferLength, &bytesParsed); + if (result == espMqttClientInternals::ParserResult::packet) { + espMqttClientInternals::MQTTPacketType packetType = _parser.getPacket().fixedHeader.packetType & 0xF0; + if (_state == State::connectingMqtt && packetType != PacketType.CONNACK) { + emc_log_w("Disconnecting, expected CONNACK - protocol error"); + _setState(State::disconnectingTcp1); + return; } + switch (packetType) { + case PacketType.CONNACK: + _onConnack(); + if (_state != State::connected) { + return; + } + break; + case PacketType.PUBLISH: + if (_state >= State::disconnectingMqtt1) break; // stop processing incoming once user has called disconnect + _onPublish(); + break; + case PacketType.PUBACK: + _onPuback(); + break; + case PacketType.PUBREC: + _onPubrec(); + break; + case PacketType.PUBREL: + _onPubrel(); + break; + case PacketType.PUBCOMP: + _onPubcomp(); + break; + case PacketType.SUBACK: + _onSuback(); + break; + case PacketType.UNSUBACK: + _onUnsuback(); + break; + case PacketType.PINGRESP: + _pingSent = false; + break; + } + } else if (result == espMqttClientInternals::ParserResult::protocolError) { + emc_log_w("Disconnecting, protocol error"); + _setState(State::disconnectingTcp1); + _disconnectReason = DisconnectReason::TCP_DISCONNECTED; + return; + } + remainingBufferLength -= bytesParsed; + index += bytesParsed; + emc_log_i("Parsed %zu - remaining %i", bytesParsed, remainingBufferLength); + bytesParsed = 0; } + } } void MqttClient::_checkPing() { - if (_keepAlive == 0) - return; // keepalive is disabled + if (_keepAlive == 0) return; // keepalive is disabled - uint32_t currentMillis = millis(); + uint32_t currentMillis = millis(); - // disconnect when server was inactive for twice the keepalive time - if (currentMillis - _lastServerActivity > 2 * _keepAlive) { - emc_log_w("Disconnecting, server exceeded keepalive"); - _state = State::disconnectingTcp1; - _disconnectReason = DisconnectReason::TCP_DISCONNECTED; - return; - } - - // send ping when client was inactive during the keepalive time - // or when server hasn't responded within keepalive time (typically due to QOS 0) - if (!_pingSent && ((currentMillis - _lastClientActivity > _keepAlive) || (currentMillis - _lastServerActivity > _keepAlive))) { - EMC_SEMAPHORE_TAKE(); - if (!_addPacket(PacketType.PINGREQ)) { - EMC_SEMAPHORE_GIVE(); - emc_log_e("Could not create PING packet"); - return; - } - EMC_SEMAPHORE_GIVE(); - _pingSent = true; + // disconnect when server was inactive for twice the keepalive time + if (currentMillis - _lastServerActivity > 2 * _keepAlive) { + emc_log_w("Disconnecting, server exceeded keepalive"); + _setState(State::disconnectingTcp1); + _disconnectReason = DisconnectReason::TCP_DISCONNECTED; + return; + } + + // send ping when client was inactive during the keepalive time + // or when server hasn't responded within keepalive time (typically due to QOS 0) + if (!_pingSent && + ((currentMillis - _lastClientActivity > _keepAlive) || + (currentMillis - _lastServerActivity > _keepAlive))) { + if (!_addPacket(PacketType.PINGREQ)) { + emc_log_e("Could not create PING packet"); + return; } + _pingSent = true; + } } void MqttClient::_checkTimeout() { - EMC_SEMAPHORE_TAKE(); - espMqttClientInternals::Outbox::Iterator it = _outbox.front(); - // check that we're not busy sending - // don't check when first item hasn't been sent yet - if (it && _bytesSent == 0 && it.get() != _outbox.getCurrent()) { - if (millis() - it.get()->timeSent > _timeout) { - emc_log_w("Packet ack timeout, retrying"); - _outbox.resetCurrent(); - } + espMqttClientInternals::Outbox::Iterator it = _outbox.front(); + // check that we're not busy sending + // don't check when first item hasn't been sent yet + if (it && _bytesSent == 0 && it.get() != _outbox.getCurrent()) { + if (millis() - it.get()->timeSent > _timeout) { + emc_log_w("Packet ack timeout, retrying"); + _outbox.resetCurrent(); } - EMC_SEMAPHORE_GIVE(); + } } void MqttClient::_onConnack() { - if (_parser.getPacket().variableHeader.fixed.connackVarHeader.returnCode == 0x00) { - _pingSent = false; // reset after keepalive timeout disconnect - _state = State::connected; - _advanceOutbox(); - if (_parser.getPacket().variableHeader.fixed.connackVarHeader.sessionPresent == 0) { - _clearQueue(1); - } - if (_onConnectCallback) { - _onConnectCallback(_parser.getPacket().variableHeader.fixed.connackVarHeader.sessionPresent); - } - } else { - _state = State::disconnectingTcp1; - // cast is safe because the parser already checked for a valid return code - _disconnectReason = static_cast(_parser.getPacket().variableHeader.fixed.connackVarHeader.returnCode); + if (_parser.getPacket().variableHeader.fixed.connackVarHeader.returnCode == 0x00) { + _pingSent = false; // reset after keepalive timeout disconnect + _setState(State::connected); + _advanceOutbox(); + if (_parser.getPacket().variableHeader.fixed.connackVarHeader.sessionPresent == 0) { + _clearQueue(1); } + if (_onConnectCallback) { + EMC_SEMAPHORE_GIVE(); + _onConnectCallback(_parser.getPacket().variableHeader.fixed.connackVarHeader.sessionPresent); + EMC_SEMAPHORE_TAKE(); + } + } else { + _setState(State::disconnectingTcp1); + // cast is safe because the parser already checked for a valid return code + _disconnectReason = static_cast(_parser.getPacket().variableHeader.fixed.connackVarHeader.returnCode); + } } void MqttClient::_onPublish() { - const espMqttClientInternals::IncomingPacket & p = _parser.getPacket(); - uint8_t qos = p.qos(); - bool retain = p.retain(); - bool dup = p.dup(); - uint16_t packetId = p.variableHeader.fixed.packetId; - bool callback = true; - if (qos == 1) { - if (p.payload.index + p.payload.length == p.payload.total) { - EMC_SEMAPHORE_TAKE(); - if (!_addPacket(PacketType.PUBACK, packetId)) { - emc_log_e("Could not create PUBACK packet"); - } - EMC_SEMAPHORE_GIVE(); - } - } else if (qos == 2) { - EMC_SEMAPHORE_TAKE(); - espMqttClientInternals::Outbox::Iterator it = _outbox.front(); - while (it) { - if ((it.get()->packet.packetType()) == PacketType.PUBREC && it.get()->packet.packetId() == packetId) { - callback = false; - _outbox.remove(it); - emc_log_e("QoS2 packet previously delivered"); - break; - } - ++it; - } - if (p.payload.index + p.payload.length == p.payload.total) { - if (!_addPacket(PacketType.PUBREC, packetId)) { - emc_log_e("Could not create PUBREC packet"); - } - } - EMC_SEMAPHORE_GIVE(); + const espMqttClientInternals::IncomingPacket& p = _parser.getPacket(); + uint8_t qos = p.qos(); + bool retain = p.retain(); + bool dup = p.dup(); + uint16_t packetId = p.variableHeader.fixed.packetId; + bool callback = true; + if (qos == 1) { + if (p.payload.index + p.payload.length == p.payload.total) { + if (!_addPacket(PacketType.PUBACK, packetId)) { + emc_log_e("Could not create PUBACK packet"); + } } - if (callback && _onMessageCallback) - _onMessageCallback({qos, dup, retain, packetId}, p.variableHeader.topic, p.payload.data, p.payload.length, p.payload.index, p.payload.total); + } else if (qos == 2) { + espMqttClientInternals::Outbox::Iterator it = _outbox.front(); + while (it) { + if ((it.get()->packet.packetType()) == PacketType.PUBREC && it.get()->packet.packetId() == packetId) { + callback = false; + emc_log_e("QoS2 packet previously delivered"); + break; + } + ++it; + } + if (p.payload.index + p.payload.length == p.payload.total) { + if (!_addPacket(PacketType.PUBREC, packetId)) { + emc_log_e("Could not create PUBREC packet"); + } + } + } + if (callback && _onMessageCallback) { + EMC_SEMAPHORE_GIVE(); + _onMessageCallback({qos, dup, retain, packetId}, + p.variableHeader.topic, + p.payload.data, + p.payload.length, + p.payload.index, + p.payload.total); + EMC_SEMAPHORE_TAKE(); + } } void MqttClient::_onPuback() { - bool callback = false; - uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; - EMC_SEMAPHORE_TAKE(); - espMqttClientInternals::Outbox::Iterator it = _outbox.front(); - while (it) { - // PUBACKs come in the order PUBs are sent. So we only check the first PUB packet in outbox - // if it doesn't match the ID, return - if ((it.get()->packet.packetType()) == PacketType.PUBLISH) { - if (it.get()->packet.packetId() == idToMatch) { - callback = true; - _outbox.remove(it); - break; - } - emc_log_w("Received out of order PUBACK"); - break; - } - ++it; + bool callback = false; + uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; + espMqttClientInternals::Outbox::Iterator it = _outbox.front(); + while (it) { + // PUBACKs come in the order PUBs are sent. So we only check the first PUB packet in outbox + // if it doesn't match the ID, return + if ((it.get()->packet.packetType()) == PacketType.PUBLISH) { + if (it.get()->packet.packetId() == idToMatch) { + callback = true; + _outbox.remove(it); + break; + } + emc_log_w("Received out of order PUBACK"); + break; } - EMC_SEMAPHORE_GIVE(); - if (callback) { - if (_onPublishCallback) - _onPublishCallback(idToMatch); - } else { - emc_log_w("No matching PUBLISH packet found"); + ++it; + } + if (callback) { + if (_onPublishCallback) { + EMC_SEMAPHORE_GIVE(); + _onPublishCallback(idToMatch); + EMC_SEMAPHORE_TAKE(); } + } else { + emc_log_w("No matching PUBLISH packet found"); + } } void MqttClient::_onPubrec() { - bool success = false; - uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; - EMC_SEMAPHORE_TAKE(); - espMqttClientInternals::Outbox::Iterator it = _outbox.front(); - while (it) { - // PUBRECs come in the order PUBs are sent. So we only check the first PUB packet in outbox - // if it doesn't match the ID, return - if ((it.get()->packet.packetType()) == PacketType.PUBLISH || (it.get()->packet.packetType()) == PacketType.PUBREL) { - if (it.get()->packet.packetId() == idToMatch) { - if (!_addPacket(PacketType.PUBREL, idToMatch)) { - emc_log_e("Could not create PUBREL packet"); - } - _outbox.remove(it); - success = true; - break; - } - emc_log_w("Received out of order PUBREC"); - break; + bool success = false; + uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; + espMqttClientInternals::Outbox::Iterator it = _outbox.front(); + while (it) { + // PUBRECs come in the order PUBs are sent. So we only check the first PUB packet in outbox + // if it doesn't match the ID, return + if ((it.get()->packet.packetType()) == PacketType.PUBLISH) { + if (it.get()->packet.packetId() == idToMatch) { + if (!_addPacket(PacketType.PUBREL, idToMatch)) { + emc_log_e("Could not create PUBREL packet"); } - ++it; + _outbox.remove(it); + success = true; + break; + } + emc_log_w("Received out of order PUBREC"); + break; } - if (!success) { - emc_log_w("No matching PUBLISH packet found"); - } - EMC_SEMAPHORE_GIVE(); + ++it; + } + if (!success) { + emc_log_w("No matching PUBLISH packet found"); + } } void MqttClient::_onPubrel() { - bool success = false; - uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; - EMC_SEMAPHORE_TAKE(); - espMqttClientInternals::Outbox::Iterator it = _outbox.front(); - while (it) { - // PUBRELs come in the order PUBRECs are sent. So we only check the first PUBREC packet in outbox - // if it doesn't match the ID, return - if ((it.get()->packet.packetType()) == PacketType.PUBREC) { - if (it.get()->packet.packetId() == idToMatch) { - if (!_addPacket(PacketType.PUBCOMP, idToMatch)) { - emc_log_e("Could not create PUBCOMP packet"); - } - _outbox.remove(it); - success = true; - break; - } - emc_log_w("Received out of order PUBREL"); - break; + bool success = false; + uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; + espMqttClientInternals::Outbox::Iterator it = _outbox.front(); + while (it) { + // PUBRELs come in the order PUBRECs are sent. So we only check the first PUBREC packet in outbox + // if it doesn't match the ID, return + if ((it.get()->packet.packetType()) == PacketType.PUBREC) { + if (it.get()->packet.packetId() == idToMatch) { + if (!_addPacket(PacketType.PUBCOMP, idToMatch)) { + emc_log_e("Could not create PUBCOMP packet"); } - ++it; + _outbox.remove(it); + success = true; + break; + } + emc_log_w("Received out of order PUBREL"); + break; } - if (!success) { - emc_log_w("No matching PUBREC packet found"); - } - EMC_SEMAPHORE_GIVE(); + ++it; + } + if (!success) { + emc_log_w("No matching PUBREC packet found"); + } } void MqttClient::_onPubcomp() { - bool callback = false; - EMC_SEMAPHORE_TAKE(); - espMqttClientInternals::Outbox::Iterator it = _outbox.front(); - uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; - while (it) { - // PUBCOMPs come in the order PUBRELs are sent. So we only check the first PUBREL packet in outbox - // if it doesn't match the ID, return - if ((it.get()->packet.packetType()) == PacketType.PUBREL) { - if (it.get()->packet.packetId() == idToMatch) { - callback = true; - _outbox.remove(it); - break; - } - emc_log_w("Received out of order PUBCOMP"); - break; - } - ++it; + bool callback = false; + espMqttClientInternals::Outbox::Iterator it = _outbox.front(); + uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; + while (it) { + // PUBCOMPs come in the order PUBRELs are sent. So we only check the first PUBREL packet in outbox + // if it doesn't match the ID, return + if ((it.get()->packet.packetType()) == PacketType.PUBREL) { + if (it.get()->packet.packetId() == idToMatch) { + callback = true; + _outbox.remove(it); + break; + } + emc_log_w("Received out of order PUBCOMP"); + break; } - EMC_SEMAPHORE_GIVE(); - if (callback) { - if (_onPublishCallback) - _onPublishCallback(idToMatch); - } else { - emc_log_w("No matching PUBREL packet found"); + ++it; + } + if (callback) { + if (_onPublishCallback) { + EMC_SEMAPHORE_GIVE(); + _onPublishCallback(idToMatch); + EMC_SEMAPHORE_TAKE(); } + } else { + emc_log_w("No matching PUBREL packet found"); + } } void MqttClient::_onSuback() { - bool callback = false; - uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; - EMC_SEMAPHORE_TAKE(); - espMqttClientInternals::Outbox::Iterator it = _outbox.front(); - while (it) { - if (((it.get()->packet.packetType()) == PacketType.SUBSCRIBE) && it.get()->packet.packetId() == idToMatch) { - callback = true; - _outbox.remove(it); - break; - } - ++it; + bool callback = false; + uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; + espMqttClientInternals::Outbox::Iterator it = _outbox.front(); + while (it) { + if (((it.get()->packet.packetType()) == PacketType.SUBSCRIBE) && it.get()->packet.packetId() == idToMatch) { + callback = true; + _outbox.remove(it); + break; } - EMC_SEMAPHORE_GIVE(); - if (callback) { - if (_onSubscribeCallback) - _onSubscribeCallback(idToMatch, - reinterpret_cast(_parser.getPacket().payload.data), - _parser.getPacket().payload.total); - } else { - emc_log_w("received SUBACK without SUB"); + ++it; + } + if (callback) { + if (_onSubscribeCallback) { + EMC_SEMAPHORE_GIVE(); + _onSubscribeCallback(idToMatch, reinterpret_cast(_parser.getPacket().payload.data), _parser.getPacket().payload.total); + EMC_SEMAPHORE_TAKE(); } + } else { + emc_log_w("received SUBACK without SUB"); + } } void MqttClient::_onUnsuback() { - bool callback = false; - EMC_SEMAPHORE_TAKE(); - espMqttClientInternals::Outbox::Iterator it = _outbox.front(); - uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; - while (it) { - if (it.get()->packet.packetId() == idToMatch) { - callback = true; - _outbox.remove(it); - break; - } - ++it; + bool callback = false; + espMqttClientInternals::Outbox::Iterator it = _outbox.front(); + uint16_t idToMatch = _parser.getPacket().variableHeader.fixed.packetId; + while (it) { + if (it.get()->packet.packetId() == idToMatch) { + callback = true; + _outbox.remove(it); + break; } - EMC_SEMAPHORE_GIVE(); - if (callback) { - if (_onUnsubscribeCallback) - _onUnsubscribeCallback(idToMatch); - } else { - emc_log_w("received UNSUBACK without UNSUB"); + ++it; + } + if (callback) { + if (_onUnsubscribeCallback) { + EMC_SEMAPHORE_GIVE(); + _onUnsubscribeCallback(idToMatch); + EMC_SEMAPHORE_TAKE(); } + } else { + emc_log_w("received UNSUBACK without UNSUB"); + } } void MqttClient::_clearQueue(int clearData) { - emc_log_i("clearing queue (clear session: %d)", clearData); - EMC_SEMAPHORE_TAKE(); - espMqttClientInternals::Outbox::Iterator it = _outbox.front(); - if (clearData == 0) { - // keep PUB (qos > 0, aka packetID != 0), PUBREC and PUBREL - // Spec only mentions PUB and PUBREL but this lib implements method B from point 4.3.3 (Fig. 4.3) - // and stores the packet id in the PUBREC packet. So we also must keep PUBREC. - while (it) { - espMqttClientInternals::MQTTPacketType type = it.get()->packet.packetType(); - if (type == PacketType.PUBREC || type == PacketType.PUBREL || (type == PacketType.PUBLISH && it.get()->packet.packetId() != 0)) { - ++it; - } else { - _outbox.remove(it); - } - } - } else if (clearData == 1) { - // keep PUB - while (it) { - if (it.get()->packet.packetType() == PacketType.PUBLISH) { - ++it; - } else { - _outbox.remove(it); - } - } - } else { // clearData == 2 - while (it) { - _outbox.remove(it); - } + emc_log_i("clearing queue (clear session: %d)", clearData); + espMqttClientInternals::Outbox::Iterator it = _outbox.front(); + if (clearData == 0) { + // keep PUB (qos > 0, aka packetID != 0), PUBREC and PUBREL + // Spec only mentions PUB and PUBREL but this lib implements method B from point 4.3.3 (Fig. 4.3) + // and stores the packet id in the PUBREC packet. So we also must keep PUBREC. + while (it) { + espMqttClientInternals::MQTTPacketType type = it.get()->packet.packetType(); + if (type == PacketType.PUBREC || + type == PacketType.PUBREL || + (type == PacketType.PUBLISH && it.get()->packet.packetId() != 0)) { + ++it; + } else { + _outbox.remove(it); + } } - EMC_SEMAPHORE_GIVE(); + } else if (clearData == 1) { + // keep PUB + while (it) { + if (it.get()->packet.packetType() == PacketType.PUBLISH) { + ++it; + } else { + _outbox.remove(it); + } + } + } else { // clearData == 2 + while (it) { + _outbox.remove(it); + } + } } void MqttClient::_onError(uint16_t packetId, espMqttClientTypes::Error error) { - if (_onErrorCallback) { - _onErrorCallback(packetId, error); - } + if (_onErrorCallback) { + _onErrorCallback(packetId, error); + } } diff --git a/lib/espMqttClient/src/MqttClient.h b/lib/espMqttClient/src/MqttClient.h index dba4bf245..eaf9d2d79 100644 --- a/lib/espMqttClient/src/MqttClient.h +++ b/lib/espMqttClient/src/MqttClient.h @@ -24,179 +24,178 @@ the LICENSE file. #include "Transport/Transport.h" class MqttClient { - public: - virtual ~MqttClient(); - bool connected() const; - bool disconnected() const; - bool connect(); - bool disconnect(bool force = false); - template - uint16_t subscribe(const char * topic, uint8_t qos, Args &&... args) { - uint16_t packetId = _getNextPacketId(); - if (_state != State::connected) { - packetId = 0; - } else { - EMC_SEMAPHORE_TAKE(); - if (!_addPacket(packetId, topic, qos, std::forward(args)...)) { - emc_log_e("Could not create SUBSCRIBE packet"); - packetId = 0; - } - EMC_SEMAPHORE_GIVE(); - } - return packetId; + public: + virtual ~MqttClient(); + bool connected() const; + bool disconnected() const; + bool connect(); + bool disconnect(bool force = false); + template + uint16_t subscribe(const char* topic, uint8_t qos, Args&&... args) { + uint16_t packetId = 0; + if (_state != State::connected) { + return packetId; + } else { + EMC_SEMAPHORE_TAKE(); + packetId = _getNextPacketId(); + if (!_addPacket(packetId, topic, qos, std::forward(args) ...)) { + emc_log_e("Could not create SUBSCRIBE packet"); + packetId = 0; + } + EMC_SEMAPHORE_GIVE(); } - template - uint16_t unsubscribe(const char * topic, Args &&... args) { - uint16_t packetId = _getNextPacketId(); - if (_state != State::connected) { - packetId = 0; - } else { - EMC_SEMAPHORE_TAKE(); - if (!_addPacket(packetId, topic, std::forward(args)...)) { - emc_log_e("Could not create UNSUBSCRIBE packet"); - packetId = 0; - } - EMC_SEMAPHORE_GIVE(); - } - return packetId; + return packetId; + } + template + uint16_t unsubscribe(const char* topic, Args&&... args) { + uint16_t packetId = 0; + if (_state != State::connected) { + return packetId; + } else { + EMC_SEMAPHORE_TAKE(); + packetId = _getNextPacketId(); + if (!_addPacket(packetId, topic, std::forward(args) ...)) { + emc_log_e("Could not create UNSUBSCRIBE packet"); + packetId = 0; + } + EMC_SEMAPHORE_GIVE(); } - uint16_t publish(const char * topic, uint8_t qos, bool retain, const uint8_t * payload, size_t length); - uint16_t publish(const char * topic, uint8_t qos, bool retain, const char * payload); - uint16_t publish(const char * topic, uint8_t qos, bool retain, espMqttClientTypes::PayloadCallback callback, size_t length); - void clearQueue(bool deleteSessionData = false); // Not MQTT compliant and may cause unpredictable results when `deleteSessionData` = true! - const char * getClientId() const; - size_t queueSize(); // No const because of mutex - void loop(); + return packetId; + } + uint16_t publish(const char* topic, uint8_t qos, bool retain, const uint8_t* payload, size_t length); + uint16_t publish(const char* topic, uint8_t qos, bool retain, const char* payload); + uint16_t publish(const char* topic, uint8_t qos, bool retain, espMqttClientTypes::PayloadCallback callback, size_t length); + void clearQueue(bool deleteSessionData = false); // Not MQTT compliant and may cause unpredictable results when `deleteSessionData` = true! + const char* getClientId() const; + size_t queueSize(); // No const because of mutex + void loop(); - protected: - explicit MqttClient(espMqttClientTypes::UseInternalTask useInternalTask, uint8_t priority = 1, uint8_t core = 1); - espMqttClientTypes::UseInternalTask _useInternalTask; - espMqttClientInternals::Transport * _transport; + protected: + explicit MqttClient(espMqttClientTypes::UseInternalTask useInternalTask, uint8_t priority = 1, uint8_t core = 1); + espMqttClientTypes::UseInternalTask _useInternalTask; + espMqttClientInternals::Transport* _transport; - espMqttClientTypes::OnConnectCallback _onConnectCallback; - espMqttClientTypes::OnDisconnectCallback _onDisconnectCallback; - espMqttClientTypes::OnSubscribeCallback _onSubscribeCallback; - espMqttClientTypes::OnUnsubscribeCallback _onUnsubscribeCallback; - espMqttClientTypes::OnMessageCallback _onMessageCallback; - espMqttClientTypes::OnPublishCallback _onPublishCallback; - espMqttClientTypes::OnErrorCallback _onErrorCallback; - typedef void (*mqttClientHook)(void *); - const char * _clientId; - IPAddress _ip; - const char * _host; - uint16_t _port; - bool _useIp; - uint32_t _keepAlive; - bool _cleanSession; - const char * _username; - const char * _password; - const char * _willTopic; - const uint8_t * _willPayload; - uint16_t _willPayloadLength; - uint8_t _willQos; - bool _willRetain; - uint32_t _timeout; + espMqttClientTypes::OnConnectCallback _onConnectCallback; + espMqttClientTypes::OnDisconnectCallback _onDisconnectCallback; + espMqttClientTypes::OnSubscribeCallback _onSubscribeCallback; + espMqttClientTypes::OnUnsubscribeCallback _onUnsubscribeCallback; + espMqttClientTypes::OnMessageCallback _onMessageCallback; + espMqttClientTypes::OnPublishCallback _onPublishCallback; + espMqttClientTypes::OnErrorCallback _onErrorCallback; + typedef void(*mqttClientHook)(void*); + const char* _clientId; + IPAddress _ip; + const char* _host; + uint16_t _port; + bool _useIp; + uint32_t _keepAlive; + bool _cleanSession; + const char* _username; + const char* _password; + const char* _willTopic; + const uint8_t* _willPayload; + uint16_t _willPayloadLength; + uint8_t _willQos; + bool _willRetain; + uint32_t _timeout; - // state is protected to allow state changes by the transport system, defined in child classes - // eg. to allow AsyncTCP - enum class State { - disconnected = 0, - connectingTcp1 = 1, - connectingTcp2 = 2, - connectingMqtt = 3, - connected = 4, - disconnectingMqtt1 = 5, - disconnectingMqtt2 = 6, - disconnectingTcp1 = 7, - disconnectingTcp2 = 8 - }; - std::atomic _state; + // state is protected to allow state changes by the transport system, defined in child classes + // eg. to allow AsyncTCP + enum class State { + disconnected = 0, + connectingTcp1 = 1, + connectingTcp2 = 2, + connectingMqtt = 3, + connected = 4, + disconnectingMqtt1 = 5, + disconnectingMqtt2 = 6, + disconnectingTcp1 = 7, + disconnectingTcp2 = 8 + }; + std::atomic _state; + inline void _setState(State newState); - private: - char _generatedClientId[EMC_CLIENTID_LENGTH]; - uint16_t _packetId; + private: + char _generatedClientId[EMC_CLIENTID_LENGTH]; + uint16_t _packetId; #if defined(ARDUINO_ARCH_ESP32) - SemaphoreHandle_t _xSemaphore; - TaskHandle_t _taskHandle; - static void _loop(MqttClient * c); + SemaphoreHandle_t _xSemaphore; + TaskHandle_t _taskHandle; + static void _loop(MqttClient* c); #elif defined(ARDUINO_ARCH_ESP8266) && EMC_ESP8266_MULTITHREADING - std::atomic _xSemaphore = false; + std::atomic _xSemaphore = false; #elif defined(__linux__) - mutable std::mutex mtx; // modified by proddy for EMS-ESP compiling standalone + std::mutex mtx; #endif - uint8_t _rxBuffer[EMC_RX_BUFFER_SIZE]; - struct OutgoingPacket { - uint32_t timeSent; - espMqttClientInternals::Packet packet; - template - OutgoingPacket(uint32_t t, espMqttClientTypes::Error & error, Args &&... args) - : // NOLINT(runtime/references) - timeSent(t) - , packet(error, std::forward(args)...) { - } - }; - espMqttClientInternals::Outbox _outbox; - size_t _bytesSent; - espMqttClientInternals::Parser _parser; - uint32_t _lastClientActivity; - uint32_t _lastServerActivity; - bool _pingSent; - espMqttClientTypes::DisconnectReason _disconnectReason; - - uint16_t _getNextPacketId(); - + uint8_t _rxBuffer[EMC_RX_BUFFER_SIZE]; + struct OutgoingPacket { + uint32_t timeSent; + espMqttClientInternals::Packet packet; template - bool _addPacket(Args &&... args) { - espMqttClientTypes::Error error(espMqttClientTypes::Error::SUCCESS); - espMqttClientInternals::Outbox::Iterator it = _outbox.emplace(0, error, std::forward(args)...); - if (it && error == espMqttClientTypes::Error::SUCCESS) { - return true; - } else { - if (it) - _outbox.remove(it); - return false; - } + OutgoingPacket(uint32_t t, espMqttClientTypes::Error& error, Args&&... args) : // NOLINT(runtime/references) + timeSent(t), + packet(error, std::forward(args) ...) {} + }; + espMqttClientInternals::Outbox _outbox; + size_t _bytesSent; + espMqttClientInternals::Parser _parser; + uint32_t _lastClientActivity; + uint32_t _lastServerActivity; + bool _pingSent; + espMqttClientTypes::DisconnectReason _disconnectReason; + + uint16_t _getNextPacketId(); + + template + bool _addPacket(Args&&... args) { + espMqttClientTypes::Error error(espMqttClientTypes::Error::SUCCESS); + espMqttClientInternals::Outbox::Iterator it = _outbox.emplace(0, error, std::forward(args) ...); + if (it && error == espMqttClientTypes::Error::SUCCESS) { + return true; + } else { + if (it) _outbox.remove(it); + return false; } + } - template - bool _addPacketFront(Args &&... args) { - espMqttClientTypes::Error error(espMqttClientTypes::Error::SUCCESS); - espMqttClientInternals::Outbox::Iterator it = _outbox.emplaceFront(0, error, std::forward(args)...); - if (it && error == espMqttClientTypes::Error::SUCCESS) { - return true; - } else { - if (it) - _outbox.remove(it); - return false; - } + template + bool _addPacketFront(Args&&... args) { + espMqttClientTypes::Error error(espMqttClientTypes::Error::SUCCESS); + espMqttClientInternals::Outbox::Iterator it = _outbox.emplaceFront(0, error, std::forward(args) ...); + if (it && error == espMqttClientTypes::Error::SUCCESS) { + return true; + } else { + if (it) _outbox.remove(it); + return false; } + } - void _checkOutbox(); - int _sendPacket(); - bool _advanceOutbox(); - void _checkIncoming(); - void _checkPing(); - void _checkTimeout(); + void _checkOutbox(); + int _sendPacket(); + bool _advanceOutbox(); + void _checkIncoming(); + void _checkPing(); + void _checkTimeout(); - void _onConnack(); - void _onPublish(); - void _onPuback(); - void _onPubrec(); - void _onPubrel(); - void _onPubcomp(); - void _onSuback(); - void _onUnsuback(); + void _onConnack(); + void _onPublish(); + void _onPuback(); + void _onPubrec(); + void _onPubrel(); + void _onPubcomp(); + void _onSuback(); + void _onUnsuback(); - void _clearQueue(int clearData); // 0: keep session, - // 1: keep only PUBLISH qos > 0 - // 2: delete all - void _onError(uint16_t packetId, espMqttClientTypes::Error error); + void _clearQueue(int clearData); // 0: keep session, + // 1: keep only PUBLISH qos > 0 + // 2: delete all + void _onError(uint16_t packetId, espMqttClientTypes::Error error); -#if defined(ARDUINO_ARCH_ESP32) -#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO - size_t _highWaterMark; -#endif -#endif + #if defined(ARDUINO_ARCH_ESP32) + #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO + size_t _highWaterMark; + #endif + #endif }; diff --git a/lib/espMqttClient/src/Outbox.h b/lib/espMqttClient/src/Outbox.h index cfb9f244d..4f9971c5f 100644 --- a/lib/espMqttClient/src/Outbox.h +++ b/lib/espMqttClient/src/Outbox.h @@ -1,217 +1,255 @@ - -/* -Copyright (c) 2022 Bert Melis. All rights reserved. - -This work is licensed under the terms of the MIT license. -For a copy, see or -the LICENSE file. -*/ - -#pragma once - -#include // new (std::nothrow) -#include // std::forward - -namespace espMqttClientInternals { - -/** - * @brief Singly linked queue with builtin non-invalidating forward iterator - * - * Queue items can only be emplaced, at front and back of the queue. - * Remove items using an iterator or the builtin iterator. - */ - -template -class Outbox { - public: - Outbox() - : _first(nullptr) - , _last(nullptr) - , _current(nullptr) - , _prev(nullptr) {} - ~Outbox() { - while (_first) { - Node* n = _first->next; - delete _first; - _first = n; - } - } - - struct Node { - public: - template - explicit Node(Args&&... args) - : data(std::forward(args) ...) - , next(nullptr) { - // empty - } - - T data; - Node* next; - }; - - class Iterator { - friend class Outbox; - public: - void operator++() { - if (_node) { - _prev = _node; - _node = _node->next; - } - } - - explicit operator bool() const { - if (_node) return true; - return false; - } - - T* get() const { - if (_node) return &(_node->data); - return nullptr; - } - - private: - Node* _node = nullptr; - Node* _prev = nullptr; - }; - - // add node to back, advance current to new if applicable - template - Iterator emplace(Args&&... args) { - Iterator it; - Node* node = new (std::nothrow) Node(std::forward(args) ...); - if (node != nullptr) { - if (!_first) { - // queue is empty - _first = _current = node; - } else { - // queue has at least one item - _last->next = node; - it._prev = _last; - } - _last = node; - it._node = node; - // point current to newly created if applicable - if (!_current) { - _current = _last; - } - } - return it; - } - - // add item to front, current points to newly created front. - template - Iterator emplaceFront(Args&&... args) { - Iterator it; - Node* node = new (std::nothrow) Node(std::forward(args) ...); - if (node != nullptr) { - if (!_first) { - // queue is empty - _last = node; - } else { - // queue has at least one item - node->next = _first; - } - _current = _first = node; - _prev = nullptr; - it._node = node; - } - return it; - } - - // remove node at iterator, iterator points to next - void remove(Iterator& it) { // NOLINT(runtime/references) - if (!it) return; - Node* node = it._node; - Node* prev = it._prev; - ++it; - _remove(prev, node); - } - - // remove current node, current points to next - void removeCurrent() { - _remove(_prev, _current); - } - - // Get current item or return nullptr - T* getCurrent() const { - if (_current) return &(_current->data); - return nullptr; - } - - void resetCurrent() { - _current = _first; - } - - Iterator front() const { - Iterator it; - it._node = _first; - return it; - } - - // Advance current item - void next() { - if (_current) { - _prev = _current; - _current = _current->next; - } - } - - // Outbox is empty - bool empty() { - if (!_first) return true; - return false; - } - - size_t size() const { - Node* n = _first; - size_t count = 0; - while (n) { - n = n->next; - ++count; - } - return count; - } - - private: - Node* _first; - Node* _last; - Node* _current; - Node* _prev; // element just before _current - - void _remove(Node* prev, Node* node) { - if (!node) return; - - // set current to next, node->next may be nullptr - if (_current == node) { - _current = node->next; - } - - if (_prev == node) { - _prev = prev; - } - - // only one element in outbox - if (_first == _last) { - _first = _last = nullptr; - - // delete first el in longer outbox - } else if (_first == node) { - _first = node->next; - - // delete last in longer outbox - } else if (_last == node) { - _last = prev; - _last->next = nullptr; - - // delete somewhere in the middle - } else { - prev->next = node->next; - } - - // finally, delete the node - delete node; - } -}; - -} // end namespace espMqttClientInternals + +/* +Copyright (c) 2022 Bert Melis. All rights reserved. + +This work is licensed under the terms of the MIT license. +For a copy, see or +the LICENSE file. +*/ + +#pragma once + +#if EMC_USE_MEMPOOL + #include "MemoryPool/src/MemoryPool.h" + #include "Config.h" +#else + #include // new (std::nothrow) +#endif +#include // std::forward + +namespace espMqttClientInternals { + +/** + * @brief Singly linked queue with builtin non-invalidating forward iterator + * + * Queue items can only be emplaced, at front and back of the queue. + * Remove items using an iterator or the builtin iterator. + */ + +template +class Outbox { + public: + Outbox() + : _first(nullptr) + , _last(nullptr) + , _current(nullptr) + , _prev(nullptr) + #if EMC_USE_MEMPOOL + , _memPool() + #endif + {} + ~Outbox() { + while (_first) { + Node* n = _first->next; + #if EMC_USE_MEMPOOL + _first->~Node(); + _memPool.free(_first); + #else + delete _first; + #endif + _first = n; + } + } + + struct Node { + public: + template + explicit Node(Args&&... args) + : data(std::forward(args) ...) + , next(nullptr) { + // empty + } + + T data; + Node* next; + }; + + class Iterator { + friend class Outbox; + public: + void operator++() { + if (_node) { + _prev = _node; + _node = _node->next; + } + } + + explicit operator bool() const { + if (_node) return true; + return false; + } + + T* get() const { + if (_node) return &(_node->data); + return nullptr; + } + + private: + Node* _node = nullptr; + Node* _prev = nullptr; + }; + + // add node to back, advance current to new if applicable + template + Iterator emplace(Args&&... args) { + Iterator it; + #if EMC_USE_MEMPOOL + void* buf = _memPool.malloc(); + Node* node = nullptr; + if (buf) { + node = new(buf) Node(std::forward(args) ...); + } + #else + Node* node = new(std::nothrow) Node(std::forward(args) ...); + #endif + if (node != nullptr) { + if (!_first) { + // queue is empty + _first = _current = node; + } else { + // queue has at least one item + _last->next = node; + it._prev = _last; + } + _last = node; + it._node = node; + // point current to newly created if applicable + if (!_current) { + _current = _last; + } + } + return it; + } + + // add item to front, current points to newly created front. + template + Iterator emplaceFront(Args&&... args) { + Iterator it; + #if EMC_USE_MEMPOOL + void* buf = _memPool.malloc(); + Node* node = nullptr; + if (buf) { + node = new(buf) Node(std::forward(args) ...); + } + #else + Node* node = new(std::nothrow) Node(std::forward(args) ...); + #endif + if (node != nullptr) { + if (!_first) { + // queue is empty + _last = node; + } else { + // queue has at least one item + node->next = _first; + } + _current = _first = node; + _prev = nullptr; + it._node = node; + } + return it; + } + + // remove node at iterator, iterator points to next + void remove(Iterator& it) { // NOLINT(runtime/references) + if (!it) return; + Node* node = it._node; + Node* prev = it._prev; + ++it; + _remove(prev, node); + } + + // remove current node, current points to next + void removeCurrent() { + _remove(_prev, _current); + } + + // Get current item or return nullptr + T* getCurrent() const { + if (_current) return &(_current->data); + return nullptr; + } + + void resetCurrent() { + _current = _first; + } + + Iterator front() const { + Iterator it; + it._node = _first; + return it; + } + + // Advance current item + void next() { + if (_current) { + _prev = _current; + _current = _current->next; + } + } + + // Outbox is empty + bool empty() { + if (!_first) return true; + return false; + } + + size_t size() const { + Node* n = _first; + size_t count = 0; + while (n) { + n = n->next; + ++count; + } + return count; + } + + private: + Node* _first; + Node* _last; + Node* _current; + Node* _prev; // element just before _current + #if EMC_USE_MEMPOOL + MemoryPool::Fixed _memPool; + #endif + + void _remove(Node* prev, Node* node) { + if (!node) return; + + // set current to next, node->next may be nullptr + if (_current == node) { + _current = node->next; + } + + if (_prev == node) { + _prev = prev; + } + + // only one element in outbox + if (_first == _last) { + _first = _last = nullptr; + + // delete first el in longer outbox + } else if (_first == node) { + _first = node->next; + + // delete last in longer outbox + } else if (_last == node) { + _last = prev; + _last->next = nullptr; + + // delete somewhere in the middle + } else { + prev->next = node->next; + } + + // finally, delete the node + #if EMC_USE_MEMPOOL + node->~Node(); + _memPool.free(node); + #else + delete node; + #endif + } +}; + +} // end namespace espMqttClientInternals diff --git a/lib/espMqttClient/src/Packets/Packet.cpp b/lib/espMqttClient/src/Packets/Packet.cpp index 5f9ceb486..14d241b20 100644 --- a/lib/espMqttClient/src/Packets/Packet.cpp +++ b/lib/espMqttClient/src/Packets/Packet.cpp @@ -10,427 +10,445 @@ the LICENSE file. namespace espMqttClientInternals { +#if EMC_USE_MEMPOOL +MemoryPool::Variable Packet::_memPool; +#endif + Packet::~Packet() { - free(_data); + #if EMC_USE_MEMPOOL + _memPool.free(_data); + #else + free(_data); + #endif } size_t Packet::available(size_t index) { - if (index >= _size) - return 0; - if (!_getPayload) - return _size - index; - return _chunkedAvailable(index); + if (index >= _size) return 0; + if (!_getPayload) return _size - index; + return _chunkedAvailable(index); } -const uint8_t * Packet::data(size_t index) const { - if (!_getPayload) { - if (!_data) - return nullptr; - if (index >= _size) - return nullptr; - return &_data[index]; - } - return _chunkedData(index); +const uint8_t* Packet::data(size_t index) const { + if (!_getPayload) { + if (!_data) return nullptr; + if (index >= _size) return nullptr; + return &_data[index]; + } + return _chunkedData(index); } size_t Packet::size() const { - return _size; + return _size; } void Packet::setDup() { - if (!_data) - return; - if (packetType() != PacketType.PUBLISH) - return; - if (_packetId == 0) - return; - _data[0] |= 0x08; + if (!_data) return; + if (packetType() != PacketType.PUBLISH) return; + if (_packetId == 0) return; + _data[0] |= 0x08; } uint16_t Packet::packetId() const { - return _packetId; + return _packetId; } MQTTPacketType Packet::packetType() const { - if (_data) - return static_cast(_data[0] & 0xF0); - return static_cast(0); + if (_data) return static_cast(_data[0] & 0xF0); + return static_cast(0); } bool Packet::removable() const { - if (_packetId == 0) - return true; - if ((packetType() == PacketType.PUBACK) || (packetType() == PacketType.PUBCOMP)) - return true; - return false; + if (_packetId == 0) return true; + if ((packetType() == PacketType.PUBACK) || (packetType() == PacketType.PUBCOMP)) return true; + return false; } -Packet::Packet(espMqttClientTypes::Error & error, - bool cleanSession, - const char * username, - const char * password, - const char * willTopic, - bool willRetain, - uint8_t willQos, - const uint8_t * willPayload, - uint16_t willPayloadLength, - uint16_t keepAlive, - const char * clientId) - : _packetId(0) - , _data(nullptr) - , _size(0) - , _payloadIndex(0) - , _payloadStartIndex(0) - , _payloadEndIndex(0) - , _getPayload(nullptr) { - if (willPayload && willPayloadLength == 0) { - size_t length = strlen(reinterpret_cast(willPayload)); - if (length > UINT16_MAX) { - emc_log_w("Payload length truncated (l:%zu)", length); - willPayloadLength = UINT16_MAX; - } else { - willPayloadLength = length; - } - } - if (!clientId || strlen(clientId) == 0) { - emc_log_w("clientId not set error"); - error = espMqttClientTypes::Error::MALFORMED_PARAMETER; - return; - } - - // Calculate size - size_t remainingLength = 6 + // protocol - 1 + // protocol level - 1 + // connect flags - 2 + // keepalive - 2 + strlen(clientId) + (willTopic ? 2 + strlen(willTopic) + 2 + willPayloadLength : 0) + (username ? 2 + strlen(username) : 0) - + (password ? 2 + strlen(password) : 0); - - // allocate memory - if (!_allocate(remainingLength, false)) { - error = espMqttClientTypes::Error::OUT_OF_MEMORY; - return; - } - - // serialize - size_t pos = 0; - - // FIXED HEADER - _data[pos++] = PacketType.CONNECT | HeaderFlag.CONNECT_RESERVED; - pos += encodeRemainingLength(remainingLength, &_data[pos]); - pos += encodeString(PROTOCOL, &_data[pos]); - _data[pos++] = PROTOCOL_LEVEL; - uint8_t connectFlags = 0; - if (cleanSession) - connectFlags |= espMqttClientInternals::ConnectFlag.CLEAN_SESSION; - if (username != nullptr) - connectFlags |= espMqttClientInternals::ConnectFlag.USERNAME; - if (password != nullptr) - connectFlags |= espMqttClientInternals::ConnectFlag.PASSWORD; - if (willTopic != nullptr) { - connectFlags |= espMqttClientInternals::ConnectFlag.WILL; - if (willRetain) - connectFlags |= espMqttClientInternals::ConnectFlag.WILL_RETAIN; - switch (willQos) { - case 0: - connectFlags |= espMqttClientInternals::ConnectFlag.WILL_QOS0; - break; - case 1: - connectFlags |= espMqttClientInternals::ConnectFlag.WILL_QOS1; - break; - case 2: - connectFlags |= espMqttClientInternals::ConnectFlag.WILL_QOS2; - break; - } - } - _data[pos++] = connectFlags; - _data[pos++] = keepAlive >> 8; - _data[pos++] = keepAlive & 0xFF; - - // PAYLOAD - // client ID - pos += encodeString(clientId, &_data[pos]); - // will - if (willTopic != nullptr && willPayload != nullptr) { - pos += encodeString(willTopic, &_data[pos]); - _data[pos++] = willPayloadLength >> 8; - _data[pos++] = willPayloadLength & 0xFF; - memcpy(&_data[pos], willPayload, willPayloadLength); - pos += willPayloadLength; - } - // credentials - if (username != nullptr) - pos += encodeString(username, &_data[pos]); - if (password != nullptr) - encodeString(password, &_data[pos]); - - error = espMqttClientTypes::Error::SUCCESS; -} - -Packet::Packet(espMqttClientTypes::Error & error, uint16_t packetId, const char * topic, const uint8_t * payload, size_t payloadLength, uint8_t qos, bool retain) - : _packetId(packetId) - , _data(nullptr) - , _size(0) - , _payloadIndex(0) - , _payloadStartIndex(0) - , _payloadEndIndex(0) - , _getPayload(nullptr) { - size_t remainingLength = 2 + strlen(topic) + // topic length + topic - 2 + // packet ID - payloadLength; - - if (qos == 0) { - remainingLength -= 2; - _packetId = 0; - } - - if (!_allocate(remainingLength)) { - error = espMqttClientTypes::Error::OUT_OF_MEMORY; - return; - } - - size_t pos = _fillPublishHeader(packetId, topic, remainingLength, qos, retain); - - // PAYLOAD - memcpy(&_data[pos], payload, payloadLength); - - error = espMqttClientTypes::Error::SUCCESS; -} - -Packet::Packet(espMqttClientTypes::Error & error, - uint16_t packetId, - const char * topic, - espMqttClientTypes::PayloadCallback payloadCallback, - size_t payloadLength, - uint8_t qos, - bool retain) - : _packetId(packetId) - , _data(nullptr) - , _size(0) - , _payloadIndex(0) - , _payloadStartIndex(0) - , _payloadEndIndex(0) - , _getPayload(payloadCallback) { - size_t remainingLength = 2 + strlen(topic) + // topic length + topic - 2 + // packet ID - payloadLength; - - if (qos == 0) { - remainingLength -= 2; - _packetId = 0; - } - - if (!_allocate(remainingLength - payloadLength + std::min(payloadLength, static_cast(EMC_RX_BUFFER_SIZE)))) { - error = espMqttClientTypes::Error::OUT_OF_MEMORY; - return; - } - - size_t pos = _fillPublishHeader(packetId, topic, remainingLength, qos, retain); - - // payload will be added by 'Packet::available' - _size = pos + payloadLength; - _payloadIndex = pos; - _payloadStartIndex = _payloadIndex; - _payloadEndIndex = _payloadIndex; - - error = espMqttClientTypes::Error::SUCCESS; -} - -Packet::Packet(espMqttClientTypes::Error & error, uint16_t packetId, const char * topic, uint8_t qos) - : _packetId(packetId) - , _data(nullptr) - , _size(0) - , _payloadIndex(0) - , _payloadStartIndex(0) - , _payloadEndIndex(0) - , _getPayload(nullptr) { - SubscribeItem list[1] = {{topic, qos}}; - _createSubscribe(error, list, 1); -} - -Packet::Packet(espMqttClientTypes::Error & error, MQTTPacketType type, uint16_t packetId) - : _packetId(packetId) - , _data(nullptr) - , _size(0) - , _payloadIndex(0) - , _payloadStartIndex(0) - , _payloadEndIndex(0) - , _getPayload(nullptr) { - if (!_allocate(2)) { - error = espMqttClientTypes::Error::OUT_OF_MEMORY; - return; - } - - size_t pos = 0; - _data[pos] = type; - if (type == PacketType.PUBREL) { - _data[pos++] |= HeaderFlag.PUBREL_RESERVED; +Packet::Packet(espMqttClientTypes::Error& error, + bool cleanSession, + const char* username, + const char* password, + const char* willTopic, + bool willRetain, + uint8_t willQos, + const uint8_t* willPayload, + uint16_t willPayloadLength, + uint16_t keepAlive, + const char* clientId) +: _packetId(0) +, _data(nullptr) +, _size(0) +, _payloadIndex(0) +, _payloadStartIndex(0) +, _payloadEndIndex(0) +, _getPayload(nullptr) { + if (willPayload && willPayloadLength == 0) { + size_t length = strlen(reinterpret_cast(willPayload)); + if (length > UINT16_MAX) { + emc_log_w("Payload length truncated (l:%zu)", length); + willPayloadLength = UINT16_MAX; } else { - pos++; + willPayloadLength = length; } - pos += encodeRemainingLength(2, &_data[pos]); - _data[pos++] = packetId >> 8; - _data[pos] = packetId & 0xFF; + } + if (!clientId || strlen(clientId) == 0) { + emc_log_w("clientId not set error"); + error = espMqttClientTypes::Error::MALFORMED_PARAMETER; + return; + } - error = espMqttClientTypes::Error::SUCCESS; + // Calculate size + size_t remainingLength = + 6 + // protocol + 1 + // protocol level + 1 + // connect flags + 2 + // keepalive + 2 + strlen(clientId) + + (willTopic ? 2 + strlen(willTopic) + 2 + willPayloadLength : 0) + + (username ? 2 + strlen(username) : 0) + + (password ? 2 + strlen(password) : 0); + + // allocate memory + if (!_allocate(remainingLength, false)) { + error = espMqttClientTypes::Error::OUT_OF_MEMORY; + return; + } + + // serialize + size_t pos = 0; + + // FIXED HEADER + _data[pos++] = PacketType.CONNECT | HeaderFlag.CONNECT_RESERVED; + pos += encodeRemainingLength(remainingLength, &_data[pos]); + pos += encodeString(PROTOCOL, &_data[pos]); + _data[pos++] = PROTOCOL_LEVEL; + uint8_t connectFlags = 0; + if (cleanSession) connectFlags |= espMqttClientInternals::ConnectFlag.CLEAN_SESSION; + if (username != nullptr) connectFlags |= espMqttClientInternals::ConnectFlag.USERNAME; + if (password != nullptr) connectFlags |= espMqttClientInternals::ConnectFlag.PASSWORD; + if (willTopic != nullptr) { + connectFlags |= espMqttClientInternals::ConnectFlag.WILL; + if (willRetain) connectFlags |= espMqttClientInternals::ConnectFlag.WILL_RETAIN; + switch (willQos) { + case 0: + connectFlags |= espMqttClientInternals::ConnectFlag.WILL_QOS0; + break; + case 1: + connectFlags |= espMqttClientInternals::ConnectFlag.WILL_QOS1; + break; + case 2: + connectFlags |= espMqttClientInternals::ConnectFlag.WILL_QOS2; + break; + } + } + _data[pos++] = connectFlags; + _data[pos++] = keepAlive >> 8; + _data[pos++] = keepAlive & 0xFF; + + // PAYLOAD + // client ID + pos += encodeString(clientId, &_data[pos]); + // will + if (willTopic != nullptr && willPayload != nullptr) { + pos += encodeString(willTopic, &_data[pos]); + _data[pos++] = willPayloadLength >> 8; + _data[pos++] = willPayloadLength & 0xFF; + memcpy(&_data[pos], willPayload, willPayloadLength); + pos += willPayloadLength; + } + // credentials + if (username != nullptr) pos += encodeString(username, &_data[pos]); + if (password != nullptr) encodeString(password, &_data[pos]); + + error = espMqttClientTypes::Error::SUCCESS; } -Packet::Packet(espMqttClientTypes::Error & error, uint16_t packetId, const char * topic) - : _packetId(packetId) - , _data(nullptr) - , _size(0) - , _payloadIndex(0) - , _payloadStartIndex(0) - , _payloadEndIndex(0) - , _getPayload(nullptr) { - const char * list[1] = {topic}; - _createUnsubscribe(error, list, 1); +Packet::Packet(espMqttClientTypes::Error& error, + uint16_t packetId, + const char* topic, + const uint8_t* payload, + size_t payloadLength, + uint8_t qos, + bool retain) +: _packetId(packetId) +, _data(nullptr) +, _size(0) +, _payloadIndex(0) +, _payloadStartIndex(0) +, _payloadEndIndex(0) +, _getPayload(nullptr) { + size_t remainingLength = + 2 + strlen(topic) + // topic length + topic + 2 + // packet ID + payloadLength; + + if (qos == 0) { + remainingLength -= 2; + _packetId = 0; + } + + if (!_allocate(remainingLength, true)) { + error = espMqttClientTypes::Error::OUT_OF_MEMORY; + return; + } + + size_t pos = _fillPublishHeader(packetId, topic, remainingLength, qos, retain); + + // PAYLOAD + memcpy(&_data[pos], payload, payloadLength); + + error = espMqttClientTypes::Error::SUCCESS; } -Packet::Packet(espMqttClientTypes::Error & error, MQTTPacketType type) - : _packetId(0) - , _data(nullptr) - , _size(0) - , _payloadIndex(0) - , _payloadStartIndex(0) - , _payloadEndIndex(0) - , _getPayload(nullptr) { - if (!_allocate(0)) { - error = espMqttClientTypes::Error::OUT_OF_MEMORY; - return; - } - _data[0] |= type; +Packet::Packet(espMqttClientTypes::Error& error, + uint16_t packetId, + const char* topic, + espMqttClientTypes::PayloadCallback payloadCallback, + size_t payloadLength, + uint8_t qos, + bool retain) +: _packetId(packetId) +, _data(nullptr) +, _size(0) +, _payloadIndex(0) +, _payloadStartIndex(0) +, _payloadEndIndex(0) +, _getPayload(payloadCallback) { + size_t remainingLength = + 2 + strlen(topic) + // topic length + topic + 2 + // packet ID + payloadLength; - error = espMqttClientTypes::Error::SUCCESS; + if (qos == 0) { + remainingLength -= 2; + _packetId = 0; + } + + if (!_allocate(remainingLength - payloadLength + std::min(payloadLength, static_cast(EMC_RX_BUFFER_SIZE)), true)) { + error = espMqttClientTypes::Error::OUT_OF_MEMORY; + return; + } + + size_t pos = _fillPublishHeader(packetId, topic, remainingLength, qos, retain); + + // payload will be added by 'Packet::available' + _size = pos + payloadLength; + _payloadIndex = pos; + _payloadStartIndex = _payloadIndex; + _payloadEndIndex = _payloadIndex; + + error = espMqttClientTypes::Error::SUCCESS; +} + +Packet::Packet(espMqttClientTypes::Error& error, uint16_t packetId, const char* topic, uint8_t qos) +: _packetId(packetId) +, _data(nullptr) +, _size(0) +, _payloadIndex(0) +, _payloadStartIndex(0) +, _payloadEndIndex(0) +, _getPayload(nullptr) { + SubscribeItem list[1] = {topic, qos}; + _createSubscribe(error, list, 1); +} + +Packet::Packet(espMqttClientTypes::Error& error, MQTTPacketType type, uint16_t packetId) +: _packetId(packetId) +, _data(nullptr) +, _size(0) +, _payloadIndex(0) +, _payloadStartIndex(0) +, _payloadEndIndex(0) +, _getPayload(nullptr) { + if (!_allocate(2, true)) { + error = espMqttClientTypes::Error::OUT_OF_MEMORY; + return; + } + + size_t pos = 0; + _data[pos] = type; + if (type == PacketType.PUBREL) { + _data[pos++] |= HeaderFlag.PUBREL_RESERVED; + } else { + pos++; + } + pos += encodeRemainingLength(2, &_data[pos]); + _data[pos++] = packetId >> 8; + _data[pos] = packetId & 0xFF; + + error = espMqttClientTypes::Error::SUCCESS; +} + +Packet::Packet(espMqttClientTypes::Error& error, uint16_t packetId, const char* topic) +: _packetId(packetId) +, _data(nullptr) +, _size(0) +, _payloadIndex(0) +, _payloadStartIndex(0) +, _payloadEndIndex(0) +, _getPayload(nullptr) { + const char* list[1] = {topic}; + _createUnsubscribe(error, list, 1); +} + +Packet::Packet(espMqttClientTypes::Error& error, MQTTPacketType type) +: _packetId(0) +, _data(nullptr) +, _size(0) +, _payloadIndex(0) +, _payloadStartIndex(0) +, _payloadEndIndex(0) +, _getPayload(nullptr) { + if (!_allocate(0, true)) { + error = espMqttClientTypes::Error::OUT_OF_MEMORY; + return; + } + _data[0] |= type; + + error = espMqttClientTypes::Error::SUCCESS; } bool Packet::_allocate(size_t remainingLength, bool check) { - if (check && EMC_GET_FREE_MEMORY() < EMC_MIN_FREE_MEMORY) { - emc_log_w("Packet buffer not allocated: low memory"); - return false; - } - _size = 1 + remainingLengthLength(remainingLength) + remainingLength; - _data = reinterpret_cast(malloc(_size)); - if (!_data) { - _size = 0; - emc_log_w("Alloc failed (l:%zu)", _size); - return false; - } - emc_log_i("Alloc (l:%zu)", _size); - memset(_data, 0, _size); - return true; + #if EMC_USE_MEMPOOL + (void) check; + #else + if (check && EMC_GET_FREE_MEMORY() < EMC_MIN_FREE_MEMORY) { + emc_log_w("Packet buffer not allocated: low memory"); + return false; + } + #endif + _size = 1 + remainingLengthLength(remainingLength) + remainingLength; + #if EMC_USE_MEMPOOL + _data = reinterpret_cast(_memPool.malloc(_size)); + #else + _data = reinterpret_cast(malloc(_size)); + #endif + if (!_data) { + _size = 0; + emc_log_w("Alloc failed (l:%zu)", _size); + return false; + } + emc_log_i("Alloc (l:%zu)", _size); + memset(_data, 0, _size); + return true; } -size_t Packet::_fillPublishHeader(uint16_t packetId, const char * topic, size_t remainingLength, uint8_t qos, bool retain) { - size_t index = 0; +size_t Packet::_fillPublishHeader(uint16_t packetId, + const char* topic, + size_t remainingLength, + uint8_t qos, + bool retain) { + size_t index = 0; - // FIXED HEADER - _data[index] = PacketType.PUBLISH; - if (retain) - _data[index] |= HeaderFlag.PUBLISH_RETAIN; - if (qos == 0) { - _data[index++] |= HeaderFlag.PUBLISH_QOS0; - } else if (qos == 1) { - _data[index++] |= HeaderFlag.PUBLISH_QOS1; - } else if (qos == 2) { - _data[index++] |= HeaderFlag.PUBLISH_QOS2; - } - index += encodeRemainingLength(remainingLength, &_data[index]); + // FIXED HEADER + _data[index] = PacketType.PUBLISH; + if (retain) _data[index] |= HeaderFlag.PUBLISH_RETAIN; + if (qos == 0) { + _data[index++] |= HeaderFlag.PUBLISH_QOS0; + } else if (qos == 1) { + _data[index++] |= HeaderFlag.PUBLISH_QOS1; + } else if (qos == 2) { + _data[index++] |= HeaderFlag.PUBLISH_QOS2; + } + index += encodeRemainingLength(remainingLength, &_data[index]); - // VARIABLE HEADER - index += encodeString(topic, &_data[index]); - if (qos > 0) { - _data[index++] = packetId >> 8; - _data[index++] = packetId & 0xFF; - } + // VARIABLE HEADER + index += encodeString(topic, &_data[index]); + if (qos > 0) { + _data[index++] = packetId >> 8; + _data[index++] = packetId & 0xFF; + } - return index; + return index; } -void Packet::_createSubscribe(espMqttClientTypes::Error & error, SubscribeItem * list, size_t numberTopics) { - // Calculate size - size_t payload = 0; - for (size_t i = 0; i < numberTopics; ++i) { - payload += 2 + strlen(list[i].topic) + 1; // length bytes, string, qos - } - size_t remainingLength = 2 + payload; // packetId + payload +void Packet::_createSubscribe(espMqttClientTypes::Error& error, + SubscribeItem* list, + size_t numberTopics) { + // Calculate size + size_t payload = 0; + for (size_t i = 0; i < numberTopics; ++i) { + payload += 2 + strlen(list[i].topic) + 1; // length bytes, string, qos + } + size_t remainingLength = 2 + payload; // packetId + payload - // allocate memory - if (!_allocate(remainingLength)) { - error = espMqttClientTypes::Error::OUT_OF_MEMORY; - return; - } + // allocate memory + if (!_allocate(remainingLength, true)) { + error = espMqttClientTypes::Error::OUT_OF_MEMORY; + return; + } - // serialize - size_t pos = 0; - _data[pos++] = PacketType.SUBSCRIBE | HeaderFlag.SUBSCRIBE_RESERVED; - pos += encodeRemainingLength(remainingLength, &_data[pos]); - _data[pos++] = _packetId >> 8; - _data[pos++] = _packetId & 0xFF; - for (size_t i = 0; i < numberTopics; ++i) { - pos += encodeString(list[i].topic, &_data[pos]); - _data[pos++] = list[i].qos; - } + // serialize + size_t pos = 0; + _data[pos++] = PacketType.SUBSCRIBE | HeaderFlag.SUBSCRIBE_RESERVED; + pos += encodeRemainingLength(remainingLength, &_data[pos]); + _data[pos++] = _packetId >> 8; + _data[pos++] = _packetId & 0xFF; + for (size_t i = 0; i < numberTopics; ++i) { + pos += encodeString(list[i].topic, &_data[pos]); + _data[pos++] = list[i].qos; + } - error = espMqttClientTypes::Error::SUCCESS; + error = espMqttClientTypes::Error::SUCCESS; } -void Packet::_createUnsubscribe(espMqttClientTypes::Error & error, const char ** list, size_t numberTopics) { - // Calculate size - size_t payload = 0; - for (size_t i = 0; i < numberTopics; ++i) { - payload += 2 + strlen(list[i]); // length bytes, string - } - size_t remainingLength = 2 + payload; // packetId + payload +void Packet::_createUnsubscribe(espMqttClientTypes::Error& error, + const char** list, + size_t numberTopics) { + // Calculate size + size_t payload = 0; + for (size_t i = 0; i < numberTopics; ++i) { + payload += 2 + strlen(list[i]); // length bytes, string + } + size_t remainingLength = 2 + payload; // packetId + payload - // allocate memory - if (!_allocate(remainingLength)) { - error = espMqttClientTypes::Error::OUT_OF_MEMORY; - return; - } + // allocate memory + if (!_allocate(remainingLength, true)) { + error = espMqttClientTypes::Error::OUT_OF_MEMORY; + return; + } - // serialize - size_t pos = 0; - _data[pos++] = PacketType.UNSUBSCRIBE | HeaderFlag.UNSUBSCRIBE_RESERVED; - pos += encodeRemainingLength(remainingLength, &_data[pos]); - _data[pos++] = _packetId >> 8; - _data[pos++] = _packetId & 0xFF; - for (size_t i = 0; i < numberTopics; ++i) { - pos += encodeString(list[i], &_data[pos]); - } + // serialize + size_t pos = 0; + _data[pos++] = PacketType.UNSUBSCRIBE | HeaderFlag.UNSUBSCRIBE_RESERVED; + pos += encodeRemainingLength(remainingLength, &_data[pos]); + _data[pos++] = _packetId >> 8; + _data[pos++] = _packetId & 0xFF; + for (size_t i = 0; i < numberTopics; ++i) { + pos += encodeString(list[i], &_data[pos]); + } - error = espMqttClientTypes::Error::SUCCESS; + error = espMqttClientTypes::Error::SUCCESS; } size_t Packet::_chunkedAvailable(size_t index) { - // index vs size check done in 'available(index)' + // index vs size check done in 'available(index)' - // index points to header or first payload byte - if (index < _payloadIndex) { - if (_size > _payloadIndex && _payloadEndIndex != 0) { - size_t copied = _getPayload(&_data[_payloadIndex], std::min(static_cast(EMC_TX_BUFFER_SIZE), _size - _payloadStartIndex), index); - _payloadStartIndex = _payloadIndex; - _payloadEndIndex = _payloadStartIndex + copied - 1; - } - - // index points to payload unavailable - } else if (index > _payloadEndIndex || _payloadStartIndex > index) { - _payloadStartIndex = index; - size_t copied = _getPayload(&_data[_payloadIndex], std::min(static_cast(EMC_TX_BUFFER_SIZE), _size - _payloadStartIndex), index); - _payloadEndIndex = _payloadStartIndex + copied - 1; + // index points to header or first payload byte + if (index < _payloadIndex) { + if (_size > _payloadIndex && _payloadEndIndex != 0) { + size_t copied = _getPayload(&_data[_payloadIndex], std::min(static_cast(EMC_TX_BUFFER_SIZE), _size - _payloadStartIndex), index); + _payloadStartIndex = _payloadIndex; + _payloadEndIndex = _payloadStartIndex + copied - 1; } - // now index points to header or payload available - return _payloadEndIndex - index + 1; + // index points to payload unavailable + } else if (index > _payloadEndIndex || _payloadStartIndex > index) { + _payloadStartIndex = index; + size_t copied = _getPayload(&_data[_payloadIndex], std::min(static_cast(EMC_TX_BUFFER_SIZE), _size - _payloadStartIndex), index); + _payloadEndIndex = _payloadStartIndex + copied - 1; + } + + // now index points to header or payload available + return _payloadEndIndex - index + 1; } -const uint8_t * Packet::_chunkedData(size_t index) const { - // CAUTION!! available(index) has to be called first to check available data and possibly fill payloadbuffer - if (index < _payloadIndex) { - return &_data[index]; - } - return &_data[index - _payloadStartIndex + _payloadIndex]; +const uint8_t* Packet::_chunkedData(size_t index) const { + // CAUTION!! available(index) has to be called first to check available data and possibly fill payloadbuffer + if (index < _payloadIndex) { + return &_data[index]; + } + return &_data[index - _payloadStartIndex + _payloadIndex]; } -} // end namespace espMqttClientInternals +} // end namespace espMqttClientInternals diff --git a/lib/espMqttClient/src/Packets/Packet.h b/lib/espMqttClient/src/Packets/Packet.h index f2b290293..5d0b67b28 100644 --- a/lib/espMqttClient/src/Packets/Packet.h +++ b/lib/espMqttClient/src/Packets/Packet.h @@ -17,7 +17,11 @@ the LICENSE file. #include "../Helpers.h" #include "../Logging.h" #include "RemainingLength.h" -#include "String.h" +#include "StringUtil.h" + +#if EMC_USE_MEMPOOL + #include "MemoryPool/src/MemoryPool.h" +#endif namespace espMqttClientInternals { @@ -133,7 +137,7 @@ class Packet { private: // pass remainingLength = total size - header - remainingLengthLength! - bool _allocate(size_t remainingLength, bool check = true); + bool _allocate(size_t remainingLength, bool check); // fills header and returns index of next available byte in buffer size_t _fillPublishHeader(uint16_t packetId, @@ -150,6 +154,10 @@ class Packet { size_t _chunkedAvailable(size_t index); const uint8_t* _chunkedData(size_t index) const; + + #if EMC_USE_MEMPOOL + static MemoryPool::Variable _memPool; + #endif }; } // end namespace espMqttClientInternals diff --git a/lib/espMqttClient/src/Packets/String.cpp b/lib/espMqttClient/src/Packets/StringUtil.cpp similarity index 96% rename from lib/espMqttClient/src/Packets/String.cpp rename to lib/espMqttClient/src/Packets/StringUtil.cpp index c3fe23fdc..7cd3dd8c4 100644 --- a/lib/espMqttClient/src/Packets/String.cpp +++ b/lib/espMqttClient/src/Packets/StringUtil.cpp @@ -6,7 +6,7 @@ For a copy, see or the LICENSE file. */ -#include "String.h" +#include "StringUtil.h" namespace espMqttClientInternals { diff --git a/lib/espMqttClient/src/Packets/String.h b/lib/espMqttClient/src/Packets/StringUtil.h similarity index 100% rename from lib/espMqttClient/src/Packets/String.h rename to lib/espMqttClient/src/Packets/StringUtil.h diff --git a/lib/espMqttClient/src/Transport/ClientPosix.cpp b/lib/espMqttClient/src/Transport/ClientPosix.cpp index 82f16b449..1cd66e2b9 100644 --- a/lib/espMqttClient/src/Transport/ClientPosix.cpp +++ b/lib/espMqttClient/src/Transport/ClientPosix.cpp @@ -38,9 +38,10 @@ bool ClientPosix::connect(IPAddress ip, uint16_t port) { memset(&_host, 0, sizeof(_host)); _host.sin_family = AF_INET; _host.sin_addr.s_addr = htonl(uint32_t(ip)); - _host.sin_port = htons(port); // modified by proddy for EMS-ESP compiling standalone + _host.sin_port = ::htons(port); int ret = ::connect(_sockfd, reinterpret_cast(&_host), sizeof(_host)); + if (ret < 0) { emc_log_e("Error connecting: %d - (%d) %s", ret, errno, strerror(errno)); return false; diff --git a/lib/espMqttClient/src/Transport/IPAddress.cpp b/lib/espMqttClient/src/Transport/ClientPosixIPAddress.cpp similarity index 94% rename from lib/espMqttClient/src/Transport/IPAddress.cpp rename to lib/espMqttClient/src/Transport/ClientPosixIPAddress.cpp index b198429dc..3386dec85 100644 --- a/lib/espMqttClient/src/Transport/IPAddress.cpp +++ b/lib/espMqttClient/src/Transport/ClientPosixIPAddress.cpp @@ -8,7 +8,7 @@ the LICENSE file. #if defined(__linux__) -#include "IPAddress.h" +#include "ClientPosixIPAddress.h" IPAddress::IPAddress() : _address(0) { diff --git a/lib/espMqttClient/src/Transport/IPAddress.h b/lib/espMqttClient/src/Transport/ClientPosixIPAddress.h similarity index 100% rename from lib/espMqttClient/src/Transport/IPAddress.h rename to lib/espMqttClient/src/Transport/ClientPosixIPAddress.h diff --git a/lib/espMqttClient/src/Transport/ClientSecureSync.h b/lib/espMqttClient/src/Transport/ClientSecureSync.h index f8c47392d..c129296fe 100644 --- a/lib/espMqttClient/src/Transport/ClientSecureSync.h +++ b/lib/espMqttClient/src/Transport/ClientSecureSync.h @@ -17,7 +17,6 @@ the LICENSE file. #else #include #endif - #include "Transport.h" namespace espMqttClientInternals { @@ -32,6 +31,7 @@ class ClientSecureSync : public Transport { void stop() override; bool connected() override; bool disconnected() override; + // added for EMS-ESP #if defined(EMC_CLIENT_SECURE) WiFiClientSecure client; #else diff --git a/lib/espMqttClient/src/Transport/Transport.h b/lib/espMqttClient/src/Transport/Transport.h index 6720c024f..d368d0184 100644 --- a/lib/espMqttClient/src/Transport/Transport.h +++ b/lib/espMqttClient/src/Transport/Transport.h @@ -10,7 +10,7 @@ the LICENSE file. #include // size_t -#include "IPAddress.h" +#include "ClientPosixIPAddress.h" namespace espMqttClientInternals { diff --git a/lib/espMqttClient/src/espMqttClient.cpp b/lib/espMqttClient/src/espMqttClient.cpp index bd9b6935a..bbbfd693e 100644 --- a/lib/espMqttClient/src/espMqttClient.cpp +++ b/lib/espMqttClient/src/espMqttClient.cpp @@ -10,114 +10,114 @@ the LICENSE file. #if defined(ARDUINO_ARCH_ESP8266) espMqttClient::espMqttClient() -: MqttClientSetup(espMqttClientTypes::UseInternalTask::NO) -, _client() { - _transport = &_client; + : MqttClientSetup(espMqttClientTypes::UseInternalTask::NO) + , _client() { + _transport = &_client; } espMqttClientSecure::espMqttClientSecure() -: MqttClientSetup(espMqttClientTypes::UseInternalTask::NO) -, _client() { - _transport = &_client; + : MqttClientSetup(espMqttClientTypes::UseInternalTask::NO) + , _client() { + _transport = &_client; } -espMqttClientSecure& espMqttClientSecure::setInsecure() { - _client.client.setInsecure(); - return *this; +espMqttClientSecure & espMqttClientSecure::setInsecure() { + _client.client.setInsecure(); + return *this; } -espMqttClientSecure& espMqttClientSecure::setFingerprint(const uint8_t fingerprint[20]) { - _client.client.setFingerprint(fingerprint); - return *this; +espMqttClientSecure & espMqttClientSecure::setFingerprint(const uint8_t fingerprint[20]) { + _client.client.setFingerprint(fingerprint); + return *this; } -espMqttClientSecure& espMqttClientSecure::setTrustAnchors(const X509List *ta) { - _client.client.setTrustAnchors(ta); - return *this; +espMqttClientSecure & espMqttClientSecure::setTrustAnchors(const X509List * ta) { + _client.client.setTrustAnchors(ta); + return *this; } -espMqttClientSecure& espMqttClientSecure::setClientRSACert(const X509List *cert, const PrivateKey *sk) { - _client.client.setClientRSACert(cert, sk); - return *this; +espMqttClientSecure & espMqttClientSecure::setClientRSACert(const X509List * cert, const PrivateKey * sk) { + _client.client.setClientRSACert(cert, sk); + return *this; } -espMqttClientSecure& espMqttClientSecure::setClientECCert(const X509List *cert, const PrivateKey *sk, unsigned allowed_usages, unsigned cert_issuer_key_type) { - _client.client.setClientECCert(cert, sk, allowed_usages, cert_issuer_key_type); - return *this; +espMqttClientSecure & espMqttClientSecure::setClientECCert(const X509List * cert, const PrivateKey * sk, unsigned allowed_usages, unsigned cert_issuer_key_type) { + _client.client.setClientECCert(cert, sk, allowed_usages, cert_issuer_key_type); + return *this; } -espMqttClientSecure& espMqttClientSecure::setCertStore(CertStoreBase *certStore) { - _client.client.setCertStore(certStore); - return *this; +espMqttClientSecure & espMqttClientSecure::setCertStore(CertStoreBase * certStore) { + _client.client.setCertStore(certStore); + return *this; } #endif #if defined(ARDUINO_ARCH_ESP32) espMqttClient::espMqttClient(espMqttClientTypes::UseInternalTask useInternalTask) -: MqttClientSetup(useInternalTask) -, _client() { - _transport = &_client; + : MqttClientSetup(useInternalTask) + , _client() { + _transport = &_client; } espMqttClient::espMqttClient(uint8_t priority, uint8_t core) -: MqttClientSetup(espMqttClientTypes::UseInternalTask::YES, priority, core) -, _client() { - _transport = &_client; + : MqttClientSetup(espMqttClientTypes::UseInternalTask::YES, priority, core) + , _client() { + _transport = &_client; } espMqttClientSecure::espMqttClientSecure(espMqttClientTypes::UseInternalTask useInternalTask) -: MqttClientSetup(useInternalTask) -, _client() { - _transport = &_client; + : MqttClientSetup(useInternalTask) + , _client() { + _transport = &_client; } espMqttClientSecure::espMqttClientSecure(uint8_t priority, uint8_t core) -: MqttClientSetup(espMqttClientTypes::UseInternalTask::YES, priority, core) -, _client() { - _transport = &_client; + : MqttClientSetup(espMqttClientTypes::UseInternalTask::YES, priority, core) + , _client() { + _transport = &_client; } -espMqttClientSecure& espMqttClientSecure::setInsecure() { +espMqttClientSecure & espMqttClientSecure::setInsecure() { #if defined(EMC_CLIENT_SECURE) - _client.client.setInsecure(); + _client.client.setInsecure(); #endif - return *this; + return *this; } -espMqttClientSecure& espMqttClientSecure::setCACert(const char* rootCA) { +espMqttClientSecure & espMqttClientSecure::setCACert(const char * rootCA) { #if defined(EMC_CLIENT_SECURE) - _client.client.setCACert(rootCA); + _client.client.setCACert(rootCA); #endif - return *this; + return *this; } -espMqttClientSecure& espMqttClientSecure::setCertificate(const char* clientCa) { +espMqttClientSecure & espMqttClientSecure::setCertificate(const char * clientCa) { #if defined(EMC_CLIENT_SECURE) - _client.client.setCertificate(clientCa); + _client.client.setCertificate(clientCa); #endif - return *this; + return *this; } -espMqttClientSecure& espMqttClientSecure::setPrivateKey(const char* privateKey) { +espMqttClientSecure & espMqttClientSecure::setPrivateKey(const char * privateKey) { #if defined(EMC_CLIENT_SECURE) - _client.client.setPrivateKey(privateKey); + _client.client.setPrivateKey(privateKey); #endif - return *this; + return *this; } -espMqttClientSecure& espMqttClientSecure::setPreSharedKey(const char* pskIdent, const char* psKey) { +espMqttClientSecure & espMqttClientSecure::setPreSharedKey(const char * pskIdent, const char * psKey) { #if defined(EMC_CLIENT_SECURE) - _client.client.setPreSharedKey(pskIdent, psKey); + _client.client.setPreSharedKey(pskIdent, psKey); #endif - return *this; + return *this; } #endif #if defined(__linux__) espMqttClient::espMqttClient() -: MqttClientSetup(espMqttClientTypes::UseInternalTask::NO) -, _client() { - _transport = &_client; + : MqttClientSetup(espMqttClientTypes::UseInternalTask::NO) + , _client() { + _transport = &_client; } #endif