unetjs 3.2.2 → 3.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).unet={})}(this,(function(e){"use strict";const t="undefined"!=typeof window&&void 0!==window.document,r="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,s="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,n="undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"));"undefined"!=typeof Deno&&Deno.core;const i="open",o="opening";var a;class l{constructor(e={}){let t=e.hostname||"localhost",r=e.port||1100;this._keepAlive=e.keepAlive,this._reconnectTime=e.reconnectTime||5e3,this.url=new URL("tcp://localhost"),this.url.hostname=t,this.url.port=r.toString(),this._buf="",this._firstConn=!0,this._firstReConn=!0,this.pendingOnOpen=[],this.connListeners=[],this.debug=!1,this._sockInit(t,r)}_sendConnEvent(e){this.connListeners.forEach((t=>{t&&"[object Function]"==={}.toString.call(t)&&t(e)}))}_sockInit(e,t){if(a)this._sockSetup(e,t);else try{import("net").then((r=>{a=r.createConnection,this._sockSetup(e,t)}))}catch(e){this.debug&&console.log("Unable to import net module")}}_sockSetup(e,t){if(a)try{this.sock=a({host:e,port:t}),this.sock.setEncoding("utf8"),this.sock.on("connect",this._onSockOpen.bind(this)),this.sock.on("error",this._sockReconnect.bind(this)),this.sock.on("close",(()=>{this._sendConnEvent(!1)})),this.sock.send=e=>{this.sock.write(e)}}catch(e){return void(this.debug&&console.log("Connection failed to ",this.sock.host+":"+this.sock.port))}}_sockReconnect(){!this._firstConn&&this._keepAlive&&this.sock.readyState!=o&&this.sock.readyState!=i&&(this._firstReConn&&this._sendConnEvent(!1),this._firstReConn=!1,setTimeout((()=>{this.pendingOnOpen=[],this._sockSetup(this.url.hostname,this.url.port)}),this._reconnectTime))}_onSockOpen(){this._sendConnEvent(!0),this._firstConn=!1,this.sock.on("close",this._sockReconnect.bind(this)),this.sock.on("data",this._processSockData.bind(this)),this.pendingOnOpen.forEach((e=>e())),this.pendingOnOpen.length=0,this._buf=""}_processSockData(e){this._buf+=e;var t=this._buf.split("\n");t.forEach(((e,r)=>{r<t.length-1?e&&this._onSockRx&&this._onSockRx.call(this,e):this._buf=e}))}toString(){let e="";return e+=(this.sock,this.sock.remoteAddress.toString()+":"+this.sock.remotePort.toString()),e}write(e){return this.sock&&this.sock.readyState!=o?this.sock.readyState==i&&(this.sock.send(e+"\n"),!0):(this.pendingOnOpen.push((()=>{this.sock.send(e+"\n")})),!0)}setReadCallback(e){e&&"[object Function]"==={}.toString.call(e)&&(this._onSockRx=e)}addConnectionListener(e){this.connListeners.push(e)}removeConnectionListener(e){let t=this.connListeners.indexOf(e);return t>=0&&(this.connListeners.splice(t,1),!0)}close(){this.sock&&(this.sock.readyState==o?this.pendingOnOpen.push((()=>{this.sock.send('{"alive": false}\n'),this.sock.removeAllListeners("connect"),this.sock.removeAllListeners("error"),this.sock.removeAllListeners("close"),this.sock.destroy()})):this.sock.readyState==i&&(this.sock.send('{"alive": false}\n'),this.sock.removeAllListeners("connect"),this.sock.removeAllListeners("error"),this.sock.removeAllListeners("close"),this.sock.destroy()))}}class c{constructor(e={}){let t=e.hostname||"localhost",r=e.port||80;this.url=new URL("ws://localhost"),this.url.hostname=t,this.url.port=r.toString(),this.url.pathname=e.pathname||"/",this._keepAlive=e.keepAlive,this._reconnectTime=e.reconnectTime||5e3,this.debug=e.debug||!1,this._firstConn=!0,this._firstReConn=!0,this.pendingOnOpen=[],this.connListeners=[],this._websockSetup(this.url)}_sendConnEvent(e){this.connListeners.forEach((t=>{t&&"[object Function]"==={}.toString.call(t)&&t(e)}))}_websockSetup(e){try{this.sock=new WebSocket(e),this.sock.onerror=this._websockReconnect.bind(this),this.sock.onopen=this._onWebsockOpen.bind(this),this.sock.onclose=()=>{this._sendConnEvent(!1)}}catch(t){return void(this.debug&&console.log("Connection failed to ",e))}}_websockReconnect(){!this._firstConn&&this._keepAlive&&this.sock.readyState!=this.sock.CONNECTING&&this.sock.readyState!=this.sock.OPEN&&(this._firstReConn&&this._sendConnEvent(!1),this._firstReConn=!1,this.debug&&console.log("Reconnecting to ",this.sock.url),setTimeout((()=>{this.pendingOnOpen=[],this._websockSetup(this.sock.url)}),this._reconnectTime))}_onWebsockOpen(){this.debug&&console.log("Connected to ",this.sock.url),this._sendConnEvent(!0),this.sock.onclose=this._websockReconnect.bind(this),this.sock.onmessage=e=>{this._onWebsockRx&&this._onWebsockRx.call(this,e.data)},this._firstConn=!1,this._firstReConn=!0,this.pendingOnOpen.forEach((e=>e())),this.pendingOnOpen.length=0}toString(){let e="";return e+=(this.sock,this.sock.url.toString()),e}write(e){return this.sock&&this.sock.readyState!=this.sock.CONNECTING?this.sock.readyState==this.sock.OPEN&&(this.sock.send(e+"\n"),!0):(this.pendingOnOpen.push((()=>{this.sock.send(e+"\n")})),!0)}setReadCallback(e){e&&"[object Function]"==={}.toString.call(e)&&(this._onWebsockRx=e)}addConnectionListener(e){this.connListeners.push(e)}removeConnectionListener(e){let t=this.connListeners.indexOf(e);return t>=0&&(this.connListeners.splice(t,1),!0)}close(){this.sock&&(this.sock.readyState==this.sock.CONNECTING?this.pendingOnOpen.push((()=>{this.sock.send('{"alive": false}\n'),this.sock.onclose=null,this.sock.close()})):this.sock.readyState==this.sock.OPEN&&(this.sock.send('{"alive": false}\n'),this.sock.onclose=null,this.sock.close()))}}const h={REQUEST:"REQUEST",AGREE:"AGREE",REFUSE:"REFUSE",FAILURE:"FAILURE",INFORM:"INFORM",CONFIRM:"CONFIRM",DISCONFIRM:"DISCONFIRM",QUERY_IF:"QUERY_IF",NOT_UNDERSTOOD:"NOT_UNDERSTOOD",CFP:"CFP",PROPOSE:"PROPOSE",CANCEL:"CANCEL"};class u{constructor(e,t=!1,r){this.name=e,this.topic=t,this.owner=r}getName(){return this.name}isTopic(){return this.topic}send(e){if(e.recipient=this.toJSON(),!this.owner)throw new Error("Unowned AgentID cannot send messages");this.owner.send(e)}async request(e,t=1e3){if(e.recipient=this.toJSON(),this.owner)return this.owner.request(e,t);throw new Error("Unowned AgentID cannot send messages")}toString(){return this.toJSON()+(this.owner&&this.owner.connector?` on ${this.owner.connector.url}`:"")}toJSON(){return(this.topic?"#":"")+this.name}async set(e,t,r=-1,s=5e3){if(!e)return null;let n=new y;n.recipient=this.name,Array.isArray(e)?(n.param=e.shift(),n.value=t.shift(),n.requests=e.map(((e,r)=>({param:e,value:t[r]}))),e.unshift(n.param)):(n.param=e,n.value=t),n.index=Number.isInteger(r)?r:-1;const i=await this.owner.request(n,s);var o=Array.isArray(e)?new Array(e.length).fill(null):null;if(!i||i.perf!=h.INFORM||!i.param){if(this.owner._returnNullOnFailedResponse)return o;throw new Error(`Unable to set ${this.name}.${e} to ${t}`)}if(Array.isArray(e)){i.values||(i.values={}),i.param&&(i.values[i.param]=i.value);const t=Object.keys(i.values);return e.map((e=>{let r=t.find((t=>t.endsWith(e)));return r?i.values[r]:void 0}))}return i.value}async get(e,t=-1,r=5e3){let s=new y;s.recipient=this.name,e&&(Array.isArray(e)?(s.param=e.shift(),s.requests=e.map((e=>({param:e}))),e.unshift(s.param)):s.param=e),s.index=Number.isInteger(t)?t:-1;const n=await this.owner.request(s,r);var i=Array.isArray(e)?new Array(e.length).fill(null):null;if(!n||n.perf!=h.INFORM||!n.param){if(this.owner._returnNullOnFailedResponse)return i;throw new Error(`Unable to get ${this.name}.${e}`)}if(e){if(Array.isArray(e)){n.values||(n.values={}),n.param&&(n.values[n.param]=n.value);const t=Object.keys(n.values);return e.map((e=>{let r=t.find((t=>t.endsWith(e)));return r?n.values[r]:void 0}))}return n.value}return n.values||(n.values={}),n.param&&(n.values[n.param]=n.value),n.values}}class g{constructor(e={msgID:null,sender:null},t=h.INFORM){this.__clazz__="org.arl.fjage.Message",this.msgID=R(8),this.sender=null,this.recipient=e.sender,this.perf=t,this.inReplyTo=e.msgID||null}toString(){let e="",t="";if(!this.__clazz__)return"";let r=this.__clazz__;r=r.replace(/^.*\./,"");let s=this.perf;for(var n in this)n.startsWith("__")||"sender"!=n&&"recipient"!=n&&"msgID"!=n&&"perf"!=n&&"inReplyTo"!=n&&("object"!=typeof this[n]?e+=" "+n+":"+this[n]:t=" ...");return e+=t,r+":"+s+"["+e.replace(/^ /,"")+"]"}_serialize(){return'{ "clazz": "'+(this.__clazz__||"org.arl.fjage.Message")+'", "data": '+JSON.stringify(this,((e,t)=>{if(!e.startsWith("__"))return t}))+" }"}_inflate(e){for(var t in e)this[t]=e[t]}static _deserialize(e){let t=null;if("string"==typeof e)try{t=JSON.parse(e)}catch(e){return null}else t=e;let r=t.clazz,s=r.replace(/^.*\./,""),n=f[s]?new f[s]:new g;return n.__clazz__=r,n._inflate(t.data),n}}class d{constructor(e={}){for(var t in _)null!=e[t]&&""!==e[t]||(e[t]=_[t]);var r=v;r.hostname=e.hostname,r.port=e.port,r.pathname=e.pathname;let s=this._getGWCache(r);if(s)return s;this._timeout=e.timeout,this._keepAlive=e.keepAlive,this._queueSize=e.queueSize,this._returnNullOnFailedResponse=e.returnNullOnFailedResponse,this.pending={},this.subscriptions={},this.listener={},this.eventListeners={},this.queue=[],this.connected=!1,this.debug=!1,this.aid=new u("gateway-"+R(4)),this.connector=this._createConnector(r),this._addGWCache(this)}_sendEvent(e,t){Array.isArray(this.eventListeners[e])&&this.eventListeners[e].forEach((e=>{if(e&&"[object Function]"==={}.toString.call(e))try{e(t)}catch(e){console.warn("Error in event listener : "+e)}}))}_onMsgRx(e){var t;this.debug&&console.log("< "+e),this._sendEvent("rx",e);try{t=JSON.parse(e,m)}catch(e){return}if(this._sendEvent("rxp",t),"id"in t&&t.id in this.pending)this.pending[t.id](t),delete this.pending[t.id];else if("send"==t.action){let e=g._deserialize(t.message);if(!e)return;if(this._sendEvent("rxmsg",e),e.recipient==this.aid.toJSON()||this.subscriptions[e.recipient]){var r=!1;if(Array.isArray(this.eventListeners.message))for(var s=0;s<this.eventListeners.message.length;s++)try{if(this.eventListeners.message[s](e)){r=!0;break}}catch(e){console.warn("Error in message listener : "+e)}for(var n in this.listener)try{if(this.listener[n](e)){r=!0;break}}catch(e){console.warn("Error in listener : "+e)}r||(this.queue.length>=this._queueSize&&this.queue.shift(),this.queue.push(e))}}else{let e={id:t.id,inResponseTo:t.action};switch(t.action){case"agents":e.agentIDs=[this.aid.getName()];break;case"containsAgent":e.answer=t.agentID==this.aid.getName();break;case"services":e.services=[];break;case"agentForService":e.agentID="";break;case"agentsForService":e.agentIDs=[];break;default:e=void 0}e&&this._msgTx(e)}}_msgTx(e){return"string"==typeof e||e instanceof String||(e=JSON.stringify(e)),this.debug&&console.log("> "+e),this._sendEvent("tx",e),this.connector.write(e)}_msgTxRx(e){return e.id=R(8),new Promise((t=>{let r=setTimeout((()=>{delete this.pending[e.id],this.debug&&console.log("Receive Timeout : "+e),t()}),8*this._timeout);this.pending[e.id]=e=>{clearTimeout(r),t(e)},this._msgTx.call(this,e)||(clearTimeout(r),delete this.pending[e.id],this.debug&&console.log("Transmit Timeout : "+e),t())}))}_createConnector(e){let t;if(e.protocol.startsWith("ws"))t=new c({hostname:e.hostname,port:parseInt(e.port),pathname:e.pathname,keepAlive:this._keepAlive,debug:this.debug});else{if(!e.protocol.startsWith("tcp"))return null;t=new l({hostname:e.hostname,port:parseInt(e.port),keepAlive:this._keepAlive,debug:this.debug})}return t.setReadCallback(this._onMsgRx.bind(this)),t.addConnectionListener((e=>{this.connected=!!e,1==e&&(this.flush(),this.connector.write('{"alive": true}'),this._update_watch()),this._sendEvent("conn",e)})),t}_isConstructor(e){try{return new new Proxy(e,{construct:()=>({})}),!0}catch(e){return!1}}_matchMessage(e,t){if("string"==typeof e||e instanceof String)return"inReplyTo"in t&&t.inReplyTo==e;if(Object.prototype.hasOwnProperty.call(e,"msgID"))return"inReplyTo"in t&&t.inReplyTo==e.msgID;if("Message"==e.__proto__.name||"Message"==e.__proto__.__proto__.name)return e.__clazz__==t.__clazz__;if("function"!=typeof e||this._isConstructor(e))return t instanceof e;try{return e(t)}catch(e){return console.warn("Error in filter : "+e),!1}}_getMessageFromQueue(e){if(!this.queue.length)return;if(!e)return this.queue.shift();let t=this.queue.find((t=>this._matchMessage(e,t)));return t&&this.queue.splice(this.queue.indexOf(t),1),t}_getGWCache(e){if(!S.fjage||!S.fjage.gateways)return null;var t=S.fjage.gateways.filter((t=>t.connector.url.toString()==e.toString()));return t.length?t[0]:null}_addGWCache(e){S.fjage&&S.fjage.gateways&&S.fjage.gateways.push(e)}_removeGWCache(e){if(S.fjage&&S.fjage.gateways){var t=S.fjage.gateways.indexOf(e);null!=t&&S.fjage.gateways.splice(t,1)}}_update_watch(){}addEventListener(e,t){Array.isArray(this.eventListeners[e])||(this.eventListeners[e]=[]),this.eventListeners[e].push(t)}removeEventListener(e,t){if(!this.eventListeners[e])return;let r=this.eventListeners[e].indexOf(t);r>=0&&this.eventListeners[e].splice(r,1)}addMessageListener(e){this.addEventListener("message",e)}removeMessageListener(e){this.removeEventListener("message",e)}addConnListener(e){this.addEventListener("conn",e)}removeConnListener(e){this.removeEventListener("conn",e)}getAgentID(){return this.aid}agent(e){return new u(e,!1,this)}topic(e,t){return"string"==typeof e||e instanceof String?new u(e,!0,this):e instanceof u?e.isTopic()?e:new u(e.getName()+(t?"__"+t:"")+"__ntf",!0,this):void 0}subscribe(e){return e.isTopic()||(e=new u(e.getName()+"__ntf",!0,this)),this.subscriptions[e.toJSON()]=!0,this._update_watch(),!0}unsubscribe(e){e.isTopic()||(e=new u(e.getName()+"__ntf",!0,this)),delete this.subscriptions[e.toJSON()],this._update_watch()}async agents(){let e=await this._msgTxRx({action:"agents"});if(!e||!Array.isArray(e.agentIDs))throw new Error("Unable to get agents");return e.agentIDs.map((e=>new u(e,!1,this)))}async containsAgent(e){let t={action:"containsAgent",agentID:e instanceof u?e.getName():e},r=await this._msgTxRx(t);if(!r)throw new Error("Unable to check if agent exists");return!!r.answer}async agentForService(e){let t={action:"agentForService",service:e},r=await this._msgTxRx(t);if(!r){if(this._returnNullOnFailedResponse)return null;throw new Error("Unable to get agent for service")}return r.agentID?new u(r.agentID,!1,this):null}async agentsForService(e){let t={action:"agentsForService",service:e},r=await this._msgTxRx(t),s=[];if(!r){if(this._returnNullOnFailedResponse)return s;throw new Error("Unable to get agents for service")}if(!Array.isArray(r.agentIDs))return s;for(var n=0;n<r.agentIDs.length;n++)s.push(new u(r.agentIDs[n],!1,this));return s}send(e){e.sender=this.aid.toJSON(),""==e.perf&&(e.__clazz__.endsWith("Req")?e.perf=h.REQUEST:e.perf=h.INFORM),this._sendEvent("txmsg",e);let t=JSON.stringify({action:"send",relay:!0,message:"###MSG###"});return t=t.replace('"###MSG###"',e._serialize()),!!this._msgTx(t)}flush(){this.queue.length=0}async request(e,t=1e3){return this.send(e),this.receive(e,t)}async receive(e,t=0){return new Promise((r=>{let s=this._getMessageFromQueue.call(this,e);if(s)return void r(s);if(0==t)return this.debug&&console.log("Receive Timeout : "+e),void r();let n,i=R(8);t>0&&(n=setTimeout((()=>{this.listener[i]&&delete this.listener[i],this.debug&&console.log("Receive Timeout : "+e),r()}),t)),this.listener[i]=t=>!!this._matchMessage(e,t)&&(n&&clearTimeout(n),this.listener[i]&&delete this.listener[i],r(t),!0)}))}close(){this.connector.close(),this._removeGWCache(this)}}const p={SHELL:"org.arl.fjage.shell.Services.SHELL"};function f(e,t=g){let r=e.replace(/^.*\./,"");if(f[r])return f[r];let s=class extends t{constructor(t){if(super(),this.__clazz__=e,t){const e=Object.keys(t);for(let r of e)this[r]=t[r]}e.endsWith("Req")&&(this.perf=h.REQUEST)}};return s.__clazz__=e,f[r]=s,s}function R(e){function t(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}let r=t();for(var s=0;s<e-1;s++)r+=t();return r}function m(e,t){if(null===t)return null;if("object"==typeof t&&"clazz"in t){let e=t.clazz;if(e.startsWith("[")&&2==e.length&&"data"in t){let e=function(e,t,r=!0){let s=S.atob(e),n=s.length,i=new Uint8Array(n);for(var o=0;o<n;o++)i[o]=s.charCodeAt(o);let a=[],l=new DataView(i.buffer);switch(t){case"[B":for(o=0;o<n;o++)a.push(l.getUint8(o));break;case"[S":for(o=0;o<n;o+=2)a.push(l.getInt16(o,r));break;case"[I":for(o=0;o<n;o+=4)a.push(l.getInt32(o,r));break;case"[J":for(o=0;o<n;o+=8)a.push(l.getBigInt64(o,r));break;case"[F":for(o=0;o<n;o+=4)a.push(l.getFloat32(o,r));break;case"[D":for(o=0;o<n;o+=8)a.push(l.getFloat64(o,r));break;default:return}return a}(t.data,t.clazz);e&&(t=e)}}return t}const _={};let v,S={};t||s?(S=window,Object.assign(_,{hostname:S.location.hostname,port:S.location.port,pathname:"/ws/",timeout:1e3,keepAlive:!0,queueSize:128,returnNullOnFailedResponse:!0}),v=new URL("ws://localhost"),void 0===S.fjage&&(S.fjage={}),void 0===S.fjage.gateways&&(S.fjage.gateways=[])):(n||r)&&(S=global,Object.assign(_,{hostname:"localhost",port:"1100",pathname:"",timeout:1e3,keepAlive:!0,queueSize:128,returnNullOnFailedResponse:!0}),v=new URL("tcp://localhost"),S.atob=e=>Buffer.from(e,"base64").toString("binary"));const y=f("org.arl.fjage.param.ParameterReq"),w=f("org.arl.unet.DatagramReq"),A=f("org.arl.unet.DatagramNtf"),N=f("org.arl.unet.phy.TxFrameReq",w),k=f("org.arl.unet.phy.RxFrameNtf",A),b=f("org.arl.unet.bb.BasebandSignal");Object.assign(p,{NODE_INFO:"org.arl.unet.Services.NODE_INFO",ADDRESS_RESOLUTION:"org.arl.unet.Services.ADDRESS_RESOLUTION",DATAGRAM:"org.arl.unet.Services.DATAGRAM",PHYSICAL:"org.arl.unet.Services.PHYSICAL",RANGING:"org.arl.unet.Services.RANGING",BASEBAND:"org.arl.unet.Services.BASEBAND",LINK:"org.arl.unet.Services.LINK",MAC:"org.arl.unet.Services.MAC",ROUTING:"org.arl.unet.Services.ROUTING",ROUTE_MAINTENANCE:"org.arl.unet.Services.ROUTE_MAINTENANCE",TRANSPORT:"org.arl.unet.Services.TRANSPORT",REMOTE:"org.arl.unet.Services.REMOTE",STATE_MANAGER:"org.arl.unet.Services.STATE_MANAGER",DEVICE_INFO:"org.arl.unet.Services.DEVICE_INFO",DOA:"org.arl.unet.Services.DOA",SCHEDULER:"org.arl.unet.Services.SCHEDULER"});let O={DATA:0,RANGING:1,LINK:2,REMOTE:3,MAC:4,ROUTING:5,TRANSPORT:6,ROUTE_MAINTENANCE:7,LINK2:8,USER:32,MAX:63},E={TestReportNtf:f("org.arl.unet.TestReportNtf"),AbnormalTerminationNtf:f("org.arl.unet.AbnormalTerminationNtf"),CapabilityListRsp:f("org.arl.unet.CapabilityListRsp"),CapabilityReq:f("org.arl.unet.CapabilityReq"),ClearReq:f("org.arl.unet.ClearReq"),DatagramCancelReq:f("org.arl.unet.DatagramCancelReq"),DatagramDeliveryNtf:f("org.arl.unet.DatagramDeliveryNtf"),DatagramFailureNtf:f("org.arl.unet.DatagramFailureNtf"),DatagramNtf:f("org.arl.unet.DatagramNtf"),DatagramProgressNtf:f("org.arl.unet.DatagramProgressNtf"),DatagramReq:f("org.arl.unet.DatagramReq"),ParamChangeNtf:f("org.arl.unet.ParamChangeNtf"),RefuseRsp:f("org.arl.unet.RefuseRsp"),FailureNtf:f("org.arl.unet.FailureNtf"),DatagramTraceReq:f("org.arl.unet.net.DatagramTraceReq"),RouteDiscoveryReq:f("org.arl.unet.net.RouteDiscoveryReq"),RouteTraceReq:f("org.arl.unet.net.RouteTraceReq"),RouteDiscoveryNtf:f("org.arl.unet.net.RouteDiscoveryNtf"),RouteTraceNtf:f("org.arl.unet.net.RouteTraceNtf"),FecDecodeReq:f("org.arl.unet.phy.FecDecodeReq"),RxSWiG1FrameNtf:f("org.arl.unet.phy.RxSWiG1FrameNtf",k),TxSWiG1FrameReq:f("org.arl.unet.phy.TxSWiG1FrameReq",N),RxJanusFrameNtf:f("org.arl.unet.phy.RxJanusFrameNtf",k),TxJanusFrameReq:f("org.arl.unet.phy.TxJanusFrameReq",N),BadFrameNtf:f("org.arl.unet.phy.BadFrameNtf"),BadRangeNtf:f("org.arl.unet.phy.BadRangeNtf"),ClearSyncReq:f("org.arl.unet.phy.ClearSyncReq"),CollisionNtf:f("org.arl.unet.phy.CollisionNtf"),RxFrameNtf:f("org.arl.unet.phy.RxFrameNtf",A),RxFrameStartNtf:f("org.arl.unet.phy.RxFrameStartNtf"),SyncInfoReq:f("org.arl.unet.phy.SyncInfoReq"),SyncInfoRsp:f("org.arl.unet.phy.SyncInfoRsp"),TxFrameNtf:f("org.arl.unet.phy.TxFrameNtf"),TxFrameReq:f("org.arl.unet.phy.TxFrameReq",w),TxFrameStartNtf:f("org.arl.unet.phy.TxFrameStartNtf"),TxRawFrameReq:f("org.arl.unet.phy.TxRawFrameReq"),AddressAllocReq:f("org.arl.unet.addr.AddressAllocReq"),AddressAllocRsp:f("org.arl.unet.addr.AddressAllocRsp"),AddressResolutionReq:f("org.arl.unet.addr.AddressResolutionReq"),AddressResolutionRsp:f("org.arl.unet.addr.AddressResolutionRsp"),BasebandSignal:f("org.arl.unet.bb.BasebandSignal"),RecordBasebandSignalReq:f("org.arl.unet.bb.RecordBasebandSignalReq"),RxBasebandSignalNtf:f("org.arl.unet.bb.RxBasebandSignalNtf",b),TxBasebandSignalReq:f("org.arl.unet.bb.TxBasebandSignalReq",b),LinkStatusNtf:f("org.arl.unet.link.LinkStatusNtf"),RangeNtf:f("org.arl.unet.localization.RangeNtf"),RangeReq:f("org.arl.unet.localization.RangeReq"),BeaconReq:f("org.arl.unet.localization.BeaconReq"),RespondReq:f("org.arl.unet.localization.RespondReq"),InterrogationNtf:f("org.arl.unet.localization.InterrogationNtf"),ReservationAcceptReq:f("org.arl.unet.mac.ReservationAcceptReq"),ReservationCancelReq:f("org.arl.unet.mac.ReservationCancelReq"),ReservationReq:f("org.arl.unet.mac.ReservationReq"),ReservationRsp:f("org.arl.unet.mac.ReservationRsp"),ReservationStatusNtf:f("org.arl.unet.mac.ReservationStatusNtf"),RxAckNtf:f("org.arl.unet.mac.RxAckNtf"),TxAckReq:f("org.arl.unet.mac.TxAckReq"),RemoteExecReq:f("org.arl.unet.remote.RemoteExecReq"),RemoteFailureNtf:f("org.arl.unet.remote.RemoteFailureNtf"),RemoteFileGetReq:f("org.arl.unet.remote.RemoteFileGetReq"),RemoteFileNtf:f("org.arl.unet.remote.RemoteFileNtf"),RemoteFilePutReq:f("org.arl.unet.remote.RemoteFilePutReq"),RemoteSuccessNtf:f("org.arl.unet.remote.RemoteSuccessNtf"),RemoteTextNtf:f("org.arl.unet.remote.RemoteTextNtf"),RemoteTextReq:f("org.arl.unet.remote.RemoteTextReq"),AddScheduledSleepReq:f("org.arl.unet.scheduler.AddScheduledSleepReq"),GetSleepScheduleReq:f("org.arl.unet.scheduler.GetSleepScheduleReq"),RemoveScheduledSleepReq:f("org.arl.unet.scheduler.RemoveScheduledSleepReq"),SleepScheduleRsp:f("org.arl.unet.scheduler.SleepScheduleRsp"),WakeFromSleepNtf:f("org.arl.unet.scheduler.WakeFromSleepNtf"),ClearStateReq:f("org.arl.unet.state.ClearStateReq"),SaveStateReq:f("org.arl.unet.state.SaveStateReq")};function T(e){let t=e*Math.PI/180,r=111132.92-559.82*Math.cos(2*t)+1.175*Math.cos(4*t)-.0023*Math.cos(6*t);return[111412.84*Math.cos(t)-93.5*Math.cos(3*t)+.118*Math.cos(5*t),r]}class C extends u{constructor(e,t,r,s=!0){e instanceof u?super(e.getName(),e.topic,e.owner):super(e,t,r),this.greedy=s,this.cache={},this.specialParams=["name","version"]}async set(e,t,r=-1,s=5e3){let n=await super.set(e,t,r,s);return this._updateCache(e,n,r),n}async get(e,t=-1,r=5e3,s=5e3){if(this._isCached(e,t,s))return this._getCache(e,t);if(!this.greedy||Array.isArray(e)&&0!=[...new Set([...e,...this.specialParams])].length||this.specialParams.includes(e)){let s=await super.get(e,t,r);return this._updateCache(e,s,t),s}{let s=await super.get(null,t,r);if(this._updateCache(null,s,t),!s)return Array.isArray(e)?new Array(e.length).fill(null):null;if(e){if(Array.isArray(e))return e.map((e=>{let t=Object.keys(s).find((t=>this._toNamed(t)===e));return t?s[t]:null}));{let t=Object.keys(s).find((t=>this._toNamed(t)===e));return t?s[t]:null}}return s}}_updateCache(e,t,r){if(null==t||Array.isArray(t)&&t.every((e=>null==e)))return;null==e?(e=Object.keys(t),t=Object.values(t)):Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]),e=e.map(this._toNamed),void 0===this.cache[r.toString()]&&(this.cache[r.toString()]={});let s=this.cache[r.toString()];for(let r=0;r<e.length;r++)void 0===s[e[r]]&&(s[e[r]]={}),s[e[r]].value=t[r],s[e[r]].ctime=Date.now()}_isCached(e,t,r){if(r<=0)return!1;if(null==e)return!1;let s=this.cache[t.toString()];if(!s)return!1;Array.isArray(e)||(e=[e]);return e.every((e=>(e=this._toNamed(e))in s&&Date.now()-s[e].ctime<=r))}_getCache(e,t){let r=this.cache[t.toString()];return r?Array.isArray(e)?e.map((e=>e in r?r[e].value:null)):e in r?r[e].value:null:null}_toNamed(e){const t=e.lastIndexOf(".");return t<0?e:e.slice(t+1)}}const F=E.AddressResolutionReq,q=E.DatagramReq,D=E.DatagramNtf,I=E.RxFrameNtf;e.AgentID=u,e.CachingAgentID=C,e.CachingGateway=class extends d{agent(e,t=!0,r=!0){const s=super.agent(e);return t?new C(s,null,null,r):s}topic(e,t,r=!0,s=!0){const n=super.topic(e,t);return r?new C(n,null,null,s):n}async agentForService(e,t=!0,r=!0){const s=await super.agentForService(e);return s&&t?new C(s,null,null,r):s}async agentsForService(e,t=!0,r=!0){const s=await super.agentsForService(e);return t?s.map((e=>new C(e,null,null,r))):s}},e.Gateway=d,e.Message=g,e.MessageClass=f,e.Performative=h,e.Protocol=O,e.Services=p,e.UnetMessages=E,e.UnetSocket=class{constructor(e,t,r=""){return(async()=>{this.gw=new d({hostname:e,port:t,path:r}),this.localProtocol=-1,this.remoteAddress=-1,this.remoteProtocol=O.DATA,this.timeout=0,this.provider=null;return(await this.gw.agentsForService(p.DATAGRAM)).forEach((e=>{this.gw.subscribe(this.gw.topic(e))})),this})()}close(){this.gw.close(),this.gw=null}isClosed(){return null==this.gw}bind(e){return(e==O.DATA||e>=O.USER&&e<=O.MAX)&&(this.localProtocol=e,!0)}unbind(){this.localProtocol=-1}isBound(){return this.localProtocol>=0}connect(e,t){return e>=0&&(t==O.DATA||t>=O.USER&&t<=O.MAX)&&(this.remoteAddress=e,this.remoteProtocol=t,!0)}disconnect(){this.remoteAddress=-1,this.remoteProtocol=0}isConnected(){return this.remoteAddress>=0}async getLocalAddress(){if(null==this.gw)return-1;const e=await this.gw.agentForService(p.NODE_INFO);if(null==e)return-1;const t=await e.get("address");return null!=t?t:-1}getLocalProtocol(){return this.localProtocol}getRemoteAddress(){return this.remoteAddress}getRemoteProtocol(){return this.remoteProtocol}setTimeout(e){e<0&&(e=0),this.timeout=e}getTimeout(){return this.timeout}async send(e,t=this.remoteAddress,r=this.remoteProtocol){if(t<0||null==this.gw)return!1;var s;if(Array.isArray(e))(s=new q).data=e,s.to=t,s.protocol=r;else{if(!(e instanceof q))return!1;s=e}let n=s.protocol;if(n!=O.DATA&&(n<O.USER||n>O.MAX))return!1;if(null==s.recipient){if(null==this.provider&&(this.provider=await this.gw.agentForService(p.TRANSPORT)),null==this.provider&&(this.provider=await this.gw.agentForService(p.ROUTING)),null==this.provider&&(this.provider=await this.gw.agentForService(p.LINK)),null==this.provider&&(this.provider=await this.gw.agentForService(p.PHYSICAL)),null==this.provider&&(this.provider=await this.gw.agentForService(p.DATAGRAM)),null==this.provider)return!1;s.recipient=this.provider}const i=await this.gw.request(s,1e3);return null!=i&&i.perf==h.AGREE}async receive(){return null==this.gw?null:await this.gw.receive((e=>{if(e.__clazz__!=D.__clazz__&&e.__clazz__!=I.__clazz__)return!1;let t=e.protocol;return(t==O.DATA||t>=O.USER)&&(this.localProtocol<0||this.localProtocol==t)}),this.timeout)}getGateway(){return this.gw}async agentForService(e,t=!0){return null==this.gw?null:await this.gw.agentForService(e,t)}async agentsForService(e,t=!0){return null==this.gw?null:await this.gw.agentsForService(e,t``)}agent(e,t=!0){return null==this.gw?null:this.gw.agent(e,t)}async host(e){const t=await this.agentForService(p.ADDRESS_RESOLUTION);if(null==t)return null;const r=new F(e);r.name=e,r.recipient=t;const s=await this.gw.request(r,1e3);return null!=s&&Object.prototype.hasOwnProperty.call(s,"address")?s.address:null}},e.toGps=function(e,t,r){let s=[],[n,i]=T(e[0]);return s[1]=t/n+e[1],s[0]=r/i+e[0],s},e.toLocal=function(e,t,r){let s=[],[n,i]=T(e[0]);return s[0]=(r-e[1])*n,s[1]=(t-e[0])*i,s}}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).unet={})}(this,(function(e){"use strict";const t="undefined"!=typeof window&&void 0!==window.document,r="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,s="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,n="undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"));"undefined"!=typeof Deno&&Deno.core;const i="open",o="opening";var a;class l{constructor(e={}){let t=e.hostname||"localhost",r=e.port||1100;this._keepAlive=e.keepAlive,this._reconnectTime=e.reconnectTime||5e3,this.url=new URL("tcp://localhost"),this.url.hostname=t,this.url.port=r.toString(),this._buf="",this._firstConn=!0,this._firstReConn=!0,this.pendingOnOpen=[],this.connListeners=[],this.debug=!1,this._sockInit(t,r)}_sendConnEvent(e){this.connListeners.forEach((t=>{t&&"[object Function]"==={}.toString.call(t)&&t(e)}))}_sockInit(e,t){if(a)this._sockSetup(e,t);else try{import("net").then((r=>{a=r.createConnection,this._sockSetup(e,t)}))}catch(e){this.debug&&console.log("Unable to import net module")}}_sockSetup(e,t){if(a)try{this.sock=a({host:e,port:t}),this.sock.setEncoding("utf8"),this.sock.on("connect",this._onSockOpen.bind(this)),this.sock.on("error",this._sockReconnect.bind(this)),this.sock.on("close",(()=>{this._sendConnEvent(!1)})),this.sock.send=e=>{this.sock.write(e)}}catch(e){return void(this.debug&&console.log("Connection failed to ",this.sock.host+":"+this.sock.port))}}_sockReconnect(){!this._firstConn&&this._keepAlive&&this.sock.readyState!=o&&this.sock.readyState!=i&&(this._firstReConn&&this._sendConnEvent(!1),this._firstReConn=!1,setTimeout((()=>{this.pendingOnOpen=[],this._sockSetup(this.url.hostname,this.url.port)}),this._reconnectTime))}_onSockOpen(){this._sendConnEvent(!0),this._firstConn=!1,this.sock.on("close",this._sockReconnect.bind(this)),this.sock.on("data",this._processSockData.bind(this)),this.pendingOnOpen.forEach((e=>e())),this.pendingOnOpen.length=0,this._buf=""}_processSockData(e){this._buf+=e;var t=this._buf.split("\n");t.forEach(((e,r)=>{r<t.length-1?e&&this._onSockRx&&this._onSockRx.call(this,e):this._buf=e}))}toString(){let e="";return e+=(this.sock,this.sock.remoteAddress.toString()+":"+this.sock.remotePort.toString()),e}write(e){return this.sock&&this.sock.readyState!=o?this.sock.readyState==i&&(this.sock.send(e+"\n"),!0):(this.pendingOnOpen.push((()=>{this.sock.send(e+"\n")})),!0)}setReadCallback(e){e&&"[object Function]"==={}.toString.call(e)&&(this._onSockRx=e)}addConnectionListener(e){this.connListeners.push(e)}removeConnectionListener(e){let t=this.connListeners.indexOf(e);return t>=0&&(this.connListeners.splice(t,1),!0)}close(){this.sock&&(this.sock.readyState==o?this.pendingOnOpen.push((()=>{this.sock.send('{"alive": false}\n'),this.sock.removeAllListeners("connect"),this.sock.removeAllListeners("error"),this.sock.removeAllListeners("close"),this.sock.destroy()})):this.sock.readyState==i&&(this.sock.send('{"alive": false}\n'),this.sock.removeAllListeners("connect"),this.sock.removeAllListeners("error"),this.sock.removeAllListeners("close"),this.sock.destroy()))}}class c{constructor(e={}){let t=e.hostname||"localhost",r=e.port||80;this.url=new URL("ws://localhost"),this.url.hostname=t,this.url.port=r.toString(),this.url.pathname=e.pathname||"/",this._keepAlive=e.keepAlive,this._reconnectTime=e.reconnectTime||5e3,this.debug=e.debug||!1,this._firstConn=!0,this._firstReConn=!0,this.pendingOnOpen=[],this.connListeners=[],this._websockSetup(this.url)}_sendConnEvent(e){this.connListeners.forEach((t=>{t&&"[object Function]"==={}.toString.call(t)&&t(e)}))}_websockSetup(e){try{this.sock=new WebSocket(e),this.sock.onerror=this._websockReconnect.bind(this),this.sock.onopen=this._onWebsockOpen.bind(this),this.sock.onclose=()=>{this._sendConnEvent(!1)}}catch(t){return void(this.debug&&console.log("Connection failed to ",e))}}_websockReconnect(){!this._firstConn&&this._keepAlive&&this.sock.readyState!=this.sock.CONNECTING&&this.sock.readyState!=this.sock.OPEN&&(this._firstReConn&&this._sendConnEvent(!1),this._firstReConn=!1,this.debug&&console.log("Reconnecting to ",this.sock.url),setTimeout((()=>{this.pendingOnOpen=[],this._websockSetup(this.sock.url)}),this._reconnectTime))}_onWebsockOpen(){this.debug&&console.log("Connected to ",this.sock.url),this._sendConnEvent(!0),this.sock.onclose=this._websockReconnect.bind(this),this.sock.onmessage=e=>{this._onWebsockRx&&this._onWebsockRx.call(this,e.data)},this._firstConn=!1,this._firstReConn=!0,this.pendingOnOpen.forEach((e=>e())),this.pendingOnOpen.length=0}toString(){let e="";return e+=(this.sock,this.sock.url.toString()),e}write(e){return this.sock&&this.sock.readyState!=this.sock.CONNECTING?this.sock.readyState==this.sock.OPEN&&(this.sock.send(e+"\n"),!0):(this.pendingOnOpen.push((()=>{this.sock.send(e+"\n")})),!0)}setReadCallback(e){e&&"[object Function]"==={}.toString.call(e)&&(this._onWebsockRx=e)}addConnectionListener(e){this.connListeners.push(e)}removeConnectionListener(e){let t=this.connListeners.indexOf(e);return t>=0&&(this.connListeners.splice(t,1),!0)}close(){this.sock&&(this.sock.readyState==this.sock.CONNECTING?this.pendingOnOpen.push((()=>{this.sock.send('{"alive": false}\n'),this.sock.onclose=null,this.sock.close()})):this.sock.readyState==this.sock.OPEN&&(this.sock.send('{"alive": false}\n'),this.sock.onclose=null,this.sock.close()))}}const h={REQUEST:"REQUEST",AGREE:"AGREE",REFUSE:"REFUSE",FAILURE:"FAILURE",INFORM:"INFORM",CONFIRM:"CONFIRM",DISCONFIRM:"DISCONFIRM",QUERY_IF:"QUERY_IF",NOT_UNDERSTOOD:"NOT_UNDERSTOOD",CFP:"CFP",PROPOSE:"PROPOSE",CANCEL:"CANCEL"};class u{constructor(e,t=!1,r){this.name=e,this.topic=t,this.owner=r}getName(){return this.name}isTopic(){return this.topic}send(e){if(e.recipient=this.toJSON(),!this.owner)throw new Error("Unowned AgentID cannot send messages");this.owner.send(e)}async request(e,t=1e3){if(e.recipient=this.toJSON(),this.owner)return this.owner.request(e,t);throw new Error("Unowned AgentID cannot send messages")}toString(){return this.toJSON()+(this.owner&&this.owner.connector?` on ${this.owner.connector.url}`:"")}toJSON(){return(this.topic?"#":"")+this.name}async set(e,t,r=-1,s=5e3){if(!e)return null;let n=new y;n.recipient=this.name,Array.isArray(e)?(n.param=e.shift(),n.value=t.shift(),n.requests=e.map(((e,r)=>({param:e,value:t[r]}))),e.unshift(n.param)):(n.param=e,n.value=t),n.index=Number.isInteger(r)?r:-1;const i=await this.owner.request(n,s);var o=Array.isArray(e)?new Array(e.length).fill(null):null;if(!i||i.perf!=h.INFORM||!i.param){if(this.owner._returnNullOnFailedResponse)return o;throw new Error(`Unable to set ${this.name}.${e} to ${t}`)}if(Array.isArray(e)){i.values||(i.values={}),i.param&&(i.values[i.param]=i.value);const t=Object.keys(i.values);return e.map((e=>{e.includes(".")&&(e=e.split(".").pop());let r=t.find((t=>(t.includes(".")?t.split(".").pop():t)==e));return r?i.values[r]:void 0}))}return i.value}async get(e,t=-1,r=5e3){let s=new y;s.recipient=this.name,e&&(Array.isArray(e)?(s.param=e.shift(),s.requests=e.map((e=>({param:e}))),e.unshift(s.param)):s.param=e),s.index=Number.isInteger(t)?t:-1;const n=await this.owner.request(s,r);var i=Array.isArray(e)?new Array(e.length).fill(null):null;if(!n||n.perf!=h.INFORM||!n.param){if(this.owner._returnNullOnFailedResponse)return i;throw new Error(`Unable to get ${this.name}.${e}`)}if(e){if(Array.isArray(e)){n.values||(n.values={}),n.param&&(n.values[n.param]=n.value);const t=Object.keys(n.values);return e.map((e=>{let r=t.find((t=>t.endsWith(e)));return r?n.values[r]:void 0}))}return n.value}return n.values||(n.values={}),n.param&&(n.values[n.param]=n.value),n.values}}class g{constructor(e={msgID:null,sender:null},t=h.INFORM){this.__clazz__="org.arl.fjage.Message",this.msgID=R(8),this.sender=null,this.recipient=e.sender,this.perf=t,this.inReplyTo=e.msgID||null}toString(){let e="",t="";if(!this.__clazz__)return"";let r=this.__clazz__;r=r.replace(/^.*\./,"");let s=this.perf;for(var n in this)n.startsWith("__")||"sender"!=n&&"recipient"!=n&&"msgID"!=n&&"perf"!=n&&"inReplyTo"!=n&&("object"!=typeof this[n]?e+=" "+n+":"+this[n]:t=" ...");return e+=t,r+":"+s+"["+e.replace(/^ /,"")+"]"}_serialize(){return'{ "clazz": "'+(this.__clazz__||"org.arl.fjage.Message")+'", "data": '+JSON.stringify(this,((e,t)=>{if(!e.startsWith("__"))return t}))+" }"}_inflate(e){for(var t in e)this[t]=e[t]}static _deserialize(e){let t=null;if("string"==typeof e)try{t=JSON.parse(e)}catch(e){return null}else t=e;let r=t.clazz,s=r.replace(/^.*\./,""),n=f[s]?new f[s]:new g;return n.__clazz__=r,n._inflate(t.data),n}}class d{constructor(e={}){for(var t in _)null!=e[t]&&""!==e[t]||(e[t]=_[t]);var r=v;r.hostname=e.hostname,r.port=e.port,r.pathname=e.pathname;let s=this._getGWCache(r);if(s)return s;this._timeout=e.timeout,this._keepAlive=e.keepAlive,this._queueSize=e.queueSize,this._returnNullOnFailedResponse=e.returnNullOnFailedResponse,this.pending={},this.subscriptions={},this.listener={},this.eventListeners={},this.queue=[],this.connected=!1,this.debug=!1,this.aid=new u("gateway-"+R(4)),this.connector=this._createConnector(r),this._addGWCache(this)}_sendEvent(e,t){Array.isArray(this.eventListeners[e])&&this.eventListeners[e].forEach((e=>{if(e&&"[object Function]"==={}.toString.call(e))try{e(t)}catch(e){console.warn("Error in event listener : "+e)}}))}_onMsgRx(e){var t;this.debug&&console.log("< "+e),this._sendEvent("rx",e);try{t=JSON.parse(e,m)}catch(e){return}if(this._sendEvent("rxp",t),"id"in t&&t.id in this.pending)this.pending[t.id](t),delete this.pending[t.id];else if("send"==t.action){let e=g._deserialize(t.message);if(!e)return;if(this._sendEvent("rxmsg",e),e.recipient==this.aid.toJSON()||this.subscriptions[e.recipient]){var r=!1;if(Array.isArray(this.eventListeners.message))for(var s=0;s<this.eventListeners.message.length;s++)try{if(this.eventListeners.message[s](e)){r=!0;break}}catch(e){console.warn("Error in message listener : "+e)}for(var n in this.listener)try{if(this.listener[n](e)){r=!0;break}}catch(e){console.warn("Error in listener : "+e)}r||(this.queue.length>=this._queueSize&&this.queue.shift(),this.queue.push(e))}}else{let e={id:t.id,inResponseTo:t.action};switch(t.action){case"agents":e.agentIDs=[this.aid.getName()];break;case"containsAgent":e.answer=t.agentID==this.aid.getName();break;case"services":e.services=[];break;case"agentForService":e.agentID="";break;case"agentsForService":e.agentIDs=[];break;default:e=void 0}e&&this._msgTx(e)}}_msgTx(e){return"string"==typeof e||e instanceof String||(e=JSON.stringify(e)),this.debug&&console.log("> "+e),this._sendEvent("tx",e),this.connector.write(e)}_msgTxRx(e){return e.id=R(8),new Promise((t=>{let r=setTimeout((()=>{delete this.pending[e.id],this.debug&&console.log("Receive Timeout : "+e),t()}),8*this._timeout);this.pending[e.id]=e=>{clearTimeout(r),t(e)},this._msgTx.call(this,e)||(clearTimeout(r),delete this.pending[e.id],this.debug&&console.log("Transmit Timeout : "+e),t())}))}_createConnector(e){let t;if(e.protocol.startsWith("ws"))t=new c({hostname:e.hostname,port:parseInt(e.port),pathname:e.pathname,keepAlive:this._keepAlive,debug:this.debug});else{if(!e.protocol.startsWith("tcp"))return null;t=new l({hostname:e.hostname,port:parseInt(e.port),keepAlive:this._keepAlive,debug:this.debug})}return t.setReadCallback(this._onMsgRx.bind(this)),t.addConnectionListener((e=>{this.connected=!!e,1==e&&(this.flush(),this.connector.write('{"alive": true}'),this._update_watch()),this._sendEvent("conn",e)})),t}_isConstructor(e){try{return new new Proxy(e,{construct:()=>({})}),!0}catch(e){return!1}}_matchMessage(e,t){if("string"==typeof e||e instanceof String)return"inReplyTo"in t&&t.inReplyTo==e;if(Object.prototype.hasOwnProperty.call(e,"msgID"))return"inReplyTo"in t&&t.inReplyTo==e.msgID;if("Message"==e.__proto__.name||"Message"==e.__proto__.__proto__.name)return e.__clazz__==t.__clazz__;if("function"!=typeof e||this._isConstructor(e))return t instanceof e;try{return e(t)}catch(e){return console.warn("Error in filter : "+e),!1}}_getMessageFromQueue(e){if(!this.queue.length)return;if(!e)return this.queue.shift();let t=this.queue.find((t=>this._matchMessage(e,t)));return t&&this.queue.splice(this.queue.indexOf(t),1),t}_getGWCache(e){if(!S.fjage||!S.fjage.gateways)return null;var t=S.fjage.gateways.filter((t=>t.connector.url.toString()==e.toString()));return t.length?t[0]:null}_addGWCache(e){S.fjage&&S.fjage.gateways&&S.fjage.gateways.push(e)}_removeGWCache(e){if(S.fjage&&S.fjage.gateways){var t=S.fjage.gateways.indexOf(e);null!=t&&S.fjage.gateways.splice(t,1)}}_update_watch(){}addEventListener(e,t){Array.isArray(this.eventListeners[e])||(this.eventListeners[e]=[]),this.eventListeners[e].push(t)}removeEventListener(e,t){if(!this.eventListeners[e])return;let r=this.eventListeners[e].indexOf(t);r>=0&&this.eventListeners[e].splice(r,1)}addMessageListener(e){this.addEventListener("message",e)}removeMessageListener(e){this.removeEventListener("message",e)}addConnListener(e){this.addEventListener("conn",e)}removeConnListener(e){this.removeEventListener("conn",e)}getAgentID(){return this.aid}agent(e){return new u(e,!1,this)}topic(e,t){return"string"==typeof e||e instanceof String?new u(e,!0,this):e instanceof u?e.isTopic()?e:new u(e.getName()+(t?"__"+t:"")+"__ntf",!0,this):void 0}subscribe(e){return e.isTopic()||(e=new u(e.getName()+"__ntf",!0,this)),this.subscriptions[e.toJSON()]=!0,this._update_watch(),!0}unsubscribe(e){e.isTopic()||(e=new u(e.getName()+"__ntf",!0,this)),delete this.subscriptions[e.toJSON()],this._update_watch()}async agents(){let e=await this._msgTxRx({action:"agents"});if(!e||!Array.isArray(e.agentIDs))throw new Error("Unable to get agents");return e.agentIDs.map((e=>new u(e,!1,this)))}async containsAgent(e){let t={action:"containsAgent",agentID:e instanceof u?e.getName():e},r=await this._msgTxRx(t);if(!r)throw new Error("Unable to check if agent exists");return!!r.answer}async agentForService(e){let t={action:"agentForService",service:e},r=await this._msgTxRx(t);if(!r){if(this._returnNullOnFailedResponse)return null;throw new Error("Unable to get agent for service")}return r.agentID?new u(r.agentID,!1,this):null}async agentsForService(e){let t={action:"agentsForService",service:e},r=await this._msgTxRx(t),s=[];if(!r){if(this._returnNullOnFailedResponse)return s;throw new Error("Unable to get agents for service")}if(!Array.isArray(r.agentIDs))return s;for(var n=0;n<r.agentIDs.length;n++)s.push(new u(r.agentIDs[n],!1,this));return s}send(e){e.sender=this.aid.toJSON(),""==e.perf&&(e.__clazz__.endsWith("Req")?e.perf=h.REQUEST:e.perf=h.INFORM),this._sendEvent("txmsg",e);let t=JSON.stringify({action:"send",relay:!0,message:"###MSG###"});return t=t.replace('"###MSG###"',e._serialize()),!!this._msgTx(t)}flush(){this.queue.length=0}async request(e,t=1e3){return this.send(e),this.receive(e,t)}async receive(e,t=0){return new Promise((r=>{let s=this._getMessageFromQueue.call(this,e);if(s)return void r(s);if(0==t)return this.debug&&console.log("Receive Timeout : "+e),void r();let n,i=R(8);t>0&&(n=setTimeout((()=>{this.listener[i]&&delete this.listener[i],this.debug&&console.log("Receive Timeout : "+e),r()}),t)),this.listener[i]=t=>!!this._matchMessage(e,t)&&(n&&clearTimeout(n),this.listener[i]&&delete this.listener[i],r(t),!0)}))}close(){this.connector.close(),this._removeGWCache(this)}}const p={SHELL:"org.arl.fjage.shell.Services.SHELL"};function f(e,t=g){let r=e.replace(/^.*\./,"");if(f[r])return f[r];let s=class extends t{constructor(t){if(super(),this.__clazz__=e,t){const e=Object.keys(t);for(let r of e)this[r]=t[r]}e.endsWith("Req")&&(this.perf=h.REQUEST)}};return s.__clazz__=e,f[r]=s,s}function R(e){function t(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}let r=t();for(var s=0;s<e-1;s++)r+=t();return r}function m(e,t){if(null===t)return null;if("object"==typeof t&&"clazz"in t){let e=t.clazz;if(e.startsWith("[")&&2==e.length&&"data"in t){let e=function(e,t,r=!0){let s=S.atob(e),n=s.length,i=new Uint8Array(n);for(var o=0;o<n;o++)i[o]=s.charCodeAt(o);let a=[],l=new DataView(i.buffer);switch(t){case"[B":for(o=0;o<n;o++)a.push(l.getUint8(o));break;case"[S":for(o=0;o<n;o+=2)a.push(l.getInt16(o,r));break;case"[I":for(o=0;o<n;o+=4)a.push(l.getInt32(o,r));break;case"[J":for(o=0;o<n;o+=8)a.push(l.getBigInt64(o,r));break;case"[F":for(o=0;o<n;o+=4)a.push(l.getFloat32(o,r));break;case"[D":for(o=0;o<n;o+=8)a.push(l.getFloat64(o,r));break;default:return}return a}(t.data,t.clazz);e&&(t=e)}}return t}const _={};let v,S={};t||s?(S=window,Object.assign(_,{hostname:S.location.hostname,port:S.location.port,pathname:"/ws/",timeout:1e3,keepAlive:!0,queueSize:128,returnNullOnFailedResponse:!0}),v=new URL("ws://localhost"),void 0===S.fjage&&(S.fjage={}),void 0===S.fjage.gateways&&(S.fjage.gateways=[])):(n||r)&&(S=global,Object.assign(_,{hostname:"localhost",port:"1100",pathname:"",timeout:1e3,keepAlive:!0,queueSize:128,returnNullOnFailedResponse:!0}),v=new URL("tcp://localhost"),S.atob=e=>Buffer.from(e,"base64").toString("binary"));const y=f("org.arl.fjage.param.ParameterReq"),w=f("org.arl.unet.DatagramReq"),A=f("org.arl.unet.DatagramNtf"),N=f("org.arl.unet.phy.TxFrameReq",w),k=f("org.arl.unet.phy.RxFrameNtf",A),b=f("org.arl.unet.bb.BasebandSignal");Object.assign(p,{NODE_INFO:"org.arl.unet.Services.NODE_INFO",ADDRESS_RESOLUTION:"org.arl.unet.Services.ADDRESS_RESOLUTION",DATAGRAM:"org.arl.unet.Services.DATAGRAM",PHYSICAL:"org.arl.unet.Services.PHYSICAL",RANGING:"org.arl.unet.Services.RANGING",BASEBAND:"org.arl.unet.Services.BASEBAND",LINK:"org.arl.unet.Services.LINK",MAC:"org.arl.unet.Services.MAC",ROUTING:"org.arl.unet.Services.ROUTING",ROUTE_MAINTENANCE:"org.arl.unet.Services.ROUTE_MAINTENANCE",TRANSPORT:"org.arl.unet.Services.TRANSPORT",REMOTE:"org.arl.unet.Services.REMOTE",STATE_MANAGER:"org.arl.unet.Services.STATE_MANAGER",DEVICE_INFO:"org.arl.unet.Services.DEVICE_INFO",DOA:"org.arl.unet.Services.DOA",SCHEDULER:"org.arl.unet.Services.SCHEDULER"});let O={DATA:0,RANGING:1,LINK:2,REMOTE:3,MAC:4,ROUTING:5,TRANSPORT:6,ROUTE_MAINTENANCE:7,LINK2:8,USER:32,MAX:63},E={TestReportNtf:f("org.arl.unet.TestReportNtf"),AbnormalTerminationNtf:f("org.arl.unet.AbnormalTerminationNtf"),CapabilityListRsp:f("org.arl.unet.CapabilityListRsp"),CapabilityReq:f("org.arl.unet.CapabilityReq"),ClearReq:f("org.arl.unet.ClearReq"),DatagramCancelReq:f("org.arl.unet.DatagramCancelReq"),DatagramDeliveryNtf:f("org.arl.unet.DatagramDeliveryNtf"),DatagramFailureNtf:f("org.arl.unet.DatagramFailureNtf"),DatagramNtf:f("org.arl.unet.DatagramNtf"),DatagramProgressNtf:f("org.arl.unet.DatagramProgressNtf"),DatagramReq:f("org.arl.unet.DatagramReq"),ParamChangeNtf:f("org.arl.unet.ParamChangeNtf"),RefuseRsp:f("org.arl.unet.RefuseRsp"),FailureNtf:f("org.arl.unet.FailureNtf"),DatagramTraceReq:f("org.arl.unet.net.DatagramTraceReq"),RouteDiscoveryReq:f("org.arl.unet.net.RouteDiscoveryReq"),RouteTraceReq:f("org.arl.unet.net.RouteTraceReq"),RouteDiscoveryNtf:f("org.arl.unet.net.RouteDiscoveryNtf"),RouteTraceNtf:f("org.arl.unet.net.RouteTraceNtf"),FecDecodeReq:f("org.arl.unet.phy.FecDecodeReq"),RxSWiG1FrameNtf:f("org.arl.unet.phy.RxSWiG1FrameNtf",k),TxSWiG1FrameReq:f("org.arl.unet.phy.TxSWiG1FrameReq",N),RxJanusFrameNtf:f("org.arl.unet.phy.RxJanusFrameNtf",k),TxJanusFrameReq:f("org.arl.unet.phy.TxJanusFrameReq",N),BadFrameNtf:f("org.arl.unet.phy.BadFrameNtf"),BadRangeNtf:f("org.arl.unet.phy.BadRangeNtf"),ClearSyncReq:f("org.arl.unet.phy.ClearSyncReq"),CollisionNtf:f("org.arl.unet.phy.CollisionNtf"),RxFrameNtf:f("org.arl.unet.phy.RxFrameNtf",A),RxFrameStartNtf:f("org.arl.unet.phy.RxFrameStartNtf"),SyncInfoReq:f("org.arl.unet.phy.SyncInfoReq"),SyncInfoRsp:f("org.arl.unet.phy.SyncInfoRsp"),TxFrameNtf:f("org.arl.unet.phy.TxFrameNtf"),TxFrameReq:f("org.arl.unet.phy.TxFrameReq",w),TxFrameStartNtf:f("org.arl.unet.phy.TxFrameStartNtf"),TxRawFrameReq:f("org.arl.unet.phy.TxRawFrameReq"),AddressAllocReq:f("org.arl.unet.addr.AddressAllocReq"),AddressAllocRsp:f("org.arl.unet.addr.AddressAllocRsp"),AddressResolutionReq:f("org.arl.unet.addr.AddressResolutionReq"),AddressResolutionRsp:f("org.arl.unet.addr.AddressResolutionRsp"),BasebandSignal:f("org.arl.unet.bb.BasebandSignal"),RecordBasebandSignalReq:f("org.arl.unet.bb.RecordBasebandSignalReq"),RxBasebandSignalNtf:f("org.arl.unet.bb.RxBasebandSignalNtf",b),TxBasebandSignalReq:f("org.arl.unet.bb.TxBasebandSignalReq",b),LinkStatusNtf:f("org.arl.unet.link.LinkStatusNtf"),RangeNtf:f("org.arl.unet.localization.RangeNtf"),RangeReq:f("org.arl.unet.localization.RangeReq"),BeaconReq:f("org.arl.unet.localization.BeaconReq"),RespondReq:f("org.arl.unet.localization.RespondReq"),InterrogationNtf:f("org.arl.unet.localization.InterrogationNtf"),ReservationAcceptReq:f("org.arl.unet.mac.ReservationAcceptReq"),ReservationCancelReq:f("org.arl.unet.mac.ReservationCancelReq"),ReservationReq:f("org.arl.unet.mac.ReservationReq"),ReservationRsp:f("org.arl.unet.mac.ReservationRsp"),ReservationStatusNtf:f("org.arl.unet.mac.ReservationStatusNtf"),RxAckNtf:f("org.arl.unet.mac.RxAckNtf"),TxAckReq:f("org.arl.unet.mac.TxAckReq"),RemoteExecReq:f("org.arl.unet.remote.RemoteExecReq"),RemoteFailureNtf:f("org.arl.unet.remote.RemoteFailureNtf"),RemoteFileGetReq:f("org.arl.unet.remote.RemoteFileGetReq"),RemoteFileNtf:f("org.arl.unet.remote.RemoteFileNtf"),RemoteFilePutReq:f("org.arl.unet.remote.RemoteFilePutReq"),RemoteSuccessNtf:f("org.arl.unet.remote.RemoteSuccessNtf"),RemoteTextNtf:f("org.arl.unet.remote.RemoteTextNtf"),RemoteTextReq:f("org.arl.unet.remote.RemoteTextReq"),AddScheduledSleepReq:f("org.arl.unet.scheduler.AddScheduledSleepReq"),GetSleepScheduleReq:f("org.arl.unet.scheduler.GetSleepScheduleReq"),RemoveScheduledSleepReq:f("org.arl.unet.scheduler.RemoveScheduledSleepReq"),SleepScheduleRsp:f("org.arl.unet.scheduler.SleepScheduleRsp"),WakeFromSleepNtf:f("org.arl.unet.scheduler.WakeFromSleepNtf"),ClearStateReq:f("org.arl.unet.state.ClearStateReq"),SaveStateReq:f("org.arl.unet.state.SaveStateReq")};function T(e){let t=e*Math.PI/180,r=111132.92-559.82*Math.cos(2*t)+1.175*Math.cos(4*t)-.0023*Math.cos(6*t);return[111412.84*Math.cos(t)-93.5*Math.cos(3*t)+.118*Math.cos(5*t),r]}class C extends u{constructor(e,t,r,s=!0){e instanceof u?super(e.getName(),e.topic,e.owner):super(e,t,r),this.greedy=s,this.cache={},this.specialParams=["name","version"]}async set(e,t,r=-1,s=5e3){let n=await super.set(e,t,r,s);return this._updateCache(e,n,r),n}async get(e,t=-1,r=5e3,s=5e3){if(this._isCached(e,t,s))return this._getCache(e,t);if(!this.greedy||Array.isArray(e)&&0!=[...new Set([...e,...this.specialParams])].length||this.specialParams.includes(e)){let s=await super.get(e,t,r);return this._updateCache(e,s,t),s}{let s=await super.get(null,t,r);if(this._updateCache(null,s,t),!s)return Array.isArray(e)?new Array(e.length).fill(null):null;if(e){if(Array.isArray(e))return e.map((e=>{let t=Object.keys(s).find((t=>this._toNamed(t)===e));return t?s[t]:null}));{let t=Object.keys(s).find((t=>this._toNamed(t)===e));return t?s[t]:null}}return s}}_updateCache(e,t,r){if(null==t||Array.isArray(t)&&t.every((e=>null==e)))return;null==e?(e=Object.keys(t),t=Object.values(t)):Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]),e=e.map(this._toNamed),void 0===this.cache[r.toString()]&&(this.cache[r.toString()]={});let s=this.cache[r.toString()];for(let r=0;r<e.length;r++)void 0===s[e[r]]&&(s[e[r]]={}),s[e[r]].value=t[r],s[e[r]].ctime=Date.now()}_isCached(e,t,r){if(r<=0)return!1;if(null==e)return!1;let s=this.cache[t.toString()];if(!s)return!1;Array.isArray(e)||(e=[e]);return e.every((e=>(e=this._toNamed(e))in s&&Date.now()-s[e].ctime<=r))}_getCache(e,t){let r=this.cache[t.toString()];return r?Array.isArray(e)?e.map((e=>e in r?r[e].value:null)):e in r?r[e].value:null:null}_toNamed(e){const t=e.lastIndexOf(".");return t<0?e:e.slice(t+1)}}const F=E.AddressResolutionReq,q=E.DatagramReq,D=E.DatagramNtf,I=E.RxFrameNtf;e.AgentID=u,e.CachingAgentID=C,e.CachingGateway=class extends d{agent(e,t=!0,r=!0){const s=super.agent(e);return t?new C(s,null,null,r):s}topic(e,t,r=!0,s=!0){const n=super.topic(e,t);return r?new C(n,null,null,s):n}async agentForService(e,t=!0,r=!0){const s=await super.agentForService(e);return s&&t?new C(s,null,null,r):s}async agentsForService(e,t=!0,r=!0){const s=await super.agentsForService(e);return t?s.map((e=>new C(e,null,null,r))):s}},e.Gateway=d,e.Message=g,e.MessageClass=f,e.Performative=h,e.Protocol=O,e.Services=p,e.UnetMessages=E,e.UnetSocket=class{constructor(e,t,r=""){return(async()=>{this.gw=new d({hostname:e,port:t,path:r}),this.localProtocol=-1,this.remoteAddress=-1,this.remoteProtocol=O.DATA,this.timeout=0,this.provider=null;return(await this.gw.agentsForService(p.DATAGRAM)).forEach((e=>{this.gw.subscribe(this.gw.topic(e))})),this})()}close(){this.gw.close(),this.gw=null}isClosed(){return null==this.gw}bind(e){return(e==O.DATA||e>=O.USER&&e<=O.MAX)&&(this.localProtocol=e,!0)}unbind(){this.localProtocol=-1}isBound(){return this.localProtocol>=0}connect(e,t){return e>=0&&(t==O.DATA||t>=O.USER&&t<=O.MAX)&&(this.remoteAddress=e,this.remoteProtocol=t,!0)}disconnect(){this.remoteAddress=-1,this.remoteProtocol=0}isConnected(){return this.remoteAddress>=0}async getLocalAddress(){if(null==this.gw)return-1;const e=await this.gw.agentForService(p.NODE_INFO);if(null==e)return-1;const t=await e.get("address");return null!=t?t:-1}getLocalProtocol(){return this.localProtocol}getRemoteAddress(){return this.remoteAddress}getRemoteProtocol(){return this.remoteProtocol}setTimeout(e){e<0&&(e=0),this.timeout=e}getTimeout(){return this.timeout}async send(e,t=this.remoteAddress,r=this.remoteProtocol){if(t<0||null==this.gw)return!1;var s;if(Array.isArray(e))(s=new q).data=e,s.to=t,s.protocol=r;else{if(!(e instanceof q))return!1;s=e}let n=s.protocol;if(n!=O.DATA&&(n<O.USER||n>O.MAX))return!1;if(null==s.recipient){if(null==this.provider&&(this.provider=await this.gw.agentForService(p.TRANSPORT)),null==this.provider&&(this.provider=await this.gw.agentForService(p.ROUTING)),null==this.provider&&(this.provider=await this.gw.agentForService(p.LINK)),null==this.provider&&(this.provider=await this.gw.agentForService(p.PHYSICAL)),null==this.provider&&(this.provider=await this.gw.agentForService(p.DATAGRAM)),null==this.provider)return!1;s.recipient=this.provider}const i=await this.gw.request(s,1e3);return null!=i&&i.perf==h.AGREE}async receive(){return null==this.gw?null:await this.gw.receive((e=>{if(e.__clazz__!=D.__clazz__&&e.__clazz__!=I.__clazz__)return!1;let t=e.protocol;return(t==O.DATA||t>=O.USER)&&(this.localProtocol<0||this.localProtocol==t)}),this.timeout)}getGateway(){return this.gw}async agentForService(e,t=!0){return null==this.gw?null:await this.gw.agentForService(e,t)}async agentsForService(e,t=!0){return null==this.gw?null:await this.gw.agentsForService(e,t``)}agent(e,t=!0){return null==this.gw?null:this.gw.agent(e,t)}async host(e){const t=await this.agentForService(p.ADDRESS_RESOLUTION);if(null==t)return null;const r=new F(e);r.name=e,r.recipient=t;const s=await this.gw.request(r,1e3);return null!=s&&Object.prototype.hasOwnProperty.call(s,"address")?s.address:null}},e.toGps=function(e,t,r){let s=[],[n,i]=T(e[0]);return s[1]=t/n+e[1],s[0]=r/i+e[0],s},e.toLocal=function(e,t,r){let s=[],[n,i]=T(e[0]);return s[0]=(r-e[1])*n,s[1]=(t-e[0])*i,s}}));
2
2
  //# sourceMappingURL=unetjs.min.js.map