1
0
Files
build.ems/build/usr/local/omc/htdocs/front/js/ws-websocket.Bq7KFeli.js
2024-10-25 14:59:47 +08:00

2 lines
2.5 KiB
JavaScript

import{H as a,I as i,J as l,K as h,L as u}from"../index.D-NvtsOM.js";class m{ws=null;options=null;heartInterval=0;reconnectTimeout=0;constructor(e){if(!window.WebSocket){console.error("Sorry! Browser does not support websocket");return}e&&this.connect(e)}connect(e){this.options=e;try{if(!e.url.startsWith("ws")){const t=e.url.startsWith("/")?e.url:`/${e.url}`,r=a("wsUrl")||"/omc-api";if(r.startsWith("ws"))e.url=`${r}${t}`;else if(r.startsWith("https"))e.url=`${r.replace("https","wss")}${t}`;else if(r.startsWith("http"))e.url=`${r.replace("http","ws")}${t}`;else{const n=window.location.protocol==="https:"?"wss://":"ws://";e.url=`${n}${location.host}${r}${t}`}}let c=Object.assign({},e.params,{[i]:l(),language:h(u)||"en_US"}),o="";for(const t in c){const r=c[t];r===""||r===void 0||(o+=`&${encodeURIComponent(t)}=${encodeURIComponent(r)}`)}o&&o.startsWith("&")&&(e.url=`${e.url}?${o.substring(1)}`);const s=new WebSocket(e.url,"omc-ws");s.onopen=t=>{e.heartTimer&&e.heartTimer>0&&this.heartCheck(e.heartTimer),typeof e.onopen=="function"&&e.onopen(t)},s.onmessage=t=>{if(t.type==="message"){const r=t.data;try{const n=JSON.parse(r);typeof e.onmessage=="function"&&e.onmessage(n)}catch(n){console.error("websocket message formatting error",n)}}},s.onclose=t=>{typeof e.onclose=="function"&&e.onclose(t.code)},s.onerror=t=>{console.error("websocket connection anomaly",t),typeof e.onerror=="function"&&e.onerror(t),e.reconnectTimer&&e.reconnectTimer>0&&this.reconnect(e.reconnectTimer)},this.ws=s}catch(c){typeof e.onerror=="function"&&e.onerror(c),e.reconnectTimer&&e.reconnectTimer>0&&this.reconnect(e.reconnectTimer)}}send(e){return this.ws?this.ws.readyState===WebSocket.CLOSED||this.ws.readyState===WebSocket.CLOSING?(this.close(),!1):(this.ws.readyState===WebSocket.CONNECTING&&setTimeout(()=>{this.ws&&this.ws.send(JSON.stringify(e))},1e3),this.ws.readyState===WebSocket.OPEN?(this.ws.send(JSON.stringify(e)),!0):!1):(console.warn("websocket unavailable"),!1)}state(){return this.ws?this.ws.readyState:-1}close(){if(this.heartInterval&&clearInterval(this.heartInterval),this.reconnectTimeout&&clearTimeout(this.reconnectTimeout),!this.ws){console.warn("websocket unavailable");return}this.ws.close(1e3,"user initiated closure")}heartCheck(e){this.heartInterval=window.setInterval(()=>{this.send({requestId:`${Date.now()}`,type:"ping"})},e)}reconnect(e){this.reconnectTimeout>0||(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=window.setTimeout(()=>{this.options&&(this.connect(this.options),this.reconnectTimeout=0)},e))}}export{m as W};