text: var util=require("util"),EventEmitter=require("events"),path=require("path"),fs=require("fs"),fs_extra=require("fs-extra"),Logger=require("x.logger.js"),deviceman=require("x.hub.deviceman.js"),fileman=require("x.hub.fileman.js");Logger.setLevel("debug","x.hub.taskman");var x=x||{};x.hub=x.hub||{};x.hub.taskman=x.hub.taskman||{};x.hub.taskman.ERROR_CODE={General_Error:"100000",Pin_Error:"100001"};
  x.hub.taskman.Cloud=function(){var d=function(){};d.prototype.URL="https://webservice.mediola.com";d.prototype._doRequest=function(b,c,e,h,d,a,f){c=require("url").parse(this.URL+c);b={host:c.hostname,port:c.port,path:c.path,method:b,headers:h};if(d||a)b.auth=(d?d:"")+":"+(a?a:"");d=require("http");"https:"==c.protocol?(d=require("https"),process&&process.env&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0"),b.port||(b.port=443)):b.port||(b.port=80);var l=f;f=d.request(b,function(a){var c="";a.on("data",
  function(a){c+=a});a.on("end",function(){var b=null;200!=a.statusCode&&(b=Error("http response error"));l&&l(b,c,a.statusCode,a.headers)})});f.setTimeout(5E3,function(){l&&l(Error("timeout"));l=null});f.on("error",function(a){l&&l(a);l=null});e&&f.write(e);f.end()};return d}();
  x.hub.taskman._Util={TimeZone_MAP:[{utc:0,dst:!1,zone:"Etc/UTC"},{utc:0,dst:!0,zone:"CET"},{utc:1,dst:!1,zone:"Etc/GMT-1"},{utc:1,dst:!0,zone:"Europe/Berlin"},{utc:2,dst:!1,zone:"Etc/GMT-2"},{utc:2,dst:!0,zone:"EET"},{utc:3,dst:!1,zone:"Etc/GMT-3"},{utc:3,dst:!0,zone:"Asia/Tehran"},{utc:4,dst:!1,zone:"Etc/GMT-4"},{utc:4,dst:!0,zone:"Asia/Kabul"},{utc:5,dst:!1,zone:"Etc/GMT-5"},{utc:5,dst:!0,zone:"Etc/GMT-5"},{utc:6,dst:!1,zone:"Etc/GMT-6"},{utc:6,dst:!0,zone:"Etc/GMT-6"},{utc:7,dst:!1,zone:"Etc/GMT-7"},
  {utc:7,dst:!0,zone:"Asia/Hovd"},{utc:8,dst:!1,zone:"Etc/GMT-8"},{utc:8,dst:!0,zone:"Asia/Ulaanbaatar"},{utc:9,dst:!1,zone:"Etc/GMT-9"},{utc:9,dst:!0,zone:"Australia/Adelaide"},{utc:10,dst:!1,zone:"Etc/GMT-10"},{utc:10,dst:!0,zone:"Australia/Sydney"},{utc:11,dst:!1,zone:"Etc/GMT-11"},{utc:11,dst:!0,zone:"Etc/GMT-11"},{utc:12,dst:!1,zone:"Etc/GMT-12"},{utc:12,dst:!0,zone:"Pacific/Auckland"},{utc:13,dst:!1,zone:"Etc/GMT-13"},{utc:13,dst:!0,zone:"Pacific/Apia"},{utc:14,dst:!1,zone:"Etc/GMT-14"},{utc:14,
  dst:!0,zone:"Etc/GMT-14"},{utc:-1,dst:!1,zone:"Etc/GMT+1"},{utc:-1,dst:!0,zone:"Etc/GMT+1"},{utc:-2,dst:!1,zone:"Etc/GMT+2"},{utc:-2,dst:!0,zone:"Etc/GMT+2"},{utc:-3,dst:!1,zone:"Etc/GMT+3"},{utc:-3,dst:!0,zone:"America/Sao_Paulo"},{utc:-4,dst:!1,zone:"Etc/GMT+4"},{utc:-4,dst:!0,zone:"America/Santiago"},{utc:-5,dst:!1,zone:"Etc/GMT+5"},{utc:-5,dst:!0,zone:"America/New_York"},{utc:-6,dst:!1,zone:"Etc/GMT+6"},{utc:-6,dst:!0,zone:"CST6CDT"},{utc:-7,dst:!1,zone:"Etc/GMT+7"},{utc:-7,dst:!0,zone:"MST7MDT"},
  {utc:-8,dst:!1,zone:"Etc/GMT+8"},{utc:-8,dst:!0,zone:"PST8PDT"},{utc:-9,dst:!1,zone:"Etc/GMT+9"},{utc:-9,dst:!0,zone:"America/Anchorage"},{utc:-10,dst:!1,zone:"Etc/GMT+10"},{utc:-10,dst:!0,zone:"America/Adak"},{utc:-11,dst:!1,zone:"Etc/GMT+11"},{utc:-11,dst:!0,zone:"Etc/GMT+11"}],_getTimeZone:function(){var d="8C";localStorage.getItem("x.hub.Server.timezone")&&(d=localStorage.getItem("x.hub.Server.timezone"));var d=parseInt(d,16),b=0!=(d&128),c=(d&31)-11,e=null;this.TimeZone_MAP.forEach(function(h){h.utc==
  c&&h.dst==b&&(e=h.zone)});e||(e="Europe/Berlin");return e},_getlatlong:function(){var d="1392",b="035C";localStorage.getItem("x.hub.Server.geo.lat")&&(d=localStorage.getItem("x.hub.Server.geo.lat"));localStorage.getItem("x.hub.Server.geo.long")&&(b=localStorage.getItem("x.hub.Server.geo.long"));d=parseInt(d,16);32768<d&&(d=32768-d);d/=100;b=parseInt(b,16);32768<b&&(b=32768-b);return{lat:d,long:b/100}}};
  x.hub.taskman._TimerManager=function(){var d=function(c,b){this._logger=require("x.logger.js").getLogger("x.hub.taskman._TimerManager.CronTimer");this.taskID=c;this.timer=b;this._cronJob=null};d.prototype.start=function(){if(this.timer.time){var c=[],b=this.timer.time.indexOf(":"),h=this.timer.time.substr(0,b),b=this.timer.time.substr(b+1);c.push("00");c.push(b);c.push(h);c.push("*");c.push("*");h="0-6";if(this.timer.week&&7==this.timer.week.length){h=[];"1"==this.timer.week.charAt(6)&&h.push(0);
  for(b=0;6>b;b++)"1"==this.timer.week.charAt(b)&&h.push(b+1);h=h.join(",")}c.push(h);c=c.join(" ");h=x.hub.taskman._Util._getTimeZone();this._logger.log("debug","start timer:"+JSON.stringify(this.timer));this._logger.log("trace","start cron job:"+c+" tz:"+h);this._cronJob=new (require("cron").CronJob)(c,this.onTick.bind(this),null,!0,h)}};d.prototype.stop=function(){this._logger.log("debug","stop timer:"+JSON.stringify(this.timer));this._cronJob&&(this._cronJob.stop(),this._cronJob=null)};d.prototype.onTick=
  function(){this._logger.log("debug","timer tick:"+JSON.stringify(this.timer));var c=require("moment-timezone"),b=x.hub.taskman._Util._getTimeZone(),h=(new Date).getTime(),h=c.tz(h,b),d=h.year(),a=this.timer.start;if(a&&("00"==a.substr(0,2)&&(a=d+a.substr(2)),a=c.tz(a,b),a.set({hour:0,minute:0,second:0,millisecond:0}),a.valueOf()>h.valueOf()))return;var f=this.timer.end;if(f){var l=!1;"00"==f.substr(0,2)&&(l=!0,f=d+f.substr(2));f=c.tz(f,b);f.set({hour:23,minute:59,second:59,millisecond:999});l&&a&&
  f.valueOf()<a.valueOf()&&(f=d+1+this.timer.end.substr(2),f=c.tz(f,b),f.set({hour:23,minute:59,second:59,millisecond:999}));if(f.valueOf()<h.valueOf())return}require("x.hub.taskman.js").taskManager.onTimerTick(this.taskID)};d.prototype.onLocationChange=function(){this.stop();this.start()};d.prototype.onTimeChange=function(){this.stop();this.start()};var b=function(){this._timers=[]};b.prototype.startTimer=function(c,b){var h=new d(c,b);this._timers.push(h);h.start()};b.prototype.stopTimer=function(c){var b=
  [];this._timers.forEach(function(h){h.taskID==c?h.stop():b.push(h)});this._timers=b};b.prototype.onLocationChange=function(){this._timers.forEach(function(b){b.onLocationChange()})};b.prototype.onTimeChange=function(){this._timers.forEach(function(b){b.onTimeChange()})};b.prototype.clear=function(){var b=this._timers;this._timers=[];b.forEach(function(b){b.stop()})};return new b}();
  x.hub.taskman._AstroManager=function(){var d=function(b,e){this._logger=require("x.logger.js").getLogger("x.hub.taskman._AstroManager.AstroTimer");this.taskID=b;this.astro=e;this._job=null};d.prototype.start=function(){this.astro.astro&&(this._logger.log("debug","start astro:"+JSON.stringify(this.astro)),this._startNextTick())};d.prototype.stop=function(){this._logger.log("debug","stop astro:"+JSON.stringify(this.astro));this._job&&(clearTimeout(this._job),this._job=null)};d.prototype._startNextTick=
  function(){var b=this._getNextTickTime();this._logger.log("debug","next "+this.astro.astro+":"+new Date(b));var e=(new Date).getTime(),h=this;this._job=setTimeout(function(){h.onTick()},b-e)};d.prototype._getNextTickTime=function(){var b=x.hub.taskman._Util._getlatlong(),e=require("suncalc"),h=new Date,d=e.getTimes(h,b.lat,b.long),a=null,a="sunrise"==this.astro.astro?d.sunrise:d.sunset,a=a.getTime();this.astro.delay&&(a+=6E4*parseInt(this.astro.delay));a<=h.getTime()&&(h=new Date(h.getTime()+864E5),
  d=e.getTimes(h,b.lat,b.long),a="sunrise"==this.astro.astro?d.sunrise:d.sunset,a=a.getTime(),this.astro.delay&&(a+=6E4*parseInt(this.astro.delay)));return a};d.prototype.onTick=function(){this._logger.log("debug","astro tick:"+JSON.stringify(this.astro));var b=require("moment-timezone"),e=x.hub.taskman._Util._getTimeZone(),h=(new Date).getTime(),h=b.tz(h,e),d=h.year();if(this.astro.offTime){var a=this.astro.offTime.indexOf(":"),f=this.astro.offTime.substr(0,a),a=this.astro.offTime.substr(a+1),f=parseInt(f),
  a=parseInt(a);if(h.hour()<f||h.hour()==f&&h.minute()<=a)return}f=h.day();0==f&&(f=7);if(!this.astro.week||7!=this.astro.week.length||"0"!=this.astro.week.charAt(f-1)){if(f=this.astro.start)if("00"==f.substr(0,2)&&(f=d+f.substr(2)),f=b.tz(f,e),f.set({hour:0,minute:0,second:0,millisecond:0}),f.valueOf()>h.valueOf())return;if(f=this.astro.end)if("00"==f.substr(0,2)&&(f=d+f.substr(2)),f=b.tz(f,e),f.set({hour:23,minute:59,second:59,millisecond:999}),f.valueOf()<h.valueOf())return;this._startNextTick();
  require("x.hub.taskman.js").taskManager.onTimerTick(this.taskID)}};d.prototype.onLocationChange=function(){this.stop();this.start()};d.prototype.onTimeChange=function(){this.stop();this.start()};var b=function(){this._timers=[]};b.prototype.startTimer=function(b,e){var h=new d(b,e);this._timers.push(h);h.start()};b.prototype.stopTimer=function(b){var e=[];this._timers.forEach(function(h){h.taskID==b?h.stop():e.push(h)});this._timers=e};b.prototype.onLocationChange=function(){this._timers.forEach(function(b){b.onLocationChange()})};
  b.prototype.onTimeChange=function(){this._timers.forEach(function(b){b.onTimeChange()})};b.prototype.clear=function(){var b=this._timers;this._timers=[];b.forEach(function(b){b.stop()})};b.prototype.getSunriseSunset=function(b){var e=require("moment-timezone"),h=x.hub.taskman._Util._getTimeZone();b=e.tz(b,h);b.set({hour:12,minute:0,second:0,millisecond:0});e=x.hub.taskman._Util._getlatlong();return require("suncalc").getTimes(b.toDate(),e.lat,e.long)};return new b}();
  x.hub.taskman._PeriodicTimerManager=function(){var d=function(b,e){this._logger=require("x.logger.js").getLogger("x.hub.taskman._PeriodicTimerManager.CronTimer");this.taskID=b;this.timer=e;this._repeater=this._cronJob=this._starter=null};d.prototype.start=function(){if(this.timer.interval){var b=this.timer.startTime,e=this.timer.endTime;b||(b="00:00");e||(e="23:59");var h=[],d=b.indexOf(":"),a=b.substr(0,d),d=b.substr(d+1);h.push("00");h.push(d);h.push(a);h.push("*");h.push("*");var f="0-6";if(this.timer.week&&
  7==this.timer.week.length){f=[];"1"==this.timer.week.charAt(6)&&f.push(0);for(var l=0;6>l;l++)"1"==this.timer.week.charAt(l)&&f.push(l+1);f=f.join(",")}h.push(f);h=h.join(" ");f=x.hub.taskman._Util._getTimeZone();this._logger.log("debug","start timer:"+JSON.stringify(this.timer));this._logger.log("trace","start cron job:"+h+" tz:"+f);this._cronJob=new (require("cron").CronJob)(h,this.onFirstTick.bind(this),null,!0,f);var l=require("moment-timezone"),n=(new Date).getTime(),h=l.tz(n,f),a=h.year(),m=
  this.timer.start;if(m&&("00"==m.substr(0,2)&&(m+=m.substr(2)),m=l.tz(m,f),m.set({hour:0,minute:0,second:0,millisecond:0}),m.valueOf()>h.valueOf()))return;if(m=this.timer.end)if("00"==m.substr(0,2)&&(m=a+m.substr(2)),m=l.tz(m,f),m.set({hour:23,minute:59,second:59,millisecond:999}),m.valueOf()<h.valueOf())return;if(a=this.timer.week)if(m=h.isoWeekday(),--m,"1"!=a.charAt(m))return;m=l.tz(n,f);d=b.indexOf(":");a=b.substr(0,d);d=b.substr(d+1);m.set({hour:parseInt(a),minute:parseInt(d),second:0,millisecond:0});
  if(!(m.valueOf()>h.valueOf()||(b=l.tz(n,f),d=e.indexOf(":"),a=e.substr(0,d),d=e.substr(d+1),b.set({hour:parseInt(a),minute:parseInt(d),second:0,millisecond:0}),b.valueOf()<h.valueOf()||!(e=this.timer.interval)))){e=1E3*parseInt(e);e=Math.ceil((h.valueOf()-m.valueOf())/e)*e+m.valueOf()-h.valueOf();this._logger.log("trace","first tick in "+e/1E3+" seconds");var u=this;this._starter=setTimeout(function(){u.onFirstTick()},e)}}};d.prototype.stop=function(){this._logger.log("debug","stop timer:"+JSON.stringify(this.timer));
  this._cronJob&&(this._cronJob.stop(),this._cronJob=null);this._repeater&&(clearInterval(this._repeater),this._repeater=null);this._starter&&(clearTimeout(this._starter),this._starter=null)};d.prototype.onFirstTick=function(){this._logger.log("debug","periodic timer first tick:"+JSON.stringify(this.timer));var b=this.timer.interval;if(b){var b=1E3*parseInt(b),e=this;this._starter&&(clearTimeout(this._starter),this._starter=null);this._repeater&&(clearInterval(this._repeater),this._repeater=null);this._repeater=
  setInterval(function(){e.onTick()},b);this.onTick()}};d.prototype.onTick=function(){this._logger.log("debug","periodic timer tick:"+JSON.stringify(this.timer));var b=require("moment-timezone"),e=this.timer.interval,e=1E3*parseInt(e),d=x.hub.taskman._Util._getTimeZone(),k=(new Date).getTime(),e=k+e,a=b.tz(k,d),k=b.tz(k,d),f=k.year(),l=this.timer.start;if(l&&("00"==l.substr(0,2)&&(l=f+l.substr(2)),l=b.tz(l,d),l.set({hour:0,minute:0,second:0,millisecond:0}),l.valueOf()>k.valueOf()))return;if(l=this.timer.end)if("00"==
  l.substr(0,2)&&(l=f+l.substr(2)),l=b.tz(l,d),l.set({hour:23,minute:59,second:59,millisecond:999}),l.valueOf()<k.valueOf())return;(d=this.timer.endTime)||(d="23:59");f=d.indexOf(":");b=d.substr(0,f);d=d.substr(f+1);a.set({hour:parseInt(b),minute:parseInt(d),second:59,millisecond:999});a.valueOf()<k.valueOf()?(this._logger.log("trace","repeater exceed end time:"+a.toString()),this._repeater&&(clearInterval(this._repeater),this._repeater=null)):(e>a.valueOf()&&(this._logger.log("trace","repeater next tick will exceed end time:"+
  a.toString()),this._repeater&&(clearInterval(this._repeater),this._repeater=null)),require("x.hub.taskman.js").taskManager.onTimerTick(this.taskID))};d.prototype.onLocationChange=function(){this.stop();this.start()};d.prototype.onTimerChange=function(){this.stop();this.start()};var b=function(){this._timers=[]};b.prototype.startTimer=function(b,e){var h=new d(b,e);this._timers.push(h);h.start()};b.prototype.stopTimer=function(b){var e=[];this._timers.forEach(function(d){d.taskID==b?d.stop():e.push(d)});
  this._timers=e};b.prototype.onLocationChange=function(){this._timers.forEach(function(b){b.onLocationChange()})};b.prototype.onTimeChange=function(){this._timers.forEach(function(b){b.onTimeChange()})};b.prototype.clear=function(){var b=this._timers;this._timers=[];b.forEach(function(b){b.stop()})};return new b}();
  x.hub.taskman._Block=function(){var d=function(g){this.type=g;this._parent=null;this._canceling=this._running=!1;this._trace=null};d.prototype.isRunning=function(){return this._running};d.prototype.do=function(g){g&&g()};d.prototype.cancel=function(g){var a=this._running;this._canceling=this._running=!1;g&&g(null,a)};d.prototype.toJSON=function(){return{type:this.type}};d.prototype.fromJSON=function(){};d.prototype.setTrace=function(g){this._trace=g};var b=function(){d.call(this);this.type=b.TYPE;
  this.subtype=null;this.flowIf=[];this.flowThen=[];this.flowElse=[]};util.inherits(b,d);b.TYPE="condition";b.prototype.isRunning=function(){var g=!1;this.flowIf&&this.flowIf.forEach(function(a){a&&a.isRunning&&(g|=a.isRunning())});this.flowThen&&this.flowThen.forEach(function(a){a&&a.isRunning&&(g|=a.isRunning())});this.flowElse&&this.flowElse.forEach(function(a){a&&a.isRunning&&(g|=a.isRunning())});return g?!0:!1};b.prototype.do=function(g,a){var b=this;this._trace&&this._trace.log('condition | check "if"');
  this._checkIfBlocks(function(f,c){b._trace&&b._trace.log('condition | check "if" - '+(f?"error:"+f.message:c));f?g&&g(f):c?(b._trace&&b._trace.log('condition | do "then"'),b._doThenBlocks(g,a)):(b._trace&&b._trace.log('condition | do "else"'),b._doElseBlocks(g,a))},a)};b.prototype.cancel=function(g){var a=0;this.flowIf&&this.flowIf.forEach(function(g){g&&g.cancel?g.cancel():a++});this.flowThen&&this.flowThen.forEach(function(g){g&&g.cancel?g.cancel():a++});this.flowElse&&this.flowElse.forEach(function(g){g&&
  g.cancel?g.cancel():a++})};b.prototype.toJSON=function(){var g={type:this.type,subtype:this.subtype,if:[],then:[],else:[]};this.flowIf&&this.flowIf.forEach(function(a){a&&g.if.push(a.toJSON())});this.flowThen&&this.flowThen.forEach(function(a){a&&g.then.push(a.toJSON())});this.flowElse&&this.flowElse.forEach(function(a){a&&g.else.push(a.toJSON())});return g};b.prototype.fromJSON=function(g){if(g){var a=this;this.subtype=g.subtype;g.if&&0<g.if.length&&g.if.forEach(function(g){g&&(g=d.parse(g))&&(g._parent=
  a,a.flowIf.push(g))});g.then&&0<g.then.length&&g.then.forEach(function(g){g&&(g=d.parse(g))&&a.flowThen.push(g)});g.else&&0<g.else.length&&g.else.forEach(function(g){g&&(g=d.parse(g))&&a.flowElse.push(g)})}};b.prototype._checkIfBlocks=function(g,a){var b=[],f=0,c=this;if(this.flowIf&&0!=this.flowIf.length){var e=function(d,h){f++;d?b.push(!1):b.push(h);if(f<c.flowIf.length)c.flowIf[f].do(e,a);else if(0==b.length)g&&g(null,!0);else{for(var l=1,n=b[0];l<b.length&&l+1!=b.length;)"AND"==b[l]?n&=b[l+1]:
  "OR"==b[l]?n|=b[l+1]:"XOR"==b[l]&&(n=n!=b[l+1]),l+=2;g&&g(null,n)}};this.flowIf[f].do(e,a)}else g&&g(null,!0)};b.prototype._doThenBlocks=function(g,a){var b=0,f=this;if(this.flowThen&&0!=this.flowThen.length){var c=function(){b++;b<f.flowThen.length?f.flowThen[b].do(c,a):g&&g()};this.flowThen[b].do(c,a)}else g&&g()};b.prototype._doElseBlocks=function(g,a){var b=0,f=this;if(this.flowElse&&0!=this.flowElse.length){var c=function(){b++;b<f.flowElse.length?f.flowElse[b].do(c,a):g&&g()};this.flowElse[b].do(c,
  a)}else g&&g()};b.prototype.setTrace=function(g){this._trace=g;this.flowIf&&this.flowIf.forEach(function(a){a&&a.setTrace&&a.setTrace(g)});this.flowThen&&this.flowThen.forEach(function(a){a&&a.setTrace&&a.setTrace(g)});this.flowElse&&this.flowElse.forEach(function(a){a&&a.setTrace&&a.setTrace(g)})};d.Condition=b;var c=function(){b.call(this);this.type=d.Root.TYPE;this._lastTiggerTime=this._taskID=null;this.singleton=!1;this.singletonMethod="ignore";this._task=null;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.Root")};
  util.inherits(c,b);c.TYPE="root";c.prototype.init=function(g){this._taskID=g;this.flowIf.forEach(function(a){a&&a.init&&a.init(g)})};c.prototype.finalize=function(g){this.flowIf.forEach(function(a){a&&a.finalize&&a.finalize(g)})};c.prototype.getTriggers=function(){return this.flowIf?this.flowIf:[]};c.prototype._onTriggered=function(g,a){var b=(new Date).getTime();if(!(this._lastTiggerTime&&400>b-this._lastTiggerTime)){if(this.singleton&&this._running){if("ignore"==this.singletonMethod){this._logger.log("debug",
  "task "+this._taskID+" is running and ignore the new trigger");g&&g();return}this._logger.log("debug","task "+this._taskID+" is running and cancel it");this.cancel()}this._logger.log("info","task "+this._taskID+" triggered");this._logger.log("trace","task "+this._taskID+" is "+(this._running?"running":"not running"));this._lastTiggerTime=b;this._trace&&this._trace.log("root | task:"+this._taskID+" triggered");this._running=!0;var f=this;this._doThenBlocks(function(){f._running=!1;g&&g()},{trigger:a,
  task:this._task})}};c.prototype.onStatusEvt=function(g){var a=!1;this._logger.log("trace","check trigger for status event");for(var b=null,f=0;f<this.flowIf.length;f++){var c=this.flowIf[f];if((c.type==m.TYPE||c.type==r.TYPE)&&c.isMatch(g)){this._logger.log("debug","trigger hit:"+JSON.stringify(c.toJSON()));a=!0;b=c;break}}a&&this._onTriggered(null,b)};c.prototype.onDedicatedStatusEvt=function(g){var a=!1;this._logger.log("trace","check trigger for status event");for(var b=null,f=0;f<this.flowIf.length;f++){var c=
  this.flowIf[f];if(c.type==m.TYPE){if(c.isMatch(g)){this._logger.log("debug","trigger hit:"+JSON.stringify(c.toJSON()));a=!0;b=c;break}}else if(c.type==r.TYPE&&c.isMatch(g)){this._logger.log("debug","trigger hit:"+JSON.stringify(c.toJSON()));a=!0;b=c;break}}a&&this._onTriggered(null,b)};c.prototype.onIREvt=function(g){this._trace&&this._trace.log("root | receive ir event:"+JSON.stringify(g));var a=!1;this._logger.log("trace","check trigger for ir event");for(var b=0;b<this.flowIf.length;b++){var f=
  this.flowIf[b];if(f.type==n.TYPE&&f.isMatch(g)){this._logger.log("debug","trigger hit:"+JSON.stringify(f.toJSON()));a=!0;break}}a&&this._onTriggered()};c.prototype.onTimerTick=function(){this._trace&&this._trace.log("root | timer tick");this._onTriggered()};c.prototype.onHttpEvt=function(g,a){this._trace&&this._trace.log("root | receive http event:"+JSON.stringify(g));for(var b=!1,f=0;f<this.flowIf.length;f++){var c=this.flowIf[f];if(c.type==k.TYPE&&c.isMatch(g)){this._logger.log("info","trigger hit:"+
  JSON.stringify(c.toJSON()));b=!0;break}}b&&this._onTriggered();a&&a(null,b)};c.prototype.setTrace=function(g){this._trace=g;this.flowIf&&this.flowIf.forEach(function(a){a&&a.setTrace&&a.setTrace(g)});this.flowThen&&this.flowThen.forEach(function(a){a&&a.setTrace&&a.setTrace(g)})};c.prototype.hasCloudTrigger=function(){if(!this.flowIf||0==this.flowIf.length)return!1;for(var g=0;g<this.flowIf.length;g++)if(this.flowIf[g]instanceof u)return!0;return!1};c.prototype.toCloudRuleFormat=function(){if(!this.flowIf||
  0==this.flowIf.length)return[];for(var g=[],a=0;a<this.flowIf.length;a++){var b=this.flowIf[a];b instanceof u&&(b=b.toCloudRuleFormat())&&g.push(b)}return g};d.Root=c;var e=function(g){d.call(this);this.type=e.TYPE;g&&(this.op=g.op)};util.inherits(e,d);e.TYPE="logic.operator";e.prototype.do=function(g){g&&g(null,this.op)};e.prototype.toJSON=function(){var g=d.prototype.toJSON.call(this);g.op=this.op;return g};e.prototype.fromJSON=function(g){g&&(this.op=g.op)};d.LogicOP=e;var h=function(){d.call(this);
  this.type=h.TYPE;this.children=[]};util.inherits(h,d);h.TYPE="bracket";h.prototype.do=function(g){var a=[],b=0,f=this;if(this.children&&0!==this.children.length){var c=function(e,d){b++;e?a.push(!1):a.push(d);if(b<f.children.length)f.children[b].do(c);else if(0===a.length)g&&g(null,!0);else{for(var l=1,h=a[0];l<a.length&&l+1!=a.length;)"AND"==a[l]?h&=a[l+1]:"OR"==a[l]?h|=a[l+1]:"XOR"==a[l]&&(h=h!=a[l+1]),l+=2;g&&g(null,h)}};this.children[b].do(c)}else g&&g(null,!0)};h.prototype.toJSON=function(){var g=
  d.prototype.toJSON.call(this);g.children=[];this.children&&this.children.forEach(function(a){a&&g.children.push(a.toJSON())});return g};h.prototype.fromJSON=function(g){if(g){var a=this;g.children&&0<g.children.length&&g.children.forEach(function(g){g&&(g=d.parse(g))&&a.children.push(g)})}};d.Bracket=h;var k=function(){d.call(this);this.type=k.TYPE;this.params=null;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.HttpTrigger")};util.inherits(k,d);k.TYPE="http.trigger";k.prototype.isMatch=
  function(g){if(!g||!this.params)return!1;for(var a in this.params)if(a&&this.params[a]!=g[a])return!1;this._logger.log("trace","trigger hit:"+JSON.stringify(this.toJSON()));return!0};k.prototype.toJSON=function(){var g=d.prototype.toJSON.call(this);g.params=this.params;return g};k.prototype.fromJSON=function(g){g&&(this.params=g.params)};d.HttpTrigger=k;var a=function(){d.call(this);this.type=a.TYPE;this.op=this.end=this.start=this.week=this.time=null;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.Timer")};
  util.inherits(a,d);a.TYPE="timer";a.prototype.init=function(g){x.hub.taskman._TimerManager.startTimer(g,this)};a.prototype.do=function(g){this._trace&&this._trace.log("check time | "+this._getDescription());var a=require("moment-timezone"),b=x.hub.taskman._Util._getTimeZone(),f=(new Date).getTime(),f=a.tz(f,b),c=f.year(),e=this.start;if(e&&("00"==e.substr(0,2)&&(e=c+e.substr(2)),e=a.tz(e,b),e.set({hour:0,minute:0,second:0,millisecond:0}),e.valueOf()>f.valueOf())){this._logger.log("trace","condition mismatch:"+
  JSON.stringify(this.toJSON()));g&&g(null,!1);return}if(e=this.end)if("00"==e.substr(0,2)&&(e=c+e.substr(2)),e=a.tz(e,b),e.set({hour:23,minute:59,second:59,millisecond:999}),e.valueOf()<f.valueOf()){this._logger.log("trace","condition mismatch:"+JSON.stringify(this.toJSON()));g&&g(null,!1);return}if(a=this.week)if(b=f.day(),0==b&&(b=7),"1"!=a.charAt(b-1)){this._logger.log("trace","condition mismatch:"+JSON.stringify(this.toJSON()));g&&g(null,!1);return}if(this.time&&this.op)if(b=this.time.indexOf(":"),
  a=this.time.substr(0,b),b=this.time.substr(b+1),a=parseInt(a),b=parseInt(b),c=f.hour(),f=f.minute(),">="==this.op){if(c<a||c==a&&f<b){this._logger.log("trace","condition mismatch:"+JSON.stringify(this.toJSON()));g&&g(null,!1);return}}else if(">"==this.op){if(c<a||c==a&&f<=b){this._logger.log("trace","condition mismatch:"+JSON.stringify(this.toJSON()));g&&g(null,!1);return}}else if("<="==this.op){if(c>a||c==a&&f>b){this._logger.log("trace","condition mismatch:"+JSON.stringify(this.toJSON()));g&&g(null,
  !1);return}}else if("<"==this.op){if(c>a||c==a&&f>=b){this._logger.log("trace","condition mismatch:"+JSON.stringify(this.toJSON()));g&&g(null,!1);return}}else if("="==this.op||"=="==this.op)if(c!=a||c==a&&f!=b){this._logger.log("trace","condition mismatch:"+JSON.stringify(this.toJSON()));g&&g(null,!1);return}this._logger.log("trace","condition match:"+JSON.stringify(this.toJSON()));g&&g(null,!0)};a.prototype.finalize=function(a){x.hub.taskman._TimerManager.stopTimer(a)};a.prototype.toJSON=function(){var a=
  d.prototype.toJSON.call(this);a.time=this.time;a.week=this.week;a.start=this.start;a.end=this.end;a.op=this.op;return a};a.prototype.fromJSON=function(a){a&&(this.time=a.time,this.week=a.week,this.start=a.start,this.end=a.end,this.op=a.op)};a.prototype._getDescription=function(){var a;a="time:"+this.time;a+=" week:"+this.week;a+=" start:"+this.start;a+=" end:"+this.end;return a+=" op:"+this.op};d.Timer=a;var f=function(){d.call(this);this.type=f.TYPE;this.op=this.end=this.start=this.week=this.delay=
  this.offTime=this.astro=null;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.Astro")};util.inherits(f,d);f.TYPE="astro";f.prototype.init=function(a){x.hub.taskman._AstroManager.startTimer(a,this)};f.prototype.do=function(a){this._trace&&this._trace.log("check astro | "+this._getDescription());var b=require("moment-timezone"),f=x.hub.taskman._Util._getTimeZone(),c=(new Date).getTime(),c=b.tz(c,f),e=c.year(),d=this.start;if(d&&("00"==d.substr(0,2)&&(d=e+d.substr(2)),d=b.tz(d,f),
  l.set({hour:0,minute:0,second:0,millisecond:0}),d.valueOf()>c.valueOf())){this._logger.log("trace","condition mismatch:"+JSON.stringify(this.toJSON()));a&&a(null,!1);return}var l=this.end;if(l&&("00"==l.substr(0,2)&&(l=e+l.substr(2)),l=b.tz(l,f),l.set({hour:23,minute:59,second:59,millisecond:999}),l.valueOf()<c.valueOf())){this._logger.log("trace","condition mismatch:"+JSON.stringify(this.toJSON()));a&&a(null,!1);return}if(b=this.week)if(f=c.day(),0==f&&(f=7),"1"!=b.charAt(f-1)){this._logger.log("trace",
  "condition mismatch:"+JSON.stringify(this.toJSON()));a&&a(null,!1);return}b=!1;this.astro&&this.op&&(f=null,f=x.hub.taskman._AstroManager.getSunriseSunset(c.toDate()),f="sunrise"==this.astro?f.sunrise.getTime():f.sunset.getTime(),this.delay&&(f+=6E4*parseInt(this.delay)),">="==this.op&&c.valueOf()>=f?b=!0:">"==this.op&&c.valueOf()>f?b=!0:"<="==this.op&&c.valueOf()<=f?b=!0:"<"==this.op&&c.valueOf()<f?b=!0:"="!=this.op&&"=="!=this.op||c.valueOf()!=f||(b=!0));this._logger.log("trace","condition "+(b?
  "match":"mismatch")+":"+JSON.stringify(this.toJSON()));a&&a(null,b)};f.prototype.finalize=function(a){x.hub.taskman._AstroManager.stopTimer(a)};f.prototype.toJSON=function(){var a=d.prototype.toJSON.call(this);a.astro=this.astro;a.offTime=this.offTime;a.delay=this.delay;a.week=this.week;a.start=this.start;a.end=this.end;a.op=this.op;return a};f.prototype.fromJSON=function(a){a&&(this.astro=a.astro,this.offTime=a.offTime,this.delay=a.delay,this.week=a.week,this.start=a.start,this.end=a.end,this.op=
  a.op)};f.prototype._getDescription=function(){var a;a="astro:"+this.astro;a+=" offTime:"+this.offTime;a+=" delay:"+this.delay;a+=" week:"+this.week;a+=" start:"+this.start;a+=" end:"+this.end;return a+=" op:"+this.op};d.Astro=f;var l=function(){d.call(this);this.type=l.TYPE;this.end=this.start=this.week=this.endTime=this.startTime=this.interval=null;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.Periodic")};util.inherits(l,d);l.TYPE="periodic";l.prototype.init=function(a){x.hub.taskman._PeriodicTimerManager.startTimer(a,
  this)};l.prototype.finalize=function(a){x.hub.taskman._PeriodicTimerManager.stopTimer(a)};l.prototype.toJSON=function(){var a=d.prototype.toJSON.call(this);a.interval=this.interval;a.startTime=this.startTime;a.endTime=this.endTime;a.week=this.week;a.start=this.start;a.end=this.end;return a};l.prototype.fromJSON=function(a){a&&(this.interval=a.interval,this.startTime=a.startTime,this.endTime=a.endTime,this.week=a.week,this.start=a.start,this.end=a.end)};d.Periodic=l;var n=function(){d.call(this);this.type=
  n.TYPE;this._lastTiggerTime=this.ir=null;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.IRTrigger")};util.inherits(n,d);n.TYPE="ir";n.prototype.isMatch=function(a){if(!(a&&a.code&&this.ir&&this.ir.code))return!1;var b=this._getDataCode(this.ir.code);a=this._getDataCode(a.code);if(b==a){b=(new Date).getTime();if(!this._lastTiggerTime)return this._lastTiggerTime=b,!0;if(1E3>b-this._lastTiggerTime)return!1;this._lastTiggerTime=b;return!0}return!1};n.prototype.toJSON=function(){var a=
  d.prototype.toJSON.call(this);a.ir=this.ir;return a};n.prototype.fromJSON=function(a){a&&(this.ir=a.ir)};n.prototype._getDataCode=function(a){a=new Buffer(a,"hex");var b;b=4*a.readInt8(8)+9;return a.slice(b).toString("hex")};d.IRTrigger=n;var m=function(){d.call(this);this.type=m.TYPE;this._cancelCB=this._lastTiggerTime=this.hysteresis=this.value=this.op=this.status=this.gateway=this.device=null;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.DeviceStatus");this._gatewayName=this._deviceName=
  null};util.inherits(m,d);m.TYPE="device.status";m.prototype.init=function(a){if(this.device||this.gateway){var b=null;this.gateway&&this.gateway.sys&&(b=this.gateway.sys);!b&&this.device&&this.device.sys&&(b=this.device.sys);if(b&&("hm"!=b||this.gateway?"neoserver"==b&&(b="aio"):b="aio",(b=require("x.hub.moduleman.js").modulemanager.getModule(b))&&b.addStateDevice)){var f={},c=this._getDevice(),e=this._getGateway();c&&(f=c);delete f.gateway;e&&(f.gateway=e);c=this.status;c.ref&&c.ref.value?c=c.ref.value:
  c.value&&(c=c.value);b.addStateDevice(f,null,{taskID:a,statusKey:c,src:"taskman",callback:this})}}};m.prototype.finalize=function(a){if(this.device||this.gateway){var b=null;this.gateway&&this.gateway.sys&&(b=this.gateway.sys);!b&&this.device&&this.device.sys&&(b=this.device.sys);if(b&&(b=require("x.hub.moduleman.js").modulemanager.getModule(b))&&b.removeStateDevice){var f={},c=this._getDevice(),e=this._getGateway();c&&(f=c);delete f.gateway;e&&(f.gateway=e);c=this.status;c.ref&&c.ref.value?c=c.ref.value:
  c.value&&(c=c.value);b.removeStateDevice(f,null,{taskID:a,statusKey:c,src:"taskman",callback:this})}}};m.prototype.do=function(a){if(this.device||this.gateway)if(this.status&&this.op){var b=this.status;this.status.ref&&(b=this.status.ref);b.value&&(b=b.value);b={value:b};this.status&&this.status.value?b=this.status:this.status&&this.status.ref&&(b=this.status.ref);var f=this,c=this._getDevice(),e=this._getGateway();this._logger.log("trace","get states:"+JSON.stringify(this.toJSON()));this._trace&&
  this._trace.log("get status | "+this._getDescription());this._running=!0;require("x.hub.commandman.js").commandHandler.getState(c,e,b,function(b){if(f._canceling){f._logger.log("trace","get states canceled:"+JSON.stringify(f.toJSON()));f._canceling=!1;b=f._running;f._running=!1;var c=f._cancelCB;f._cancelCB=null;c&&c(null,b)}else if(f._running=!1,!b||b.error?f._trace&&f._trace.log("get status | "+f._getDescription()+" | error:"+(b?b.error.message:"invalid response")):("undefined"==typeof b.data||
  null==b.data)&&f._trace&&f._trace.log("get status | "+f._getDescription()+" | error:no status"),!b||b.error)a&&a(b?b.error:Error("get state error"));else if("undefined"==typeof b.data||null==b.data)a&&a(null,!1);else{var c=b.data.value,e=!1;"="==f.op||"=="==f.op?e="true"==f.value?"true"==String(c):"false"==f.value?"false"==String(c):c==f.value:"!="==f.op?e="true"==f.value?"true"!=String(c):"false"==f.value?"false"!=String(c):c!=f.value:">="==f.op?e=parseFloat(c)>=parseFloat(f.value):">"==f.op?e=parseFloat(c)>
  parseFloat(f.value):"<="==f.op?e=parseFloat(c)<=parseFloat(f.value):"<"==f.op&&(e=parseFloat(c)<parseFloat(f.value));f._logger.log("trace","condition "+(e?"match":"mismatch")+":"+JSON.stringify(f.toJSON()));f._trace&&f._trace.log("get status | "+f._getDescription()+" | success:"+JSON.stringify(b.data)+" | match="+e);a&&a(null,e)}})}else a&&a(Error("no status point or operator"));else a&&a(Error("no device or gateway"))};m.prototype.cancel=function(a){this._running?(this._canceling=!0,this._cancelCB=
  a):a&&a(null,this._running)};m.prototype.isMatch=function(a){if(!a||!a.device)return!1;var b=a.device.sys;b&&"neoserver"!=b||(b="aio");b=require("x.hub.moduleman.js").modulemanager.getModule(b);if(!b||!b.checkDeviceMatch)return!1;var f=this._getDevice(),c=this._getGateway();if(!b.checkDeviceMatch({device:f,gateway:c},a))return!1;b=this.status;b.ref&&b.ref.value?b=b.ref.value:b.value&&(b=b.value);return b!=a.data.key?!1:this.isValueMatch(a)};m.prototype.isValueMatch=function(a){if(!a||!a.data)return!1;
  var b=(new Date).getTime(),f=!1,f="="==this.op?"true"==this.value?"true"==String(a.data.value):"false"==this.value?"false"==String(a.data.value):this.value==a.data.value:">="==this.op?parseFloat(a.data.value)>=parseFloat(this.value):">"==this.op?parseFloat(a.data.value)>parseFloat(this.value):"<="==this.op?parseFloat(a.data.value)<=parseFloat(this.value):"<"==this.op?parseFloat(a.data.value)<parseFloat(this.value):!1,c=this.value;"undefined"!=typeof this.hysteresis&&null!=this.hysteresis&&(c=this.hysteresis);
  var e=!1;if(">"==this.op)e=parseFloat(a.data.value)<=parseFloat(c);else if(">="==this.op)e=parseFloat(a.data.value)<parseFloat(c);else if("<"==this.op)e=parseFloat(a.data.value)>=parseFloat(c);else if("<="==this.op)e=parseFloat(a.data.value)>parseFloat(c);else if("="==this.op||"=="==this.op)e=a.data.value!=c;e&&(this._lastTiggerTime=null);this._trace&&(this._trace.log("trigger | "+this._getDescription()),this._trace.log("receive event | "+JSON.stringify(a.data)+" | hysteresis="+this.hysteresis+" | hit="+
  f));if(f){if(!this._lastTiggerTime)return this._lastTiggerTime=b,!0;if(1E3>b-this._lastTiggerTime||"undefined"!=typeof this.hysteresis&&null!=this.hysteresis&&this._lastTiggerTime||(a=this._getDevice())&&"aio"==a.sys&&"ENOCEAN"==a.type&&("bb-aa-cc"==a.data||"d2-06-10"==a.data)&&this._lastTiggerTime)return!1;this._lastTiggerTime=b;return!0}return!1};m.prototype.onEvent=function(a){try{this.isValueMatch(a)&&this._parent&&this._parent._onTriggered&&this._parent._onTriggered(null,this)}catch(b){}};m.prototype.toJSON=
  function(){var a=d.prototype.toJSON.call(this);a.device=this.device;a.gateway=this.gateway;a.status=this.status;a.op=this.op;a.value=this.value;a.hysteresis=this.hysteresis;return a};m.prototype.fromJSON=function(a){a&&(this.device=a.device,this.gateway=a.gateway,this.status=a.status,this.op=a.op,this.value=a.value,this.hysteresis=a.hysteresis)};m.prototype._getDevice=function(){if(!this.device)return null;var a=null;if(this.device.__neoIndex&&deviceman.deviceManager)try{var b=deviceman.deviceManager.findDeviceWithIndex(this.device.__neoIndex);
  b&&b.info&&(this._deviceName=b.name,a=JSON.parse(JSON.stringify(b.info)))}catch(f){}a||(a=JSON.parse(JSON.stringify(this.device)));return a};m.prototype._getGateway=function(){if(!this.gateway)return null;var a=null;if(this.gateway.__neoIndex&&deviceman.deviceManager)try{var b=deviceman.deviceManager.findGatewayWithIndex(this.gateway.__neoIndex);b&&b.info&&(this._gatewayName=b.name,a=JSON.parse(JSON.stringify(b.info)))}catch(f){}a||(a=JSON.parse(JSON.stringify(this.gateway)));a&&this.gateway.__neoIndex&&
  (a.__neoInfo={db:1,index:this.gateway.__neoIndex});return a};m.prototype._getDescription=function(){var a=null;this._deviceName||this._gatewayName?a=this._deviceName?this._deviceName:this._gatewayName:this.device?a=JSON.stringify(this.device):this.gateway&&(a=JSON.stringify(this.gateway));var b=this.status;this.status.ref&&(b=this.status.ref);b.value&&(b=b.value);return a+" | "+b+this.op+this.value};d.DeviceStatus=m;var u=function(){m.call(this);this.type=u.TYPE;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.CloudDeviceTrigger");
  this._cloudRuleID=null};util.inherits(u,m);u.TYPE="cloud.trigger.device";u.prototype.init=function(a){};u.prototype.finalize=function(a){};u.prototype.toCloudTriggerFormat=function(){var a=this.status;a.ref&&a.ref.value?a=a.ref.value:a.value&&(a=a.value);a={event:{sys:this.device.module,data:{connection:this.device.connection,id:this.device.id,state:a},comp:{value:this.value,operator:this.op}}};if("undefined"!=typeof this.hysteresis&&null!=this.hysteresis)if("="==this.op||"=="==this.op)a.event.comp.hyst=
  .1;else if(">="==this.op||">"==this.op)a.event.comp.hyst=parseFloat(this.value)-parseFloat(this.hysteresis);else if("<="==this.op||"<"==this.op)a.event.comp.hyst=parseFloat(this.hysteresis)-parseFloat(this.value);return a};d.CloudDeviceTrigger=u;var r=function(){d.call(this);this.type=r.TYPE;this.gateway=this.device=null;this.upperThreshold={type:null,op:null,value:null,delay:null,repeat:null};this.lowerThreshold={type:null,op:null,value:null,delay:null,repeat:null};this._upper_threshold_state=0;
  this._upper_threshold_repeat_to=this._upper_threshold_deley_to=null;this._lower_threshold_state=0;this._lower_threshold_repeat_to=this._lower_threshold_deley_to=null;this._lastTigger={upperThreshold:!1,lowerThreshold:!1};this._upperMatchCount=0;this._cancelCB=null;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.DominoswissWS");this._lastHit=null};util.inherits(r,m);r.TYPE="device.dominoswiss.weatherstation";r.prototype.init=function(a){if(this.device||this.gateway){var b=null;
  this.gateway&&this.gateway.sys&&(b=this.gateway.sys);!b&&this.device&&this.device.sys&&(b=this.device.sys);if(b&&(b=require("x.hub.moduleman.js").modulemanager.getModule(b))&&b.addStateDevice){var f={},c=this._getDevice(),e=this._getGateway();c&&(f=c);delete f.gateway;e&&(f.gateway=e);b.addStateDevice(f,null,{taskID:a,statusKey:"*",src:"taskman"})}}};r.prototype.finalize=function(a){if(this.device||this.gateway){var b=null;this.gateway&&this.gateway.sys&&(b=this.gateway.sys);!b&&this.device&&this.device.sys&&
  (b=this.device.sys);if(b&&(b=require("x.hub.moduleman.js").modulemanager.getModule(b))&&b.removeStateDevice){var f={},c=this._getDevice(),e=this._getGateway();c&&(f=c);delete f.gateway;e&&(f.gateway=e);b.removeStateDevice(f,null,{taskID:a,statusKey:"*",src:"taskman"})}}};r.prototype.isMatch=function(a){if(!a||!a.device||!a.device.sys)return!1;var b=require("x.hub.moduleman.js").modulemanager.getModule(a.device.sys);if(!b||!b.checkDeviceMatch)return!1;var f=this._getDevice(),c=this._getGateway();if(!b.checkDeviceMatch({device:f,
  gateway:c},a))return!1;this._logger.log("trace","receive event for device:"+JSON.stringify(a));f=b=!1;c=this._matchUpperThreshold(a);a=this._matchLowerThreshold(a);this._logger.log("trace","upperMatch:"+c+" - lowerMatch:"+a);if("upper"==this._lastHit&&!a)return this._logger.log("trace","lastHit:upper - lowerMatch:"+a),!1;if("lower"==this._lastHit&&!c)return this._logger.log("trace","lastHit:lower - upperMatch:"+c),!1;"upper"==this._lastHit&&a&&(this._lastHit=null);"lower"==this._lastHit&&c&&(this._lastHit=
  null);1==c&&(this._upperMatchCount+=1,65535<this._upperMatchCount&&(this._upperMatchCount=1));switch(this._upper_threshold_state){case 0:1==c&&("undefined"!=typeof this.upperThreshold.delay&&null!=this.upperThreshold.delay&&0<parseInt(this.upperThreshold.delay)?this._handleUpperThresholdDelay():(b=!0,this.upperThreshold.repeat&&this._handleUpperThresholdRepeat()));break;case 1:0==c&&(this._logger.log("trace","upper threshold not match, clear delay timeout"),this._upper_threshold_deley_to&&(clearTimeout(this._upper_threshold_deley_to),
  this._upper_threshold_deley_to=null),this._upper_threshold_state=0);break;case 2:0==c&&(this._logger.log("trace","upper threshold not match, clear repeat timeout"),this._upper_threshold_repeat_to&&(clearTimeout(this._upper_threshold_repeat_to),this._upper_threshold_repeat_to=null),this._upper_threshold_state=0)}switch(this._lower_threshold_state){case 0:1==a&&0<this._upperMatchCount&&("undefined"!=typeof this.lowerThreshold.delay&&null!=this.lowerThreshold.delay&&0<parseInt(this.lowerThreshold.delay)?
  this._handleLowerThresholdDelay():(f=!0,this._upperMatchCount=0,this.lowerThreshold.repeat&&this._handleLowerThresholdRepeat()));break;case 1:0==a&&(this._logger.log("trace","lower threshold not match, clear delay timeout"),this._lower_threshold_deley_to&&(clearTimeout(this._lower_threshold_deley_to),this._lower_threshold_deley_to=null),this._lower_threshold_state=0);break;case 2:0==a&&(this._logger.log("trace","lower threshold not match, clear repeat timeout"),this._lower_threshold_repeat_to&&(clearTimeout(this._lower_threshold_repeat_to),
  this._lower_threshold_repeat_to=null),this._lower_threshold_state=0)}this._lastTigger={upperThreshold:b,lowerThreshold:f};this._logger.log("trace","upperHit:"+b+" - lowerHit:"+f);b?this._lastHit="upper":f&&(this._lastHit="lower");return b|f};r.prototype._matchUpperThreshold=function(a){if(!(this.upperThreshold&&this.upperThreshold.type&&a&&a.data&&a.data.key&&this.upperThreshold.type==a.data.key))return null;var b=this.upperThreshold.op;b||(b=">=");var f=this.upperThreshold.value;if("undefined"==
  typeof f||null==f)f=0;return this._matchThreshold(b,f,a.data.value)};r.prototype._matchLowerThreshold=function(a){if(!(this.lowerThreshold&&this.lowerThreshold.type&&a&&a.data&&a.data.key&&this.lowerThreshold.type==a.data.key))return null;var b=this.lowerThreshold.op;b||(b=">=");var f=this.lowerThreshold.value;if("undefined"==typeof f||null==f)f=0;return this._matchThreshold(b,f,a.data.value)};r.prototype._matchThreshold=function(a,b,f){var c=!1;return c="="==a||"=="==a?"true"==b?"true"==String(f):
  "false"==b?"false"==String(f):b==f:">="==a?parseFloat(f)>=parseFloat(b):">"==a?parseFloat(f)>parseFloat(b):"<="==a?parseFloat(f)<=parseFloat(b):"<"==a?parseFloat(f)<parseFloat(b):!1};r.prototype._handleUpperThresholdDelay=function(){var a=this;this._upper_threshold_state=1;this._logger.log("trace","start upper threshold hit delay timeout:"+parseInt(this.upperThreshold.delay));this._upper_threshold_deley_to=setTimeout(function(){a._logger.log("trace","upper threshold delay timeout expired");a._lastTigger=
  {upperThreshold:!0,lowerThreshold:!1};if(a._parent&&"root"==a._parent.type)try{a._lastHit="upper",a._parent._onTriggered(null,a)}catch(b){}a.upperThreshold.repeat?a._handleUpperThresholdRepeat():a._upper_threshold_state=0},1E3*parseInt(this.upperThreshold.delay))};r.prototype._handleLowerThresholdDelay=function(){var a=this;this._lower_threshold_state=1;this._logger.log("trace","start lower threshold hit delay timeout:"+parseInt(this.lowerThreshold.delay));this._lower_threshold_delay_to=setTimeout(function(){a._lastTigger=
  {upperThreshold:!1,lowerThreshold:!0};a._upperMatchCount=0;a._logger.log("trace","lower threshold delay timeout expired");if(a._parent&&"root"==a._parent.type)try{a._lastHit="lower",a._parent._onTriggered(null,a)}catch(b){}a.lowerThreshold.repeat?a._handleLowerThresholdRepeat():a._lower_threshold_state=0},1E3*parseInt(this.lowerThreshold.delay))};r.prototype._handleUpperThresholdRepeat=function(){var a=this;this._upper_threshold_state=2;var b=this.upperThreshold.repeat,f=0;if(b&&"string"==typeof b&&
  b.match(/^([0-1]?[0-9]|2[0-3])(:[0-5][0-9])?$/g)){var f=require("moment-timezone"),c=x.hub.taskman._Util._getTimeZone(),e=(new Date).getTime(),e=f.tz(e,c),d=parseInt(b.substr(0,b.indexOf(":"))),b=parseInt(b.substr(b.indexOf(":")+1)),l=(new Date).getTime(),l=f.tz(l,c);l.set({hour:d,minute:b,second:0,millisecond:0});f=l.valueOf()-e.valueOf();if(0>f){this._upper_threshold_state=0;return}}else if(0<parseInt(b))f=1E3*parseInt(b);else{this._upper_threshold_state=0;return}this._logger.log("trace","start upper threshold hit repeat timeout:"+
  Math.round(f/1E3));this._upper_threshold_repeat_to=setTimeout(function(){a._logger.log("trace","upper threshold repeat timeout expired");a._upper_threshold_state=0;a._lastTigger={upperThreshold:!0,lowerThreshold:!1};if(a._parent&&"root"==a._parent.type)try{a._lastHit="upper",a._parent._onTriggered(null,a)}catch(b){}},f)};r.prototype._handleLowerThresholdRepeat=function(){var a=this;this._lower_threshold_state=2;var b=this.lowerThreshold.repeat,f=0;if(b&&"string"==typeof b&&b.match(/^([0-1]?[0-9]|2[0-3])(:[0-5][0-9])?$/g)){var f=
  require("moment-timezone"),c=x.hub.taskman._Util._getTimeZone(),e=(new Date).getTime(),e=f.tz(e,c),d=parseInt(b.substr(0,b.indexOf(":"))),b=parseInt(b.substr(b.indexOf(":")+1)),l=(new Date).getTime(),l=f.tz(l,c);l.set({hour:d,minute:b,second:0,millisecond:0});f=l.valueOf()-e.valueOf();if(0>f){this._lower_threshold_state=0;return}}else if(0<parseInt(b))f=1E3*parseInt(b);else{this._lower_threshold_state=0;return}this._logger.log("trace","start lower threshold hit repeat timeout:"+Math.round(f/1E3));
  this._lower_threshold_repeat_to=setTimeout(function(){a._logger.log("trace","lower threshold repeat timeout expired");a._upperMatchCount=0;a._lower_threshold_state=0;a._lastTigger={upperThreshold:!1,lowerThreshold:!0};if(a._parent&&"root"==a._parent.type)try{a._lastHit="lower",a._parent._onTriggered(null,a)}catch(b){}},f)};r.prototype.toJSON=function(){var a=d.prototype.toJSON.call(this);a.device=this.device;a.gateway=this.gateway;a.upperThreshold=this.upperThreshold;a.lowerThreshold=this.lowerThreshold;
  return a};r.prototype.fromJSON=function(a){a&&(this.device=a.device,this.gateway=a.gateway,this.upperThreshold=a.upperThreshold,this.lowerThreshold=a.lowerThreshold)};d.DominoswissWS=r;var p=function(){d.call(this);this.type=p.TYPE};util.inherits(p,d);p.TYPE="action";d.Action=p;var C=function(){p.call(this);this.subtype=C.SUBTYPE;this.body=this.event=this.key=null;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.IFTTTMakerAction")};util.inherits(C,p);C.SUBTYPE="iftttmaker";C.prototype.do=
  function(a){if(this.key||this.event){var b=a;a={hostname:"maker.ifttt.com",port:443,path:"/trigger/"+this.event+"/with/key/"+this.key,method:"POST",headers:{"Content-Type":"application/json"}};this._logger.log("trace","send https:"+JSON.stringify(a));this._logger.log("trace","with data:"+JSON.stringify(this.body));var f=this;a=require("https").request(a,function(a){a.setEncoding("utf8");var c="";a.on("data",function(a){c+=a});a.on("end",function(){f._logger.log("trace","action response:"+a.statusCode);
  f._logger.log("trace","with data:"+c);b&&(b(null,a.statusCode,c),b=null)})});a.on("error",function(a){f._logger.log("debug","do action err:"+a.stack);b&&(b(a),b=null)});a.setTimeout(5E3,function(){f._logger.log("debug","do action timeout");b&&(b(Error("timeout")),b=null)});if(this.body)try{var c=JSON.stringify(this.body);a.write(c)}catch(e){}a.end()}else a&&a(Error("no key or event"))};C.prototype.toJSON=function(){var a=p.prototype.toJSON.call(this);a.subtype=this.subtype;a.key=this.key;a.event=
  this.event;a.body=this.body;return a};C.prototype.fromJSON=function(a){a&&(this.key=a.key,this.event=a.event,this.body=a.body)};d.IFTTTMakerAction=C;var z=function(){p.call(this);this.subtype=z.SUBTYPE;this._cancelCB=this._doCB=this.body=this.headers=this.query=this.pathname=this.port=this.hostname=this.auth=this.protocol=this.method=null;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.HttpAction")};util.inherits(z,p);z.SUBTYPE="http.action";z.prototype.do=function(a){var b=this.method;
  b||(b="GET");var f=this.protocol;f||(f="http");var c=this.port;if(!c||0>=parseInt(c))c="https"==f?443:80;var e=require("querystring"),d=this.pathname?this.pathname:"/";this.query&&(d+="?"+e.stringify(this.query));c={hostname:this.hostname,port:c,path:d,method:b,headers:this.headers};this.auth&&(c.auth=this.auth);this._logger.log("trace","send "+f+" "+b+":"+JSON.stringify(c));this._logger.log("trace","with data:"+JSON.stringify(this.body));this._trace&&(this._trace.log("execute http | "+f+" "+b+":"+
  JSON.stringify(c)),this._trace.log("execute http | with data:"+JSON.stringify(this.body)));this._running=!0;this._doCB=a;var l=this;a=require(f).request(c,function(a){a.setEncoding("utf8");var b="";a.on("data",function(a){b+=a});a.on("end",function(){l._logger.log("trace","action response:"+a.statusCode);l._logger.log("trace","with data:"+b);l._trace&&(l._trace.log("execute http | response code:"+a.statusCode),l._trace.log("execute http | response data:"+b));l._doCB&&(l._running=!1,l._doCB(null,a.statusCode,
  b),l._doCB=null)})});a.on("error",function(a){l._trace&&l._trace.log("execute http | error:"+a.message);l._logger.log("debug","do action err:"+a.stack);l._doCB&&(l._running=!1,l._doCB(a),l._doCB=null)});a.setTimeout(5E3,function(){l._trace&&l._trace.log("execute http | error:timeout");l._logger.log("debug","do action timeout");l._doCB&&(l._running=!1,l._doCB(Error("timeout")),l._doCB=null)});if(this.body&&"GET"!=b&&"DELETE"!=b)if("string"==typeof this.body)a.write(this.body);else try{var h=JSON.stringify(this.body);
  a.write(h)}catch(n){}a.end()};z.prototype.cancel=function(a){this._running?(this._logger.log("trace","http action canceled"),this._doCB=null,this._running=!1,a&&a(null,!0)):a&&a(null,this._running)};z.prototype.toJSON=function(){var a=p.prototype.toJSON.call(this);a.subtype=this.subtype;a.method=this.method;a.protocol=this.protocol;a.auth=this.auth;a.hostname=this.hostname;a.port=this.port;a.pathname=this.pathname;a.query=this.query;a.headers=this.headers;a.body=this.body;return a};z.prototype.fromJSON=
  function(a){a&&(this.subtype=a.subtype,this.method=a.method,this.protocol=a.protocol,this.auth=a.auth,this.hostname=a.hostname,this.port=a.port,this.pathname=a.pathname,this.query=a.query,this.headers=a.headers,this.body=a.body)};d.HttpAction=z;var t=function(){p.call(this);this.subtype=t.SUBTYPE;this._cancelCB=this.command=this.gateway=this.device=null;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.CommandAction");this._gatewayName=this._deviceName=null};util.inherits(t,p);t.SUBTYPE=
  "command";t.prototype.do=function(a,b){if(this.device||this.gateway)if(this.command){var f=this.command;f.ref&&(f=f.ref);var c=require("x.hub.commandman.js").commandHandler;this._logger.log("trace","do command:"+JSON.stringify(this.toJSON()));var e=this._getDevice(),l=this._getGateway();if(e&&"sonos"==e.sys&&f&&"playAlarm"==f.value&&(f=this._buildSonosCommand(f.ext),!f))return;this._running=!0;this._trace&&this._trace.log("execute command | "+this._getDescription());var d=this;c.executeCommand(e,
  l,f,function(b){b&&b.error?d._trace&&d._trace.log("execute command | "+d._getDescription()+" | error:"+b.error.message):d._trace&&d._trace.log("execute command | "+d._getDescription()+" | success");if(d._canceling){d._logger.log("trace","command action canceled:"+JSON.stringify(d.toJSON()));d._canceling=!1;b=d._running;d._running=!1;var f=d._cancelCB;d._cancelCB=null;f&&f(null,b)}else d._running=!1,a&&a()})}else a&&a(Error("no command"));else a&&a(Error("no device or gateway"))};t.prototype.cancel=
  function(a){this._running?(this._canceling=!0,this._cancelCB=a):a&&a(null,this._running)};t.prototype.toJSON=function(){var a=p.prototype.toJSON.call(this);a.subtype=this.subtype;a.device=this.device;a.gateway=this.gateway;a.command=this.command;return a};t.prototype.fromJSON=function(a){a&&(this.device=a.device,this.gateway=a.gateway,this.command=a.command)};t.prototype._getDevice=function(){if(!this.device)return null;var a=null;if(this.device.__neoIndex&&deviceman.deviceManager)try{var b=deviceman.deviceManager.findDeviceWithIndex(this.device.__neoIndex);
  b&&b.info&&(this._deviceName=b.name,a=JSON.parse(JSON.stringify(b.info)))}catch(f){}a||(a=JSON.parse(JSON.stringify(this.device)));return a};t.prototype._getGateway=function(){if(!this.gateway)return null;var a=null;if(this.gateway.__neoIndex&&deviceman.deviceManager)try{var b=deviceman.deviceManager.findGatewayWithIndex(this.gateway.__neoIndex);b&&b.info&&(this._gatewayName=b.name,a=JSON.parse(JSON.stringify(b.info)))}catch(f){}a||(a=JSON.parse(JSON.stringify(this.gateway)));a&&this.gateway.__neoIndex&&
  (a.__neoInfo={db:1,index:this.gateway.__neoIndex});return a};t.prototype._getDescription=function(){var a=null;this._deviceName||this._gatewayName?a=this._deviceName?this._deviceName:this._gatewayName:this.device?a=JSON.stringify(this.device):this.gateway&&(a=JSON.stringify(this.gateway));var b=this.command;b.ref&&(b=b.ref);return a+" | "+JSON.stringify(b)};t.prototype._getLocalIP=function(){var a=require("os").networkInterfaces(),b;for(b in a)for(var f=a[b],c=0;c<f.length;c++){var e=f[c];if(e&&"IPv4"==
  e.family&&0==e.internal)return e.address}return null};t.prototype._getLocalPort=function(){var a=require("x.hub.js");return a.server?a.server._port:null};t.prototype._buildSonosCommand=function(a){var b=this._getLocalIP(),f=this._getLocalPort();if(!b||!f)return null;var c=null;switch(a){case "alarm_on":c="alarm_on.mp3";break;case "alarm_off":c="alarm_off.mp3";break;case "pre_alarm":c="pre_alarm.mp3";break;case "alarm":c="alarm.mp3";break;default:return null}return{value:"playUrl",ext:"http://"+b+
  ":"+f+"/resources/rehau_alarm/"+c}};d.CommandAction=t;var H=function(){p.call(this);this.subtype=H.SUBTYPE;this._cancelCB=this.command=this.gateway=this.device=null;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.BrelagUpperThresholdAction")};util.inherits(H,t);H.SUBTYPE="command.dominoswiss.upperthreshold";H.prototype.do=function(a,b){if(b&&b.trigger&&b.trigger.type==r.TYPE){var f=b.trigger._lastTigger;f&&f.upperThreshold?t.prototype.do.call(this,a,b):a&&a()}else a&&a()};d.BrelagUpperThresholdAction=
  H;var I=function(){p.call(this);this.subtype=I.SUBTYPE;this._cancelCB=this.command=this.gateway=this.device=null;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.BrelagLowerThresholdAction")};util.inherits(I,t);I.SUBTYPE="command.dominoswiss.lowerthreshold";I.prototype.do=function(a,b){if(b&&b.trigger&&b.trigger.type==r.TYPE){var f=b.trigger._lastTigger;f&&f.lowerThreshold?t.prototype.do.call(this,a,b):a&&a()}else a&&a()};d.BrelagUpperThresholdAction=I;var D=function(){p.call(this);
  this.subtype=D.SUBTYPE;this.actionID=null;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.CloudAction")};util.inherits(D,p);D.SUBTYPE="cloud_action";D.prototype.do=function(a){if(this.actionID){this._logger.log("trace","do cloud action:"+this.actionID);var b=require("x.hub.js").server;if(b)if(b=b._cloudConnect){var f=JSON.stringify({type:"ACTION",data:this.actionID}),f=new Buffer("EVT:"+f,"utf8");b.sendMessageActive("0103"+f.toString("hex"),function(b){a&&a(b)})}else a&&a(Error("no cloud connect"));
  else a&&a(Error("no server in hub"))}else a&&a(Error("action id is empty"))};D.prototype.cancel=function(a){a&&a(null,!1)};D.prototype.toJSON=function(){var a=p.prototype.toJSON.call(this);a.subtype=this.subtype;a.actionID=this.actionID;return a};D.prototype.fromJSON=function(a){a&&(this.actionID=a.actionID)};var v=function(){p.call(this);this.subtype=v.SUBTYPE;this.macroName=this.groupName=null;this._canceling=!1;this._macroExecutorID=this._cancelCB=null;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.MacroAction")};
  util.inherits(v,p);v.SUBTYPE="macro";v.prototype.do=function(a){if(this.groupName&&this.macroName){var b=require("x.hub.macroman.js");this._logger.log("trace","do macro:"+JSON.stringify(this.toJSON()));var f=this;this._running=!0;this._trace&&this._trace.log("execute macro | "+this._getDescription());b.execute(this.groupName,this.macroName,function(b){f._trace&&f._trace.log("execute macro | "+f._getDescription()+" | return:"+JSON.stringify(b));f._canceling?(f._logger.log("trace","macro action canceled:"+
  JSON.stringify(f.toJSON())),f._canceling=!1,f._running=!1,b=f._cancelCB,f._cancelCB=null,b&&b()):(f._running=!1,a&&a(b))},function(a){a&&a.id&&(f._macroExecutorID=a.id)})}else a&&a(Error("no group or macro"))};v.prototype.cancel=function(a){this._running?(this._canceling=!0,this._cancelCB=a,this._macroExecutorID&&require("x.hub.macroman.js").cancel(this._macroExecutorID)):a&&a(null,this._running)};v.prototype.toJSON=function(){var a=p.prototype.toJSON.call(this);a.subtype=this.subtype;a.groupName=
  this.groupName;a.macroName=this.macroName;return a};v.prototype.fromJSON=function(a){a&&(this.groupName=a.groupName,this.macroName=a.macroName)};v.prototype._getDescription=function(){return this.groupName+"."+this.macroName};d.MacroAction=v;var A=function(){p.call(this);this._cancelCB=this.token=null;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.SnsAction")};util.inherits(A,p);A.prototype.do=function(a){if(this.token){var b=this;this._logger.log("trace","do sns:"+JSON.stringify(this.toJSON()));
  var f=new x.hub.taskman.Cloud;this._running=!0;this._trace&&this._trace.log("execute sns | "+this._getDescription());f._doRequest("GET","/xhub/sns/dosns?token="+this.token,null,null,null,null,function(f,c){b._trace&&b._trace.log("execute sns | "+b._getDescription()+" | "+(f?"error:"+f.message:"response:"+c));if(b._canceling){b._logger.log("trace","sns action canceled:"+JSON.stringify(b.toJSON()));b._canceling=!1;var e=b._running;b._running=!1;var d=b._cancelCB;b._cancelCB=null;d&&d(null,e)}else b._running=
  !1,f&&b._logger.log("warn","do sns error:"+f.stack),a&&a(f)})}else a&&a(Error("token is empty"))};A.prototype.cancel=function(a){this._running?(this._canceling=!0,this._cancelCB=a):a&&a(null,this._running)};A.prototype._getDescription=function(){return this.subtype+"."+this.token};var E=function(){A.call(this);this.subtype=E.SUBTYPE;this.token=null};util.inherits(E,A);E.SUBTYPE="EMAIL";E.prototype.toJSON=function(){var a=p.prototype.toJSON.call(this);a.subtype=this.subtype;a.token=this.token;return a};
  E.prototype.fromJSON=function(a){a&&(this.token=a.token)};d.EmailAction=E;var F=function(){A.call(this);this.subtype=F.SUBTYPE;this.token=null};util.inherits(F,A);F.SUBTYPE="PUSH";F.prototype.toJSON=function(){var a=p.prototype.toJSON.call(this);a.subtype=this.subtype;a.token=this.token;return a};F.prototype.fromJSON=function(a){a&&(this.token=a.token)};d.PushAction=F;var G=function(){A.call(this);this.subtype=G.SUBTYPE;this.token=null};util.inherits(G,A);G.SUBTYPE="SMS";G.prototype.toJSON=function(){var a=
  p.prototype.toJSON.call(this);a.subtype=this.subtype;a.token=this.token;return a};G.prototype.fromJSON=function(a){a&&(this.token=a.token)};d.SmsAction=G;var J=function(a,b){this._runCallback=b;this._finishCallback=null;this._action=a;var f=this;this.runCallback=function(a){f._action.removeRunTask(f);f._runCallback&&f._runCallback(a)};this.finishCallback=function(){f._action.removeRunTask(f)}},w=function(){p.call(this);this.subtype=w.SUBTYPE;this.name=this.id=null;this._scriptRunTasks=[];this._logger=
  require("x.logger.js").getLogger("x.hub.taskman._Block.ScriptAction")};util.inherits(w,p);w.SUBTYPE="script";w.prototype.do=function(a){if(this.id){var b=require("x.hub.scriptman.js").scriptManager;this._logger.log("trace","do script:"+JSON.stringify(this.toJSON()));this._running=!0;a=new J(this,a);this._scriptRunTasks.push(a);this._trace&&this._trace.log("execute skript | "+this.id);b.runScript(this.id,a.runCallback,a.finishCallback)}else a&&a(Error("no script id"))};w.prototype.cancel=function(a){if(this._running){var b=
  require("x.hub.scriptman.js").scriptManager;this._scriptRunTasks=[];this._running=!1;this._logger.log("trace","script action canceled:"+JSON.stringify(this.toJSON()));b.stopScript(this.id,function(){a&&a(null,!0)})}else a&&a(null,this._running)};w.prototype.removeRunTask=function(a){a=this._scriptRunTasks.indexOf(a);-1!=a&&this._scriptRunTasks.splice(a,1);0==this._scriptRunTasks.length&&(this._running=!1)};w.prototype.toJSON=function(){var a=p.prototype.toJSON.call(this);a.subtype=this.subtype;a.id=
  this.id;a.name=this.name;return a};w.prototype.fromJSON=function(a){a&&(this.id=a.id,this.name=a.name)};d.ScriptAction=w;var B=function(){p.call(this);this.subtype=B.SUBTYPE;this._to=this.value=null;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.WaitAction")};util.inherits(B,p);B.SUBTYPE="wait";B.prototype.do=function(a){if(this.value){this._running=!0;var b=this;this._trace&&this._trace.log("execute wait | wait "+this.value+" ms");this._to=setTimeout(function(){b._trace&&b._trace.log("execute wait | wait expired");
  b._running=!1;b._to=null;a&&a()},this.value)}else a&&a()};B.prototype.cancel=function(a){this._running?(this._to&&(this._logger.log("trace","wait action canceled:"+JSON.stringify(this.toJSON())),clearTimeout(this._to),this._to=null),this._running=!1,a&&a(null,!0)):a&&a(null,this._running)};B.prototype.toJSON=function(){var a=p.prototype.toJSON.call(this);a.subtype=this.subtype;a.value=this.value;return a};B.prototype.fromJSON=function(a){a&&(this.value=a.value)};d.WaitAction=B;var y=function(){p.call(this);
  this.subtype=y.SUBTYPE;this.page=this.remote=null;this._logger=require("x.logger.js").getLogger("x.hub.taskman._Block.ChangePageAction");this._cancelCB=null};util.inherits(y,p);y.SUBTYPE="remote.changepage";y.prototype.do=function(a){this._trace&&this._trace.log("execute change page | "+this.remote+"."+this.page);this._running=!0;var b=[],f=require("os").networkInterfaces(),c;for(c in f)for(var e=f[c],d=0;d<e.length;d++){var l=e[d];"IPv4"==l.family&&0==l.internal&&b.push(l.address)}var h=this,n=0,
  k=function(){if(h._canceling){h._logger.log("trace","change page action canceled:"+JSON.stringify(h.toJSON()));h._canceling=!1;var f=h._running;h._running=!1;var c=h._cancelCB;h._cancelCB=null;c&&c(null,f)}else n++,n>=b.length?(h._running=!1,a&&a()):h._sendEvent(b[n],k)};this._sendEvent(b[n],k)};y.prototype.cancel=function(a){this._running?(this._canceling=!0,this._cancelCB=a):a&&a(null,this._running)};y.prototype._sendEvent=function(a,b){var f=require("dgram"),c=require("unorm"),e={func:"changePage",
  remote:c.nfc(this.remote),page:c.nfc(this.page)},e=new Buffer("{XC_EVT}"+JSON.stringify(e),"utf8"),d=f.createSocket({type:"udp4",reuseAddr:!0});d.bind(a,function(){d.setBroadcast(!0);d.send(e,0,e.length,1902,"255.255.255.255");d.send(e,0,e.length,1902,"255.255.255.255",function(a){d.close();b&&b(a)})})};y.prototype.toJSON=function(){var a=p.prototype.toJSON.call(this);a.subtype=this.subtype;a.remote=this.remote;a.page=this.page;return a};y.prototype.fromJSON=function(a){a&&(this.remote=a.remote,this.page=
  a.page)};d.ChangePageAction=y;d.parse=function(g){if(!g||!g.type)return null;var q=null;switch(g.type){case c.TYPE:q=d.Root;break;case b.TYPE:q=b;break;case p.TYPE:switch(g.subtype){case t.SUBTYPE:q=t;break;case H.SUBTYPE:q=H;break;case I.SUBTYPE:q=I;break;case E.SUBTYPE:q=E;break;case F.SUBTYPE:q=F;break;case G.SUBTYPE:q=G;break;case w.SUBTYPE:q=w;break;case B.SUBTYPE:q=B;break;case v.SUBTYPE:q=v;break;case C.SUBTYPE:q=C;break;case z.SUBTYPE:q=z;break;case y.SUBTYPE:q=y;break;case D.SUBTYPE:q=D;
  break;default:return null}break;case m.TYPE:q=m;break;case r.TYPE:q=r;break;case a.TYPE:q=a;break;case f.TYPE:q=f;break;case l.TYPE:q=l;break;case e.TYPE:q=e;break;case h.TYPE:q=h;break;case k.TYPE:q=k;break;case n.TYPE:q=n;break;case u.TYPE:q=u;break;default:return null}q=new q;q.fromJSON(g);return q};return d}();
  x.hub.taskman.Task=function(){var d=function(b){this._logger=require("x.logger.js").getLogger("x.hub.taskman.Task");this.root=this.name=this.id=null;this.active=!0;this.singleton=this.rehauAlarmTask=this.isAlarmTask=!1;this.singletonMethod="ignore";this._trace=null;b&&(this.id=b.id,this.name=b.name,this.active=b.active,this.isAlarmTask=b.isAlarmTask,this.rehauAlarmTask=b.rehauAlarmTask,this.singleton=b.singleton,this.singletonMethod=b.singletonMethod);if("undefined"==typeof this.active||null==this.active)this.active=
  !0;if("undefined"==typeof this.isAlarmTask||null==this.isAlarmTask)this.isAlarmTask=!1;if("undefined"==typeof this.rehauAlarmTask||null==this.rehauAlarmTask)this.rehauAlarmTask=!1};d.prototype.init=function(){this.root&&this.root.init(this.id)};d.prototype.getTriggers=function(){return this.root?this.root.getTriggers():[]};d.prototype.finalize=function(){try{this.root&&this.root.finalize(this.id)}catch(b){this._logger.log("warn","finalize task "+this.id+" error:"+b.message)}};d.prototype.trigger=
  function(b){this.root?(this.root._onTriggered(),b&&b()):b&&b(Error("no content"))};d.prototype.cancel=function(b){this.root?(this.root.cancel(),b&&b()):b&&b(Error("no content"))};d.prototype.isActive=function(){return this.active};d.prototype.setActive=function(b){if("undefined"==typeof b||null==b)b=!0;"string"==typeof b&&(b="false"==b?!1:!0);this.active=b};d.prototype.toggleActive=function(){this.active=!this.active};d.prototype.setRehauAlarmTask=function(b){this.rehauAlarmTask=b};d.prototype.isRehauAlarmTask=
  function(){return this.rehauAlarmTask};d.prototype.setAlarmTask=function(b){if("undefined"==typeof b||null==b)b=!1;"string"==typeof b&&(b="false"==b?!1:!0);this.isAlarmTask=b};d.prototype.isRunning=function(){return this.root?this.root.isRunning():!1};d.prototype.onStatusEvt=function(b){this._logger.log("trace","task "+this.id+" (active:"+this.active+", root:"+(this.root?!0:!1)+") receive status");if(this.active&&this.root&&(!this.isAlarmTask||require("x.hub.taskman.js").taskManager._alarmTask._active))this.root.onStatusEvt(b)};
  d.prototype.onStatusEvtForTask=function(b){this._logger.log("trace","task "+this.id+" (active:"+this.active+", root:"+(this.root?!0:!1)+") receive dedicated status");if(this.active&&this.root&&(!this.isAlarmTask||require("x.hub.taskman.js").taskManager._alarmTask._active))this.root.onDedicatedStatusEvt(b)};d.prototype.onIREvt=function(b){this._logger.log("trace","task "+this.id+" (active:"+this.active+", root:"+(this.root?!0:!1)+") receive ir event");if(this.active&&this.root&&(!this.isAlarmTask||
  require("x.hub.taskman.js").taskManager._alarmTask._active))this.root.onIREvt(b)};d.prototype.onTimerTick=function(){this._logger.log("trace","task "+this.id+" (active:"+this.active+", root:"+(this.root?!0:!1)+") receive timer tick");if(this.active&&this.root&&(!this.isAlarmTask||require("x.hub.taskman.js").taskManager._alarmTask._active))this.root.onTimerTick()};d.prototype.onHttpEvt=function(b,c){this._logger.log("trace","task "+this.id+" (active:"+this.active+", root:"+(this.root?!0:!1)+") receive http event");
  if(this.active&&this.root)if(this.isAlarmTask&&!require("x.hub.taskman.js").taskManager._alarmTask._active)c&&c(null,!1);else this.root.onHttpEvt(b,c);else c&&c(null,!1)};d.prototype.toJSON=function(){var b={id:this.id,name:this.name,active:this.active,isAlarmTask:this.isAlarmTask,rehauAlarmTask:this.rehauAlarmTask,singleton:this.singleton,singletonMethod:this.singletonMethod,root:{}};this.root&&(b.root=this.root.toJSON());return b};d.prototype.startTaskTrace=function(b,c){this._trace||(this._trace=
  new x.hub.taskman.TaskTrace(this),this.root&&this.root.setTrace(this._trace));this._trace.addListener(b);c&&c()};d.prototype.stopTaskTrace=function(b,c){this._trace&&(this._trace.removeListener(b),0==this._trace.getListeners().length&&(this.root&&this.root.setTrace(null),this._trace=null));c&&c()};d.prototype.toCloudRuleJSON=function(b,c,e,d,k){var a=[],f=this.getTriggers();if(!f||0==f.length)return null;for(var l=0;l<f.length;l++){var n=f[l];n&&"cloud.trigger.device"==n.type&&(n=n.toCloudTriggerFormat())&&
  a.push(n)}return 0==a.length?null:{name:this.name,owner:c,app:b,action:[{sys:"mediola",data:{data:{XC_FNC:"DoTask",id:this.id},token:k,ccs:e+(d?":"+d:""),cmd:"cmd"}}],trigger:a}};d.prototype.getCloudDeviceTriggerGateway=function(){if(!this.root)return null;var b=this.root.getTriggers(),c=null;if(!b||0>=b.length)return null;for(var e=0;e<b.length;e++){var d=b[e];if(d&&"cloud.trigger.device"==d.type&&(c=d._getGateway()))break}return c};d.parse=function(b){if(!b||!b.id||!b.name)return null;var c=new d(b);
  b.root&&(c.root=x.hub.taskman._Block.parse(b.root),c.root&&(c.root._task=c,c.root.singleton=c.singleton,c.root.singletonMethod=c.singletonMethod));return c};return d}();
  x.hub.taskman.AlarmTask=function(){var d=function(){this._active=!1;this._delay=0;this._activateDelayTO=null};d.prototype.init=function(){this._active="true"==localStorage.getItem("x.hub.taskman.TaskManager.alarmActive");this._delay=parseInt(localStorage.getItem("x.hub.taskman.TaskManager.alarmDelay"))};d.prototype.setAlarmActive=function(b,c,e,d){var k=function(a,b,c){if("undefined"==typeof b||null==b)b=!0;"string"==typeof b&&(b="false"==b?!1:!0);a._tasks.forEach(function(a){a.isAlarmTask&&(a.active=
  b)});a._writeData(c)};if(this._getAlarmPin()!=c)c=Error("pin error"),c.code=x.hub.taskman.ERROR_CODE.Pin_Error,d&&d(c);else if(this._activateDelayTO&&(clearTimeout(this._activateDelayTO),this._activateDelayTO=null),this._delay&&b){var a=this;this._activateDelayTO=setTimeout(function(){localStorage.setItem("x.hub.taskman.TaskManager.alarmActive",b);a._active=b;a._activateDelayTO=null;k(e,b)},1E3*this._delay);d&&d()}else localStorage.setItem("x.hub.taskman.TaskManager.alarmActive",b),this._active=b,
  k(e,b,d)};d.prototype.setAlarmDelay=function(b,c,e){this._getAlarmPin()!=c?(b=Error("pin error"),b.code=x.hub.taskman.ERROR_CODE.Pin_Error,e&&e(b)):(localStorage.setItem("x.hub.taskman.TaskManager.alarmDelay",b),this._delay=b,e&&e())};d.prototype.getAlarmInfo=function(b){b&&b(null,{active:this._active,delay:this._delay?this._delay:0,pendingActive:null!=this._activateDelayTO})};d.prototype.selectAlarmTask=function(b,c,e,d,k){if(b){for(var a=null,f=0;f<d.length;f++){var l=d[f];if(l.id==b){a=l;break}}a?
  (b=this._getAlarmPin(),e&&e==b?this._active?k&&k(Error("alarm task active")):(a.setAlarmTask(c),k&&k()):(c=Error("pin error"),c.code=x.hub.taskman.ERROR_CODE.Pin_Error,k&&k(c))):k&&k(Error("no such task:"+b))}else k&&k(Error("task id is null"))};d.prototype._getAlarmPin=function(){return localStorage.getItem("x.hub.taskman.TaskManager.alarmPin")?localStorage.getItem("x.hub.taskman.TaskManager.alarmPin"):d.DEFAULT_PIN};d.prototype.setAlarmPin=function(b,c,e){var d=this._getAlarmPin();b?c!=d?(b=Error("pin error"),
  b.code=x.hub.taskman.ERROR_CODE.Pin_Error,e&&e(b)):(localStorage.setItem("x.hub.taskman.TaskManager.alarmPin",b),e&&e()):e&&e(Error("new pin invalid"))};d.DEFAULT_PIN="0000";return d}();
  x.hub.taskman.TaskTrace=function(){var d=function(b){this._logger=require("x.logger.js").getLogger("x.hub.taskman.TaskTrace");this._task=b;this._listeners=[]};d.prototype.addListener=function(b){b&&-1==this._listeners.indexOf(b)&&this._listeners.push(b)};d.prototype.removeListener=function(b){b&&(b=this._listeners.indexOf(b),-1!=b&&this._listeners.splice(b,1))};d.prototype.getListeners=function(b){return this._listeners};d.prototype.log=function(b){this._logger.log("trace","[Task "+this._task.id+
  "]:"+b);b="["+this._getTimestamp()+"] "+b;this._listeners.forEach(function(c){c&&c(b)})};d.prototype._getTimestamp=function(){return(new Date).toTimeString()};return d}();x.hub.taskman.rehau={};
  x.hub.taskman.rehau.AlarmTaskManager=function(){var d=function(){this._logger=Logger.getLogger("x.hub.taskman.rehau.AlarmTask.AlarmDoor");this._alarmTask=this._activateEvent=this._device=this._id=null};d.prototype.init=function(){if(this._device){var a=require("x.hub.moduleman.js").modulemanager.getModule("aio");a&&a.addStateDevice&&this._activateEvent&&this._activateEvent.status&&a.addStateDevice(this._device,null,{alarmTaskID:this._alarmTask.getID(),statusKey:this._activateEvent.status,src:"rehau:alarmTask"})}};
  d.prototype.finalize=function(){if(this._device){var a=require("x.hub.moduleman.js").modulemanager.getModule("aio");a&&a.removeStateDevice&&this._activateEvent&&this._activateEvent.status&&a.removeStateDevice(this._device,null,{alarmTaskID:this._alarmTask.getID(),statusKey:this._activateEvent.status,src:"rehau:alarmTask"})}};d.prototype.setAlarmTask=function(a){this._alarmTask=a};d.prototype.getID=function(){return this._id};d.prototype.setID=function(a){this._id=a};d.prototype.setDevice=function(a){this._device=
  a};d.prototype.setActivateEvent=function(a){this._activateEvent=a};d.prototype.toJSON=function(){return{id:this._id,device:this._device,activateEvent:this._activateEvent}};d.prototype.matchDevice=function(a){return this._device&&a?this._device.type==a.type&&this._device.address==a.address:!1};d.prototype.onStatusEvt=function(a){a&&a.data&&this._activateEvent&&this._activateEvent.status==a.data.key&&this._activateEvent.value==a.data.value&&(this._logger.log("trace","alarm door:"+this._device.address+
  " receive event:"+a.data.value+" and trigger door alarm"),this._alarmTask&&this._alarmTask.triggerDoorAlarm())};d.buildDoorfromJSON=function(a){if(!a||!a.device)return null;var b=new d;b.setID(a.id);b.setDevice(a.device);b.setActivateEvent(a.activateEvent);return b};var b=function(){this._logger=Logger.getLogger("x.hub.taskman.rehau.AlarmTask.AlarmKey");this._alarmTask=this._deactivateEvent=this._activateEvent=this._device=this._id=null};b.prototype.init=function(){if(this._device){var a=require("x.hub.moduleman.js").modulemanager.getModule("aio");
  a&&a.addStateDevice&&(this._activateEvent&&this._activateEvent.status&&a.addStateDevice(this._device,null,{alarmTaskID:this._alarmTask.getID(),statusKey:this._activateEvent.status,src:"rehau:alarmTask"}),this._deactivateEvent&&this._deactivateEvent.status&&a.addStateDevice(this._device,null,{alarmTaskID:this._alarmTask.getID(),statusKey:this._deactivateEvent.status,src:"rehau:alarmTask"}))}};b.prototype.finalize=function(){if(this._device){var a=require("x.hub.moduleman.js").modulemanager.getModule("aio");
  a&&a.removeStateDevice&&(this._activateEvent&&this._activateEvent.status&&a.removeStateDevice(this._device,null,{alarmTaskID:this._alarmTask.getID(),statusKey:this._activateEvent.status,src:"rehau:alarmTask"}),this._deactivateEvent&&this._deactivateEvent.status&&a.removeStateDevice(this._device,null,{alarmTaskID:this._alarmTask.getID(),statusKey:this._deactivateEvent.status,src:"rehau:alarmTask"}))}};b.prototype.setAlarmTask=function(a){this._alarmTask=a};b.prototype.getID=function(){return this._id};
  b.prototype.setID=function(a){this._id=a};b.prototype.setDevice=function(a){this._device=a};b.prototype.setActivateEvent=function(a){this._activateEvent=a};b.prototype.setDeactivateEvent=function(a){this._deactivateEvent=a};b.prototype.toJSON=function(){return{id:this._id,device:this._device,activateEvent:this._activateEvent,deactivateEvent:this._deactivateEvent}};b.prototype.matchDevice=function(a){return this._device&&a?this._device.type==a.type&&this._device.address==a.address:!1};b.prototype.onStatusEvt=
  function(a){if(a&&a.data)if(this._activateEvent&&this._activateEvent.status==a.data.key&&this._activateEvent.value==a.data.value){if(this._logger.log("trace","alarm key:"+this._device.address+" receive event:"+a.data.key+" and activate alarm task"),this._alarmTask){a=this._alarmTask.getManager();var b=this._alarmTask.getID();a._setAlarmActive(b,!0,function(a){})}}else this._deactivateEvent&&this._deactivateEvent.status==a.data.key&&this._deactivateEvent.value==a.data.value&&(this._logger.log("trace",
  "alarm key:"+this._device.address+" receive event:"+a.data.key+" and deactivate alarm task"),this._alarmTask&&this._alarmTask.deactivate())};b.buildKeyfromJSON=function(a){if(!a||!a.device)return null;var f=new b;f.setID(a.id);f.setDevice(a.device);f.setActivateEvent(a.activateEvent);f.setDeactivateEvent(a.deactivateEvent);return f};var c=function(){this._logger=Logger.getLogger("x.hub.taskman.rehau.AlarmTask.AlarmConfirmation");this._alarmTask=this._preAlarmNotificationInterval=this._deactivateAction=
  this._activateAction=this._device=this._id=null};c.prototype.setAlarmTask=function(a){this._alarmTask=a};c.prototype.getID=function(){return this._id};c.prototype.setID=function(a){this._id=a};c.prototype.setDevice=function(a){this._device=a};c.prototype.setActivateAction=function(a){this._activateAction=a};c.prototype.setDeactivateAction=function(a){this._deactivateAction=a};c.prototype.toJSON=function(){return{id:this._id,device:this._device,activateAction:this._activateAction,deactivateAction:this._deactivateAction}};
  c.prototype.activationBlockedForAlarmKey=function(){if(this._device&&this._activateAction&&"aio"==this._device.sys&&"HM"==this._device.type&&"ip_siren"==this._device.data){var a=require("x.hub.commandman.js").commandHandler;this._logger.log("trace","do activate confirmation:"+JSON.stringify(this.toJSON()));var b=this;a.executeCommand(this._device,null,{value:"triggerAlarm12,6,2,0",ext:[{value:"alarmAudio",ext:"FREQUENCY_FALLING"},{value:"alarmVisual",ext:"BLINKING_ALTERNATELY_REPEATING"},{value:"alarmDur",
  ext:1},{value:"alarmDurUnit",ext:"S"}]},function(a){a&&a.error&&b._logger.log("trace","do activate confirmation error:"+a.error.message)})}};c.prototype.onActivated=function(){if(this._device&&this._activateAction){var a=this._activateAction;a.ref&&(a=a.ref);if("sonos"==this._device.sys&&(a=this._buildSonosCommand(this._activateAction.ext),!a))return;var b=require("x.hub.commandman.js").commandHandler;this._logger.log("trace","do activate confirmation:"+JSON.stringify(this.toJSON()));var c=this;b.executeCommand(this._device,
  null,a,function(a){a&&a.error&&c._logger.log("trace","do activate confirmation error:"+a.error.message)})}};c.prototype.onDeactivated=function(){this._preAlarmNotificationInterval&&(clearInterval(this._preAlarmNotificationInterval),this._preAlarmNotificationInterval=null);if(this._device&&this._deactivateAction){var a=this._deactivateAction;a.ref&&(a=a.ref);if("sonos"==this._device.sys&&(a=this._buildSonosCommand(this._deactivateAction.ext),!a))return;var b=require("x.hub.commandman.js").commandHandler;
  this._logger.log("trace","do deactivate confirmation:"+JSON.stringify(this.toJSON()));var c=this;b.executeCommand(this._device,null,a,function(a){a&&c._logger.log("trace","do deactivate confirmation error:"+a.message)})}};c.prototype.startPreAlarmNotification=function(){if(!this._preAlarmNotificationInterval){var a=this;this._doPreAlarmNotification();this._preAlarmNotificationInterval=setInterval(function(){a._doPreAlarmNotification()},7E3)}};c.prototype.stopPreAlarmNotification=function(){this._preAlarmNotificationInterval&&
  (clearInterval(this._preAlarmNotificationInterval),this._preAlarmNotificationInterval=null)};c.prototype._doPreAlarmNotification=function(){if(this._device&&this._activateAction){var a=this._activateAction;a.ref&&(a=a.ref);if("sonos"==this._device.sys&&(a=this._buildSonosCommand("pre_alarm"),!a))return;var b=require("x.hub.commandman.js").commandHandler;this._logger.log("trace","do pre alarm notification:"+JSON.stringify(this.toJSON()));var c=this;b.executeCommand(this._device,null,a,function(a){a&&
  a.error&&c._logger.log("trace","do pre alarm notification error:"+a.error.message)})}};c.prototype._getLocalIP=function(){var a=require("os").networkInterfaces(),b;for(b in a)for(var c=a[b],e=0;e<c.length;e++){var d=c[e];if(d&&"IPv4"==d.family&&0==d.internal)return d.address}return null};c.prototype._getLocalPort=function(){var a=require("x.hub.js");return a.server?a.server._port:null};c.prototype._buildSonosCommand=function(a){var b=this._getLocalIP(),c=this._getLocalPort();if(!b||!c)return null;
  var e=null;switch(a){case "alarm_on":e="alarm_on.mp3";break;case "alarm_off":e="alarm_off.mp3";break;case "pre_alarm":e="pre_alarm.mp3";break;case "alarm":e="alarm.mp3";break;default:return null}return{value:"playUrl",ext:"http://"+b+":"+c+"/resources/rehau_alarm/"+e,timeout:15}};c.buildConfirmationfromJSON=function(a){if(!a||!a.device)return null;var b=new c;b.setID(a.id);b.setDevice(a.device);b.setActivateAction(a.activateAction);b.setDeactivateAction(a.deactivateAction);return b};var e=function(a){this._logger=
  Logger.getLogger("x.hub.taskman.rehau.AlarmTask");this._id=a;this._pin=null;this._active=!1;this._delay=0;this._doorAlarmDelay=5;this._alarmKeys=[];this._alarmDoors=[];this._manager=this._doorAlarmDelayTimer=this._activateDelayTimer=this._associateTaskId_prealarm=this._associateTaskId_alarm=this._alarmConfirmation=null};e.DEFAULT_PIN="0000";e.prototype.init=function(a){this._logger.log("trace","init rehau alarm task");this._initAllAlarmKeys();this._initAllAlarmDoors();this._initAllAlarmWindowsSensors();
  a&&a()};e.prototype._initAllAlarmKeys=function(){for(var a=0;a<this._alarmKeys.length;a++){var b=this._alarmKeys[a];b&&b.init()}};e.prototype._initAllAlarmDoors=function(){for(var a=0;a<this._alarmDoors.length;a++){var b=this._alarmDoors[a];b&&b.init()}};e.prototype._initAllAlarmWindowsSensors=function(){this._active&&require("x.hub.m.enocean.js").setRehauAlarm(this._active)};e.prototype.setManager=function(a){this._manager=a};e.prototype.getManager=function(){return this._manager};e.prototype.getID=
  function(){return this._id};e.prototype.getDelay=function(){return this._delay};e.prototype.setDelay=function(a){this._delay=a};e.prototype.getAssociateTaskIdAlarm=function(){return this._associateTaskId_alarm};e.prototype.setAssociateTaskIdAlarm=function(a){this._associateTaskId_alarm=a};e.prototype.getAssociateTaskIdPreAlarm=function(){return this._associateTaskId_prealarm};e.prototype.setAssociateTaskIdPreAlarm=function(a){this._associateTaskId_prealarm=a};e.prototype.getPin=function(){return this._pin?
  this._pin:e.DEFAULT_PIN};e.prototype.setPin=function(a){this._pin=a};e.prototype.getDoorAlarmDelay=function(){return this._doorAlarmDelay};e.prototype.setDoorAlarmDelay=function(a){this._doorAlarmDelay=a};e.prototype.isActive=function(){return this._active};e.prototype.isWaitForActive=function(){return this._activateDelayTimer&&!this._active?!0:!1};e.prototype.cancelDelayActive=function(){this._activateDelayTimer&&clearTimeout(this._activateDelayTimer);this._activateDelayTimer=null;this._doorAlarmDelayTimer&&
  clearTimeout(this._doorAlarmDelayTimer);this._doorAlarmDelayTimer=null};e.prototype.activate=function(){var a=require("x.hub.m.enocean.js");if(a.isRehauWindowOpen()||require("x.hub.m.hm.js").isWindowOpen())return!0;var b=this;if(this._delay)this._logger.log("trace","activate alarm task:"+this._id+" after "+this._delay+" seconds"),this._activateDelayTimer=setTimeout(function(){b._logger.log("trace","activate alarm task:"+this._id);b._active=!0;b._setAssociateTaskActive(!0);b._manager&&b._manager.save();
  a.setRehauAlarm(!0);b._activateDelayTimer=null;if(b._alarmConfirmation)b._alarmConfirmation.onActivated()},1E3*this._delay);else if(this._logger.log("trace","activate alarm task:"+this._id),this._active=!0,this._setAssociateTaskActive(!0),this._manager&&this._manager.save(),a.setRehauAlarm(!0),this._alarmConfirmation)this._alarmConfirmation.onActivated();return!1};e.prototype.deactivate=function(){this._active=!1;this._activateDelayTimer&&clearTimeout(this._activateDelayTimer);this._activateDelayTimer=
  null;this._doorAlarmDelayTimer&&clearTimeout(this._doorAlarmDelayTimer);this._doorAlarmDelayTimer=null;this._logger.log("trace","deactivate alarm task:"+this._id);this._setAssociateTaskActive(!1);this._manager&&this._manager.save();require("x.hub.m.enocean.js").setRehauAlarm(!1);if(this._alarmConfirmation)this._alarmConfirmation.onDeactivated()};e.prototype._setAssociateTaskActive=function(a,b){if(this._manager){var c=0;this._associateTaskId_alarm&&(c+=1);this._associateTaskId_prealarm&&(c+=1);var e=
  function(){c--;0==c&&b&&b()};this._associateTaskId_alarm&&this._manager.setAssociateTaskActive(this._associateTaskId_alarm,a,e);this._associateTaskId_prealarm&&this._manager.setAssociateTaskActive(this._associateTaskId_prealarm,a,e)}else b&&b(Error("manager is null"))};e.prototype.activationBlockedForAlarmKey=function(){this._alarmConfirmation&&this._alarmConfirmation.activationBlockedForAlarmKey()};e.prototype.addAlarmKey=function(a,f){if(a){var c=b.buildKeyfromJSON(a);if(c)if(c.getID())f&&f(Error("id for new alarm key is not null "));
  else{c.setID(this._generateAlarmKeyID());this._addAlarmKeySync(c);var e=this;this._manager.save(function(a){f&&f(a,e.toJSON())})}else f&&f(Error("alarm key json invalid"))}else f&&f(Error("alarm key json is null"))};e.prototype.updateAlarmKey=function(a,f){if(a){var c=b.buildKeyfromJSON(a);if(c){var e=c.getID();if(e){var d=this._getAlarmKeySync(e);if(d){this._deleteAlarmKeySync(d);this._addAlarmKeySync(c);var h=this;this._manager.save(function(a){f&&f(a,h.toJSON())})}else f&&f(Error("no such alarm key with id:"+
  e))}else f&&f(Error("id for alarm key is null"))}else f&&f(Error("alarm key json invalid"))}else f&&f(Error("alarm key json is null"))};e.prototype.deleteAlarmKey=function(a,b){if(a){var c=this._getAlarmKeySync(a.id);if(c){this._deleteAlarmKeySync(c);var e=this;this._manager.save(function(a){b&&b(a,e.toJSON())})}else b&&b(Error("no such alarm key with id:"+a.id))}else b&&b(Error("alarm key is null"))};e.prototype.addAlarmDoor=function(a,b){if(a){var c=d.buildDoorfromJSON(a);if(c)if(c.getID())b&&b(Error("id for new alarm door is not null "));
  else{c.setID(this._generateAlarmDoorID());this._addAlarmDoorSync(c);var e=this;this._manager.save(function(a){b&&b(a,e.toJSON())})}else b&&b(Error("alarm door json invalid"))}else b&&b(Error("alarm door json is null"))};e.prototype.updateAlarmDoor=function(a,b){if(a){var c=d.buildDoorfromJSON(a);if(c){var e=c.getID();if(e){var h=this._getAlarmDoorSync(e);if(h){this._deleteAlarmDoorSync(h);this._addAlarmDoorSync(c);var k=this;this._manager.save(function(a){b&&b(a,k.toJSON())})}else b&&b(Error("no such alarm door with id:"+
  e))}else b&&b(Error("id for alarm door is null"))}else b&&b(Error("alarm door json invalid"))}else b&&b(Error("alarm door json is null"))};e.prototype.deleteAlarmDoor=function(a,b){if(a){var c=this._getAlarmDoorSync(a.id);if(c){this._deleteAlarmDoorSync(c);var e=this;this._manager.save(function(a){b&&b(a,e.toJSON())})}else b&&b(Error("no such alarm door with id:"+a.id))}else b&&b(Error("alarm door is null"))};e.prototype.setAlarmConfirmation=function(a,b){if(a){var e=c.buildConfirmationfromJSON(a);
  if(e){e.setAlarmTask(this);var d=this;this._alarmConfirmation=e;this._manager.save(function(a){b&&b(a,d.toJSON())})}else b&&b(Error("alarm confirmation json invalid"))}else b&&b(Error("alarm confirmation json is null"))};e.prototype.getAlarmTaskSync=function(a){return this._taskmanager.readTaskSync(a)};e.prototype.triggerDoorAlarm=function(){if(this._active)if(!this._doorAlarmDelay)this._logger.log("trace","no door alarm delay, execute associated task:"+this._associateTaskId_alarm),this._associateTaskId_alarm&&
  this._manager&&this._manager.executeAssociateTask(this._associateTaskId_alarm);else if(!this._doorAlarmDelayTimer){this._alarmConfirmation&&(this._logger.log("trace","door alarm start pre-alarm notification"),this._alarmConfirmation.startPreAlarmNotification());this._logger.log("trace","door alarm execute associated task:"+this._associateTaskId_alarm+" after "+this._doorAlarmDelay+" seconds");var a=this;this._doorAlarmDelayTimer=setTimeout(function(){a._doorAlarmDelayTimer=null;a._alarmConfirmation&&
  (a._logger.log("trace","door alarm stop pre-alarm notification"),a._alarmConfirmation.stopPreAlarmNotification());a._associateTaskId_alarm&&(a._logger.log("trace","door alarm execute associated task:"+a._associateTaskId_alarm),a._manager&&a._manager.executeAssociateTask(a._associateTaskId_alarm))},1E3*this._doorAlarmDelay)}};e.prototype.triggerWindowSensorAlarm=function(a){this._active&&(a&&this._associateTaskId_prealarm?this._manager&&this._manager.executeAssociateTask(this._associateTaskId_prealarm):
  !a&&this._associateTaskId_alarm&&this._manager&&this._manager.executeAssociateTask(this._associateTaskId_alarm))};e.prototype.onStatusEvt=function(a){if(a){for(var b=0;b<this._alarmKeys.length;b++){var c=this._alarmKeys[b];if(c&&c.matchDevice(a.device))c.onStatusEvt(a)}for(b=0;b<this._alarmDoors.length;b++)if((c=this._alarmDoors[b])&&c.matchDevice(a.device))c.onStatusEvt(a)}};e.prototype._getAlarmKeySync=function(a){if(!a)return null;var b=this._alarmKeys.length;if(!b)return null;for(;b--;){var c=
  this._alarmKeys[b];if(c&&c.getID()==a)return c}return null};e.prototype._addAlarmKeySync=function(a){a.setAlarmTask(this);this._alarmKeys.push(a);a.init()};e.prototype._deleteAlarmKeySync=function(a){a.finalize();a=this._alarmKeys.indexOf(a);-1!=a&&this._alarmKeys.splice(a,1)};e.prototype._getAlarmDoorSync=function(a){if(!a)return null;var b=this._alarmDoors.length;if(!b)return null;for(;b--;){var c=this._alarmDoors[b];if(c&&c.getID()==a)return c}return null};e.prototype._addAlarmDoorSync=function(a){a.setAlarmTask(this);
  this._alarmDoors.push(a);a.init()};e.prototype._deleteAlarmDoorSync=function(a){a.finalize();a=this._alarmDoors.indexOf(a);-1!=a&&this._alarmDoors.splice(a,1)};e.prototype._generateAlarmKeyID=function(){var a=[],b=this._alarmKeys.length;if(0==b)return 1;for(;b--;){var c=this._alarmKeys[b];c&&(a[c.getID()]=!0)}for(b=1;a[b];)b++;return b};e.prototype._generateAlarmDoorID=function(){var a=[],b=this._alarmDoors.length;if(0==b)return 1;for(;b--;){var c=this._alarmDoors[b];c&&(a[c.getID()]=!0)}for(b=1;a[b];)b++;
  return b};e.prototype._getActivationDelayTimer=function(a){return this._activateDelayTimer[a]};e.prototype._clearActivationDelayTimer=function(a){var b=this._activateDelayTimer[a];b&&clearTimeout(b);delete this._activateDelayTimer[a]};e.prototype.toJSON=function(){for(var a={id:this._id,active:this._active,delay:this._delay,doorAlarmDelay:this._doorAlarmDelay,alarmKeys:[],alarmDoors:[],alarmConfirmation:null,associateTaskId_alarm:this._associateTaskId_alarm,associateTaskId_prealarm:this._associateTaskId_prealarm},
  b=0;b<this._alarmKeys.length;b++){var c=this._alarmKeys[b];c&&(c=c.toJSON())&&a.alarmKeys.push(c)}for(b=0;b<this._alarmDoors.length;b++)(c=this._alarmDoors[b])&&(c=c.toJSON())&&a.alarmDoors.push(c);this._alarmConfirmation&&(a.alarmConfirmation=this._alarmConfirmation.toJSON());return a};e.buldTaskFromJSON=function(a){if(!a||!a.id)return null;var f=new e(a.id);f._pin=a.pin;f._active=a.active;f._delay=a.delay;f._doorAlarmDelay=a.doorAlarmDelay;f._associateTaskId_alarm=a.associateTaskId_alarm;f._associateTaskId_prealarm=
  a.associateTaskId_prealarm;if(a.alarmKeys)for(var h=0;h<a.alarmKeys.length;h++){var n=a.alarmKeys[h];n&&(n=b.buildKeyfromJSON(n))&&(n.setAlarmTask(f),f._alarmKeys.push(n))}if(a.alarmDoors)for(h=0;h<a.alarmDoors.length;h++)if(n=a.alarmDoors[h])if(n=d.buildDoorfromJSON(n))n.setAlarmTask(f),f._alarmDoors.push(n);a.alarmConfirmation&&(a=c.buildConfirmationfromJSON(a.alarmConfirmation))&&(a.setAlarmTask(f),f._alarmConfirmation=a);return f};var h=function(a){this._alarmTaskTokenPoll=[];this._manager=a};
  h.prototype.generateToken=function(a){var b=this._manager._getAlarmTask(a);if(null==b||100<this._alarmTaskTokenPoll.length)return null;for(var c=this._generateNonce();this._nonceExist(c);)c=this._generateNonce();var b=b.getPin(),b=this._hashPin(c,b),e=this,d={nonce:c,hash:b,taskID:a,timeout:null,failedCount:0};this._alarmTaskTokenPoll.push(d);d.timeout=setTimeout(function(){e._tokenExpired(d)},3E4);return c};h.prototype.authenticate=function(a,b){if(null==this._manager._getAlarmTask(a)||20>=b.length)return!1;
  for(var c=b.substr(0,20),e=b.substr(20),d=null,h=0;h<this._alarmTaskTokenPoll.length;h++){var k=this._alarmTaskTokenPoll[h];if(k&&k.nonce==c&&k.hash==e&&k.taskID==a)return this._tokenExpired(k),!0;k&&k.nonce==c&&(d=k)}d&&(d.failedCount+=1,3<=d.failedCount&&this._tokenExpired(d));return!1};h.prototype.expireAllToken=function(a){var b=[],c,e;for(c=0;c<this._alarmTaskTokenPoll.length;c++)(e=this._alarmTaskTokenPoll[c])&&e.taskID==a&&b.push(e);if(b&&0<b.length)for(c=0;c<this._alarmTaskTokenPoll.length;c++)e=
  this._alarmTaskTokenPoll[c],this._tokenExpired(e);return!1};h.prototype._tokenExpired=function(a){a.timeout&&(clearTimeout(a.timeout),a.timeout=null);a=this._alarmTaskTokenPoll.indexOf(a);-1!=a&&this._alarmTaskTokenPoll.splice(a,1)};h.prototype._nonceExist=function(a){for(var b=0;b<this._alarmTaskTokenPoll.length;b++){var c=this._alarmTaskTokenPoll[b];if(c&&c.nonce==a)return!0}return!1};h.prototype._generateNonce=function(){return require("crypto").randomBytes(10).toString("hex")};h.prototype._hashPin=
  function(a,b){var c=a.substr(5,4),e=require("crypto").createHash("sha1");e.update(c+b);return e.digest("hex")};var k=function(a){this._logger=Logger.getLogger("x.hub.taskman.rehau.AlarmTaskManager");this._taskmanager=a;this._alarmTasks=[];this._auth=new h(this)};k.FILE_NAME="alarm_rehau.json";k.prototype.init=function(a){this._logger.log("trace","init rehau alarm task manager");var b=this;this._loadSettings(function(c){c&&b._logger.log("warn","init rehau alarm task manager error:"+c.message);b._setupDefaultAlarmTask();
  b._initAllAlarmTasks();a&&a()})};k.prototype.save=function(a){this._saveSettings(a)};k.prototype.challenge=function(a,b){if(this._getAlarmTask(a)){var c=this._auth.generateToken(a);b&&b(c?null:Error("generate token failed"),{token:c})}else b&&b(Error("no such alarm task with id:"+a))};k.prototype.getAlarmInfo=function(a){var b=this._toSettingsJSON();a&&a(null,b)};k.prototype.setAlarmDelay=function(a,b,c,e){var d=this._getAlarmTask(a);d?d.isActive()?e&&e(Error("alarm task is active")):this._auth.authenticate(a,
  c)?(d.setDelay(b),this._saveSettings(function(a){e&&e(a,d.toJSON())})):(a=Error("pin error"),a.code=x.hub.taskman.ERROR_CODE.Pin_Error,e&&e(a)):e&&e(Error("no such alarm task with id:"+a))};k.prototype.selectAssociateTaskAlarm=function(a,b,c,e){var d=this._getAlarmTask(a);if(d){var h=null;if(b&&(h=this._taskmanager.readTaskSync(b),!h)){e&&e(Error("no such task with id:"+b));return}if(d.isActive())e&&e(Error("alarm task is active"));else if(this._auth.authenticate(a,c)){a=d.getAssociateTaskIdPreAlarm();
  (c=d.getAssociateTaskIdAlarm())&&c!=b&&c!=a&&(a=this._taskmanager.readTaskSync(c))&&a.setRehauAlarmTask(!1);d.setAssociateTaskIdAlarm(b);h&&(h.setRehauAlarmTask(!0),h.setActive(!1));var k=this;this._saveSettings(function(a){a?e&&e(a):k._taskmanager.save(function(a){e&&e(a,d.toJSON())})})}else b=Error("pin error"),b.code=x.hub.taskman.ERROR_CODE.Pin_Error,e&&e(b)}else e&&e(Error("no such alarm task with id:"+a))};k.prototype.selectAssociateTaskPreAlarm=function(a,b,c,e){var d=this._getAlarmTask(a);
  if(d){var h=null;if(b&&(h=this._taskmanager.readTaskSync(b),!h)){e&&e(Error("no such task with id:"+b));return}if(d.isActive())e&&e(Error("alarm task is active"));else if(this._auth.authenticate(a,c)){a=d.getAssociateTaskIdAlarm();(c=d.getAssociateTaskIdPreAlarm())&&c!=b&&c!=a&&(a=this._taskmanager.readTaskSync(c))&&a.setRehauAlarmTask(!1);d.setAssociateTaskIdPreAlarm(b);h&&(h.setRehauAlarmTask(!0),h.setActive(!1));var k=this;this._saveSettings(function(a){a?e&&e(a):k._taskmanager.save(function(a){e&&
  e(a,d.toJSON())})})}else b=Error("pin error"),b.code=x.hub.taskman.ERROR_CODE.Pin_Error,e&&e(b)}else e&&e(Error("no such alarm task with id:"+a))};k.prototype.setAlarmActive=function(a,b,c,e){b||this._auth.authenticate(a,c)?this._setAlarmActive(a,b,e):(a=Error("pin error"),a.code=x.hub.taskman.ERROR_CODE.Pin_Error,e&&e(a))};k.prototype._setAlarmActive=function(a,b,c){for(var e=null,d=0;d<this._alarmTasks.length;d++)if(this._alarmTasks[d])if(this._alarmTasks[d].getID()==a)e=this._alarmTasks[d];else{if(this._alarmTasks[d].isActive()){c&&
  c(Error("another alarm task with id:"+this._alarmTasks[d].getID()+" is active"));return}this._alarmTasks[d].isWaitForActive()&&this._alarmTasks[d].cancelDelayActive()}e?b&&e.isActive()?c&&c(null,e.toJSON()):b&&!e.isActive()?e.activate()?(a=Error("rehau window is open"),a.code="200002",c&&c(a)):c&&c(null,e.toJSON()):(e.deactivate(),c&&c(null,e.toJSON())):c&&c(Error("no such alarm task with id:"+a))};k.prototype.setNewPin=function(a,b,c,e){var d=this._getAlarmTask(a);d?d.isActive()?e&&e(Error("alarm task is active")):
  this._auth.authenticate(a,c)?d.getPin()==b?e&&e():(d.setPin(b),this._auth.expireAllToken(a),this._saveSettings(function(a){e&&e(a)})):(a=Error("pin error"),a.code=x.hub.taskman.ERROR_CODE.Pin_Error,e&&e(a)):e&&e(Error("no such alarm task with id:"+a))};k.prototype.setDoorAlarmDelay=function(a,b,c,e){var d=this._getAlarmTask(a);d?d.isActive()?e&&e(Error("alarm task is active")):this._auth.authenticate(a,c)?(d.setDoorAlarmDelay(b),this._saveSettings(function(a){e&&e(a,d.toJSON())})):(a=Error("pin error"),
  a.code=x.hub.taskman.ERROR_CODE.Pin_Error,e&&e(a)):e&&e(Error("no such alarm task with id:"+a))};k.prototype.addAlarmKey=function(a,b,c,e){var d=this._getAlarmTask(a);d?d.isActive()?e&&e(Error("alarm task is active")):this._auth.authenticate(a,c)?d.addAlarmKey(b,e):(a=Error("pin error"),a.code=x.hub.taskman.ERROR_CODE.Pin_Error,e&&e(a)):e&&e(Error("no such alarm task with id:"+a))};k.prototype.updateAlarmKey=function(a,b,c,e){var d=this._getAlarmTask(a);d?d.isActive()?e&&e(Error("alarm task is active")):
  this._auth.authenticate(a,c)?d.updateAlarmKey(b,e):(a=Error("pin error"),a.code=x.hub.taskman.ERROR_CODE.Pin_Error,e&&e(a)):e&&e(Error("no such alarm task with id:"+a))};k.prototype.deleteAlarmKey=function(a,b,c,e){var d=this._getAlarmTask(a);d?d.isActive()?e&&e(Error("alarm task is active")):this._auth.authenticate(a,c)?d.deleteAlarmKey(b,e):(a=Error("pin error"),a.code=x.hub.taskman.ERROR_CODE.Pin_Error,e&&e(a)):e&&e(Error("no such alarm task with id:"+a))};k.prototype.addAlarmDoor=function(a,b,
  c,e){var d=this._getAlarmTask(a);d?d.isActive()?e&&e(Error("alarm task is active")):this._auth.authenticate(a,c)?d.addAlarmDoor(b,e):(a=Error("pin error"),a.code=x.hub.taskman.ERROR_CODE.Pin_Error,e&&e(a)):e&&e(Error("no such alarm task with id:"+a))};k.prototype.updateAlarmDoor=function(a,b,c,e){var d=this._getAlarmTask(a);d?d.isActive()?e&&e(Error("alarm task is active")):this._auth.authenticate(a,c)?d.updateAlarmDoor(b,e):(a=Error("pin error"),a.code=x.hub.taskman.ERROR_CODE.Pin_Error,e&&e(a)):
  e&&e(Error("no such alarm task with id:"+a))};k.prototype.deleteAlarmDoor=function(a,b,c,e){var d=this._getAlarmTask(a);d?d.isActive()?e&&e(Error("alarm task is active")):this._auth.authenticate(a,c)?d.deleteAlarmDoor(b,e):(a=Error("pin error"),a.code=x.hub.taskman.ERROR_CODE.Pin_Error,e&&e(a)):e&&e(Error("no such alarm task with id:"+a))};k.prototype.setAlarmConfirmation=function(a,b,c,e){var d=this._getAlarmTask(a);d?d.isActive()?e&&e(Error("alarm task is active")):this._auth.authenticate(a,c)?
  d.setAlarmConfirmation(b,e):(a=Error("pin error"),a.code=x.hub.taskman.ERROR_CODE.Pin_Error,e&&e(a)):e&&e(Error("no such alarm task with id:"+a))};k.prototype.setAssociateTaskActive=function(a,b,c){var e=this._taskmanager.readTaskSync(a);e?(e.setActive(b),this._taskmanager.save(c)):c&&c(Error("no such task with id:"+a))};k.prototype.executeAssociateTask=function(a,b){var c=this._taskmanager.readTaskSync(a);c?c.trigger(b):b&&b(Error("no such task with id:"+a))};k.prototype.onStatusEvtForTask=function(a,
  b){this._logger.log("debug","for task:"+b+" receive status event:"+JSON.stringify(a));var c=this._getAlarmTask(b);if(c)c.onStatusEvt(a)};k.prototype.onWindowSensorAlarmTriggered=function(a){for(var b=0;b<this._alarmTasks.length;b++){var c=this._alarmTasks[b];c&&c.isActive()&&c.triggerWindowSensorAlarm(a)}};k.prototype._getAlarmTask=function(a){for(var b=0;b<this._alarmTasks.length;b++){var c=this._alarmTasks[b];if(c&&c.getID()==a)return c}return null};k.prototype._isAlarmTaskActive=function(a){};
  k.prototype._setupDefaultAlarmTask=function(){var a=null;0==this._alarmTasks.length&&(a=new e(1),a.setManager(this),this._alarmTasks.push(a));1==this._alarmTasks.length&&(a=this._alarmTasks[0],a=1==a.getID()?2:1,a=new e(a),a.setManager(this),this._alarmTasks.push(a))};k.prototype._initAllAlarmTasks=function(){for(var a=0;a<this._alarmTasks.length;a++){var b=this._alarmTasks[a];b&&b.init()}};k.prototype._loadSettings=function(a){var b=this,c=this._getFile();fs_extra.ensureFile(c,function(e){e?a&&a(e):
  b._loadFile(c,function(c,e){c?a&&a(c):(b._fromSettingsJSON(e),a&&a())})})};k.prototype._saveSettings=function(a){var b=this._getFile(),c=this._toSettingsJSON();this._saveFile(b,c,function(b){a&&a(b)})};k.prototype._fromSettingsJSON=function(a){if(a&&Array.isArray(a))for(var b=0;b<a.length;b++){var c=e.buldTaskFromJSON(a[b]);c&&(c.setManager(this),this._alarmTasks.push(c))}};k.prototype._toSettingsJSON=function(){for(var a=[],b=0;b<this._alarmTasks.length;b++){var c=this._alarmTasks[b];c&&a.push(c.toJSON())}return a};
  k.prototype._loadFile=function(a,b){fs.readFile(a,"utf8",function(a,c){if(a)b&&b(a);else if(c)try{var e=JSON.parse(c);b&&b(null,e)}catch(d){b&&b(d)}else b&&b(null,null)})};k.prototype._saveFile=function(a,b,c){fs.writeFile(a,JSON.stringify(b,null,2),function(a){c&&c(a)})};k.prototype._getFile=function(){var a=fileman.fileManager.getUserRootDataPath();return path.resolve(a,k.FILE_NAME)};return k}();
  x.hub.taskman.TaskManager=function(){var d=function(){this._logger=require("x.logger.js").getLogger("x.hub.taskman.TaskManager");this.version=d.TMP_VERSION;this._tasks=[];this._alarmTask=new x.hub.taskman.AlarmTask;this._mode=31;this._lock=!1};d.TMP_VERSION="1.0.0";d.NS_VERSION="2.3.2";d.FILE_NAME="tm.json";d.prototype.init=function(b){this._alarmTask.init();this._load(b)};d.prototype.clear=function(){for(var b=0;b<this._tasks.length;b++)try{this._tasks[b].finalize()}catch(c){}x.hub.taskman._TimerManager.clear();
  x.hub.taskman._AstroManager.clear();x.hub.taskman._PeriodicTimerManager.clear();this._tasks=[]};d.prototype.save=function(b){this._writeData(b)};d.prototype.reload=function(b){this.clear();this._load(b)};d.prototype._load=function(b){var c=this,e=require("fs-extra"),d=this._getFile();e.ensureFile(d,function(e){e?b&&b(e):c._loadData(function(a,e){a?b&&b(a):(c._tasks=e,c._sort(),e.forEach(function(a){a.init()}),b&&b())})})};d.prototype.lock=function(){this._lock=!0};d.prototype.unlock=function(){this._lock=
  !1};d.prototype.createTask=function(b,c){if(b){for(var e=1,d=-1,k=0;k<this._tasks.length;k++)if(this._tasks[k].id>e){b.id=e;d=k;break}else e++;-1==d&&(b.id=e,d=this._tasks.length);this._tasks.splice(d,0,b);b.init();this._writeData(c)}else c&&c(Error("task is null"))};d.prototype.readTask=function(b,c){if(b){for(var e=null,d=0;d<this._tasks.length;d++){var k=this._tasks[d];if(k.id==b){e=k;break}}e?c&&c(null,e):c&&c(Error("no such task with id:"+b))}else c&&c(Error("task id is null"))};d.prototype.readAllTasks=
  function(b){b&&b(null,this._tasks)};d.prototype.updateTask=function(b,c,e){for(var d=null,k=-1,a=0;a<this._tasks.length;a++){var f=this._tasks[a];if(f.id==b.id){d=f;k=a;break}}if(d){if(d.isAlarmTask){if(this._alarmTask._active){e&&e(Error("alarm task active"));return}a=this._alarmTask._getAlarmPin();if(!c||c!=a){b=Error("pin error");b.code=x.hub.taskman.ERROR_CODE.Pin_Error;e&&e(b);return}}d.isRehauAlarmTask()&&d.isActive()?e&&e(Error("rehau alarm task active")):(d.finalize(),this._tasks.splice(k,
  1,b),b.init(),this._writeData(e))}else e&&e(Error("no such task with id:"+b.id))};d.prototype.deleteTask=function(b,c,e){if(b){for(var d=-1,k=null,a=0;a<this._tasks.length;a++){var f=this._tasks[a];if(f.id==b){d=a;k=f;break}}if(k.isAlarmTask){if(this._alarmTask._active){e&&e(Error("alarm task active"));return}b=this._alarmTask._getAlarmPin();if(!c||c!=b){c=Error("pin error");c.code=x.hub.taskman.ERROR_CODE.Pin_Error;e&&e(c);return}}k.isRehauAlarmTask()&&k.isActive()?e&&e(Error("rehau alarm task active")):
  (k.finalize(),-1!=d&&this._tasks.splice(d,1),this._writeData(e))}else e&&e(Error("task id is null"))};d.prototype.setTaskActive=function(b,c,e,d){if(b){for(var k=null,a=0;a<this._tasks.length;a++){var f=this._tasks[a];if(f.id==b){k=f;break}}if(k){if(k.isAlarmTask){if(this._alarmTask._active){d&&d(Error("alarm task active"));return}b=this._alarmTask._getAlarmPin();if(!e||e!=b){c=Error("pin error");c.code=x.hub.taskman.ERROR_CODE.Pin_Error;d&&d(c);return}}k.isRehauAlarmTask()?d&&d(Error("do not allow to set active state for rehau alarm task")):
  (k.setActive(c),this._writeData(d))}else d&&d(Error("no such task:"+b))}else d&&d(Error("task id is null"))};d.prototype.doTask=function(b,c,e){if(b){for(var d=null,k=0;k<this._tasks.length;k++){var a=this._tasks[k];if(a.id==b){d=a;break}}if(d.isAlarmTask){if(this._alarmTask._active){e&&e(Error("alarm task active"));return}b=this._alarmTask._getAlarmPin();if(!c||c!=b){c=Error("pin error");c.code=x.hub.taskman.ERROR_CODE.Pin_Error;e&&e(c);return}}d.trigger(e)}else e&&e(Error("task id is null"))};d.prototype.cancelTask=
  function(b,c,e){if(b){for(var d=null,k=0;k<this._tasks.length;k++){var a=this._tasks[k];if(a.id==b){d=a;break}}if(d){if(d.isAlarmTask){if(this._alarmTask._active){e&&e(Error("alarm task active"));return}b=this._alarmTask._getAlarmPin();if(!c||c!=b){c=Error("pin error");c.code=x.hub.taskman.ERROR_CODE.Pin_Error;e&&e(c);return}}d.cancel(e)}else e&&e(Error("no such task"))}else e&&e(Error("task id is null"))};d.prototype.toggleTaskActive=function(b,c,e){if(b){for(var d=null,k=0;k<this._tasks.length;k++){var a=
  this._tasks[k];if(a.id==b){d=a;break}}if(d){if(d.isAlarmTask&&(b=this._alarmTask._getAlarmPin(),!c||c!=b)){c=Error("pin error");c.code=x.hub.taskman.ERROR_CODE.Pin_Error;e&&e(c);return}d.toggleActive();this._writeData(e)}else e&&e(Error("no such task:"+b))}else e&&e(Error("task id is null"))};d.prototype.isTaskRunning=function(b,c){if(b){for(var e=null,d=0;d<this._tasks.length;d++){var k=this._tasks[d];if(k.id==b){e=k;break}}e?c&&c(null,e.isRunning()):c&&c(Error("no such task"))}else c&&c(Error("task id is null"))};
  d.prototype.getCloudDeviceTriggerGateway=function(b){for(var c=null,e=0;e<this._tasks.length;e++){var d=this._tasks[e];if(d&&(c=d.getCloudDeviceTriggerGateway()))break}b&&b(null,c)};d.prototype.readTaskSync=function(b){if(!b)return null;for(var c=null,e=0;e<this._tasks.length;e++){var d=this._tasks[e];if(d.id==b){c=d;break}}return c};d.prototype.startTaskTrace=function(b,c,e){this.readTask(b,function(b,d){b?e&&e(b):d.startTaskTrace(c,function(a){e&&e(a)})})};d.prototype.stopTaskTrace=function(b,c,
  e){this.readTask(b,function(b,d){b?e&&e(b):d.stopTaskTrace(c,function(a){e&&e(a)})})};d.prototype.setAlarmActive=function(b,c,e){this._alarmTask.setAlarmActive(b,c,this,e)};d.prototype.setAlarmDelay=function(b,c,e){this._alarmTask.setAlarmDelay(b,c,e)};d.prototype.getAlarmInfo=function(b){this._alarmTask.getAlarmInfo(b)};d.prototype.selectAlarmTask=function(b,c,e,d){var k=this;this._alarmTask.selectAlarmTask(b,c,e,this._tasks,function(a){a?d&&d(a):k._writeData(d)})};d.prototype._getAlarmPin=function(){return this._alarmTask._getAlarmPin()};
  d.prototype.setAlarmPin=function(b,c,e){this._alarmTask.setAlarmPin(b,c,e)};d.prototype.onStatusEvt=function(b){if(this._lock)this._logger.log("debug","task manager locked");else{this._logger.log("debug","receive status event:"+JSON.stringify(b));for(var c=0;c<this._tasks.length&&!(2<=c&&0!=this._mode%31);c++)this._tasks[c].onStatusEvt(b)}};d.prototype.onStatusEvtForTask=function(b,c){if(this._lock)this._logger.log("debug","task manager locked");else{this._logger.log("debug","for task:"+c+" receive status event:"+
  JSON.stringify(b));for(var e=0;e<this._tasks.length&&!(2<=e&&0!=this._mode%31);e++){var d=this._tasks[e];if(d.id==c)d.onStatusEvtForTask(b)}}};d.prototype.onIREvt=function(b){if(this._lock)this._logger.log("debug","task manager locked");else{this._logger.log("info","receive ir event:"+JSON.stringify(b));for(var c=0;c<this._tasks.length&&!(2<=c&&0!=this._mode%31);c++)this._tasks[c].onIREvt(b)}};d.prototype.onLocationChange=function(b){this._lock?this._logger.log("debug","task manager locked"):(x.hub.taskman._TimerManager.onLocationChange(b),
  x.hub.taskman._AstroManager.onLocationChange(b),x.hub.taskman._PeriodicTimerManager.onLocationChange(b))};d.prototype.onTimeChange=function(b){this._lock?this._logger.log("debug","task manager locked"):(x.hub.taskman._TimerManager.onTimeChange(b),x.hub.taskman._AstroManager.onTimeChange(b),x.hub.taskman._PeriodicTimerManager.onTimeChange(b))};d.prototype.onTimerTick=function(b){if(this._lock)this._logger.log("debug","task manager locked");else{this._logger.log("info","receive time tick for task:"+
  b);for(var c=0;c<this._tasks.length&&!(2<=c&&0!=this._mode%31);c++){var e=this._tasks[c];if(e.id==b)e.onTimerTick()}}};d.prototype.onHttpEvt=function(b,c){if(this._lock)this._logger.log("debug","task manager locked");else{this._logger.log("info","receive http event"+JSON.stringify(b));var e=!1,d=0,d=this._tasks.length;0!=this._mode%31&&2<d&&(d=2);for(var k=0;k<this._tasks.length&&!(2<=k&&0!=this._mode%31);k++)this._tasks[k].onHttpEvt(b,function(a,b){b&&(e=!0);d--;0==d&&c&&c(null,e)})}};d.prototype.onActivation=
  function(b){this.version=b?d.NS_VERSION:d.TMP_VERSION};d.prototype._writeData=function(b){var c=[];this._tasks.forEach(function(b){b&&c.push(b.toJSON())});var e=require("fs"),d=this._getFile();e.writeFile(d,JSON.stringify(c,null,2),function(c){b&&b(c)})};d.prototype._loadData=function(b){var c=require("fs"),e=this._getFile();c.readFile(e,"utf8",function(c,e){if(c)b&&b(c);else if(e)try{var a=JSON.parse(e),d=[];Array.isArray(a)&&a.forEach(function(a){(a=x.hub.taskman.Task.parse(a))&&d.push(a)});b&&
  b(null,d?d:[])}catch(l){b&&b(l)}else b&&b(null,[])})};d.prototype._getFile=function(){var b=require("x.hub.fileman.js").fileManager,c=require("path");require("fs");b=b.getUserRootDataPath();return c.resolve(b,d.FILE_NAME)};d.prototype._sort=function(){var b=this._tasks.length-1,c=!1;do for(var c=!1,e=0;e<b;++e)this._tasks[e].id>this._tasks[e+1].id&&(c=this._tasks[e],this._tasks[e]=this._tasks[e+1],this._tasks[e+1]=c,c=!0);while(c)};return d}();
  x.hub.taskman.Handler=function(){var d=function(){this._logger=require("x.logger.js").getLogger("x.hub.taskman.Handler");this.taskManager=new x.hub.taskman.TaskManager;this._rehauAlarmTaskManager=new x.hub.taskman.rehau.AlarmTaskManager(this.taskManager);var b=require("x.hub.eventbus.js");b.on("status",this.onStatusEvt.bind(this));b.on("irevt",this.onIREvt.bind(this));b.on("locationchange",this.onLocationChange.bind(this));b.on("timechange",this.onTimeChange.bind(this));b.on("neoserver_activation",
  this.onActivation.bind(this))};d.prototype.TaskManager=x.hub.taskman.TaskManager;d.prototype.Task=x.hub.taskman.Task;d.prototype.Cloud=x.hub.taskman.Cloud;d.prototype.init=function(b){this._logger.log("info","init task manager");if(localStorage){"true"==localStorage.getItem("x.hub.taskman.NEO_SERVER")&&(this.taskManager.version=x.hub.taskman.TaskManager.NS_VERSION);var c=localStorage.getItem("x.hub.taskman.CLOUD_SERVER");c&&(x.hub.taskman.Cloud.prototype.URL=c)}var e=this;this.taskManager.init(function(){e._rehauAlarmTaskManager.init(b)})};
  d.prototype.getRehauAlarmTaskManager=function(){return this._rehauAlarmTaskManager};d.prototype.lock=function(){this.taskManager.lock()};d.prototype.unlock=function(){this.taskManager.unlock()};d.prototype.doWebRequest=function(b,c,e){var d=function(b){if(b.error){var a=x.hub.taskman.ERROR_CODE.General_Error;b.error.code&&(a=b.error.code);e(JSON.stringify({XC_ERR:{code:a,msg:b.error.message}}))}else e(JSON.stringify({XC_SUC:"undefined"!=typeof b.data&&null!=b.data?b.data:""}))};switch(b){case "Read":b=
  c.query.id;"undefined"==typeof b?this.readAllTasks(d):this.readTask(b,d);break;case "Create":this.createTask(c.query.data,d);break;case "Update":this.updateTask(c.query.data,c.query.pin,d);break;case "Delete":this.deleteTask(c.query.id,c.query.pin,d);break;case "Do":this.doTask(c.query.id,c.query.pin,d);break;case "Cancel":this.cancelTask(c.query.id,c.query.pin,d);break;case "isRunning":this.isTaskRunning(c.query.id,d);break;case "SetTaskActive":this.setTaskActive(c.query.id,c.query.active,c.query.pin,
  d);break;case "ToggleTaskActive":this.toggleTaskActive(c.query.id,c.query.pin,d);break;case "SetAlarmActive":this.setAlarmActive(c.query.active,c.query.pin,d);break;case "SetAlarmDelay":this.setAlarmDelay(c.query.delay,c.query.pin,d);break;case "GetAlarmInfo":this.getAlarmInfo(d);break;case "SelectAlarmTask":this.selectAlarmTask(c.query.id,c.query.isAlarmTask,c.query.pin,d);break;case "SetAlarmPin":this.setAlarmPin(c.query.newPin,c.query.pin,d);break;case "GetCloudServer":d({data:x.hub.taskman.Cloud.prototype.URL});
  break;case "SetCloudServer":if(!c.query.url){d({error:Error("url invalid")});break}"http"!=c.query.url.substr(0,4)&&(c.query.url="https://"+c.query.url);localStorage.setItem("x.hub.taskman.CLOUD_SERVER",c.query.url);x.hub.taskman.Cloud.prototype.URL=c.query.url;d({data:"success"});break;case "GetCloudDeviceTriggerGateway":this.getCloudDeviceTriggerGateway(d);break;default:b&&0==b.indexOf("Rehau")&&this.doRehauWebRequest(b,c,e)}};d.prototype.doRehauWebRequest=function(b,c,e){var d=function(b){if(b.error){var a=
  x.hub.taskman.ERROR_CODE.General_Error;b.error.code&&(a=b.error.code);e(JSON.stringify({XC_ERR:{code:a,msg:b.error.message}}))}else e(JSON.stringify({XC_SUC:"undefined"!=typeof b.data&&null!=b.data?b.data:""}))};switch(b){case "RehauPinChallenge":this._rehauAlarmTaskManager.challenge(c.query.id,function(b,a){d({error:b,data:a})});break;case "RehauGetAlarmInfo":this._rehauAlarmTaskManager.getAlarmInfo(function(b,a){d({error:b,data:a})});break;case "RehauSetAlarmDelay":this._rehauAlarmTaskManager.setAlarmDelay(c.query.id,
  c.query.delay,c.query.token,function(b,a){d({error:b,data:a})});break;case "RehauSetDoorAlarmDelay":this._rehauAlarmTaskManager.setDoorAlarmDelay(c.query.id,c.query.delay,c.query.token,function(b,a){d({error:b,data:a})});break;case "RehauSetAlarmActive":this._rehauAlarmTaskManager.setAlarmActive(c.query.id,c.query.active,c.query.token,function(b,a){d({error:b,data:a})});break;case "RehauSelectAssociateTaskAlarm":this._rehauAlarmTaskManager.selectAssociateTaskAlarm(c.query.id,c.query.associateTaskId,
  c.query.token,function(b,a){d({error:b,data:a})});break;case "RehauSelectAssociateTaskPreAlarm":this._rehauAlarmTaskManager.selectAssociateTaskPreAlarm(c.query.id,c.query.associateTaskId,c.query.token,function(b,a){d({error:b,data:a})});break;case "RehauSetNewPin":this._rehauAlarmTaskManager.setNewPin(c.query.id,c.query.pin,c.query.token,function(b,a){d({error:b,data:a})});break;case "RehauAddAlarmKey":this._rehauAlarmTaskManager.addAlarmKey(c.query.id,c.query.data,c.query.token,function(b,a){d({error:b,
  data:a})});break;case "RehauUpdateAlarmKey":this._rehauAlarmTaskManager.updateAlarmKey(c.query.id,c.query.data,c.query.token,function(b,a){d({error:b,data:a})});break;case "RehauDeleteAlarmKey":this._rehauAlarmTaskManager.deleteAlarmKey(c.query.id,c.query.data,c.query.token,function(b,a){d({error:b,data:a})});break;case "RehauAddAlarmDoor":this._rehauAlarmTaskManager.addAlarmDoor(c.query.id,c.query.data,c.query.token,function(b,a){d({error:b,data:a})});break;case "RehauUpdateAlarmDoor":this._rehauAlarmTaskManager.updateAlarmDoor(c.query.id,
  c.query.data,c.query.token,function(b,a){d({error:b,data:a})});break;case "RehauDeleteAlarmDoor":this._rehauAlarmTaskManager.deleteAlarmDoor(c.query.id,c.query.data,c.query.token,function(b,a){d({error:b,data:a})});break;case "RehauSetAlarmConfirmation":this._rehauAlarmTaskManager.setAlarmConfirmation(c.query.id,c.query.data,c.query.token,function(b,a){d({error:b,data:a})})}};d.prototype.readAllTasks=function(b){this.taskManager.readAllTasks(function(c,e){if(c)b&&b({error:c});else{var d=[];e.forEach(function(b){d.push(b.toJSON())});
  b&&b({data:d})}})};d.prototype.createTask=function(b,c){if(b){b.id||(b.id=-1);var e=x.hub.taskman.Task.parse(b);e?this.taskManager.createTask(e,function(b){c&&c({error:b})}):c&&c({error:Error("task json invalid")})}else c&&c({error:Error("task json is null")})};d.prototype.readTask=function(b,c){this.taskManager.readTask(b,function(b,d){c&&c({error:b,data:d?d.toJSON():null})})};d.prototype.updateTask=function(b,c,e){b?(b=x.hub.taskman.Task.parse(b))?this.taskManager.updateTask(b,c,function(b){e&&
  e({error:b})}):e&&e({error:Error("task json invalid")}):e&&e({error:Error("task json is null")})};d.prototype.deleteTask=function(b,c,e){this.taskManager.deleteTask(b,c,function(b){e&&e({error:b})})};d.prototype.setTaskActive=function(b,c,e,d){this.taskManager.setTaskActive(b,c,e,function(b){d&&d({error:b})})};d.prototype.doTask=function(b,c,e){this.taskManager.doTask(b,c,function(b){e&&e({error:b})})};d.prototype.cancelTask=function(b,c,e){this.taskManager.cancelTask(b,c,function(b){e&&e({error:b})})};
  d.prototype.toggleTaskActive=function(b,c,e){this.taskManager.toggleTaskActive(b,c,function(b){e&&e({error:b})})};d.prototype.isTaskRunning=function(b,c){this.taskManager.isTaskRunning(b,function(b,d){c&&c({error:b,data:d})})};d.prototype.getCloudDeviceTriggerGateway=function(b){this.taskManager.getCloudDeviceTriggerGateway(function(c,e){c?b&&b({error:c}):(e||(e={}),b&&b({data:e}))})};d.prototype.startTaskTrace=function(b,c,e){this.taskManager.startTaskTrace(b,c,function(b){e&&e({error:b})})};d.prototype.stopTaskTrace=
  function(b,c,e){this.taskManager.stopTaskTrace(b,c,function(b){e&&e({error:b})})};d.prototype.setAlarmActive=function(b,c,e){this.taskManager.setAlarmActive(b,c,function(b){e&&e({error:b})})};d.prototype.setAlarmDelay=function(b,c,e){this.taskManager.setAlarmDelay(b,c,function(b){e&&e({error:b})})};d.prototype.getAlarmInfo=function(b){this.taskManager.getAlarmInfo(function(c,e){b&&b({error:c,data:e})})};d.prototype.selectAlarmTask=function(b,c,e,d){this.taskManager.selectAlarmTask(b,c,e,function(b){d&&
  d({error:b})})};d.prototype.setAlarmPin=function(b,c,d){this.taskManager.setAlarmPin(b,c,function(b){d&&d({error:b})})};d.prototype._getAlarmPin=function(){return this.taskManager._getAlarmPin()};d.prototype.onStatusEvt=function(b,c){c&&"taskman"==c.src&&c.taskID?(this._logger.log("trace","receive for task: "+c.taskID+" status event:"+JSON.stringify(b)),this.taskManager.onStatusEvtForTask(b,c.taskID)):c&&"rehau:alarmTask"==c.src&&c.alarmTaskID?(this._logger.log("trace","receive for rehau alarm task: "+
  c.alarmTaskID+" status event:"+JSON.stringify(b)),this._rehauAlarmTaskManager.onStatusEvtForTask(b,c.alarmTaskID)):(this._logger.log("trace","receive status event:"+JSON.stringify(b)),this.taskManager.onStatusEvt(b))};d.prototype.onIREvt=function(b){this._logger.log("trace","receive ir event:"+JSON.stringify(b));this.taskManager.onIREvt(b)};d.prototype.onLocationChange=function(b){this._logger.log("trace","receive location change event:"+JSON.stringify(b));this.taskManager.onLocationChange(b)};d.prototype.onTimeChange=
  function(b){this._logger.log("trace","receive time change event:"+JSON.stringify(b));this.taskManager.onTimeChange(b)};d.prototype.onActivation=function(b){this._logger.log("trace","receive activation change event:"+b);var c=!1;"true"==b&&(c=!0);this.taskManager.onActivation(c)};return d}();"undefined"!=typeof exports&&"undefined"!=typeof module&&module.exports&&(exports=module.exports=new x.hub.taskman.Handler);
  