Page 1 of 1

Bind and unbind to devices.

Posted: 25 Jul 2017 03:00
by Fredrikman
Hi. I am trying to write something that turn my SwitchBinary off whenever it's been on for 120 minutes. I decided to use the app "TimerSwitch" for timer.

This is my first attempt to write any code so far. It does the job, but I don’t manage to close binding to the virtual device. And I seem to catch multiple true events from the SwitchBinary (dev17), which I think starts multiple bindings to the virtual device. Does anyone feel like reviewing my code and give me any pointers or suggestions?

Code: Select all

devTimerSwitch = controller.devices.get('TimerSwitch_29');
zway.devices[17].SwitchBinary.data.level.bind( function() {
	if (this.value === true) {
		devTimerSwitch.performCommand('exact',{ level: 120 });
		devTimerSwitch.on('change:metrics:level', function(vDev) {
			level = devTimerSwitch.get("metrics:level");
			if (level <= 0) {
				zway.devices[17].instances[0].SwitchBinary.Set(0);		
				devTimerSwitch.off('change:metrics:level', function(vDev) {
					debugPrint(‘myScript unbinding devTimerSwitch.off');
				});
			}
		  });
	}
});
Regards, Fredrik.

Re: Bind and unbind to devices.

Posted: 25 Jul 2017 10:18
by PoltoS
You can use AutoOff. It already does what you need.

To still help you with your code:

1. You should not do devTimerSwitch.on inside the handler. Do it outside. Otherwise you subscribe many times.

2. Unsubscribe from it only on module stop.

3. Also unsubscribe on stop from the binding of Z-Way object (line 2)

4. level is defined without var. Not good - it will be global.

Re: Bind and unbind to devices.

Posted: 25 Jul 2017 13:43
by Fredrikman
Thank you for your reply PoltoS.

I don't fully understand your answers, but I guess google/this forum could help me with "AutoOff", "outside handler", "module stop", etc that I guess is fundamentals of writing code. :)

Anyway, If you or someone else could help me to layout the design of the code it I would appreciate that very much.

Regards, Fredrik.

Re: Bind and unbind to devices.

Posted: 26 Jul 2017 01:19
by Fredrikman
Ah, I found the "Automated Switch Off" module. You are right. It does exactly what I was looking for.

Regards Fredrik.