# Rule Machine® Introduction

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 conditions and 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 for Rules, Triggers, Triggered Rules and Actions

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.

The actions supported are the following:

Delay these actions by minutes, seconds, or milliseconds, with optional cancel on change, or random time
Switches to turn on
Switches to turn off
Switches to toggle
Switches to turn on or off after a delay
Switches to turn on or off after a delay, pending cancellation
Button to push
Button to push per mode
Capture switches state
Restore switches state, with optional delay, cancellable
Dimmers to level A, or to track event dimmers
Dimmers to level B
Dimmers to toggle
Dimmers to level per mode
Set color temperature
Set colors
Fan to adjust — low, medium, high, off
Open garage door
Close garage door
Locks to lock
Locks to unlock
Valves to open
Valves to close
Thermostats to set
Set Hubitat Safety Monitor state
Send or speak message, push, notification or SMS, with triggering device name
Change mode
Take photos
Control music player
Beep tone device
Set Private Boolean for this Rule or other Rule, with optional delay, cancellable
Evaluate Rules
Run Rule actions
Update Rules
Custom commands (see below)

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:

• softwhite() and deepfade() on an Fibaro RGBW controller that uses @twack device type
• playTrackAndRestore('https://s3.amazonaws.com/smartthingssmartapps/Boss+is+arriving.mp3',6,30) on a Samsung Speaker
• fanOff() on a custom AEON dual switch device by @Mike_Maxwell

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.

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

See this post for a mini-tutorial on Rule-Trigger Integration and Private Boolean.

11 Likes

## Rule Machine®Version 2.5

There are a number of updates to Rule Machine. These fixes and new features will not be available in existing rules, only in new rules. Any old rules will continue to run on the prior version of Rule Machine. If you are affected by any of these changes, you will need to redo the rule with this new version, Version 2.5.

Removal of Limitations

Prior limitations on the number of Time of Day, Days of Week and Mode conditions for a rule have been removed. Similarly, prior limitations on the number of Certain Time, Mode and Periodic events for triggers have been removed. It is now possible to have any number of such conditions in a rule or events for a trigger.

Previously, Private Boolean for other rules could only be set to true or false, but not separately for different rules. Now it is possible to set some rules to true and others to false.

New Features

Repeat Actions and Stop Actions
There are two new actions, one to Repeat These Actions, and the other to Stop Actions. The first allows a rule to begin a repetition of its actions for true or false, with the repetition optionally being stopped upon truth change. The second allows a rule to stop the actions of another rule or trigger, including delayed actions, repeated actions, periodic triggers and fade dimmers over time.

Cloud and Local Endpoints
It is now possible to use a cloud or local endpoint as an event in a trigger. Choosing this event selection will create the corresponding URL, which may be copied for use elsewhere. Hitting that URL will fire the trigger.

Refined UI Layout
The UI for actions has been cleaned up to more clearly distinguish groups of related actions. Come actions selection pages have been reorganized for clarity.

Bug Fix

A reported bug with using hsmStatus as a trigger as been fixed. Previously, such a trigger fired indiscriminately without testing for the correct value.

5 Likes

@bravenel did the ability to set another rules private boolean state change? I don't see this as an option anymore?

It's still there.

OK, looks like if the rule is created in RM 2.5 it can only set boolean for rules also created using RM 2.5?

Ah, yes, that is true. We can fix this in a hot fix release soon. However, in the meantime, redo the rule you want to hit into 2.5. An oversight -- my bad.

Thanks, was just re-doing a couple of rules to use the new nest integration and noticed it. I do like the new UI though, much improved!

I can no longer view or edit (or delete) rules created with pre-2.5. Is that expected?

It's a mistake. Will be fixed soon. In the meantime you would have to re-enter those rules with 2.5.

I don't mind recreating rules, but I don't want to do that if I can't remove the old ones. I suppose I could remove RM entirely and set everything up from scratch, but I have so many rules...

We are going to push out a fix tomorrow. So just sit tight?

You can remove old rules. I've tested the fix and all will be good.

Awesome. Thanks!

Will the hotfix allow editing and continued use of old rules, or must we still delete and rebuild?

You should be able to edit the old ones.

1 Like

D'oh, so one issue I had initially wasn't necessarily that RM could edit legacy rules, but that clicking a link didn't actually open the proper config URL (I wasn't paying close enough attention).

What happens is this: I mouse over a RM rule link and I see the proper URL in the status bar, like `http://10.0.1.99/installedapp/configure/545`. If I inspect the DOM the link address looks fine. However, when I click the link I'm directed to `http://10.0.1.99/installedapp/configure/1`, which sends me to the "create a rule" view. Clicking the status link (`http://10.0.1.99/installedapp/status/545`) also sends me to `/configure/1`.

This only happens in desktop Safari. It's happened with other parts of the UI before, but currently I'm only seeing this particular issue (redirecting to a `/1` resource) with RM apps.

There is a known issue with safari that causes this issue. Right clicking on the link is a work around for now.

That fix is available. Check it out.

1 Like

Ah, good to know.

I installed the update and I can now edit and remove legacy rules. Yay!

You're talking about from within actions that reference other rules, right?