Rule-5.1

From Hubitat Documentation
Revision as of 03:55, 13 September 2022 by RobertM (talk | contribs) (Add missing tips/notes from Rule 5.1 doc)
Jump to: navigation, search

Rule Machine is the most powerful built-in tool for creating custom automations in Hubitat Elevation.

Tip: Rule Machine is very powerful but can be somewhat complex for new users. Before using Rule Machine, you may wish to consider if another built-in app (Notifications, Room Lighting, Basic Rules, etc.) meets your needs.

Creating a new Rule

  1. Navigate to the hub interface, then select Apps in the sidebar.
  2. Select Rule Machine from the list. (Or install Rule Machine with Add Built-In App first if you have not already.)
  3. Select Create New Rule, then follow the prompts to provide a name for your rule. This is how it will appear in the Apps list and in logs.
  4. Specify triggers, actions, and other components you need to make your rule work as intended, as described below.

Anatomy of a rule

Rules consist of up to three parts:

  • Trigger events: When any of the trigger events happen, the "Actions to Run" will begin executing.
  • Required expression: If used, the rule will not trigger unless the expression evaluates to true at the moment of the trigger event.
  • Actions to run: A list of actions to run when the rule is triggered — for example, turning on lights, changing a mode, or running just about any command on any device.

Trigger events

Each rule can have one or more trigger events specified. Events are generated by devices or by your hub itself. Examples of trigger events include "Motion sensor X is active" or "Time is 8:00 PM". Rules will listen for trigger events and run the "Actions to Run" when any trigger event happens (except in some cases when a required expression is used, as described below).

To specify a trigger event, open the Select Trigger Events page by selecting the Select Trigger Events box. Then, choose the "capability" that matches the kind of trigger event you want to add. For example, to trigger on "motion active," choose the "Motion" capability. To trigger on a switch (including a bulb or dimmer) turning on or off, choose "Switch." See the List of Trigger Event Capabilities section below for a complete list of capabilities and the attributes or events they correspond to.

The And stays? option, also called a "sticky trigger," is option available for many types of trigger events. (If this option does not appear, that particular kind of trigger event does not support this option, generally events that do not relate to state changes.) For example, a trigger of Front door opens and stays that way for 0:05:00 will trigger only if the front door opens and remains in an opened state for 5 minutes. If the door is closed before that time, the trigger will not happen.

NOTE: Rules can also be created without any trigger events. However, such rules' actions will run only when called by another rule or when run manually viewing the rule (with the Run Rule Actions button).

Required expression

Enabling the Use required expression option allows you to define an expression (a single condition or any combination of conditions) that must evaluate to true in order for the rule to trigger. If the required expression evaluates to false at the moment when the rule is triggered, the rule will not actually trigger, and the specified actions will not run.

One possible use for required expressions is to trigger only on specific state changes. For example, if you want a rule to trigger only on a specific mode change — say, Away mode to Home mode — then a required expression is an easy way to make that happen:

Trigger events: Mode becomes Home

Required expression: Mode is Away

Without the required expression, this rule would trigger any time mode becomes Home, regardless of the previous mode.

Another possible use for a required expression is to restrict the execution of actions under certain conditions (though this can generally also be done with conditional actions in "Actions to Run"; see below for more).

NOTE: Almost any condition can be used to create a required expression. However, local variables should not be used in conditions used to create required expressions (they do not generate events and thus the required expression will not be re-evaluated when it changes). Hub variables and Private Boolean will work without caveats.

Actions to run

This is where you define what happens when the rule is is run. To add an action, first choose the appropriate category for the action under Select Action Type to add. Then, choose the specific action under Select Which Action. See the List of Actions section below for a complete list of where to find any particular action in this menu structure. Most actions run a command on a device. For example, Set Dimmers and Bulbs > Set dimmer can be used to set the level (brightness) on a dimmer or bulb. Under the hood, this calls the "Set Level" command on the device, but you do not need to know this; Rule Machine handles running commands on devices as needed based on your selections here.

Actions to run are essentially an ordered script. You can add as many actions as you need in whatever order you want. Note that some "special" action lines like IF (expression) THEN and Repeat have specific formats that must be followed; see below for more details on these.

Modifying Actions

Actions can be modified with the Edit Action or Delete Actions drop-downs. (Edit Actions can be used for minor changes, like replacing one device with another or changing a specified value. To completely replace one type of action with another, you will need to delete the action and insert a new one at the desired location.) Insert Action Before will allow you to choose a specific location to insert a new action; by default, new actions will be added to the end of the list.

The Cut Action, Copy Action, and Paste Action Before drop-downs can be used to cut, copy, and insert actions in typical "clipboard" fashion. Cut or copied actions can be shared to another rule by selecting the Export clipboard? option in one rule and using the Import Clipboard From drop-down in another rule.

Rule options

  • Each rule has options for Logging:
    • Events: logs any time a trigger event happens. The log entry will contain the name of the rule and a description of the event (e.g., "My Rule event: Side Door Lock unlocked)
    • Triggers: logs any time the rule was triggered (e.g., "My Rule Triggered")
    • Actions: writes a log immediately before each action in the rule is run (or also if it was skipped — for example, because it is inside a conditional action that evaluated to false)

All log entries will appear in "Logs," accessible from the sidebar. These options can be useful for troubleshooting.

  • Display current values: if enabled, the current value for any selected device attributes, variables, etc. will be displayed next to the device the list of trigger events and actions to run. These values will also be displayed with the actions in "Logs" if action logging is enabled.
  • Run Actions button: will run the Actions to Run section (effectively a way to manually trigger a rule)
  • Update Rule button: re-initializes rule like Done but without leaving the rule editor page
  • Remove button: removes this rule. Note that the Remove button inside a rule removes only that rule; the Remove Rule Machine button inside the "parent" Rule Machine app will remove Rule Machine and all rules.
  • Done button: re-initializes rule (updates trigger event subscriptions; cancels any timers/scheduled jobs), then returns to the Apps list page. (Note that changes inside the "Select Actions to Run" page are saved as they are made and do not require use of this button.)

Special Actions

Most Rule Machine actions run commands on devices. For example, Control Switches, Push Buttons > Turn switches on/off will send an "On" or "Off" command to the selected device(s), depending on the options chosen. Toggle switches will turn the switch (or dimmer, bulb, etc.) off it it is on or on of it is off. However, Rule Machine also contains various types of special actions, like delays and repeats.

Conditional Actions

Rule Machine offers two types of conditional actions:

IF (expression) THEN

The most powerful option is the "full" conditional action you can get by selecting IF (expression) THEN. Any action between this action and END-IF, which must be used to indicate the end of your block of conditional actions, will be executed only if the provided expression is true when the IF (expression) THEN line is reached. For example:

IF (Living Room Dimmer is on) THEN
  Dim: Living Room Dimmer: 50%
END-IF

The "Dim..." action will be reached only if the Living Room Dimmer device is on when the IF...THEN line is reached. If not, the rule will proceed to the next action after the END-IF. You can put multiple lines of actions between the IF...THEN and END-IF. You can also use ELSE and ELSE-IF to create more complicated flows. These work similarly to conditional logic in most programming languages. Here is a more complicated example:

IF (Living Room Dimmer is on) THEN
  IF (Mode is Day) THEN
    Dim: Living Room Dimmer: 75%
    On: Kitchen Lights
  ELSE-IF (Mode is Night) THEN
    Dim: Living Room Dimmer: 25%
    Off: Kitchen Lights
  ELSE
    Dim: Living Room Dimmer: 50%
END-IF

(Note that these are only examples of how to create rule actions and may appear somewhat contrived to demonstrate possible structure; we are not considering what might trigger this rule.)

Simple Conditional Action

A simple conditional action is an expression that can be "attached" to a single action, and that action will only run if the condition is true. Our first example above could have been re-written using the Simple Conditoinal Action option as:

IF (Living Room Dimmer is on) Dim: Living Room Dimmer: 50%

Unlike "full" conditional actions, a simple conditional action allows only a single action to run when the condition is true. It also does not provide a way to specify alternate flows if false.

Manage Conditions/Create Conditions

The Select Actions to Run page includes a Create Conditions or Manage Conditions section at the bottom:

Screenshot: "Manage Conditions" box in Rule Machine

This allows you to edit (or pre-build) conditions used in conditional actions, wait for expression actions, and other places where conditions can be used — without needing to edit or re-create that action.

NOTE: Creating or adding conditions under Create Conditions or Manage Conditions will not do anything per se. These conditions are available to use (and perhaps are being used) in conditional actions, wait for expression actions, and other rule actions where expression can be used — but they do not do anything unless they are used somewhere.

A similar option appears in the Define Required Expression page, and the same applies (although these two "banks" of conditions are separate and only available in required expressions or actions, respectively).

Delay

Rule Machine has two types of delays. A delay can be added as a special type of action under Delay, Wait, Exit or Comment > Delay Actions (or Delay Actions Per Mode to specify a different delay for each mode). This causes the actions to effectively pause at the delay, wait for the specified amount of time, then resume with the next action when the time is up.

Alternatively, with most actions, a delay option can be specified on the action itself. To do this, select an option from the Delay? drop-down when creating or editing the action. Choose hrs:min:sec to specify a specific amount of time, or choose variable to use a local or hub variable (must be of type number or decimal).

For any delay, the Cancelable? option may be selected. By default, a rule being re-triggered (or the rule actions running again for any reason) does not cancel previously scheduled delays. Choosing the Cancelable option allows the delay to be cancelled with the Cancel Delayed Actions action elsewhere in the same rule, but this must be done explicitly.

Care must be taken when using delays embedded inside conditionals. If the rule re-triggers while the delay is pending and the conditional action is reached again, you may see a "Multiple simultaneous rule execution error" in Logs (and the rule actions will not run as intended). Solutions include restricting execution of the rule while the delay is pending (e.g., with a required expression), cancelling the delay earlier in the rule, or using a "Wait for events: elapsed time" action instead if you want the timer to be cancelled on re-trigger of the rule.

NOTE: The Cancel Rule Timers actions will also cancel delayed actions (and can be called on the rule from any rule, not just the same rule), but it affects all rule timers, not just delays. It will also cancel delays with or without the Cancelable? option selected.

Wait

Rule Machine offers two types of waits under Delay, Wait, Exit or Comment: the Wait for Events action and the Wait for Expression action.

Wait for Events

Wait for Events allows you to specify one or more events. The rule will effectively pause at this point and wait for one of the specified event(s) to fire. When any of the specified events happen, the rule will proceed with the next action.

To add more than one event to wait for, press Add another Wait Event after adding the first (or any subsequent) event. When you are finished with everything, press Done with Wait Events to return to the previous page to add or edit other actions.

The Timeout? option allows you to specify an amount of time after which the rule will proceed with the next action in case none of the specified event(s) happen.

The And stays? option requires the condition resulting from the event to remain true for the specified amount of time before continuing. If the event happens but the resulting state does not remain true for the specified time, the rule will continue to wait.

Wait for Expression

Wait for Expression allows you to specify a condition or combination of conditions (i.e., an expression). If the expression is true when this wait is reached, the rule will immediately proceed with the next action (unless a duration is required; see below). If it is false, the rule will effectively pause at this point and wait for the expression to become true.

The Timeout? option allows you to specify an amount of time after which the rule will proceed with the next action in case the specified expression does not become true before that amount of time passes. The Use Duration? option allows you to specify a Duration, an amount of time for which the expression must remain true in order for rule to proceed to the next action. If a duration is specified and the action becomes (or is) true for some amount of time less than the duration and then becomes false again, the wait will start over.

Cancellation of Waits

Any type of "Wait" action is cancelled upon re-triggering of a rule. (The Cancel Rule Timers action will also cancel waits but is rarely necessary, and it affects all rule timers ,as described elsewhere.) Note that this behavior differs from delays, which must be explicitly cancelled.

TIP: Using Wait for Events with Elapsed Time chosen as the capability is a particularly handy method of delaying actions. Unlike the Delay action (or the Delay? option on an action), waits are cancelled when the rule is re-triggered without any additional configuration required. This can save a couple clicks compared to a "delay" if this is the desired outcome. (Note: the Elapsed time option is not available if other events have already been selected, as it is effectively equivalent to setting a timeout on that wait for event.)

Exit Rule

Exit Rule stops the execution of rule actions past the Exit Rule action itself. Note that it does not cancel any repeats, delays, waits, or other scheduled actions that may have already been set in place.

This action is generally most useful if used as part of a conditional action. For example:

IF (Mode is Night) THEN
  Exit Rule
END-IF
(remaining actions to run only in modes besides Night..)

Comment

This action has no effect; it simply allows you to write a "comment" at that location in your rule actions that will display in the editor (this could be helpful if you want to document for yourself why you are using certain actions at that point in the rule).

Repeat

Rule Machine offers two types of repeat: Repeat Actions and Repeat While Expression. Either must be terminated with an END-REP, with the Repeat Actions and END-REP or Repeat While Expression and END-REP enclosing the action(s) to be repeated.

You must specify the time interval for the repetition. Be careful not to make this interval too short, as you can consume your hub CPU resources by repeating too quickly. You can select any number of iterations if desired, but some method to stop the repetition is required. One option is the Repeat n times option, which will stop the repeat after n repetitions. Additionally, there is an optional Stoppable? option for a Repeat..., and if selected, then Stop Repeating Actions will stop this repetition when called from elsewhere in the rule. Using Cancel Rule Timers from either the current rule or another rule will stop all repeats (and other rule timers), regardless of whether this option is selected.

Examples of repeats

General format

With Repeat Actions:

Repeat Actions
     some actions...
END-REP

With Repeat While (Expression):

Repeat While (Expression)
  some actions...
END-REP

The above is equivalent to a simple conditional on a Repeat Actions, which was the only option to create such a repeat in Rule 5.0 and prior (and still works):

IF (condition) Repeat Actions
     some actions...
END-REP

The following can also be logically equivalent:

Repeat Actions (stoppable)
     some actions
    IF (condition) Stop Repeating Actions
END-REP

or:

Repeat Actions (stoppable)
  IF (condition) THEN
    Stop Repeating Actions
  ELSE
    some actions...
  END-IF
END-REP

Repeat n times (like a "for loop"):

Repeat Actions n times
     some actions...
END-REP

Ping

Rule Machine includes an action that can ping an IP address (under Send, Speak, or Log a Message, Send HTTP Request). This sets the built-in text variable to the response results of three ping attempts and the built-in value variable to the packet loss or 100 if no response. (See above on how to use built-in rule variables.)

Custom Action

Most Rule Machine actions run specific commands on a device. For example, the Set Dimmers and Bulbs > Set Dimmer action runs the Set Level command on a device (and passes the level and optional fade time as parameters).

If you want a Rule Machine action to run a command on a device that is not available via built-in Rule Machine actions, the Set Variable, Mode or File, Run Custom Action > Run Custom Action action can do that. Select this action, then choose the device (by either using "Last Event Device" or choosing a capability the desired device supports and then finding it in the list), and finally, choose the command to run. Optionally, specify one or more parameters. The Device Detail page for the device displays all commands at the top of the page and will show you what, if any, parameters are optional or required.

Others

Rule Machine is arbitrarily powerful, and there will always be things it can do that you won't find an example of. For questions, the Hubitat Community is a great resource!

Special Features

Local Variables

Rule Machine allows you to create local variables in each rule. These function similar to hub variables, except they are only available for use inside the specific rule where they are created. (Users of older Rule versions may recall global variables, which have effectively been replaced by hub variables and are also usable inside Rule Machine.)

Use the Create Local Variables or Create, Set, or Delete Local Variables option at the bottom of the main page of any rule to create or edit local variables for that rule. Data types, naming restrictions, and in-rule usage possibilites are generally similar to those for hub variables.

Rule Machine allows the use of local variables (and hub) variables in certain UI actions. For example, if you have a local variable named MyVariable, you can can use the string %MyVariable% in many string inputs to substitute the value of the variable. This works with any action under Send, Speak, or Log a Message, Send HTTP Request, including Send/Speak a Message, as well as when setting the value of String variables. Many actions will also offer the option to use a variable for a specific value, e.g., Set Dimmer has a Variable level? option that can be enabled to specify a variable to use for the level.

Rule Machine also has a few "built-in" variables local to each rule that refer to the last device event (usually the most recent trigger event). These can be referred to in string inputs using:

  • %device%: name of the device that generated the event (or "timeout" after a "Wait..." action if a timeout is specified on a wait and the next action is reached because the timeout expires)
  • %value%: the value of the event (e.g., could be "off" for a switch)
  • %text%: the descriptionText property for the event (as provided by the driver, often in a format resembling "Living Room switch is off")
  • %date%: the date the event was generated
  • %time%: the time the event was generated
  • %now%: the current time

Private Boolean

Private Boolean is a built-in boolean (two values: true or false) variable available to each rule. It functions similarly to a local boolean variable, except:

  • you do not have to create it; it is already part of every rule
  • it can be modified via other rules, not just the same rule (and is done differently from "regular" variables, using the actions under the Set Private Boolean, Run/Pause/Cancel Rules action category)
  • it can be used as part of a required expression

NOTE: Private Boolean does not do anything on its own; it is used only if and how you use it in your rule(s).

Frequently asked questions

Why didn't my rule run?

Try enabling logging as described in the Rule Options section. Then, use "Logs" in the sidebar to see what, if anything, your rule did and when. (Note that you'll need to use the "Past Logs" option on this page unless you had "Current Logs" open at the time the log entry was generated.) Sometimes, you will find that your rule, in fact, did execute as expected, but a device may not have responded as intended. This will help you begin troubleshooting. The "Display current values" may also be helpful to have enabled if you have conditional actions or may otherwise care about the value of conditions/expressions, variables, and other states during execution.

Additionally, ensure your rule was created correctly. For example, without trigger events, rule actions will never execute unless run from another rule or app (or run manually from the rule page itself).

Why can't I use "AND" in the list of trigger events?

Triggers represent events, which are an instant in time — for example, motion becoming active, a switch turning on, or the time becoming 8:30 PM. If you want to check a state rather than respond to a specific event, you can do so in the actions (using a conditional actions), or you can use a required expression to restrict triggering when a certain condition or combination of conditions is not true.

Need more help?

The Hubitat Community is a great place to ask questions and share ideas with fellow users.

Capabilities and Actions

Below is a complete list of trigger event capabilities (on the "Select Trigger Events" page) and available actions (on the "Actions to Run") page, which can be useful to consult if you are not sure where to find something or what capability to choose for a specific event.

List of Trigger Event Capabilities

The following is a list of capabilities found on the "Select Trigger Events" page and the attribute or event that the trigger can listen for. Most of these capabilities can also be used to create conditions and expressions in rules as well.

Capability Description (attribute, event, etc.)
Acceleration: active / inactive
Between two dates: starting month on this date / ending month on this date
Battery: value
Button: pressed / held / doubleTapped / released
Certain Time: at a certain time, including sunrise / sunset with offset
Cloud End Point: trigger with HTTP GET on generated cloud URL
Contact: open / closed
Custom attribute: device capability
Days of Week: on certain days of the week
Dimmer level: value
Door: open, closed, opening, closing, unknown
Energy meter: value
Garage door: open, closed, opening, closing, unknown
HSM alert: intrusion, intrusion-delay, intrusion-home, intrusion-home-delay, intrusion-night, cancelRuleAlerts, intrusion-night-delay,
smoke, water, rule, arming, armingHome, armingNight, cancel
HSM status: armed away, armed home, armed night, delayed arming home, delayed arming night, delayed arming away, disarmed, all disarmed
Humidity: value
Illuminance: value
Last Event Device select device and attribute
Local End Point: trigger with HTTP GET on generated local URL
Lock: locked / unlocked
Mode: any of your hub's modes
Motion: active / inactive
Music player: playing, paused, stopped
Periodic: allows periodic schedules for minutes, hourly, daily, weekly, monthly or yearly
Physical dimmer level: value
Physical switch: on / off
Power meter: value
Power source: mains / battery
Presence: present / not present or arrives / leaves
Private Boolean: true / false
Rule paused: rule
Smoke detector: clear, detected, tested
Switch: on / off
Temperature: value
Thermostat cool setpoint: value
Thermostat fan mode: value
Thermostat heat setpoint: value
Thermostat mode: heat / cool / auto / off / emergency heat
Thermostat state: heating / cooling / fan only / idle / pending heat / pending cool
Time of day: specific time / sunrise / sunset
Variable: value
Water sensor: dry / wet

List of Actions

The following is a list of the actions available on the "Select Actions to Run" page. This can be helpful to consult if you are unsure where to find a specific action in the menus.

Select Action Type to Add Select Which Action
Conditional Actions IF (expression) THEN

ELSE-IF (expression) THEN
ELSE
END-IF
Simple Conditional Action

Control Switches, Push Buttons Turn switches on/off

Toggle switches
Flash switches
Set switches per mode
Push button
Push button per mode

Set Dimmers and Bulbs Set dimmer

Toggle dimmer
Adjust dimmer
Set dimmer per mode
Fade dimmer over time
Stop dimmer fade
Start raising/lowering dimmer
Stop changing dimmer
Set color
Toggle color
Set color per mode
Set color temperature
Toggle color temperature
Set color temperature per mode
Change color temperature over time
Stop changing color temperature

Activate Scenes, Adjust Shades or Fans Activate scenes

Activate scenes per mode
Open/Close shades/blinds
Set shade/blind position
Set fan speed
Cycle fans

Control HSM, Garage Doors, Locks, or Valves Arm/Disarm Hubitat® Safety Monitor

Open/Close garage door
Lock/Unlock locks
Open/Close valves

Control Thermostats or Thermostat Scheduler Set thermostats

Set Thermostat Scheduler

Send, Speak, or Log a Message, Send HTTP Request Send/Speak a Message

Log a Message
Send HTTP Get
Send HTTP Post
Ping IP address

Control Music Player, Volume, Sounds Control Music Player

Set Volume
Mute/Unmute
Sound Tone
Sound Chime
Control Siren

Set Variable, Mode or File, Run Custom Action Set Variable

Set Mode
Run Custom Action
Write to local file
Append to local file
Delete local file

Set Private Boolean, Run/Cancel/Pause Rules Set Private Booleans

Run Rule Actions
Cancel Rule Timers
Pause/Resume Rules

Capture/Restore, Device Refresh or Polling Capture Devices

Restore Devices
Refresh devices
Poll devices
Disable/Enable devices
Start/Stop Z-Wave Polling

Repeat actions Repeat Actions

Repeat While Expression
END-REP
Repeat Until Expression
Stop Repeating Actions

Delay, Wait, Exit or Comment Delay Actions

Delay Actions Per Mode
Cancel Delayed Actions
Wait for Events
Wait for Expression
Exit Rule
Comment