sunshineRunWs.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import io from 'socket.io-client';
  2. import { ref, onMounted, onUnmounted, onBeforeUnmount } from 'vue';
  3. import useAppStore from '@/store/modules/app';
  4. // import router from '@/router';
  5. // let socketHand: any = null; //ws实例对象
  6. // socketHand = io(address + '/', {
  7. // transports: ['websocket', 'polling'],
  8. // query: {
  9. // type: 'hand',
  10. // Authorization: token ? myToken : ''
  11. // }
  12. // });
  13. export function useSunshineRunSocket() {
  14. const address: any = import.meta.env.VITE_APP_BASE_API;
  15. const token: any = localStorage.getItem('token');
  16. const deviceid: any = localStorage.getItem('deviceid');
  17. const myToken: any = 'JWT ' + token;
  18. // let socketHand: any = useAppStore().getSocketHand() || null; //ws实例对象
  19. // if (socketHand == null) {
  20. // socketHand = io(address + '/', {
  21. // transports: ['websocket', 'polling'],
  22. // query: {
  23. // type: 'hand',
  24. // Authorization: token ? myToken : '',
  25. // }
  26. // });
  27. // useAppStore().setSocketHand(socketHand);
  28. // }
  29. let socketHand: any = null; //ws实例对象
  30. socketHand = io(address + '/', {
  31. transports: ['websocket', 'polling'],
  32. query: {
  33. type: 'sunshineRun',
  34. Authorization: token ? myToken : ''
  35. }
  36. });
  37. function sunshineRunWs(callback: any) {
  38. if (socketHand == null) {
  39. return false;
  40. }
  41. callback({
  42. wksid: socketHand.id
  43. });
  44. socketHand.on('connect', (e: any) => {
  45. callback(e);
  46. });
  47. socketHand.on('my_response', (e: any) => {
  48. callback(e);
  49. });
  50. socketHand.on('sunlight_result', (e: any) => {
  51. callback(e);
  52. });
  53. socketHand.on('disconnect', (e: any) => {
  54. callback(e);
  55. });
  56. }
  57. /**
  58. * 发送消息
  59. */
  60. function sendMessage(type: string, data: any, callback?: () => void) {
  61. if (socketHand == null) {
  62. return false;
  63. }
  64. if (socketHand.connected) {
  65. callback = callback || function () {};
  66. socketHand.emit(type, data, callback);
  67. }
  68. }
  69. /**
  70. * 开始连接
  71. */
  72. function startConnect(data?: any, callback?: any) {
  73. sendMessage(
  74. 'fe_sunlight_init',
  75. {
  76. cmd:"sunlight_init"
  77. },
  78. () => {}
  79. );
  80. }
  81. onBeforeUnmount(() => {
  82. // if (socketHand) {
  83. // // if(['/gesture'].includes(router.currentRoute.value.path)){
  84. // // socketHand.close();
  85. // // socketHand = null;
  86. // // }
  87. // socketHand = null;
  88. // }
  89. // getClearTimer();
  90. if (socketHand) {
  91. socketHand.close();
  92. socketHand = null;
  93. }
  94. });
  95. return { sunshineRunWs, sendMessage, startConnect };
  96. }