Switch and Dimmers Rule [5.x]

Description
This script allows you to unify the control of light through switches without making changes to the script every time you need to change the assignment of switches and target lamps. It can also run rules/scenes and send fixed commands from buttons — so one button can combine light toggling (short press) with a scene trigger (hold) or any custom action.

Language:
“ECMAScript 262 Edition 11 (application/javascript; version=ECMAScript-2021)”

Dependencies:

  • Javascript Automation Add-in (ECMA2011)
  • Latest openhab-js installed
  • Buttons configured as Switches or Contacts (see “switchState” variable below) with custom metadata (read further)

Resources

uid: lazygatto:switch_and_dimmers
label: Switch and Dimmers Rule
description: >
    Control lights from wall switches/buttons with metadata-driven bindings: single/double/triple
    presses, hold-to-dim with previous-level restore, hold actions, fixed commands and rule/scene
    triggers (linkedItem / linkedOn / linkedOff / linkedRule / holdRule metadata). Drop-in
    compatible with the original rule and with community extensions.
configDescriptions:
    - name: switchesGroup
      type: TEXT
      context: item
      filterCriteria:
          - name: type
            value: Group
      label: Switches Group
      required: true
      description: Group Item that holds all the switches/contacts.
    - name: sceneGroup
      type: TEXT
      context: item
      filterCriteria:
          - name: type
            value: Group
      label: Scene Switch Group (optional)
      required: false
      defaultValue: gSceneSwitches
      description: >
          Group for command-driven scene switches: a command ON evaluates the linkedOn
          metadata, OFF evaluates linkedOff. If you do not use scene buttons, keep the default.
    - name: delayMulti
      type: INTEGER
      label: Short Press Delay (ms)
      description: Window used to detect multiple presses. Also the hold threshold.
      defaultValue: 500
      required: true
    - name: debounceMs
      type: INTEGER
      label: Contact Debounce (ms)
      description: Drop re-triggers closer than this. Useful for press&release contacts (0 = off).
      defaultValue: 0
      required: true
    - name: delayDimStep
      type: INTEGER
      label: Dimmer Steps Delay (ms)
      description: Pause between dim steps while holding.
      defaultValue: 100
      required: true
    - name: dimStep
      type: INTEGER
      label: Dimmer Step Size
      description: Level change per dim step.
      defaultValue: 2
      required: true
    - name: minDim
      type: INTEGER
      label: Minimum Dim Level
      description: Lower limit of hold-dimming.
      defaultValue: 5
      required: true
    - name: switchStateON
      type: TEXT
      label: Switch State ON
      description: "'ON' for Switch items, 'CLOSED' for Contact items."
      defaultValue: CLOSED
      required: true
    - name: switchStateOFF
      type: TEXT
      label: Switch State OFF
      description: "'OFF' for Switch items, 'OPEN' for Contact items."
      defaultValue: OPEN
      required: true
    - name: p2p3FallbackToMain
      type: BOOLEAN
      label: Unconfigured p2/p3 Falls Back To Main
      description: >
          When true, double/triple presses without configured p2/p3 toggle the main item.
          When false (original behaviour), nothing happens.
      defaultValue: false
      required: false
triggers:
    - id: "1"
      configuration:
          groupName: "{{switchesGroup}}"
          previousState: "{{switchStateOFF}}"
          state: "{{switchStateON}}"
      type: core.GroupStateChangeTrigger
    - id: "2"
      configuration:
          groupName: "{{sceneGroup}}"
      type: core.GroupCommandTrigger
actions:
    - inputs: {}
      id: "3"
      configuration:
          type: application/javascript
          script: |-
              /*

              Switch and Dimmers Rule — v1.0 (unified)

              The MIT License (MIT)
              Copyright © 2023–2026 LazyGatto (https://community.openhab.org/u/lazygatto)
              Extensions (action model, linkedOn/linkedOff, linkedRule) © 2026 PeterK
              (https://community.openhab.org/t/switch-and-dimmers-rule-3-4-4-4-0-4/146842),
              based on Felix Krämer script
              https://community.openhab.org/t/multi-press-and-hold-to-dim-js-script-for-thing-buttons/144589

              Drop-in replacement compatible with:
                - original v0.2/v0.3 metadata:  linkedItem (value + p2/p3/hold)
                - PeterK extension:             linkedItem.config.action = toggle|runRule|command,
                                                config.command, linkedOn / linkedOff (state-dependent),
                                                linkedRule (value or config.ruleUID)
                - v1.0 addition:                linkedItem.config.holdRule = UID of rule/scene to run
                                                on hold of a switch button (e.g. scenes on hold)

              Requirements: JS Scripting (GraalJS), openhab-js. No external modules.

              Metadata cheat-sheet:

                linkedItem:
                  value: <main item name>            # or rule/scene UID when action=runRule
                  config:
                    action: toggle | runRule | command   # default: toggle
                    command: <fixed command>             # for action=command
                    p2: <item>   p3: <item>              # double/triple press (toggle)
                    hold: <item>                         # hold for switch items (toggle)
                    holdRule: <rule or scene UID>        # hold for switch items (run rule) — v1.0

                linkedOn / linkedOff:                    # state-dependent actions
                  value: <item name or rule/scene UID>
                  config:
                    action: runRule | command | toggle   # default: runRule
                    command: <fixed command>

                linkedRule:
                  value: <rule UID>                      # (or config.ruleUID)

              TEMPLATE PARAMS (replaced on marketplace publish):
                {{switchesGroup}}, {{sceneGroup}}, {{delayMulti}}, {{debounceMs}},
                {{delayDimStep}}, {{dimStep}}, {{minDim}}, {{switchStateON}}, {{switchStateOFF}},
                {{p2p3FallbackToMain}}
              */

              // ==== Configuration (template params) ====
              var delayMulti = {{delayMulti}};    // ms, window for counting multiple presses (hold threshold)
              var debounceMs = {{debounceMs}};      // ms, drop re-triggers closer than this (MegaD P&R: 150)
              var delayDimStep = {{delayDimStep}};  // ms, pause between dim steps
              var dimStep = {{dimStep}};         // dim step per iteration
              var minDim = {{minDim}};          // minimum dim level
              var dimMaxTicks = 60;    // hard cap of dim iterations (~6 s) — runaway guard
              var dimBlinkLow = 30;    // dip level when hitting the UPPER limit
              var dimBlinkHigh = 12;   // flash level when hitting the LOWER limit
              var p2p3FallbackToMain = {{p2p3FallbackToMain}}; // true: unconfigured p2/p3 fall back to main toggle
              var switchState = {
                ON: '{{switchStateON}}',  // 'ON' for Switch items, 'CLOSED' for Contact items
                OFF: '{{switchStateOFF}}'    // 'OFF' for Switch items, 'OPEN' for Contact items
              };
              var NS_ITEM = 'linkedItem';
              var NS_ON = 'linkedOn';
              var NS_OFF = 'linkedOff';
              var NS_RULE = 'linkedRule';
              var LOG_PREFIX = '[SwitchDim] ';
              // ==== END Configuration ====

              console.loggerName = 'org.openhab.automation.script.switchanddimmers';

              function sdMain() {

                // --- which button fired (triggeringItem in UI/file rules, event in REST rules) ---
                var btnName = null;
                try {
                  if (typeof triggeringItem !== 'undefined' && triggeringItem) btnName = String(triggeringItem.name);
                } catch (e) { /* not injected in this context */ }
                if (!btnName) {
                  try {
                    if (typeof event !== 'undefined' && event && event.itemName) btnName = String(event.itemName);
                  } catch (e) { /* no event either */ }
                }
                if (!btnName) {
                  console.error(LOG_PREFIX + 'no item name in trigger context, exit');
                  return;
                }

                var isCommand = false;
                var cmdText = null;
                try {
                  if (typeof event !== 'undefined' && event && event.itemCommand) {
                    isCommand = true;
                    cmdText = String(event.itemCommand);
                  }
                } catch (e) { /* state trigger */ }

                // --- helpers (fresh wrappers only; cache keeps names/scalars — see v0.3 notes) ---
                function liveItem(name) {
                  try { return items.getItem(name); } catch (e) { return null; }
                }
                function liveLevel(item) { var v = Number(item.state); return isNaN(v) ? 0 : v; }
                function isDimmerItem(item) {
                  var t = String(item && item.type);
                  return t === 'Dimmer' || t === 'DimmerItem' || t === 'Color' || t === 'ColorItem';
                }

                function runRuleUID(uid, source) {
                  if (!uid) { console.warn(LOG_PREFIX + 'no rule UID for ' + source); return; }
                  try {
                    rules.runRule(String(uid), {});
                    console.log(LOG_PREFIX + 'run rule ' + uid + ' (from ' + source + ')');
                  } catch (e) {
                    console.warn(LOG_PREFIX + 'runRule ' + uid + ' failed: ' + e);
                  }
                }

                function toggleItem(name, stor) {
                  var itemObj = liveItem(name);
                  if (!itemObj) return;
                  var st = String(itemObj.state);
                  var stateToSet = null;
                  if (st === 'OFF') {
                    stateToSet = 'ON';
                  } else if (isDimmerItem(itemObj)) {
                    var lv = liveLevel(itemObj);
                    if (lv === 0) {
                      var prev = (stor && stor.prevLevel) ? stor.prevLevel : null;
                      stateToSet = (prev && prev > 0 && prev <= 100) ? prev : 100;
                    } else {
                      if (stor && lv > 0 && lv <= 100) {
                        stor.prevLevel = lv;
                        cache.private.put(stor.cacheId, stor);
                      }
                      stateToSet = 'OFF';
                    }
                  } else {
                    stateToSet = 'OFF';
                  }
                  console.log(LOG_PREFIX + 'toggle ' + itemObj.name + ' -> ' + stateToSet);
                  itemObj.sendCommand(stateToSet);
                }

                function doCommand(name, command, stor) {
                  if (command === undefined || command === null) {
                    console.warn(LOG_PREFIX + 'no command configured for ' + name);
                    return;
                  }
                  var itemObj = liveItem(name);
                  if (!itemObj) return;
                  console.log(LOG_PREFIX + 'send ' + command + ' to ' + name);
                  itemObj.sendCommand(command);
                }

                // PeterK v2 semantics: linkedOn/linkedOff/linkedRule default action is runRule
                function parseActionMeta(meta) {
                  if (!meta) return null;
                  var c = meta.configuration || {};
                  return {
                    action: (c.action !== undefined && c.action !== null && String(c.action) !== '')
                      ? String(c.action) : 'runRule',
                    value: meta.value ? String(meta.value) : null,
                    command: (c.command !== undefined && c.command !== null) ? String(c.command) : null
                  };
                }

                function executeMetadataAction(cfg, source) {
                  if (!cfg) return false;
                  if (cfg.action === 'runRule') { runRuleUID(cfg.value, source); return true; }
                  if (!cfg.value) { console.warn(LOG_PREFIX + 'no target for ' + source); return false; }
                  if (cfg.action === 'command') { doCommand(cfg.value, cfg.command, null); return true; }
                  toggleItem(cfg.value, null);
                  return true;
                }

                function executePrimary(stor) {
                  if (!stor.hasMain) return;
                  if (stor.mainAction === 'runRule') { runRuleUID(stor.mainTarget, stor.switchName); return; }
                  if (stor.mainAction === 'command') { doCommand(stor.mainTarget, stor.mainCommand, stor); return; }
                  toggleItem(stor.mainTarget, stor);
                }

                function shortPressAction(stor) {
                  switch (stor.pressCount) {
                    case 1:
                      executePrimary(stor);
                      if (stor.linkedRuleUID) runRuleUID(stor.linkedRuleUID, stor.switchName + ':linkedRule');
                      executeMetadataAction(stor.onAction, stor.switchName + ':linkedOn');
                      break;
                    case 2:
                      if (stor.p2Name) toggleItem(stor.p2Name, stor);
                      else if (p2p3FallbackToMain) toggleItem(stor.mainTarget, stor);
                      else console.log(LOG_PREFIX + 'no action for 2 presses on ' + stor.switchName);
                      break;
                    case 3:
                      if (stor.p3Name) toggleItem(stor.p3Name, stor);
                      else if (p2p3FallbackToMain) toggleItem(stor.mainTarget, stor);
                      else console.log(LOG_PREFIX + 'no action for 3 presses on ' + stor.switchName);
                      break;
                    default:
                      if (p2p3FallbackToMain) toggleItem(stor.mainTarget, stor);
                      else console.log(LOG_PREFIX + 'no action for ' + stor.pressCount + ' presses on ' + stor.switchName);
                  }
                }

                function resetStorage(stor) {
                  stor.btnTimer = null;
                  stor.pressCount = 0;
                  stor.dimTimer = null;
                  stor.dimTicks = 0;
                  stor.blink = null;
                  cache.private.put(stor.cacheId, stor);
                }

                function dimItem(stor) {
                  var linked = liveItem(stor.mainTarget);
                  var btn = liveItem(stor.switchName);
                  if (!linked || !btn) { resetStorage(stor); return; }

                  // limit-feedback phase (three dips/flashes): plays out fully, release ignores
                  if (stor.blink) {
                    if (stor.blink.i < stor.blink.seq.length) {
                      linked.sendCommand(stor.blink.seq[stor.blink.i]);
                      stor.blink.i++;
                      cache.private.put(stor.cacheId, stor);
                      if (stor.dimTimer) stor.dimTimer.reschedule(time.toZDT(delayDimStep));
                      else { stor.blink = null; resetStorage(stor); }
                      return;
                    }
                    stor.blink = null;
                    resetStorage(stor);
                    return;
                  }

                  if (String(btn.state) === switchState.OFF) { resetStorage(stor); return; }

                  stor.dimTicks++;
                  if (stor.dimTicks > dimMaxTicks) {
                    console.log(LOG_PREFIX + linked.name + ': dim tick limit reached, stop');
                    resetStorage(stor);
                    return;
                  }

                  var cur = liveLevel(linked);
                  var dimToSet;
                  if (stor.dimUp === true) {
                    dimToSet = cur + dimStep;
                    if (dimToSet >= 100) {
                      linked.sendCommand(100);
                      stor.blink = { seq: [dimBlinkLow, 100, dimBlinkLow, 100, dimBlinkLow, 100], i: 0 };
                      cache.private.put(stor.cacheId, stor);
                      if (stor.dimTimer) stor.dimTimer.reschedule(time.toZDT(delayDimStep));
                      return;
                    }
                  } else {
                    dimToSet = cur - dimStep;
                    if (dimToSet <= minDim) {
                      linked.sendCommand(minDim);
                      stor.blink = { seq: [dimBlinkHigh, minDim, dimBlinkHigh, minDim, dimBlinkHigh, minDim], i: 0 };
                      cache.private.put(stor.cacheId, stor);
                      if (stor.dimTimer) stor.dimTimer.reschedule(time.toZDT(delayDimStep));
                      return;
                    }
                  }
                  linked.sendCommand(dimToSet);
                  if (stor.dimTimer) stor.dimTimer.reschedule(time.toZDT(delayDimStep));
                }

                function getPressCountTimer(stor) {
                  var btn = liveItem(stor.switchName);
                  if (!btn) { resetStorage(stor); return; }

                  if (String(btn.state) === switchState.OFF) { // short press
                    shortPressAction(stor);
                    resetStorage(stor);
                    return;
                  }

                  // hold
                  console.log(LOG_PREFIX + 'hold ' + stor.switchName + ' (main=' + stor.mainTarget + ', action=' + stor.mainAction + ')');
                  resetStorage(stor);

                  if (!stor.hasMain) {
                    if (stor.linkedRuleUID) runRuleUID(stor.linkedRuleUID, stor.switchName + ':linkedRule');
                    executeMetadataAction(stor.onAction, stor.switchName + ':linkedOn');
                    return;
                  }
                  if (stor.mainAction === 'runRule') {
                    runRuleUID(stor.mainTarget, stor.switchName);
                    if (stor.linkedRuleUID) runRuleUID(stor.linkedRuleUID, stor.switchName + ':linkedRule');
                    executeMetadataAction(stor.onAction, stor.switchName + ':linkedOn');
                    return;
                  }
                  if (stor.mainAction === 'command') {
                    doCommand(stor.mainTarget, stor.mainCommand, stor);
                    if (stor.linkedRuleUID) runRuleUID(stor.linkedRuleUID, stor.switchName + ':linkedRule');
                    executeMetadataAction(stor.onAction, stor.switchName + ':linkedOn');
                    return;
                  }

                  var linked = liveItem(stor.mainTarget);
                  if (!linked) { resetStorage(stor); return; }

                  if (isDimmerItem(linked)) {
                    var cur = liveLevel(linked);
                    if (cur > 90) stor.dimUp = false;
                    else if (cur < 10) stor.dimUp = true;
                    else stor.dimUp = !stor.dimUp;
                    stor.dimTimer = actions.ScriptExecution.createTimer(stor.dimTimerId, time.toZDT(), function () { dimItem(stor); });
                    cache.private.put(stor.cacheId, stor);
                  } else {
                    // switch: holdRule (v1.0) -> hold item (legacy) -> main
                    if (stor.holdRuleUID) runRuleUID(stor.holdRuleUID, stor.switchName + ':holdRule');
                    else if (stor.holdName) toggleItem(stor.holdName, stor);
                    else toggleItem(stor.mainTarget, stor);
                  }
                }

                // --- command path (scene group: ON -> linkedOn, OFF -> linkedOff) ---
                if (isCommand) {
                  if (cmdText !== switchState.ON && cmdText !== switchState.OFF) {
                    console.debug(LOG_PREFIX + 'ignore command ' + cmdText + ' on ' + btnName);
                    return;
                  }
                  var ns = (cmdText === switchState.OFF) ? NS_OFF : NS_ON;
                  var btnItem = liveItem(btnName);
                  if (!btnItem) return;
                  var cfg = parseActionMeta(items.metadata.getMetadata(btnItem, ns));
                  if (!cfg) { console.debug(LOG_PREFIX + btnName + ': no ' + ns + ' metadata'); return; }
                  console.log(LOG_PREFIX + 'command ' + cmdText + ' on ' + btnName + ' -> ' + ns);
                  executeMetadataAction(cfg, btnName + ':' + ns);
                  return;
                }

                // --- state path (taster press): act only on press (fresh state == ON) ---
                var btn = liveItem(btnName);
                if (!btn) return;
                if (String(btn.state) !== switchState.ON) return;

                var liMeta = items.metadata.getMetadata(btn, NS_ITEM);
                var onMeta = items.metadata.getMetadata(btn, NS_ON);
                var ruleMeta = items.metadata.getMetadata(btn, NS_RULE);
                if (!liMeta && !onMeta && !ruleMeta) {
                  // coexistence guard: item is not ours (e.g. handled by another script) — stay silent
                  console.debug(LOG_PREFIX + btnName + ': no linkedItem/linkedOn/linkedRule metadata, skip');
                  return;
                }

                var cacheId = 'sd1_' + btnName;
                var mainName = null, mainAction = 'toggle', mainCommand = null;
                var p2Name = null, p3Name = null, holdName = null, holdRuleUID = null;
                var liConfig = (liMeta && liMeta.configuration) ? liMeta.configuration : {};
                if (liMeta && liMeta.value) {
                  mainName = String(liMeta.value);
                  mainAction = (liConfig.action !== undefined && liConfig.action !== null && String(liConfig.action) !== '')
                    ? String(liConfig.action) : 'toggle';
                  mainCommand = (liConfig.command !== undefined && liConfig.command !== null) ? String(liConfig.command) : null;
                  if (liConfig.p2) p2Name = String(liConfig.p2);
                  if (liConfig.p3) p3Name = String(liConfig.p3);
                  if (liConfig.hold) holdName = String(liConfig.hold);
                  if (liConfig.holdRule) holdRuleUID = String(liConfig.holdRule);
                }

                var stor = cache.private.get(cacheId, function () {
                  return {
                    cacheId: cacheId,
                    switchName: btnName,
                    btnTimer: null,
                    pressCount: 0,
                    dimTimer: null,
                    dimTimerId: btnName + '_dimTimerId',
                    dimUp: false,
                    lastPressMs: 0,
                    prevLevel: null,
                    dimTicks: 0,
                    blink: null
                  };
                });
                // metadata may change between presses — always re-sync
                stor.switchName = btnName;
                stor.hasMain = !!mainName;
                stor.mainTarget = mainName;
                stor.mainAction = mainAction;
                stor.mainCommand = mainCommand;
                stor.p2Name = p2Name;
                stor.p3Name = p3Name;
                stor.holdName = holdName;
                stor.holdRuleUID = holdRuleUID;
                stor.onAction = parseActionMeta(onMeta);

                // linkedRule (PeterK v1): rule to run in addition to primary action
                stor.linkedRuleUID = null;
                if (ruleMeta) {
                  var rc = ruleMeta.configuration || {};
                  stor.linkedRuleUID = (rc.ruleUID !== undefined && rc.ruleUID !== null) ? String(rc.ruleUID)
                    : (ruleMeta.value ? String(ruleMeta.value) : null);
                }

                // debounce (MegaD press&release sends event bursts)
                var now = Date.now();
                if (stor.lastPressMs && (now - stor.lastPressMs) < debounceMs) {
                  cache.private.put(cacheId, stor);
                  return;
                }
                stor.lastPressMs = now;
                stor.pressCount++;

                if (stor.btnTimer !== null) clearTimeout(stor.btnTimer);
                stor.btnTimer = setTimeout(function () { getPressCountTimer(stor); }, delayMulti);
                cache.private.put(cacheId, stor);
              }

              try { sdMain(); } catch (e) { console.error('[SwitchDim] ' + e); }
      type: script.ScriptAction

Settings

It is necessary to place all switches in one group.

The script supports switches and dimmers. The detection occurs automatically, according to the type of lighting element (SwitchItem or DimmerItem).

Then you have to enter custom metadata for you switch Item, called linkedItem (see the Examples section at the bottom of this post).

Where properties in config section

  • value - main linked Item.
  • p2 - item to action with while 2 presses detected.
  • p3 - item to action with while 3 presses detected.

Property value is mandatory, while other configuration is optional.

If main linked Item, specified in value field, is DimmerType Item, then item specified in hold property will be ignored, because hold action used to control dimmerType.

Main target actions

The main linked target can be more than a simple toggle — the action property in the config section changes how value is treated:

  • action: toggle (default) — switch the Item (value) on/off.
  • action: runRule — run a rule or a scene; value must be the rule/scene UID.
  • action: command — send a fixed command to the Item (value); the command itself is set by the command property.

State-dependent actions: linkedOn / linkedOff

In addition to linkedItem you can define linkedOn and/or linkedOff metadata: linkedOn is evaluated when the switch turns ON (or receives an ON command), linkedOff — for OFF. Each behaves as a standalone action:

  • action: runRule (default here) — run rule/scene, value = rule UID.
  • action: command — send a fixed command, value = item name.
  • action: toggle — toggle the item, value = item name.

linkedRule

Alternative way to run a rule on single press / hold (kept for compatibility with earlier versions) — see Examples below.

holdRule

Run a rule/scene on hold of a switch button — the short press still toggles the light — see Examples below.

How It works

One/Two/Three short press:

  • switching on/off conventional lamps (Switch).
  • turning on / off dimmers (Dimmer) with the restoration of the previous dimming level.

Long press:

If main linked Item (in value) is Switch

  • switching on/off conventional lamps (Switch).
  • if holdRule config is specified — the rule/scene it points to is executed instead.
  • if hold config is specified (and no holdRule) — that Item is toggled instead of the main one.

If main linked Item (in value) is Dimmer

  • dimmers increase to 100% / decrease to ‘minDim’ values. If you release and press the button again, the dimming direction changes.

In this case hold config will be ignored.

Additionally, you can register any other actions for double / triple, etc. clicks by modifying the “shortPressAction” function.

Screenshots

Changelog

Version 0.1

  • initial release

Version 0.2

  • code refactored a bit
  • support for additional configuration, possibility to add several items for 2, 3 presses, and for hold actions for switch items.

Version 1.0

  • unified with the community extension by @PeterK: linkedItem.config.action (toggle | runRule | command) + command, linkedOn/linkedOff state-dependent metadata, command-driven scene switch group, linkedRule
  • new: holdRule — run a rule/scene on hold of a switch button
  • new: feedback blink at dimming limits — when hold-dimming reaches 100% or minDim, the dimmer dips/flashes three times so you can see the limit is reached in that direction
  • stability: fresh item lookups (cached Item wrappers went stale after item reload → runaway dimming), dim loop iteration cap, optional contact debounce (debounceMs), p2p3FallbackToMain option
  • hold threshold default is now 500 ms
  • full backward compatibility: original and extended metadata work unchanged — drop-in replacement

N.B.
If you need to separately display information about all switches and what light sources are linked to them in the metadata, you can create a separate widget that will show the necessary information in a list.

Notes: Based on Felix Krämer script. Scene/rule extensions (v1.0) by @PeterK. Icon Author

Examples

linkedItem (basic)

value: testLight
config:
  p2: testLightDimmer
  p3: testLightDimmer2
  hold: testSwitch4

Main target with action: runRule

value: MyScene
config:
  action: runRule

linkedOn / linkedOff

linkedOn:
  value: MyScene
  config:
    action: runRule

linkedOff:
  value: testLight
  config:
    action: command
    command: OFF

linkedRule

linkedRule:
  value: myRuleUID

holdRule

value: testLight
config:
  holdRule: mySceneRuleUID

Widget: switches and their linked items

uid: widget_96f79b9179
tags: []
props:
  parameters: []
  parameterGroups: []
timestamp: May 23, 2023, 10:53:24 AM
component: f7-card
config: {}
slots:
  default:
    - component: oh-list
      config:
        mediaList: true
      slots:
        default:
          - component: oh-repeater
            config:
              fragment: true
              for: item
              sourceType: itemsInGroup
              groupItem: gAllSwitches
              fetchMetadata: linkedItem
            slots:
              default:
                - component: oh-list-item
                  config:
                    accordionList: true
                    icon: ='oh:' + loop.item.category
                    title: =loop.item.label
                    subtitle: >
                      ="item Name: " + loop.item.name
                    footer: >
                      ="linked Item: " + loop.item.metadata.linkedItem.value
                    after: =loop.item.state

Woah.
Nice. This seems pretty awesome to manage rooms with multiple spot light groups that you’d want to control individually.
Unfortunately i don’t have a use case for this, but this makes life much easier for anyone who does.

Strange behaviour - 1st post updated, but in Marketplace I cannot see changes from some moment.
And firstly tried to add link to GitHub raw file.
In this case was unable to add template from Marketplace. Button ADD just pressed and template actually was not added.
BTW, is there possibility to see what’s wrong in some logs?

Hi,

I rarely post here, but I regularly follow the community and really appreciate all the ongoing development around OpenHAB.

I recently came across this rule by chance and wanted to provide some feedback.

Unfortunately, I was unable to install it through the Marketplace and received the following error:

CommunityRuleTemplateAddonHandler Rule template marketplace:146842 has neither download URL nor embedded content

org.openhab.core.addon.marketplace.internal.community.CommunityRuleTemplateAddonHandler Failed to add rule template from the marketplace: Rule template has neither download URL nor embedded content

I’m currently running OpenHAB 5.1.4. The issue may be related to that version, although it’s equally possible that I missed something on my side.

Since I ended up importing the rule as a JavaScript file anyway, I took the opportunity to make a small extension. The original functionality remains unchanged. I only added the ability to trigger scenes/rules in addition to linked items.

To achieve this, I introduced a new metadata property called LinkedRule alongside the existing LinkedItem property. When LinkedRule is present, the rule will trigger the specified rule/scene instead of sending a command to a linked item.

I make extensive use of scenes in my setup to coordinate multiple switches and actions, so this was a useful addition for me. The new LinkedRule metadata can reference either a regular rule or a scene, as scenes can be triggered just like any other rule in OpenHAB. This makes the solution much more flexible than simple item switching and enables use cases such as updating String items, triggering automations, or controlling groups of devices through scenes.

Perhaps others may find it useful as well. I’ve included the modified code below.

'use strict';
 
/*
 * Direkte JavaScript-Version von yaml/rules/community-taster.yaml.
 *
 * Basis: LazyGattos Community-Regel "Switch and Dimmers Rule" plus minimale
 * Erweiterungen:
 * - linkedItem.config.action=command sendet einen festen Command an das linkedItem
 * - linkedRule-Metadata startet zusätzlich oder eigenständig eine openHAB-Regel
 */

const { actions, cache, items, rules, time, triggers } = require('openhab');
const { eventStateFrom, eventStateTo, requireGroupMemberEvent } = require('oh-core/events');
const { configureLogger, logTriggered } = require('oh-core/logging');

const LOGGER_NAME = 'org.openhab.automation.script.CommunityTaster';
const RULE_LOG_NAME = 'Community Taster: ';
const TASTER_GROUP = 'gTA_Taster_Community';

// ==== Configuration ====
const delayMulti = 350; // registering multiple pushes
const delayDimStep = 100; // pause between in-/decrease steps
const dimStep = 2; // step to increase/decrease dimming level for one iteration
const minDim = 5; // minimum level for dimming
const switchState = {
  ON: 'ON', // CLOSED for Contact Type
  OFF: 'OFF' // OPEN for Contact Type
};
// ==== END Configuration ====

configureLogger(LOGGER_NAME);

function isObjectEmpty(objectName) {
  return JSON.stringify(objectName) === '{}';
}

function stateText(value) {
  if (value === undefined || value === null) {
    return undefined;
  }

  return typeof value.toString === 'function' ? value.toString() : String(value);
}

function linkedItemAction(itemObj) {
  return 'action' in itemObj ? itemObj.action : 'toggle';
}

function linkedTarget(itemObj) {
  return 'linkedItem' in itemObj ? itemObj.linkedItem : itemObj;
}

function runRuleUID(ruleUID, sourceName) {
  const uid = stateText(ruleUID);
  if (!uid) {
    console.warn(`${RULE_LOG_NAME}keine Rule UID für ${sourceName} ermittelbar`);
    return;
  }

  console.log(`${RULE_LOG_NAME}starte verknüpfte Regel ${uid} für ${sourceName}`);
  rules.runRule(uid, {});
}

function runLinkedRule(itemObj) {
  const target = linkedTarget(itemObj);
  const configuredRuleUID = 'ruleUID' in itemObj ? itemObj.ruleUID : undefined;
  runRuleUID(configuredRuleUID || target.name, target.name);
}

function runConfiguredLinkedRule(stor) {
  if (stor.linkedRuleUID) {
    runRuleUID(stor.linkedRuleUID, stor.switchTriggered.name);
  }
}

function commandLinkedItem(itemObj) {
  const target = linkedTarget(itemObj);
  if (!('command' in itemObj)) {
    console.warn(`${RULE_LOG_NAME}kein Command für linkedItem ${target.name} konfiguriert`);
    return;
  }

  console.log(`${RULE_LOG_NAME}sende ${itemObj.command} an ${target.name}`);
  target.sendCommand(itemObj.command);
}

function toggleItem(itemObj) {
  if (linkedItemAction(itemObj) === 'runRule') {
    runLinkedRule(itemObj);
    return;
  }

  if (linkedItemAction(itemObj) === 'command') {
    commandLinkedItem(itemObj);
    return;
  }

  let stateToSet = null;

  if (stateText(itemObj.state) === 'OFF') {
    stateToSet = 'ON';
  } else if (Number(itemObj.state) === 0) {
    stateToSet = 'previousState' in itemObj ? itemObj.previousState : 100;
  } else {
    itemObj.previousState = itemObj.state;
    stateToSet = 'OFF';
  }

  console.log(`${RULE_LOG_NAME}toggle ${itemObj.name} -> ${stateToSet}`);
  itemObj.sendCommand(stateToSet);
}

function executePrimaryLinkedItemAction(stor) {
  if (!stor.linkedItem) {
    return;
  }

  if (linkedItemAction(stor) === 'runRule') {
    runLinkedRule(stor);
  } else if (linkedItemAction(stor) === 'command') {
    commandLinkedItem(stor);
  } else {
    toggleItem(stor.linkedItem);
  }
}

function shortPressAction(stor) {
  switch (stor.pressCount) {
    case 1:
      executePrimaryLinkedItemAction(stor);
      runConfiguredLinkedRule(stor);
      break;

    case 2:
      if (stor.linkedItem && 'p2' in stor.linkedItem) {
        toggleItem(stor.linkedItem.p2);
      } else {
        console.log(`${RULE_LOG_NAME}keine Aktion für 2 Tastendrücke auf ${stor.switchTriggered.name}`);
      }
      break;

    case 3:
      if (stor.linkedItem && 'p3' in stor.linkedItem) {
        toggleItem(stor.linkedItem.p3);
      } else {
        console.log(`${RULE_LOG_NAME}keine Aktion für 3 Tastendrücke auf ${stor.switchTriggered.name}`);
      }
      break;

    default:
      console.log(`${RULE_LOG_NAME}keine Aktion für ${stor.pressCount} Tastendrücke auf ${stor.switchTriggered.name}`);
  }
}

function resetStorage(stor) {
  stor.btnTimer = null;
  stor.pressCount = 0;
  stor.dimTimer = null;
  cache.private.put(stor.cacheId, stor);
}

function dimItem(stor) {
  let dimToSet = null;

  if (stateText(stor.switchTriggered.state) === switchState.OFF) {
    resetStorage(stor);
    return;
  }

  if (stor.dimUp === true) {
    dimToSet = Number(stor.linkedItem.state) + dimStep;
    if (dimToSet > 100) {
      dimToSet = 100;
      resetStorage(stor);
    }
  } else {
    dimToSet = Number(stor.linkedItem.state) - dimStep;
    if (dimToSet < minDim) {
      dimToSet = minDim;
      resetStorage(stor);
    }
  }

  stor.linkedItem.sendCommand(dimToSet);

  if (stor.dimTimer) {
    stor.dimTimer.reschedule(time.toZDT(delayDimStep));
  }
}

function getPressCountTimer(stor) {
  if (stateText(stor.switchTriggered.state) === switchState.OFF) {
    shortPressAction(stor);
    resetStorage(stor);
    return;
  }

  resetStorage(stor);

  if (!stor.linkedItem) {
    runConfiguredLinkedRule(stor);
    return;
  }

  if (linkedItemAction(stor) === 'runRule') {
    runLinkedRule(stor);
    runConfiguredLinkedRule(stor);
    return;
  }

  if (linkedItemAction(stor) === 'command') {
    commandLinkedItem(stor);
    runConfiguredLinkedRule(stor);
    return;
  }

  switch (stor.linkedItem.type) {
    case 'SwitchItem':
      if ('hold' in stor.linkedItem) {
        toggleItem(stor.linkedItem.hold);
      } else {
        toggleItem(stor.linkedItem);
      }
      break;

    case 'DimmerItem':
      if (Number(stor.linkedItem.state) > 90) {
        stor.dimUp = false;
      } else if (Number(stor.linkedItem.state) < 10) {
        stor.dimUp = true;
      } else {
        stor.dimUp = !stor.dimUp;
      }

      if (stor.dimTimer === null) {
        stor.dimTimer = actions.ScriptExecution.createTimer(stor.dimTimerId, time.toZDT(), () => dimItem(stor));
      }
      cache.private.put(stor.cacheId, stor);
      break;

    default:
      console.warn(`${RULE_LOG_NAME}${stor.linkedItem.name} hat nicht unterstützten Typ ${stor.linkedItem.type}`);
  }
}

function readActionMetadata(switchTriggered) {
  const linkedItemMetadata = items.metadata.getMetadata(switchTriggered, 'linkedItem');
  const linkedRuleMetadata = items.metadata.getMetadata(switchTriggered, 'linkedRule');

  if (linkedItemMetadata === null && linkedRuleMetadata === null) {
    console.error(`${RULE_LOG_NAME}${switchTriggered.name} hat weder linkedItem- noch linkedRule-Metadata; Abbruch`);
    return undefined;
  }

  return { linkedItemMetadata, linkedRuleMetadata };
}

function linkedRuleUID(metadata) {
  if (metadata === null) {
    return undefined;
  }

  const configuration = metadata.configuration || {};
  return stateText(configuration.ruleUID) || stateText(metadata.value);
}

function attachConfiguredLinkedItems(linkedItem, configuration) {
  if (isObjectEmpty(configuration)) {
    return;
  }

  if ('p2' in configuration) {
    linkedItem.p2 = items.getItem(configuration.p2);
  }
  if ('p3' in configuration) {
    linkedItem.p3 = items.getItem(configuration.p3);
  }
  if ('hold' in configuration) {
    linkedItem.hold = items.getItem(configuration.hold);
  }
}

function handleButtonPress(switchTriggered) {
  const cacheId = `${switchTriggered.name}_Id`;
  const metadata = readActionMetadata(switchTriggered);

  if (!metadata) {
    return;
  }

  const linkedItemMetadata = metadata.linkedItemMetadata;
  const configuration = linkedItemMetadata === null ? {} : linkedItemMetadata.configuration || {};
  const linkedItem = linkedItemMetadata === null ? undefined : items.getItem(linkedItemMetadata.value);

  if (linkedItem) {
    attachConfiguredLinkedItems(linkedItem, configuration);
  }

  const stor = cache.private.get(cacheId, () => ({
    cacheId,
    switchTriggered,
    linkedItem,
    btnTimer: null,
    pressCount: 0,
    dimTimer: null,
    dimTimerId: linkedItem ? `${linkedItem.name}_dimTimerId` : `${switchTriggered.name}_dimTimerId`,
    dimUp: false
  }));

  stor.linkedItem = linkedItem;
  stor.dimTimerId = linkedItem ? `${linkedItem.name}_dimTimerId` : `${switchTriggered.name}_dimTimerId`;
  stor.action = 'action' in configuration ? configuration.action : 'toggle';
  stor.ruleUID = 'ruleUID' in configuration ? configuration.ruleUID : undefined;
  stor.command = 'command' in configuration ? configuration.command : undefined;
  stor.linkedRuleUID = linkedRuleUID(metadata.linkedRuleMetadata);
  stor.pressCount++;

  if (stor.btnTimer !== null) {
    clearTimeout(stor.btnTimer);
  }

  stor.btnTimer = setTimeout(() => getPressCountTimer(stor), delayMulti);
  cache.private.put(cacheId, stor);
}

rules.JSRule({
  name: 'Community Taster linkedItem',
  description: 'Direkte JS-Instanz der minimal erweiterten Community Switch-and-Dimmers-Regel für gTA_Taster_Community.',
  triggers: [triggers.GroupStateChangeTrigger(TASTER_GROUP)],
  execute: (event) => {
    logTriggered(RULE_LOG_NAME, event);

    const groupEvent = requireGroupMemberEvent(event, { expectedGroupName: TASTER_GROUP });
    if (!eventStateFrom(event, switchState.OFF) || !eventStateTo(event, switchState.ON)) {
      console.debug(
        `${RULE_LOG_NAME}ignoriere ${groupEvent.itemName}: ${groupEvent.oldStateText} -> ${groupEvent.newStateText}`
      );
      return;
    }

    const switchTriggered = items.getItem(groupEvent.itemName);
    handleButtonPress(switchTriggered);
  },
  id: 'community_taster_switch_and_dimmers'
});

Best regards
Peter

Hi,

just a small update: with this extension, I was able to control my entire heating system using buttons that trigger scenes such as “Vacation”, “Standard”, “Away”, and similar modes.

BR

Peter

Hi,
Please ignore the code from my previous posts. I decided to take a different approach that should provide even more flexibility in the long run.

Once I have finished testing it and verified that everything works as intended, I will publish the code here.

BR Peter

If it truely is a different approach, you could publish it as a separate rule template which will make it easier for users to install and use, and which is more in keeping with the intent of the marketpalce threads overall.

By “different approach”, I did not mean a different approach to the rule itself. I meant a different approach to achieving my goal of scene integration and scene control. I intended this as a “extension” to the original rule.

The goal was not to create a new rule with different behavior, but to achieve exactly the same result as the original rule while adding support for a few additional use cases. Existing item-configurations (metadata) continue to work unchanged, as the original metadata and behavior remain fully supported.

The original linkedItem metadata remains the primary compatibility path and behaves exactly as before. In addition, two new metadata namespaces were added:

  • linkedOn

  • linkedOff

This allows a trigger item to perform different actions depending on the received state:

  • ON → evaluate linkedOn

  • OFF → evaluate linkedOff

Example:

metadata:
  linkedOn:
    value: DR_AB_HueSchalter_Aussen1
    config:
      action: runRule

  linkedOff:
    value: DR_AB_Lampen
    config:
      action: command
      command: OFF

Supported Actions

runRule

Starts a rule or scene.

linkedOn:
  value: My_Scene
  config:
    action: runRule

command

Sends a predefined command to an item.

linkedOff:
  value: My_Lights
  config:
    action: command
    command: OFF

The existing toggle behavior remains available and is used whenever no explicit action is configured.

Most of the work was originally done by LazyGatto in the community rule. I only added the functionality required for these additional use cases while keeping the original behavior intact.

'use strict';
 
/*
 * Direkte JavaScript-Version von yaml/rules/community-taster.yaml.
 *
 * Basis: LazyGattos Community-Regel "Switch and Dimmers Rule" plus minimale
 * Erweiterungen:
 * - linkedItem.config.action=command sendet einen festen Command an das linkedItem
 * - linkedOn-/linkedOff-Metadata kann zustandsabhängig Regeln starten oder Items steuern
 */

const { actions, cache, items, rules, time, triggers } = require('openhab');
const { eventStateFrom, eventStateTo, normalizeEvent, requireGroupMemberEvent } = require('oh-core/events');
const { configureLogger, logTriggered } = require('oh-core/logging');

const LOGGER_NAME = 'org.openhab.automation.script.CommunityTaster';
const RULE_LOG_NAME = 'Community Taster: ';
const TASTER_GROUP = 'gTA_Taster_Community';
const SCENE_SWITCH_GROUP = 'Szenenschalter';

// ==== Configuration ====
const delayMulti = 350; // registering multiple pushes
const delayDimStep = 100; // pause between in-/decrease steps
const dimStep = 2; // step to increase/decrease dimming level for one iteration
const minDim = 5; // minimum level for dimming
const switchState = {
  ON: 'ON', // CLOSED for Contact Type
  OFF: 'OFF' // OPEN for Contact Type
};
// ==== END Configuration ====

configureLogger(LOGGER_NAME);

function isObjectEmpty(objectName) {
  return JSON.stringify(objectName) === '{}';
}

function stateText(value) {
  if (value === undefined || value === null) {
    return undefined;
  }

  return typeof value.toString === 'function' ? value.toString() : String(value);
}

function linkedItemAction(itemObj) {
  return 'action' in itemObj ? itemObj.action : 'toggle';
}

function linkedTarget(itemObj) {
  return 'linkedItem' in itemObj ? itemObj.linkedItem : itemObj;
}

function runRuleUID(ruleUID, sourceName) {
  const uid = stateText(ruleUID);
  if (!uid) {
    console.warn(`${RULE_LOG_NAME}keine Rule UID für ${sourceName} ermittelbar`);
    return;
  }

  console.log(`${RULE_LOG_NAME}starte verknüpfte Regel ${uid} für ${sourceName}`);
  rules.runRule(uid, {});
}

function runLinkedRule(itemObj) {
  const target = linkedTarget(itemObj);
  const configuredRuleUID = 'ruleUID' in itemObj ? itemObj.ruleUID : undefined;
  runRuleUID(configuredRuleUID || target.name, target.name);
}

function commandLinkedItem(itemObj) {
  const target = linkedTarget(itemObj);
  if (!('command' in itemObj) || itemObj.command === undefined || itemObj.command === null) {
    console.warn(`${RULE_LOG_NAME}kein Command für linkedItem ${target.name} konfiguriert`);
    return;
  }

  console.log(`${RULE_LOG_NAME}sende ${itemObj.command} an ${target.name}`);
  target.sendCommand(itemObj.command);
}

function actionFromMetadata(metadata) {
  const configuration = metadata && metadata.configuration ? metadata.configuration : {};
  return {
    action: stateText(configuration.action) || 'runRule',
    command: stateText(configuration.command),
    value: stateText(metadata && metadata.value)
  };
}

function executeMetadataAction(actionConfig, sourceName) {
  if (!actionConfig) {
    return false;
  }

  if (actionConfig.action === 'runRule') {
    runRuleUID(actionConfig.value, sourceName);
    return true;
  }

  if (!actionConfig.value) {
    console.warn(`${RULE_LOG_NAME}kein Ziel-Item für ${sourceName} konfiguriert`);
    return false;
  }

  const target = items.getItem(actionConfig.value);
  if (actionConfig.action === 'command') {
    commandLinkedItem({
      linkedItem: target,
      command: actionConfig.command
    });
    return true;
  }

  toggleItem(target);
  return true;
}

function linkedActionForState(switchTriggered, state) {
  const metadataName = state === switchState.OFF ? 'linkedOff' : 'linkedOn';
  const metadata = items.metadata.getMetadata(switchTriggered, metadataName);
  return metadata === null ? undefined : actionFromMetadata(metadata);
}

function toggleItem(itemObj) {
  if (linkedItemAction(itemObj) === 'runRule') {
    runLinkedRule(itemObj);
    return;
  }

  if (linkedItemAction(itemObj) === 'command') {
    commandLinkedItem(itemObj);
    return;
  }

  let stateToSet = null;

  if (stateText(itemObj.state) === 'OFF') {
    stateToSet = 'ON';
  } else if (Number(itemObj.state) === 0) {
    stateToSet = 'previousState' in itemObj ? itemObj.previousState : 100;
  } else {
    itemObj.previousState = itemObj.state;
    stateToSet = 'OFF';
  }

  console.log(`${RULE_LOG_NAME}toggle ${itemObj.name} -> ${stateToSet}`);
  itemObj.sendCommand(stateToSet);
}

function executePrimaryLinkedItemAction(stor) {
  if (!stor.linkedItem) {
    return;
  }

  if (linkedItemAction(stor) === 'runRule') {
    runLinkedRule(stor);
  } else if (linkedItemAction(stor) === 'command') {
    commandLinkedItem(stor);
  } else {
    toggleItem(stor.linkedItem);
  }
}

function shortPressAction(stor) {
  switch (stor.pressCount) {
    case 1:
      executePrimaryLinkedItemAction(stor);
      executeMetadataAction(stor.linkedOnAction, stor.switchTriggered.name);
      break;

    case 2:
      if (stor.linkedItem && 'p2' in stor.linkedItem) {
        toggleItem(stor.linkedItem.p2);
      } else {
        console.log(`${RULE_LOG_NAME}keine Aktion für 2 Tastendrücke auf ${stor.switchTriggered.name}`);
      }
      break;

    case 3:
      if (stor.linkedItem && 'p3' in stor.linkedItem) {
        toggleItem(stor.linkedItem.p3);
      } else {
        console.log(`${RULE_LOG_NAME}keine Aktion für 3 Tastendrücke auf ${stor.switchTriggered.name}`);
      }
      break;

    default:
      console.log(`${RULE_LOG_NAME}keine Aktion für ${stor.pressCount} Tastendrücke auf ${stor.switchTriggered.name}`);
  }
}

function resetStorage(stor) {
  stor.btnTimer = null;
  stor.pressCount = 0;
  stor.dimTimer = null;
  cache.private.put(stor.cacheId, stor);
}

function dimItem(stor) {
  let dimToSet = null;

  if (stateText(stor.switchTriggered.state) === switchState.OFF) {
    resetStorage(stor);
    return;
  }

  if (stor.dimUp === true) {
    dimToSet = Number(stor.linkedItem.state) + dimStep;
    if (dimToSet > 100) {
      dimToSet = 100;
      resetStorage(stor);
    }
  } else {
    dimToSet = Number(stor.linkedItem.state) - dimStep;
    if (dimToSet < minDim) {
      dimToSet = minDim;
      resetStorage(stor);
    }
  }

  stor.linkedItem.sendCommand(dimToSet);

  if (stor.dimTimer) {
    stor.dimTimer.reschedule(time.toZDT(delayDimStep));
  }
}

function getPressCountTimer(stor) {
  if (stateText(stor.switchTriggered.state) === switchState.OFF) {
    shortPressAction(stor);
    resetStorage(stor);
    return;
  }

  resetStorage(stor);

  if (!stor.linkedItem) {
    executeMetadataAction(stor.linkedOnAction, stor.switchTriggered.name);
    return;
  }

  if (linkedItemAction(stor) === 'runRule') {
    runLinkedRule(stor);
    executeMetadataAction(stor.linkedOnAction, stor.switchTriggered.name);
    return;
  }

  if (linkedItemAction(stor) === 'command') {
    commandLinkedItem(stor);
    executeMetadataAction(stor.linkedOnAction, stor.switchTriggered.name);
    return;
  }

  switch (stor.linkedItem.type) {
    case 'SwitchItem':
      if ('hold' in stor.linkedItem) {
        toggleItem(stor.linkedItem.hold);
      } else {
        toggleItem(stor.linkedItem);
      }
      break;

    case 'DimmerItem':
      if (Number(stor.linkedItem.state) > 90) {
        stor.dimUp = false;
      } else if (Number(stor.linkedItem.state) < 10) {
        stor.dimUp = true;
      } else {
        stor.dimUp = !stor.dimUp;
      }

      if (stor.dimTimer === null) {
        stor.dimTimer = actions.ScriptExecution.createTimer(stor.dimTimerId, time.toZDT(), () => dimItem(stor));
      }
      cache.private.put(stor.cacheId, stor);
      break;

    default:
      console.warn(`${RULE_LOG_NAME}${stor.linkedItem.name} hat nicht unterstützten Typ ${stor.linkedItem.type}`);
  }
}

function readActionMetadata(switchTriggered) {
  const linkedItemMetadata = items.metadata.getMetadata(switchTriggered, 'linkedItem');
  const linkedOnMetadata = items.metadata.getMetadata(switchTriggered, 'linkedOn');

  if (linkedItemMetadata === null && linkedOnMetadata === null) {
    console.error(`${RULE_LOG_NAME}${switchTriggered.name} hat weder linkedItem- noch linkedOn-Metadata; Abbruch`);
    return undefined;
  }

  return {
    linkedItemMetadata,
    linkedOnAction: linkedOnMetadata === null ? undefined : actionFromMetadata(linkedOnMetadata)
  };
}

function attachConfiguredLinkedItems(linkedItem, configuration) {
  if (isObjectEmpty(configuration)) {
    return;
  }

  if ('p2' in configuration) {
    linkedItem.p2 = items.getItem(configuration.p2);
  }
  if ('p3' in configuration) {
    linkedItem.p3 = items.getItem(configuration.p3);
  }
  if ('hold' in configuration) {
    linkedItem.hold = items.getItem(configuration.hold);
  }
}

function handleStateSpecificAction(switchTriggered, state) {
  const actionConfig = linkedActionForState(switchTriggered, state);
  if (!actionConfig) {
    console.error(`${RULE_LOG_NAME}${switchTriggered.name} hat keine linkedOn-/linkedOff-Metadata für ${state}; Abbruch`);
    return;
  }

  executeMetadataAction(actionConfig, switchTriggered.name);
}

function handleButtonPress(switchTriggered) {
  const cacheId = `${switchTriggered.name}_Id`;
  const metadata = readActionMetadata(switchTriggered);

  if (!metadata) {
    return;
  }

  const linkedItemMetadata = metadata.linkedItemMetadata;
  const configuration = linkedItemMetadata === null ? {} : linkedItemMetadata.configuration || {};
  const linkedItem = linkedItemMetadata === null ? undefined : items.getItem(linkedItemMetadata.value);

  if (linkedItem) {
    attachConfiguredLinkedItems(linkedItem, configuration);
  }

  const stor = cache.private.get(cacheId, () => ({
    cacheId,
    switchTriggered,
    linkedItem,
    btnTimer: null,
    pressCount: 0,
    dimTimer: null,
    dimTimerId: linkedItem ? `${linkedItem.name}_dimTimerId` : `${switchTriggered.name}_dimTimerId`,
    dimUp: false
  }));

  stor.linkedItem = linkedItem;
  stor.dimTimerId = linkedItem ? `${linkedItem.name}_dimTimerId` : `${switchTriggered.name}_dimTimerId`;
  stor.action = 'action' in configuration ? configuration.action : 'toggle';
  stor.ruleUID = 'ruleUID' in configuration ? configuration.ruleUID : undefined;
  stor.command = 'command' in configuration ? configuration.command : undefined;
  stor.linkedOnAction = metadata.linkedOnAction;
  stor.pressCount++;

  if (stor.btnTimer !== null) {
    clearTimeout(stor.btnTimer);
  }

  stor.btnTimer = setTimeout(() => getPressCountTimer(stor), delayMulti);
  cache.private.put(cacheId, stor);
}

rules.JSRule({
  name: 'Community Taster linkedItem',
  description: 'Erweiterte Community Switch-and-Dimmers-Regel für Taster und metadatengesteuerte Szenenschalter.',
  triggers: [
    triggers.GroupStateChangeTrigger(TASTER_GROUP),
    triggers.GroupCommandTrigger(SCENE_SWITCH_GROUP)
  ],
  execute: (event) => {
    logTriggered(RULE_LOG_NAME, event);

    const normalizedEvent = normalizeEvent(event);
    const switchTriggered = items.getItem(normalizedEvent.itemName);

    if (normalizedEvent.groupName === SCENE_SWITCH_GROUP || normalizedEvent.isCommand) {
      const command = normalizedEvent.commandText;
      if (command !== switchState.ON && command !== switchState.OFF) {
        console.debug(`${RULE_LOG_NAME}ignoriere ${normalizedEvent.itemName}: Command ${command}`);
        return;
      }

      handleStateSpecificAction(switchTriggered, command);
      return;
    }

    const groupEvent = requireGroupMemberEvent(event, { expectedGroupName: TASTER_GROUP });
    if (!eventStateTo(event, switchState.ON) || eventStateFrom(event, switchState.ON)) {
      console.debug(
        `${RULE_LOG_NAME}ignoriere ${groupEvent.itemName}: ${groupEvent.oldStateText} -> ${groupEvent.newStateText}`
      );
      return;
    }

    handleButtonPress(switchTriggered);
  },
  id: 'community_taster_switch_and_dimmers'
});

I’m not sure what the best approach is. My original intention was to propose it to @LazyGatto as a possible enhancement to the existing rule rather than publishing it as a completely separate rule in the marketplace.

Hi Peter,

First of all — thank you for digging into this rule, and sorry for the slow reply!
Your message (and the marketplace error you hit) was exactly the push I needed to
bring the rule back to life.

About the marketplace install: you were right, it was broken on OH 5.x — the
embedded resource in the first post had rotted over the years (I hit the same thing
back in 2023, see post #3). I have replaced the first post with a freshly generated
resource block. Could you please try installing it again on your 5.1.4 and let me
know if it works now?

v1.0 — unified version. I merged your extension into the rule, so it is now a
drop-in replacement for everyone:

  • Your action model in linkedItem.config (toggle / runRule / command) —
    supported as-is.
  • linkedOn / linkedOff state-dependent metadata, including the command-driven
    scene switch group — supported as-is (including the runRule default action).
  • linkedRule (your first version) — also supported, for anyone who grabbed it.
  • One addition from my side: holdRule in linkedItem.config — runs a rule/scene
    on hold of a switch button. I use it to trigger house scenes from regular light
    switches: short press toggles the light, hold fires the scene — no helper items needed.
  • Your existing metadata keeps working without any reconfiguration — original
    linkedItem users and your extension users can replace the old rule with v1.0
    and nothing else changes.

Stability fixes baked in (from running it daily on OH 5.x, where your base
version had the same issue): cached Item wrappers went stale after an item
reload/rename — the dimming loop then read a frozen state and never stopped. v1.0
keeps only names/scalars in the cache and re-reads items fresh on every access,
adds a hard iteration cap for the dim loop, an optional contact debounce (for
press&release contacts), a small “limit reached” feedback blink, and a
p2p3FallbackToMain option.

If you could test v1.0 as a replacement for your fork with your heating scene
setup, that would be great — in theory your metadata should keep working without
any changes, but your setup is the only real-world test bed for those paths.

Credit where due: you are in the file header and the changelog.

PS: The first post is now updated with v1.0 — and, finally, the marketplace
installation works again. The embedded resource block in the old post had rotted over
the years (that’s exactly the “has neither download URL nor embedded content” error
@PeterK hit). Confirmed installing cleanly on OH 5.2.3 and showing up in the rule
templates list.

Peter, when you get a chance — could you try installing it on your 5.1.4 and, if it
installs, run your linkedOn / linkedOff / command configuration against it?
In theory everything should work without any reconfiguration: your metadata model is
now part of the rule itself (with credit in the file header and the changelog).