Skip to content

Commit

Permalink
MQTT subscription bug fix
Browse files Browse the repository at this point in the history
  • Loading branch information
seizu committed Feb 2, 2025
1 parent af093da commit 20702cd
Show file tree
Hide file tree
Showing 8 changed files with 119 additions and 47 deletions.
43 changes: 25 additions & 18 deletions platformio.ini
Original file line number Diff line number Diff line change
Expand Up @@ -8,38 +8,45 @@
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html

; ---------------------- EPS32 Config ----------------------
[env:esp32doit-devkit-v1]
platform = espressif32
board = esp32doit-devkit-v1
framework = arduino
monitor_speed = 115200
lib_deps = ottowinter/ESPAsyncWebServer-esphome@^3.0.0
knolleary/PubSubClient@^2.8
adafruit/Adafruit_VL53L0X@^1.2.4
lib_deps =
ottowinter/ESPAsyncWebServer-esphome@^3.0.0
knolleary/PubSubClient@^2.8
adafruit/Adafruit_VL53L0X@^1.2.4
build_flags = -DLOG_SERIAL_LEVEL=7
build_type = debug
;build_type = release
;build_flags = -Os
;board_build.partitions = partitions.csv

;-------- debug settings --------------
debug_build_flags = -g3 -O0
debug_tool = custom
debug_server = openocd
-f
${PROJECT_DIR}/ft232h.cfg
-f
board/esp-wroom-32.cfg
debug_server =
openocd
-f
${PROJECT_DIR}/ft232h.cfg
-f
board/esp-wroom-32.cfg
debug_speed = 2000

;---------------------- EPS8266 Config ----------------------
[env:esp12e]
platform = espressif8266
board = esp12e
framework = arduino
monitor_speed = 115200
lib_deps = ottowinter/ESPAsyncWebServer-esphome@^3.0.0
knolleary/PubSubClient@^2.8
adafruit/Adafruit_VL53L0X@^1.2.4
lib_deps =
ottowinter/ESPAsyncWebServer-esphome@^3.0.0
knolleary/PubSubClient@^2.8
adafruit/Adafruit_VL53L0X@^1.2.4
build_flags = -DLOG_SERIAL_LEVEL=7

[env:esp32-s3]
platform = espressif32
board = adafruit_feather_esp32s3
framework = arduino
monitor_speed = 115200
lib_deps =
ottowinter/ESPAsyncWebServer-esphome@^3.0.0
knolleary/PubSubClient@^2.8
adafruit/Adafruit_VL53L0X@^1.2.4
build_flags = -DLOG_SERIAL_LEVEL=7
5 changes: 4 additions & 1 deletion src/MqttClient/MqttClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,10 @@ bool MqttClient::ensureConnected(bool force) {
next_retry = 0;
return true;
} else {
LOG_SERROR("MQTT connection failed: %d\n", client.state());
LOG_SERROR("MQTT connection failed: %d\n", client.state());
if(this->sub_state = MqttClient::SUB_DONE) {
this->sub_state = MqttClient::SUB_PENDING;
}
if(!force)
reconnect_attempts++;
return false;
Expand Down
3 changes: 2 additions & 1 deletion src/MqttClient/MqttClient.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

class MqttClient {
public:
// after 3 failed retries idle 60 secounds
MqttClient(const char *domain, const char *id, MQTT_CALLBACK_SIGNATURE = nullptr, const char *user = "", const char *password = "", int retries = 3, ulong idle=60000);
~MqttClient();
bool publish(const char *topic, const char *payload, bool force = false);
Expand All @@ -24,7 +25,7 @@ class MqttClient {
SUB_PENDING = 0,
SUB_DONE = 1
};
// Interne Methode zum Verwalten der Verbindung

bool ensureConnected(bool force);

WiFiClient espClient;
Expand Down
20 changes: 20 additions & 0 deletions src/WebPrefs/WebPrefs copy3.htm
Original file line number Diff line number Diff line change
Expand Up @@ -460,12 +460,32 @@
border-radius: 100%;
}

.input-clean {
border: none !important;
background: transparent !important;
text-align: right;
color: black;
pointer-events: none;
font-family: inherit;
font-size: 10px;
outline: none !important;
box-shadow: none !important;
appearance: none !important;
-webkit-appearance: none !important;
-moz-appearance: none !important;
border-style: none !important;
padding-top: 0 !important;
padding-bottom: 0 !important;
margin: 0 !important;
}

@-webkit-keyframes rotation{from{-webkit-transform:rotate(0deg)}to{-webkit-transform:rotate(359deg)}}@-moz-keyframes rotation{from{-moz-transform:rotate(0deg)}to{-moz-transform:rotate(359deg)}}@keyframes rotation{from{transform:rotate(0deg)}to{transform:rotate(359deg)}}
</style>


</head><body onload=""><div id="spn" calss="spinner" class="" style="display: none;"></div>
<div class="bog">
<input type="text" class="input-clean" value="Firmware V1.3" disabled>
<div class="divider">WIFI/Network</div>
<form id="myPrefs" action="./postForm">
<label>WIFI SSID
Expand Down
19 changes: 19 additions & 0 deletions src/WebPrefs/css.h
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,25 @@ label:not(.switch){padding:0;font-size:14px;color:#808080}*{font-family:Arial,He
border-radius: 100px;
}

.input-clean-right {
border: none !important;
background: transparent !important;
text-align: right;
color: black;
pointer-events: none;
font-family: inherit;
font-size: 10px;
outline: none !important;
box-shadow: none !important;
appearance: none !important;
-webkit-appearance: none !important;
-moz-appearance: none !important;
border-style: none !important;
padding-top: 0 !important;
padding-bottom: 0 !important;
margin: 0 !important;
}

@-webkit-keyframes rotation{from{-webkit-transform:rotate(0deg)}to{-webkit-transform:rotate(359deg)}}@-moz-keyframes rotation{from{-moz-transform:rotate(0deg)}to{-moz-transform:rotate(359deg)}}@keyframes rotation{from{transform:rotate(0deg)}to{transform:rotate(359deg)}}</style>

)rawliteral";
3 changes: 2 additions & 1 deletion src/WebPrefs/html.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ static const char done_body[] PROGMEM = R"rawliteral(
static const char settings_body[] PROGMEM = R"rawliteral(
</head><body onload="onloaded('form');"><div id="spn" calss="spinner"></div>
<div class="bog">
<input type="text" class="input-clean-right" id="info_text" disabled>
<div class="divider">WIFI/Network</div>
<form id="myPrefs" action="./postForm">
<label>WIFI SSID
Expand Down Expand Up @@ -80,7 +81,7 @@ static const char settings_body[] PROGMEM = R"rawliteral(

<div class="divider">MQTT</div>

<label>MQTT 16</label>
<label>MQTT</label>
<div class="cbWrapper">
<input type="hidden" value="off">
<input type="checkbox" onclick="update(this, true)" id="mqtt_enabled" class="cbToggle" toggle-rules="[-3]" activation-rules="[17,18,19,20,21,22,23]">
Expand Down
7 changes: 5 additions & 2 deletions src/config.h
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ struct _device_config {
uint16_t autooff_timer;

bool poweron_state; // default switch state on power on

char info_text[129]; // some information to show in WebPrefs

} *device_config;
// --------------------------------------------------------------

Expand Down Expand Up @@ -97,7 +98,9 @@ const std::vector<WebPrefs::input_field> input_fields = {

{VAR_NAME(rnd_mod), "off", WebPrefs::CHECKBOX, sizeof(_device_config::rnd_mod), offsetof(_device_config, rnd_mod),0,1},
{VAR_NAME(rnd_min), "10", WebPrefs::INTEGER, sizeof(_device_config::rnd_min), offsetof(_device_config, rnd_min),1,720},
{VAR_NAME(rnd_max), "50", WebPrefs::INTEGER, sizeof(_device_config::rnd_max), offsetof(_device_config, rnd_max),1,720}
{VAR_NAME(rnd_max), "50", WebPrefs::INTEGER, sizeof(_device_config::rnd_max), offsetof(_device_config, rnd_max),1,720},
// --------
{VAR_NAME(info_text), "", WebPrefs::STRING, sizeof(_device_config::mqtt_user), offsetof(_device_config, info_text),0,128}

//{VAR_NAME(wifi_passwd), "https://api.telegram.org/bot$token$/sendMessage?chat_id=YOUR_CHAT_ID&text=$text$", WebPrefs::STRING, sizeof(_device_config::alert_link), offsetof(_device_config, alert_link)},
//{VAR_NAME(wifi_passwd), "the pet want's in ($bat$V)", WebPrefs::STRING, sizeof(_device_config::alert_text), offsetof(_device_config, alert_text)},
Expand Down
66 changes: 42 additions & 24 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
#include <ESPAsyncWebServer.h>

//#define READECONFIG
#define VL53LXX
#define D1_MINI

#if defined(ESP8266)
#include <ESPAsyncTCP.h>
Expand All @@ -20,11 +22,19 @@
#elif defined(ESP32)
#include <AsyncTCP.h>
#include <HTTPClient.h>
#if defined(D1_MINI)
#define SWITCH_PIN 26
#define SCL_PIN 22
#define SDA_PIN 21
#define RESTORE_PIN 27
#define MCU "ESP32 D1 MINI"
#else
#define SWITCH_PIN 4
#define SCL_PIN 22
#define SDA_PIN 21
#define RESTORE_PIN 33
#define MCU "ESP32"
#endif
#endif

#include "serlog.h"
Expand All @@ -46,7 +56,7 @@
#define AP_SSID_PREFIX "SS"
#define AP_PASSWD "SmartSwitch"

#define VERSION "1.0.5"
#define VERSION "1.0.6"


uint8_t blink = LOW;
Expand All @@ -73,7 +83,7 @@ bool vl53l0x_enabled;

bool enableWifi(bool ap_mode, bool web_server);
bool disableWifi();
void processManualTrigger();
void handleExternalSignal();
void triggerSwitch(bool onoff);
void mqttIncomming(char* topic, byte* payload, unsigned int length);
bool mqttPublish(const char *message, const char *payload, bool force = false);
Expand All @@ -99,8 +109,8 @@ void setup() {
pinMode(RESTORE_PIN, INPUT_PULLDOWN);
// PULLDOWN not supported by ESP8266 (RESTORE mod off: connect RESTORE_PIN with GND PIN)
// PULLUP (RESTORE mod on: connect RESTORE_PIN with 10k resistor to 3.3V PIN)
#endif
Serial.printf("SmartSwitch - Firmware V%s\n", VERSION);
#endif
LOG_SINFO("SmartSwitch V%s\n", VERSION);
#if defined(ESP32)
randomSeed(esp_random());
#elif defined(ESP8266)
Expand All @@ -117,7 +127,7 @@ void setup() {
LOG_SERROR("Config read NOK! ChkSum: 0x%X\n", device_config->check_sum);
}
#endif

// init WIFI
sw = new SimpleWifi(AP_SSID_PREFIX);
// init WebPrefs Server on port 80
Expand All @@ -134,6 +144,7 @@ void setup() {
wp->debugPrintConfig();
}
device_config->switch_onoff = device_config->poweron_state;
snprintf(device_config->info_text,sizeof(device_config->info_text),"SmartSwitch V%s", VERSION);

// init MQTT
mqtt = new MqttClient(device_config->mqtt_server, device_config->mqtt_id, mqttIncomming,device_config->mqtt_user, device_config->mqtt_passwd);
Expand All @@ -146,34 +157,32 @@ void setup() {
LOG_SERROR("MQTT subscribe failed: %s\n",device_config->mqtt_command);
}
}

#if defined VL53LXX
// init VL53L0X sensor
vl53l0x_enabled = lox.begin();
if(vl53l0x_enabled) {
LOG_SINFO("init VL53L0X done!");
} else {
LOG_SERROR("Failed to init VL53L0X");
}
#endif

// reset task timer/events
rnd_event = toggle24h_event = autooff_event = webprefs_idle_event = millis();
rnd_timer = random(device_config->rnd_min, device_config->rnd_max);
toggle24h_timer = device_config->toggle24h_timer;

mqttPublish("SYSTEM","SETUP");
// set power_on switch state

// set power_on switch state
}

void loop() {
delay(100);
delay(10);
ulong now = millis();

// turn off wifi & webserver after idle timeout
// turn off wifi & webserver after WebPrefs idle timeout
if(WiFi.getMode() != WIFI_OFF && device_config->disable_wifi==true && (now - webprefs_idle_event) >= (device_config->web_idle_timeout * 60 * 1000)) {
wp->stop();
sw->disableWifi();
LOG_SDEBUG("WIFI Disabled\n");
disableWifi();
}

// Switch triggered via WebPrefs?
Expand All @@ -182,7 +191,7 @@ void loop() {
}

// Manual trigger
processManualTrigger();
handleExternalSignal();

// Random mod
if(device_config->rnd_mod) {
Expand Down Expand Up @@ -232,24 +241,25 @@ void loop() {
}


void processManualTrigger() {
void handleExternalSignal() {
if ((millis() - manual_switch_event) < (device_config->manual_switch_delay * 1000)) {
return; // Sperre weitere Ereignisse
return;
}

#if defined VL53LXX
VL53L0X_RangingMeasurementData_t measure;
lox.rangingTest(&measure, false);

if (measure.RangeStatus == 0) {
uint16_t distance = measure.RangeMilliMeter;

// Überprüfe, ob die Distanz den Schwellwert erfüllt
// Check whether the distance meets the threshold value
if (distance > 0 && distance < device_config->switch_detection_distance) {
LOG_SDEBUG("Manual trigger distance: %d\n", distance);
manual_switch_event = millis(); // Timer zurücksetzen
manual_switch_event = millis();
triggerSwitch(switch_state ^ 1);
}
}
}
#endif
}

void triggerSwitch(bool onoff) {
Expand All @@ -258,8 +268,7 @@ void triggerSwitch(bool onoff) {
LOG_SDEBUG("Switch state already %s\n",switch_state ? "ON" : "OFF");
return;
}



// Reactivate WiFi at toggle threshold
if(now - toggle_event < ((ulong)(device_config->manual_switch_delay + 2) * 1000) ) {
if((device_config->enable_wifi_ontoggle > 0) && (++toggle_count >= device_config->enable_wifi_ontoggle) && WiFi.getMode() == WIFI_OFF) {
Expand Down Expand Up @@ -307,7 +316,16 @@ void mqttIncomming(char *topic, byte *payload, unsigned int length) {
if (jdata["DEVICE"] == "INFO") {
char *info = new char[256];
snprintf(info, 256, "INFO:MCU=%s V=%s RS_PIN=%d SW_PIN=%d SCL=%d SDA=%d VL53=%d SW_STATE=%d IP=%s",
MCU, VERSION, RESTORE_PIN, SWITCH_PIN, SCL_PIN, SDA_PIN, (int)vl53l0x_enabled, (int)switch_state, WiFi.localIP().toString().c_str());
MCU,
VERSION,
RESTORE_PIN,
SWITCH_PIN,
SCL_PIN,
SDA_PIN,
(int)vl53l0x_enabled,
(int)switch_state,
WiFi.localIP().toString().c_str());

mqttPublish("DEVICE", info);
delete[] info;
} else if(jdata["DEVICE"] == "REBOOT") {
Expand Down Expand Up @@ -338,7 +356,7 @@ bool mqttPublish(const char *message, const char *payload, bool force) {

bool disableWifi() {
wp->stop();
return WiFi.mode(WIFI_OFF);
return sw->disableWifi();
}

bool enableWifi(bool ap_mode, bool web_server) {
Expand Down

0 comments on commit 20702cd

Please sign in to comment.