unetjs 2.0.1 → 2.0.4

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,s="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,r="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,n="open",i="opening";var o;class a{constructor(e={}){this.url=new URL("tcp://localhost");let t=e.hostname||"localhost",s=e.port||-1;this.url.hostname=e.hostname,this.url.port=e.port,this._buf="",this.pendingOnOpen=[],this.connListeners=[],this._sockInit(t,s)}_sendConnEvent(e){this.connListeners.forEach((t=>{t&&"[object Function]"==={}.toString.call(t)&&t(e)}))}_sockInit(e,t){if(o)this._sockSetup(e,t);else try{import("net").then((s=>{o=s.createConnection,this._sockSetup(e,t)}))}catch(e){this.debug&&console.log("Unable to import net module")}}_sockSetup(e,t){if(o)try{this.sock=o({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!=i&&this.sock.readyState!=n&&(this._firstReConn&&this._sendConnEvent(!1),this._firstReConn=!1,this.debug&&console.log("Reconnecting to ",this.sock.remoteAddress+":"+this.sock.remotePort),setTimeout((()=>{this.pendingOnOpen=[],this._sockSetup(this.sock.url)}),this._reconnectTime))}_onSockOpen(){this._sendConnEvent(!0),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,s)=>{s<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!=i?this.sock.readyState==n&&(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==i?this.pendingOnOpen.push((()=>{this.sock.send('{"alive": false}\n'),this.sock.onclose=null,this.sock.destroy()})):this.sock.readyState==n&&(this.sock.send('{"alive": false}\n'),this.sock.onclose=null,this.sock.destroy()))}}class l{constructor(e={}){this.url=new URL("ws://localhost"),this.url.hostname=e.hostname,this.url.port=e.port,this.url.pathname=e.pathname,this._reconnectTime=e.reconnectTime||5e3,this._keepAlive=e.keepAlive,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 c={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,s){this.name=e,this.topic=t,this.owner=s}getName(){return this.name}isTopic(){return this.topic}send(e){e.recipient=this.toJSON(),this.owner.send(e)}async request(e,t=1e3){return e.recipient=this.toJSON(),this.owner.request(e,t)}toString(){return this.toJSON()+(this.owner&&this.owner.connector?` on ${this.owner.connector.url}`:"")}toJSON(){return(this.topic?"#":"")+this.name}async set(e,t,s=-1,r=5e3){if(!e)return null;let n=new S;n.recipient=this.name,Array.isArray(e)?n.requests=e.map(((e,s)=>({param:e,value:t[s]}))):(n.param=e,n.value=t),n.index=Number.isInteger(s)?s:-1;const i=await this.owner.request(n,r);var o=Array.isArray(e)?new Array(e.length).fill(null):null;if(!i||i.perf!=c.INFORM||!i.param)return o;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 s=t.find((t=>t.endsWith(e)));return s?i.values[s]:null}))}return i.value}async get(e,t=-1,s=5e3){let r=new S;r.recipient=this.name,e&&(Array.isArray(e)?r.requests=e.map((e=>({param:e}))):r.param=e),r.index=Number.isInteger(t)?t:-1;const n=await this.owner.request(r,s);var i=Array.isArray(e)?new Array(e.length).fill(null):null;if(!n||n.perf!=c.INFORM||e&&!n.param)return i;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 s=t.find((t=>t.endsWith(e)));return s?n.values[s]:null}))}return n.value}return n.values||(n.values={}),n.param&&(n.values[n.param]=n.value),n.values}}class h{constructor(e={msgID:null,sender:null},t=""){this.__clazz__="org.arl.fjage.Message",this.msgID=p(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 s=this.__clazz__;s=s.replace(/^.*\./,"");let r=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,s+":"+r+"["+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){if("string"==typeof e||e instanceof String)try{e=JSON.parse(e)}catch(e){return null}let t=e.clazz,s=t.replace(/^.*\./,""),r=d[s]?new d[s]:new h;return r.__clazz__=t,r._inflate(e.data),r}}const g={SHELL:"org.arl.fjage.shell.Services.SHELL"};function d(e,t=h){let s=e.replace(/^.*\./,"");if(d[s])return d[s];let r=class extends t{constructor(t){if(super(),this.__clazz__=e,t){const e=Object.keys(t);for(let s of e)this[s]=t[s]}}};return r.__clazz__=e,d[s]=r,r}function p(e){function t(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}let s=t();for(var r=0;r<e-1;r++)s+=t();return s}function f(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,s=!0){let r=_.atob(e),n=r.length,i=new Uint8Array(n);for(var o=0;o<n;o++)i[o]=r.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,s));break;case"[I":for(o=0;o<n;o+=4)a.push(l.getInt32(o,s));break;case"[J":for(o=0;o<n;o+=8)a.push(l.getInt64(o,s));break;case"[F":for(o=0;o<n;o+=4)a.push(l.getFloat32(o,s));break;case"[D":for(o=0;o<n;o+=8)a.push(l.getFloat64(o,s));break;default:return}return a}(t.data,t.clazz);e&&(t=e)}}return t}const R={};let m,_={};t||s?(_=window,Object.assign(R,{hostname:_.location.hostname,port:_.location.port,pathname:"/ws/",timeout:1e3,keepAlive:!0,queueSize:128}),m=new URL("ws://localhost"),void 0===_.fjage&&(_.fjage={}),void 0===_.fjage.gateways&&(_.fjage.gateways=[])):((()=>"undefined"!=typeof window&&"nodejs"===window.name||navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"))||r)&&(_=global,Object.assign(R,{hostname:"localhost",port:"1100",pathname:"",timeout:1e3,keepAlive:!0,queueSize:128}),m=new URL("tcp://localhost"),_.atob=e=>Buffer.from(e,"base64").toString("binary"));const S=d("org.arl.fjage.param.ParameterReq"),v=d("org.arl.unet.DatagramReq"),y=d("org.arl.unet.DatagramNtf"),A=d("org.arl.unet.bb.BasebandSignal");Object.assign(g,{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"});let N={DATA:0,RANGING:1,LINK:2,REMOTE:3,MAC:4,ROUTING:5,TRANSPORT:6,ROUTE_MAINTENANCE:7,LINK2:8,USER:32,MAX:63},w={TestReportNtf:d("org.arl.unet.TestReportNtf"),AbnormalTerminationNtf:d("org.arl.unet.AbnormalTerminationNtf"),CapabilityListRsp:d("org.arl.unet.CapabilityListRsp"),CapabilityReq:d("org.arl.unet.CapabilityReq"),ClearReq:d("org.arl.unet.ClearReq"),DatagramCancelReq:d("org.arl.unet.DatagramCancelReq"),DatagramDeliveryNtf:d("org.arl.unet.DatagramDeliveryNtf"),DatagramFailureNtf:d("org.arl.unet.DatagramFailureNtf"),DatagramNtf:d("org.arl.unet.DatagramNtf"),DatagramProgressNtf:d("org.arl.unet.DatagramProgressNtf"),DatagramReq:d("org.arl.unet.DatagramReq"),ParamChangeNtf:d("org.arl.unet.ParamChangeNtf"),RefuseRsp:d("org.arl.unet.RefuseRsp"),FailureNtf:d("org.arl.unet.FailureNtf"),DatagramTraceReq:d("org.arl.unet.net.DatagramTraceReq"),RouteDiscoveryReq:d("org.arl.unet.net.RouteDiscoveryReq"),RouteTraceReq:d("org.arl.unet.net.RouteTraceReq"),RouteDiscoveryNtf:d("org.arl.unet.net.RouteDiscoveryNtf"),RouteTraceNtf:d("org.arl.unet.net.RouteTraceNtf"),FecDecodeReq:d("org.arl.unet.phy.FecDecodeReq"),RxJanusFrameNtf:d("org.arl.unet.phy.RxJanusFrameNtf"),TxJanusFrameReq:d("org.arl.unet.phy.TxJanusFrameReq"),BadFrameNtf:d("org.arl.unet.phy.BadFrameNtf"),BadRangeNtf:d("org.arl.unet.phy.BadRangeNtf"),ClearSyncReq:d("org.arl.unet.phy.ClearSyncReq"),CollisionNtf:d("org.arl.unet.phy.CollisionNtf"),RxFrameNtf:d("org.arl.unet.phy.RxFrameNtf",y),RxFrameStartNtf:d("org.arl.unet.phy.RxFrameStartNtf"),SyncInfoReq:d("org.arl.unet.phy.SyncInfoReq"),SyncInfoRsp:d("org.arl.unet.phy.SyncInfoRsp"),TxFrameNtf:d("org.arl.unet.phy.TxFrameNtf"),TxFrameReq:d("org.arl.unet.phy.TxFrameReq",v),TxFrameStartNtf:d("org.arl.unet.phy.TxFrameStartNtf"),TxRawFrameReq:d("org.arl.unet.phy.TxRawFrameReq"),AddressAllocReq:d("org.arl.unet.addr.AddressAllocReq"),AddressAllocRsp:d("org.arl.unet.addr.AddressAllocRsp"),AddressResolutionReq:d("org.arl.unet.addr.AddressResolutionReq"),AddressResolutionRsp:d("org.arl.unet.addr.AddressResolutionRsp"),BasebandSignal:d("org.arl.unet.bb.BasebandSignal"),RecordBasebandSignalReq:d("org.arl.unet.bb.RecordBasebandSignalReq"),RxBasebandSignalNtf:d("org.arl.unet.bb.RxBasebandSignalNtf",A),TxBasebandSignalReq:d("org.arl.unet.bb.TxBasebandSignalReq",A),LinkStatusNtf:d("org.arl.unet.link.LinkStatusNtf"),RangeNtf:d("org.arl.unet.localization.RangeNtf"),RangeReq:d("org.arl.unet.localization.RangeReq"),BeaconReq:d("org.arl.unet.localization.BeaconReq"),RespondReq:d("org.arl.unet.localization.RespondReq"),InterrogationNtf:d("org.arl.unet.localization.InterrogationNtf"),ReservationAcceptReq:d("org.arl.unet.mac.ReservationAcceptReq"),ReservationCancelReq:d("org.arl.unet.mac.ReservationCancelReq"),ReservationReq:d("org.arl.unet.mac.ReservationReq"),ReservationRsp:d("org.arl.unet.mac.ReservationRsp"),ReservationStatusNtf:d("org.arl.unet.mac.ReservationStatusNtf"),RxAckNtf:d("org.arl.unet.mac.RxAckNtf"),TxAckReq:d("org.arl.unet.mac.TxAckReq"),RemoteExecReq:d("org.arl.unet.remote.RemoteExecReq"),RemoteFailureNtf:d("org.arl.unet.remote.RemoteFailureNtf"),RemoteFileGetReq:d("org.arl.unet.remote.RemoteFileGetReq"),RemoteFileNtf:d("org.arl.unet.remote.RemoteFileNtf"),RemoteFilePutReq:d("org.arl.unet.remote.RemoteFilePutReq"),RemoteSuccessNtf:d("org.arl.unet.remote.RemoteSuccessNtf"),RemoteTextNtf:d("org.arl.unet.remote.RemoteTextNtf"),RemoteTextReq:d("org.arl.unet.remote.RemoteTextReq"),AddScheduledSleepReq:d("org.arl.unet.scheduler.AddScheduledSleepReq"),GetSleepScheduleReq:d("org.arl.unet.scheduler.GetSleepScheduleReq"),RemoveScheduledSleepReq:d("org.arl.unet.scheduler.RemoveScheduledSleepReq"),SleepScheduleRsp:d("org.arl.unet.scheduler.SleepScheduleRsp"),WakeFromSleepNtf:d("org.arl.unet.scheduler.WakeFromSleepNtf"),ClearStateReq:d("org.arl.unet.state.ClearStateReq"),SaveStateReq:d("org.arl.unet.state.SaveStateReq")};function k(e){let t=e*Math.PI/180,s=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),s]}class b extends u{constructor(e,t,s,r=!0){e instanceof u?super(e.getName(),e.topic,e.owner):super(e,t,s),this.greedy=r,this.cache={}}async set(e,t,s=-1,r=5e3){let n=await super.set(e,t,s,r);this._updateCache(e,n,s)}async get(e,t=-1,s=5e3,r=5e3){if(this._isCached(e,t,r))return this._getCache(e,t);if(!this.greedy||Array.isArray(e)&&e.includes("name")||"name"==e){let r=await super.get(e,t,s);return this._updateCache(e,r,t),r}{let r=await super.get(null,t,s);if(this._updateCache(null,r,t),Array.isArray(e))return e.map((e=>{let t=Object.keys(r).find((t=>this._toNamed(t)===e));return t?r[t]:null}));{let t=Object.keys(r).find((t=>this._toNamed(t)===e));return t?r[t]:null}}}_updateCache(e,t,s){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[s.toString()]&&(this.cache[s.toString()]={});let r=this.cache[s.toString()];for(let s=0;s<e.length;s++)void 0===r[e[s]]&&(r[e[s]]={}),r[e[s]].value=t[s],r[e[s]].ctime=Date.now()}_isCached(e,t,s){if(s<=0)return!1;if(null==e)return!1;let r=this.cache[t.toString()];if(!r)return!1;Array.isArray(e)||(e=[e]);return e.every((e=>(e=this._toNamed(e))in r&&Date.now()-r[e].ctime<=s))}_getCache(e,t){let s=this.cache[t.toString()];return s?Array.isArray(e)?e.map((e=>e in s?s[e].value:null)):e in s?s[e].value:null:null}_toNamed(e){const t=e.lastIndexOf(".");return t<0?e:e.slice(t+1)}}class O extends class{constructor(e={},s,r="/ws/",n=1e3){("string"==typeof e||e instanceof String)&&(e={hostname:e,port:s||_.location.port,pathname:r,timeout:n},console.warn("Deprecated use of Gateway constructor")),e=Object.assign({},R,e);var i=m;i.hostname=e.hostname,i.port=e.port,i.pathname=e.pathname;let o=this._getGWCache(i);if(o)return o;this._timeout=e.timeout,this._keepAlive=e.keepAlive,this._queueSize=e.queueSize,this.pending={},this.subscriptions={},this.listener={},this.eventListeners={},this.queue=[],this.debug=!1,this.aid=new u(t?"WebGW-":"NodeGW-"+p(4)),this.connector=this._createConnector(i),this._addGWCache(this)}_sendEvent(e,t){Array.isArray(this.eventListeners[e])&&this.eventListeners[e].forEach((e=>{e&&"[object Function]"==={}.toString.call(e)&&e(t)}))}_onMsgRx(e){var t;this.debug&&console.log("< "+e),this._sendEvent("rx",e);try{t=JSON.parse(e,f)}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=h._deserialize(t.message);if(!e)return;if(this._sendEvent("rxmsg",e),e.recipient==this.aid.toJSON()||this.subscriptions[e.recipient]){var s=!1;if(Array.isArray(this.eventListeners.message))for(var r=0;r<this.eventListeners.message.length;r++)if(this.eventListeners.message[r](e)){s=!0;break}for(var n in this.listener)if(this.listener[n](e)){s=!0;break}s||(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=p(8),new Promise((t=>{let s=setTimeout((()=>{delete this.pending[e.id],this.debug&&console.log("Receive Timeout : "+e),t()}),8*this._timeout);this.pending[e.id]=e=>{clearTimeout(s),t(e)},this._msgTx.call(this,e)||(clearTimeout(s),delete this.pending[e.id],this.debug&&console.log("Transmit Timeout : "+e),t())}))}_createConnector(e){let t;if(e.protocol.startsWith("ws"))t=new l({hostname:e.hostname,port:e.port,pathname:e.pathname,keepAlive:this._keepAlive});else{if(!e.protocol.startsWith("tcp"))return null;t=new a({hostname:e.hostname,port:e.port,keepAlive:this._keepAlive})}return t.setReadCallback(this._onMsgRx.bind(this)),t.addConnectionListener((e=>{1==e&&(this.flush(),this.connector.write('{"alive": true}'),this._update_watch())})),t}_matchMessage(e,t){return"string"==typeof e||e instanceof String?"inReplyTo"in t&&t.inReplyTo==e:Object.prototype.hasOwnProperty.call(e,"msgID")?"inReplyTo"in t&&t.inReplyTo==e.msgID:"Message"==e.__proto__.name?e.__clazz__==t.__clazz__:"function"==typeof e?e(t):t instanceof e}_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(!_.fjage||!_.fjage.gateways)return null;var t=_.fjage.gateways.filter((t=>t.connector.url.toString()==e.toString()));return t.length?t[0]:null}_addGWCache(e){_.fjage&&_.fjage.gateways&&_.fjage.gateways.push(e)}_removeGWCache(e){if(_.fjage&&_.fjage.gateways){var t=_.fjage.gateways.indexOf(e);null!=t&&_.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 s=this.eventListeners[e].indexOf(t);s>=0&&this.eventListeners[e].splice(s,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){e.isTopic()||(e=new u(e.getName()+"__ntf",!0,this)),this.subscriptions[e.toJSON()]=!0,this._update_watch()}unsubscribe(e){e.isTopic()||(e=new u(e.getName()+"__ntf",!0,this)),delete this.subscriptions[e.toJSON()],this._update_watch()}async agentForService(e){let t={action:"agentForService",service:e},s=await this._msgTxRx(t);if(s&&s.agentID)return new u(s.agentID,!1,this)}async agentsForService(e){let t={action:"agentsForService",service:e},s=await this._msgTxRx(t),r=[];if(!s||!Array.isArray(s.agentIDs))return r;for(var n=0;n<s.agentIDs.length;n++)r.push(new u(s.agentIDs[n],!1,this));return r}send(e){e.sender=this.aid.toJSON(),""==e.perf&&(e.__clazz__.endsWith("Req")?e.perf=c.REQUEST:e.perf=c.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((s=>{let r=this._getMessageFromQueue.call(this,e);if(r)return void s(r);if(0==t)return this.debug&&console.log("Receive Timeout : "+e),void s();let n,i=p(8);t>0&&(n=setTimeout((()=>{delete this.listener[i],this.debug&&console.log("Receive Timeout : "+e),s()}),t)),this.listener[i]=t=>!!this._matchMessage(e,t)&&(n&&clearTimeout(n),delete this.listener[i],s(t),!0)}))}close(){this.connector.close(),this._removeGWCache(this)}}{agent(e,t=!0,s=!0){const r=super.agent(e);return t?new b(r,null,null,s):r}topic(e,t,s=!0,r=!0){const n=super.topic(e,t);return s?new b(n,null,null,r):n}async agentForService(e,t=!0,s=!0){const r=await super.agentForService(e);return t?new b(r,null,null,s):r}async agentsForService(e,t=!0,s=!0){const r=await super.agentsForService(e);return t?r.map((e=>new b(e,null,null,s))):r}}const T=w.AddressResolutionReq,E=w.DatagramReq,C=w.DatagramNtf,q=w.RxFrameNtf;e.AgentID=u,e.CachingAgentID=b,e.Gateway=O,e.Message=h,e.MessageClass=d,e.Performative=c,e.Protocol=N,e.Services=g,e.UnetMessages=w,e.UnetSocket=class{constructor(e,t,s=""){return(async()=>{this.gw=new O({hostname:e,port:t,path:s}),this.localProtocol=-1,this.remoteAddress=-1,this.remoteProtocol=N.DATA,this.timeout=0,this.provider=null;return(await this.gw.agentsForService(g.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==N.DATA||e>=N.USER&&e<=N.MAX)&&(this.localProtocol=e,!0)}unbind(){this.localProtocol=-1}isBound(){return this.localProtocol>=0}connect(e,t){return e>=0&&(t==N.DATA||t>=N.USER&&t<=N.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(g.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,s=this.remoteProtocol){if(t<0||null==this.gw)return!1;var r;if(Array.isArray(e))(r=new E).data=e,r.to=t,r.protocol=s;else{if(!(e instanceof E))return!1;r=e}let n=r.protocol;if(n!=N.DATA&&(n<N.USER||n>N.MAX))return!1;if(null==r.recipient){if(null==this.provider&&(this.provider=await this.gw.agentForService(g.TRANSPORT)),null==this.provider&&(this.provider=await this.gw.agentForService(g.ROUTING)),null==this.provider&&(this.provider=await this.gw.agentForService(g.LINK)),null==this.provider&&(this.provider=await this.gw.agentForService(g.PHYSICAL)),null==this.provider&&(this.provider=await this.gw.agentForService(g.DATAGRAM)),null==this.provider)return!1;r.recipient=this.provider}const i=await this.gw.request(r,1e3);return null!=i&&i.perf==c.AGREE}async receive(){return null==this.gw?null:await this.gw.receive((e=>{if(e.__clazz__!=C.__clazz__&&e.__clazz__!=q.__clazz__)return!1;let t=e.protocol;return(t==N.DATA||t>=N.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(g.ADDRESS_RESOLUTION);if(null==t)return null;const s=new T(e);s.name=e,s.recipient=t;const r=await this.gw.request(s,1e3);return null!=r&&Object.prototype.hasOwnProperty.call(r,"address")?r.address:null}},e.toGps=function(e,t,s){let r=[],[n,i]=k(e[0]);return r[1]=t/n+e[1],r[0]=s/i+e[0],r},e.toLocal=function(e,t,s){let r=[],[n,i]=k(e[0]);return r[0]=(s-e[1])*n,r[1]=(t-e[0])*i,r}}));
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,s="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,r="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={}){this.url=new URL("tcp://localhost");let t=e.hostname||"localhost",s=e.port||-1;this.url.hostname=e.hostname,this.url.port=e.port,this._buf="",this.pendingOnOpen=[],this.connListeners=[],this._sockInit(t,s)}_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((s=>{a=s.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,this.debug&&console.log("Reconnecting to ",this.sock.remoteAddress+":"+this.sock.remotePort),setTimeout((()=>{this.pendingOnOpen=[],this._sockSetup(this.sock.url)}),this._reconnectTime))}_onSockOpen(){this._sendConnEvent(!0),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,s)=>{s<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.onclose=null,this.sock.destroy()})):this.sock.readyState==i&&(this.sock.send('{"alive": false}\n'),this.sock.onclose=null,this.sock.destroy()))}}class c{constructor(e={}){this.url=new URL("ws://localhost"),this.url.hostname=e.hostname,this.url.port=e.port,this.url.pathname=e.pathname,this._reconnectTime=e.reconnectTime||5e3,this._keepAlive=e.keepAlive,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 u={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 h{constructor(e,t,s){this.name=e,this.topic=t,this.owner=s}getName(){return this.name}isTopic(){return this.topic}send(e){e.recipient=this.toJSON(),this.owner.send(e)}async request(e,t=1e3){return e.recipient=this.toJSON(),this.owner.request(e,t)}toString(){return this.toJSON()+(this.owner&&this.owner.connector?` on ${this.owner.connector.url}`:"")}toJSON(){return(this.topic?"#":"")+this.name}async set(e,t,s=-1,r=5e3){if(!e)return null;let n=new S;n.recipient=this.name,Array.isArray(e)?n.requests=e.map(((e,s)=>({param:e,value:t[s]}))):(n.param=e,n.value=t),n.index=Number.isInteger(s)?s:-1;const i=await this.owner.request(n,r);var o=Array.isArray(e)?new Array(e.length).fill(null):null;if(!i||i.perf!=u.INFORM||!i.param)return o;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 s=t.find((t=>t.endsWith(e)));return s?i.values[s]:null}))}return i.value}async get(e,t=-1,s=5e3){let r=new S;r.recipient=this.name,e&&(Array.isArray(e)?r.requests=e.map((e=>({param:e}))):r.param=e),r.index=Number.isInteger(t)?t:-1;const n=await this.owner.request(r,s);var i=Array.isArray(e)?new Array(e.length).fill(null):null;if(!n||n.perf!=u.INFORM||e&&!n.param)return i;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 s=t.find((t=>t.endsWith(e)));return s?n.values[s]:null}))}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=""){this.__clazz__="org.arl.fjage.Message",this.msgID=f(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 s=this.__clazz__;s=s.replace(/^.*\./,"");let r=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,s+":"+r+"["+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){if("string"==typeof e||e instanceof String)try{e=JSON.parse(e)}catch(e){return null}let t=e.clazz,s=t.replace(/^.*\./,""),r=p[s]?new p[s]:new g;return r.__clazz__=t,r._inflate(e.data),r}}const d={SHELL:"org.arl.fjage.shell.Services.SHELL"};function p(e,t=g){let s=e.replace(/^.*\./,"");if(p[s])return p[s];let r=class extends t{constructor(t){if(super(),this.__clazz__=e,t){const e=Object.keys(t);for(let s of e)this[s]=t[s]}}};return r.__clazz__=e,p[s]=r,r}function f(e){function t(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}let s=t();for(var r=0;r<e-1;r++)s+=t();return s}function R(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,s=!0){let r=v.atob(e),n=r.length,i=new Uint8Array(n);for(var o=0;o<n;o++)i[o]=r.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,s));break;case"[I":for(o=0;o<n;o+=4)a.push(l.getInt32(o,s));break;case"[J":for(o=0;o<n;o+=8)a.push(l.getInt64(o,s));break;case"[F":for(o=0;o<n;o+=4)a.push(l.getFloat32(o,s));break;case"[D":for(o=0;o<n;o+=8)a.push(l.getFloat64(o,s));break;default:return}return a}(t.data,t.clazz);e&&(t=e)}}return t}const m={};let _,v={};t||r?(v=window,Object.assign(m,{hostname:v.location.hostname,port:v.location.port,pathname:"/ws/",timeout:1e3,keepAlive:!0,queueSize:128}),_=new URL("ws://localhost"),void 0===v.fjage&&(v.fjage={}),void 0===v.fjage.gateways&&(v.fjage.gateways=[])):(n||s)&&(v=global,Object.assign(m,{hostname:"localhost",port:"1100",pathname:"",timeout:1e3,keepAlive:!0,queueSize:128}),_=new URL("tcp://localhost"),v.atob=e=>Buffer.from(e,"base64").toString("binary"));const S=p("org.arl.fjage.param.ParameterReq"),y=p("org.arl.unet.DatagramReq"),A=p("org.arl.unet.DatagramNtf"),N=p("org.arl.unet.bb.BasebandSignal");Object.assign(d,{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"});let w={DATA:0,RANGING:1,LINK:2,REMOTE:3,MAC:4,ROUTING:5,TRANSPORT:6,ROUTE_MAINTENANCE:7,LINK2:8,USER:32,MAX:63},k={TestReportNtf:p("org.arl.unet.TestReportNtf"),AbnormalTerminationNtf:p("org.arl.unet.AbnormalTerminationNtf"),CapabilityListRsp:p("org.arl.unet.CapabilityListRsp"),CapabilityReq:p("org.arl.unet.CapabilityReq"),ClearReq:p("org.arl.unet.ClearReq"),DatagramCancelReq:p("org.arl.unet.DatagramCancelReq"),DatagramDeliveryNtf:p("org.arl.unet.DatagramDeliveryNtf"),DatagramFailureNtf:p("org.arl.unet.DatagramFailureNtf"),DatagramNtf:p("org.arl.unet.DatagramNtf"),DatagramProgressNtf:p("org.arl.unet.DatagramProgressNtf"),DatagramReq:p("org.arl.unet.DatagramReq"),ParamChangeNtf:p("org.arl.unet.ParamChangeNtf"),RefuseRsp:p("org.arl.unet.RefuseRsp"),FailureNtf:p("org.arl.unet.FailureNtf"),DatagramTraceReq:p("org.arl.unet.net.DatagramTraceReq"),RouteDiscoveryReq:p("org.arl.unet.net.RouteDiscoveryReq"),RouteTraceReq:p("org.arl.unet.net.RouteTraceReq"),RouteDiscoveryNtf:p("org.arl.unet.net.RouteDiscoveryNtf"),RouteTraceNtf:p("org.arl.unet.net.RouteTraceNtf"),FecDecodeReq:p("org.arl.unet.phy.FecDecodeReq"),RxJanusFrameNtf:p("org.arl.unet.phy.RxJanusFrameNtf"),TxJanusFrameReq:p("org.arl.unet.phy.TxJanusFrameReq"),BadFrameNtf:p("org.arl.unet.phy.BadFrameNtf"),BadRangeNtf:p("org.arl.unet.phy.BadRangeNtf"),ClearSyncReq:p("org.arl.unet.phy.ClearSyncReq"),CollisionNtf:p("org.arl.unet.phy.CollisionNtf"),RxFrameNtf:p("org.arl.unet.phy.RxFrameNtf",A),RxFrameStartNtf:p("org.arl.unet.phy.RxFrameStartNtf"),SyncInfoReq:p("org.arl.unet.phy.SyncInfoReq"),SyncInfoRsp:p("org.arl.unet.phy.SyncInfoRsp"),TxFrameNtf:p("org.arl.unet.phy.TxFrameNtf"),TxFrameReq:p("org.arl.unet.phy.TxFrameReq",y),TxFrameStartNtf:p("org.arl.unet.phy.TxFrameStartNtf"),TxRawFrameReq:p("org.arl.unet.phy.TxRawFrameReq"),AddressAllocReq:p("org.arl.unet.addr.AddressAllocReq"),AddressAllocRsp:p("org.arl.unet.addr.AddressAllocRsp"),AddressResolutionReq:p("org.arl.unet.addr.AddressResolutionReq"),AddressResolutionRsp:p("org.arl.unet.addr.AddressResolutionRsp"),BasebandSignal:p("org.arl.unet.bb.BasebandSignal"),RecordBasebandSignalReq:p("org.arl.unet.bb.RecordBasebandSignalReq"),RxBasebandSignalNtf:p("org.arl.unet.bb.RxBasebandSignalNtf",N),TxBasebandSignalReq:p("org.arl.unet.bb.TxBasebandSignalReq",N),LinkStatusNtf:p("org.arl.unet.link.LinkStatusNtf"),RangeNtf:p("org.arl.unet.localization.RangeNtf"),RangeReq:p("org.arl.unet.localization.RangeReq"),BeaconReq:p("org.arl.unet.localization.BeaconReq"),RespondReq:p("org.arl.unet.localization.RespondReq"),InterrogationNtf:p("org.arl.unet.localization.InterrogationNtf"),ReservationAcceptReq:p("org.arl.unet.mac.ReservationAcceptReq"),ReservationCancelReq:p("org.arl.unet.mac.ReservationCancelReq"),ReservationReq:p("org.arl.unet.mac.ReservationReq"),ReservationRsp:p("org.arl.unet.mac.ReservationRsp"),ReservationStatusNtf:p("org.arl.unet.mac.ReservationStatusNtf"),RxAckNtf:p("org.arl.unet.mac.RxAckNtf"),TxAckReq:p("org.arl.unet.mac.TxAckReq"),RemoteExecReq:p("org.arl.unet.remote.RemoteExecReq"),RemoteFailureNtf:p("org.arl.unet.remote.RemoteFailureNtf"),RemoteFileGetReq:p("org.arl.unet.remote.RemoteFileGetReq"),RemoteFileNtf:p("org.arl.unet.remote.RemoteFileNtf"),RemoteFilePutReq:p("org.arl.unet.remote.RemoteFilePutReq"),RemoteSuccessNtf:p("org.arl.unet.remote.RemoteSuccessNtf"),RemoteTextNtf:p("org.arl.unet.remote.RemoteTextNtf"),RemoteTextReq:p("org.arl.unet.remote.RemoteTextReq"),AddScheduledSleepReq:p("org.arl.unet.scheduler.AddScheduledSleepReq"),GetSleepScheduleReq:p("org.arl.unet.scheduler.GetSleepScheduleReq"),RemoveScheduledSleepReq:p("org.arl.unet.scheduler.RemoveScheduledSleepReq"),SleepScheduleRsp:p("org.arl.unet.scheduler.SleepScheduleRsp"),WakeFromSleepNtf:p("org.arl.unet.scheduler.WakeFromSleepNtf"),ClearStateReq:p("org.arl.unet.state.ClearStateReq"),SaveStateReq:p("org.arl.unet.state.SaveStateReq")};function b(e){let t=e*Math.PI/180,s=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),s]}class O extends h{constructor(e,t,s,r=!0){e instanceof h?super(e.getName(),e.topic,e.owner):super(e,t,s),this.greedy=r,this.cache={}}async set(e,t,s=-1,r=5e3){let n=await super.set(e,t,s,r);this._updateCache(e,n,s)}async get(e,t=-1,s=5e3,r=5e3){if(this._isCached(e,t,r))return this._getCache(e,t);if(!this.greedy||Array.isArray(e)&&e.includes("name")||"name"==e){let r=await super.get(e,t,s);return this._updateCache(e,r,t),r}{let r=await super.get(null,t,s);if(this._updateCache(null,r,t),!r)return Array.isArray(e)?new Array(e.length).fill(null):null;if(Array.isArray(e))return e.map((e=>{let t=Object.keys(r).find((t=>this._toNamed(t)===e));return t?r[t]:null}));{let t=Object.keys(r).find((t=>this._toNamed(t)===e));return t?r[t]:null}}}_updateCache(e,t,s){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[s.toString()]&&(this.cache[s.toString()]={});let r=this.cache[s.toString()];for(let s=0;s<e.length;s++)void 0===r[e[s]]&&(r[e[s]]={}),r[e[s]].value=t[s],r[e[s]].ctime=Date.now()}_isCached(e,t,s){if(s<=0)return!1;if(null==e)return!1;let r=this.cache[t.toString()];if(!r)return!1;Array.isArray(e)||(e=[e]);return e.every((e=>(e=this._toNamed(e))in r&&Date.now()-r[e].ctime<=s))}_getCache(e,t){let s=this.cache[t.toString()];return s?Array.isArray(e)?e.map((e=>e in s?s[e].value:null)):e in s?s[e].value:null:null}_toNamed(e){const t=e.lastIndexOf(".");return t<0?e:e.slice(t+1)}}class T extends class{constructor(e={},s,r="/ws/",n=1e3){("string"==typeof e||e instanceof String)&&(e={hostname:e,port:s||v.location.port,pathname:r,timeout:n},console.warn("Deprecated use of Gateway constructor")),e=Object.assign({},m,e);var i=_;i.hostname=e.hostname,i.port=e.port,i.pathname=e.pathname;let o=this._getGWCache(i);if(o)return o;this._timeout=e.timeout,this._keepAlive=e.keepAlive,this._queueSize=e.queueSize,this.pending={},this.subscriptions={},this.listener={},this.eventListeners={},this.queue=[],this.debug=!1,this.aid=new h(t?"WebGW-":"NodeGW-"+f(4)),this.connector=this._createConnector(i),this._addGWCache(this)}_sendEvent(e,t){Array.isArray(this.eventListeners[e])&&this.eventListeners[e].forEach((e=>{e&&"[object Function]"==={}.toString.call(e)&&e(t)}))}_onMsgRx(e){var t;this.debug&&console.log("< "+e),this._sendEvent("rx",e);try{t=JSON.parse(e,R)}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 s=!1;if(Array.isArray(this.eventListeners.message))for(var r=0;r<this.eventListeners.message.length;r++)if(this.eventListeners.message[r](e)){s=!0;break}for(var n in this.listener)if(this.listener[n](e)){s=!0;break}s||(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=f(8),new Promise((t=>{let s=setTimeout((()=>{delete this.pending[e.id],this.debug&&console.log("Receive Timeout : "+e),t()}),8*this._timeout);this.pending[e.id]=e=>{clearTimeout(s),t(e)},this._msgTx.call(this,e)||(clearTimeout(s),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:e.port,pathname:e.pathname,keepAlive:this._keepAlive});else{if(!e.protocol.startsWith("tcp"))return null;t=new l({hostname:e.hostname,port:e.port,keepAlive:this._keepAlive})}return t.setReadCallback(this._onMsgRx.bind(this)),t.addConnectionListener((e=>{1==e&&(this.flush(),this.connector.write('{"alive": true}'),this._update_watch())})),t}_matchMessage(e,t){return"string"==typeof e||e instanceof String?"inReplyTo"in t&&t.inReplyTo==e:Object.prototype.hasOwnProperty.call(e,"msgID")?"inReplyTo"in t&&t.inReplyTo==e.msgID:"Message"==e.__proto__.name||"Message"==e.__proto__.__proto__.name?e.__clazz__==t.__clazz__:"function"==typeof e?e(t):t instanceof e}_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(!v.fjage||!v.fjage.gateways)return null;var t=v.fjage.gateways.filter((t=>t.connector.url.toString()==e.toString()));return t.length?t[0]:null}_addGWCache(e){v.fjage&&v.fjage.gateways&&v.fjage.gateways.push(e)}_removeGWCache(e){if(v.fjage&&v.fjage.gateways){var t=v.fjage.gateways.indexOf(e);null!=t&&v.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 s=this.eventListeners[e].indexOf(t);s>=0&&this.eventListeners[e].splice(s,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 h(e,!1,this)}topic(e,t){return"string"==typeof e||e instanceof String?new h(e,!0,this):e instanceof h?e.isTopic()?e:new h(e.getName()+(t?"__"+t:"")+"__ntf",!0,this):void 0}subscribe(e){e.isTopic()||(e=new h(e.getName()+"__ntf",!0,this)),this.subscriptions[e.toJSON()]=!0,this._update_watch()}unsubscribe(e){e.isTopic()||(e=new h(e.getName()+"__ntf",!0,this)),delete this.subscriptions[e.toJSON()],this._update_watch()}async agentForService(e){let t={action:"agentForService",service:e},s=await this._msgTxRx(t);if(s&&s.agentID)return new h(s.agentID,!1,this)}async agentsForService(e){let t={action:"agentsForService",service:e},s=await this._msgTxRx(t),r=[];if(!s||!Array.isArray(s.agentIDs))return r;for(var n=0;n<s.agentIDs.length;n++)r.push(new h(s.agentIDs[n],!1,this));return r}send(e){e.sender=this.aid.toJSON(),""==e.perf&&(e.__clazz__.endsWith("Req")?e.perf=u.REQUEST:e.perf=u.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((s=>{let r=this._getMessageFromQueue.call(this,e);if(r)return void s(r);if(0==t)return this.debug&&console.log("Receive Timeout : "+e),void s();let n,i=f(8);t>0&&(n=setTimeout((()=>{delete this.listener[i],this.debug&&console.log("Receive Timeout : "+e),s()}),t)),this.listener[i]=t=>!!this._matchMessage(e,t)&&(n&&clearTimeout(n),delete this.listener[i],s(t),!0)}))}close(){this.connector.close(),this._removeGWCache(this)}}{agent(e,t=!0,s=!0){const r=super.agent(e);return t?new O(r,null,null,s):r}topic(e,t,s=!0,r=!0){const n=super.topic(e,t);return s?new O(n,null,null,r):n}async agentForService(e,t=!0,s=!0){const r=await super.agentForService(e);return r&&t?new O(r,null,null,s):r}async agentsForService(e,t=!0,s=!0){const r=await super.agentsForService(e);return t?r.map((e=>new O(e,null,null,s))):r}}const E=k.AddressResolutionReq,C=k.DatagramReq,q=k.DatagramNtf,F=k.RxFrameNtf;e.AgentID=h,e.CachingAgentID=O,e.Gateway=T,e.Message=g,e.MessageClass=p,e.Performative=u,e.Protocol=w,e.Services=d,e.UnetMessages=k,e.UnetSocket=class{constructor(e,t,s=""){return(async()=>{this.gw=new T({hostname:e,port:t,path:s}),this.localProtocol=-1,this.remoteAddress=-1,this.remoteProtocol=w.DATA,this.timeout=0,this.provider=null;return(await this.gw.agentsForService(d.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==w.DATA||e>=w.USER&&e<=w.MAX)&&(this.localProtocol=e,!0)}unbind(){this.localProtocol=-1}isBound(){return this.localProtocol>=0}connect(e,t){return e>=0&&(t==w.DATA||t>=w.USER&&t<=w.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(d.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,s=this.remoteProtocol){if(t<0||null==this.gw)return!1;var r;if(Array.isArray(e))(r=new C).data=e,r.to=t,r.protocol=s;else{if(!(e instanceof C))return!1;r=e}let n=r.protocol;if(n!=w.DATA&&(n<w.USER||n>w.MAX))return!1;if(null==r.recipient){if(null==this.provider&&(this.provider=await this.gw.agentForService(d.TRANSPORT)),null==this.provider&&(this.provider=await this.gw.agentForService(d.ROUTING)),null==this.provider&&(this.provider=await this.gw.agentForService(d.LINK)),null==this.provider&&(this.provider=await this.gw.agentForService(d.PHYSICAL)),null==this.provider&&(this.provider=await this.gw.agentForService(d.DATAGRAM)),null==this.provider)return!1;r.recipient=this.provider}const i=await this.gw.request(r,1e3);return null!=i&&i.perf==u.AGREE}async receive(){return null==this.gw?null:await this.gw.receive((e=>{if(e.__clazz__!=q.__clazz__&&e.__clazz__!=F.__clazz__)return!1;let t=e.protocol;return(t==w.DATA||t>=w.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(d.ADDRESS_RESOLUTION);if(null==t)return null;const s=new E(e);s.name=e,s.recipient=t;const r=await this.gw.request(s,1e3);return null!=r&&Object.prototype.hasOwnProperty.call(r,"address")?r.address:null}},e.toGps=function(e,t,s){let r=[],[n,i]=b(e[0]);return r[1]=t/n+e[1],r[0]=s/i+e[0],r},e.toLocal=function(e,t,s){let r=[],[n,i]=b(e[0]);return r[0]=(s-e[1])*n,r[1]=(t-e[0])*i,r}}));
2
2
  //# sourceMappingURL=unetjs.min.js.map