import { defineStore } from 'pinia' import Socket from '@/socket' import moment from 'moment' import { useSettingStore } from './setting' import { useUserStore } from './user' import { useOperatorStore } from './operator' import { useDeviceStore } from './device' import { useTestStore } from './test' import { useAuditStore } from './audit' import { useFormulaStore } from './formula' import { useHistoryStore } from './history' import { useEchartsStore } from './echarts' import { useRunningStore } from './running' import { showSuccessToast, showFailToast } from 'vant' import { saveEchartsDataToLocal } from '@/utils' export const useWebSocketStore = defineStore({ id: 'websocket', // id必填,且需要唯一 // state state: () => { return { // 命令websocket 实例 socketCommandInstance: null, // 事件上报websocket 实例 socketEventInstance: null, // Event Handlers eventHandlers : {}, // Call ID Counter callIdCounter : 0, // Call Resolve Handler Map callPromiseHandlers : {}, // Call Param Merge Commands callparamMergeCmds : [ 'cleanDisinfectionRecord', 'startDisinfection', 'changeDisinfectionParameter','setSettingVal' ], } }, // actions actions: { // register event handler registerEventHandler( event, handler ) { this.eventHandlers[event] = this.eventHandlers[event] || []; this.eventHandlers[event].push(handler); }, initCommandSocket() { const url = import.meta.env.VITE_BASE_WS1_URL const init = new Socket(url) const settingStore = useSettingStore() const userStore = useUserStore() const testStore = useTestStore() const deviceStore = useDeviceStore() const operatorStore = useOperatorStore() const echartsStore = useEchartsStore() const auditStore = useAuditStore() const formulaStore = useFormulaStore() const runningStore = useRunningStore() const historyStore = useHistoryStore() init.connect() let $this = this; init.ws.onmessage = function (ev) { const { messageId, timeStamp } = JSON.parse(ev.data) // 优先处理call-response if ( undefined !== $this.callPromiseHandlers[messageId] ) { let response = JSON.parse(ev.data); const handler = $this.callPromiseHandlers[messageId]; delete $this.callPromiseHandlers[messageId]; console.log(`[Call Response : ${messageId}] ${handler.message.command} => ${JSON.stringify(response)}`); if ( 0 === response.ackcode ) { handler.resolve(response); } else { handler.reject(response.ackDisplayInfo); } return; } console.log(JSON.parse(ev.data)) switch (messageId) { case 'getState': // 初始化完毕 const { state } = JSON.parse(ev.data) const { disinfectionWorkState, disinfectionState, preHeat, preHeatRaminTimeS, estimatedRemainingTimeS, disinfection_id, isLogin, permissionLevel, sensor_data, drainingWorkState, replenishingFluidsWorkState, } = state || {} if (!isLogin) { window.location.href = 'http://127.0.0.1/#/' return } const { h2o2_1, h2o2_2, h2o2_3, humid_1, humid_2, humid_3, saturation_1, saturation_2, saturation_3, temp_1, temp_2, temp_3, airCompressor, disinfectant_volume, heatingStrip, airBlower, sprinklerPump, chargingPump, waterImmersionSensor1, waterImmersionSensor2, chargingPumpRPM, sprinklerPumpRPM, sprinklerPumpGPM, pressure, } = sensor_data const { nowlog, targetlog } = disinfectionState || {} deviceStore.updateTargetLog(targetlog) // 必须开始的时候才改变log 否则不懂 if ([1, 2, 3, 4].includes(disinfectionWorkState)) { localStorage.setItem('logVal', targetlog) } deviceStore.updateNowLog(nowlog) if ([1, 2, 3, 4].includes(disinfectionWorkState)) { operatorStore.updateShowStartReady(false) } else { operatorStore.updateStopReady(false) } settingStore.updateSprinklerPumpGPM(sprinklerPumpGPM) settingStore.updateChargingPumpRPM(chargingPumpRPM) settingStore.updateSprinklerPumpRPM(sprinklerPumpRPM) operatorStore.updateDrainingWorkState(drainingWorkState) operatorStore.updateReplenishingFluidsWorkState( replenishingFluidsWorkState, ) testStore.updateWaterImmersionSensor1( waterImmersionSensor1 == 0 ? false : true, ) testStore.updateWaterImmersionSensor2( waterImmersionSensor2 == 0 ? false : true, ) // 将sensor_data中的数据更新到store中 testStore.updateAirCompressorObj(airCompressor) testStore.updateAirBlowerObj(airBlower) testStore.updateHeatingStripObj(heatingStrip) testStore.updateSprinklerPump(sprinklerPump) testStore.updateChargingPump(chargingPump) testStore.updateAllPressure(pressure) settingStore.updateDeviceIp('192.168.8.10') deviceStore.updateDisinfectantCapacity(disinfectant_volume) deviceStore.updateBinTemperature(temp_1) deviceStore.updateBinHumidity(humid_1) deviceStore.updateBinHP(h2o2_1) deviceStore.updateBinSaturation(saturation_1) deviceStore.updateEnvirTemperature1(temp_2) deviceStore.updateEnvirHumidity1(humid_2) deviceStore.updateEnvirHP1(h2o2_2) deviceStore.updateEnvSaturation1(saturation_2) deviceStore.updateEnvirTemperature2(temp_3) deviceStore.updateEnvirHumidity2(humid_3) deviceStore.updateEnvirHP2(h2o2_3) deviceStore.updateEnvSaturation2(saturation_3) userStore.updatePermission(permissionLevel) settingStore.updateInitLoading() operatorStore.updatePreHeatRaminTimeS(preHeatRaminTimeS) operatorStore.updatePreHeat(preHeat) operatorStore.updateDisinfectStatus(disinfectionWorkState) operatorStore.updateEstimatedRemainingTimeS(estimatedRemainingTimeS) operatorStore.updateDisinfectionId(disinfection_id) // 将sensor_data中的数据更新到store中 if ([1, 2, 3, 4].includes(operatorStore.disinfectStatus)) { saveEchartsDataToLocal( moment().utcOffset(8).format('HH:mm'), [temp_1, humid_1, h2o2_1, saturation_1], [temp_2, humid_2, h2o2_2, saturation_2], [temp_3, humid_3, h2o2_3, saturation_3], ) echartsStore.updateBinCharts( JSON.parse(localStorage.getItem('bin')), ) echartsStore.updateEnvir1Charts( JSON.parse(localStorage.getItem('envir1')), ) echartsStore.updateEnvir2Charts( JSON.parse(localStorage.getItem('envir2')), ) } break case 'getAllUser': const { dbval } = JSON.parse(ev.data) console.log(dbval, 'dbva;') userStore.updateUserList(dbval) break case 'chpasswd': const { ackcode: chpasswdCode } = JSON.parse(ev.data) if (chpasswdCode != 0) { // 修改失败 showFailToast('修改失败') } else { showSuccessToast('修改成功') } break case 'startReplenishingFluids': const { ackcode: startReplenishingCode } = JSON.parse(ev.data) if (startReplenishingCode == 0) { operatorStore.updateReplenishingFluidsWorkState(1) } case 'startDraining': const { ackcode: startDrainingCode } = JSON.parse(ev.data) if (startDrainingCode == 0) { operatorStore.updateDrainingWorkState(1) } case 'startDisinfection': break case 'disinfectionLogsGetList': const { ackcode: disinfectionLogsCode, disinfectionLogList } = JSON.parse(ev.data) || {} if (disinfectionLogsCode == 0) { historyStore.updateHistoryDataList(disinfectionLogList) } break case 'disinfectionLogsGetRecord': const { ackcode: logDetailCode, record } = JSON.parse(ev.data) || {} const { content } = record || {} if (logDetailCode == 0) { historyStore.updateDetailData(content) } break case 'stopDisinfection': break case 'exportUserBehaviorRecord': settingStore.updateExportLoading(false) const { ackcode: exportUserCode } = JSON.parse(ev.data) || {} if (exportUserCode == 0) { showSuccessToast('导出成功') } if (exportUserCode == 3000) { showFailToast('未检测到U盘') } if (exportUserCode != 0 && exportUserCode != 3000) { showFailToast('导出错误') } break case 'exportDisinfectionRecord': settingStore.updateExportLoading(false) const { ackcode: disinfectionRecordCode } = JSON.parse(ev.data) || {} if (disinfectionRecordCode == 0) { showSuccessToast('导出成功') } if (disinfectionRecordCode == 3000) { showFailToast('未检测到U盘') } if (disinfectionRecordCode != 0 && disinfectionRecordCode != 3000) { showFailToast('导出错误') } break case 'getAllFormula': const { formula } = JSON.parse(ev.data) || {} const { formulas } = formula || {} formulaStore.updateFormulaList(formulas || []) break case 'getUserBehaviorRecordDescJson': const { records } = JSON.parse(ev.data) || {} const { iterms, page, total, totalpage } = records || {} auditStore.updateAuditList(iterms || []) auditStore.updateTotalPage(totalpage) auditStore.updateTotal(total) auditStore.updatePage(page) auditStore.updateAuditLoading(false) break case 'getDisinfectionConfig': const { disinfectionConfig } = JSON.parse(ev.data) runningStore.updateDisinfectionConfig(disinfectionConfig) break case 'login': const { ackcode: loginCode } = JSON.parse(ev.data) || {} if (loginCode == 50001) { showFailToast('用户不存在') } if (loginCode == 5000) { showFailToast('密码错误') } break case 'getAllRecords': break case 'getAllSetting': const { dbval: allSetting } = JSON.parse(ev.data) console.log(JSON.parse(ev.data)) settingStore.updateAllSettingList(allSetting) break default: break } } this.socketCommandInstance = init }, sendCommandMsg(message) { this.socketCommandInstance?.msg(message) }, // call and wait for response call( command, params=null ) { this.callIdCounter += 1; if ( this.callIdCounter > 1000000 ) { this.callIdCounter = 0; } const callId = `call-${this.callIdCounter}`; return new Promise(( resolve, reject ) => { let message = {}; message.command = command; message.messageId = callId; if ( null !== params ) { if ( this.callparamMergeCmds.includes(command) ) { message = { ...message, ...params }; } else { message.params = params; } } this.callPromiseHandlers[callId] = { resolve, reject, message }; console.log(`[Call Request : ${callId}] ${command}(${JSON.stringify(params)})`); this.sendCommandMsg(message); }); }, initEventSocket() { const url = import.meta.env.VITE_BASE_WS2_URL const init = new Socket(url) init.connect() const deviceStore = useDeviceStore() const testStore = useTestStore() const settingStore = useSettingStore() const operatorStore = useOperatorStore() const echartsStore = useEchartsStore() let $this = this; init.ws.onmessage = function (ev) { // console.log(JSON.parse(ev.data)) const { command, timeStamp } = JSON.parse(ev.data) if ( undefined !== $this.eventHandlers[command] ) { let data = JSON.parse(ev.data); data = data.data; for ( const handler of $this.eventHandlers[command] ) { handler(data); } return ; } switch (command) { case 'RealtimeSensorDataReport': const { sensor_data } = JSON.parse(ev.data) const { h2o2_1, h2o2_2, h2o2_3, humid_1, humid_2, humid_3, temp_1, temp_2, temp_3, saturation_1, saturation_2, saturation_3, airCompressor, disinfectant_volume, heatingStrip, airBlower, sprinklerPump, chargingPump, waterImmersionSensor1, waterImmersionSensor2, } = sensor_data // 将sensor_data中的数据更新到store中 testStore.updateWaterImmersionSensor1( waterImmersionSensor1 == 0 ? false : true, ) testStore.updateWaterImmersionSensor2( waterImmersionSensor2 == 0 ? false : true, ) testStore.updateAirCompressorObj(airCompressor) testStore.updateAirBlowerObj(airBlower) testStore.updateHeatingStripObj(heatingStrip) testStore.updateSprinklerPump(sprinklerPump) testStore.updateChargingPump(chargingPump) settingStore.updateDeviceIp('192.168.8.10') deviceStore.updateDisinfectantCapacity(disinfectant_volume) deviceStore.updateBinTemperature(temp_1) deviceStore.updateBinHumidity(humid_1) deviceStore.updateBinHP(h2o2_1) deviceStore.updateBinSaturation(saturation_1) deviceStore.updateEnvirTemperature1(temp_2) deviceStore.updateEnvirHumidity1(humid_2) deviceStore.updateEnvirHP1(h2o2_2) deviceStore.updateEnvirTemperature2(temp_3) deviceStore.updateEnvirHumidity2(humid_3) deviceStore.updateEnvirHP2(h2o2_3) // 对数据进行处理 并存入到localstorage中 if ([1, 2, 3, 4].includes(operatorStore.disinfectStatus)) { saveEchartsDataToLocal( moment().utcOffset(8).format('HH:mm'), [temp_1, humid_1, h2o2_1, saturation_1], [temp_2, humid_2, h2o2_2, saturation_2], [temp_3, humid_3, h2o2_3, saturation_3], ) echartsStore.updateBinCharts( JSON.parse(localStorage.getItem('bin')), ) echartsStore.updateEnvir1Charts( JSON.parse(localStorage.getItem('envir1')), ) echartsStore.updateEnvir2Charts( JSON.parse(localStorage.getItem('envir2')), ) } break default: break } } this.socketEventInstance = init }, sendEventMsg(message) { this.socketEventInstance?.msg(message) }, }, })