import{L as t}from"./index-BRshd4I5.js";const s={HEARTBEAT_REQ:"10001",HEARTBEAT_RESP:"10002",JOINT_ENABLE:"10020",SINGLE_AXIS_ANGLE:"10021",MULTI_AXIS_ANGLE:"10022",SET_SINGLE_AXIS_PARM:"10023",ZERO_CALI:"1002F",GET_MOTOR_INFO:"10031",GET_MOTOR_ALL_INFO:"10032",GET_SINGLE_PARM:"10033",FAULT_REPORT:"1003F",CAN2:"10052",BATTERY:"10043"};class e{constructor(t="ws://192.168.0.3:3001/jointadjustment"){this.url=t,this.socketTask=null,this.isConnected=!1,this.isRunning=!0,this.maxRetry=10,this.retryDelayList=[1e3,3e3,5e3,1e4],this.currentRetry=0,this.heartbeatInterval=3e4,this.heartbeatTimeout=3,this.heartbeatMissCount=0,this.heartbeatTimer=null,this.onMessageCallback=null}buildRequest(t,s={}){return JSON.stringify({cmd:t,data:s,timestamp:Date.now()})}sendCmd(t,s={}){if(this.isConnected&&this.socketTask)try{const e=this.buildRequest(t,s);this.socketTask.send({data:e})}catch(e){console.log("[发送异常]",e)}else console.log("[发送失败] 未连接")}startHeartbeat(){this.stopHeartbeat(),this.heartbeatMissCount=0,this.heartbeatTimer=setInterval((()=>{this.heartbeatMissCount++,console.log("[心跳] 发送,丢失计数:",this.heartbeatMissCount),this.sendCmd(s.HEARTBEAT_REQ),this.heartbeatMissCount>=this.heartbeatTimeout&&(console.log("[心跳] 超时,重连"),this.closeSocket(),this.reconnect())}),this.heartbeatInterval)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}connect(){this.isRunning&&(this.socketTask&&this.closeSocket(),console.log("[连接] 连接中...",this.url),this.socketTask=t({url:this.url,success:()=>{},fail:t=>{console.log("[连接失败]",t),this.reconnect()}}),this.socketTask.onOpen((()=>{console.log("[连接成功]"),this.isConnected=!0,this.currentRetry=0,this.startHeartbeat()})),this.socketTask.onMessage((t=>{try{const s=JSON.parse(t.data);this.handleMessage(s)}catch(s){console.log("消息解析失败")}})),this.socketTask.onClose((()=>{console.log("[连接关闭]"),this.isConnected=!1,this.stopHeartbeat(),this.reconnect()})),this.socketTask.onError((t=>{console.log("[错误]",t),this.isConnected=!1,this.reconnect()})))}handleMessage(t){if(t.cmd===s.HEARTBEAT_RESP)return this.heartbeatMissCount=0,void console.log("[心跳回执] 正常");this.onMessageCallback&&this.onMessageCallback(t)}reconnect(){if(!this.isRunning||this.isConnected)return;if(this.currentRetry>=this.maxRetry)return void console.log("已达最大重连次数");this.currentRetry++;const t=Math.min(this.currentRetry-1,this.retryDelayList.length-1),s=this.retryDelayList[t];console.log(`[${this.currentRetry}/${this.maxRetry}] ${s}ms 后重连`),setTimeout((()=>{this.connect()}),s)}closeSocket(){if(this.isRunning=!1,this.isConnected=!1,this.stopHeartbeat(),this.socketTask){try{this.socketTask.close()}catch{}this.socketTask=null}}}export{s as C,e as J};