Rule Machine

From Hubitat Documentation
Revision as of 18:56, 10 May 2019 by Bravenel (talk | contribs)
Jump to: navigation, search

Rule Machine® is a generalized rule engine for Hubitat. It allows you to predicate actions to be taken by Hubitat by a logical rule based on specified conditions of your system. Rule Machine also provides Triggers, basic event-causes-action building blocks, and Triggered Rules where an event causes a rule evaluation. Rules, Triggers, Triggered Rules, and Actions work together to create sophisticated automations.

What are Rules?

A rule is a method of specifying certain conditions and their truth relationships in order to cause some action to take place in Hubitat.

For example, one person posed this case:

Suppose my presence or my wife’s presence is home, there is motion in the bedroom, it’s between 8 PM and 11PM, and the temperature is below 65 — if those conditions are met, turn on the electric blanket.

In order for this action to take place in Hubitat, based on those conditions, Rule Machine will evaluate those conditions, and if they are met, turn on the electric blanket. Rule Machine allows you to specify the conditions, the rule they must meet, and the desired actions to take place. This is called a Rule.

What are Triggers?

A Trigger is a simple mechanism through which some event in your system causes a selected action to take place. This is a basic building block of automations.

For example: if the door opens, turn on the light.

What are Triggered Rules?

A triggered rule adds a rule to be evaluated for a triggered event. Wwhen any of its trigger events fire, it evaluates the conditions under the rule and then takes actions based on the truth outcome of that evaluation. This is called a Triggered Rule.

What are Actions?

Actions are a set of actions that can be taken. These don't do anything by themselves. They can be used by Rules, Triggers and Triggered Rules as an action. One defined set of actions can be used by multiple other rules or triggers without having to be defined for each one.

What are Schedules?

A Schedule allows a set of actions to be done at a pre-determined time. Optionally, a second set of actions can be done after some time. For example, a pool pump could be turned on at 5:00 AM every day, and then turned off 180 minutes later. Schedules can be defined by day of week, including groups of days (e.g. one schedule for weekdays and a different schedule of weekends).

What are Conditions and Trigger Events?

Rule Machine allows a wide range of possible conditions and events to be selected. For rules we select conditions. For triggers we select events. Conditions and events are closely related because each event results in a condition. For example, the door opening is an event and results in the condition of the door being open. Both rules and triggers rely on events to cause their actions. Rules examine the conditions, and act on truth change. Triggers act on events.

Events are created by the devices in your system. Each device creates events appropriate to the type of device. When you create a rule, Rule Machine listens for any event that might affect the truth of the rule. When a rule receives a selected event, it evaluates the truth of its rule, and then takes selected actions based on that evaluation. A trigger also listens for events. When a trigger receives a selected event, it either takes the selected actions unconditionally (if no conditions were specified), or it causes the conditions to be evaluated under the rule and actions taken accordingly.

Rule Machine allows the following conditions/events in a Hubitat system to be tested in a rule or acted upon in a trigger. Each condition results in a single test. There may be as many conditions as you want in a rule, or as many event triggers as you want in a trigger. The supported conditions, events and states that can be tested are listed below. Note: Days of week and Time of day are not available in a trigger. There are additional events available for triggers; see below.

Acceleration:	            active / inactive
Battery: 		    value
Contact:		    open / closed
Days of week:               Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
Dimmer level: 	            value
Door: 			    open, closed, opening, closing, unknown
Energy meter:	            value
Garage door: 	            open, closed, opening, closing, unknown
HSM status:                 armed away, armed home, disarmed
Humidity:		    value
Illuminance:	            value
Lock:			    locked / unlocked
Mode:			    any of your hub's modes
Motion:			    active / inactive
Music player: 	            playing, paused, stopped
Power meter:	            value
Presence:		    present / not present or arrives / leaves
Private Boolean: 	    true / false
Rule truth: 		    true / false
Smoke detector:             clear, detected, tested
Switch:			    on / off
Temperature:		    value
Thermostat mode: 	    heat / cool / auto / off / emergency heat
Thermostat state: 	    heating / cooling / fan only / idle / pending heat / pending cool
Time of day:		    between two times, including sunrise / sunset with offsets
Water sensor: 		    dry / wet

Note: value means compare current value to a number or to another device with an offset

Triggers respond to these additional events:

Button:               pressed / held
Certain Time:         at a certain time, including sunrise / sunset with offset
Cloud End Point:      hitting URL fires
Local End Point:      hitting URL fires
Periodic:             Allows periodic schedules for minutes, hourly, daily, weekly, monthly or yearly
Physical switch:      on / off

For each condition/event that refers to a device, one or more devices can be selected, and then the device state required for the condition to be met can be selected. When multiple devices are selected, the condition/event may apply for ANY (default) or ALL of the devices.

For example, the conditions for the electric blanket case are,

my presence or my wife’s presence is present (ANY)
bedroom motion is active
time of day is between 8:00 PM and 11:00 PM
bedroom temperature is < 65

How is a rule defined?

A rule is a logical expression built up using the conditions and the three logical operators AND, OR and NOT, along with parenthesized sub-rules, each of which is itself a logical expression. A logical expression defines the logical relationship between the various conditions. In order to decide if the end action should be taken or not, Rule Machine evaluates the truth of the defined rule. In the electric blanket case, we have a very simple rule:

my presence or my wife’s presence is present AND
bedroom motion is active AND
time of day is between 8:00 PM and 11:00 PM AND
bedroom temperature is < 65

There can be more complex rules than this. Suppose we want the same basic rule, but want it to apply if either bedroom motion is active or the bedroom door is closed. We would add the additional condition of “bedroom door is closed”. That rule would be this:

my presence or my wife’s presence is present AND
(bedroom motion is active OR bedroom door is closed) AND
time of day is between 8:00 PM and 11:00 PM AND
bedroom temperature is < 65

In this example, we have used parentheses to group two conditions into a sub-rule: (bedroom motion is active OR bedroom door is closed). Rule Machine allows arbitrarily complex rules to be defined, with parentheses used to group conditions into sub-rules. To use this feature of sub-rules in parentheses, you must first turn on the "Advanced Rule input" option, at the beginning of the Define Rule page. It allows nested sub-rules to any depth, and it allows any number of conditions. To help you see exactly the rule you are building, Rule Machine displays the partial rule at each step as you define it. See screen shots in a following post.

Rule Machine is a fully generalized rule engine. The logical expression can be described as a sequence of terms, separated by operators, where each term is either a condition or a parenthesized sub-rule (available with Advanced Rule input enabled), and the operators are AND, OR and NOT. The evaluation of a rule or sub-rule is strictly left to right. If at any point in the evaluation, the truth value preceding an AND operator is false, the sub-rule or the rule itself is false without further evaluation. Similarly, if the truth value preceding an OR operator is true, the sub-rule or the rule itself is true without further evaluation. For those familiar with coding, there is no operator precedence as to AND and OR, only for NOT that applies to the term it precedes. Each rule or sub-rule may have as many terms as desired, each separated by AND or OR. Any term may be logically negated by preceding it with the NOT operator.

Rule Evaluation for Rules

A rule is installed with conditions, rule, and actions. For a rule, whenever something happens in Hubitat that could affect the conditions, Rule Machine evaluates the rule to see if it is true or false. If it becomes true, then it will take some selected actions; if it becomes false, it can take some other selected actions. In the case of the electric blanket, the rule would be evaluated whenever any of the following things happen:

my presence or my wife’s presence arrives or leaves
the bedroom motion goes active or inactive
the bedroom door is opened or closed
the time becomes 8:00 PM, or becomes 11:00 PM
the bedroom temperature is reported

Since our rule for this case involves all of these possible events, any of those events might be the one that changes the evaluation outcome from false to true. If that happens, Rule Machine will turn on the electric blanket.

Rule Machine only acts on the change of rule state from false to true, or true to false, except in the case of a trigger event causing rule evaluation. It may evaluate the rule many times, depending on what sort of events are subscribed to, but only a truth change causes action. A trigger causing rule evaluation will result in action if the rule is true, without regard to prior rule truth or rule truth changing.

The evaluation of a rule is strictly from left to right. If at any point in the evaluation, the truth value preceding an AND operator is false, the rule is false without any further evaluation. Similarly, if the truth value preceding an OR operator is true, the rule is true without any further evaluation. You must take this into consideration as you define your rule, if you have many terms.

Triggered Rule

When a trigger event of a triggered rule occurs the conditions are evaluated under the rule, and then actions are taken based on the true/false outcome. Only a trigger event will cause rule evaluation, and the action will be performed irrespective of the prior rule truth (unlike a rule, above).

Actions Supported

When a rule proves true, after previously false, Rule Machine will do the actions selected on the Actions for True page. When a Rule proves false, after previously true, Rule Machine will do the actions on the Actions for False page. When a Trigger event occurs for a trigger, Rule Machine will do the actions selected on the Actions page. When a trigger event occurs for a Triggered Rule, Rule Machine will evaluate the rule and do the Actions for True or Actions for False accordingly. A Schedule does one set of Actions at the scheduled time, and optionally another set of actions some time later.

The actions supported are the following:

     		Control Switches, Capture or Restore 
     			Turn on these switches
     			Turn off these switches
     			Toggle these switches
     			Flash these switches
     			Set these switches per mode
     			Capture Devices
     			Restore Devices
     		Set Dimmers 
     			Set these dimmers
     			Toggle these dimmers
     			Adjust these dimmers
     			Set these dimmers per mode
     			Fade these dimmers over time
     			Start raising dimmers
     			Start lowering dimmers
     			Stop changing dimmers
     		Set Color or Color Temperature Bulbs 
     			Set color
     			Set color per mode
     			Set color temperature
     			Set color temperature per mode
     		Activate Scenes, Adjust Shades or Fans 
     			Activate scenes
     			Activate scenes per mode
    			Open shades
    			Close shades
     			Set shade position
     			Set fan speed
     			Adjust fans
     		Control HSM, Garage Doors, Locks or Valves 
     			Arm/Disarm Hubitat® Safety Monitor
     			Open garage door
     			Close garage door
     			Lock locks
     			Unlock locks
     			Open valves
     			Close valves
     		Control Thermostats or Thermostat Scheduler 
     			Set thermostats
     			Set Thermostat Scheduler
     		Send or Speak a Message, Send HTTP Request 
     			Send or Speak a Message
     			Send HTTP Get
     			Send HTTP Post
     		Control Music Player Sounds 
     			Control Music Player
     			Sound Tone
     			Control Siren
     		Set Mode or Global Variables, Push Buttons 
     			Set Mode
     			Set Global Variable
     			Push a button
     			Push a button per mode
     		Set Private Boolean, Run/Stop/Pause Rules 
     			Set Private Booleans True
     			Set Private Booleans False
     			Evaluate Rules
     			Run Rule Actions
     			Stop Rule Actions
     			Pause Rules
     			Resume Rules
     		Run Custom Action or Custom Command Polling 
     			Run Custom Action
     			Run Custom Command
     			Refresh devices
     			Poll devices
     			Start Z-Wave poll on switches
     			Stop Z-Wave poll on switches
     			Start Z-Wave poll on dimmers
     			Stop Z-Wave poll on dimmers
     		Delay or Repeat Actions 
     			Delay Actions
     			Delay Actions Per Mode
     			Repeat Actions
     			End Repetition
     		Conditional Actions 
     			Simple Conditional Action
     			IF (condition) THEN
     			ELSE-IF (condition) THEN
     			ELSE
     			END-IF

Note: Multiple phone numbers may be entered for SMS messages, each separated by a comma. Phone numbers must begin with +1.

Rule - Trigger Integration

One of the most powerful features of Rule Machine is the ability of Rules and Triggers to be combined to create sophisticated automations. Just as with the devices in your system, the Rules you have in Rule Machine have a state, their truth state. Both Rules and Triggers can use rule-truth as a condition or as an event. This leads to many possibilities, several of which are very useful:

A Trigger can use rule-truth as an event. When a Rule changes state, a Trigger can take actions. This integration allows you to have additional actions for each Rule. If you need more Actions for True, simply create a Trigger tied to rule-truth for that Rule becoming true, and you have additional actions available in the Trigger. For example, suppose you want one Rule to start a sequence of actions. Perhaps do one thing after 3 minutes, something else after 10 minutes, and then a final thing after 30 minutes. One Rule plus two Triggers can do this, where each Trigger is tied to the rule-truth, then has an action that it delays taking for 10, or 30 minutes; the rule itself has the action of true of doing something after 3 minutes.

A Rule can also use rule-truth as a condition. This feature allows generalized linking of Rules. One example would be to have a master set of conditions, that several Rules would need. One Rule has those conditions but no actions. The other Rules have the first rule-truth as a condition, and have whatever additional conditions they need, and take whatever actions they want. This can make repetitive rule creation much simpler, or lead to very sophisticated automations.

Both Triggers and Rules can take an action to cause a selected Rule (or Rules) to be evaluated. This would allow, for example, a button to cause a Rule to be evaluated, through the use of a Trigger tied to the button. Or, at a certain time of day, a Rule can be caused to be evaluated. The reason these things might be useful, is that ordinarily a Rule only takes action when it changes truth state. By causing a rule evaluation, the actions will be taken as selected for that Rule based on its truth, irrespective of the prior state of the rule-truth for that Rule.

Both Triggers and Rules can also cause a selected Rule or Rules to have their Actions for True run irrespective of the Rule's Conditions or Rule. This allows for triggers to share a Rule's actions, while preserving its Rule (vs. Triggered Rule) nature. It is also possible to create a Rule that has no Triggers and no Conditions, a Rule that only has Actions. Such a Rule can be run from any other Trigger or Rule as an action.

Warning: When using any of the Rule - Trigger Integration features, do not change the name of any Rule, Trigger or Actions referenced by another rule. The name of a rule is the linkage mechanism, and it is not possible to correct for a rule name change in the rules that make reference to it. Consequently, changing the name of a rule will cause all of the rules that reference that rule to be broken. Similarly, removing a rule would cause all of the rules that reference that rule to be broken.

Further Warning: It is possible with Rule-Trigger integration and Private Boolean to create rules with circular logic, possible indirect circular logic. These are doomed to fail, sometimes by falling into infinite loops. DO NOT use these features to create circularity, and be careful about the logic patterns you create by linking rules.

Custom Commands

The Custom Commands section of Rule Machine allows you to discover commands available for virtually any device, including custom device types and otherwise not supported devices. Once you've found a command you want to use, you can set parameters for it, and save it as a Custom Command. These Custom Commands can be used in Actions for any rule (Actions for True, Actions for False, Actions). Once you have saved one or more Custom Commands, the action "Run custom commands" becomes available in Actions, as the very last option.

These are some notable examples of published devices with custom capabilities:

  • Fibaro RGBW controller, all of the buttons in the device detail tile have associated custom commands.
  • Sonos and other Speaker devices, playTrackAndRestore and playTrackAndResume being two that are useful.
  • Thing Shields, every ThingShield has nothing but custom commands, you can now run these commands directly from Rule Machine.
  • Thermostats often have commands that can be useful but are otherwise not exposed in Rule Machine.
  • Multi channel relays; these can be controlled directly instead of with virtual switches.

Any device that formerly required a custom app to support could be a candidate to migrate and control using Rule Machine.

Here are a few examples in use with Rule Machine:

With custom commands, you can explore any device you have to see the commands that it offers. There are two steps required to use those commands in your rules.

  1. Create, test and save your custom command with "Tap to create Custom Commands" on the Rule Machine main page
  2. Incorporate the saved custom command into your rules with "Run custom commands"

1. Create, test and save your custom command

  • Open Rule Machine
  • Under Expert Features "Tap to create Custom Commands"
  • Select a capability for devices to test for available commands (if unsure, try Actuator)
  • Select a device of that capability to test for commands
  • Select New custom command to see the available commands, then select the command you want
  • Once selected, the command will be tested on the selected device and the results of the command execution shown
  • Add any required parameters to the command
  • After the command is executing against the device as expected, select Save command now, then Done, then Done again to return to the Custom Commands page
  • The saved custom command will now be available in your new and existing rules

2. Select the custom command to run in your rule and the devices to run it on

  • Create a new rule or edit an existing one
  • In the Actions section (at the very bottom), select Run custom command, then select the custom command (saved above) and the devices to run it on

Be sure that each device selected supports the selected command; any errors will be trapped and shown in the logs.

3. Manage custom commands
One or more custom commands can be removed by selecting them in Delete Custom Commands, then Delete commands now, then Done. You can also test saved custom commands against other devices you might select.

Tips:

  • Un-select your test device or the "saved command to test" before leaving the custom commands page, otherwise the command will execute the next time you open the page.
  • Un-Select "available device commands" after saving the new command, otherwise the command will execute the next time you open the page.
  • Un-Select "parameter type" for each of your parameters, in reverse order (ie 3,2,1) after saving the new command, this is just a convenience thing.
  • The success or failure of any parameters can't be determined by expert, use the logging in the IDE if you're having issues getting a command to function.
  • If your wizBang device isn't in the list, add capability actuator to it.

Cautions:
Using custom commands exposes commands on device types that aren't published or supported by Hubitat. When you expose these commands and play with them, you are doing so at your own risk. No one will have any sympathy when you successfully execute wipeDisk() on your new Samsung appliance and have bricked it.

Rule Machine API

It is possible for other apps to use Rules, Triggers, Triggered Rules, and Actions defined in Rule Machine. This is very similar, and uses the same mechanism, as actions in Rule Machine that affect other rules. It is also possible to use Rules, Triggers, Triggered Rules, and Actions from an HTTP request to an endpoint.

Using Rule Machine from other apps

First, import the RM helper class into your app:

`import hubitat.helper.RMUtils`

The List of Rules

Rule Machine maintains a list of available Rules, Triggers, Triggered Rules, and Actions. This list can be obtained with this method call:

    def rules = RMUtils.getRuleList()

The resulting list, in this example in the variable "rules", can be used as an input to an "enum", as the options.

Supported Actions

It is possible to set the Private Boolean, evaluate a rule, run the rule actions, or stop running rule actions (either delayed or repeating). This is accomplished by sending an action request to Rule Machine. These will each take this form:

    def RMUtils.sendAction(rules, action, appLabel)
 Set Private Boolean True:     
     action     "setRuleBooleanTrue"
 
 Set Private Boolean False:     
     action     "setRuleBooleanFalse"
 
 Evaluate Rule:
     action     "runRule"
 
 Run Rule Actions:
     action     "runRuleAct"
 
 Stop Rule Actions:
     action     "stopRuleAct"
 
 Pause Rule:
     action     "pauseRule"
 
 Resume Rule:
     action     "resumeRule"

In each case above, a list of rules selected by input is sent. The rule options come from the variable to which they were input as described above, in the options section of the input..

The "appLabel" parameter is passed and will appear in the log entry that the rule makes when it performs the action commanded. Typically, simply pass `app.label`, for the name of the app that is causing the action. This has no other function than logging.

Example:

    def rules = RMUtils.getRuleList()
    input "theseRules", "enum", title: "Select which rules to stop", options: rules
    RMUtils.sendAction(theseRules, "stopRuleAct", app.label)

Using Rule Machine from HTTP requests

It is also possible to cause Rule Machine to perform these same actions from an HTTP request. To do this one would create a Trigger or a Triggered Rule with either a Local End Point or Cloud End Point. The endpoint URL given by Rule Machine has this form:

`http://192.168.0.36/apps/api/10249/trigger?access_token=ecd95469-bbcd-4889-a694-9b05ef80f4db`

To run rule actions this URL must be modified to include the list of rules and the action. The modification takes this form:

`/action=rule1&rule2&rule3`

Where action is the action from the list above and `rule1&rule2&rule3` are the appIds of the rules to run separated by ampersands.

This parameter is inserted in the endpoint URL just before the ? that precedes the access_token, like this:

`http://192.168.0.36/apps/api/10249/trigger/stopRuleAct=943&956&10217?access_token=ecd95469-bbcd-4889-a694-9b05ef80f4db`

This example would do the same thing as the code example above, where 943&956&10217 are the appIds that were selected by consequence of the input for theseRules, and stopRuleAct is the action to perform.

The appIds are the values selected by the input described above, for example `theseRules`. The appIds can also be found for a rule by opening the rule and observing its appId in its url, like this:

`http://192.168.0.36/installedapp/configure/10249/mainPage`

The appId for that rule is 10249.

Get Rule List

To get the list of rules as is returned from `getRuleList()` use this insert for the URL:

`/getRuleList`

for full URL like this:

`http://192.168.0.36/apps/api/10249/trigger/getRuleList?access_token=ecd95469-bbcd-4889-a694-9b05ef80f4db`

This returns a JSON object with appId and rule name pairs. The other requests return a JSON object with a human readable description of what was done.

Set Global Variable

A Global Variable can be set by an endpoint trigger. The format for the parameter is this:

`/setGlobalVariable=varName:varString`

The `varString` portion is assumed to be URL encoded, and is URL decoded before being stored into the `varName` global variable.



Note: Rule Machine actions Stop Rule Actions, Pause Rule and Resume Rule only work for Rule 2.5 or later. Rule Machine action Set Global Variable only works for Rule 3.0 or later.

Dedication

Rule Machine is dedicated to Alan Turing. He gave us the concept of an abstract machine that could compute, and from that we built small implementations of his vision. Today, we all use them every day of our lives.

More Information

See [this post](https://community.hubitat.com/t/what-is-the-best-way-to-know-what-hubitat-can-and-cant-do/2143/23) for a mini-tutorial on Rule-Trigger Integration and Private Boolean.