WordClockESP/lib/framework/MqttSettingsService.h

149 lines
4.2 KiB
C
Raw Normal View History

#ifndef MqttSettingsService_h
#define MqttSettingsService_h
#include <StatefulService.h>
#include <HttpEndpoint.h>
#include <FSPersistence.h>
#include <AsyncMqttClient.h>
Settings placeholder substitution (#164) * Use text formatting for default factory values to produce dynamic names. Header files contains duplicates of factory values defined in factory_settings.ini Removed them to simplify the code. * Use text formatting for default factory values to produce dynamic names. Header files contains duplicates of factory values defined in factory_settings.ini Removed them to simplify the code. * Configured the WiFi host name to contain the device id by default * Removed possibility to use placeholders for FACTORY_WIFI_SSID factory setting. * Update README.md Updated documentation * Use text formatting for default factory values to produce dynamic names. Header files contains duplicates of factory values defined in factory_settings.ini Removed them to simplify the code. * Configured the WiFi host name to contain the device id by default * Removed possibility to use placeholders for FACTORY_WIFI_SSID factory setting. * Added a space to the end of the file to comply project code style * fix typos clang formatting use 2 spaces in ini files use ${platform}-${chip_id} for hostname put chip id in brackets in AP SSID * restore (and update) factory setting ifndefs - this is so src can be built without an exaustive set build-time defines - standardize ordering of defines: factory settings, paths, config * format and modify comment * escape spaces in pio defines experiment with removing $'s from our format strings (they are being substituted with empty values by pio) * fix formatting in readme rename FactoryValue to SettingValue, put in own header give example of direct usage of FactorySetting::format in README.md * auto format * use hash to delimit placeholders * fix factory_settings.ini * remove flash string helpers * format ini file * use MAC address instead of chip id for properly unique identifier * use lower case hex encoding for unique id use chip id and unique id for more secure secret * fix comment * Use random values for JWT secret Arduino uses the ESP random number generator for "true random" numbers on both esp32 and esp8266 This makes a better JWT secret and may be useful for other factory defaults too In addition a modification has been made to force the FSPersistance to save the file if applying defaults * Don't use spaces in default AP SSID * restore helpful comment in factory_settings.ini fix default defines Co-authored-by: kasedy <kasedy@gmail.com>
2021-01-03 17:00:36 +00:00
#include <SettingValue.h>
#ifndef FACTORY_MQTT_ENABLED
#define FACTORY_MQTT_ENABLED false
#endif
#ifndef FACTORY_MQTT_HOST
#define FACTORY_MQTT_HOST "test.mosquitto.org"
#endif
#ifndef FACTORY_MQTT_PORT
#define FACTORY_MQTT_PORT 1883
#endif
#ifndef FACTORY_MQTT_USERNAME
#define FACTORY_MQTT_USERNAME ""
#endif
#ifndef FACTORY_MQTT_PASSWORD
#define FACTORY_MQTT_PASSWORD ""
#endif
#ifndef FACTORY_MQTT_CLIENT_ID
Settings placeholder substitution (#164) * Use text formatting for default factory values to produce dynamic names. Header files contains duplicates of factory values defined in factory_settings.ini Removed them to simplify the code. * Use text formatting for default factory values to produce dynamic names. Header files contains duplicates of factory values defined in factory_settings.ini Removed them to simplify the code. * Configured the WiFi host name to contain the device id by default * Removed possibility to use placeholders for FACTORY_WIFI_SSID factory setting. * Update README.md Updated documentation * Use text formatting for default factory values to produce dynamic names. Header files contains duplicates of factory values defined in factory_settings.ini Removed them to simplify the code. * Configured the WiFi host name to contain the device id by default * Removed possibility to use placeholders for FACTORY_WIFI_SSID factory setting. * Added a space to the end of the file to comply project code style * fix typos clang formatting use 2 spaces in ini files use ${platform}-${chip_id} for hostname put chip id in brackets in AP SSID * restore (and update) factory setting ifndefs - this is so src can be built without an exaustive set build-time defines - standardize ordering of defines: factory settings, paths, config * format and modify comment * escape spaces in pio defines experiment with removing $'s from our format strings (they are being substituted with empty values by pio) * fix formatting in readme rename FactoryValue to SettingValue, put in own header give example of direct usage of FactorySetting::format in README.md * auto format * use hash to delimit placeholders * fix factory_settings.ini * remove flash string helpers * format ini file * use MAC address instead of chip id for properly unique identifier * use lower case hex encoding for unique id use chip id and unique id for more secure secret * fix comment * Use random values for JWT secret Arduino uses the ESP random number generator for "true random" numbers on both esp32 and esp8266 This makes a better JWT secret and may be useful for other factory defaults too In addition a modification has been made to force the FSPersistance to save the file if applying defaults * Don't use spaces in default AP SSID * restore helpful comment in factory_settings.ini fix default defines Co-authored-by: kasedy <kasedy@gmail.com>
2021-01-03 17:00:36 +00:00
#define FACTORY_MQTT_CLIENT_ID "#{platform}-#{unique_id}"
#endif
#ifndef FACTORY_MQTT_KEEP_ALIVE
#define FACTORY_MQTT_KEEP_ALIVE 16
#endif
#ifndef FACTORY_MQTT_CLEAN_SESSION
#define FACTORY_MQTT_CLEAN_SESSION true
#endif
#ifndef FACTORY_MQTT_MAX_TOPIC_LENGTH
#define FACTORY_MQTT_MAX_TOPIC_LENGTH 128
#endif
Settings placeholder substitution (#164) * Use text formatting for default factory values to produce dynamic names. Header files contains duplicates of factory values defined in factory_settings.ini Removed them to simplify the code. * Use text formatting for default factory values to produce dynamic names. Header files contains duplicates of factory values defined in factory_settings.ini Removed them to simplify the code. * Configured the WiFi host name to contain the device id by default * Removed possibility to use placeholders for FACTORY_WIFI_SSID factory setting. * Update README.md Updated documentation * Use text formatting for default factory values to produce dynamic names. Header files contains duplicates of factory values defined in factory_settings.ini Removed them to simplify the code. * Configured the WiFi host name to contain the device id by default * Removed possibility to use placeholders for FACTORY_WIFI_SSID factory setting. * Added a space to the end of the file to comply project code style * fix typos clang formatting use 2 spaces in ini files use ${platform}-${chip_id} for hostname put chip id in brackets in AP SSID * restore (and update) factory setting ifndefs - this is so src can be built without an exaustive set build-time defines - standardize ordering of defines: factory settings, paths, config * format and modify comment * escape spaces in pio defines experiment with removing $'s from our format strings (they are being substituted with empty values by pio) * fix formatting in readme rename FactoryValue to SettingValue, put in own header give example of direct usage of FactorySetting::format in README.md * auto format * use hash to delimit placeholders * fix factory_settings.ini * remove flash string helpers * format ini file * use MAC address instead of chip id for properly unique identifier * use lower case hex encoding for unique id use chip id and unique id for more secure secret * fix comment * Use random values for JWT secret Arduino uses the ESP random number generator for "true random" numbers on both esp32 and esp8266 This makes a better JWT secret and may be useful for other factory defaults too In addition a modification has been made to force the FSPersistance to save the file if applying defaults * Don't use spaces in default AP SSID * restore helpful comment in factory_settings.ini fix default defines Co-authored-by: kasedy <kasedy@gmail.com>
2021-01-03 17:00:36 +00:00
#define MQTT_SETTINGS_FILE "/config/mqttSettings.json"
#define MQTT_SETTINGS_SERVICE_PATH "/rest/mqttSettings"
#define MQTT_RECONNECTION_DELAY 5000
class MqttSettings {
public:
// host and port - if enabled
bool enabled;
String host;
uint16_t port;
// username and password
String username;
String password;
// client id settings
String clientId;
// connection settings
uint16_t keepAlive;
bool cleanSession;
uint16_t maxTopicLength;
static void read(MqttSettings& settings, JsonObject& root) {
root["enabled"] = settings.enabled;
root["host"] = settings.host;
root["port"] = settings.port;
root["username"] = settings.username;
root["password"] = settings.password;
root["client_id"] = settings.clientId;
root["keep_alive"] = settings.keepAlive;
root["clean_session"] = settings.cleanSession;
root["max_topic_length"] = settings.maxTopicLength;
}
static StateUpdateResult update(JsonObject& root, MqttSettings& settings) {
settings.enabled = root["enabled"] | FACTORY_MQTT_ENABLED;
settings.host = root["host"] | FACTORY_MQTT_HOST;
settings.port = root["port"] | FACTORY_MQTT_PORT;
Settings placeholder substitution (#164) * Use text formatting for default factory values to produce dynamic names. Header files contains duplicates of factory values defined in factory_settings.ini Removed them to simplify the code. * Use text formatting for default factory values to produce dynamic names. Header files contains duplicates of factory values defined in factory_settings.ini Removed them to simplify the code. * Configured the WiFi host name to contain the device id by default * Removed possibility to use placeholders for FACTORY_WIFI_SSID factory setting. * Update README.md Updated documentation * Use text formatting for default factory values to produce dynamic names. Header files contains duplicates of factory values defined in factory_settings.ini Removed them to simplify the code. * Configured the WiFi host name to contain the device id by default * Removed possibility to use placeholders for FACTORY_WIFI_SSID factory setting. * Added a space to the end of the file to comply project code style * fix typos clang formatting use 2 spaces in ini files use ${platform}-${chip_id} for hostname put chip id in brackets in AP SSID * restore (and update) factory setting ifndefs - this is so src can be built without an exaustive set build-time defines - standardize ordering of defines: factory settings, paths, config * format and modify comment * escape spaces in pio defines experiment with removing $'s from our format strings (they are being substituted with empty values by pio) * fix formatting in readme rename FactoryValue to SettingValue, put in own header give example of direct usage of FactorySetting::format in README.md * auto format * use hash to delimit placeholders * fix factory_settings.ini * remove flash string helpers * format ini file * use MAC address instead of chip id for properly unique identifier * use lower case hex encoding for unique id use chip id and unique id for more secure secret * fix comment * Use random values for JWT secret Arduino uses the ESP random number generator for "true random" numbers on both esp32 and esp8266 This makes a better JWT secret and may be useful for other factory defaults too In addition a modification has been made to force the FSPersistance to save the file if applying defaults * Don't use spaces in default AP SSID * restore helpful comment in factory_settings.ini fix default defines Co-authored-by: kasedy <kasedy@gmail.com>
2021-01-03 17:00:36 +00:00
settings.username = root["username"] | SettingValue::format(FACTORY_MQTT_USERNAME);
settings.password = root["password"] | FACTORY_MQTT_PASSWORD;
Settings placeholder substitution (#164) * Use text formatting for default factory values to produce dynamic names. Header files contains duplicates of factory values defined in factory_settings.ini Removed them to simplify the code. * Use text formatting for default factory values to produce dynamic names. Header files contains duplicates of factory values defined in factory_settings.ini Removed them to simplify the code. * Configured the WiFi host name to contain the device id by default * Removed possibility to use placeholders for FACTORY_WIFI_SSID factory setting. * Update README.md Updated documentation * Use text formatting for default factory values to produce dynamic names. Header files contains duplicates of factory values defined in factory_settings.ini Removed them to simplify the code. * Configured the WiFi host name to contain the device id by default * Removed possibility to use placeholders for FACTORY_WIFI_SSID factory setting. * Added a space to the end of the file to comply project code style * fix typos clang formatting use 2 spaces in ini files use ${platform}-${chip_id} for hostname put chip id in brackets in AP SSID * restore (and update) factory setting ifndefs - this is so src can be built without an exaustive set build-time defines - standardize ordering of defines: factory settings, paths, config * format and modify comment * escape spaces in pio defines experiment with removing $'s from our format strings (they are being substituted with empty values by pio) * fix formatting in readme rename FactoryValue to SettingValue, put in own header give example of direct usage of FactorySetting::format in README.md * auto format * use hash to delimit placeholders * fix factory_settings.ini * remove flash string helpers * format ini file * use MAC address instead of chip id for properly unique identifier * use lower case hex encoding for unique id use chip id and unique id for more secure secret * fix comment * Use random values for JWT secret Arduino uses the ESP random number generator for "true random" numbers on both esp32 and esp8266 This makes a better JWT secret and may be useful for other factory defaults too In addition a modification has been made to force the FSPersistance to save the file if applying defaults * Don't use spaces in default AP SSID * restore helpful comment in factory_settings.ini fix default defines Co-authored-by: kasedy <kasedy@gmail.com>
2021-01-03 17:00:36 +00:00
settings.clientId = root["client_id"] | SettingValue::format(FACTORY_MQTT_CLIENT_ID);
settings.keepAlive = root["keep_alive"] | FACTORY_MQTT_KEEP_ALIVE;
settings.cleanSession = root["clean_session"] | FACTORY_MQTT_CLEAN_SESSION;
settings.maxTopicLength = root["max_topic_length"] | FACTORY_MQTT_MAX_TOPIC_LENGTH;
return StateUpdateResult::CHANGED;
}
};
class MqttSettingsService : public StatefulService<MqttSettings> {
public:
MqttSettingsService(AsyncWebServer* server, FS* fs, SecurityManager* securityManager);
~MqttSettingsService();
void begin();
void loop();
bool isEnabled();
bool isConnected();
const char* getClientId();
AsyncMqttClientDisconnectReason getDisconnectReason();
AsyncMqttClient* getMqttClient();
protected:
void onConfigUpdated();
private:
HttpEndpoint<MqttSettings> _httpEndpoint;
FSPersistence<MqttSettings> _fsPersistence;
// Pointers to hold retained copies of the mqtt client connection strings.
// This is required as AsyncMqttClient holds refrences to the supplied connection strings.
char* _retainedHost;
char* _retainedClientId;
char* _retainedUsername;
char* _retainedPassword;
// variable to help manage connection
bool _reconfigureMqtt;
unsigned long _disconnectedAt;
// connection status
AsyncMqttClientDisconnectReason _disconnectReason;
// the MQTT client instance
AsyncMqttClient _mqttClient;
#ifdef ESP32
void onStationModeGotIP(WiFiEvent_t event, WiFiEventInfo_t info);
void onStationModeDisconnected(WiFiEvent_t event, WiFiEventInfo_t info);
#elif defined(ESP8266)
WiFiEventHandler _onStationModeDisconnectedHandler;
WiFiEventHandler _onStationModeGotIPHandler;
void onStationModeGotIP(const WiFiEventStationModeGotIP& event);
void onStationModeDisconnected(const WiFiEventStationModeDisconnected& event);
#endif
void onMqttConnect(bool sessionPresent);
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason);
void configureMqtt();
};
#endif // end MqttSettingsService_h