Thanks for your pointers.
So clearTimeout will throw an error because self.timer is not defined so I defined it as null at the top, and didn’t bother checking if it was null or not before clearing it.
Once this was done we were in the same boat as before with a pir detection of 1 before the timeout has fired resulting in the mirror turning off and on again which is annoying. This is fixed by adding an onstate variable and simply not executing the activatemirror if its already activated. I just moved cleartimeout outside of that check otherwise it won’t work.
My working code below since I find it annoying when people don’t come back when they solve a problem:
// Subclass socketNotificationReceived received.
socketNotificationReceived: function(notification, payload) {
if (notification === ‘CONFIG’ && this.started == false) {
const self = this;
this.config = payload;
self.timer = null;
self.onState = 0;
//Log.info('PIR: ' + this.name);
//Setup pins
this.pir = new Gpio(this.config.sensorPIN, 'in', 'both');
if (this.config.relayPIN) {
this.relay = new Gpio(this.config.relayPIN, 'out');
this.relay.writeSync(this.config.relayOnState);
exec("/opt/vc/bin/tvservice --preferred && sudo chvt 6 && sudo chvt 7", null);
}
//Detected movement
this.pir.watch(function(err, value) {
if (value == 1) {
clearTimeout(self.timer);
if(self.onState != 1){
self.sendSocketNotification("USER_PRESENCE", true);
if (self.config.powerSaving){
self.activateMonitor();
self.onState = 1;
}
}
}
else if (value == 0) {
if(self.onState != 0){
self.timer = setTimeout(function(){
self.sendSocketNotification("USER_PRESENCE", false);
if (self.config.powerSaving){
self.deactivateMonitor();
self.onState = 0;
}
}, self.config.offDelay);
}
}
});
this.started = true;
} else if (notification === 'SCREEN_WAKEUP') {
this.activateMonitor();
}
}
});