UNPKG

ck-inodrive-api

Version:

CK-InoDrive-API allows you interact with variables, files, and other data being utilized by your application as it works across the InoWorx/InoDrive landscape.

1 lines 59.8 kB
import*as e from"ws";import{createRequire as t}from"node:module";import*as r from"@msgpack/msgpack";var n={m:{},d:(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},u:e=>e+".js?v=364e98e3ec5efd162393",o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};(()=>{var e;if("string"==typeof import.meta.url&&(e=import.meta.url),!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})(),n.b=new URL("./",import.meta.url);var i={};n.d(i,{Z:()=>J,e:()=>Z});const s=(a={WebSocket:()=>e.WebSocket},c={},n.d(c,a),c),o=t(import.meta.url)("node:worker_threads");var a,c;class l{_context=null;_callbacks={};constructor(e){e=e||{},this._context=e.context?e.context:this}on=(e,t)=>{try{let r={};if("object"==typeof e)r=e;else{if("string"!=typeof e||"function"!=typeof t)return;r[e]=t}for(const[e,t]of Object.entries(r))"string"==typeof e&&"function"==typeof t&&(this._callbacks.hasOwnProperty(e)?this._callbacks[e].indexOf(t)<0&&this._callbacks[e].push(t):this._callbacks[e]=[t])}catch(e){}};remove=(e,t)=>{try{if("string"!=typeof e)return;if("function"!=typeof t)return;this._callbacks[e]&&this._callbacks[e].indexOf(t)>=0&&this._callbacks[e].splice(this._callbacks[e].indexOf(t),1),0==this._callbacks[e].length&&delete this._callbacks[e]}catch(e){}};dispatch=(e,...t)=>{try{let r=this._callbacks[e];if(r)for(let e of r)"function"==typeof e&&e.call(this._context,...t)}catch(e){}};dispatchWithContext=(e,t,...r)=>{try{let n=this._callbacks[t];if(n)for(let t of n)"function"==typeof t&&t.call(e,...r)}catch(e){}}}function u(e,t){e=d([e,"unknown"],"string"),t=d([t,{}],"object");let r=this;return r.msg_list={nan:"Value [ %{0} ] is not number",min:"Value [ %{0} ] is smaller then [ %{1} ]",max:"Value [ %{0} ] is bigger then [ %{1} ]",precision:"Value [ %{0} ] has precision bigger then [ %{1} ] digits",infinity:"Value is Infinity",float_format:'Value [ %{0} ] does not match "float" number format',float_single:"Value [ %{0} ] is not single precision float number",float_double:"Value [ %{0} ] is not double precision float number",int_format:'Value [ %{0} ] does not match "integer" number format',hex_format:'Value [ %{0} ] does not match "hexadecimal" number format',bin_format:'Value [ %{0} ] does not match "binary" number format',variable_format:"Value [ %{0} ] does not match variable name format",variable_low_dash:'Variable name [ %{0} ] should not begin with "_" character',variable_min_size:"Variable name [ %{0} ] is shorter then the minimum allowed [ %{1} ] characters",variable_max_size:"Variable name [ %{0} ] is longer then the maximum allowed [ %{1} ] characters",variable_exist:"Variable name [ %{0} ] already exist",ipv4_format:"Value [ %{0} ] does not match IP V4 address format",ipv4_string:'Value [ %{0} ] is not "string" type',ipv4_octet_count:"Value [ %{0} ] needs to have four octets",ipv4_octet_range:"Value [ %{0} ] has octet out of the range from 0 to 255"},r.set_msg_list=e=>{try{e=d([e,{}],"object");for(const[t,n]of Object.entries(e))r.msg_list[t]=n}catch(e){}},r.msg=e=>d([r.msg_list[e],""],"string"),r.variable=function(){let e=d([t.min,1],"number"),n=d([t.max,20],"number"),i=d([t.items,[]],"object");t.ignore=d([t.ignore,{}],"object");let s=d([t.ignore.low_dash,!1],"boolean"),o=d([t.ignore.min_size,!1],"boolean"),a=d([t.ignore.max_size,!1],"boolean"),c=d([t.ignore.self,!1],"boolean"),l=d([t.ignore.format,!1],"boolean");return function(t){let u=e=>{};return this&&d([this.setTooltip],"function")&&(u=this.setTooltip),!o&&t.length<e?(u(w(r.msg("variable_min_size"),[t,e])),!1):!a&&t.length>n?(u(w(r.msg("variable_max_size"),[t,n])),!1):c||-1==i.indexOf(t)?l?(u(),!0):/^[\wа-яА-Я]+$/.test(t)?s||"_"!=t[0]?(u(),!0):(u(w(r.msg("variable_low_dash"),t)),!1):(u(!l&&w(r.msg("variable_format"),t)),!1):(u(w(r.msg("variable_exist"),t)),!1)}},r.networkID=function(){let e=d([t.max,36],"number"),n=d([t.items,[]],"object"),i=d([t.includeIPv4,!0],"boolean");t.ignore=d([t.ignore,{}],"object");let s=d([t.ignore.self,!1],"boolean");return function(t){let o=e=>{};if(this&&d([this.setTooltip],"function")&&(o=this.setTooltip),t=`${t}`,i){if(t.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/))return 4!=t.split(".").length?(o(w(r.msg("ipv4_octet_count"),t)),!1):4!=t.split(".").filter((e=>parseInt(e)>=0&&parseInt(e)<=255)).length?(o(w(r.msg("ipv4_octet_range"),t)),!1):(o(),!0);if(t.split(".").length>1)return o(w(r.msg("ipv4_format"),t)),!1}else if(t.split(".").length>1)return o('Network ID cannot contain "."'),!1;return"-"==t[0]||"-"==t[t.length-1]?(o("Dash is not allowed at the beginning or end of the network ID"),!1):t.match(/[_]+/)?(o("Low dash cannot be part of the network ID"),!1):t.length>e?(o("Network ID cannot be longer then 36 characters"),!1):/^[-\w]+$/.test(t)?s||-1==n.indexOf(t)?(o(),!0):(o(w(r.msg("variable_exist"),t)),!1):(o(`${t}> does not match network ID format`),!1)}},r.date=function(){t.ignore=d([t.ignore,{}],"object");let e=d([t.ignore.format,!1],"boolean");return function(t){let n=e=>{};return this&&d([this.setTooltip],"function")&&(n=this.setTooltip),/^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{2}|\d{4})$/.test(t)?(n(),!0):(n(!e&&w(r.msg("date_format"),t)),!1)}},r.IPv4=function(){return function(e){let t=e=>{};return this&&d([this.setTooltip],"function")&&(t=this.setTooltip),"string"!=typeof e?(t(w(r.msg("ipv4_string"),e)),!1):e.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)?4!=e.split(".").length?(t(w(r.msg("ipv4_octet_count"),e)),!1):4!=e.split(".").filter((e=>parseInt(e)>=0&&parseInt(e)<=255)).length?(t(w(r.msg("ipv4_octet_range"),e)),!1):(t(),!0):(t(w(r.msg("ipv4_format"),e)),!1)}},r.int=function(){let e=d([t.min],"number"),n=d([t.max],"number");return function(t){let i=e=>{};this&&d([this.setTooltip],"function")&&(i=this.setTooltip);let s=b(t);return/^[+-]?(\d+)?$/.test(s.toUpperCase())?(t=parseInt(s),isNaN(t)?(i(w(r.msg("nan"),s)),!1):t==-1/0||t==1/0?(i(r.msg("infinity")),!1):null!=e&&t<e?(i(w(r.msg("min"),[s,e])),!1):null!=n&&t>n?(i(w(r.msg("max"),[s,n])),!1):(i(),!0)):(i(w(r.msg("int_format"),s)),!1)}},r.float=function(){let e=d([t.min],"number"),n=d([t.max],"number"),i=d([t.precision],"number"),s=d([t.double,!0],"boolean");return function(t){let o=e=>{};this&&d([this.setTooltip],"function")&&(o=this.setTooltip);let a=b(t);if(/^[+-]?\d+(\.?(\d+)?)?$/.test(a)){if(t=parseFloat(a),isNaN(t))return o(w(r.msg("nan"),a)),!1;if(t==-1/0||t==1/0)return o(r.msg("infinity")),!1;if(null!=e&&t<e)return o(w(r.msg("min"),[a,e])),!1;if(null!=n&&t>n)return o(w(r.msg("max"),[a,n])),!1;if(null!=i){let e=a.indexOf(".");if(e&&a.substring(e+1).length>i)return o(w(r.msg("precision"),[a,i])),!1}if(0!=t)if(s){if((""+t).replace(".","")!=a.replace(".",""))return o(w(r.msg("float_double"),a)),!1}else{if(Math.fround(t)==-1/0||Math.fround(t)==1/0)return o(r.msg("infinity")),!1;if("0"!=a.slice(-1)&&"."!=a.slice(-1)&&Math.fround(t)==Math.fround(parseFloat(a.slice(0,a.length-1))))return o(w(r.msg("float_single"),a)),!1}return o(),!0}return o(w(r.msg("float_format"),a)),!1}},r.hex=function(){let e=d([t.min],"number"),n=d([t.max],"number");return function(t){let i=e=>{};this&&d([this.setTooltip],"function")&&(i=this.setTooltip);let s=`${t}`.toUpperCase();if(/^(0X|16#)?([0-9ABCDEF]+)?$/.test(s.toUpperCase())){"16#"==s.slice(0,3)&&(s=s.slice(3)),"0X"==s.slice(0,2)&&(s=s.slice(2)),""==s&&(s="0");let t=parseInt(s,16);return isNaN(t)?(i(w(r.msg("nan"),s)),!1):t==-1/0||t==1/0?(i(r.msg("infinity")),!1):null!=e&&t<e?(i(w(r.msg("min"),[s,e])),!1):null!=n&&t>n?(i(w(r.msg("max"),[s,n])),!1):(i(),!0)}return i(w(r.msg("hex_format"),s)),!1}},r.number=function(){let e=d([t.double,!0],"boolean"),n=d([t.float,!1],"boolean"),i=d([t.hex,!1],"boolean"),s=d([t.bin,!1],"boolean"),o=d([t.precision],"number"),a=d([t.min],"number"),c=d([t.max],"number"),l=d([t.type,!1],"boolean");return function(t){let u=e=>{};this&&d([this.setTooltip],"function")&&(u=this.setTooltip);let h="int";i?h="hex":s?h="bin":n&&(h="float");let p=`${t}`.toUpperCase();""==p&&(p="0");let g=null;switch(h){case"int":g=/^[+-]?(\d+)?$/;break;case"float":g=/^[+-]?\d+(\.?(\d+)?)?$/;break;case"hex":g=/^(0X|16#)?([0-9ABCDEF]+)?$/;break;case"bin":g=/^(0B)?([01]+)?$/}if(g.test(p)){let t=null;switch(h){case"int":t=parseInt(p);break;case"float":p="."==p.slice(-1)?p.slice(0,p.length-1):p;do{p="0"==p.slice(-1)?p.slice(0,p.length-1):p}while(p.length&&"0"==p.slice(-1));""==p&&(p="0"),t=parseFloat(p);break;case"hex":"16#"==p.slice(0,3)&&(p=p.slice(3)),"0X"==p.slice(0,2)&&(p=p.slice(2)),""==p&&(p="0"),t=parseInt(p,16)}if(l&&(t=y(t,{type:l})),isNaN(t))return u(w(r.msg("nan"),t)),!1;if(t==-1/0||t==1/0)return u(r.msg("infinity")),!1;if(null!=a&&t<a)return u(w(r.msg("min"),[t,a])),!1;if(null!=c&&t>c)return u(w(r.msg("max"),[t,c])),!1;switch(h){case"int":case"hex":case"bin":break;case"float":if(null!=o){let e=p.indexOf(".");if(e&&p.substring(e+1).length>o)return u(w(r.msg("precision"),[t,o])),!1}if(0!=t)if(e){if((""+t).replace(".","")!=p.replace(".",""))return u(w(r.msg("float_double"),t)),!1}else{if(Math.fround(t)==-1/0||Math.fround(t)==1/0)return u(r.msg("infinity")),!1;if("0"!=p.slice(-1)&&"."!=p.slice(-1)&&Math.fround(t)==Math.fround(parseFloat(p.slice(0,p.length-1))))return u(w(r.msg("float_single"),t)),!1}}return u(),!0}switch(h){case"int":u(w(r.msg("int_format"),t));break;case"float":u(w(r.msg("float_format"),t));break;case"hex":u(w(r.msg("hex_format"),t));break;case"bin":u(w(r.msg("bin_format"),t))}return!1}},d([r[e]],"function")?r[e]():function(){A.error("Unknown validator...")}}let h=()=>{var e=(new Date).getTime(),t="xxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){var r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?r:3&r|8).toString(16)}));return String.fromCharCode(97+Math.floor(6*Math.random()))+t},d=(e,t)=>{let r,n=!1;try{"object"==typeof t&&(r=t.default,n=!!t.acceptNull,t=t.type);for(let r of e)if(void 0!==r){if(null!==r){if(t&&t.length>0){let e=[];"string"==typeof t?e=[t]:Array.isArray(t)&&(e=t);let n=!1;for(let t of e){if("obj"===t?t="object":"func"==t?t="function":"str"==t?t="string":"num"==t?t="number":"bool"==t?t="boolean":"arr"==t&&(t="array"),"array"===t&&Array.isArray(r)){n=!0;break}if(typeof r===t){n=!0;break}}if(!n)continue}return r}if(n)return r}}catch(e){logging.exception(e)}if(void 0!==r)return r},p=(e,t)=>{try{null==t&&(t=0);let r=Math.pow(10,t);return Math.round(e*r)/r}catch(e){logging.exception(e)}return NaN},g=e=>new Promise(((t,r)=>setTimeout(t,e))),_=(e,t)=>{if(null===e)return e;switch(typeof e){case"string":case"number":case"boolean":case"undefined":return e;case"function":return"__func__";case"object":{let r=null;if(Array.isArray(e)){r=[];for(let t of e){let e=typeof t;"string"===e||"number"===e||"boolean"===e||"function"===e||"undefined"===e||null===t||Array.isArray(t)||$.isPlainObject(t)?r.push(_(t)):r.push("__obj__")}}else{r={};for(let n in e){if(Array.isArray(t))for(let e of t)e!==n||(r[n]=null);let i=typeof e[n];"string"===i||"number"===i||"boolean"===i||"function"===i||"undefined"===i||null===e[n]||Array.isArray(e[n])||$.isPlainObject(e[n])?r[n]=_(e[n]):r[n]="__obj__"}}return r}}return"__unknown__"},m=e=>{var t=[],r=0;for(let i=0;i<e.length;i++){var n=e.charCodeAt(i);n<128?t[r++]=n:n<2048?(t[r++]=n>>6|192,t[r++]=63&n|128):55296==(64512&n)&&i+1<e.length&&56320==(64512&e.charCodeAt(i+1))?(n=65536+((1023&n)<<10)+(1023&e.charCodeAt(++i)),t[r++]=n>>18|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128,t[r++]=63&n|128):(t[r++]=n>>12|224,t[r++]=n>>6&63|128,t[r++]=63&n|128)}return t},f=(e,t)=>{for(var r=[],n=0,i=0;n<e.length;){var s=e[n++];if(t&&0==s)return r.join("");if(s<128)r[i++]=String.fromCharCode(s);else if(s>191&&s<224){var o=e[n++];r[i++]=String.fromCharCode((31&s)<<6|63&o)}else if(s>239&&s<365){var a=((7&s)<<18|(63&(o=e[n++]))<<12|(63&(c=e[n++]))<<6|63&e[n++])-65536;r[i++]=String.fromCharCode(55296+(a>>10)),r[i++]=String.fromCharCode(56320+(1023&a))}else{o=e[n++];var c=e[n++];r[i++]=String.fromCharCode((15&s)<<12|(63&o)<<6|63&c)}}return r.join("")},b=function(e){let t="";"-"==(e+="").charAt(0)&&(e=e.substring(1),t="-");let r=e.split(/[e]/gi);if(r.length<2)return t+e;let n=.1.toLocaleString().substr(1,1),i=r[0],s=+r[1],o=(i=i.replace(/^0+/,"")).replace(n,""),a=i.split(n)[1]?i.indexOf(n)+s:o.length+s,c=a-o.length,l=""+BigInt(o);return o=s>=0?c>=0?l+"0".repeat(c):u():a<=0?"0"+n+"0".repeat(Math.abs(a))+l:u(),c=o.split(n),(0==c[0]&&0==c[1]||0==+o&&0==+l)&&(o=0),t+o;function u(){return o.replace(new RegExp(`^(.{${a}})(.)`),`$1${n}$2`)}},y=(e,t)=>{try{t=d([t,{}],"object");let r=d([t.size,32],"number"),n=d([t.signed,!0],"boolean"),i=d([t.type,"float"],"string"),s=d([t.from,"dec"],"string"),o=d([t.to,"dec"],"string"),a=d([t.padded,!1],"boolean"),c={1:{true:e=>e?1:0,false:e=>e?1:0},8:{true:e=>new Int8Array([Math.round(e)])[0],false:e=>new Uint8Array([Math.round(e)])[0]},16:{true:e=>new Int16Array([Math.round(e)])[0],false:e=>new Uint16Array([Math.round(e)])[0]},32:{true:e=>new Int32Array([Math.round(e)])[0],false:e=>new Uint32Array([Math.round(e)])[0]},float:{true:e=>parseFloat(`${e}`),false:e=>parseFloat(`${e}`)}};if(i)switch(t.type){case"bool":r=1,n=!1;break;case"s_byte":r=8,n=!0;break;case"u_byte":r=8,n=!1;break;case"s_int":r=16,n=!0;break;case"u_int":r=16,n=!1;break;case"s_dint":r=32,n=!0;break;case"u_dint":r=32,n=!1;break;case"float":r="float",n=!1}let l=`${e}`.toUpperCase();switch(s){case"dec":break;case"hex":"16#"==l.slice(0,3)&&(l=l.slice(3)),"0X"==l.slice(0,2)&&(l=l.slice(2)),""==l&&(l=0),e=parseInt(l,16);break;case"bin":"0B"==l.slice(0,2)&&(l=l.slice(2)),""==l&&(l=0),e=parseInt(l,2)}if(isNaN(e))return null;switch(e=c[r][n](e),o){case"dec":break;case"hex":e=(e=c[r][!1](e)).toString(16).toUpperCase(),a&&(e=a(e,r/2)),e=`0x${e}`;break;case"bin":e=e.toString(2).toUpperCase(),a&&(e=a(e,r)),e=`0b${e}`}return e}catch(e){logging.exception(e)}return null};function w(e,t){return Array.isArray(t)||(t=[t]),e.replace(/%{(\d+)}/g,((e,r)=>t[r]))}const A=new function(){this._outputInterface="none",this._numRepeats=10,this._navigatorFormatting={debug:[],log:["%c"+"%s ".repeat(this._numRepeats),"color:LightSeaGreen; font-weight:bold;"],info:["%c"+"%s ".repeat(this._numRepeats),"color:OliveDrab; font-weight:bold;"],warning:["%c"+"%s ".repeat(this._numRepeats),"color:Gold; font-weight:bold;"],error:["%c"+"%s ".repeat(this._numRepeats),"color:DeepPink; font-weight:bold;"],exception:[]},this._navigatorConsoleFunction={debug:console.log,log:console.debug,info:console.info,warning:console.warn,error:console.error,exception:console.error};try{process&&(this._navigatorFormatting={debug:["%c ","padding-left: 5px;"],log:["%c ","background: LightSeaGreen; padding-left: 5px;"],info:["%c ","background: OliveDrab; padding-left: 5px;"],warning:["%c ","background: Gold; padding-left: 5px;"],error:["%c ","background: DeepPink; padding-left: 5px;"],exception:[]})}catch(e){navigator.userAgent.search("Chrome")>=0||navigator.userAgent.search("Electron")>=0?this._navigatorFormatting={debug:["%c ","padding-left: 5px;"],log:["%c ","background: LightSeaGreen; padding-left: 5px;"],info:["%c ","background: OliveDrab; padding-left: 5px;"],warning:["%c ","background: Gold; padding-left: 5px;"],error:["%c ","background: DeepPink; padding-left: 5px;"],exception:[]}:navigator.userAgent.search("Safari")>=0&&(this._navigatorFormatting={debug:[],log:[],info:[],warning:[],error:[],exception:[]})}this._items=[],this._maxItems=1e4,this.setMaxLogLength=e=>{"number"==typeof e&&(this._maxItems=p(e),this._trimLength())},this.setOutputIf=e=>{if(this._outputInterface=e,"console"===this._outputInterface)for(let e in this._navigatorConsoleFunction)this[e]=this._navigatorConsoleFunction[e].bind(console,...this._navigatorFormatting[e]);else if("log"===this._outputInterface)for(let e in this._navigatorConsoleFunction)this[e]=(...t)=>{this._log(e,...t)};else for(let e in this._navigatorConsoleFunction)this[e]=()=>{}},this.getOutputIf=()=>this._outputInterface,this.showLog=()=>{try{for(let e of this._items)this._navigatorConsoleFunction[e.type](...this._navigatorFormatting[e.type],`[${e.function}][${e.file}]`,...e.data)}catch(e){}},this.logClean=()=>{try{this._items=[]}catch(e){}},this.logSize=()=>{try{return this._items.length}catch(e){}},this.getLogAsJsonString=()=>{try{return JSON.stringify(this._items)}catch(e){}},this.logSizeInBytes=()=>{try{return this.getLogAsJsonString().length}catch(e){}},this._trimLength=()=>{try{for(;this._items.length>=this._maxItems;)this._items.shift()}catch(e){}},this._log=(e,...t)=>{try{this._trimLength();let r=(new Error).stack.split("\n")[3].split("@"),n=[];for(let r of[...t])"exception"===e?n.push({error:r.toString(),stack:r.stack}):n.push(_(r));this._items.push({type:e,data:n,function:r[0].split("/").pop(),file:r[1].split("/").pop()})}catch(e){}},this.setOutputIf(this._outputInterface)};try{window&&!window.logging&&(window.logging=A)}catch(e){}let T=A,I={NOP:0,RESPONSE:1,UNIQUE_TOKEN:2,TYPE:{STRING:17,BLOB:18,INT_NUM:19,FLOAT_NUM:20,IPv4:21,IPv4_CIDR:22,IPv6:23,IPv6_CIDR:24,NTP_TIME:25,PTP_TIME:42,RESERVED_TIME:43,MSG_PACK:44},MODULE:{NAME:257,IP_CFG:258,IP:259,IP_MASK:260,IP_CIDR:261,GATEWAY:262,DNS_1:263,DNS_2:264,DHCP:265,FACTORY_DEFAULTS:266},FILE:{UAPP_TRANSFER:513,FIRMWARE_TRANSFER:514,BACKUP_FW_TRANSFER:515,TRANSFER:516,LIST:517,WEBPAGE_TRANSFER:520},SPECIAL:{UPGRADE_FIRMWARE:769,START_UAPP:770,STOP_UAPP:771,DELETE_UAPP:772,GET_DISCOVER_INFO:773,JSON_API:774,CONSOLE:775},RESULT:{OK:0,OUT_OF_MEM:1,LENGTH_EXCEEDS_FRAME:2,UNKNOWN_TYPE:3,BAD_LENGTH_FOR_TYPE:4,UNIQUE_TOKEN_TOO_LONG:5,STRING_TOO_LONG:6,MULTIPLE_COMMANDS:7,FILE_ERROR:8,UPGRADE_ERROR:9,MSG_PACK_NOT_SUPPORTED:11},COMMAND:{FILE:{READ:0,WRITE:1}},JSON_API_MSG_TYPE:{KEEP_ALIVE:0,VAR_LIST:1,VAR_ACCESS:2,DISCONNECT:255},API_VAR_ACCESS:{none:0,read:1,write:2,readWrite:3,0:"none",1:"read",2:"write",3:"readWrite"},API_C_TYPES:{bool:{type:0,size:1},s_byte:{type:1,size:8},u_byte:{type:2,size:8},s_int:{type:3,size:16},u_int:{type:4,size:16},s_dint:{type:5,size:32},u_dint:{type:6,size:32},s_long:{type:7,size:64},u_long:{type:8,size:64},float:{type:9,size:32},double:{type:10,size:64},timer:{type:11,size:0},counter:{type:12,size:0}},MSG_PACK:{INVALID:0,BEACON:1,CONSOLE_ENABLE:2,TAKE_CONTROL:3,MODULE_INFO:4,GET_INPUTS:16,GET_OUTPUTS:17,GET_METRICS:18,LIST_VARIABLES:22,ACCESS_VARIABLES:23,SET_INPUT_POLARITY:32,SET_OUTPUTS:33,SET_HOLDING_BRAKE:34}};const v={invalid:0,initializing:1,initFailed:2,faulted:3,operational:4,inFailSafeMode:10,connectingToPeers:11,motorNotConfigured:20,motorDisabled:21,motorI2tLimited:22,motorInSto:23,motorLimitSwitchActive:24,motorHoldingBrakeFault:25,motorStopped:26,motorRunning:27,externalControl:40,uAppNotPresent:41,uAppStartDelay:42,getStateByValue:e=>{for(let[t,r]of Object.entries(v))if(e==r)return t;return"invalid"}},k=(e=>{var t={};return n.d(t,e),t})({decode:()=>r.decode,encode:()=>r.encode});function P(e,t){try{e=d([e,""],"string"),t=d([t,{}],"object");let r=d([t.secure,!1],"boolean"),n=d([t.port],"number"),i=d([t.path],"string"),s=d([t.timestamp,!0],"boolean"),o=d([t.dotLocal,!0],"boolean"),a=t.protocolType;["ws","http"].indexOf(a)<0&&(a="ws");let c=!!e.match(/\.local$/);c&&(e=e.replace(".local",""));let l,h=`${a}${r?"s":""}`;null!=n&&(l=`:${n}`),i&&(i=i.replace(/\\/g,"/"),"/"==i[0]&&(i=i.substring(1)));let p="--",g=new u("IPv4"),_=`${h}://${e}`;return g(e)||(s&&!r&&(_+=`${p}T${Date.now()}`),(c||o)&&(_+=".local")),l&&(_+=`${l}`),i&&(_+=`/${i||""}`),_}catch(e){return T.exception(e),""}}function S(e){try{return 0==(e=d([e,8],"number"))&&(e=1),e>36&&(e=8),h().replace(/-/g,"").substring(0,e)}catch(e){T.exception(e)}return"12345678"}function E(e,t,r){try{if(isNaN(e))return null;r=null!=r&&r;let n=null;switch(t){case"int8":n=new DataView(new ArrayBuffer(1)),n.setInt8(0,e,r);break;case"uint8":n=new DataView(new ArrayBuffer(1)),n.setUint8(0,e,r);break;case"int16":n=new DataView(new ArrayBuffer(2)),n.setInt16(0,e,r);break;case"uint16":n=new DataView(new ArrayBuffer(2)),n.setUint16(0,e,r);break;case"int32":n=new DataView(new ArrayBuffer(4)),n.setInt32(0,e,r);break;case"uint32":n=new DataView(new ArrayBuffer(4)),n.setUint32(0,e,r)}if(n)return Array.from(new Uint8Array(n.buffer))}catch(e){T.exception(e)}return null}function C(e,t,r){try{if(!Array.isArray(e))return null;r=null!=r&&r;let n=new DataView(new Uint8Array(e).buffer);switch(t){case"int8":return n.getInt8(0,r);case"uint8":return n.getUint8(0,r);case"int16":return n.getInt16(0,r);case"uint16":return n.getUint16(0,r);case"int32":return n.getInt32(0,r);case"uint32":return n.getUint32(0,r)}}catch(e){T.exception(e)}return null}function x(e,t){try{Array.isArray(t)||(t=[]);let r=E(e,"uint32",!1);return r=r.concat(E(t.length,"uint32",!1)),r=r.concat(t),r}catch(e){T.exception(e)}return[]}function R(e){try{return(0,k.decode)(e)}catch(e){T.exception(e)}}function N(e){try{return{production:!!(64&e),failsafe:!!(128&e)}}catch(e){T.exception(e)}return{}}function M(e){try{return{}}catch(e){T.exception(e)}return{}}function O(e){try{return{}}catch(e){T.exception(e)}return{}}function D(e){try{let t=0;t=1;let r=e.slice(0,t)[0];e=e.slice(t,e.length),t=25;let n=f(e.slice(0,t),!0);e=e.slice(t,e.length),t=25;let i=f(e.slice(0,t),!0);e=e.slice(t,e.length),t=33;let s=f(e.slice(0,t),!0);e=e.slice(t,e.length),t=1;let o=e.slice(0,t)[0];e=e.slice(t,e.length),t=1;let a=e.slice(0,t)[0];e=e.slice(t,e.length),t=1;let c=e.slice(0,t)[0];e=e.slice(t,e.length),t=1;let l=e.slice(0,t)[0];e=e.slice(t,e.length);let u=N(l);t=6;let h=e.slice(0,t).map((e=>{let t=e.toString(16);return 1==t.length?"0"+t:t})).join(":");e=e.slice(t,e.length),t=4;let d=e.slice(0,t).join(".");e=e.slice(t,e.length),t=4;let p=e.slice(0,t).join(".");e=e.slice(t,e.length),t=4;let g=e.slice(0,t).join(".");e=e.slice(t,e.length),t=4;let _=e.slice(0,t).join(".");e=e.slice(t,e.length);let m=1,b=1,y=1,w=0;r>=2&&(t=1,m=e.slice(0,t)[0],e=e.slice(t,e.length),t=1,b=e.slice(0,t)[0],e=e.slice(t,e.length),t=1,y=e.slice(0,t)[0],e=e.slice(t,e.length),r>=3&&(t=1,w=e.slice(0,t)[0],e=e.slice(t,e.length)));let A=M();return{discoverVersion:r,sn:n,pn:i,name:s,firmware:[o,a,c].join("."),firmwareFlags:u,network:{ip:d,mask:p,gw:g,dns:_,mac:h},pcb:[m,b,y].join("."),pcbFlags:A}}catch(e){console.log(e)}return null}class V{_connecting=!1;_disconnecting=!1;constructor(e){this.id=d([e.id,h()],"string"),this.target=d([e.target,e.host,""],"string"),this.port=e.port,this.path=d([e.path,"cmd"],"string"),this.secure=d([e.secure,!1],"boolean"),this._reconnectAttempts=d([e.reconnectAttempts,3],"number"),this.createTimeout=d([e.createTimeout,15e3],"number"),this.connectTimeout=d([e.connectTimeout,15e3],"number"),this.requestTimeout=d([e.requestTimeout,1e4],"number"),this.keepAliveTimeout=d([e.keepAliveTimeout,5e3],"number"),this.reconnectTimeout=parseInt(this.connectTimeout/3-500),this.reconnectTimeout<=0&&(T.error("Connect time too small. Has to be at least: 5000"),this.reconnectTimeout=1e3),this._wsInputBuffSize=d([e.wsInputBuffSize],"number"),this.autoConnect=d([e.autoConnect,!1],"boolean"),this.reconnect=d([e.reconnect,!0],"boolean"),this.keepAlive=d([e.keepAlive,!0],"boolean"),this.binary=d([e.binary,!0],"boolean"),this.keepAliveTimeout<1e3&&(this.keepAliveTimeout=1e3),this.targetUrl=this.getTarget(),this._reconnectCount=this._reconnectAttempts,this._lastRequestTime=Date.now(),this._msgQueue={},this._msgSendAllowedTimeout=100,this._msgSendAllowed=!0,this._cmdState=null,this._state="disconnected",this._connectionGuardTimeout=100,this._connectionGuardTimer=null,this._callback=e.callback}get callback(){return this._callback}get on(){return this._callback.on}dispose=async()=>{try{this._cmdState="dispose",await this.disconnect(),this._msgQueue={}}catch(e){T.exception(e)}return null};getTarget=e=>{"object"!=typeof e&&(e={});let t={port:this.port,path:this.path,secure:this.secure,...e},r=P(this.target,t);return t.secure&&this._wsInputBuffSize&&(r=`${r}?ibs=${this._wsInputBuffSize}`),r};setTarget=e=>{try{if("string"!=typeof e)return void T.error("Target is not string:",e);this.target=e,this.targetUrl=P(this.target,{port:this.port,path:this.path,secure:this.secure})}catch(e){T.exception(e)}};connect=e=>new Promise((async(t,r)=>{try{this._connecting=!0;let r=await this._connect(e);this._connecting=!1,t(r)}catch(e){this._connecting=!1,r(e)}}));disconnect=()=>new Promise((async(e,t)=>{try{this._disconnecting=!0;let t=await this._disconnect();this._disconnecting=!1,e(t)}catch(e){this._disconnecting=!1,t(e)}}));connected=()=>"connected"==this._state;disconnected=()=>"disconnected"==this._state;setBinary=e=>{};send=e=>{throw new Error("Method not implemented...")};request=e=>new Promise((async(t,r)=>{try{this._lastRequestTime=Date.now();let n=S(),i=x(I.UNIQUE_TOKEN,m(n));i=i.concat(e),this._msgQueuePut(n,{state:"sent",time:this._lastRequestTime,resolve:t,reject:r}),this.send(i)}catch(e){T.exception(e),r(e)}}));msgPackRequest=async e=>new Promise((async(t,r)=>{try{let r=function(e){try{return x(I.TYPE.MSG_PACK,Array.from(function(e){try{return(0,k.encode)(e)}catch(e){T.exception(e)}}(e)))}catch(e){T.exception(e)}return[]}(e),n=await this.request(r);if(n.error)return void t({success:!1,error});if(0==n.items.length)return void t({success:!1,error:"Response items are missing..."});if(n.items[0].ctpType!=I.TYPE.MSG_PACK)return void t({success:!1,error:"Response item is not MsgPack..."});let i=n.items[0].data;if(i.length<2)return void t({success:!1,error:"MsgPack returns less then required two items - success and error"});if(!i[0])return void t({success:!1,error:i[1]});let s={success:!0,token:n.token,data:i.slice(2)};n.ntpTime&&(s.ntpTime=n.ntpTime),t(s)}catch(e){t({success:!1,error:e})}}));onMessage=e=>{try{let t=e.data;if(this.binary){if(t=function(e){try{if(!Array.isArray(e))return{error:"Message is not array"};if(e.length<8)return T.debug("ERROR:",e),{error:"Message length is less then 8 bytes"};let t={error:null,items:[]};for(;e.length>=8;){let r=C(e.slice(0,4),"uint32",!1),n=C(e.slice(4,8),"uint32",!1),i=[];switch(n>0&&(i=e.slice(8,8+n)),r){case I.UNIQUE_TOKEN:t.token=i;break;case I.TYPE.NTP_TIME:{let e=C(i.slice(0,4),"uint32",!1),r=C(i.slice(4,8),"uint32",!1);t.ntpTime=e+p(r/Math.pow(2,32),3);break}case I.RESPONSE:t.type=r,t.response=i[0];break;case I.SPECIAL.CONSOLE:t.type=r;break;case I.TYPE.MSG_PACK:t.items.push({ctpType:r,ctpLength:n,data:R(i)});break;default:t.items.push({ctpType:r,ctpLength:n,data:i})}e=e.slice(8+n)}return t}catch(e){return{error:e}}}(Array.from(new Uint8Array(t))),t.type==I.SPECIAL.CONSOLE){let e=function(e){let t={success:!0,timestamp:e.ntpTime,error:null};try{for(let r of e.items)r.ctpType==I.TYPE.STRING&&(t.text||(t.text=""),t.text+=f(r.data))}catch(e){T.exception(e),t.success=!1,t.error=e}return t}(t);return void(e.error||this._callback.dispatch("console",e))}let e=null;t.token&&(e=f(t.token));let r=this._msgQueueGet(e);r&&(r.state="received",t.error?r.reject(t.error):t.response!=I.RESULT.OK?r.reject(`Unexpected response type [${t.response}]: ${function(e){try{for(let t in I.RESULT)if(I.RESULT[t]==e)return t}catch(e){T.exception(e)}return null}(t.response)}'`):r.resolve(t),this._msgQueuePull(e))}this._callback.dispatch("message",t)}catch(e){T.exception(e)}};onConnect=e=>{T.debug(`Connection connected: ${this.targetUrl}`),this._state="connected",this._callback.dispatch("connect",e)};onDisconnect=e=>{T.debug(`Connection disconnected: ${this.targetUrl}`),this._state="disconnected",this._callback.dispatch("disconnect",e)};onError=e=>{T.exception(`Connection error: ${this.targetUrl}`),this._state="error",this._callback.dispatch("error",e)};_connect=()=>new Promise(((e,t)=>{t("Method not implemented...")}));_disconnect=()=>new Promise(((e,t)=>{t("Method not implemented...")}));_msgQueueGet=e=>{try{return this._msgQueue[e]}catch(e){}return null};_msgQueuePut=(e,t)=>{if(this._msgQueue.hasOwnProperty(e))return T.warning(`Message with token [ ${e} ] already exist...`),void t.reject(`Connection message queue [ ${e} ] -> Duplicated token...`);this._msgQueue[e]=t};_msgQueuePull=e=>{try{delete this._msgQueue[e]}catch(e){}};_guardStart=()=>{this._connectionGuardTimer||(T.warning(`Start guard [ ${this.targetUrl} ]`),this._connectionGuardTimer=setTimeout(this._connectionGuardLoop,1))};_guardStop=()=>{T.warning(`Stop guard [ ${this.targetUrl} ]`),this._connectionGuardTimer=clearTimeout(this._connectionGuardTimer)};_connectionGuardLoop=async()=>{this._connectionGuardTimer=clearTimeout(this._connectionGuardTimer);try{if("dispose"==this._cmdState)return;let e=[],t=Date.now();for(let[r,n]of Object.entries(this._msgQueue))n&&"object"==typeof n&&t-n.time>=this.requestTimeout&&(n.state="timeout",e.push(r));for(let t of e)T.warning(`Connection ${this.targetUrl} token [ ${t} ] timeout -> Garbage collected...`),"function"==typeof this._msgQueue[t].reject&&this._msgQueue[t].reject(`Request ID:${t} timeout...`),delete this._msgQueue[t];if(this.connected()&&Date.now()-this._lastRequestTime>=this.keepAliveTimeout)try{this.request(x(I.NOP))}catch(e){}this.reconnect&&"connect"==this._cmdState&&!this.connected()&&(this._reconnectTime?Date.now()-this._reconnectTime>=this.reconnectTimeout&&(this._reconnectTime=null,this._connecting||this.connect()):this._reconnectTime=Date.now())}catch(e){T.exception(e)}this._connectionGuardTimer=setTimeout(this._connectionGuardLoop,this._connectionGuardTimeout)}}class U extends V{constructor(e){super(e),this._ipcRenderer=e.ipcRenderer,this._requestTarget="ws",this._commHandleDisposed=!1,this._created=!1,this._ipcRenderer&&this._ipcRenderer.on(this.id,this.handleMessage)}dispose=async()=>{try{T.debug(`Connection dispose - Host: ${this.target}/${this.path}`),this._cmdState="dispose",await this.disconnect(),await this._disposeConnection(),this._ipcRenderer&&this._ipcRenderer.removeListener(this.id,this.handleMessage),this._msgQueue={}}catch(e){T.exception(e)}return null};created=()=>!!this._created;_requestHandle=e=>{try{this._ipcRenderer&&this._ipcRenderer.send(this._requestTarget,e)}catch(e){T.exception(e)}};create=()=>new Promise((async(e,t)=>{try{if(this.created())return void e();this._requestHandle({id:this.id,type:"create",target:P(this.target,{port:this.port,path:this.path,secure:this.secure}),binary:this.binary});let r=!1,n=setTimeout((()=>{this.created()||(r=!0)}),this.createTimeout);for(;!this.created()&&(!r||this.created());)await g(100);n&&clearTimeout(n),r?t("timeout"):e()}catch(e){t(e)}}));connect=(e,t)=>new Promise((async(r,n)=>{try{if(this.connected())return void r();if("string"==typeof e&&(this.targetUrl=e),this._state="connecting",this._cmdState="connect",this._guardStart(),this._requestHandle({id:this.id,type:"connect",target:this.targetUrl}),t)return void r();let i=!1,s=setTimeout((()=>{this.connected()||(i=!0)}),this.connectTimeout+5e3);for(;!this.connected()&&(!i||this.connected());)await g(100);clearTimeout(s),s=null,i?(T.debug(`Connecting to: ${this.target}/${this.path} timeout...`),n("timeout")):r()}catch(e){n(e)}}));disconnect=()=>new Promise((async(e,t)=>{try{if(!this.connected())return void e();this._state="disconnecting",this._cmdState="disconnect",this._guardStop(),this._requestHandle({id:this.id,type:"disconnect"});let r=!1,n=setTimeout((()=>{this.connected()&&(r=!0)}),this.connectTimeout+5e3);for(;!(this.disconnected()||r&&this.connected());)await g(100);clearTimeout(n),n=null,r?(T.debug(`Disconnecting from: ${this.target}/${this.path} timeout...`),t("timeout")):e()}catch(e){t(e)}}));send=e=>{try{this._requestHandle({id:this.id,type:"dataTransfer",payload:e})}catch(e){}};handleMessage=async(e,t)=>{try{switch(t.type){case"connection":"created"==t.state?this._created=!0:"connected"==t.state?"function"==typeof this.onConnect&&this.onConnect():"disconnected"==t.state?"function"==typeof this.onDisconnect&&this.onDisconnect():"disposed"==t.state?this._commHandleDisposed=!0:"error"==t.state&&"function"==typeof this.onError&&this.onError(t.error);break;case"dataTransfer":this.onMessage({data:t.payload});break;default:T.error("Unsupported message:",t)}}catch(e){T.exception(e)}};_disposeConnection=()=>new Promise((async(e,t)=>{try{if(this._created=!1,this._commHandleDisposed)return T.debug(`Connection ${this.target}/${this.path} already disposed...`),void e();T.debug("Dispose Communication handle..."),this._requestHandle({id:this.id,type:"dispose"});let r=!1,n=setTimeout((()=>{this._commHandleDisposed||(r=!0)}),this.connectTimeout+5e3);for(;!this._commHandleDisposed;){if(r&&!this._commHandleDisposed){T.warning("Remote connection disposed...");break}await g(100)}n&&clearTimeout(n),r?(T.debug("Communication handle dispose timeout..."),t(`Communication handle dispose: ${this.target}/${this.path} timeout...`)):e()}catch(e){t(e)}}))}class F extends V{constructor(e){super(e),this._useSecure=!!e.useSecure,this._getWebSocket=e.getWebSocket,this._ws=null}dispose=async()=>{try{T.debug(`Dispose connection -> host: ${this.target}...`),this._cmdState="dispose",await this.disconnect(),this._msgQueue={}}catch(e){T.exception(e)}return null};setBinary=e=>{this._ws&&(this._ws.binaryType=e?"arraybuffer":"blob")};send=e=>{try{if(this._ws){if(this.binary&&Array.isArray(e))return void this._ws.send(new Uint8Array(e));this._ws.send(e)}}catch(e){}};_connect=e=>new Promise((async(t,r)=>{try{if("connected"==this._state)return void t();"string"==typeof e&&(this.targetUrl=e);let n=!1,i=setTimeout((()=>{this.connected()||(n=!0)}),this.connectTimeout),s=1;for(s=1;s<=this._reconnectAttempts;s++){if(this._state="connecting",this._cmdState="connect",!this._ws){let e=this.getTarget({timestamp:s==this._reconnectAttempts});T.warning(`Connect to :---\x3e ${e}`),this._ws=this._getWebSocket(e),this.setBinary(this.binary),this._ws.onopen=this.onConnect,this._ws.onclose=this.onDisconnect,this._ws.onerror=this.onError,this._ws.onmessage=this.onMessage}let e=Date.now();for(;Date.now()-e<this.reconnectTimeout&&!n&&"connecting"==this._state;)await g(100);if(this.connected())break;if(this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{},this._ws.onmessage=()=>{},this._ws.close(),this._ws=null),n)break}i=clearTimeout(i),this.connected()?(this._guardStart(),t()):n?r(`Connecting to: ${this.targetUrl} timeout...`):s>=this._reconnectAttempts?r(`Connecting to: ${this.targetUrl} reconnect...`):r(`Connecting to: ${this.targetUrl} failed...`)}catch(e){r(e)}}));_disconnect=()=>new Promise((async(e,t)=>{try{if("disconnected"==this._state)return this._disposeWs(),void e();this._state="disconnecting",this._cmdState="disconnect",this._guardStop(),this._ws&&this._ws.close();let r=!1,n=setTimeout((()=>{this.disconnected()||(r=!0)}),this.connectTimeout);for(;!this.disconnected()&&(!r||this.disconnected());)await g(10);n&&clearTimeout(n),r?t(`Disconnecting from: ${this.target} timeout...`):(this._disposeWs(),e())}catch(e){t(e)}}));_disposeWs=()=>{try{this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{},this._ws.onmessage=()=>{},this._ws=null)}catch(e){T.exception(e)}}}class L{constructor(e){this._getConnectionHandle=e.getConnectionHandle}get _connectionHandle(){return this._getConnectionHandle()}dispose=async()=>{};read=(e,t)=>new Promise((async(r,n)=>{try{if(!e)return void n("Method readFiles expects array argument...");Array.isArray(e)||(e=[e]);let i=[];t=d([t,I.FILE.TRANSFER],"number");for(let r of e){let e=r.path,s=d([r.content,"bytes"],"string");if(!e||"string"!=typeof e)return void n("File path is not string...");e=e.replace(/\\/g,"/"),"."==e[0]&&(e=e.substring(1)),"/"!=e[0]&&(e=`/${e}`);let o=x(t,[I.COMMAND.FILE.READ]);o=o.concat(x(I.TYPE.STRING,m(e)));let a=await this._connectionHandle.request(o);if(a.error)return void n(a.error);let c=a.items[0].data;"string"!=s&&"json"!=s||(c=f(c),"json"==s&&(c=JSON.parse(c))),i.push(c)}0==i.length?n("There is no file(s) content received..."):i.length>1?r(i):r(i[0])}catch(e){n(e)}}));write=(e,t)=>new Promise((async(r,n)=>{try{if(!e)return void n("Files not provided...");Array.isArray(e)||(e=[e]),t=d([t,I.FILE.TRANSFER],"number");for(let r of e){let e=r.path;if(!e||"string"!=typeof e)return void n("File path is not string...");e=e.replace(/\\/g,"/"),"."==e[0]&&(e=e.substring(1)),"/"!=e[0]&&(e=`/${e}`);let i=r.content;if("object"!=typeof i||Array.isArray(i)||(i=JSON.stringify(i)),"string"==typeof i&&(i=m(i)),!i||!Array.isArray(i))return void n("File data is not array...");let s=x(t,[I.COMMAND.FILE.WRITE]);s=s.concat(x(I.TYPE.STRING,m(e))),s=s.concat(x(I.TYPE.BLOB,i));let o=await this._connectionHandle.request(s);if(o.error)return void n(o.error)}r(!0)}catch(e){n(e)}}));deleteUserApp=()=>new Promise((async(e,t)=>{try{let r=await this._connectionHandle.request(x(I.SPECIAL.DELETE_UAPP));if(r.error)return void t(r.error);e(!0)}catch(t){e(t)}}));uploadUserApp=e=>{try{return this.write([{path:"/uapp/application.idsol",content:e}],I.FILE.UAPP_TRANSFER)}catch(e){T.exception(e)}};uploadFirmware=e=>{try{return this.write([{path:"/firmware/firmware.ckfw",content:e}],I.FILE.FIRMWARE_TRANSFER)}catch(e){T.exception(e)}};uploadWebpage=e=>{try{return this.write([{path:"web.bfb",content:e}],I.FILE.WEBPAGE_TRANSFER)}catch(e){T.exception(e)}};readModuleConfig=()=>{try{return this.read({path:"/config/module_cfg.json",content:"json"})}catch(e){return T.exception(e),null}};writeModuleConfig=e=>{try{return this.write({path:"/config/module_cfg.json",content:e})}catch(e){return T.exception(e),null}}}class G{constructor(e){this._getConnectionHandle=e.getConnectionHandle}get _connectionHandle(){return this._getConnectionHandle()}dispose=async()=>{};getInfo=()=>new Promise((async(e,t)=>{try{let r=x(I.SPECIAL.GET_DISCOVER_INFO),n=await this._connectionHandle.request(r);if(n.error)return void t(n.error);let i=null;if(n.items.length>0&&(i=D(n.items[0].data)),!i)return void t("Message decoding error");e(i)}catch(e){t({error:e})}}))}class H{constructor(e){this._getConnectionHandle=e.getConnectionHandle}get _connectionHandle(){return this._getConnectionHandle()}dispose=async()=>{};getMetrics=()=>new Promise((async(e,t)=>{try{let t=await this._connectionHandle.msgPackRequest([I.MSG_PACK.GET_METRICS]);t.error&&e({success:!1,error:`InoDrive getMetrics Error: ${t.error}`});let r=t.data[0];if(r.state)for(let[e,t]of Object.entries(r.state))r.state[e]=v.getStateByValue(t);let n={};for(let e of r.eth_ports)n[e.name]={link:e.link,errors:e.errors};r.eth_ports=n,r.success=!0,e(r)}catch(t){e({success:!1,error:t})}}));getTemperatures=()=>new Promise((async(e,t)=>{try{let t=await this.getMetrics();t.error&&(T.error(t.error),e(null)),e({case:t.temperatures.case,cpu:t.temperatures.cpu,fets:t.temperatures.fets,outputs:t.temperatures.outputs,regen:t.temperatures.regen})}catch(t){T.exception(t),e(null)}}));getInputVoltage=()=>new Promise((async(e,t)=>{try{let t=await this.getMetrics();t.error&&(T.error(t.error),e(null)),e(t.v_in)}catch(t){T.exception(t),e(null)}}));getOperationalState=()=>new Promise((async(e,t)=>{try{let t=await this.getMetrics();t.error&&(T.error(t.error),e(null)),e(t.state)}catch(t){T.exception(t),e(null)}}));getEthernetPorts=()=>new Promise((async(e,t)=>{try{let t=await this.getMetrics();t.error&&(T.error(t.error),e(null)),e(t.eth_ports)}catch(t){T.exception(t),e(null)}}));getInputsData=()=>new Promise((async(e,t)=>{try{let t=await this._connectionHandle.msgPackRequest([I.MSG_PACK.GET_INPUTS]);t.error&&e({success:!1,error:`InoDrive GetInputData Error: ${t.error}`});let r=t.data[0];r.success=!0,e(r)}catch(t){e({success:!1,error:t})}}));getAccelerometer=()=>new Promise((async(e,t)=>{try{let t=await this.getInputsData();t.error&&(T.error(t.error),e(null)),e({x:t.g_forces[0],y:t.g_forces[1],z:t.g_forces[2]})}catch(t){T.exception(t),e(null)}}));getInput=e=>new Promise((async(t,r)=>{try{let r=await this.getInputsData();r.error&&(T.error(r.error),t(null)),Number.isInteger(e)&&e>=0&&e<=3?t(r.digital>>e&1?1:0):t(r.digital)}catch(e){T.exception(e),t(null)}}));getSafetyInput=e=>new Promise((async(t,r)=>{try{let r=await this.getInputsData();r.error&&(T.error(r.error),t(null)),Number.isInteger(e)&&e>=0&&e<=1?t(r.safety>>e&1?1:0):t(r.safety)}catch(e){T.exception(e),t(null)}}));getAnalogInput=()=>new Promise((async(e,t)=>{try{let t=await this.getInputsData();t.error&&(T.error(t.error),e(null)),e(t.analog)}catch(t){T.exception(t),e(null)}}));setInputPolarity=(e,t)=>new Promise((async(r,n)=>{try{if("all"==e&&t)e=-1,t="string"==typeof t?"NPN"==t.toUpperCase()?15:0:t?15:0;else if("val"==e&&t===parseInt(t,10))e=-1;else{if(!(Number.isInteger(e)&&e>=0&&e<=3&&t))return T.error("InoDrive SetInputPolarity Error: target or state not supported..."),void r(null);t="string"==typeof t?"NPN"==t.toUpperCase()?1:0:t?1:0}let n=await this._connectionHandle.msgPackRequest([I.MSG_PACK.SET_INPUT_POLARITY,e,t]);n.error&&r({success:!1,error:`InoDrive SetInputPolarity Error: ${n.error}`}),r(!0)}catch(e){T.exception(e),r(null)}}));getInputPolarity=e=>new Promise((async(t,r)=>{try{let r=await this.getInputsData();r.error&&(T.error(r.error),t(null)),Number.isInteger(e)&&e>=0&&e<=3?t(r.polarity>>e&1?"NPN":"PNP"):t(r.polarity)}catch(e){T.exception(e),t(null)}}));getOutputsData=()=>new Promise((async(e,t)=>{try{let t=await this._connectionHandle.msgPackRequest([I.MSG_PACK.GET_OUTPUTS]);t.error&&e({success:!1,error:`InoDrive GetOutputData Error: ${t.error}`});let r=t.data[0];r.success=!0,e(r)}catch(t){e({success:!1,error:t})}}));setOutput=(e,t)=>new Promise((async(r,n)=>{try{if("all"==e&&void 0!==t)e=-1,t=t?7:0;else if("val"==e&&t===parseInt(t,10))e=-1;else{if(!(Number.isInteger(e)&&e>=0&&e<=2&&void 0!==t))return T.error("InoDrive SetOutput Error: target or state not supported..."),void r(null);t=t?1:0}let n=await this._connectionHandle.msgPackRequest([I.MSG_PACK.SET_OUTPUTS,e,t]);n.error&&r({success:!1,error:`InoDrive SetOutput Error: ${n.error}`}),r(!0)}catch(e){T.exception(e),r(null)}}));getOutput=e=>new Promise((async(t,r)=>{try{let r=await this.getOutputsData();r.error&&(T.error(r.error),t(null)),Number.isInteger(e)&&e>=0&&e<=2?t(r.digital>>e&1?1:0):t(r.digital)}catch(e){T.exception(e),t(null)}}));getOutputFault=e=>new Promise((async(t,r)=>{try{let r=await this.getOutputsData();r.error&&(T.error(r.error),t(null)),Number.isInteger(e)&&e>=0&&e<=2?t(r.digital_faults>>e&1?1:0):t(r.digital_faults)}catch(e){T.exception(e),t(null)}}));setHoldingBrake=e=>new Promise((async(t,r)=>{try{let r=await this._connectionHandle.msgPackRequest([I.MSG_PACK.SET_HOLDING_BRAKE,!!e]);r.error&&t({success:!1,error:`InoDrive SetHoldingBrake Error: ${r.error}`}),t(!0)}catch(e){T.exception(e),t(null)}}));getHoldingBrake=()=>new Promise((async(e,t)=>{try{let t=await this.getOutputsData();t.error&&(T.error(t.error),e(null)),e(t.brake)}catch(t){T.exception(t),e(null)}}));getHoldingBrakeFault=()=>new Promise((async(e,t)=>{try{let t=await this.getOutputsData();t.error&&(T.error(t.error),e(null)),e(t.brake_fault?1:0)}catch(t){T.exception(t),e(null)}}))}const j="msgPack",B="json";class q{_guardTimer=null;_guardTimeout=10;_lastPollTime=null;_connected=!1;_pollActive=!1;_initialized=!1;_dataAvailable=!1;constructor(e){this._callback=e.callback,this._getWorker=e.getWorker,this._getConnectionHandle=e.getConnectionHandle,this._guardMultiplier=d([e.disconnectOnMissedPolls,3],"number"),this._protocol=j,this._variableValues={},this._awaitingResponse=!1,this._programId=null,this._ntpPollTime=0,this._pollTime=d([e.pollTime,1e3],"number"),this._pollRunning=!1,this._worker=this._getWorker(this._onWorkerMessage),this._callback.on("connect",this._onConnect),this._callback.on("disconnect",this._onDisconnect),this._callback.on("error",this._onError),this._callback.on("console",this._onConsole)}get _connectionHandle(){return this._getConnectionHandle()}get callback(){return this._callback}get on(){return this._callback.on}dispose=async()=>{this.stopPoll()};getVariable=e=>{try{for(let[t,r]of Object.entries(this._variableValues)){if(d([e],"string")&&t==e)return r;if(Number.isInteger(e)&&r.id==e)return r}}catch(e){T.error(e)}return null};getVariableCType=e=>{try{for(let[t,r]of Object.entries(I.API_C_TYPES))if(r.type==e)return t}catch(e){T.error(e)}return null};startPoll=async e=>{e&&(this._pollTime=e),this._lastPollTime=Date.now(),await this._poll(),this._worker&&this._worker.postMessage({cmd:"start",timeout:this._pollTime}),this._guardTimer=clearTimeout(this._guardTimer),this._guardTimer=setTimeout(this._pollGuardLoop,this._guardTimeout)};stopPoll=()=>{this._guardTimer=clearTimeout(this._guardTimer),this._worker&&this._worker.postMessage({cmd:"stop"})};waitForDataAvailable=e=>new Promise((async(t,r)=>{e=e||5e3,T.debug("Timeout:",e);let n=Date.now();for(;Date.now()-n<e;)Object.keys(this._variableValues).length>0&&t(),await g(100);r("timeout")}));getVariablesList=e=>{try{let t=[];e&&!Array.isArray(e)&&(e=[e]);for(let[r,n]of Object.entries(this._variableValues))e&&e.indexOf(n.access)<0||t.push(r);return t}catch(e){T.error(e)}};getAllVariables=()=>{let e={timestamp:this._ntpPollTime,programId:this._programId,items:{}};for(let[t,r]of Object.entries(this._variableValues))e.items[t]={id:r.id,access:I.API_VAR_ACCESS[r.access],type:r.type,value:r.value};return e};updateVariablesList=()=>new Promise((async(e,t)=>{try{let r=null,n=null;if(this._protocol==j){let e=await this._connectionHandle.msgPackRequest([I.MSG_PACK.LIST_VARIABLES]);if(e.error){if(!([I.RESULT.UNKNOWN_TYPE,I.RESULT.MSG_PACK_NOT_SUPPORTED].indexOf(e.error)>=0))return void t(`Retrieving variables list failed. Error: ${e.error}`);this._protocol=B}else r=e.data[0],n=e.data[1]}if(this._protocol==B){let e=x(I.SPECIAL.JSON_API),i={id:S(8),request:I.JSON_API_MSG_TYPE.VAR_LIST};e=e.concat(x(I.TYPE.STRING,m(JSON.stringify(i))));let s=await this._connectionHandle.request(e);if(s.error)return void t(s.error);if(0==s.items.length)return void t("Missing data.");if(s.items[0].ctpType!=I.TYPE.STRING)return void t(`Unsupported response type: ${s.items[0].ctpType}`);let o=JSON.parse(f(s.items[0].data));r=o.program_id,n=o.data}if(!r)return void t("Program ID is missing.");if(!n)return void t("Variable list data is missing.");this._programId=r,this._updateVariablesList(n),e(this._variableValues)}catch(e){t(e)}}));readVar=async(e,t)=>new Promise((async(r,n)=>{try{this._connectionHandle.connected()&&!this._initialized&&await this._poll(),t=d([t,{}],"object");let i=[],s=[];if(d([e],"string")||Number.isInteger(e))s.push(e);else{if(!Array.isArray(e))return void n("Unsupported argument type...");s=e}for(let e of s){let t=this.getVariable(e);if(!t)return void n(`Variable < ${e} > not found...`);if(this._protocol==j)i.push([t.id,!1]);else{if(this._protocol!=B)return void n("Unsupported protocol.");i.push({id:t.id})}}if(0==i.length)return void n("Invalid Request Data...");let o=await this._var_access_request(i);if(o.error)return void n(o.error);let a={};for(let e of o.data){let r=this.getVariable(e[0]);if(r){r.value=e[1];let n=this._getVarNameByID(r.id);null!=r.value&&d([t.floatPrecision],"number")>=0&&"float"==r.type?a[n]=parseFloat(r.value.toFixed(t.floatPrecision)):a[n]=r.value}}Object.entries(a).length>0&&(Array.isArray(e)||(a=Object.values(a)[0])),r(a)}catch(e){n(e)}}));writeVar=(e,t,r)=>new Promise((async(n,i)=>{try{this._connectionHandle.connected()&&!this._initialized&&await this._poll(),r=d([r,{}],"object");let s={},o=[];if(!d([e],"string")&&!Number.isInteger(e)||isNaN(t)){if(Array.isArray(e)||"object"!=typeof e)return void i("Unsupported argument type...");s=e}else s[e]=t;for(let[e,t]of Object.entries(s)){let r=this.getVariable(e);if(!r)return void i(`Variable < ${e} > not found...`);let n=y(t,{type:r.type});if(r.value=n,this._protocol==j)"bool"==r.type&&(r.value=!!r.value),o.push([r.id,!0,r.value]);else{if(this._protocol!=B)return void i("Unsupported protocol.");o.push({id:r.id,val:r.value})}}let a=await this._var_access_request(o);if(a.error)return void i(a.error);n(!0)}catch(e){i(e)}}));getVar=(e,t)=>{try{t=d([t,{}],"object");let r=[];if(d([e],"string")||Number.isInteger(e))r.push(e);else{if(!Array.isArray(e))return reject("Unsupported argument type..."),!1;r=e}let n={};for(let e of r){let r=this.getVariable(e);if(!r)return T.error(`Variable < ${e} > not found...`),!1;let i=this._getVarNameByID(r.id);null!=r.value&&d([t.floatPrecision],"number")>=0&&"float"==r.type?n[i]=parseFloat(r.value.toFixed(t.floatPrecision)):n[i]=r.value}if(Object.entries(n).length>0)return Array.isArray(e)?n:Object.values(n)[0]}catch(e){T.error(e)}return null};setVar=(e,t,r)=>{try{r=d([r,{}],"object");let n={};if(!d([e],"string")&&!Number.isInteger(e)||isNaN(t)){if(Array.isArray(e)||"object"!=typeof e)return reject("Unsupported argument type..."),!1;n=e}else n[e]=t;for(let[e,t]of Object.entries(n)){let r=this.getVariable(e);if(!r)return T.error(`Variable < ${e} > not found...`),!1;let n=y(t,{type:r.type});return"bool"==r.type&&(n=!!n),r.value=n,r.write=!0,!0}}catch(e){T.error(e)}return!1};_onConnect=e=>{try{this._connected||(this._callback.dispatch("appStatus",{state:"connected"}),this._connected=!0)}catch(e){T.error(e)}};_onDisconnect=e=>{try{this._connected&&(this._callback.dispatch("appStatus",{state:"disconnected"}),this._connected=!1)}catch(e){T.error(e)}};_onError=e=>{try{this._connected&&(this._callback.dispatch("appStatus",{state:"disconnected"}),this._connected=!1)}catch(e){T.error(e)}};_onConsole=e=>{try{this._pollActive&&this._callback.dispatch("appConsole",e)}catch(e){T.error(e)}};_onWorkerMessage=async e=>{try{let t=null;if(t=e.data?e.data:e,!t)return;if("poll"===t.cmd){if(this._pollRunning)return;this._pollRunning=!0,await this._poll(),this._pollRunning=!1}}catch(e){T.error(e)}};_getVarNameByID=e=>{for(let t in this._variableValues)if(this._variableValues[t].id==e)return t;return null};_updateVariablesList=e=>{try{let t=[];for(let[r,n]of Object.entries(this._variableValues)){let n=!1;for(let t of e)r!=t.name||(n=!0);n||t.push(r)}t.map((e=>{delete this._variableValues[e]}));for(let t of e){let e=this._variableValues[t.name];e?(e.id=t.id,e.type=this.getVariableCType(t.type),e.access=t.access,e.value=y(e.value,{type:e.type})):this._variableValues[t.name]={id:t.id,type:this.getVariableCType(t.type),access:t.access,value:null,