diff --git a/tasmota/include/tasmota.h b/tasmota/include/tasmota.h
index f3e9bfbde..db4bcec0b 100644
--- a/tasmota/include/tasmota.h
+++ b/tasmota/include/tasmota.h
@@ -405,7 +405,7 @@ enum XsnsFunctions { FUNC_SETTINGS_OVERRIDE, FUNC_I2C_INIT, FUNC_PRE_INIT, FUNC_
FUNC_COMMAND, FUNC_COMMAND_SENSOR, FUNC_COMMAND_DRIVER,
FUNC_RULES_PROCESS,
FUNC_SET_CHANNELS,
- FUNC_last_function // Insert functions with return results before here
+ FUNC_last_function // Insert functions WITH return results before here
};
enum AddressConfigSteps { ADDR_IDLE, ADDR_RECEIVE, ADDR_SEND };
diff --git a/tasmota/tasmota_support/support_button_v3.ino b/tasmota/tasmota_support/support_button_v3.ino
index b12ef5714..92e278ec0 100644
--- a/tasmota/tasmota_support/support_button_v3.ino
+++ b/tasmota/tasmota_support/support_button_v3.ino
@@ -17,7 +17,7 @@
along with this program. If not, see .
*/
-#define BUTTON_V3
+//#define BUTTON_V3
#ifdef BUTTON_V3
/*********************************************************************************************\
* Button support with input filter
diff --git a/tasmota/tasmota_support/support_button_v4.ino b/tasmota/tasmota_support/support_button_v4.ino
new file mode 100644
index 000000000..4de6f9ae5
--- /dev/null
+++ b/tasmota/tasmota_support/support_button_v4.ino
@@ -0,0 +1,572 @@
+/*
+ support_button.ino - button support for Tasmota
+
+ Copyright (C) 2022 Federico Leoni and Theo Arends
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
+
+#define BUTTON_V4
+#ifdef BUTTON_V4
+/*********************************************************************************************\
+ * Button support with input filter
+ *
+ * Inspired by (https://github.com/OLIMEX/olimex-iot-firmware-esp8266/blob/master/olimex/user/user_switch2.c)
+\*********************************************************************************************/
+
+#define MAX_RELAY_BUTTON1 5 // Max number of relay controlled by BUTTON1
+
+const uint8_t BUTTON_PROBE_INTERVAL = 10; // Time in milliseconds between button input probe
+const uint8_t BUTTON_FAST_PROBE_INTERVAL = 2; // Time in milliseconds between button input probe for AC detection
+const uint8_t BUTTON_AC_PERIOD = (20 + BUTTON_FAST_PROBE_INTERVAL - 1) / BUTTON_FAST_PROBE_INTERVAL; // Duration of an AC wave in probe intervals
+
+const char kMultiPress[] PROGMEM = "|SINGLE|DOUBLE|TRIPLE|QUAD|PENTA|CLEAR|";
+
+#include
+
+Ticker TickerButton;
+
+struct BUTTON {
+ uint32_t debounce = 0; // Button debounce timer
+ uint32_t no_pullup_mask = 0; // key no pullup flag (1 = no pullup)
+ uint32_t pulldown_mask = 0; // key pulldown flag (1 = pulldown)
+ uint32_t inverted_mask = 0; // Key inverted flag (1 = inverted)
+ uint32_t virtual_pin_used = 0; // Key used bitmask
+ uint32_t virtual_pin = 0; // Key state bitmask
+ uint16_t hold_timer[MAX_KEYS] = { 0 }; // Timer for button hold
+ uint16_t dual_code = 0; // Sonoff dual received code
+ uint8_t state[MAX_KEYS] = { 0 };
+ uint8_t last_state[MAX_KEYS]; // Last button states
+ uint8_t debounced_state[MAX_KEYS]; // Button debounced states
+ uint8_t window_timer[MAX_KEYS] = { 0 }; // Max time between button presses to record press count
+ uint8_t press_counter[MAX_KEYS] = { 0 }; // Number of button presses within Button.window_timer
+ uint8_t dual_receive_count = 0; // Sonoff dual input flag
+ uint8_t first_change = 0;
+ uint8_t present = 0; // Number of buttons found flag
+ bool probe_mutex;
+} Button;
+
+#if defined(SOC_TOUCH_VERSION_1) || defined(SOC_TOUCH_VERSION_2)
+struct TOUCH_BUTTON {
+ uint32_t touch_mask = 0; // Touch flag (1 = enabled)
+ uint32_t calibration = 0; // Bitfield
+ uint8_t hits[MAX_KEYS] = { 0 }; // Hits in a row to filter out noise
+} TouchButton;
+#endif // ESP32 SOC_TOUCH_VERSION_1 or SOC_TOUCH_VERSION_2
+
+/********************************************************************************************/
+
+void ButtonPullupFlag(uint32_t button_bit) {
+ bitSet(Button.no_pullup_mask, button_bit);
+}
+
+void ButtonPulldownFlag(uint32_t button_bit) {
+ bitSet(Button.pulldown_mask, button_bit);
+}
+
+void ButtonInvertFlag(uint32_t button_bit) {
+ bitSet(Button.inverted_mask, button_bit);
+}
+
+#if defined(SOC_TOUCH_VERSION_1) || defined(SOC_TOUCH_VERSION_2)
+void ButtonTouchFlag(uint32_t button_bit) {
+ bitSet(TouchButton.touch_mask, button_bit);
+}
+#endif // ESP32 SOC_TOUCH_VERSION_1 or SOC_TOUCH_VERSION_2
+
+
+void ButtonSetVirtualPinState(uint32_t index, uint32_t state) {
+ if (!Button.probe_mutex) {
+ bitWrite(Button.virtual_pin, index, state);
+ }
+}
+
+/*********************************************************************************************/
+
+void ButtonProbe(void) {
+ if (Button.probe_mutex || (TasmotaGlobal.uptime < 4)) { return; } // Block GPIO for 4 seconds after poweron to workaround Wemos D1 / Obi RTS circuit
+ Button.probe_mutex = true;
+
+ uint32_t state_filter;
+ uint32_t first_change = Button.first_change;
+ uint32_t debounce_flags = Settings->button_debounce % 10;
+ bool force_high = (debounce_flags &1); // 51, 101, 151 etc
+ bool force_low = (debounce_flags &2); // 52, 102, 152 etc
+ bool ac_detect = (debounce_flags == 9); // 39, 49, 59 etc
+
+ if (ac_detect) {
+ if (Settings->button_debounce < 2 * BUTTON_AC_PERIOD * BUTTON_FAST_PROBE_INTERVAL + 9) {
+ state_filter = 2 * BUTTON_AC_PERIOD;
+ } else if (Settings->button_debounce > (0x7f - 2 * BUTTON_AC_PERIOD) * BUTTON_FAST_PROBE_INTERVAL) {
+ state_filter = 0x7f;
+ } else {
+ state_filter = (Settings->button_debounce - 9) / BUTTON_FAST_PROBE_INTERVAL;
+ }
+ } else {
+ state_filter = Settings->button_debounce / BUTTON_PROBE_INTERVAL; // 5, 10, 15
+ }
+
+ uint32_t not_activated;
+ for (uint32_t i = 0; i < MAX_KEYS; i++) {
+ if (PinUsed(GPIO_KEY1, i)) {
+#if defined(SOC_TOUCH_VERSION_1) || defined(SOC_TOUCH_VERSION_2)
+ if (bitRead(TouchButton.touch_mask, i)) {
+ if (ac_detect || bitRead(TouchButton.calibration, i +1)) { continue; } // Touch is slow. Takes 21mS to read
+ uint32_t value = touchRead(Pin(GPIO_KEY1, i));
+#ifdef SOC_TOUCH_VERSION_2
+ not_activated = (value < Settings->touch_threshold); // ESPS3 No touch = 24200, Touch > 40000
+#else
+ not_activated = ((value == 0) || (value > Settings->touch_threshold)); // ESP32 No touch = 74, Touch < 40
+#endif
+ } else
+#endif // ESP32 SOC_TOUCH_VERSION_1 or SOC_TOUCH_VERSION_2
+ not_activated = (digitalRead(Pin(GPIO_KEY1, i)) != bitRead(Button.inverted_mask, i));
+ }
+ else if (bitRead(Button.virtual_pin_used, i)) {
+ not_activated = bitRead(Button.virtual_pin, i);
+ }
+ else { continue; }
+
+ if (not_activated) {
+
+ if (ac_detect) { // Enabled with ButtonDebounce x9
+ Button.state[i] |= 0x80;
+ if (Button.state[i] > 0x80) {
+ Button.state[i]--;
+ if (0x80 == Button.state[i]) {
+ Button.debounced_state[i] = 0;
+ Button.first_change = false;
+ }
+ }
+ } else {
+
+ if (force_high) { // Enabled with ButtonDebounce x1
+ if (1 == Button.debounced_state[i]) {
+ Button.state[i] = state_filter; // With noisy input keep current state 1 unless constant 0
+ }
+ }
+
+ if (Button.state[i] < state_filter) {
+ Button.state[i]++;
+ if (state_filter == Button.state[i]) {
+ Button.debounced_state[i] = 1;
+ }
+ }
+ }
+ } else {
+
+ if (ac_detect) { // Enabled with ButtonDebounce x9
+ /*
+ * Moes MS-104B and similar devices using an AC detection circuitry
+ * on their switch inputs generating an ~4 ms long low pulse every
+ * AC wave. We start the time measurement on the falling edge.
+ *
+ * state: bit7: previous state, bit6..0: counter
+ */
+ if (Button.state[i] & 0x80) {
+ Button.state[i] &= 0x7f;
+ if (Button.state[i] < state_filter - 2 * BUTTON_AC_PERIOD) {
+ Button.state[i] += 2 * BUTTON_AC_PERIOD;
+ } else {
+ Button.state[i] = state_filter;
+ Button.debounced_state[i] = 1;
+ if (first_change) {
+ Button.last_state[i] = 1;
+ Button.first_change = false;
+ }
+ }
+ } else {
+ if (Button.state[i] > 0x00) {
+ Button.state[i]--;
+ if (0x00 == Button.state[i]) {
+ Button.debounced_state[i] = 0;
+ Button.first_change = false;
+ }
+ }
+ }
+ } else {
+
+ if (force_low) { // Enabled with ButtonDebounce x2
+ if (0 == Button.debounced_state[i]) {
+ Button.state[i] = 0; // With noisy input keep current state 0 unless constant 1
+ }
+ }
+
+ if (Button.state[i] > 0) {
+ Button.state[i]--;
+ if (0 == Button.state[i]) {
+ Button.debounced_state[i] = 0;
+ }
+ }
+ }
+ }
+ }
+ Button.probe_mutex = false;
+}
+
+void ButtonInit(void) {
+ bool ac_detect = (Settings->button_debounce % 10 == 9);
+
+ Button.present = 0;
+ Button.virtual_pin_used = 0;
+
+#ifdef ESP8266
+ if ((SONOFF_DUAL == TasmotaGlobal.module_type) || (CH4 == TasmotaGlobal.module_type)) {
+ Button.present++;
+ }
+#endif // ESP8266
+
+ for (uint32_t i = 0; i < MAX_KEYS; i++) {
+ Button.last_state[i] = NOT_PRESSED;
+ bool used = false;
+
+ if (PinUsed(GPIO_KEY1, i)) {
+ Button.present++;
+#ifdef ESP8266
+ pinMode(Pin(GPIO_KEY1, i), bitRead(Button.no_pullup_mask, i) ? INPUT : ((16 == Pin(GPIO_KEY1, i)) ? INPUT_PULLDOWN_16 : INPUT_PULLUP));
+#endif // ESP8266
+#ifdef ESP32
+ pinMode(Pin(GPIO_KEY1, i), bitRead(Button.pulldown_mask, i) ? INPUT_PULLDOWN : bitRead(Button.no_pullup_mask, i) ? INPUT : INPUT_PULLUP);
+#endif // ESP32
+ // Set global now so doesn't change the saved power state on first button check
+ Button.last_state[i] = (digitalRead(Pin(GPIO_KEY1, i)) != bitRead(Button.inverted_mask, i));
+ used = true;
+ }
+#ifdef USE_ADC
+ else if (PinUsed(GPIO_ADC_BUTTON, i) || PinUsed(GPIO_ADC_BUTTON_INV, i)) {
+ Button.present++;
+ }
+#endif // USE_ADC
+ else {
+ XdrvMailbox.index = i;
+ if (XdrvCall(FUNC_ADD_BUTTON)) {
+
+ AddLog(LOG_LEVEL_DEBUG, PSTR("BTN: Add button %d"), i);
+
+ bitSet(Button.virtual_pin_used, i);
+ Button.present++;
+ Button.last_state[i] = XdrvMailbox.payload;
+ used = true;
+ }
+ }
+
+ if (used && ac_detect) {
+ Button.state[i] = 0x80 + 2 * BUTTON_AC_PERIOD;
+ Button.last_state[i] = 0; // Will set later in the debouncing code
+ }
+ Button.debounced_state[i] = Button.last_state[i];
+ }
+ if (Button.present) {
+ Button.first_change = true;
+ TickerButton.attach_ms((ac_detect) ? BUTTON_FAST_PROBE_INTERVAL : BUTTON_PROBE_INTERVAL, ButtonProbe);
+ }
+}
+
+uint8_t ButtonSerial(uint8_t serial_in_byte) {
+ if (Button.dual_receive_count) {
+ Button.dual_receive_count--;
+ if (Button.dual_receive_count) {
+ Button.dual_code = (Button.dual_code << 8) | serial_in_byte;
+ serial_in_byte = 0;
+ } else {
+ if (serial_in_byte != 0xA1) {
+ Button.dual_code = 0; // 0xA1 - End of Sonoff dual button code
+ }
+ }
+ }
+ if (0xA0 == serial_in_byte) { // 0xA0 - Start of Sonoff dual button code
+ serial_in_byte = 0;
+ Button.dual_code = 0;
+ Button.dual_receive_count = 3;
+ }
+
+ return serial_in_byte;
+}
+
+/*********************************************************************************************\
+ * Button handler with single press only or multi-press and hold on all buttons
+ *
+ * ButtonDebounce (50) - Debounce time in mSec
+ * SetOption1 (0) - If set do not execute commands WifiConfig and Reset
+ * SetOption11 (0) - If set perform single press action on double press and reverse (on two relay devices only)
+ * SetOption13 (0) - If set act on single press only
+ * SetOption32 (40) - Button held for factor times longer
+ * SetOption40 (0) - Do not ignore button hold
+ * SetOption73 (0) - Decouple button from relay and send just mqtt topic
+\*********************************************************************************************/
+
+void ButtonHandler(void) {
+ if (TasmotaGlobal.uptime < 4) { return; } // Block GPIO for 4 seconds after poweron to workaround Wemos D1 / Obi RTS circuit
+
+ uint8_t hold_time_extent = IMMINENT_RESET_FACTOR; // Extent hold time factor in case of iminnent Reset command
+ uint16_t loops_per_second = 1000 / Settings->button_debounce; // ButtonDebounce (50)
+ char scmnd[20];
+
+ for (uint32_t button_index = 0; button_index < MAX_KEYS; button_index++) {
+ uint8_t button = NOT_PRESSED;
+ uint8_t button_present = 0;
+
+#ifdef ESP8266
+ if (!button_index && ((SONOFF_DUAL == TasmotaGlobal.module_type) || (CH4 == TasmotaGlobal.module_type))) {
+ button_present = 1;
+ if (Button.dual_code) {
+ AddLog(LOG_LEVEL_DEBUG, PSTR("BTN: Code %04X"), Button.dual_code);
+ button = PRESSED;
+ if (0xF500 == Button.dual_code) { // Button hold
+ Button.hold_timer[button_index] = (loops_per_second * Settings->param[P_HOLD_TIME] / 10) -1; // SetOption32 (40)
+ hold_time_extent = 1;
+ }
+ Button.dual_code = 0;
+ }
+ } else
+#endif // ESP8266
+ if (PinUsed(GPIO_KEY1, button_index)) {
+
+#if defined(SOC_TOUCH_VERSION_1) || defined(SOC_TOUCH_VERSION_2)
+ if (bitRead(TouchButton.touch_mask, button_index) && bitRead(TouchButton.calibration, button_index +1)) { // Touch
+ uint32_t _value = touchRead(Pin(GPIO_KEY1, button_index));
+#ifdef SOC_TOUCH_VERSION_2
+ if (_value > Settings->touch_threshold) { // ESPS3 No touch = 24200, Touch = 100000
+#else
+ if ((_value > 0) && (_value < Settings->touch_threshold)) { // ESP32 No touch = 74, Touch = 20 (Probably read-error (0))
+#endif
+ TouchButton.hits[button_index]++;
+ } else {
+ TouchButton.hits[button_index] = 0;
+ }
+ AddLog(LOG_LEVEL_INFO, PSTR("PLOT: %u, %u, %u,"), button_index +1, _value, TouchButton.hits[button_index]); // Button number (1..4), value, continuous hits under threshold
+ continue;
+ } else
+#endif // ESP32 SOC_TOUCH_VERSION_1 or SOC_TOUCH_VERSION_2
+
+ button_present = 1;
+ button = Button.debounced_state[button_index];
+ }
+#ifdef USE_ADC
+ else if (PinUsed(GPIO_ADC_BUTTON, button_index)) {
+ button_present = 1;
+ button = AdcGetButton(Pin(GPIO_ADC_BUTTON, button_index));
+ }
+ else if (PinUsed(GPIO_ADC_BUTTON_INV, button_index)) {
+ button_present = 1;
+ button = AdcGetButton(Pin(GPIO_ADC_BUTTON_INV, button_index));
+ }
+#endif // USE_ADC
+ else if (bitRead(Button.virtual_pin_used, button_index)) {
+ button_present = 1;
+ button = Button.debounced_state[button_index];
+ }
+
+ if (button_present) {
+ XdrvMailbox.index = button_index;
+ XdrvMailbox.payload = button;
+ if (XdrvCall(FUNC_BUTTON_PRESSED)) {
+ // Serviced
+ }
+#ifdef ESP8266
+ else if (SONOFF_4CHPRO == TasmotaGlobal.module_type) {
+ if (Button.hold_timer[button_index]) { Button.hold_timer[button_index]--; }
+
+ bool button_pressed = false;
+ if ((PRESSED == button) && (NOT_PRESSED == Button.last_state[button_index])) {
+ AddLog(LOG_LEVEL_DEBUG, PSTR("BTN: Button%d level 1-0"), button_index +1);
+ Button.hold_timer[button_index] = loops_per_second;
+ button_pressed = true;
+ }
+ if ((NOT_PRESSED == button) && (PRESSED == Button.last_state[button_index])) {
+ AddLog(LOG_LEVEL_DEBUG, PSTR("BTN: Button%d level 0-1"), button_index +1);
+ if (!Button.hold_timer[button_index]) { button_pressed = true; } // Do not allow within 1 second
+ }
+ if (button_pressed) {
+ if (!Settings->flag3.mqtt_buttons) { // SetOption73 (0) - Decouple button from relay and send just mqtt topic
+ if (!SendKey(KEY_BUTTON, button_index +1, POWER_TOGGLE)) { // Execute Toggle command via MQTT if ButtonTopic is set
+ ExecuteCommandPower(button_index +1, POWER_TOGGLE, SRC_BUTTON); // Execute Toggle command internally
+ }
+ } else {
+ MqttButtonTopic(button_index +1, 1, 0); // SetOption73 (0) - Decouple button from relay and send just mqtt topic
+ }
+ }
+ }
+#endif // ESP8266
+ else {
+ if ((PRESSED == button) && (NOT_PRESSED == Button.last_state[button_index])) {
+
+ if (Settings->flag.button_single) { // SetOption13 (0) - Allow only single button press for immediate action,
+ if (!Settings->flag3.mqtt_buttons) { // SetOption73 (0) - Decouple button from relay and send just mqtt topic
+ AddLog(LOG_LEVEL_DEBUG, PSTR("BTN: Button%d immediate"), button_index +1);
+ if (!SendKey(KEY_BUTTON, button_index +1, POWER_TOGGLE)) { // Execute Toggle command via MQTT if ButtonTopic is set
+ ExecuteCommandPower(button_index +1, POWER_TOGGLE, SRC_BUTTON); // Execute Toggle command internally
+ }
+ } else {
+ MqttButtonTopic(button_index +1, 1, 0); // SetOption73 1 - Decouple button from relay and send just mqtt topic
+ }
+ } else {
+ Button.press_counter[button_index] = (Button.window_timer[button_index]) ? Button.press_counter[button_index] +1 : 1;
+ AddLog(LOG_LEVEL_DEBUG, PSTR("BTN: Button%d multi-press %d"), button_index +1, Button.press_counter[button_index]);
+ Button.window_timer[button_index] = loops_per_second / 2; // 0.5 second multi press window
+ }
+ TasmotaGlobal.blinks = 201;
+ }
+
+ if (NOT_PRESSED == button) {
+ Button.hold_timer[button_index] = 0;
+ if (Settings->flag3.mqtt_buttons && (PRESSED == Button.last_state[button_index]) && !Button.press_counter[button_index]) { // SetOption73 (0) - Decouple button from relay and send just mqtt topic
+ MqttButtonTopic(button_index +1, 6, 0);
+ }
+ } else {
+ Button.hold_timer[button_index]++;
+ if (Settings->flag.button_single) { // SetOption13 (0) - Allow only single button press for immediate action
+ if (Button.hold_timer[button_index] == loops_per_second * hold_time_extent * Settings->param[P_HOLD_TIME] / 10) { // SetOption32 (40) - Button held for factor times longer
+ snprintf_P(scmnd, sizeof(scmnd), PSTR(D_CMND_SETOPTION "13 0")); // Disable single press only
+ ExecuteCommand(scmnd, SRC_BUTTON);
+ }
+ } else {
+ if (Button.hold_timer[button_index] == loops_per_second * Settings->param[P_HOLD_TIME] / 10) { // SetOption32 (40) - Button hold
+ Button.press_counter[button_index] = 0;
+ if (Settings->flag3.mqtt_buttons) { // SetOption73 (0) - Decouple button from relay and send just mqtt topic
+ MqttButtonTopic(button_index +1, 3, 1);
+ } else {
+ SendKey(KEY_BUTTON, button_index +1, POWER_HOLD); // Execute Hold command via MQTT if ButtonTopic is set
+ }
+ } else {
+ if (Settings->flag.button_restrict) { // SetOption1 (0) - Control button multipress
+ if (Settings->param[P_HOLD_IGNORE] > 0) { // SetOption40 (0) - Do not ignore button hold
+ if (Button.hold_timer[button_index] > loops_per_second * Settings->param[P_HOLD_IGNORE] / 10) {
+ Button.hold_timer[button_index] = 0; // Reset button hold counter to stay below hold trigger
+ Button.press_counter[button_index] = 0; // Discard button press to disable functionality
+ }
+ }
+ } else {
+ if ((Button.hold_timer[button_index] == loops_per_second * hold_time_extent * Settings->param[P_HOLD_TIME] / 10)) { // SetOption32 (40) - Button held for factor times longer
+ Button.press_counter[button_index] = 0;
+ snprintf_P(scmnd, sizeof(scmnd), PSTR(D_CMND_RESET " 1"));
+ ExecuteCommand(scmnd, SRC_BUTTON);
+ }
+ }
+ }
+ }
+ }
+
+ if (!Settings->flag.button_single) { // SetOption13 (0) - Allow multi-press
+ if (Button.window_timer[button_index]) {
+ Button.window_timer[button_index]--;
+ } else {
+ if (!TasmotaGlobal.restart_flag && !Button.hold_timer[button_index] && (Button.press_counter[button_index] > 0) && (Button.press_counter[button_index] < 7)) {
+
+ bool single_press = false;
+ if (Button.press_counter[button_index] < 3) { // Single or Double press
+#ifdef ESP8266
+ if ((SONOFF_DUAL_R2 == TasmotaGlobal.module_type) || (SONOFF_DUAL == TasmotaGlobal.module_type) || (CH4 == TasmotaGlobal.module_type)) {
+ single_press = true;
+ } else
+#endif // ESP8266
+ {
+ single_press = (Settings->flag.button_swap +1 == Button.press_counter[button_index]); // SetOption11 (0)
+ if ((1 == Button.present) && (2 == TasmotaGlobal.devices_present)) { // Single Button with two devices only
+ if (Settings->flag.button_swap) { // SetOption11 (0)
+ Button.press_counter[button_index] = (single_press) ? 1 : 2;
+ }
+ }
+ }
+ }
+
+ XdrvMailbox.index = button_index;
+ XdrvMailbox.payload = Button.press_counter[button_index];
+ if (XdrvCall(FUNC_BUTTON_MULTI_PRESSED)) {
+ // Serviced
+ } else
+
+#ifdef ROTARY_V1
+ if (!RotaryButtonPressed(button_index)) {
+#endif
+ if (!Settings->flag3.mqtt_buttons && single_press && SendKey(KEY_BUTTON, button_index + Button.press_counter[button_index], POWER_TOGGLE)) { // Execute Toggle command via MQTT if ButtonTopic is set
+ // Success
+ } else {
+ if (Button.press_counter[button_index] < 6) { // Single to Penta press
+// if (WifiState() > WIFI_RESTART) { // Wifimanager active
+// TasmotaGlobal.restart_flag = 1;
+// }
+ if (!Settings->flag3.mqtt_buttons) { // SetOption73 - Detach buttons from relays and enable MQTT action state for multipress
+ if (Button.press_counter[button_index] == 1) { // By default first press always send a TOGGLE (2)
+ ExecuteCommandPower(button_index + Button.press_counter[button_index], POWER_TOGGLE, SRC_BUTTON);
+ } else {
+ SendKey(KEY_BUTTON, button_index +1, Button.press_counter[button_index] +9); // 2,3,4 and 5 press send just the key value (11,12,13 and 14) for rules
+ if (0 == button_index) { // BUTTON1 can toggle up to 5 relays if present. If a relay is not present will send out the key value (2,11,12,13 and 14) for rules
+ bool valid_relay = PinUsed(GPIO_REL1, Button.press_counter[button_index]-1);
+#ifdef ESP8266
+ if ((SONOFF_DUAL == TasmotaGlobal.module_type) || (CH4 == TasmotaGlobal.module_type)) {
+ valid_relay = (Button.press_counter[button_index] <= TasmotaGlobal.devices_present);
+ }
+#endif // ESP8266
+#ifdef USE_SHELLY_PRO
+ if (TasmotaGlobal.gpio_optiona.shelly_pro) {
+ valid_relay = (Button.press_counter[button_index] <= TasmotaGlobal.devices_present);
+ }
+#endif // USE_SHELLY_PRO
+ if ((Button.press_counter[button_index] > 1) && valid_relay && (Button.press_counter[button_index] <= MAX_RELAY_BUTTON1)) {
+ ExecuteCommandPower(button_index + Button.press_counter[button_index], POWER_TOGGLE, SRC_BUTTON); // Execute Toggle command internally
+// AddLog(LOG_LEVEL_DEBUG, PSTR("BTN: Relay%d found on GPIO%d"), Button.press_counter[button_index], Pin(GPIO_REL1, Button.press_counter[button_index]-1));
+ }
+ }
+ }
+ }
+
+ } else { // 6 press start wificonfig 2
+ if (!Settings->flag.button_restrict) { // SetOption1 - Control button multipress
+ snprintf_P(scmnd, sizeof(scmnd), PSTR(D_CMND_WIFICONFIG " 2"));
+ ExecuteCommand(scmnd, SRC_BUTTON);
+ }
+ }
+ if (Settings->flag3.mqtt_buttons) { // SetOption73 (0) - Decouple button from relay and send just mqtt topic
+ if (Button.press_counter[button_index] >= 1 && Button.press_counter[button_index] <= 5) {
+ MqttButtonTopic(button_index +1, Button.press_counter[button_index], 0);
+ }
+ }
+ }
+#ifdef ROTARY_V1
+ }
+#endif
+ Button.press_counter[button_index] = 0;
+ }
+ }
+ }
+
+ }
+ }
+ Button.last_state[button_index] = button;
+ }
+}
+
+void MqttButtonTopic(uint32_t button_id, uint32_t action, uint32_t hold) {
+ SendKey(KEY_BUTTON, button_id, (hold) ? 3 : action +9);
+
+ if (!Settings->flag.hass_discovery) { // SetOption19 - Control Home Assistant automatic discovery (See SetOption59)
+ char scommand[10];
+ snprintf_P(scommand, sizeof(scommand), PSTR(D_JSON_BUTTON "%d"), button_id);
+ char mqttstate[7];
+ Response_P(S_JSON_SVALUE_ACTION_SVALUE, scommand, (hold) ? SettingsText(SET_STATE_TXT4) : GetTextIndexed(mqttstate, sizeof(mqttstate), action, kMultiPress));
+ MqttPublishPrefixTopicRulesProcess_P(RESULT_OR_STAT, scommand);
+ }
+}
+
+void ButtonLoop(void) {
+ if (Button.present) {
+ if (TimeReached(Button.debounce)) {
+ SetNextTimeInterval(Button.debounce, Settings->button_debounce); // ButtonDebounce (50)
+ ButtonHandler();
+ }
+ }
+}
+
+#endif // BUTTON_V3
diff --git a/tasmota/tasmota_support/support_switch_v3.ino b/tasmota/tasmota_support/support_switch_v3.ino
index f00160131..392c0afda 100644
--- a/tasmota/tasmota_support/support_switch_v3.ino
+++ b/tasmota/tasmota_support/support_switch_v3.ino
@@ -17,7 +17,7 @@
along with this program. If not, see .
*/
-#define SWITCH_V3
+//#define SWITCH_V3
#ifdef SWITCH_V3
/*********************************************************************************************\
* Switch support with input filter
diff --git a/tasmota/tasmota_support/support_switch_v4.ino b/tasmota/tasmota_support/support_switch_v4.ino
new file mode 100644
index 000000000..9b4a81f72
--- /dev/null
+++ b/tasmota/tasmota_support/support_switch_v4.ino
@@ -0,0 +1,490 @@
+/*
+ support_switch.ino - switch support for Tasmota
+
+ Copyright (C) 2021 Theo Arends
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
+
+#define SWITCH_V4
+#ifdef SWITCH_V4
+/*********************************************************************************************\
+ * Switch support with input filter
+ *
+ * Inspired by (https://github.com/OLIMEX/olimex-iot-firmware-esp8266/blob/master/olimex/user/user_switch2.c)
+\*********************************************************************************************/
+
+const uint8_t SWITCH_PROBE_INTERVAL = 10; // Time in milliseconds between switch input probe
+const uint8_t SWITCH_FAST_PROBE_INTERVAL = 2; // Time in milliseconds between switch input probe for AC detection
+const uint8_t SWITCH_AC_PERIOD = (20 + SWITCH_FAST_PROBE_INTERVAL - 1) / SWITCH_FAST_PROBE_INTERVAL; // Duration of an AC wave in probe intervals
+
+// Switch Mode definietions
+#define SM_TIMER_MASK 0x3F
+#define SM_NO_TIMER_MASK 0xFF
+#define SM_FIRST_PRESS 0x40
+#define SM_SECOND_PRESS 0x80
+#define POWER_NONE 99
+
+const char kSwitchPressStates[] PROGMEM =
+ "||||POWER_INCREMENT|POWER_INV|POWER_CLEAR|POWER_RELEASE|POWER_100||POWER_DELAYED";
+
+#include
+
+Ticker TickerSwitch;
+
+struct SWITCH {
+ uint32_t debounce = 0; // Switch debounce timer
+ uint32_t no_pullup_mask = 0; // Switch pull-up bitmask flags
+ uint32_t pulldown_mask = 0; // Switch pull-down bitmask flags
+ uint32_t virtual_pin_used = 0; // Switch used bitmask
+ uint32_t virtual_pin = 0; // Switch state bitmask
+ uint8_t state[MAX_SWITCHES] = { 0 };
+ uint8_t last_state[MAX_SWITCHES]; // Last wall switch states
+ uint8_t hold_timer[MAX_SWITCHES] = { 0 }; // Timer for wallswitch push button hold
+ uint8_t debounced_state[MAX_SWITCHES]; // Switch debounced states
+ uint8_t first_change = 0;
+ uint8_t present = 0;
+ bool probe_mutex;
+} Switch;
+
+/********************************************************************************************/
+
+void SwitchPullupFlag(uint32 switch_bit) {
+ bitSet(Switch.no_pullup_mask, switch_bit);
+}
+
+void SwitchPulldownFlag(uint32 switch_bit) {
+ bitSet(Switch.pulldown_mask, switch_bit);
+}
+
+void SwitchSetVirtualPinState(uint32_t index, uint32_t state) {
+ if (!Switch.probe_mutex) {
+ bitWrite(Switch.virtual_pin, index, state);
+ }
+}
+
+void SwitchSetVirtual(uint32_t index, uint32_t state) {
+ bitSet(Switch.virtual_pin_used, index);
+ Switch.debounced_state[index] = state;
+}
+
+uint8_t SwitchGetVirtual(uint32_t index) {
+ return Switch.debounced_state[index];
+}
+
+uint8_t SwitchLastState(uint32_t index) {
+ return Switch.last_state[index];
+}
+
+bool SwitchState(uint32_t index) {
+ uint32_t switchmode = Settings->switchmode[index];
+ return ((FOLLOW_INV == switchmode) ||
+ (PUSHBUTTON_INV == switchmode) ||
+ (PUSHBUTTONHOLD_INV == switchmode) ||
+ (FOLLOWMULTI_INV == switchmode) ||
+ (PUSHHOLDMULTI_INV == switchmode) ||
+ (PUSHON_INV == switchmode) ||
+ (PUSH_IGNORE_INV == switchmode)
+ ) ^ Switch.last_state[index];
+}
+
+/*********************************************************************************************/
+
+void SwitchProbe(void) {
+ if (Switch.probe_mutex || (TasmotaGlobal.uptime < 4)) { return; } // Block GPIO for 4 seconds after poweron to workaround Wemos D1 / Obi RTS circuit
+ Switch.probe_mutex = true;
+
+ uint32_t state_filter;
+ uint32_t first_change = Switch.first_change;
+ uint32_t debounce_flags = Settings->switch_debounce % 10;
+ bool force_high = (debounce_flags &1); // 51, 101, 151 etc
+ bool force_low = (debounce_flags &2); // 52, 102, 152 etc
+ bool ac_detect = (debounce_flags == 9);
+
+ if (ac_detect) {
+ if (Settings->switch_debounce < 2 * SWITCH_AC_PERIOD * SWITCH_FAST_PROBE_INTERVAL + 9) {
+ state_filter = 2 * SWITCH_AC_PERIOD;
+ } else if (Settings->switch_debounce > (0x7f - 2 * SWITCH_AC_PERIOD) * SWITCH_FAST_PROBE_INTERVAL) {
+ state_filter = 0x7f;
+ } else {
+ state_filter = (Settings->switch_debounce - 9) / SWITCH_FAST_PROBE_INTERVAL;
+ }
+ } else {
+ state_filter = Settings->switch_debounce / SWITCH_PROBE_INTERVAL; // 5, 10, 15
+ }
+
+ uint32_t not_activated;
+ for (uint32_t i = 0; i < MAX_SWITCHES; i++) {
+ if (PinUsed(GPIO_SWT1, i)) {
+ not_activated = digitalRead(Pin(GPIO_SWT1, i));
+ }
+ else if (bitRead(Switch.virtual_pin_used, i)) {
+ not_activated = bitRead(Switch.virtual_pin, i);
+ }
+ else { continue; }
+
+ // Olimex user_switch2.c code to fix 50Hz induced pulses
+ if (not_activated) {
+
+ if (ac_detect) { // Enabled with SwitchDebounce x9
+ Switch.state[i] |= 0x80;
+ if (Switch.state[i] > 0x80) {
+ Switch.state[i]--;
+ if (0x80 == Switch.state[i]) {
+ Switch.debounced_state[i] = 0;
+ Switch.first_change = false;
+ }
+ }
+ } else {
+
+ if (force_high) { // Enabled with SwitchDebounce x1
+ if (1 == Switch.debounced_state[i]) {
+ Switch.state[i] = state_filter; // With noisy input keep current state 1 unless constant 0
+ }
+ }
+
+ if (Switch.state[i] < state_filter) {
+ Switch.state[i]++;
+ if (state_filter == Switch.state[i]) {
+ Switch.debounced_state[i] = 1;
+ }
+ }
+ }
+ } else {
+
+ if (ac_detect) { // Enabled with SwitchDebounce x9
+ /*
+ * Moes MS-104B and similar devices using an AC detection circuitry
+ * on their switch inputs generating an ~4 ms long low pulse every
+ * AC wave. We start the time measurement on the falling edge.
+ *
+ * state: bit7: previous state, bit6..0: counter
+ */
+ if (Switch.state[i] & 0x80) {
+ Switch.state[i] &= 0x7f;
+ if (Switch.state[i] < state_filter - 2 * SWITCH_AC_PERIOD) {
+ Switch.state[i] += 2 * SWITCH_AC_PERIOD;
+ } else {
+ Switch.state[i] = state_filter;
+ Switch.debounced_state[i] = 1;
+ if (first_change) {
+ Switch.last_state[i] = 1;
+ Switch.first_change = false;
+ }
+ }
+ } else {
+ if (Switch.state[i] > 0x00) {
+ Switch.state[i]--;
+ if (0x00 == Switch.state[i]) {
+ Switch.debounced_state[i] = 0;
+ Switch.first_change = false;
+ }
+ }
+ }
+ } else {
+
+ if (force_low) { // Enabled with SwitchDebounce x2
+ if (0 == Switch.debounced_state[i]) {
+ Switch.state[i] = 0; // With noisy input keep current state 0 unless constant 1
+ }
+ }
+
+ if (Switch.state[i] > 0) {
+ Switch.state[i]--;
+ if (0 == Switch.state[i]) {
+ Switch.debounced_state[i] = 0;
+ }
+ }
+ }
+ }
+ }
+
+ Switch.probe_mutex = false;
+}
+
+void SwitchInit(void) {
+ bool ac_detect = (Settings->switch_debounce % 10 == 9);
+
+ Switch.present = 0;
+ Switch.virtual_pin_used = 0;
+ for (uint32_t i = 0; i < MAX_SWITCHES; i++) {
+ Switch.last_state[i] = NOT_PRESSED; // Init global to virtual switch state;
+ bool used = false;
+
+ if (PinUsed(GPIO_SWT1, i)) {
+ Switch.present++;
+#ifdef ESP8266
+ pinMode(Pin(GPIO_SWT1, i), bitRead(Switch.no_pullup_mask, i) ? INPUT : ((16 == Pin(GPIO_SWT1, i)) ? INPUT_PULLDOWN_16 : INPUT_PULLUP));
+#endif // ESP8266
+#ifdef ESP32
+ pinMode(Pin(GPIO_SWT1, i), bitRead(Switch.pulldown_mask, i) ? INPUT_PULLDOWN : bitRead(Switch.no_pullup_mask, i) ? INPUT : INPUT_PULLUP);
+#endif // ESP32
+ Switch.last_state[i] = digitalRead(Pin(GPIO_SWT1, i)); // Set global now so doesn't change the saved power state on first switch check
+ used = true;
+ }
+ else {
+ XdrvMailbox.index = i;
+ if (XdrvCall(FUNC_ADD_SWITCH)) {
+
+ AddLog(LOG_LEVEL_DEBUG, PSTR("SWT: Add switch %d"), i);
+
+ bitSet(Switch.virtual_pin_used, i);
+ Switch.present++;
+ Switch.last_state[i] = XdrvMailbox.payload;
+ used = true;
+ }
+ }
+
+ if (used && ac_detect) {
+ Switch.state[i] = 0x80 + 2 * SWITCH_AC_PERIOD;
+ Switch.last_state[i] = 0; // Will set later in the debouncing code
+ }
+ Switch.debounced_state[i] = Switch.last_state[i];
+ }
+ if (Switch.present) {
+ Switch.first_change = true;
+ TickerSwitch.attach_ms((ac_detect) ? SWITCH_FAST_PROBE_INTERVAL : SWITCH_PROBE_INTERVAL, SwitchProbe);
+ }
+}
+
+/*********************************************************************************************\
+ * Switch handler
+\*********************************************************************************************/
+
+void SwitchHandler(uint32_t mode) {
+ if (TasmotaGlobal.uptime < 4) { return; } // Block GPIO for 4 seconds after poweron to workaround Wemos D1 / Obi RTS circuit
+
+ uint32_t loops_per_second = 1000 / Settings->switch_debounce;
+
+ for (uint32_t i = 0; i < MAX_SWITCHES; i++) {
+ if (PinUsed(GPIO_SWT1, i) || bitRead(Switch.virtual_pin_used, i)) {
+ uint32_t button = Switch.debounced_state[i];
+ uint32_t switchflag = POWER_TOGGLE +1;
+ uint32_t mqtt_action = POWER_NONE;
+ uint32_t switchmode = Settings->switchmode[i];
+
+ if (Switch.hold_timer[i] & (((switchmode == PUSHHOLDMULTI) | (switchmode == PUSHHOLDMULTI_INV)) ? SM_TIMER_MASK: SM_NO_TIMER_MASK)) {
+ Switch.hold_timer[i]--;
+ if ((Switch.hold_timer[i] & SM_TIMER_MASK) == loops_per_second * Settings->param[P_HOLD_TIME] / 25) {
+ if ((switchmode == PUSHHOLDMULTI) | (switchmode == PUSHHOLDMULTI_INV)){
+ if (((switchmode == PUSHHOLDMULTI) & (NOT_PRESSED == Switch.last_state[i])) | ((switchmode == PUSHHOLDMULTI_INV) & (PRESSED == Switch.last_state[i]))) {
+ SendKey(KEY_SWITCH, i +1, POWER_INCREMENT); // Execute command via MQTT
+ }
+ else if ((Switch.hold_timer[i] & ~SM_TIMER_MASK) == SM_FIRST_PRESS) {
+ SendKey(KEY_SWITCH, i +1, POWER_DELAYED); // Execute command via MQTT
+ mqtt_action = POWER_DELAYED;
+ Switch.hold_timer[i] = 0;
+ }
+ }
+ }
+ if (0 == (Switch.hold_timer[i] & (((switchmode == PUSHHOLDMULTI) | (switchmode == PUSHHOLDMULTI_INV)) ? SM_TIMER_MASK: SM_NO_TIMER_MASK))) {
+ switch (switchmode) {
+ case TOGGLEMULTI:
+ switchflag = POWER_TOGGLE; // Toggle after hold
+ break;
+ case FOLLOWMULTI:
+ switchflag = button &1; // Follow wall switch state after hold
+ break;
+ case FOLLOWMULTI_INV:
+ switchflag = ~button &1; // Follow inverted wall switch state after hold
+ break;
+ case PUSHHOLDMULTI:
+ if (NOT_PRESSED == button) {
+ Switch.hold_timer[i] = loops_per_second * Settings->param[P_HOLD_TIME] / 25;
+ SendKey(KEY_SWITCH, i +1, POWER_INCREMENT); // Execute command via MQTT
+ mqtt_action = POWER_INCREMENT;
+ } else {
+ Switch.hold_timer[i]= 0;
+ SendKey(KEY_SWITCH, i +1, POWER_CLEAR); // Execute command via MQTT
+ mqtt_action = POWER_CLEAR;
+ }
+ break;
+ case PUSHHOLDMULTI_INV:
+ if (PRESSED == button) {
+ Switch.hold_timer[i] = loops_per_second * Settings->param[P_HOLD_TIME] / 25;
+ SendKey(KEY_SWITCH, i +1, POWER_INCREMENT); // Execute command via MQTT
+ mqtt_action = POWER_INCREMENT;
+ } else {
+ Switch.hold_timer[i]= 0;
+ SendKey(KEY_SWITCH, i +1, POWER_CLEAR); // Execute command via MQTT
+ mqtt_action = POWER_CLEAR;
+ }
+ break;
+ default:
+ SendKey(KEY_SWITCH, i +1, POWER_HOLD); // Execute command via MQTT
+ mqtt_action = POWER_HOLD;
+ break;
+ }
+ }
+ }
+
+ if (button != Switch.last_state[i]) { // This implies if ((PRESSED == button) then (NOT_PRESSED == Switch.last_state[i]))
+ switch (switchmode) {
+ case TOGGLE:
+ case PUSHBUTTON_TOGGLE:
+ switchflag = POWER_TOGGLE; // Toggle
+ break;
+ case FOLLOW:
+ switchflag = button &1; // Follow wall switch state
+ break;
+ case FOLLOW_INV:
+ switchflag = ~button &1; // Follow inverted wall switch state
+ break;
+ case PUSHBUTTON:
+ if (PRESSED == button) {
+ switchflag = POWER_TOGGLE; // Toggle with pushbutton to Gnd
+ }
+ break;
+ case PUSHBUTTON_INV:
+ if (NOT_PRESSED == button) {
+ switchflag = POWER_TOGGLE; // Toggle with releasing pushbutton from Gnd
+ }
+ break;
+ case PUSHBUTTONHOLD:
+ if (PRESSED == button) {
+ Switch.hold_timer[i] = loops_per_second * Settings->param[P_HOLD_TIME] / 10; // Start timer on button press
+ }
+ if ((NOT_PRESSED == button) && (Switch.hold_timer[i])) {
+ Switch.hold_timer[i] = 0; // Button released and hold timer not expired : stop timer...
+ switchflag = POWER_TOGGLE; // ...and Toggle
+ }
+ break;
+ case PUSHBUTTONHOLD_INV:
+ if (NOT_PRESSED == button) {
+ Switch.hold_timer[i] = loops_per_second * Settings->param[P_HOLD_TIME] / 10; // Start timer on button press...
+ }
+ if ((PRESSED == button) && (Switch.hold_timer[i])) {
+ Switch.hold_timer[i] = 0; // Button released and hold timer not expired : stop timer.
+ switchflag = POWER_TOGGLE; // ...and Toggle
+ }
+ break;
+ case TOGGLEMULTI:
+ case FOLLOWMULTI:
+ case FOLLOWMULTI_INV:
+ if (Switch.hold_timer[i]) {
+ Switch.hold_timer[i] = 0;
+ SendKey(KEY_SWITCH, i +1, POWER_HOLD); // Execute command via MQTT
+ mqtt_action = POWER_HOLD;
+ } else {
+ Switch.hold_timer[i] = loops_per_second / 2; // 0.5 second multi press window
+ }
+ break;
+ case PUSHHOLDMULTI:
+ if (NOT_PRESSED == button) {
+ if ((Switch.hold_timer[i] & SM_TIMER_MASK) != 0) {
+ Switch.hold_timer[i] = ((Switch.hold_timer[i] & ~SM_TIMER_MASK) == SM_FIRST_PRESS) ? SM_SECOND_PRESS : 0;
+ SendKey(KEY_SWITCH, i +1, POWER_INV); // Execute command via MQTT
+ mqtt_action = POWER_INV;
+ }
+ } else {
+ if ((Switch.hold_timer[i] & SM_TIMER_MASK) > loops_per_second * Settings->param[P_HOLD_TIME] / 25) {
+ if ((Switch.hold_timer[i] & ~SM_TIMER_MASK) != SM_SECOND_PRESS) {
+ Switch.hold_timer[i]= SM_FIRST_PRESS;
+ switchflag = POWER_TOGGLE; // Toggle with pushbutton
+ }
+ else{
+ SendKey(KEY_SWITCH, i +1, POWER_100); // Execute command via MQTT
+ mqtt_action = POWER_100;
+ Switch.hold_timer[i]= 0;
+ }
+ } else {
+ Switch.hold_timer[i]= 0;
+ SendKey(KEY_SWITCH, i +1, POWER_RELEASE); // Execute command via MQTT
+ mqtt_action = POWER_RELEASE;
+ }
+ }
+ Switch.hold_timer[i] = (Switch.hold_timer[i] & ~SM_TIMER_MASK) | loops_per_second * Settings->param[P_HOLD_TIME] / 10;
+ break;
+ case PUSHHOLDMULTI_INV:
+ if (PRESSED == button) {
+ if ((Switch.hold_timer[i] & SM_TIMER_MASK) != 0) {
+ Switch.hold_timer[i] = ((Switch.hold_timer[i] & ~SM_TIMER_MASK) == SM_FIRST_PRESS) ? SM_SECOND_PRESS : 0;
+ SendKey(KEY_SWITCH, i +1, POWER_INV); // Execute command via MQTT
+ mqtt_action = POWER_INV;
+ }
+ } else {
+ if ((Switch.hold_timer[i] & SM_TIMER_MASK)> loops_per_second * Settings->param[P_HOLD_TIME] / 25) {
+ if ((Switch.hold_timer[i] & ~SM_TIMER_MASK) != SM_SECOND_PRESS) {
+ Switch.hold_timer[i]= SM_FIRST_PRESS;
+ switchflag = POWER_TOGGLE; // Toggle with pushbutton
+ }
+ else{
+ SendKey(KEY_SWITCH, i +1, POWER_100); // Execute command via MQTT
+ mqtt_action = POWER_100;
+ Switch.hold_timer[i]= 0;
+ }
+ } else {
+ Switch.hold_timer[i]= 0;
+ SendKey(KEY_SWITCH, i +1, POWER_RELEASE); // Execute command via MQTT
+ mqtt_action = POWER_RELEASE;
+ }
+ }
+ Switch.hold_timer[i] = (Switch.hold_timer[i] & ~SM_TIMER_MASK) | loops_per_second * Settings->param[P_HOLD_TIME] / 10;
+ break;
+ case PUSHON:
+ if (PRESSED == button) {
+ switchflag = POWER_ON; // Power ON with pushbutton to Gnd
+ }
+ break;
+ case PUSHON_INV:
+ if (NOT_PRESSED == button) {
+ switchflag = POWER_ON; // Power ON with releasing pushbutton from Gnd
+ }
+ break;
+ case PUSH_IGNORE:
+ case PUSH_IGNORE_INV:
+ Switch.last_state[i] = button; // Update switch state before publishing
+ MqttPublishSensor();
+ break;
+ }
+ Switch.last_state[i] = button;
+ }
+ if (switchflag <= POWER_TOGGLE) {
+ if (!Settings->flag5.mqtt_switches) { // SetOption114 (0) - Detach Switches from relays and enable MQTT action state for all the SwitchModes
+ if (!SendKey(KEY_SWITCH, i +1, switchflag)) { // Execute command via MQTT
+ ExecuteCommandPower(i +1, switchflag, SRC_SWITCH); // Execute command internally (if i < TasmotaGlobal.devices_present)
+ }
+ } else { mqtt_action = switchflag; }
+ }
+ if ((mqtt_action != POWER_NONE) && Settings->flag5.mqtt_switches) { // SetOption114 (0) - Detach Switches from relays and enable MQTT action state for all the SwitchModes
+ if (!Settings->flag.hass_discovery) { // SetOption19 - Control Home Assistant automatic discovery (See SetOption59)
+ char mqtt_state_str[16];
+ char *mqtt_state = mqtt_state_str;
+ if (mqtt_action <= 3) {
+ if (mqtt_action != 3) { SendKey(KEY_SWITCH, i +1, mqtt_action); }
+ mqtt_state = SettingsText(SET_STATE_TXT1 + mqtt_action);
+ } else {
+ GetTextIndexed(mqtt_state_str, sizeof(mqtt_state_str), mqtt_action, kSwitchPressStates);
+ }
+ Response_P(S_JSON_SVALUE_ACTION_SVALUE, GetSwitchText(i).c_str(), mqtt_state);
+ char scommand[10];
+ snprintf_P(scommand, sizeof(scommand), PSTR(D_JSON_SWITCH "%d"), i +1);
+ MqttPublishPrefixTopicRulesProcess_P(RESULT_OR_STAT, scommand);
+ }
+ mqtt_action = POWER_NONE;
+ }
+ }
+ }
+}
+
+void SwitchLoop(void) {
+ if (Switch.present) {
+ if (TimeReached(Switch.debounce)) {
+ SetNextTimeInterval(Switch.debounce, Settings->switch_debounce);
+ SwitchHandler(0);
+ }
+ }
+}
+
+#endif // SWITCH_V3
diff --git a/tasmota/tasmota_xdrv_driver/xdrv_52_3_berry_tasmota.ino b/tasmota/tasmota_xdrv_driver/xdrv_52_3_berry_tasmota.ino
index b31ed5b99..4ac0451d3 100644
--- a/tasmota/tasmota_xdrv_driver/xdrv_52_3_berry_tasmota.ino
+++ b/tasmota/tasmota_xdrv_driver/xdrv_52_3_berry_tasmota.ino
@@ -580,7 +580,7 @@ extern "C" {
be_newobject(vm, "list");
for (uint32_t i = 0; i < MAX_SWITCHES; i++) {
if (PinUsed(GPIO_SWT1, i)) {
- be_pushbool(vm, Switch.virtual_state[i] == PRESSED);
+ be_pushbool(vm, SwitchGetVirtual(i) == PRESSED);
be_data_push(vm, -2);
be_pop(vm, 1);
}
diff --git a/tasmota/tasmota_xdrv_driver/xdrv_88_esp32_shelly_pro.ino b/tasmota/tasmota_xdrv_driver/xdrv_88_esp32_shelly_pro.ino
index 9642163ce..94573422e 100644
--- a/tasmota/tasmota_xdrv_driver/xdrv_88_esp32_shelly_pro.ino
+++ b/tasmota/tasmota_xdrv_driver/xdrv_88_esp32_shelly_pro.ino
@@ -19,7 +19,7 @@
#ifdef ESP32
#ifdef USE_SPI
-#ifdef USE_SHELLY_PRO
+#ifdef USE_SHELLY_PRO_V1
/*********************************************************************************************\
* Shelly Pro support
*
diff --git a/tasmota/tasmota_xdrv_driver/xdrv_88_esp32_shelly_pro_v2.ino b/tasmota/tasmota_xdrv_driver/xdrv_88_esp32_shelly_pro_v2.ino
new file mode 100644
index 000000000..2b43768f9
--- /dev/null
+++ b/tasmota/tasmota_xdrv_driver/xdrv_88_esp32_shelly_pro_v2.ino
@@ -0,0 +1,501 @@
+/*
+ xdrv_88_shelly_pro.ino - Shelly pro family support for Tasmota
+
+ Copyright (C) 2022 Theo Arends
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+*/
+
+#ifdef ESP32
+#ifdef USE_SPI
+#ifdef USE_SHELLY_PRO
+/*********************************************************************************************\
+ * Shelly Pro support
+ *
+ * {"NAME":"Shelly Pro 1","GPIO":[0,1,0,1,768,0,0,0,672,704,736,0,0,0,5600,6214,0,0,0,5568,0,0,0,0,0,0,0,0,0,0,0,32,4736,0,160,0],"FLAG":0,"BASE":1,"CMND":"AdcParam1 2,10000,10000,3350"}
+ * {"NAME":"Shelly Pro 1PM","GPIO":[9568,1,9472,1,768,0,0,0,672,704,736,0,0,0,5600,6214,0,0,0,5568,0,0,0,0,0,0,0,0,3459,0,0,32,4736,0,160,0],"FLAG":0,"BASE":1,"CMND":"AdcParam1 2,10000,10000,3350"}
+ * {"NAME":"Shelly Pro 2","GPIO":[0,1,0,1,768,0,0,0,672,704,736,0,0,0,5600,6214,0,0,0,5568,0,0,0,0,0,0,0,0,0,0,0,32,4736,4737,160,161],"FLAG":0,"BASE":1,"CMND":"AdcParam1 2,10000,10000,3350;AdcParam2 2,10000,10000,3350"}
+ * {"NAME":"Shelly Pro 2PM","GPIO":[9568,1,9472,1,768,0,0,0,672,704,736,9569,0,0,5600,6214,0,0,0,5568,0,0,0,0,0,0,0,0,3460,0,0,32,4736,4737,160,161],"FLAG":0,"BASE":1,"CMND":"AdcParam1 2,10000,10000,3350;AdcParam2 2,10000,10000,3350"}
+ *
+ * {"NAME":"Shelly Pro 4PM","GPIO":[769,1,1,1,9568,0,0,0,1,705,9569,737,768,0,5600,0,0,0,0,5568,0,0,0,0,0,0,0,6214,736,704,3461,0,4736,1,0,672],"FLAG":0,"BASE":1,"CMND":"AdcParam1 2,5600,4700,3350"}
+ * {"NAME":"Shelly Pro 4PM No display","GPIO":[1,1,1,1,9568,0,0,0,1,1,9569,1,768,0,5600,0,0,0,0,5568,0,0,0,0,0,0,0,6214,736,704,3461,0,4736,1,0,672],"FLAG":0,"BASE":1,"CMND":"AdcParam1 2,5600,4700,3350"}
+ *
+ * Shelly Pro 1/2 uses SPI to control one 74HC595 for relays/leds and one ADE7953 (1PM) or two ADE7953 (2PM) for energy monitoring
+ * Shelly Pro 4 uses an SPI to control one MCP23S17 for buttons/switches/relays/leds and two ADE7953 for energy monitoring and a second SPI for the display
+\*********************************************************************************************/
+
+#define XDRV_88 88
+
+#define SHELLY_PRO_PIN_LAN8720_RESET 5
+#define SHELLY_PRO_4_PIN_SPI_CS 16
+#define SHELLY_PRO_4_PIN_MCP23S17_INT 35
+#define SHELLY_PRO_4_MCP23S17_ADDRESS 0x40
+
+struct SPro {
+ uint32_t last_update;
+ uint32_t probe_pin;
+ int switch_offset;
+ int button_offset;
+ uint8_t last_button[3];
+ uint8_t pin_register_cs;
+ uint8_t pin_mcp23s17_int;
+ uint8_t ledlink;
+ uint8_t power;
+ uint8_t detected;
+} SPro;
+
+/*********************************************************************************************\
+ * Shelly Pro MCP23S17 support
+\*********************************************************************************************/
+
+enum SP4MCP23X17GPIORegisters {
+ // A side
+ SP4_MCP23S17_IODIRA = 0x00,
+ SP4_MCP23S17_IPOLA = 0x02,
+ SP4_MCP23S17_GPINTENA = 0x04,
+ SP4_MCP23S17_DEFVALA = 0x06,
+ SP4_MCP23S17_INTCONA = 0x08,
+ SP4_MCP23S17_IOCONA = 0x0A,
+ SP4_MCP23S17_GPPUA = 0x0C,
+ SP4_MCP23S17_INTFA = 0x0E,
+ SP4_MCP23S17_INTCAPA = 0x10,
+ SP4_MCP23S17_GPIOA = 0x12,
+ SP4_MCP23S17_OLATA = 0x14,
+ // B side
+ SP4_MCP23S17_IODIRB = 0x01,
+ SP4_MCP23S17_IPOLB = 0x03,
+ SP4_MCP23S17_GPINTENB = 0x05,
+ SP4_MCP23S17_DEFVALB = 0x07,
+ SP4_MCP23S17_INTCONB = 0x09,
+ SP4_MCP23S17_IOCONB = 0x0B,
+ SP4_MCP23S17_GPPUB = 0x0D,
+ SP4_MCP23S17_INTFB = 0x0F,
+ SP4_MCP23S17_INTCAPB = 0x11,
+ SP4_MCP23S17_GPIOB = 0x13,
+ SP4_MCP23S17_OLATB = 0x15,
+};
+
+uint8_t sp4_mcp23s17_olata = 0;
+uint8_t sp4_mcp23s17_olatb = 0;
+
+void SP4Mcp23S17Enable(void) {
+ SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE0));
+ digitalWrite(SPro.pin_register_cs, 0);
+}
+
+void SP4Mcp23S17Disable(void) {
+ SPI.endTransaction();
+ digitalWrite(SPro.pin_register_cs, 1);
+}
+
+uint32_t SP4Mcp23S17ReadGpio(void) {
+ // Read 16-bit gpio registers: (gpiob << 8) | gpioa
+ SP4Mcp23S17Enable();
+ SPI.transfer(SHELLY_PRO_4_MCP23S17_ADDRESS | 1);
+ SPI.transfer(SP4_MCP23S17_GPIOA);
+ uint32_t gpio = SPI.transfer(0xFF); // SP4_MCP23S17_GPIOA
+ gpio |= (SPI.transfer(0xFF) << 8); // SP4_MCP23S17_GPIOB
+ SP4Mcp23S17Disable();
+ return gpio;
+}
+
+bool SP4Mcp23S17Read(uint8_t reg, uint8_t *value) {
+ SP4Mcp23S17Enable();
+ SPI.transfer(SHELLY_PRO_4_MCP23S17_ADDRESS | 1);
+ SPI.transfer(reg);
+ *value = SPI.transfer(0xFF);
+ SP4Mcp23S17Disable();
+ return true;
+}
+
+bool SP4Mcp23S17Write(uint8_t reg, uint8_t value) {
+ SP4Mcp23S17Enable();
+ SPI.transfer(SHELLY_PRO_4_MCP23S17_ADDRESS);
+ SPI.transfer(reg);
+ SPI.transfer(value);
+ SP4Mcp23S17Disable();
+ return true;
+}
+
+void SP4Mcp23S17Update(uint8_t pin, bool pin_value, uint8_t reg_addr) {
+ uint8_t bit = pin % 8;
+ uint8_t reg_value = 0;
+ if (reg_addr == SP4_MCP23S17_OLATA) {
+ reg_value = sp4_mcp23s17_olata;
+ } else if (reg_addr == SP4_MCP23S17_OLATB) {
+ reg_value = sp4_mcp23s17_olatb;
+ } else {
+ SP4Mcp23S17Read(reg_addr, ®_value);
+ }
+ if (pin_value) {
+ reg_value |= 1 << bit;
+ } else {
+ reg_value &= ~(1 << bit);
+ }
+ SP4Mcp23S17Write(reg_addr, reg_value);
+ if (reg_addr == SP4_MCP23S17_OLATA) {
+ sp4_mcp23s17_olata = reg_value;
+ } else if (reg_addr == SP4_MCP23S17_OLATB) {
+ sp4_mcp23s17_olatb = reg_value;
+ }
+}
+
+void SP4Mcp23S17Setup(void) {
+ SP4Mcp23S17Write(SP4_MCP23S17_IOCONA, 0b01011000); // Enable INT mirror, Slew rate disabled, HAEN pins for addressing
+ SP4Mcp23S17Write(SP4_MCP23S17_GPINTENA, 0x6F); // Enable interrupt on change
+ SP4Mcp23S17Write(SP4_MCP23S17_GPINTENB, 0x80); // Enable interrupt on change
+
+ // Read current output register state
+ SP4Mcp23S17Read(SP4_MCP23S17_OLATA, &sp4_mcp23s17_olata);
+ SP4Mcp23S17Read(SP4_MCP23S17_OLATB, &sp4_mcp23s17_olatb);
+}
+
+void SP4Mcp23S17PinMode(uint8_t pin, uint8_t flags) {
+ uint8_t iodir = pin < 8 ? SP4_MCP23S17_IODIRA : SP4_MCP23S17_IODIRB;
+ uint8_t gppu = pin < 8 ? SP4_MCP23S17_GPPUA : SP4_MCP23S17_GPPUB;
+ if (flags == INPUT) {
+ SP4Mcp23S17Update(pin, true, iodir);
+ SP4Mcp23S17Update(pin, false, gppu);
+ } else if (flags == (INPUT | PULLUP)) {
+ SP4Mcp23S17Update(pin, true, iodir);
+ SP4Mcp23S17Update(pin, true, gppu);
+ } else if (flags == OUTPUT) {
+ SP4Mcp23S17Update(pin, false, iodir);
+ }
+}
+
+bool SP4Mcp23S17DigitalRead(uint8_t pin) {
+ uint8_t bit = pin % 8;
+ uint8_t reg_addr = pin < 8 ? SP4_MCP23S17_GPIOA : SP4_MCP23S17_GPIOB;
+ uint8_t value = 0;
+ SP4Mcp23S17Read(reg_addr, &value);
+ return value & (1 << bit);
+}
+
+void SP4Mcp23S17DigitalWrite(uint8_t pin, bool value) {
+ uint8_t reg_addr = pin < 8 ? SP4_MCP23S17_OLATA : SP4_MCP23S17_OLATB;
+ SP4Mcp23S17Update(pin, value, reg_addr);
+}
+
+/*********************************************************************************************\
+ * Shelly Pro 4
+\*********************************************************************************************/
+
+const uint8_t sp4_relay_pin[] = { 8, 13, 14, 12 };
+const uint8_t sp4_switch_pin[] = { 6, 1, 0, 15 };
+const uint8_t sp4_button_pin[] = { 5, 2, 3 };
+
+void ShellyPro4Init(void) {
+ /*
+ Shelly Pro 4PM MCP23S17 registers
+ bit 0 = input - Switch3
+ bit 1 = input - Switch2
+ bit 2 = input, pullup, inverted - Button Down
+ bit 3 = input, pullup, inverted - Button OK
+ bit 4 = output - Reset, display, ADE7953
+ bit 5 = input, pullup, inverted - Button Up
+ bit 6 = input - Switch1
+ bit 7
+ bit 8 = output - Relay O1
+ bit 9
+ bit 10
+ bit 11
+ bit 12 = output - Relay O4
+ bit 13 = output - Relay O2
+ bit 14 = output - Relay O3
+ bit 15 = input - Switch4
+ */
+ SP4Mcp23S17Setup();
+
+ for (uint32_t i = 0; i < 4; i++) {
+ SP4Mcp23S17PinMode(sp4_switch_pin[i], INPUT); // Switch1..4
+ SP4Mcp23S17PinMode(sp4_relay_pin[i], OUTPUT); // Relay O1..O4
+ }
+ SPro.switch_offset = -1;
+
+ for (uint32_t i = 0; i < 3; i++) {
+ SP4Mcp23S17PinMode(sp4_button_pin[i], PULLUP); // Button Up, Down, OK
+ }
+ SPro.button_offset = -1;
+
+ SP4Mcp23S17PinMode(4, OUTPUT); // Reset display, ADE7943
+ SP4Mcp23S17DigitalWrite(4, 1);
+
+}
+
+void ShellyPro4Reset(void) {
+ SP4Mcp23S17DigitalWrite(4, 0); // Reset pin display, ADE7953
+ delay(1); // To initiate a hardware reset, this pin must be brought low for a minimum of 10 μs.
+ SP4Mcp23S17DigitalWrite(4, 1);
+}
+
+bool ShellyProAddButton(void) {
+ if (SPro.detected != 4) { return false; }
+ if (SPro.button_offset < 0) { SPro.button_offset = XdrvMailbox.index; }
+ uint32_t index = XdrvMailbox.index - SPro.button_offset;
+ if (index > 2) { return false; }
+ XdrvMailbox.payload = SP4Mcp23S17DigitalRead(sp4_button_pin[index]);
+ return true;
+}
+
+bool ShellyProAddSwitch(void) {
+ if (SPro.detected != 4) { return false; }
+ if (SPro.switch_offset < 0) { SPro.switch_offset = XdrvMailbox.index; }
+ uint32_t index = XdrvMailbox.index - SPro.switch_offset;
+ if (index > 3) { return false; }
+ XdrvMailbox.payload = SP4Mcp23S17DigitalRead(sp4_switch_pin[index]);
+ return true;
+}
+
+void ShellyProUpdateSwitches(void) {
+ if (SPro.detected != 4) { return; }
+ if (digitalRead(SPro.pin_mcp23s17_int)) { return; }
+
+ uint32_t gpio = SP4Mcp23S17ReadGpio();
+
+ AddLog(LOG_LEVEL_DEBUG, PSTR("SHP: Input detected 0x%04X"), gpio);
+
+ // Propagate state
+ uint32_t state;
+ for (uint32_t i = 0; i < 4; i++) {
+ state = (gpio >> sp4_switch_pin[i]) &1;
+ SwitchSetVirtualPinState(SPro.switch_offset +i, state);
+ }
+ for (uint32_t i = 0; i < 3; i++) {
+ state = (gpio >> sp4_button_pin[i]) &1;
+ ButtonSetVirtualPinState(SPro.button_offset +i, state);
+ }
+}
+
+bool ShellyProButton(void) {
+ if (SPro.detected != 4) { return false; }
+
+ uint32_t button_index = XdrvMailbox.index - SPro.button_offset;
+ if (button_index > 2) { return false; } // We only support Up, Down, Ok
+
+ bool result = false;
+ uint32_t button = XdrvMailbox.payload;
+ if ((PRESSED == button) && (NOT_PRESSED == SPro.last_button[button_index])) { // Button pressed
+
+ AddLog(LOG_LEVEL_DEBUG, PSTR("SHP: Button %d pressed"), button_index +1);
+
+ // Do something with the Up,Down,Ok button
+ switch (button_index) {
+ case 0: // Up
+ break;
+ case 1: // Down
+ break;
+ case 2: // Ok
+ break;
+ }
+ result = true; // Disable further button processing
+ }
+ SPro.last_button[button_index] = button;
+ return result;
+}
+
+/*********************************************************************************************\
+ * Shelly Pro 1/2
+\*********************************************************************************************/
+
+void ShellyProUpdate(void) {
+ /*
+ Shelly Pro 1/2/PM 74HC595 register
+ bit 0 = relay/led 1
+ bit 1 = relay/led 2
+ bit 2 = wifi led blue
+ bit 3 = wifi led green
+ bit 4 = wifi led red
+ bit 5 - 7 = nc
+ OE is connected to Gnd with 470 ohm resistor R62 AND a capacitor C81 to 3V3
+ - this inhibits output of signals (also relay state) during power on for a few seconds
+ */
+ uint8_t val = SPro.power | SPro.ledlink;
+ SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE0));
+ SPI.transfer(val); // Write 74HC595 shift register
+ SPI.endTransaction();
+// delayMicroseconds(2); // Wait for SPI clock to stop
+ digitalWrite(SPro.pin_register_cs, 1); // Latch data
+ delayMicroseconds(1); // Shelly 10mS
+ digitalWrite(SPro.pin_register_cs, 0);
+}
+
+/*********************************************************************************************\
+ * Shelly Pro
+\*********************************************************************************************/
+
+void ShellyProPreInit(void) {
+ if ((SPI_MOSI_MISO == TasmotaGlobal.spi_enabled) &&
+ PinUsed(GPIO_SPI_CS) && // 74HC595 rclk / MCP23S17
+ TasmotaGlobal.gpio_optiona.shelly_pro) { // Option_A7
+
+ if (PinUsed(GPIO_SWT1) || PinUsed(GPIO_KEY1)) {
+ SPro.detected = 1; // Shelly Pro 1
+ if (PinUsed(GPIO_SWT1, 1) || PinUsed(GPIO_KEY1, 1)) {
+ SPro.detected = 2; // Shelly Pro 2
+ }
+ SPro.ledlink = 0x18; // Blue led on - set by first call ShellyProPower() - Shelly 1/2
+ }
+ if (SHELLY_PRO_4_PIN_SPI_CS == Pin(GPIO_SPI_CS)) {
+ SPro.detected = 4; // Shelly Pro 4PM (No SWT or KEY)
+ }
+
+ if (SPro.detected) {
+ TasmotaGlobal.devices_present += SPro.detected;
+
+ SPro.pin_register_cs = Pin(GPIO_SPI_CS);
+ pinMode(SPro.pin_register_cs, OUTPUT);
+ // Does nothing if SPI is already initiated (by ADE7953) so no harm done
+ SPI.begin(Pin(GPIO_SPI_CLK), Pin(GPIO_SPI_MISO), Pin(GPIO_SPI_MOSI), -1);
+
+ if (4 == SPro.detected) {
+ digitalWrite(SPro.pin_register_cs, 1);
+ SPro.pin_mcp23s17_int = SHELLY_PRO_4_PIN_MCP23S17_INT; // GPIO35 = MCP23S17 common interrupt
+ pinMode(SPro.pin_mcp23s17_int, INPUT);
+ // Init MCP23S17
+ ShellyPro4Init();
+ } else {
+ digitalWrite(SPro.pin_register_cs, 0);
+ }
+ }
+ }
+}
+
+void ShellyProInit(void) {
+ int pin_lan_reset = SHELLY_PRO_PIN_LAN8720_RESET; // GPIO5 = LAN8720 nRST
+// delay(30); // (t-purstd) This pin must be brought low for a minimum of 25 mS after power on
+ digitalWrite(pin_lan_reset, 0);
+ pinMode(pin_lan_reset, OUTPUT);
+ delay(1); // (t-rstia) This pin must be brought low for a minimum of 100 uS
+ digitalWrite(pin_lan_reset, 1);
+
+ AddLog(LOG_LEVEL_INFO, PSTR("HDW: Shelly Pro %d%s initialized"), SPro.detected, (PinUsed(GPIO_ADE7953_CS))?"PM":"");
+}
+
+void ShellyProPower(void) {
+ if (4 == SPro.detected) {
+
+ AddLog(LOG_LEVEL_DEBUG, PSTR("SHP: Set Power 0x%08X"), XdrvMailbox.index);
+
+ power_t rpower = XdrvMailbox.index;
+ for (uint32_t i = 0; i < 4; i++) {
+ power_t state = rpower &1;
+ SP4Mcp23S17DigitalWrite(sp4_relay_pin[i], state);
+ rpower >>= 1; // Select next power
+ }
+ } else {
+ SPro.power = XdrvMailbox.index &3;
+ ShellyProUpdate();
+ }
+}
+
+void ShellyProUpdateLedLink(uint32_t ledlink) {
+ if (4 == SPro.detected) {
+
+
+ } else {
+ if (ledlink != SPro.ledlink) {
+ SPro.ledlink = ledlink;
+ ShellyProUpdate();
+ }
+ }
+}
+
+void ShellyProLedLink(void) {
+ if (4 == SPro.detected) {
+
+
+ } else {
+ /*
+ bit 2 = blue, 3 = green, 4 = red
+ Shelly Pro documentation
+ - Blue light indicator will be on if in AP mode.
+ - Red light indicator will be on if in STA mode and not connected to a Wi-Fi network.
+ - Yellow light indicator will be on if in STA mode and connected to a Wi-Fi network.
+ - Green light indicator will be on if in STA mode and connected to a Wi-Fi network and to the Shelly Cloud.
+ - The light indicator will be flashing Red/Blue if OTA update is in progress.
+ Tasmota behaviour
+ - Blue light indicator will blink if no wifi or mqtt.
+ - Green light indicator will be on if in STA mode and connected to a Wi-Fi network.
+ */
+ SPro.last_update = TasmotaGlobal.uptime;
+ uint32_t ledlink = 0x1C; // All leds off
+ if (XdrvMailbox.index) {
+ ledlink &= 0xFB; // Blue blinks if wifi/mqtt lost
+ }
+ else if (!TasmotaGlobal.global_state.wifi_down) {
+ ledlink &= 0xF7; // Green On
+ }
+ ShellyProUpdateLedLink(ledlink);
+ }
+}
+
+void ShellyProLedLinkWifiOff(void) {
+ if (4 == SPro.detected) {
+
+
+ } else {
+ /*
+ bit 2 = blue, 3 = green, 4 = red
+ - Green light indicator will be on if in STA mode and connected to a Wi-Fi network.
+ */
+ if (SPro.last_update +1 < TasmotaGlobal.uptime) {
+ ShellyProUpdateLedLink((TasmotaGlobal.global_state.wifi_down) ? 0x1C : 0x14); // Green off if wifi OFF
+ }
+ }
+}
+
+/*********************************************************************************************\
+ * Interface
+\*********************************************************************************************/
+
+bool Xdrv88(uint32_t function) {
+ bool result = false;
+
+ if (FUNC_MODULE_INIT == function) {
+ ShellyProPreInit();
+ } else if (SPro.detected) {
+ switch (function) {
+ case FUNC_EVERY_50_MSECOND:
+ ShellyProUpdateSwitches();
+ break;
+ case FUNC_BUTTON_PRESSED:
+ result = ShellyProButton();
+ break;
+ case FUNC_EVERY_SECOND:
+ ShellyProLedLinkWifiOff();
+ break;
+ case FUNC_SET_DEVICE_POWER:
+ ShellyProPower();
+ return true;
+ case FUNC_LED_LINK:
+ ShellyProLedLink();
+ break;
+ case FUNC_INIT:
+ ShellyProInit();
+ break;
+ case FUNC_ADD_BUTTON:
+ result = ShellyProAddButton();
+ break;
+ case FUNC_ADD_SWITCH:
+ result = ShellyProAddSwitch();
+ break;
+ }
+ }
+ return result;
+}
+
+#endif // USE_SHELLY_PRO
+#endif // USE_SPI
+#endif // ESP32
diff --git a/tasmota/tasmota_xnrg_energy/xnrg_07_ade7953.ino b/tasmota/tasmota_xnrg_energy/xnrg_07_ade7953.ino
index c5f282bef..380ef16e8 100644
--- a/tasmota/tasmota_xnrg_energy/xnrg_07_ade7953.ino
+++ b/tasmota/tasmota_xnrg_energy/xnrg_07_ade7953.ino
@@ -36,21 +36,21 @@
* Based on datasheet from https://www.analog.com/en/products/ade7953.html
*
* Model differences:
- * Function Model1 Model2 Model3 Model4 Model5 Remark
- * ------------------------------ ------- ------- ------- ------ ------ -------------------------------------------------
- * Shelly 2.5 EM Plus2PM Pro1PM Pro2PM
- * Processor ESP8266 ESP8266 ESP32 ESP32 ESP32
- * Interface I2C I2C I2C SPI SPI Interface type used
- * Number of ADE9753 chips 1 1 1 1 2 Count of ADE9753 chips
- * ADE9753 IRQ 1 2 3 4 5 Index defines model number
- * Current measurement device shunt CT shunt shunt shunt CT = Current Transformer
- * Common voltage Yes Yes Yes No No Show common voltage in GUI/JSON
- * Common frequency Yes Yes Yes No No Show common frequency in GUI/JSON
- * Swapped channel A/B Yes No No No No Defined by hardware design - Fixed by Tasmota
- * Support Export Active No Yes No No No Only EM supports correct negative value detection
- * Show negative (reactive) power No Yes No No No Only EM supports correct negative value detection
- * Default phase calibration 0 200 0 0 0 CT needs different phase calibration than shunts
- * Default reset pin on ESP8266 - 16 - - - Legacy support. Replaced by GPIO ADE7953RST
+ * Function Model1 Model2 Model3 Model4 Model5 Model6 Remark
+ * ------------------------------ ------- ------- ------- ------ ------ ------ -------------------------------------------------
+ * Shelly 2.5 EM Plus2PM Pro1PM Pro2PM Pro4PM
+ * Processor ESP8266 ESP8266 ESP32 ESP32 ESP32 ESP32
+ * Interface I2C I2C I2C SPI SPI SPI Interface type used
+ * Number of ADE9753 chips 1 1 1 1 2 2 Count of ADE9753 chips
+ * ADE9753 IRQ 1 2 3 4 5 6 Index defines model number
+ * Current measurement device shunt CT shunt shunt shunt shunt CT = Current Transformer
+ * Common voltage Yes Yes Yes No No No Show common voltage in GUI/JSON
+ * Common frequency Yes Yes Yes No No No Show common frequency in GUI/JSON
+ * Swapped channel A/B Yes No No No No No Defined by hardware design - Fixed by Tasmota
+ * Support Export Active No Yes No No No No Only EM supports correct negative value detection
+ * Show negative (reactive) power No Yes No No No No Only EM supports correct negative value detection
+ * Default phase calibration 0 200 0 0 0 0 CT needs different phase calibration than shunts
+ * Default reset pin on ESP8266 - 16 - - - - Legacy support. Replaced by GPIO ADE7953RST
*
* I2C Address: 0x38
*********************************************************************************************
@@ -82,7 +82,7 @@
#define ADE7953_PHCAL_DEFAULT 0 // = range -383 to 383 - Default phase calibration for Shunts
#define ADE7953_PHCAL_DEFAULT_CT 200 // = range -383 to 383 - Default phase calibration for Current Transformers (Shelly EM)
-enum Ade7953Models { ADE7953_SHELLY_25, ADE7953_SHELLY_EM, ADE7953_SHELLY_PLUS_2PM, ADE7953_SHELLY_PRO_1PM, ADE7953_SHELLY_PRO_2PM };
+enum Ade7953Models { ADE7953_SHELLY_25, ADE7953_SHELLY_EM, ADE7953_SHELLY_PLUS_2PM, ADE7953_SHELLY_PRO_1PM, ADE7953_SHELLY_PRO_2PM, ADE7953_SHELLY_PRO_4PM };
enum Ade7953_8BitRegisters {
// Register Name Addres R/W Bt Ty Default Description
@@ -225,7 +225,7 @@ struct Ade7953 {
uint32_t active_power[2] = { 0, 0 };
int32_t calib_data[2][ADE7953_CALIBREGS];
uint8_t init_step = 0;
- uint8_t model = 0; // 0 = Shelly 2.5, 1 = Shelly EM, 2 = Shelly Plus 2PM, 3 = Shelly Pro 1PM, 4 = Shelly Pro 2PM
+ uint8_t model = 0; // 0 = Shelly 2.5, 1 = Shelly EM, 2 = Shelly Plus 2PM, 3 = Shelly Pro 1PM, 4 = Shelly Pro 2PM, 5 = Shelly Pro 4PM
uint8_t cs_index;
#ifdef USE_ESP32_SPI
SPISettings spi_settings;
@@ -233,6 +233,8 @@ struct Ade7953 {
#endif // USE_ESP32_SPI
} Ade7953;
+/*********************************************************************************************/
+
int Ade7953RegSize(uint16_t reg) {
int size = 0;
switch ((reg >> 8) & 0x0F) {
@@ -250,6 +252,18 @@ int Ade7953RegSize(uint16_t reg) {
return size;
}
+void Ade7953SpiEnable(void) {
+ digitalWrite(Ade7953.pin_cs[Ade7953.cs_index], 0);
+ delayMicroseconds(1); // CS 1uS to SCLK edge
+ SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE0)); // Set up SPI at 1MHz, MSB first, Capture at rising edge
+}
+
+void Ade7953SpiDisable(void) {
+ SPI.endTransaction();
+ delayMicroseconds(2); // CS high 1.2uS after SCLK edge (when writing to COMM_LOCK bit)
+ digitalWrite(Ade7953.pin_cs[Ade7953.cs_index], 1);
+}
+
void Ade7953Write(uint16_t reg, uint32_t val) {
int size = Ade7953RegSize(reg);
if (size) {
@@ -258,6 +272,7 @@ void Ade7953Write(uint16_t reg, uint32_t val) {
#ifdef USE_ESP32_SPI
if (Ade7953.pin_cs[0] >= 0) {
+/*
digitalWrite(Ade7953.pin_cs[Ade7953.cs_index], 0);
delayMicroseconds(1); // CS 1uS to SCLK edge
SPI.beginTransaction(Ade7953.spi_settings);
@@ -269,6 +284,15 @@ void Ade7953Write(uint16_t reg, uint32_t val) {
SPI.endTransaction();
delayMicroseconds(2); // CS high 1.2uS after SCLK edge (when writing to COMM_LOCK bit)
digitalWrite(Ade7953.pin_cs[Ade7953.cs_index], 1);
+*/
+ Ade7953SpiEnable();
+ SPI.transfer16(reg);
+ SPI.transfer(0x00); // Write
+ while (size--) {
+ SPI.transfer((val >> (8 * size)) & 0xFF); // Write data, MSB first
+ }
+ Ade7953SpiDisable();
+
} else {
#endif // USE_ESP32_SPI
Wire.beginTransmission(ADE7953_ADDR);
@@ -292,6 +316,7 @@ int32_t Ade7953Read(uint16_t reg) {
if (size) {
#ifdef USE_ESP32_SPI
if (Ade7953.pin_cs[0] >= 0) {
+/*
digitalWrite(Ade7953.pin_cs[Ade7953.cs_index], 0);
delayMicroseconds(1); // CS 1uS to SCLK edge
SPI.beginTransaction(Ade7953.spi_settings);
@@ -302,6 +327,15 @@ int32_t Ade7953Read(uint16_t reg) {
}
SPI.endTransaction();
digitalWrite(Ade7953.pin_cs[Ade7953.cs_index], 1);
+*/
+ Ade7953SpiEnable();
+ SPI.transfer16(reg);
+ SPI.transfer(0x80); // Read
+ while (size--) {
+ response = response << 8 | SPI.transfer(0xFF); // receive DATA (MSB first)
+ }
+ Ade7953SpiDisable();
+
} else {
#endif // USE_ESP32_SPI
Wire.beginTransmission(ADE7953_ADDR);
@@ -449,9 +483,16 @@ void Ade7953GetData(void) {
#ifdef USE_ESP32_SPI
}
#endif // USE_ESP32_SPI
- AddLog(LOG_LEVEL_DEBUG_MORE, PSTR("ADE: ACCMODE 0x%06X, VRMS %d, %d, Period %d, %d, IRMS %d, %d, WATT %d, %d, VA %d, %d, VAR %d, %d"),
- acc_mode, reg[0][4], reg[1][4], reg[0][5], reg[1][5],
- reg[0][0], reg[1][0], reg[0][1], reg[1][1], reg[0][2], reg[1][2], reg[0][3], reg[1][3]);
+
+#ifdef USE_ESP32_SPI
+ if (1 == Energy.phase_count) {
+ AddLog(LOG_LEVEL_DEBUG_MORE, PSTR("ADE: ACCMODE 0x%06X, VRMS %d, Period %d, IRMS %d, WATT %d, VA %d, VAR %d"),
+ acc_mode, reg[0][4], reg[0][5], reg[0][0], reg[0][1], reg[0][2], reg[0][3]);
+ } else
+#endif // USE_ESP32_SPI
+ AddLog(LOG_LEVEL_DEBUG_MORE, PSTR("ADE: ACCMODE 0x%06X, VRMS %d, %d, Period %d, %d, IRMS %d, %d, WATT %d, %d, VA %d, %d, VAR %d, %d"),
+ acc_mode, reg[0][4], reg[1][4], reg[0][5], reg[1][5],
+ reg[0][0], reg[1][0], reg[0][1], reg[1][1], reg[0][2], reg[1][2], reg[0][3], reg[1][3]);
// If the device is initializing, we read the energy registers to reset them, but don't report the values as the first read may be inaccurate
if (Ade7953.init_step) { return; }
@@ -459,7 +500,7 @@ void Ade7953GetData(void) {
uint32_t apparent_power[2] = { 0, 0 };
uint32_t reactive_power[2] = { 0, 0 };
- for (uint32_t channel = 0; channel < 2; channel++) {
+ for (uint32_t channel = 0; channel < Energy.phase_count; channel++) {
Ade7953.voltage_rms[channel] = reg[channel][4];
Ade7953.current_rms[channel] = reg[channel][0];
if (Ade7953.current_rms[channel] < 2000) { // No load threshold (20mA)
@@ -477,7 +518,7 @@ void Ade7953GetData(void) {
if (Energy.power_on) { // Powered on
float divider;
- for (uint32_t channel = 0; channel < 2; channel++) {
+ for (uint32_t channel = 0; channel < Energy.phase_count; channel++) {
Energy.data_valid[channel] = 0;
float power_calibration = (float)EnergyGetCalibration(channel, ENERGY_POWER_CALIBRATION) / 10;
@@ -649,6 +690,11 @@ void Ade7953DrvInit(void) {
pinMode(pin_reset, INPUT);
}
}
+#ifdef USE_SHELLY_PRO
+ if (Ade7953.model == ADE7953_SHELLY_PRO_4PM) {
+ ShellyPro4Reset();
+ }
+#endif // USE_SHELLY_PRO
delay(100); // Need 100mS to init ADE7953
#ifdef USE_ESP32_SPI