text: var x=x||{};x.hub=x.hub||{};x.hub.v5=x.hub.v5||{};require("x.logger.js").setLevel("info","x.hub.v5.USBSerial");require("x.logger.js").setLevel("trace","x.hub.v5.CloudConnect");x.hub.v5.LocalSPIBus=function(b,a){this._device=a;this._openspi=null;this._timeout=2E3;this._callback=null};
  x.hub.v5.LocalSPIBus.prototype._transferChunked=function(b,a,c,d){var e=b;b.length>c&&(e=b.slice(0,c));var f=new Buffer(e.length),g=this;this._openspi.transfer(e,f,function(e,f){a=Buffer.concat([a,f]);b.length>c?g._transferChunked(b.slice(c),a,c,d):d(a)})};
  x.hub.v5.LocalSPIBus.prototype._openDevice=function(b){var a=require("spi"),c=this,d=this._device;null==this._openspi&&(this._openspi=new a.Spi(d,{mode:a.MODE.MODE_0,chipSelect:a.CS.low,bitOrder:a.ORDER.msb}),this._openspi.maxSpeed(1E6),this._openspi.open());this._transferChunked(new Buffer(b),new Buffer([]),63,function(a){for(var b=0;b<a.length;b++);c._callback&&c._callback({error:null,data:a})})};x.hub.v5.LocalSPIBus.prototype.send=function(b,a,c){this._callback=c;this._openDevice(b)};
  x.hub.v5.LocalSPIBus.prototype.receive=function(b,a,c){a=[];for(var d=0;d<b;d++)a.push(0);this.send(a,null,function(a){c&&c(a)})};x.hub.v5.LocalSPIBus.prototype.end=function(){};x.hub.v5.STMSPISerial=function(){this._onTimeout=this._onData=this._onError=this._timeoutTimer=this._spiPort=this._pin=this._port=null};x.hub.v5.STMSPISerial.prototype.on=function(b,a){"error"==b?this._onError=a:"data"==b?this._onData=a:"timeout"==b&&(this._onTimeout=a)};
  x.hub.v5.STMSPISerial.prototype.open=function(b,a,c,d){c||(c=1E6);this._port=b;this._pin=d;this._baudrate=c;var e;try{e=require("spi")}catch(f){}e?(this._spiPort=new e.Spi(this._port,{mode:e.MODE.MODE_0,chipSelect:e.CS.low,bitOrder:e.ORDER.msb}),this._spiPort.maxSpeed(this._baudrate),this._spiPort.open(),a&&a(),this._read()):this._onError&&this._onError()};
  x.hub.v5.STMSPISerial.prototype._writeChunked=function(b,a,c,d){var e=b;b.length>c&&(e=b.slice(0,c));new Buffer(e.length);var f=this;this._spiPort.write(e,function(e,h){b.length>c?f._writeChunked(b.slice(c),a,c,d):d()})};
  x.hub.v5.STMSPISerial.prototype.write=function(b,a){if(this._spiPort){var c=this;XC.debugf("WRITE SPI:");XC.debugf(b);c._writeChunked(new Buffer(b),new Buffer([]),63,function(b){a&&(c._timeoutTimer&&clearTimeout(c._timeoutTimer),c._timeoutTimer=setTimeout(function(){c._spiPort=null;c._onTimeout&&c._onTimeout()},a))})}};x.hub.v5.STMSPISerial.prototype.flush=function(){};
  x.hub.v5.STMSPISerial.prototype.close=function(){this._spiPort&&this._spiPort.close();this._timeoutTimer&&(clearTimeout(this._timeoutTimer),this._timeoutTimer=null);this._onTimeout=this._onData=this._onError=null};x.hub.v5.STMSPISerial.prototype.generateCommandMessage=function(b,a){var c=b;if(a){c=[31];c.push(a);for(var d=0;d<b.length;d++)if("string"==typeof b)c.push(b.charCodeAt(d));else{var e=b[d];31!=e&&4!=e&&27!=e||c.push(27);c.push(e)}c.push(0);c.push(4)}return c};
  x.hub.v5.STMSPISerial.prototype._read=function(){if(this._spiPort){var b=this,a=require("child_process").exec,a=a("cat /sys/class/gpio/"+this._pin+"/value");a.stdout.on("data",function(a){if(1==a.trim()&&b._spiPort){var d=new Buffer(63);for(a=0;63>a;a++)d[a]="0x00";var e=new Buffer(d.length);setTimeout(function(){b._spiPort.transfer(d,e,function(a,c){for(var d=!1,e=0;63>e;e++)if(4!=c[e]){d=!0;break}d&&b._timeoutTimer&&(clearTimeout(b._timeoutTimer),b._timeoutTimer=null);d&&b._onData&&b._onData(c)})},
  50)}});a.on("error",function(a){});a.on("close",function(a){b._readTimeout=setTimeout(function(){b._read()},50)})}};x.hub.v5.USBSerial=function(b,a,c){this._logger=require("x.logger.js").getLogger("x.hub.v5.USBSerial");this._port=b;this._pin=a;this._pin||(this._pin="gpio228");this._stmUSBSerial=null;this._receiveBuffer=new Buffer([]);this._onData=null;this._useAck=!0;this._reqFifo=[];this.REQ_FIFO_MAX_LEN=5;this.ACK_TO=200;this.RSP_TO=1E4;this.RSP_END_TO=2E3;this._openSTMUSB(c)};
  x.hub.v5.USBSerial.prototype.on=function(b,a){"data"==b&&(this._onData=a)};x.hub.v5.USBSerial.prototype.reset=function(b){this._logger.log("info","reset st fifo");var a=this._reqFifo;this._reqFifo=[];for(var c=0;c<a.length;c++)this._onRequestCancel(a[c]);b&&b()};
  x.hub.v5.USBSerial.prototype._getNextDataPackage=function(){for(var b=!1,a=!1,c=!1,d=!1,e=0,f=[],g=0;g<this._receiveBuffer.length;g++){d=!1;if(27==this._receiveBuffer[g]||4==this._receiveBuffer[g]||31==this._receiveBuffer[g])if(b)d=!0;else if(27==this._receiveBuffer[g])b=!0;else if(4==this._receiveBuffer[g]){var h=!1;a&&(h=!0);a=!1;c=!0;if(h){this._receiveBuffer=this._receiveBuffer.slice(g+1);break}else c=!1}else 31==this._receiveBuffer[g]&&(a=!0,e=0);else a&&(d=!0);d&&(f[e++]=this._receiveBuffer[g],
  b=!1)}b=null;c&&2<=e&&(b=new Buffer(f.slice(0,e)));return b};
  x.hub.v5.USBSerial.prototype._openSTMUSB=function(b){if(this._stmUSBSerial)b&&b(!0);else{var a=this,c=b,d=require("xnm.aio.m10T.js"),e=null,f=!1;-1!=this._port.indexOf("spi")?(f=!0,e=new x.hub.v5.STMSPISerial,d=1E6):(e=new d.STMUSBSerial,d=115200);e.on("error",function(){a._logger.log("trace","st port error");try{a._stmUSBSerial.close()}catch(b){}a._stmUSBSerial=null;c&&c(!1);c=null});e.on("timeout",function(){a._logger.log("trace","st port timeout");if(f){try{a._stmUSBSerial.close()}catch(c){}a._stmUSBSerial=
  null;setTimeout(function(){a._openSTMUSB(b)},500)}});e.on("data",function(b){a._logger.log("trace","st data:"+b.toString("hex"));a._receiveBuffer=Buffer.concat([a._receiveBuffer,b]);for(b=a._getNextDataPackage();b;){a._logger.log("trace","st package:"+b.toString("hex"));var c=b.slice(1,b.length-1);switch(b[0]){case 80:a._logger.log("info","receive st event:"+c.toString());a._sendAck();break;case 0:a._onNak();break;case 1:a._onAck();break;case 34:a._sendAck();a._onRspError(c);break;case 32:a._sendAck();
  a._onRsp(c);break;case 33:a._sendAck(),a._onRspEnd(c)}a._onData&&a._onData({type:b[0],data:c});b=a._getNextDataPackage()}});e.open(this._port,function(){a._logger.log("trace","st connected");a._stmUSBSerial=e;c&&c(!0);c=null},d,this._pin)}};
  x.hub.v5.USBSerial.prototype.sendCommand=function(b,a,c,d){this._logger.log("info","add st request:"+a);d=this._reqFifo.length;b={type:b,req:a,ackTo:null,ackToRetry:0,rspTo:null,state:0,callback:c,responseBuffer:null};this._reqFifo.length==this.REQ_FIFO_MAX_LEN&&(this._onRequestCancel(this._reqFifo[1]),this._reqFifo.splice(1,1));this._reqFifo.push(b);0==d&&this._sendNextReq()};
  x.hub.v5.USBSerial.prototype._sendNextReq=function(){var b=this._reqFifo[0];if(b){var a=this;b.state=this._useAck&&16==b.type?1:2;b.rspTo=setTimeout(function(){a._onRspTimeout()},this.RSP_TO);this._logger.log("debug","send st (0x"+b.type.toString(16)+") request:"+b.req);this._openSTMUSB(function(c){c?(c=a._stmUSBSerial.generateCommandMessage(b.req,b.type),a._stmUSBSerial.write(c,0,function(){b.ackTo=setTimeout(function(){a._onAckTimeout()},a.ACK_TO)})):(a._logger.log("debug","open st failed"),a._onRequestFinish("st not open"))})}};
  x.hub.v5.USBSerial.prototype._sendAck=function(){if(this._useAck){this._logger.log("debug","send ack to st");var b=this._stmUSBSerial.generateCommandMessage("",1);this._stmUSBSerial.write(b)}};
  x.hub.v5.USBSerial.prototype._onAckTimeout=function(){var b=this._reqFifo[0];if(b)if(b.ackToRetry+=1,3<b.ackToRetry)this._onRequestFinish("response ack timeout 3 times");else{this._logger.log("debug","st ack timeout, re-send "+b.ackToRetry+". request:"+b.req);var a=this;b.state=1;b.ackTo=setTimeout(function(){a._onAckTimeout()},this.ACK_TO*b.ackToRetry);this._logger.log("debug","re-send st (0x"+b.type.toString(16)+") request:"+b.req);b=this._stmUSBSerial.generateCommandMessage(b.req,b.type);this._stmUSBSerial.write(b)}};
  x.hub.v5.USBSerial.prototype._onNak=function(){var b=this._reqFifo[0];b&&(this._logger.log("debug","receive st nak:"+b.req),this._onRequestFinish("response nak"))};x.hub.v5.USBSerial.prototype._onAck=function(){var b=this._reqFifo[0];if(b&&1==b.state){this._logger.log("debug","receive st ack:"+b.req);var a=this;b.state=2;b.ackTo&&(clearTimeout(b.ackTo),b.ackTo=null);b.rspTo&&(clearTimeout(b.rspTo),b.rspTo=null);b.rspTo=setTimeout(function(){a._onRspTimeout()},this.RSP_TO)}};
  x.hub.v5.USBSerial.prototype._onRspTimeout=function(){var b=this._reqFifo[0];b&&(this._logger.log("debug","st response timeout:"+b.req),1==b.state?this._onRequestFinish("no ack"):2==b.state?this._onRequestFinish("response timeout"):3==b.state&&this._onRequestFinish("response end timeout"))};x.hub.v5.USBSerial.prototype._onRspError=function(b){this._logger.log("debug","receive st response_error");this._onRequestFinish("response error:"+(b?b.toString():""))};
  x.hub.v5.USBSerial.prototype._onRsp=function(b){var a=this._reqFifo[0];if(a&&0!=a.state&&1!=a.state){this._logger.log("debug","receive st response:"+a.req+" --\x3e "+b.toString());var c=this;a.state=3;a.rspTo&&clearTimeout(a.rspTo);a.rspTo=setTimeout(function(){c._onRspTimeout()},this.RSP_END_TO);a.responseBuffer=a.responseBuffer?Buffer.concat([a.responseBuffer,b]):b}};
  x.hub.v5.USBSerial.prototype._onRspEnd=function(b){var a=this._reqFifo[0];a&&0!=a.state&&1!=a.state&&(this._logger.log("debug","receive st response_end:"+a.req+" --\x3e "+b.toString()),a.state=0,a.rspTo&&(clearTimeout(a.rspTo),a.rspTo=null),a.responseBuffer=a.responseBuffer?Buffer.concat([a.responseBuffer,b]):b,this._onRequestFinish(null))};
  x.hub.v5.USBSerial.prototype._onRequestFinish=function(b){var a=this._reqFifo[0];if(a){a.ackTo&&(clearTimeout(a.ackTo),a.ackTo=null);a.rspTo&&(clearTimeout(a.rspTo),a.rspTo=null);var c="request finish:"+a.req+" --\x3e ";b?this._logger.log("warn",c+b):(c+=a.responseBuffer.toString(),this._logger.log("info",c));try{a.callback&&a.callback({error:b,data:a.responseBuffer})}catch(d){}this._reqFifo.splice(0,1);this._sendNextReq()}};
  x.hub.v5.USBSerial.prototype._onRequestCancel=function(b){b&&(b.ackTo&&(clearTimeout(b.ackTo),b.ackTo=null),b.rspTo&&(clearTimeout(b.rspTo),b.rspTo=null),this._logger.log("warn","request cancelled:"+b.req),b.callback&&b.callback({error:"request cancelled"}))};x.hub.v5.PK=null;
  x.hub.v5.getHWSerial=function(b){var a=require("child_process").exec,a=a("cat /proc/cpuinfo | grep Serial | cut -d ':' -f 2");a.stdout.on("data",function(a){b(a.trim());b=null});a.on("error",function(a){b&&b("");b=null});a.on("close",function(a){b&&b("");b=null})};
  x.hub.v5.getPrivateKey=function(b){x.hub.v5.PK?b(x.hub.v5.PK):x.hub.v5.getHWSerial(function(a){var c="";if(!localStorage.getItem("x.hub.v5.PK")){for(var d=0;64>d;d++)c+=Math.floor(15*Math.random()).toString(16);localStorage.setItem("x.hub.v5.PK",c)}c=localStorage.getItem("x.hub.v5.PK");d=require("x.crypt.js");x.hub.v5.PK=d.SHA256(c+a);b(x.hub.v5.PK)})};
  x.hub.v5.CloudConnect=function(){this._logger=require("x.logger.js").getLogger("x.hub.v5.CloudConnect");this._request=null;this._timeout=3E5;this._error_count=0};x.hub.v5.CloudConnect.prototype.CLOUD_SERVER="v5ws.mediola.com";x.hub.v5.CloudConnect.prototype.CLOUD_SERVER_PORT=443;
  x.hub.v5.CloudConnect.prototype.init=function(b){b&&(this._server=b);this._liveResponse=null;this._messages=[];this._challenge=[];this._cloudToken=[0,0,0,0,0,0,0,0];b=require("x.crypt.js");this._cloudServer=localStorage.getItem("x.hub.v5.cloudServer");this._cloudServer||(this._cloudServer=this.CLOUD_SERVER);this._cloudPort=localStorage.getItem("x.hub.v5.cloudPort");this._cloudPort||(this._cloudPort=this.CLOUD_SERVER_PORT);localStorage.getItem("x.hub.v5.SID")&&(this._SID=b.AES.h2a(localStorage.getItem("x.hub.v5.SID")));
  this._cloudKey=localStorage.getItem("x.hub.v5.cloudKey");var a=this;this._computeKeys(function(){a._request?a._disconnect(!0):a.checkConnection()})};x.hub.v5.CloudConnect.prototype.checkConnection=function(){var b=255;localStorage&&localStorage.getItem("x.hub.v5.config")&&(b=parseInt(localStorage.getItem("x.hub.v5.config"),16),0==(b&64)&&this._cloudServer&&localStorage.getItem("x.hub.v5.SID")?this._connect():this._disconnect())};
  x.hub.v5.CloudConnect.prototype.sendMessage=function(b,a){a?this._messages.push(b):this._messages.unshift(b)};x.hub.v5.CloudConnect.prototype.sendMessageActive=function(b,a){this._messages.unshift(b);this._request&&this._request.abort();a&&a()};
  x.hub.v5.CloudConnect.prototype._computeKeys=function(b){var a=this;this._iv&&this._key?b():x.hub.v5.getPrivateKey(function(c){var d=require("x.crypt.js");c=d.Curve25519.curve25519(c,a._cloudKey);for(var e="",f=0;f<c.length;f++)e+=XC.getHexVal(c[f],2);a._key=d.AES.h2a(e.substr(0,32));a._iv=d.AES.h2a(e.substr(32));b()})};
  x.hub.v5.CloudConnect.prototype._handleServerResponse=function(b){var a=[],c=null;if(4<=b.length)if(4<=b.length&&240==b[1])b.splice(0,4);else if(4<=b.length&&255==b[1])b.splice(0,4),this._request&&this._request.abort();else{var d=(b[2]<<8)+b[3];b.length>=d+4&&(c=b[1],a=b.slice(4,d+4),b.splice(0,d+4))}if(0<a.length){b=[];for(d=0;d<a.length;d++)b.push(a[d]);a=require("x.crypt.js");a.AES.setSize(128);b=a.AES.a2a(a.AES.decrypt(b,this._key,this._iv,!1));if(16<=b.length)if(b.slice(8,16).toString()==this._challenge.toString())if(this._cloudToken=
  b.slice(0,8),a=a.AES.a2s([b.slice(16)]),0!=c&&(this._liveResponse?this._liveResponse=null:0<this._messages.length&&this._messages.pop()),0==c||1==c){var e=null;localStorage&&localStorage.getItem("x.hub.Server.pwd")&&(e=localStorage.getItem("x.hub.Server.pwd"));null==e&&(e="null");a!=e?(this.sendMessage("0101"+e,!0),this._request&&this._request.abort()):0==c?this._request&&this._request.abort():0<this._messages.length&&this._request&&this._request.abort()}else{if((5==c||3==c)&&8<a.length){var f=null;
  5==c&&(f=a.substr(0,8),a=a.substr(8));c=require("url").parse(a,!0);if("/"==c.pathname||"/info"==c.pathname||"/set"==c.pathname||"/cmd"==c.pathname||"/executeCommand"==c.pathname||"/getStates"==c.pathname){if(c.query&&c.query.json)try{JSON.parse(c.query.json)}catch(g){a=a.replace(c.pathname,""),"?json="==a.substr(0,6)&&(a=a.substr(6),c.query={json:a})}this._logger.log("trace","Remote Request Query:"+JSON.stringify(c.query));var h=this;if(c.query&&c.query.json&&1==Object.keys(c.query).length)try{c.query=
  JSON.parse(c.query.json);c.path="";for(e in c.query)c.path+="&"+e+"="+c.query[e];c.path=c.pathname+"?"+c.path.substr(1)}catch(k){}this._server.doRequest(c.pathname,{query:c.query,url:c.path},function(a){f&&(h._liveResponse=f+a);h._request&&h._request.abort()})}else f&&(this._liveResponse=f+'{"XC_ERR":{"code":"000001", "msg":"invalid request"}}'),this._request&&this._request.abort()}}else return 1}return 0};
  x.hub.v5.CloudConnect.prototype._disconnect=function(b){this._request&&(this._request.abort(),b&&(this._request=null))};
  x.hub.v5.CloudConnect.prototype._connect=function(){var b=225,a="";this._liveResponse?(a=this._liveResponse,b=226):0<this._messages.length&&(a=this._messages[this._messages.length-1]);var c=require("x.crypt.js");c.AES.setSize(128);var a=c.AES.s2a(a),d=[],d=d.concat(this._cloudToken);this._challenge=[];for(var e=0;8>e;e++)this._challenge.push(Math.floor(255*Math.random()));d=d.concat(this._challenge);d=d.concat(a);a=c.AES.encrypt(d,this._key,this._iv);a=c.AES.a2a(a);c.AES.a2a(c.AES.decrypt(a,this._key,
  this._iv,!1));b=[0,b];b=b.concat(this._SID);b=b.concat(a);b=new Buffer(b);c=this._cloudPort;80==c&&(c=443);a=require("x.hub.v5.js");d="";a.server&&(d+=a.server.HWV+"/"+a.server.VERSION+"/"+a.server._vid);var c={host:this._cloudServer,port:c,path:"/msmt",method:"POST",headers:{"Content-Type":"application/octet-stream","Content-Length":b.length,Connection:"keep-alive","X-MG-Info":d}},a=require("https"),f=this;f._logger.log("trace","Remote Access Start: "+JSON.stringify(c));this._request=a.request(c,
  function(a){f._logger.log("trace","Remote Access Response:"+a.statusCode);if(200==a.statusCode){a.setEncoding("binary");var b=[],c=0;a.on("data",function(a){a=new Buffer(a,"binary");for(var d=0;d<a.length;d++)b.push(a[d]);c=f._handleServerResponse(b)});a.on("end",function(){f._logger.log("trace","Remote Access End");f._error_count=0;f._disconnect();1==c?setTimeout(function(){f._iv=null;f._key=null;f._request=null;f.init()},1E3):f.checkConnection()})}else XC.debugf("Failed to post request to "+f.ip)});
  this._request.setTimeout(this._timeout,function(){f._logger.log("warn","Remote Access Timeout");f._request.abort()});this._request.on("close",function(a){XC.debugf("close")});this._request.on("error",function(a){f._logger.log("warn","Remote Access ERROR: "+a);f._error_count++;f._disconnect();a=f._error_count*f._error_count*100;2E3<a&&(a=2E3);setTimeout(function(){f.checkConnection()},a)});b&&this._request.write(b);this._request.end()};
  x.hub.v5.DownloadFile=function(b,a,c){var d=require("http"),e=require("fs");e.existsSync(b)&&e.unlinkSync(b);var f=e.createWriteStream(b);d.get(a,function(a){a&&200==a.statusCode?(a.pipe(f),f.on("finish",function(){f.close(function(){c&&c(!0)})}),f.on("error",function(a){e.unlink(b);c&&c(!1)})):c&&c(!1)}).on("error",function(a){e.unlink(b);c&&c(!1)})};
  x.hub.v5.BackupSTData=function(b,a,c){if(b._stmPort){var d=function(a,c,d){b.doSTMCommand(a,function(a){a&&a.XC_SUC?require("fs").writeFile(c,JSON.stringify(a.XC_SUC),function(a){a?d(!1):d(!0)}):d(!1)})};d("XC_FNC=GetStates&config=1",a+"/states.json",function(b){b?d("XC_FNC=GetSI",a+"/si.json",function(a){a&&c?c(!0):c&&c(!1)}):c&&c(!1)})}else c&&c(!0)};x.hub.v5.ResetSTData=function(b,a){b.doSTMRequest(53,[],function(b){a&&a()})};
  x.hub.v5.RestoreSTData=function(b,a,c){var d=require("fs-extra"),e=require("querystring"),f=function(c){var f=function(a){if(0<a.length){var d=a.pop();d.type&&d.adr?(d=e.stringify(d),b.doSTMCommand("XC_FNC=AddSensor&"+d,function(b){f(a)})):f(a)}else c(!0)};d.existsSync(a+"/states.json")?d.readFile(a+"/states.json",function(a,b){if(a)c(!1);else{var d=null;try{d=JSON.parse(b.toString())}catch(e){}d?0<d.length?f(d):c(!0):c(!1)}}):c(!0)};b._stmPort?f(function(a){a?c&&c(!0):c&&c(!1)}):c&&c(!0)};
  x.hub.v5.NativeWrapper=function(){this._mconfigPath="../../sbin/mconfig";this._stserPath="../../bin/stser";this._resetPin=236;this._hmPort="/dev/hmip-uart";this._usbMountPath="/media/usb0";this._resetPinState="1";this._getIpCbs=[]};
  x.hub.v5.NativeWrapper.prototype._execMConfig=function(b,a){var c=require("child_process").exec,c=c(this._mconfigPath+" "+b),d="";c.stdout.on("data",function(a){a=String(a).trim();a=a.replace(/[\n\r]/g,"");a=a.replace(/\\x00/g,"");d+=a});c.on("error",function(b){a&&a({XC_ERR:{code:"000001",msg:"Error when executing mconfig."}})});c.on("close",function(b){b=null;if(0<d.length)try{b=JSON.parse(d)}catch(c){b={XC_ERR:{code:"000001",msg:c.message},res:String(d)}}a&&a(b)})};
  x.hub.v5.NativeWrapper.prototype._exec=function(b,a,c){var d=require("child_process").exec;b=d(b);b.stdout.on("data",function(b){b=String(b).trim();a&&a(b)});b.on("error",function(a){c&&c(a)});b.on("close",function(a){c&&c()})};
  x.hub.v5.NativeWrapper.prototype.checkHMSerial=function(b){var a=require("child_process").exec,a=a("eq3configcmd update-coprocessor -p "+this._hmPort+" -c -v -d /srv/hm-root/opt/hm/firmware/"),c="";a.stdout.on("data",function(a){c+=a.trim().replace(/[\n\r]/g,"")});a.stderr.on("data",function(a){c+=a.trim().replace(/[\n\r]/g,"")});a.on("error",function(a){});a.on("close",function(a){-1<c.indexOf("<Info> Version:")&&(c="OK");b&&b(c)})};
  x.hub.v5.NativeWrapper.prototype.getIPData=function(b){var a=this._getIpCbs.length;b&&-1==this._getIpCbs.indexOf(b)&&this._getIpCbs.push(b);if(0==a){var c=this;this._execMConfig("config network show",function(a){var b=c._getIpCbs;c._getIpCbs=[];var f={};if(a){for(var g in a){var h=a[g];f[g]=[];for(l=0;l<h.length;l++){var k=h[l];"object"===typeof h[l]&&null!==h[l]&&(k.IPV4&&(k.IP=k.IPV4,delete k.IPV4),k.MAC&&(k.MAC=k.MAC.replace(/\:/g,"-")),k.DNS&&Array.isArray(k.DNS)&&k.DNS[0]&&(k.DNS=k.DNS[0]),k.DHCP=
  k.DHCP&&"TRUE"==k.DHCP,f[g].push(k))}}l=0}else var l=0;for(;l<b.length;l++)b[l]&&b[l](f)})}};x.hub.v5.NativeWrapper.prototype._setNTP=function(b,a){b?this._execMConfig("config network ntp server "+b,function(b){a&&a(!0)}):a&&a(!1)};
  x.hub.v5.NativeWrapper.prototype.scanWiFi=function(b){this._execMConfig("config network wlan scan",function(a){var c=null,d=[];if(Array.isArray(a))for(var e=0;e<a.length;e++)"string"===typeof a[e].ssid&&0<a[e].ssid.length&&d.push(a[e]);else"string"===typeof a?c=Error(JSON.stringify({XC_ERR:{msg:a}})):a.XC_ERR&&(c=Error(JSON.stringify(a)));b&&b(c,d)})};
  x.hub.v5.NativeWrapper.prototype.connectWiFi=function(b,a,c){b="config network wlan connect "+('"'+String(b).replace(/"/g,'\\"')+'"');b+='"'+String(a).replace(/"/g,'\\"')+'"';var d=this;this._execMConfig(b,function(a){a=a&&"done"==a.status;c&&c(a);setTimeout(function(){d.reboot()},1E3)})};x.hub.v5.NativeWrapper.prototype.resetNetwork=function(b){this._execMConfig("config network reset",function(a){var c=!1;a&&"done"==a.status&&(c=!0);b&&b(c)})};
  x.hub.v5.NativeWrapper.prototype.resetHM=function(b){this._execMConfig("system resetHM",function(a){var c=!1;a&&"done"==a.status&&(c=!0);b&&b(c)})};x.hub.v5.NativeWrapper.prototype.resetZway=function(b){this._execMConfig("system resetZWAY",function(a){var c=!1;a&&"done"==a.status&&(c=!0);b&&b(c)})};x.hub.v5.NativeWrapper.prototype.resetZigbee=function(b){this._execMConfig("system resetZigbee",function(a){var c=!1;a&&"done"==a.status&&(c=!0);b&&b(c)})};
  x.hub.v5.NativeWrapper.prototype._setIPData=function(b,a){var c=null;1==b.DHCP?c="config network lan dhcp":b.IP&&b.SN&&b.GW&&b.DNS&&(c="config network lan static "+b.IP+" "+b.SN+" "+b.GW+" "+b.DNS);var d=this;this._setNTP(b.NTP,function(){a&&a(!0);c&&d._execMConfig(c,function(a){XC.debugf("setIPData:");XC.debugf(a);setTimeout(function(){d._execMConfig("config network restart eth0",function(a){XC.debugf(a)})},1500)})})};
  x.hub.v5.NativeWrapper.prototype._setMAC=function(b,a,c){a.MAC?b.doSTMRequest(57,XC.getBytes(a.MAC,!0),function(d){d||XC.debugf("set st mac error");b.doSTMRequest(58,[],function(b){b&&XC.debugf("new mac: "+b.toString("hex"));c&&(b&&b.toString("hex")==a.MAC.toLowerCase()?c(!0):c(!1))})}):c&&c(!0)};x.hub.v5.NativeWrapper.prototype.setIPData=function(b,a,c){var d=this;this._setMAC(b,a,function(b){b?d._setIPData(a,c):c&&c(!1)})};
  x.hub.v5.NativeWrapper.prototype.setWLANData=function(b,a){var c=null;!0===b.DHCP?c="config network wlan dhcp":b.IP&&b.SN&&b.GW&&b.DNS&&(c="config network wlan static ",c+='"'+b.IP+'" "'+b.SN+'" "'+b.GW+'" "'+b.DNS+'"');var d=this;this._setNTP(b.NTP,function(){c?d._execMConfig(c,function(b){a&&a(!0);setTimeout(function(){d._execMConfig("config network restart wlan0",function(a){XC.debugf(a)})},1500)}):a&&a(!0)})};
  x.hub.v5.NativeWrapper.prototype.updateFirmware=function(b,a,c,d){var e=require("http"),f=require("fs");f.existsSync("/tmp/firmware_update.iopk")&&f.unlinkSync("/tmp/firmware_update.iopk");var g=f.createWriteStream("/tmp/firmware_update.iopk"),h=this;e.get("http://"+b+":"+a+c,function(a){a&&200==a.statusCode?(a.pipe(g),g.on("finish",function(){g.close(function(){h._execMConfig("system update",function(a){XC.debugf(a);d&&d('{"XC_SUC":{}}')})})}),g.on("error",function(a){f.unlink("/tmp/firmware_update.iopk");
  d&&d('{"XC_ERR":{"code":"000000", "msg":"internal error"}}')})):d&&d('{"XC_ERR":{"code":"000001", "msg":"invalid request"}}')}).on("error",function(a){f.unlink("/tmp/firmware_update.iopk");d&&d('{"XC_ERR":{"code":"000000", "msg":"internal error"}}')})};
  x.hub.v5.NativeWrapper.prototype.updateSTFirmware=function(b,a,c,d,e){var f=require("http"),g=require("fs");g.existsSync("/tmp/st.bin")&&g.unlinkSync("/tmp/st.bin");var h=g.createWriteStream("/tmp/st.bin");f.get("http://"+b+":"+a+c,function(a){a&&200==a.statusCode?(a.pipe(h),h.on("finish",function(){h.close(function(){var a=new (require("xnm.aio.m10T.js").STMUpdater)("/tmp/st.bin");a.hostType="A20";var b=0;a.startSPIUpdate(new x.hub.v5.LocalSPIBus("SPI","/dev/spidev0.0"),function(c){c.error?(XC.debugf("\r\nfailed to flash ST ("+
  c.error+")"),a.resetST(!1),e?e('{"XC_SUC":{}}'):d&&d.send("ERROR.")):100==c.state?(XC.debugf("\r\nflashed ST!"),a.resetST(!1),e?e('{"XC_SUC":{}}'):d&&d.end("100.")):d&&b!=c.state&&(d.write(c.state+"."),b=c.state)})})}),h.on("error",function(a){g.unlink("/tmp/st.bin");e?e('{"XC_ERR":{"code":"000000", "msg":"internal error"}}'):d&&d.send("ERROR.")})):e?e('{"XC_ERR":{"code":"000001", "msg":"invalid request"}}'):d&&d.send("ERROR.")}).on("error",function(a){g.unlink("/tmp/st.bin");e?e('{"XC_ERR":{"code":"000000", "msg":"internal error"}}'):
  d&&d.send("ERROR.")})};
  x.hub.v5.NativeWrapper.prototype.updateV5PFirmware=function(b,a,c){var d=this;this._saveFirmware(b,function(e,f){e?(a.end("ERROR.["+e.message+"]"),c&&c(e)):d._splitFirmwareV5PlusFile(f,"/tmp",b.query.filename,function(b,e,f){b?(a.end("ERROR.["+b.message+"]"),c&&c(b)):e&&f?d._updateSTFirmware(f,a,function(b){b?(a.end("ERROR.["+b.message+"]"),c&&c(b)):d._updateA20Firmware(e,function(b){b?(a.end("ERROR.["+b.message+"]"),c&&c(b)):a.end('{"XC_SUC":{}}',function(){c&&c()})})}):f?d._updateSTFirmware(f,a,
  function(b){b?(a.end("ERROR.["+b.message+"]"),c&&c(b)):a.end('{"XC_SUC":{}}',function(){c&&c()})}):e&&d._updateA20Firmware(e,function(b){if(b)a.end("ERROR.["+b.message+"]"),c&&c(b);else{var d=0;setInterval(function(){d++;100>=d?a.write(d+"."):a.end('{"XC_SUC":{}}',function(){c&&c()})},100)}})})})};
  x.hub.v5.NativeWrapper.prototype._saveFirmware=function(b,a){var c=require("fs");require("os");var d=require("path"),e=d.join("/tmp","/firmware_update.v5pfw");c.existsSync(d)&&c.unlinkSync(d);var f=c.createWriteStream(e);b.pipe(f);f.on("finish",function(){f.close(function(){a&&a(null,e)})});f.on("error",function(b){c.unlink(e);a&&a(b)})};
  x.hub.v5.NativeWrapper.prototype._splitFirmwareV5PlusFile=function(b,a,c,d){var e=require("fs"),f=require("os"),g=require("path");a=a||f.tmpdir();var h=function(a,c,d,f){a=e.createWriteStream(a);a.on("finish",function(){f&&f(null)});var g=e.createReadStream(b,{flags:"r",start:c,end:d});g.on("error",function(a){f&&f(a);f=null;g.end()});g.pipe(a)};e.readFileLine(b,1,function(f,e){if(f)"string"==typeof f&&(f=Error(f)),d&&d(f,null,null);else{var m=(new (require("xnm.aio.m10T.js").V5Updater)).parseHeader(e),
  n=!1,q=!1;if(!m&&(c&&-1!=c.indexOf(".iopk")?n=!0:c&&-1!=c.indexOf(".bin")&&(q=!0),!n&&!q)){f=Error("Could not parse header section of file.");d&&d(f,null,null);return}Date.now();var r=g.join(a,"firmware_update.iopk"),p=g.join(a,"st.bin");if(m){var t=m.offset+m.esp[3],u=t+m.esp[4];h(r,t,u,function(a){t=m.offset+m.st[3];u=t+m.st[4];var b=m.st[2].split(".");a=parseInt(b[0]);b=parseInt(b[1]);1<a||1==a&&1<=b?d&&d(null,r,null):h(p,t,u,function(a){d&&d(null,r,p)})})}else n?d&&d(null,b,null):q?d&&d(null,
  null,b):d&&d(Error("invalid firmware data"),null,null)}})};x.hub.v5.NativeWrapper.prototype._updateA20Firmware=function(b,a){console.log("update system");this._execMConfig("system update",function(b){console.log("update system finish");XC.debugf(b);a&&a()})};
  x.hub.v5.NativeWrapper.prototype._updateSTFirmware=function(b,a,c){var d=new (require("xnm.aio.m10T.js").STMUpdater)(b);d.hostType="A20";var e=0;d.startSPIUpdate(new x.hub.v5.LocalSPIBus("SPI","/dev/spidev0.0"),function(b){console.log("!!!!!!!",b?JSON.stringify(b):"null");b.error?(XC.debugf("\r\nfailed to flash ST ("+b.error+")"),d.resetST(!1),a&&a.write("ERROR.["+b.error+"]"),c&&c(Error(b.error))):100==b.state?(XC.debugf("\r\nflashed ST!"),d.resetST(!1),a&&a.write("100."),c&&c()):a&&e!=b.state&&
  (a.write(b.state+"."),e=b.state)})};
  x.hub.v5.NativeWrapper.prototype.backup=function(b,a){var c=require("fs-extra");c.existsSync("/tmp/firmware_backup.iopk")&&c.removeSync("/tmp/firmware_backup.iopk");var d=this;x.hub.v5.BackupSTData(b,"./data",function(b){b?d._execMConfig("system backup "+(Math.floor(49*Math.random())+1),function(b){b&&"done"==b.status&&c.existsSync("/tmp/firmware_backup.iopk")?(b=(new Date).toISOString().substr(0,16).replace(/T/g,"").replace(/-/g,"").replace(/:/g,""),a.setHeader("Content-disposition","attachment; filename=backup_"+
  b+".iopk"),a.sendFile("/tmp/firmware_backup.iopk",null,function(b){c.removeSync("./data/states.json");c.removeSync("./data/si.json");c.removeSync("/tmp/firmware_backup.iopk");b&&a.status(500).end()})):a.status(500).end()}):a.status(500).end()})};
  x.hub.v5.NativeWrapper.prototype.restore=function(b,a,c){var d=require("fs-extra");d.existsSync("/tmp/firmware_backup.iopk")&&d.removeSync("/tmp/firmware_backup.iopk");var e=this;x.hub.v5.DownloadFile("/tmp/firmware_backup.iopk",a,function(a){a&&d.existsSync("/tmp/firmware_backup.iopk")?e._execMConfig("system restore",function(a){a&&"done"==a.status?x.hub.v5.RestoreSTData(b,"./data",function(a){a?(d.removeSync("/tmp/firmware_backup.iopk"),c&&c('{"XC_SUC":{}}')):c&&c('{"XC_ERR":{"code":"000000", "msg":"internal error"}}')}):
  c&&c('{"XC_ERR":{"code":"000000", "msg":"internal error"}}')}):c&&c('{"XC_ERR":{"code":"000000", "msg":"internal error"}}')})};x.hub.v5.NativeWrapper.prototype.reboot=function(){this._execMConfig("system reboot",function(b){})};
  x.hub.v5.NativeWrapper.prototype._checkResetPin=function(b,a,c){0==b.readSync()&&(b=Date.now()-this._resetPinPressBegin,8E3<b?(this._resetPinPressBegin=Date.now(),this._resetMode="reboot",a&&a.doSTMCommand("XC_FNC=SendSC&type=RGB&data=0000")):6E3<b?(this._resetMode="factory",a&&a.doSTMCommand("XC_FNC=SendSC&type=RGB&data=0003")):4E3<b?(this._resetMode="passwords",a&&a.doSTMCommand("XC_FNC=SendSC&type=RGB&data=0004")):2E3<b&&(this._resetMode="network",a&&a.doSTMCommand("XC_FNC=SendSC&type=RGB&data=0001")))};
  x.hub.v5.NativeWrapper.prototype.watchResetPin=function(b,a){var c=require("onoff").Gpio,d=new c(this._resetPin,"in","both");d.unexport();var d=new c(this._resetPin,"in","both"),e=this,f=null;d.watch(function(c,h){f&&(clearInterval(f),f=null);b&&b.doSTMCommand("XC_FNC=SendSC&type=RGB&data=0000");0==h?(e._resetPinPressBegin=Date.now(),e._resetMode=null,f=setInterval(function(){e._checkResetPin(d,b,a)},200)):a&&a(e._resetMode)})};
  x.hub.v5.NativeWrapper.prototype.checkResetPin=function(){return(new (require("onoff").Gpio)(this._resetPin,"in","both")).readSync()};
  x.hub.v5.NativeWrapper.prototype.mountUSB=function(b){var a=b,c=setTimeout(function(){a&&a(Error("execute setUSBmount start timeout"));a=null},2E4),d=this;b=require("child_process").exec;b=b("../../sbin/setUSBmount start");var e="",f="";b.stdout.on("data",function(a){e+=a;XC.debugf("setUSBmount start: "+e)});b.stderr.on("data",function(a){f+=a;XC.debugf("setUSBmount start error: "+f)});b.on("error",function(b){c&&(clearTimeout(c),c=null);a&&a(Error("execute setUSBmount start error"));a=null});b.on("close",
  function(b){XC.debugf("exec close");XC.debugf("setUSBmount start: "+e);c&&(clearTimeout(c),c=null);var h;f&&(f=f.replace("/dev/sda",""),f=f.replace("on",""),f=f.replace("/media/usb0",""),h=Error(f));a&&a(h,d._usbMountPath);a=null})};
  x.hub.v5.NativeWrapper.prototype.unmountUSB=function(b){var a=b,c=setTimeout(function(){a&&a(Error("execute setUSBmount stop timeout"));a=null},2E4);b=require("child_process").exec;b=b("../../sbin/setUSBmount stop");var d="";b.stdout.on("data",function(a){});b.stderr.on("data",function(a){d+=a;XC.debugf("setUSBmount stop error: "+d)});b.on("error",function(b){c&&(clearTimeout(c),c=null);a&&a(Error("execute setUSBmount stop error"));a=null});b.on("close",function(b){var c;d&&(d=d.replace("/dev/sda",
  ""),d=d.replace("on",""),d=d.replace("/media/usb0",""),c=Error(d));a&&a(c);a=null})};x.hub.v5.NativeWrapper.prototype.setDateTime=function(b,a,c,d,e,f){a+="";2>a.length&&(a="0"+a);c+="";2>c.length&&(c="0"+c);d+="";2>d.length&&(d="0"+d);e+="";2>e.length&&(e="0"+e);b=a+c+d+e+b;console.log("set system time:"+b);this._execMConfig("system set time "+b,function(a){console.log("set system time finish",a);f&&f(!0)})};x.hub.v5.NativeWrapper.prototype.runMdev=function(b){this._exec("mdev -s",null,b)};
  x.hub.v5.Handler=function(){this._logger=require("x.logger.js").getLogger("x.hub.v5.Handler");this._usbPath=this._pk=this._serial=this.server=null};
  x.hub.v5.Handler.prototype.setRGBColor=function(b){if(this.server&&"A20"==this.server.hostType)this.server.doSTMCommand("XC_FNC=SendSC&type=RGB&data=00"+b);else{var a=parseInt(b,16);a&16711680&&(a|=1048576);a&65280&&(a|=4096);a&255&&(a|=16);try{var c=require("rpi-ws281x-native/lib/ws281x-native");c&&(c.init(1),c.render([a]),setTimeout(function(){c.render([a])},100))}catch(d){}}};
  x.hub.v5.Handler.prototype.getPublicKey=function(b){x.hub.v5.getPrivateKey(function(a){a=require("x.crypt.js").Curve25519.curve25519(a);for(var c="",d=0;d<a.length;d++)c+=XC.getHexVal(a[d],2);c=c.toLowerCase();b(c)})};
  x.hub.v5.Handler.prototype.backup=function(b,a,c){var d=require("fs"),e=require("fs-extra");d.existsSync("/tmp/backup")&&d.rmdirRecursiveSync("/tmp/backup");d.mkdirSync("/tmp/backup");this._backup(b,"/tmp/backup",c,function(b,c,d){b?a.status(500).end():(a.setHeader("Content-disposition","attachment; filename="+d),a.sendFile(c,null,function(b){e.removeSync("/tmp/backup");e.removeSync(c);b&&a.status(500).end()}))})};
  x.hub.v5.Handler.prototype.restore=function(b,a,c,d){var e=require("fs");require("fs-extra");var f=this;x.hub.v5.DownloadFile("/tmp/restore.zip",a,function(a){a?(e.existsSync("/tmp/restore/")&&e.rmdirRecursiveSync("/tmp/restore/"),f._extractBackupZip("/tmp/restore.zip","/tmp/restore/",c,function(a){a?d&&d('{"XC_ERR":{"msg":"'+a.message+'"}}'):e.existsSync("/tmp/restore/backup")?f._restore(b,"/tmp/restore/","backup",function(a){a?d&&d('{"XC_ERR":{"code":"000000", "msg":"'+a.message+'"}}'):d('{"XC_SUC":{}}')}):
  d&&d('{"XC_ERR":{"code":"000000", "msg":"internal error"}}')})):d&&d('{"XC_ERR":{"code":"000000", "msg":"internal error"}}')})};x.hub.v5.Handler.prototype.mountUSB=function(b){var a=this;this.Native.mountUSB(function(c,d){c?b&&b({error:c}):a.setBackupUsbPath(d,b)})};x.hub.v5.Handler.prototype.unmountUSB=function(b){try{require("fs-extra").remove("./backup_local")}catch(a){}this._usbPath=null;this.Native.unmountUSB(function(a){b&&b({error:a})})};
  x.hub.v5.Handler.prototype.setBackupUsbPath=function(b,a){this._usbPath=b;var c=require("fs-extra");c.existsSync("./backup_local")?c.emptyDirSync("./backup_local"):c.ensureDirSync("./backup_local");c.existsSync(b)||c.ensureDirSync(b);a&&a({})};x.hub.v5.Handler.prototype.saveDeviceXMLforBackup=function(b,a){require("fs-extra").writeFile("./backup_local/devices.xml",b,function(b){a&&a({error:b})})};
  x.hub.v5.Handler.prototype.saveMacrosXMLforBackup=function(b,a){require("fs-extra").writeFile("./backup_local/macros.xml",b,function(b){a&&a({error:b})})};x.hub.v5.Handler.prototype.saveIrcodesXMLforBackup=function(b,a){require("fs-extra").writeFile("./backup_local/ircodes.xml",b,function(b){a&&a({error:b})})};
  x.hub.v5.Handler.prototype.backupLocal=function(b,a,c){if(this._usbPath){var d=require("fs-extra"),e=this;this._backup(b,"./backup_local",a,function(a,b,h){d.emptyDir("./backup_local");a?c&&c({error:a}):d.move(b,e._usbPath+"/"+h,{overwrite:!0},function(a){c&&c({error:a,data:h})})})}else c&&c({error:Error("please choose the usb storage")})};
  x.hub.v5.Handler.prototype.listUsbBackups=function(b){this._usbPath?require("fs-extra").readdir(this._usbPath,function(a,c){if(a)b&&b({error:a});else{for(var d=[],e=0;e<c.length;e++){var f=c[e],g=f.indexOf(".xbp");if(-1!=g){var h={filename:c[e],time:null},k=f.substr(0,g);"backup_"==k.substr(0,7)&&(k=k.substr(7));var f=k.substr(0,4),g=k.substr(4,2),l=k.substr(6,2),m=k.substr(8,2),n=k.substr(10,2),k=k.substr(12,2);h.time=f+"-"+g+"-"+l+" "+m+":"+n+":"+k;d.push(h)}}b&&b({data:d})}}):b&&b({error:Error("please choose the usb storage")})};
  x.hub.v5.Handler.prototype.deleteBackup=function(b,a){this._usbPath?require("fs-extra").remove(this._usbPath+"/"+b,function(b){a&&a({error:b})}):a&&a({error:Error("please mount the usb storage")})};
  x.hub.v5.Handler.prototype.loadBackup=function(b,a,c){if(this._usbPath){var d=require("fs-extra"),e=this;d.ensureDirSync("./restore_local/");d.emptyDirSync("./restore_local/");d.copy(this._usbPath+"/"+b,"./"+b,function(d){d?c&&c({error:d}):e._extractBackupZip("./"+b,"./restore_local/",a,function(a){c&&c({error:a})})})}else c&&c({error:Error("please choose the usb storage")})};
  x.hub.v5.Handler.prototype.loadDeviceXML=function(b){require("fs-extra").readFile("./restore_local/backup_local/devices.xml",{encoding:"utf8"},function(a,c){b&&b({error:a,data:c})})};x.hub.v5.Handler.prototype.loadMacroXML=function(b){require("fs-extra").readFile("./restore_local/backup_local/macros.xml",{encoding:"utf8"},function(a,c){b&&b({error:a,data:c})})};
  x.hub.v5.Handler.prototype.loadIrcodesXML=function(b){require("fs-extra").readFile("./restore_local/backup_local/ircodes.xml",{encoding:"utf8"},function(a,c){b&&b({error:a,data:c})})};x.hub.v5.Handler.prototype.restoreLocal=function(b,a){this._restore(b,"./restore_local/","backup_local",function(b){a&&a({error:b})})};
  x.hub.v5.Handler.prototype.testReadOnly=function(b){var a=require("fs-extra"),c="./read_only_test_"+(new Date).getTime();a.ensureFile(c,function(d){d?b&&b(d):a.remove(c,function(a){b&&b(a)})})};x.hub.v5.Handler.prototype.fixReadOnly=function(b,a){b.writeHead(200,{"Content-Type":"text/plain"});this.Native._exec("/etc/init.d/S99_checkfs manual",function(a){b.write(a)},function(a){a?b.write('{"XC_ERR":{"code":"01001", "message":"'+a.message+'"}}'):b.write('{"XC_SUC":{}}');b.end()})};
  x.hub.v5.Handler.prototype._backup=function(b,a,c,d){var e=this;x.hub.v5.BackupSTData(b,a,function(b){if(b){var g=require("fs-extra");g.copySync("./data",a+"/data");g.existsSync(a+"/data/localstorage/x.hub.Server.pwd")&&g.removeSync(a+"/data/localstorage/x.hub.Server.pwd");g.existsSync("/srv/hm-root/opt/hm/etc/config")&&g.copySync("/srv/hm-root/opt/hm/etc/config",a+"/config");g.existsSync("/srv/z-way-server/config")&&g.copySync("/srv/z-way-server/config",a+"/zway/config");g.existsSync("/srv/z-way-server/automation/storage")&&
  g.copySync("/srv/z-way-server/automation/storage",a+"/zway/automation/storage");g.existsSync("/srv/Apps/zigbee/SYSTEM/data")&&g.copySync("/srv/Apps/zigbee/SYSTEM/data",a+"/zigbee/data");b=require("archiver");var h=new Date,k=h.getFullYear()+"",l=h.getMonth()+1+"";1==l.length&&(l="0"+l);var m=h.getDate()+"";1==m.length&&(m="0"+m);var n=h.getHours()+"";1==n.length&&(n="0"+n);var q=h.getMinutes()+"";1==q.length&&(q="0"+q);h=h.getSeconds()+"";1==h.length&&(h="0"+h);var r="backup_"+(k+l+m+n+q+h)+".xbp",
  p="/tmp/"+r,k=g.createWriteStream(p);b=b("zip");k.on("close",function(){if(c){var a=require("crypto").createCipher("aes-256-cbc",c),b=g.createReadStream(p),e=g.createWriteStream(p+".enc");e.on("finish",function(){g.removeSync(p);d&&d(null,p+".enc",r)});b.pipe(a).pipe(e)}else d&&d(null,p,r)});k.on("error",function(a){e._logger.log("warn","write backup zip file failed:"+a.message);d&&d(a);d=null});b.on("error",function(a){e._logger.log("warn","zip backup data failed:"+a.message);d&&d(a);d=null});b.pipe(k);
  b.directory(a+"/","backup");b.finalize()}else e._logger.log("warn","backup st data failed"),d&&d(Error("backup st data failed")),d=null})};
  x.hub.v5.Handler.prototype._extractBackupZip=function(b,a,c,d){var e=require("fs"),f=require("fs-extra"),g=require("adm-zip"),h=null;try{(new g(b)).extractAllTo(a,!0)}catch(k){h="invalid backup file/password"}if(h)if(c){c=require("crypto").createDecipher("aes-256-cbc",c);var l=e.createReadStream(b),e=e.createWriteStream(b+".dec.zip");c.on("error",function(){f.removeSync(b);f.removeSync(b+".dec.zip");d&&d(Error(h))});e.on("finish",function(){h=null;try{(new g(b+".dec.zip")).extractAllTo(a,!0)}catch(c){h=
  "invalid backup file/password"}f.removeSync(b);f.removeSync(b+".dec.zip");d&&d(h?Error(h):null)});l.pipe(c).pipe(e)}else f.removeSync(b),d&&d(Error(h)),d=null;else f.removeSync(b),d&&d(),d=null};
  x.hub.v5.Handler.prototype._restore=function(b,a,c,d){var e=require("fs"),f=require("fs-extra"),g=a+c;if(e.existsSync(g+"/zigbee/data"))try{f.ensureDirSync("/srv/Apps/zigbee/SYSTEM"),f.copySync(g+"/zigbee/data","/srv/Apps/zigbee/SYSTEM/data")}catch(h){}if(e.existsSync(g+"/zway/config")&&e.existsSync("/srv/z-way-server"))try{f.copySync(g+"/zway/config","/srv/z-way-server/config")}catch(k){}if(e.existsSync(g+"/zway/automation/storage")&&e.existsSync("/srv/z-way-server/automation"))try{f.copySync(g+
  "/zway/automation/storage","/srv/z-way-server/automation/storage")}catch(l){}this._restoreHM(g,function(){x.hub.v5.RestoreSTData(b,g,function(b){b?f.copy(g+"/data","./data",function(b){f.removeSync(a);b&&d?d(Error("internal error")):d&&d()}):d&&d(Error("internal error"))})})};
  x.hub.v5.Handler.prototype._restoreHM=function(b,a){function c(a){a=f.extname(a);return".ap"===a||".apkx"===a}var d=require("fs"),e=require("fs-extra"),f=require("path");d.existsSync(b+"/config")&&d.existsSync("/srv/hm-root/opt/hm/etc")?this.Native.resetHM(function(f){XC.debugf("reset HM:"+f);try{e.copySync(b+"/config","/srv/hm-root/opt/hm/etc/config");var h=[];d.readdirSync("/srv/hm-root/opt/hm/etc/config/crRFD/data").filter(c).forEach(function(a){h.push(a)});for(f=0;f<h.length;f++);}catch(k){console.error(k)}a&&
  a()}):a&&a()};x.hub.v5.Handler.prototype.getSerialPorts=function(b){var a=null;try{a=require("serialport")}catch(c){a=null}a?this.Native.runMdev(function(c){console.log("run mdev finish",c);c?b(JSON.stringify({XC_ERR:{code:"00000",msg:"run mdev error:"+c.message}})):a.list(function(a,c){console.log("list serial port finish",a,JSON.stringify(c));void 0==c&&(c=[]);for(var d=[],h=0;h<c.length;h++)c[h]&&d.push(c[h].comName);b('{"XC_SUC":'+JSON.stringify(d)+"}")})}):b('{"XC_ERR":{"code":"000000", "msg":"internal error"}}')};
  x.hub.v5.Handler.prototype.getLogs=function(b){var a=require("fs-extra"),c=require("archiver"),d="logs_"+(new Date).toISOString().substr(0,16).replace(/T/g,"").replace(/-/g,"").replace(/:/g,"")+".zip",e="/tmp/"+d,f=a.createWriteStream(e),c=c("zip");f.on("close",function(){b.setHeader("Content-disposition","attachment; filename="+d);b.sendFile(e,null,function(c){a.removeSync(e);c&&b.status(500).end()})});f.on("error",function(a){b.status(500).end()});c.on("error",function(a){b.status(500).end()});
  c.pipe(f);c.directory("/var/log");c.finalize()};
  x.hub.v5.Handler.prototype.getNeoServerLogs=function(b){var a=require("path"),c=require("x.hub.fileman.js").fileManager,d=c.getUserRootDataPath(),e=a.dirname(c.getLogFile()),f=c.getTmpDir(),g=require("fs-extra"),c=require("archiver"),h="logs_"+(new Date).toISOString().substr(0,16).replace(/T/g,"").replace(/-/g,"").replace(/:/g,"")+".zip",k=f+a.sep+h,a=g.createWriteStream(k),c=c("zip");a.on("close",function(){b.setHeader("Content-disposition","attachment; filename="+h);b.sendFile(k,null,function(a){g.removeSync(k);
  a&&b.status(500).end()})});a.on("error",function(a){b.status(500).end()});c.on("error",function(a){b.status(500).end()});c.pipe(a);c.directory(d);c.directory(e);c.finalize()};x.hub.v5.Handler.prototype.clearLogs=function(b){require("fs-extra").emptyDir("/var/log",function(a){b&&b()})};
  x.hub.v5.Handler.prototype.reset=function(b,a,c){var d=require("fs"),e=require("fs-extra");"passwords"==a?(d.existsSync("./data/localstorage/x.hub.Server.pwd")&&e.removeSync("./data/localstorage/x.hub.Server.pwd"),c&&c()):"factory"==a?(d.existsSync("./data")&&e.emptyDirSync("./data"),x.hub.v5.ResetSTData(b,function(){c&&c()})):c&&c()};
  x.hub.v5.Handler.prototype.resetST=function(b){this._logger.log("info","reset st");this._logger.log("trace","set st led to permant white");var a=this;this.server.doSTMCommand("XC_FNC=SendSC&type=RGB&data=0105",function(c){c&&c.XC_SUC?(a._logger.log("trace","reset st data"),x.hub.v5.ResetSTData(a.server,function(){a._logger.log("trace","reboot st");var c=new (require("xnm.aio.m10T.js").STMUpdater);c.hostType=a.server.hostType;c.resetST();a._logger.log("info","reset st finish");b&&b()})):(c=c&&c.XC_ERR?
  Error(c.XC_ERR):Error("set led white failed"),a._logger.log("trace","set led white error:"+c.message),b&&b(c))})};
  x.hub.v5.Handler.prototype.rebootST=function(b){this._logger.log("info","reboot st");this._logger.log("trace","set st led to permant white");var a=this;this.server.doSTMCommand("XC_FNC=SendSC&type=RGB&data=0105",function(c){c&&c.XC_SUC?(a._logger.log("trace","now reboot st"),c=new (require("xnm.aio.m10T.js").STMUpdater),c.hostType=a.server.hostType,c.resetST(),a._logger.log("info","reboot st finish"),b&&b()):(c=c&&c.XC_ERR?Error(c.XC_ERR):Error("set led white failed"),a._logger.log("trace","set led white error:"+
  c.message),b&&b(c))})};x.hub.v5.Handler.prototype.USBSerial=x.hub.v5.USBSerial;x.hub.v5.Handler.prototype.CloudConnect=x.hub.v5.CloudConnect;x.hub.v5.Handler.prototype.LocalSPIBus=x.hub.v5.LocalSPIBus;x.hub.v5.Handler.prototype.Native=new x.hub.v5.NativeWrapper;"undefined"!=typeof exports&&"undefined"!=typeof module&&module.exports&&(exports=module.exports=new x.hub.v5.Handler);
  