Destroyed Rules Examples circa 20190507 (markdown)

Michael Ingraham 2019-05-16 07:53:29 -04:00
parent e0a6c7ebc7
commit d175300535
1 changed files with 0 additions and 929 deletions

@ -1,929 +0,0 @@
# Examples
The following examples will explain some use cases.
[1. Use long press action on a switch](Rules#1-use-long-press-action-on-a-switch)
[2. Execute any MQTT message when a button is pressed](Rules#2-execute-any-mqtt-message-when-a-button-is-pressed)
[3. Execute Several Commands when a Timer Expires](Rules#3-execute-several-commands-when-a-timer-expires)
[4. Usage of one-shot (once)](Rules#4-usage-of-one-shot-once)
[5. Use of Variables and tele-](Rules#5-use-of-variables-and-tele-)
[6. Use a Potentiometer](Rules#6-use-a-potentiometer)
[7. Setting Variables](Rules#7-setting-variables)
[8. Arithmetic Commands to be used with VARs](Rules#8-arithmetic-commands-to-be-used-with-vars)
[8.a. Sending the value of a sensor to MQTT only when a delta is reached](Rules#8a-sending-the-value-of-a-sensor-to-mqtt-only-when-a-delta-is-reached)
[8.b. Adjust the value of a sensor and send it by MQTT](Rules#8b-adjust-the-value-of-a-sensor-and-send-it-by-mqtt)
[9. Simple Thermostat Example](Rules#9-simple-thermostat-example)
[10. Simple Staircase Timer](Rules#10-simple-staircase-timer)
[10.a. Advanced PIR rules for Staircase](Rules#10a-advanced-pir-rules-for-staircase)
[11. Energy Saving Smart Switch](Rules#11-energy-saving-smart-switch)
[12. Controlling Timers Enable from a switch](Rules#12-controlling-timers-enable-from-a-switch)
[13. Toggle a Relay only when holding the button for 2 seconds](Rules#13-toggle-a-relay-only-when-holding-the-button-for-2-seconds)
[14. Rule to Make Sure Light is on at Night](Rules#14-rule-to-make-sure-light-is-on-at-night)
[15. Rule to enable a PIR Sensor only at night](Rules#15-rule-to-enable-a-pir-sensor-only-at-night)
[16. Using an external button with single press - double press and hold](Rules#16-using-an-external-button-with-single-press---double-press-and-hold)
[17. Rule to enable or disable doorbell relay with HTTP call](Rules#17-rule-to-enable-or-disable-doorbell-relay-with-http-call)
[18. Rule to force automatic reconnection to MQTT server via SD DNS](Rules#18-rule-to-force-automatic-reconnection-to-mqtt-server-via-sd-dns)
[19. Rule to change distance to percentage](Rules#19-rule-to-change-distance-to-percentage)
[20. Rules to distinguish Switch1 and Switch2 without the use of Relay1 and Relay2](Rules/#20-rules-to-distinguish-switch1-and-switch2-without-the-use-of-relay1-and-relay2)
[21. Rule for receiving state of intercom doorbell (or anything that triggers your SWITCHX more than one times).](Rules#21-rule-for-receiving-state-of-intercom-doorbell-or-anything-that-triggers-your-switchx-more-than-one-times)
[22. Invoking rules using clock timer to control a luminance-triggered switch only in mornings](Rules#22-invoking-rules-using-clock-timer-to-control-a-luminance-triggered-switch-only-in-mornings)
[23. Prevent Wemos D1 mini load overcurrent](Rules#1-prevent-wemos-d1-mini-load-overcurrent)
[BackToTop](Rules#summary)
------------------------------------------------------------------------------
#### 1. Use long press action on a switch
Activate long press action with `Switchmode 5` first and shorten long press time to 2 seconds.
Long pressing on switch1 sends `POWER TOGGLE` command to the `sonoff02` device
```
SwitchMode 5
SetOption32 20
Rule on switch1#state=3 do cmnd/sonoff02/POWER 2 endon
Rule 1
```
------------------------------------------------------------------------------
#### 2. Execute any MQTT message when a button is pressed
When a button is pressed the user has the possibility to send a MQTT message based on FullTopic and ButtonTopic. This MQTT message is going to be received by the MQTT Broker and if there is any other device(s) subscripted to that Topic, it will receive also that message. So this approach can be used for sending messages/commands to MQTT Broker to Home Automation System, and/or sending messages/commands to MQTT Broker to other device(s).
A problem with this solution is that on a Sonoff 4CH all four buttons will be sending the same MQTT topic using only a different Power index number like ``cmnd/ButtonTopic/power3 toggle``.
By using a rule a single button can now send any MQTT message allowing much more flexibility.
Hardware
- Sonoff 4CH
Software
- Sonoff-Tasmota with define USE_RULES enabled
- Disable ButtonTopic as it overrides rules for buttons: ``ButtonTopic 0``
Rule
- ``Rule on button1#state do publish cmnd/ring2/power %value% endon on button2#state do publish cmnd/strip1/power %value% endon``
(You will likely need to enable this rule if it's the first time you've used them)
"Rule1 on".
Result
- When button 1 is pressed the rule kicks in and sends a MQTT message substituting variable ``%value%`` with the button state like ``cmnd/ring2/power 2``. When button 2 is pressed a MQTT message like ``cmnd/strip1/power 2`` will be sent.
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 3. Execute several commands when a Timer expires
The default Timer1..16 functionality allows for controlling one output to either off, on, toggle or blink. When rules are enabled the blink option will be replaced by rule functionality allowing much more flexibility.
Hardware
- Sonoff 4CH
Software
- Sonoff-Tasmota with define USE_RULES enabled
- Configure timer5 for rule execution when activated: ``timer5 {"Arm":1,"Mode":0,"Time":"16:00","Days":"1111111","Repeat":1,"Action":3}``
Rule
- ``on clock#Timer=5 do backlog power2 on;power1 off;power3 2 endon``
Result
- When the timer expires the rule kicks in and set Power1 to OFF, Power2 to ON and Toggles Power3
If you want to have blink functionality define a rule like ``on clock#Timer=5 do power 3 endon``
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 4. Usage of one-shot (once)
The rule command once option provides the possibility to trigger only once on a slow change while the change is still within the bounds of the test.
Rule
- ``on ENERGY#Current>0.100 do publish tool/tablesaw/power 1 endon on ENERGY#Current<0.100 do publish tool/tablesaw/power 0 endon``
This creates a rule to publish MQTT commands whenever a Sonoff POW has current passing through it. Used as is, it will publish MQTT commands repeatedly, over and over, while current is >0.100 ... but, executing another command:
``Rule 5``
Now the MQTT message will be sent once, and only once, while the condition is met. This is perfect for thermostat on/off depending on temperature, bathroom extractor fan on/off depending on humidity, workshop dust collector on/off depending on whether some dust-producing machine is running.
It meets the 'hard thermostat' requests that have been common.
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 5. Use of variables and tele-
Using variables allows for storing sensor results to be used in composing a single HA message like used with Domoticz. To prevent flooding Domoticz with messages we only want to send a message at TelePeriod time. This is achieved by prefixing the SensorName with the label ``tele-``. This example will use a variable storing the temperature to be used together with humidity in one Domoticz MQTT message.
Hardware
- Sonoff TH or Wemos D1 mini
- AM2301 Temperature and Humidity sensor
Software
- Sonoff-Tasmota with define USE_RULES enabled
- Home Automation tool Domoticz configured with a virtual sensor Temp+Hum using Idx 134
Rule
- ``on tele-am2301-12#temperature do var1 %value% endon on tele-am2301-12#humidity do publish domoticz/in {"idx":134,"svalue":"%var1%;%value%;1"} endon``
Result
- As a result of the ``tele-`` prefix the rules will be checked at TelePeriod time for sensor AM2301-12 Temperature and Humidity. The first rule will use the Temperature stored in ``%value%`` and save it in ``%var1%`` for future use. The second rule will use the Humidity stored in ``%value%`` and the Temperature stored in ``%var1%`` to compose a single MQTT message suitable for Domoticz.
Clever Dickies now finally have a way to send Temperatures from multiple DS18B20 to Domoticz.
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 6. Use a potentiometer
Connecting a potentiometer to the Analog A0 input and a rule can be used to control the dimmer state of any device.
Hardware
- Wemos D1 mini
- Potentiometer of 2k2 connected to Gnd, A0 and 3V3
- WS2812 LED
Software
- Sonoff-Tasmota with define USE_RULES enabled
Rule
- ``on analog#a0div10 do dimmer %value% endon``
Result
- Turning the potentiometer the voltage on the analog input will change resulting in a value change of 0 (Off) to 100 for the trigger. Using this value to control the dimmer of the WS2812 will control the brightness of the led(s)
Rule
- ``on analog#a0div10 do publish cmnd/grouplight/dimmer %value% endon``
Result
- This time all lights configured with GroupTopic ``grouplight`` will change their brightness according to the potentiometer position.
NOTE: You might want to execute command ``SaveData 2`` to reduce flash writes ;-)
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 7. Setting variables
Demonstrate the use of variables. Make sure to execute commands ``Rule 4``(Disable one-shot detection) first when trying the following example.
* Set a variable
rule needed:
``on event#setvar1 do var1 %value% endon``
command:
``event setvar1=1``
* View a variable
rule needed:
``on event#getvar1 do var1 endon``
command:
``event getvar1``
* Toggle a variable
rules needed:
``on event#togglevar1 do event toggling1=%var1% endon``
``on event#toggling1<1 do event setvar1=1 endon``
``on event#toggling1>0 do event setvar1=0 endon``
``on event#setvar1 do var1 %value% endon``
command:
``event togglevar1``
* Show Messages:
rule needed:
``on event#message do publish stat/[topic]/log %value% endon``
command:
``event message=INIT``
* All event commands can be executed from:
console: ``event anyname=number``
mqtt: ``cmnd/[topic]/event anyname=number``
Everything together:
``Rule on event#togglevar1 do event toggling1=%var1% endon on event#toggling1<1 do event setvar1=1 endon on event#toggling1>0 do event setvar1=0 endon on event#setvar1 do var1 %value% endon on event#getvar1 do var1 endon on event#message do publish stat/sonoff/log %value% endon``
**NOTE**
Note that the following won't work:
``Rule on event#setvar1 do backlog var1 %value%; power1 %var1% endon``
Well at least not as you probably would expect. The var1 value used by the power1 command will be the value present before the backlog command is executed. This is so, because the rule will replace %var1% BEFORE the backlog commands are put in the backlog-log.
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 8. Arithmetic commands to be used with VARs
* ADD
`ADD1` to `ADD5`: Add a value to `VARx`
Syntax: `ADDx value`
Usage: `ADD1 15`
Result: `VAR1 = VAR1 + 15`
* SUBTRACT
`SUB1 `to `SUB5`: Subtract a value from `VARx`
Syntax: `SUBx value`
Usage: `SUB1 15`
Result: `VAR1 = VAR1 - 15`
* MULTIPLY
`MULT1 `to `MULT5`: Multiply a value to `VARx`
Syntax: `MULTx value`
Usage: `MULT1 15`
Result: `VAR1 = VAR1 * 15`
* SCALE A VALUE
`SCALE1 `to `SCALE5`: Scale a value from a low and high limit to another low and high limit and store it in `VARx` (directly equivalent to MAP arduino command)
Syntax: `SCALEx value, fromLow, fromHigh, toLow, toHigh`
where,
_value_: the number to scale
_fromLow_: the lower bound of the values current range
_fromHigh_: the upper bound of the values current range
_toLow_: the lower bound of the values target range
_toHigh_: the upper bound of the values target range
_(omitted values are taken as zero)_
Usage: `SCALE1 15, 0, 100, 0, 1000`
Result: `VAR1 = 150`
#### 8.a. Sending the value of a sensor to MQTT only when a delta is reached
When it is needed that a sensor value is only sent when it changes a delta, can be solved applying the following rule example:
```
Rule
on SI7021#temperature>%var1% do backlog var1 %value%; publish stat/sonoff/temp %value%; var2 %value%; add1 2; sub2 2 endon
on SI7021#temperature<%var2% do backlog var2 %value%; publish stat/sonoff/temp %value%; var1 %value%; add1 2; sub2 2 endon
```
#### 8.b. Adjust the value of a sensor and send it by MQTT
This example adds 2 degrees to the measured temperature and then sends that value to a MQTT topic.
```
Rule
on tele-SI7021#temperature do backlog var1 %value%; add1 2; event sendtemp endon
on event#sendtemp do publish stat/sonoff/temp %var1% endon
```
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 9. Simple Thermostat Example
As example, to be used on a Sonoff TH10 with Sensor Si7021
This example turn on and off an output based on the temperature value and the upper set point and the lower set point.
It waits until is enabled by pressing the button or by mqtt message 1 to mem1. This value is remembered. So if power cycle occurs, will resume operation.
The set point values can be changed on the fly by mqtt or console commands
If the Temperature sensor disconnects, the outputs will shutdown until the sensor is back again and will resume operation.
When the device is power up, the thermostat also waits until the sensor value to resume operation.
Inital Config:
* Available physical button as **switch1**
* **Relay1** will be used the controller
* **Rules** must be used to control Relay so the pushbutton must only control **switch1** and not directly control the relay - For this we use SwitchMode1 3 as described below and create the necessary rules because the pushbutton control of the relay is only disabled when the rules are in place.
Inital config on console:
* `SwitchMode1 3` <- Use the switch1 as pushbutton (It will allow us to disable the link between the button and the relay by inserting a rule to dictate what the pushbutton will do - **NOTE: Until rules are created the pushbutton will still control the relay!**)
* `Rule 1 ` <- turn on rules
* `Rule 4` <- turn off one-shot rule
* `TelePeriod 60` <- check temp every minute
* `SetOption26 1` <- use power1 on mqtt messages
* `SetOption0 0` <- dont save relay status on eeprom
* `poweronstate 0` <- start all relays off
* `mem1 0` <- thermostat status: 0-off 1-enabled - View or set by MQTT cmnd/sonoff/mem1
* `mem2 25` <- setpoint Temp upper limit - View or set by MQTT cmnd/sonoff/mem2
* `mem3 23` <- setpoint Temp lower limit - View or set by MQTT cmnd/sonoff/mem3
* `var1 0 ` <- thermostat actual status: 1-OK 0-NOT READY - View by MQTT cmnd/sonoff/var1
Rules:
On boot start a watch dog timer to check temp sensor connection.
`Rule on system#boot do RuleTimer1 70 endon`
An available button is configured as switch to set thermostat ON or OFF
`on switch1#state do backlog event toggling1=%mem1% endon`
`on event#toggling1=0 do mem 1 endon`
`on event#toggling1=1 do mem 0 endon`
Check temp sensor connection. If fails, set to off and turn off thermostat. Also continue checking
`on Rules#Timer=1 do backlog var1 0; RuleTimer1 70; power1 0 endon`
Resets checking timer if temperature is connected
`on tele-SI7021#temperature do backlog var1 1; RuleTimer1 30; event ctrl_ready=1; event temp_demand=%value% endon`
Thermostat control - upper limit and lower limit and enabled
`on on event#ctrl_ready>%mem1% do var1 0 endon on event#temp_demand>%mem2% do power1 0 endon on event#temp_demand<%mem3% do power1 %var1% endon`
Thermostat can be turned On by:
* pushing button
* by command on local console: mem1 1
* by command on any other console: publish cmnd/sonoff/mem1 1
* or MQTT at: cmnd/sonoff/mem1 1
Thermostat can be turned Off by:
* pushing button
* by command on local console: mem1 0
* by command on any other console: publish cmnd/sonoff/mem1 0
* or MQTT at: cmnd/sonoff/mem1 0
To get the status:
* `mem1` <- thermostat status: 0-off 1-enabled - View or set by MQTT cmnd/sonoff/mem1
* `mem2` <- setpoint Temp upper limit - View or set by MQTT cmnd/sonoff/mem2
* `mem3` <- setpoint Temp lower limit - View or set by MQTT cmnd/sonoff/mem3
* `var1` <- thermostat actual status: 1-OK 0-NOT READY - View by MQTT cmnd/sonoff/var1
Everything together:
INITIAL CONFIG: (To note RuleTimer1 must be greater that TelePeriod for expected results)
`backlog SwitchMode1 3; Rule 1; Rule 4; TelePeriod 60; SetOption26 1; SetOption0 0; poweronstate 0; mem1 0; mem2 25; mem3 23; var1 0`
RULES:
```
Rule1 on system#boot do RuleTimer1 70 endon on Switch1#State do event toggling1=%mem1% endon on event#toggling1=0 do mem 1 endon on event#toggling1=1 do mem 0 endon on Rules#Timer=1 do backlog var1 0; RuleTimer1 70; power1 0 endon on tele-SI7021#temperature do backlog var1 1; RuleTimer1 70; event ctrl_ready=1; event temp_demand=%value% endon on event#ctrl_ready>%mem1% do var1 0 endon on event#temp_demand>%mem2% do power1 0 endon on event#temp_demand<%mem3% do power1 %var1% endon
```
EXAMPLE RULES WITHOUT TEMP SENSOR TO TEST THE THERMOSTAT RULES
```
Rule on system#boot do RuleTimer1 70 endon on Switch1#State do event toggling1=%mem1% endon on event#toggling1=0 do mem 1 endon on event#toggling1=1 do mem 0 endon on Rules#Timer=1 do backlog var1 0; RuleTimer1 70; power1 0 endon on event#temp do backlog var1 1; RuleTimer1 70; event ctrl_ready=1; event temp_demand=%value% endon on event#ctrl_ready>%mem1% do var1 0 endon on event#temp_demand>%mem2% do power1 0 endon on event#temp_demand<%mem3% do power1 %var1% endon
```
TESTS:
* Push the button1. The thermostat changes to ENABLED (mem1=1)
* on console: event temp=20 (now the system receives like a tele message from temperature sensor) and will turn on the relay1 (to heat)
* on console: event temp=26 (the thermostat turn off the heater)
* on console: event temp=22 (the thermostat turn on the heater)
* wait more than a minute without using the event temp and the thermostat will turn off as there is no temperature value (like a sensor error or disconnection)
* will resume when using again the event temp
* console mem1 0, DISABLED, console mem1 1, ENABLED
TIMERS:
* With the above the timers can be used to control mem1 and add a schedule to when the thermostat will be enabled
`Rule2 on Clock#Timer=1 do mem 1 endon on Clock#Timer=2 do mem 0`
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 10. Simple Staircase Timer
**Rule:**
`Rule1 on button1#state do backlog power1 %value%; RuleTimer1 600 endon on Rules#Timer=1 do power1 off endon`
**Result:**
` on button1#state do backlog power1 %value%;`
* On Button press the Light in the Staircase will switch on/off
` RuleTimer1 600 endon`
* Additionally RuleTimer1 will begin to countdown 10 minutes
` on Rules#Timer=1 do power1 off endon`
* After the RuleTimer1 expires the light will be switched off (if you forgot to switch it off)
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 10.a. Advanced PIR rules for Staircase
Example works fine on a Wemos D1 Mini. Used as night light with motion sensor or as ambient light on floor or kitchen.
I connect an LED Strip WS2812 on D1 and the PIR on D2 and a LDR on A0 (voltage divider with 10k ohm resistor)
PIR example: HR-SC501
**The Setting are:**
18 Generic
D1 WS2812
D2 Switch1
LDR on Wemos A0 (activated in user_config.h)
and i type the following rules in the konsole:
**Rules:**
`SwitchMode1 1`
`Rule1 on analog#a0<400 do backlog Rule3 0; Rule2 1 endon on analog#a0>500 do backlog Rule2 0; Rule3 1 endon`
`Rule2 on switch1#state do backlog power1 1; RuleTimer1 30 endon on Rules#Timer=1 do power1 off endon`
`Rule3 on switch1#state do power1 off endon`
`Rule1 1` (activate Rule1)
`Rule1 6` (one shot detection)
optional
`Rule2 4`
`Rule3 4`
**Result:**
`on analog#a0>400`
disable Rule3 and activate Rule2
`on analog#a0>500`
disable Rule2 and activate Rule3
* Rule2 activates the LEDs for RuleTimer1 30 seconds on each trigger from PIR the RuleTimer start again.
`on Rules#Timer=1 do power1 off`
The LEDs turn off after the RuleTimer expires
* Rule3 is active on daylight and pipe the PIR signal in a power1 off signal. The LEDs stay off.
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 11. Energy Saving Smart Switch
Example of a switch controlling a light with a condition of a required amount of lux.
When the switch is on, the light will turn on but only when you have less than 100 lux in that room. While if the switch is off the light will be off.
```
on switch1#state=1 do var1 100 endon
on switch1#state=0 do backlog var1 0; power1 off endon
on APDS9960#Ambient<%var1% do power1 on endon
```
_All together to work as a rule:_
```
Rule 1
Rule on switch1#state=1 do var1 100 endon on switch1#state=0 do backlog var1 0; power1 off endon on APDS9960#Ambient<%var1% do power1 on endon
```
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 12. Controlling Timers Enable from a Switch
Assuming that your switch is on `GPIO00` and configured as `Switch1`:
```
SwitchMode1 1
Rule 1
Rule on Switch1#state=1 do Timers 0 endon on Switch1#state=0 do Timers 1 endon
```
Switchmode1 1 will make Switch1#state to be 1 when ON and 0 when OFF
If you don't set Switchmode1 or it is equal 0, it will only have Switch1#state=2 (toggle) and the previous rule will not work.
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 13. Toggle a Relay only when holding the button for 2 seconds
The following example is to explain how to catch and use the HOLD feature for buttons.
Behaviour: Disable Button1 Short Press and Toggle Relay1 only when holding the button1 for 2 Seconds.
Type in the console:
```
ButtonTopic 0
SetOption1 1
SetOption32 20
Rule on button1#state=3 do power1 2 endon on button1#state=2 do delay endon
Rule 1
```
**Commands Explanation**
`ButtonTopic 0` : (default) To not use topics for buttons <br>
`SetOption1 1` : Allow only single, double and hold press button actions <br>
`SetOption32 20` : Set key hold time from 0.1 to 10 seconds (20 = 2 seconds) <br>
`Rule on button1#state=3 do power1 2 endon` : When holding the button1 for 2 seconds it wil toggle relay 1 (state = 3 means HOLD) <br>
`on button1#state=2 do delay endon` : Do nothing when short pressing the button1 (state = 2 means TOGGLE) <br>
`Rule 1` : To enable rules
NOTE: There is not a state number for "double press" for Buttons. It is designed that double press will toggle the relay. See [Control Other Devices](control-other-devices) for more information.
In the case you do not want the double press feature you can configure your button as switch and also set the SwitchMode that fits you (like SwitchMode 5 to make it behave as a pushbutton) [SWITCH does not have double press ]
**Another example but using switch instead of button:**
```
SwitchTopic1 0
SwitchMode1 5
SetOption32 20
Rule on switch1#state=3 do power1 2 endon on switch1#state=2 do delay endon
Rule 1
```
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 14. Rule to Make Sure Light is on at Night
Using Timers, you can be set to turn on and off a light for iluminate a street/patio by night. But if the Sonoff Device has no power at the trigger time, then, when it powers up, the light will be off all night. So, as a failsafe, can be implemented a conditional control to be checked at Sonoff Startup with rules.
Set Timers to turn on your light at Sunset and Turn off at sunrise.
Use `poweronstate 0` in order to start with lights off when powering up your Sonoff.
Set the following rules:
```
on Time#Initialized do backlog event checksunrise=%time%; event checksunset=%time% endon
on event#checksunset>%sunset% do power1 1 endon
on event#checksunrise<%sunrise% do power1 1 endon
```
The previous rules are conditionals that represent the following logic:
IF %time%>%sunset DO power1 1 / IF %time%<%sunrise DO power1 1
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 15. Rule to enable a PIR Sensor only at night
PreInfo:
- PIR HC-SR501
- GPIO14 09 Switch1 (Sonoff Basic)
- Jumper outside ( [like this](https://user-images.githubusercontent.com/14855001/44810565-5c034480-abd2-11e8-893e-1be9302cb91e.jpg) )
- Lat and Lng set in config
Commands:
```
SwitchMode1 1
Rule1
on Switch1#state=1 do backlog event checksunrise=%time%; event checksunset=%time% endon
on event#checksunrise<%sunrise% do power1 1 endon
on event#checksunset>%sunset% do power1 1 endon
Rule1 1
```
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 16. Using an external button with single press - double press and hold
You can have all 3 actions but only if defining your GPIO as button. In this case the double press will toggle the relay.
There is also an [option](Control-other-devices) to swap the actions of the **single press** and **double press**.
So,
**_BUTTON WITH 3 DIFFERENT ACTIONS_**
- As an example:
**_[ assuming GPIO0 is configured as Button1 ]_**
And that you want:
**single press**: Turn relay 1
**double press**: send a mqtt message
**hold 2 secs**: send another mqtt message
```
ButtonTopic 0
SetOption1 1
SetOption11 1
SetOption32 20
Rule on button1#state=3 do publish cmnd/topicHOLD/power 2 endon on button1#state=2 do publish cmnd/topicDOUBLEPRESS/power 2 endon
Rule 1
```
- Another example:
**_[ assuming GPIO0 is configured as Button1 ]_**
And that you want:
**single press**: send a mqtt message
**double press**: Turn relay 1
**hold 2 secs**: send another mqtt message
```
ButtonTopic 0
SetOption1 1
SetOption11 0
SetOption32 20
Rule on button1#state=3 do publish cmnd/topicHOLD/power 2 endon on button1#state=2 do publish cmnd/topicSINGLEPRESS/power 2 endon
Rule 1
```
please note that `SetOption11 0`.
**_SWITCHES WITH 2 DIFFERENT ACTIONS_**
**Switches do not have double press feature**
- Example:
**_[ assuming GPIO0 is configured as Switch1 and that you have a pushbutton connected ]_**
And that you want:
**single press**: Do nothing
**hold 2 secs**: Toggle relay 1
```
SwitchTopic1 0
SwitchMode1 5
SetOption32 20
Rule on Switch1#State=3 do Power1 2 endon on Switch1#State=2 do Delay endon
Rule 1
```
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 17. Rule to enable or disable doorbell relay with HTTP call
When you want to send MQTT messages ( we use domoticz in this example ) and choose when you want the relay (GPIO12) on or off, by simply sending HTTP commands to trigger an event.<br>
In this example we're using rules.
**Initial Config:**
- PushButton Doorbell
- GPIO14 12 Switch4 (Sonoff Basic)
Connect the PushButton to GND and GPIO14 on your sonoff basic.<br>
To be sure put a 4.7k resistor between VCC(3.3v) and GPIO14, this prevents ghost switching (capacitor is optional) See: [YouTube](https://www.youtube.com/watch?v=aq8_os6g13s)<br>
_Dont forget to change the IDX value_
**Commands:**
```
SwitchTopic 0
SwitchMode4 2
SetOption0 0
poweronstate 0
var1 1
Rule1
on event#doorbell do var1 %value% endon
on switch4#state=1 do publish domoticz/in {"idx":11,"nvalue":1} endon
on switch4#state=1 do power1 %var1% endon
on switch4#state=0 do publish domoticz/in {"idx":11,"nvalue":0} endon
on switch4#state=0 do power1 0 endon
Rule1 1
```
<br>**Usage:**<br>
Now you can call the event using HTTP to turn off the relay ( GPIO12 ).
```
http://<tasmotaIP>/cm?cmnd=event%20doorbell=0
```
and to turn on the relay ( GPIO12 ) use this one below.
```
http://<tasmotaIP>/cm?cmnd=event%20doorbell=1
```
<br>If your tasmota device is password protected, which is most common then use the following HTTP commands instead.<br>
Make sure you change tasmotaUsername and tasmotaPassword<br><br>
Off:
```
http://<tasmotaIP>/cm?&user=<tasmotaUsername>&password=<tasmotaPassword>&cmnd=event%20doorbell=0
```
On:
```
http://<tasmotaIP>/cm?&user=<tasmotaUsername>&password=<tasmotaPassword>&cmnd=event%20doorbell=1
```
[BackToExamples](Rules#examples)
#### 18. Rule to force automatic reconnection to MQTT server via SD DNS
In order to search for the MQTT server using SD-DNS service (a.k.a. Bonjour or Zero Network Configuration) the suggested configuration is to leave the MQTT Host field blank.
The standard behavior of Tasmota is
- to search for _mqtt._tcp service
- resolve that to the proper IP address
- connect to it
- in case the connection is successful, retain the IP address and use that in the subsequent connections
The above is not proper, though, in case you have a redundant MQTT (e.g., two MQTT server synchronized).
In such case, when the active MQTT fails for any reason, the expected behavior is to achieve automatic reconnection to the other MQTT server.
That can be easily configured defining the following rule on the device console:
```
Rule1 1
Rule1 on Mqtt#Disconnected do MqttHost 0 endon
```
If the MqttHost field already contains an IP, you have to delete it using the web interface or the following MQTT command:
```
mosquitto_pub -h mqtt_server.local -t "cmnd/sonoff-0657/MqttHost" -m ''
```
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 19. Rule to change distance to percentage
When measuring distance and you have the need to see it in percentage of distance.
In the example 100% is everything below 69cm and 0% is everything above 128cm.
This is used for showing fill percentage of a wood pellets storage.
```
Rule
on tele-SR04#distance do backlog var1 %value%; event checklimit=%value%; event senddistance endon
on event#checklimit>128 do var1 128 endon
on event#checklimit<69 do var1 68 endon
on event#senddistance do backlog SCALE1 %var1%, 128, 69, 0, 100; event pubdata endon
on event#pubdata do publish tele/pannrum-temp/SENSOR %var1% endon
```
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 20. Rules to distinguish Switch1 and Switch2 (without the use of Relay1 and Relay2)
When two (or more) switches are defined as input and you want to distinguish these in the RESULT topic without the use of Relais, then consider the following rules.
```
- SwitchMode1 1 will make Switch1#state to be 1 when ON and 0 when OFF
SwitchMode1 1
- SwitchMode2 1 will make Switch2#state to be 1 when ON and 0 when OFF
SwitchMode2 1
- Publish json with key POWER1 and value %value%
Rule1 on switch1#state do publish stat/wemos-4/RESULT {"POWER1":"%value%"} endon
- Publish json with key POWER2 and value %value%
Rule2 on switch2#state do publish stat/wemos-4/RESULT {"POWER2":"%value%"} endon
- Enable Rule1
Rule1 1
- Enable Rule2
Rule2 1
```
Output:
```
00:05:03 RUL: SWITCH1#STATE performs "publish stat/wemos-4/RESULT {"POWER1":"1"}"
00:05:03 MQT: stat/wemos-4/RESULT = {"POWER1":"1"}
00:05:08 RUL: SWITCH2#STATE performs "publish stat/wemos-4/RESULT {"POWER2":"1"}"
00:05:08 MQT: stat/wemos-4/RESULT = {"POWER2":"1"}
00:05:08 RUL: SWITCH1#STATE performs "publish stat/wemos-4/RESULT {"POWER1":"0"}"
00:05:08 MQT: stat/wemos-4/RESULT = {"POWER1":"0"}
00:05:11 RUL: SWITCH2#STATE performs "publish stat/wemos-4/RESULT {"POWER2":"0"}"
00:05:11 MQT: stat/wemos-4/RESULT = {"POWER2":"0"}
00:05:12 RUL: SWITCH1#STATE performs "publish stat/wemos-4/RESULT {"POWER1":"1"}"
00:05:12 MQT: stat/wemos-4/RESULT = {"POWER1":"1"}
00:05:16 RUL: SWITCH1#STATE performs "publish stat/wemos-4/RESULT {"POWER1":"0"}"
00:05:16 MQT: stat/wemos-4/RESULT = {"POWER1":"0"}
```
[BackToExamples](Rules#examples)
------------------------------------------------------------------------------
#### 21. Rule for receiving state of intercom doorbell (or anything that triggers your SWITCHX more than one times).
With analog intercoms you can take out info about ringing from speaker voltage. You can connect GPIO to it via optoisolator and resistor to take out state.
But even with those speaker voltage is dropping so it switches Sonoff multiple times.
```
14:03:00 MQT: cmnd/doorbell/POWER2 = OFF (retained)
14:03:01 MQT: cmnd/doorbell/POWER2 = ON (retained)
14:03:02 MQT: cmnd/doorbell/POWER2 = OFF (retained)
14:03:03 MQT: cmnd/doorbell/POWER2 = ON (retained)
14:03:04 MQT: cmnd/doorbell/POWER2 = OFF (retained)
```
To solve it we can use rules.
```
SwitchTopic 0
Rule1 1
on System#Boot var1 0 endon
on Switch2#State do backlog add1 1; event START endon
on event#START do event BELL=%var1% endon
on event#BELL=1.000 do backlog publish cmnd/bell/power on; RuleTimer1 60 endon
on event#BELL=0 do publish cmnd/bell/power off endon
on Rules#Timer=1 do backlog var1 0; event BELL=%var1% endon
```
description:
- turn off switchtopic as it is necessary to trigget Switch2#state
- enable rule 1
- on system boot set var1 to 0
- on switch2 click (person pushing doorbell) - var1 += 1; trigger event START
- on START - set event BELL equal to var1
- if event#BELL=1 (triggered first time) publish mqtt message ON and trigger RulesTimer1 for 60 seconds
- if event#BELL=0 publish mqtt message OFF
- on RulesTimer1 - reset var1 to 0, and call event#BELL.
In this case we have lock for 60 seconds for multiple people calls or to be resistant for speaker voltage drops.
[BackToExamples](Rules#examples)
#### 22. Invoking Rules using Clock Timer to control a Luminance triggered switch (only in mornings)
##### Background:
Tasmota powers a sonoff basic attached to a TS-2561 Luminance Sensor. This switch toggles a lamp ON or OFF. The switch should work as below:
i) during daytime (sunrise-sunset): ON when it is too dark (<150 lx) and OFF when it gets brighter (>175 lx).
ii) during evenings it ignores the sensor and turns on at sunset and turns off after about 5 hours
##### Approach:
Used a combination of Clock Timers and Rule to do this.
##### Timer 1 : Power ON switch at Sunset
Powers on the switch at sunset with an offset of 20 minutes. Repeats every day.
```
Timer1 {"Arm":1,"Mode":2,"Time":"-00:20","Window":0,"Days":"1111111","Repeat":1,"Output":1,"Action":1}
```
##### Timer 2: Power OFF switch at Night.
Turns power OFF at 23.00hrs. Repeats every day.
```
Timer2 {"Arm":1,"Mode":0,"Time":"23:00","Window":0,"Days":"1111111","Repeat":1,"Output":1,"Action":0}
```
##### Timer 3: Trigger Luminance Rule at Sunrise
Start watching the Lux sensor 15 minutes after sunrise.
```
Timer3 {"Arm":1,"Mode":1,"Time":"00:15","Window":0,"Days":"1111111","Repeat":1,"Output":1,"Action":3}
```
##### Rule 1: Main Rule to check Luminance
If Luminance is less than 150lx, power ON. If it goes beyond 175lx, power OFF.
```
Rule1 on tele-TSL2561#Illuminance<150 do power1 1 endon on tele-TSL2561#Illuminance>175 do power1 0 endon
Rule1 1
```
##### Rule 2: Trigger Rule1 only in the Mornings
This ensures that Rule1 is triggered when Timer3 starts (in the morning) and stops when Timer1 starts (in the evenings).
```
Rule2 on Clock#Timer=3 do Rule1 1 endon on Clock#Timer=4 do Rule1 0 endon
Rule2 1
```
------------------------------------------------------------------------------
#### 23. Prevent Wemos D1 mini load overcurrent
As a WS2812 24 led ring draws approximately 24x3x20 mA = 1.44A and the Wemos D1 mini powered from a PC's USB port can only provide up to 0.5A it would be nice to have some kind of mechanism in place to limit the amount of current to the WS2812 LEDring to 0.1A. This is still enough to light all 24 leds up to color 202020.
Hardware
- Wemos D1 mini
- INA219 I2C sensor
- WS2812 LEDring with 24 LEDs powered by the Wemos D1 mini 5V thru the INA219 sensor
Software
- Sonoff-Tasmota with define USE_RULES enabled
Rule
- ``on INA219#Current>0.100 do Backlog Dimmer 10;Color 10,0,0 endon``
Result
- When a user raises brightness to a level using more than 0.1A the rule kicks in and lowers the current by executing command ``Dimmer 10`` and changes the color to Red with command ``Color 10,0,0``.