Add options for inverted switches and default values.

This commit is contained in:
Hermann Kraus 2020-11-01 18:08:30 +01:00
parent fe3fb622ee
commit b725d66ee3
2 changed files with 27 additions and 6 deletions

View File

@ -21,7 +21,7 @@ void registerUsermods()
## Define pins
Add a define for MQTTSWITCHPINS to platformio_override.ini.
The following example defines 3 switches connected to the GPIO pins 13, 0 and 2:
The following example defines 3 switches connected to the GPIO pins 13, 5 and 2:
```
[env:livingroom]
@ -34,9 +34,13 @@ build_flags = ${common.build_flags_esp8266}
-D RLYPIN=12
-D RLYMDE=1
-D STATUSPIN=15
-D MQTTSWITCHPINS="13, 0, 2"
-D MQTTSWITCHPINS="13, 5, 2"
```
Pins can be inverted by setting `MQTTSWITCHINVERT`. For example `-D MQTTSWITCHINVERT="false, false, true"` would invert the switch on pin 2 in the previous example.
The default state after booting before any MQTT message can be set by `MQTTSWITCHDEFAULTS`. For example `-D MQTTSWITCHDEFAULTS="ON, OFF, OFF"` would power on the switch on pin 13 and power off switches on pins 5 and 2.
## MQTT topics
This usermod listens on `[mqttDeviceTopic]/switch/0/set` (where 0 is replaced with the index of the switch) for commands. Anything starting with `ON` turns on the switch, everything else turns it off.
Feedback about the current state is provided at `[mqttDeviceTopic]/switch/0/state`.

View File

@ -6,14 +6,31 @@
#endif
#ifndef MQTTSWITCHPINS
#error "Please define MQTTSWITCHPINS in platformio_override.ini. e.g. -D MQTTSWITCHPINS="12, 0, 2" "
// The following define helps Eclipse's C++ parser but is never used in production due to the #error statement on the line before
#define MQTTSWITCHPINS 12, 0, 2
//#error "Please define MQTTSWITCHPINS in platformio_override.ini. e.g. -D MQTTSWITCHPINS="12, 0, 2" "
#endif
// Default behavior: All outputs active high
#ifndef MQTTSWITCHINVERT
#define MQTTSWITCHINVERT
#endif
static const uint8_t switchPins[] = {MQTTSWITCHPINS};
// Default behavior: All outputs off
#ifndef MQTTSWITCHDEFAULTS
#define MQTTSWITCHDEFAULTS
#endif
static const uint8_t switchPins[] = { MQTTSWITCHPINS };
//This is a hack to get the number of pins defined by the user
#define NUM_SWITCH_PINS (sizeof(switchPins))
static const bool switchInvert[NUM_SWITCH_PINS] = { MQTTSWITCHINVERT};
//Make settings in config file more readable
#define ON 1
#define OFF 0
static const bool switchDefaults[NUM_SWITCH_PINS] = { MQTTSWITCHDEFAULTS};
#undef ON
#undef OFF
class UsermodMqttSwitch: public Usermod
{
@ -30,8 +47,8 @@ public:
void setup()
{
for (int pinNr = 0; pinNr < NUM_SWITCH_PINS; pinNr++) {
setState(pinNr, switchDefaults[pinNr]);
pinMode(switchPins[pinNr], OUTPUT);
setState(pinNr, false);
}
}
@ -64,7 +81,7 @@ public:
if (pinNr > NUM_SWITCH_PINS)
return;
switchState[pinNr] = active;
digitalWrite((char) switchPins[pinNr], (char) active);
digitalWrite((char) switchPins[pinNr], (char) (switchInvert[pinNr] ? !active : active));
updateState(pinNr);
}
};