Rule cookbook - FengtianGu/Sonoff-Tasmota GitHub Wiki

  1. Use long press action on a switch
  2. Execute any MQTT message when a button is pressed
  3. Execute Several Commands when a Timer Expires
  4. Usage of one-shot (once)
  5. Use of Variables and tele-
  6. Use a Potentiometer
  7. Setting Variables
  8. Control device LEDs with Relays
  9. Simple Thermostat Example
  10. Simple Staircase Timer
  11. Energy Saving Smart Switch
  12. Controlling Timers Enable from a switch
  13. Toggle a Relay only when holding the button for 2 seconds
  14. Make sure light is on at night
  15. Enable a PIR Sensor only at night
  16. Using an external button with single press - double press and hold
  17. Enable or disable doorbell relay with HTTP call
  18. Force automatic reconnection to MQTT server via SD DNS
  19. Change distance to percentage
  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).
  22. Invoking rules using clock timer to control a luminance-triggered switch only in mornings
  23. Prevent Wemos D1 mini load overcurrent
  24. Using dummy relays to send Serial codes to the MCU
  25. Arithmetic Commands to be used with VARs
  26. Timer-triggered Low frequency blink (intermittent timer)
  27. Switch relais via serial interface

1. Use long press action on a switch

Activate long press action with Switchmode 5 and shorten long press time to 2 seconds (Setoption32 20).

Long pressing on switch1 sends POWER 2 (toggle action) command to the sonoff02 device

SwitchMode 5
SetOption32 20
Rule on switch1#state=3 do cmnd/sonoff02/POWER 2 endon
Rule 1

Notice we use Rule which edits Rule1 rule set. They can be used interchangeably.


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.

Back To Top


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

Back To Top


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.

Back To Top


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.

Back To Top


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 ;-)

Back To Top


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.

Back To Top


8. Control device LEDs with Relays

If a device has more than one relay and LEDs on different GPIOs (not connected to the relay) you need to use rules to display current relay status on LEDs. This example is a 3 gang wall switch. Instead of LEDs you need to assign 3 dummy relays that will be controlled when the real relays are switched to reflect their status.

seriallog 0
rule1 on power1#state do power4 %value% endon on power2#state do power5 %value% endon on power3#state do power6 %value% endon
rule1 1
ledmask 0x0000
setoption13 1

Note: This method doubles the number of flash writes. Link to the device

Back To Top


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

Back To Top


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)

Back To Top


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.

Back To Top


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

Back To Top


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.

Back To Top


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
SetOption1 1 : Allow only single, double and hold press button actions
SetOption32 20 : Set key hold time from 0.1 to 10 seconds (20 = 2 seconds)
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)
on button1#state=2 do delay endon : Do nothing when short pressing the button1 (state = 2 means TOGGLE)
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 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

Back To Top


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

Back To Top


15. Rule to enable a PIR Sensor only at night

PreInfo:

  • PIR HC-SR501
  • GPIO14 09 Switch1 (Sonoff Basic)
  • Jumper outside ( like this )
  • 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

Back To Top


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 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

Back To Top


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.

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.
To be sure put a 4.7k resistor between VCC(3.3v) and GPIO14, this prevents ghost switching (capacitor is optional) See: YouTube
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


Usage:

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


If your tasmota device is password protected, which is most common then use the following HTTP commands instead.
Make sure you change tasmotaUsername and tasmotaPassword

Off:

http://<tasmotaIP>/cm?&user=<tasmotaUsername>&password=<tasmotaPassword>&cmnd=event%20doorbell=0

On:

http://<tasmotaIP>/cm?&user=<tasmotaUsername>&password=<tasmotaPassword>&cmnd=event%20doorbell=1

Back To Top


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 ''

Back To Top


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

Back To Top


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"}

Back To Top


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=0 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.

Back To Top


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

Back To Top


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.

24. Using dummy relays to send Serial codes to the MCU

By having a device (an Oil Diffusser) that controls all its features through an MCU and reports the states in serial codes to the ESP8266 I had to create some rules to control it using the Web UI or standard Power commands.

Rule2 on power1#state=1 do serialsend5 55AA00060005020400010213 endon on power1#state=0 do serialsend5 55AA00060005020400010011 endon on power2#state=1 do serialsend5 55AA00060005060400010217 endon on power2#state=0 do serialsend5 55AA00060005060400010015 endon

Power1 controls the device, Power2 turn on and off the light on the device.

Another rule was created to issued commands on boot so the serial interface works every time and to control the built in fan using Event triggers and have its state retained in an MQTT message for Home Assistant.

Rule3 on system#boot do backlog baudrate 9600; seriallog 2; serialsend5 55aa000300010306 endon on event#high do backlog serialsend5 55AA00060005650400010175; publish2 stat/diffuser/FAN high endon on event#low do backlog serialsend5 55AA00060005650400010074; publish2 stat/diffuser/FAN low endon

Back To Top


25. 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 value’s current range fromHigh: the upper bound of the value’s current range toLow: the lower bound of the value’s target range toHigh: the upper bound of the value’s target range

(omitted values are taken as zero)

Usage: SCALE1 15, 0, 100, 0, 1000 Result: VAR1 = 150

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

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

Back To Top


26 Timer-triggered Low Frequency Blink

This example uses a rule timer to call itself to allow the power to be switched on and off within a set time period. The rule timer is triggered by Global timers - one to set it going, the other to turn it off.

To set the whole period of operation, set the ON timer1 through the web interface to trigger a rule. Set the OFF timer2 through the web interface to trigger a rule.

Write the following rules:

rule1 on Clock#Timer=1 do backlog power 1; ruletimer#1 10 endon

This rule is triggered by global timer 1 and switched the device on then sets the timeout at 10 seconds

rule2 on RuleTimer=1 do backlog power 2; rules#timer=1 10 endon

This rule is called on the ruletimer timeout and toggles the power then resets the timer for another 10 seconds

rule3 on Clock#Timer=2 do backlog power 0; rules#timer=1 0 endon

At the end of the desired period of operation, the clocktimer times out and runs rule3 which turns power off and sets the ruletimer to zero so it does not run. The device remains off.

These rules were used to run a heater intermittently to keep a room warm in the absence of a thermostat.


27. Switch relais via serial interface

This example switches a connected relais over the software serial on and off.
Write the following rules:

rule1 on SSerialReceived#Data=on do power1 1 endon on SSerialReceived#Data=off do power1 0 endon

receiving on and off results in

MQT: tele/sonoff-1585B3/RESULT = {"SSerialReceived":"on"}
RUL: SSERIALRECEIVED#DATA=ON performs "power1 1"
MQT: stat/sonoff-1585B3/RESULT = {"POWER":"ON"}
MQT: stat/sonoff-1585B3/POWER = ON
MQT: tele/sonoff-1585B3/RESULT = {"SSerialReceived":"off"}
RUL: SSERIALRECEIVED#DATA=OFF performs "power1 0"
MQT: stat/sonoff-1585B3/RESULT = {"POWER":"OFF"}
MQT: stat/sonoff-1585B3/POWER = OFF

⚠️ **GitHub.com Fallback** ⚠️