Presence Simulation [4.0.0.0;4.9.9.9]

logo

Warning: If you’ve installed this template prior to OH 4.2 M3, you will need to remove and re-add the templated from the add-on store and then instantiate the rule to pick up the changes that lets the template work with the breaking changes introduced in 4.2 M3.

Simulates presence by playing back Item states from the default persistence from a number of days ago commanding the devices so they behave the same way, simulating presence.

Parameter Type Purpose
Enable Simulation Switch Item Switch Item which, when OFF, will trigger the simulator rule to run. OFF was chosen to make it easier to tie the rule to an Item that tracks presence.
Simulation Items Group Group Item Group whose members are those Items that should be included in the presence simulation. All these Items must support commands (e.g. no Contact Items) and their states must be saved by the default persistence (e.g. no String Items if using rrd4j).
Num Days integer The number of days in the past to simulate the behavior from. It’s best to choose a multiple of 7 to correctly capture different behaviors between work days and weekends.
Minutes integer How many minutes between runs of the rule.

This template is a rewrite of the version written for 3.x to take advantage of new features built into OH 4 and to use JS Scripting.

Language: JS Scripting Scripting with openhab-js 4.0

Dependencies:

  • Persistence is installed and configured and the default persistence saves the states of the Items that are to be simulated.
  • openhab-js 4.1.0 or later
  • openhab_rules_tools 2.0.1 or later

Changelog

Version 1.0

  • Updates to work with breaking changes in openhab-js 5.0.0. The template remains backwards compatible with openhab-js 4.1.0 forward.

Version 0.2

  • throws an exception if openhab-js or openhab_rules_tools is too old

Version 0.1

  • initial release

Sponsorship

If you want to send a tip my way or sponsor my work you can through Sponsor @rkoshak on GitHub or PayPal. It won’t change what I contribute to OH but it might keep me in coffee or let me buy hardware to test out new things.

Resources

https://raw.githubusercontent.com/rkoshak/openhab-rules-tools/main/rule-templates/presenceSim/presence_sim2.yaml

3 Likes

@rlkoshak : maybe this a stupid question: How are the parameters setup and initialised in the UI?

As with all rule templates:

  1. Navigate to Settings → Automation
  2. Select the rule template to install and click “add”
  3. Navigate to Settings → Rules and click + to create a new rule
  4. Choose the rule template to base the rule off of
  5. Fill in the parameters

Thanks for the fast reply.
There are no Rule Templates in Settings → Automation. Even after applying the procedure described here: Section 'Rule Templates' missing in Automation - #5 by Mav63
Any other suggestion?

If you have JS Scripting installed and Settings → Community Marketplace enabled you should see rule templates in Settings → Automation.

Unfortunately there are no rule templates in Settings → Automation with Settings → Community Marketplace enabled.

But I got a suspicious entry in openhab.log on restart:

> 2023-08-04 07:22:38.041 [INFO ] [rketplace.MarketplaceBundleInstaller] - Reinstalling missing marketplace bundle: marketplace:130488
> 2023-08-04 07:22:40.143 [INFO ] [org.openhab.core.Activator          ] - Starting openHAB 4.0.1 (build Release Build)
> 2023-08-04 07:24:51.623 [WARN ] [ity.CommunityMarketplaceAddonService] - Unable to retrieve marketplace add-ons: Connection timed out

How could this be addressed?

Open a new thread to go over what ever the problem is with installing the marketplace. Fixing that is outside the scope of this thread and I have no idea what the problem can be.

I use OH 4.0.2 and just see this rule template to install when I enable unpublished Add-Ons in Community Marketplace Add-Ons. And then I get a warning if I really want to install.

Is it safe to install and use? Installed openhab-js version is 4.0.2

Thanks for the heads up. I forgot to add then “published” tag. It should show up properly now.

is there a logfile where i see what presence simulation is doing? shoud changes be logged in event.log ?

You should be seeing commands and where applicable changes in events.log.

There is very little logging in the rule itself. There’s a debug if the rule decides not to command the Item if it’s already in the desired state and a warning level log if there is no data in persistence to play back.

You can change the logging level of the rule in all the usual ways or by editing the Script Action to change line 4 and uncommenting it out. You can also add additional log statements or make any other changes desired.

I did create the following script:

-------Code Start-------------
configuration:
days: 7
simItems: ALW
enableSim: ALW
minutes: 5
triggers:

  • id: “1”
    configuration:
    cronExpression: 0 0/5 * * * ? *
    type: timer.GenericCronTrigger
    conditions:

  • inputs: {}
    id: “2”
    configuration:
    itemName: ALW
    state: ON
    operator: “!=”
    type: core.ItemStateCondition
    actions:

  • inputs: {}
    id: “3”
    configuration:
    type: application/javascript
    script: >-
    // Version 0.2

    var {helpers} = require('openhab_rules_tools');
    
    console.loggerName = 'org.openhab.automation.rules_tools.Presence Sim';
    
    // osgi.getService('org.apache.karaf.log.core.LogService').setLevel(console.loggerName, 'DEBUG');
    
    
    helpers.validateLibraries('4.1.0', '2.0.1');
    
    
    items.ALW.members.forEach((i) => {
    
      const hState = i.history.historicState(time.toZDT().minusDays(7));
      if(hState === undefined || hState === null) {
        console.warn(i.name + ' does not have a historic state for ' + '7' + ' days ago');
      }
      else {
        console.debug('Commanding ' + i.name + ' to ' + hState.state);
        if(i.state != hState.state) {
          i.sendCommand(hState.state.toString());
        }
        else {
          console.debug(i.name + ' is already ' + hState.state);
        }
      }
    });
    

    type: script.ScriptAction

-------Code Stop-------------

Idea was to use a presence rule when ALW (which is a group for living room lamps) is not on.

Nothing currently happened since I activated this rule.

To activate logging I did set org.openhab.automation.rules_tools.Presence to DEBUG Level is that correct?

I just did found out in openhab.log, that I get this error when to rule tries to start.

2023-09-16 17:55:00.292 [ERROR] [internal.handler.ScriptActionHandler] - Script execution of rule with UID ‘cc3bac37a8’ failed: org.graalvm.polyglot.PolyglotException: TypeError: invokeMember (getMembers) on org.openhab.core.library.items.SwitchItem@183530b failed due to: Unknown identifier: getMembers
2023-09-16 18:00:00.277 [ERROR] [b.automation.script.javascript.stack] - Failed to execute script:
org.graalvm.polyglot.PolyglotException: TypeError: invokeMember (getMembers) on org.openhab.core.library.items.SwitchItem@183530b failed due to: Unknown identifier: getMembers
at .get members(@openhab-globals.js:2) ~[?:?]

Any ideas what I’m doing wrong?

ALW isn’t a Group, it’s just a Switch.

The Items to control must be in a Group and a Group is required for “Simulation Items Group”.

Thanks for the nice template as always.

However how can the persistence service be specified in the rule if it is different than the default?
Perhaps this can be added to the rule parameters?

In the coming days I’ll add that as a parameter.

In the mean time change the following line:

const hState = i.history.historicState(time.toZDT().minusDays(7));

to

const hState = i.history.historicState(time.toZDT().minusDays(7), "rrd4j");

Note, the number will be what you configured when you created the rule and may be different from 7. And use the name of the persistence you want to use if it’s not rrd4j.

Many thanks
Precise as always

Hi there, A simple simple but very effective script, thanks a lot!

I have one question: The script currently seems to interact with another functionality I had planned ina funny way: I wanted to implement a rule that, when I activate any of our PNX touch sensors, switches the house to the “People present” state. (We have a dedicated touch button for that, too, but my wife often forgets to press it. And we have no presence sensors.)

Now with the presence simulation active, that rule would mistake the trigger from that simulation script for an activation through the touch sensor, Thus I wonder: is there any way for a script to figure out where a state update was sent from? E.g. can I figure out whether it came from the KNX binding or your presence simulation script? Or could I extend the script to piggyback some metadata into the state update that would carry over that information?

Happy holidays!

Only indirectly. See Design Pattern: Manual Trigger Detection. The proxy item approach is probably best for this situation.

Sorry, if this is a stupid question, but I get the following error with this template:

2024-05-24 11:24:24.613 [ERROR] [internal.handler.ScriptActionHandler] - Script execution of rule with UID 'PresenseSimulationRule' failed: org.graalvm.polyglot.PolyglotException: TypeError: Cannot load CommonJS module: 'openhab_rules_tools'

Where do I get this missing module from?

I have a OpenHAB 4.1.2 docker installation.

Thanks in advance

Michael