import io from 'socket.io-client'; import { ref, onMounted, onUnmounted, onBeforeUnmount } from 'vue'; import useAppStore from '@/store/modules/app'; // import router from '@/router'; // let socketHand: any = null; //ws实例对象 // socketHand = io(address + '/', { // transports: ['websocket', 'polling'], // query: { // type: 'hand', // Authorization: token ? myToken : '' // } // }); export function useSunshineRunSocket() { const address: any = import.meta.env.VITE_APP_BASE_API; const token: any = localStorage.getItem('token'); const deviceid: any = localStorage.getItem('deviceid'); const myToken: any = 'JWT ' + token; // let socketHand: any = useAppStore().getSocketHand() || null; //ws实例对象 // if (socketHand == null) { // socketHand = io(address + '/', { // transports: ['websocket', 'polling'], // query: { // type: 'hand', // Authorization: token ? myToken : '', // } // }); // useAppStore().setSocketHand(socketHand); // } let socketHand: any = null; //ws实例对象 socketHand = io(address + '/', { transports: ['websocket', 'polling'], query: { type: 'sunshineRun', Authorization: token ? myToken : '' } }); function sunshineRunWs(callback: any) { if (socketHand == null) { return false; } callback({ wksid: socketHand.id }); socketHand.on('connect', (e: any) => { callback(e); }); socketHand.on('my_response', (e: any) => { callback(e); }); socketHand.on('sunlight_result', (e: any) => { callback(e); }); socketHand.on('disconnect', (e: any) => { callback(e); }); } /** * 发送消息 */ function sendMessage(type: string, data: any, callback?: () => void) { if (socketHand == null) { return false; } if (socketHand.connected) { callback = callback || function () {}; socketHand.emit(type, data, callback); } } /** * 开始连接 */ function startConnect(data?: any, callback?: any) { sendMessage( 'fe_sunlight_init', { cmd:"sunlight_init" }, () => {} ); } onBeforeUnmount(() => { // if (socketHand) { // // if(['/gesture'].includes(router.currentRoute.value.path)){ // // socketHand.close(); // // socketHand = null; // // } // socketHand = null; // } // getClearTimer(); if (socketHand) { socketHand.close(); socketHand = null; } }); return { sunshineRunWs, sendMessage, startConnect }; }