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;valuemust be the rule/scene UID.action: command— send a fixed command to the Item (value); the command itself is set by thecommandproperty.
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
holdRuleconfig is specified — the rule/scene it points to is executed instead. - if
holdconfig is specified (and noholdRule) — 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/linkedOffstate-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),p2p3FallbackToMainoption - 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



