Browse Source

升级为vue3

Caner 2 years ago
parent
commit
2b3e700462

+ 1 - 0
.env

@@ -0,0 +1 @@
+VITE_PROXY_URL=http://114.114.114.114:28181

+ 4 - 0
.eslintignore

@@ -0,0 +1,4 @@
+# 排除eslint检查文件
+/dist
+/public
+/main.js

+ 64 - 0
.eslintrc.json

@@ -0,0 +1,64 @@
+{
+  "root": true,
+  "env": {
+    "node": true,
+    "browser": true,
+    "es2021": true
+  },
+  "parserOptions": {
+    "ecmaVersion": "latest",
+    "parser": "@typescript-eslint/parser",
+    "sourceType": "module"
+  },
+  "extends": [
+    "plugin:vue/vue3-recommended",
+    "airbnb-base"
+  ],
+  "rules": {
+    "no-console": 0, // 禁用打印
+    "comma-dangle": [ 2, "never" ], // 禁止使用拖尾逗号
+    "no-extra-semi": 2, // 禁止不必要的分号
+    "array-bracket-spacing": [ 2, "always" ], // 指定数组的元素之间要以空格隔开
+    "jsx-quotes": 0, // 强制使用单引号
+    "max-len": 0, // 强制一行的最大长度
+    "semi": [ 2, "never" ], // 禁止使用分号
+    "no-unused-vars": 0,
+    "no-unneeded-ternary": 2, // 禁止不必要的嵌套 var isYes = answer === 1 ? true : false;
+    "no-unreachable": 2, // 不能有无法执行的代码
+    "no-unused-expressions": 1, // 禁止无用的表达式
+    "linebreak-style": [ 0, "error", "windows" ],
+    "import/no-unresolved": 0,
+    "import/extensions": 0,
+    "import/no-absolute-path": 0,
+    "import/no-extraneous-dependencies": 2,
+    "class-methods-use-this": 0,
+    "no-mixed-operators": 0,
+    "eol-last": 0,
+    "import/newline-after-import": 0,
+    "vue/multi-word-component-names": 0,
+    "no-param-reassign": 0,
+    "no-restricted-syntax": 0,
+    "no-underscore-dangle": 0,
+    "no-plusplus": 0,
+    "no-bitwise": 0,
+    "guard-for-in": 0,
+    "func-names": 0,
+    "import/order": 0,
+    "vue/no-deprecated-slot-attribute": 0,
+    "vue/v-on-event-hyphenation": 0,
+    "vue/no-deprecated-filter": 0,
+    "vue/require-explicit-emits": 0,
+    "vue/no-v-html": 0,
+    "vue/order-in-components": 0,
+    "vue/no-reserved-component-names": 0,
+    "no-promise-executor-return": 0,
+    "no-sparse-arrays": 0,
+    "no-nested-ternary": 0,
+    "no-continue": 0,
+    "complexity": [ 2, 9 ],
+    "no-return-await": 0,
+    "max-classes-per-file": 0,
+    "consistent-return" : 0,
+    "no-shadow": 0
+  }
+}

+ 14 - 12
.gitignore

@@ -1,26 +1,28 @@
-.DS_Store
-node_modules
-/dist
-
-
-# local env files
-.env.local
-.env.*.local
-
-# Log files
+# Logs
+logs
+*.log
 npm-debug.log*
 npm-debug.log*
 yarn-debug.log*
 yarn-debug.log*
 yarn-error.log*
 yarn-error.log*
 pnpm-debug.log*
 pnpm-debug.log*
+lerna-debug.log*
+
+node_modules
+dist
+dist-ssr
+*.local
 
 
 # Editor directories and files
 # Editor directories and files
+.vscode/*
+!.vscode/extensions.json
 .idea
 .idea
-.vscode
+.DS_Store
 *.suo
 *.suo
 *.ntvs*
 *.ntvs*
 *.njsproj
 *.njsproj
 *.sln
 *.sln
 *.sw?
 *.sw?
 yarn.lock
 yarn.lock
+dist
 package-lock.json
 package-lock.json
-www
+dist-ssr

+ 72 - 0
LICENSE

@@ -0,0 +1,72 @@
+Apache License 
+Version 2.0, January 2004 
+http://www.apache.org/licenses/
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
+
+"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
+
+"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
+
+"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
+
+"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
+
+"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
+
+"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
+
+"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
+
+"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
+
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
+
+(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
+
+(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
+
+(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
+
+(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
+
+You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License"); 
+you may not use this file except in compliance with the License. 
+You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software 
+distributed under the License is distributed on an "AS IS" BASIS, 
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
+See the License for the specific language governing permissions and 
+limitations under the License.

+ 11 - 21
README.md

@@ -1,26 +1,16 @@
-# Desc
+# 桌面应用模板
 ```
 ```
-控制端采用手柄
+本版本为vue3+ts+eslint 自动修正,其它规则请手动添加到rules。
 ```
 ```
-## Debug
+## 注意
 ```
 ```
 1. yarn
 1. yarn
-2. yarn dev
-3. 房间ID同车端ID
+2. npm run dev 启动 web 端
+3. npm run edev 启动 electron
+4. npm run make 打包带压缩文件
+5. npm run pmake 打包不带压缩文件
+6. /pucli 文件中的 loader 不能删除,为了渲染进程和主进程之间通信
+7. out 文件为输出包
+8. 环境变量在 vite.config 中添加
+9. 多页面跳转在 electron 中使用 loadurl
 ```
 ```
-
-## Fn
-```
-1. 遥控手柄自行连接电脑
-2. 左摇杆云台控制
-3. 右摇杆方向及车速控制
-4. A键是2档
-5. B键是1档
-6. R2是语音(按住说话)
-7. X3是静音
-8. Y2是鸣笛
-```
-## TODO:
-```
-1. 电量采集优化(准确性)
-```

+ 28 - 0
index.html

@@ -0,0 +1,28 @@
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+  <meta charset="UTF-8" />
+  <title>Contrl</title>
+  <style>
+    video,
+    #app,
+    html,
+    body {
+      margin: 0;
+      padding: 0;
+      user-select: none;
+      width: 100%;
+      height: 100%;
+      overflow: hidden;
+    }
+  </style>
+</head>
+
+<body>
+  <div id="app"></div>
+  <script type="module" src="./src/main.ts"></script>
+  <script src="./loader.js"></script>
+</body>
+
+</html>

+ 33 - 0
loading.html

@@ -0,0 +1,33 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta http-equiv="X-UA-Compatible" content="IE=edge">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>loading</title>
+    <style>
+        .loader {
+        border: 5px solid #f3f3f3;
+        border-radius: 50%;
+        border-top: 5px solid #3498db;
+        width: 30px;
+        height: 30px;
+        -webkit-animation: spin 2s linear infinite;
+        animation: spin 2s linear infinite;
+        }
+
+        @-webkit-keyframes spin {
+        0% { -webkit-transform: rotate(0deg); }
+        100% { -webkit-transform: rotate(360deg); }
+        }
+
+        @keyframes spin {
+        0% { transform: rotate(0deg); }
+        100% { transform: rotate(360deg); }
+        }        
+    </style>
+</head>
+<body>
+    <div class="loader"></div>
+</body>
+</html>

+ 82 - 0
main.js

@@ -0,0 +1,82 @@
+const {
+  app, BrowserWindow, Menu, ipcMain
+} = require('electron')// 引入electron
+let win; let
+  loadingWin
+Menu.setApplicationMenu(null) // 去掉菜单栏
+app.commandLine.appendSwitch('wm-window-animations-disabled') // 拖动闪屏
+
+// 消息通知
+function notifiction (title, options) {
+	const WebNotification =  window.Notification || window.mozNotification || window.webkitNotification
+    const isTrue = WebNotification.requestPermission(result => {
+      return (result === 'granted') // granted(允许) || denied(拒绝)
+    })
+    const noti =  new WebNotification(title, options)
+    noti.onclick=()=>{
+      console.log('关闭')
+    }
+}
+
+
+// 创建loading 窗口
+const showLoading = () => {
+  loadingWin = new BrowserWindow({
+    frame: false, // 无边框(窗口、工具栏等),只包含网页内容
+    width: 200,
+    height: 200,
+    resizable: false,
+    center: true,
+    alwaysOnTop: true,
+    transparent: true // 窗口是否支持透明,如果想做高级效果最好为true
+  })
+  loadingWin.loadFile('loading.html')
+  loadingWin.on('close', () => {
+    loadingWin = null
+  })
+}
+// 创建主程序 窗口
+const createWindow = () => {
+  win = new BrowserWindow({
+    maxWidth: 1920,
+    maxHeight: 1080,
+    minWidth: 1620,
+    minHeight: 900,
+    webPreferences: {
+      contextIsolation: false,
+      nodeIntegration: true,
+      webSecurity: false // 去掉跨越
+    },
+    show: false
+  })// 创建一个窗口
+  // 在窗口内要展示的内容index.html 就是打包生成的index.html
+  win.loadFile('dist/index.html')
+  // 开启调试工具
+  // win.webContents.openDevTools();
+  // 事件监听
+  win.on('close', () => {
+    // 回收BrowserWindow对象
+    win = null
+  })
+}
+
+// 事件监听
+app.on('ready', async () => {
+  showLoading()
+  createWindow()
+  // 监听渲染进行
+  ipcMain.once('close-loading', () => {
+    loadingWin.close()
+    win.show()
+  })
+})
+
+app.on('window-all-closed', () => {
+  app.quit()
+})
+
+app.on('activate', () => {
+  if (win == null) {
+    createWindow()
+  }
+})

+ 44 - 11
package.json

@@ -1,19 +1,52 @@
 {
 {
-  "name": "app",
-  "version": "0.1.0",
-  "private": true,
+  "name": "contrl-client",
+  "version": "1.0.0",
+  "main": "main.js",
+  "author": "Caner",
+  "description": "控制端",
   "scripts": {
   "scripts": {
-    "dev": "vue-cli-service serve",
-    "build": "vue-cli-service build",
-    "lint": "vue-cli-service lint"
+    "dev": "vite",
+    "edev": "yarn build && electron .",
+    "build": "vue-tsc --noEmit && vite build",
+    "make": "electron-forge make",
+    "pmake": "electron-forge package"
   },
   },
   "dependencies": {
   "dependencies": {
-    "echarts": "^5.4.0",
-    "socket.io-client": "^4.5.3",
-    "vue": "^2.6.11"
+    "echarts": "^5.4.2",
+    "socket.io-client": "^4.6.1",
+    "vue": "^3.3.2",
+    "vue-router": "^4.2.0"
   },
   },
   "devDependencies": {
   "devDependencies": {
-    "@vue/cli-service": "~5.0.8",
-    "compression-webpack-plugin": "^10.0.0"
+    "@electron-forge/cli": "^6.1.1",
+    "@electron-forge/maker-zip": "^6.1.1",
+    "@types/node": "^18.15.3",
+    "@typescript-eslint/parser": "^5.40.0",
+    "@vitejs/plugin-vue": "^4.2.3",
+    "eslint": "^8.40.0",
+    "eslint-config-airbnb-base": "^15.0.0",
+    "eslint-plugin-import": "^2.27.5",
+    "eslint-plugin-vue": "^9.13.0",
+    "less": "^4.1.3",
+    "typescript": "^5.0.4",
+    "vite": "^4.3.6",
+    "vite-plugin-compression": "^0.5.1",
+    "vite-plugin-eslint": "^1.8.1",
+    "vue-tsc": "^1.6.5",
+    "vite-plugin-svg-icons": "^2.0.1",
+    "electron": "^23.1.2"
+  },
+  "config": {
+    "forge": {
+      "packagerConfig": {
+        "asar": true,
+        "ignore": "(out|vite.config.ts|README.md|.env|.gitignore|.eslintrc.json|src|public|node_modules|package-lock.json)"
+      },
+      "makers": [
+        {
+          "name": "@electron-forge/maker-zip"
+        }
+      ]
+    }
   }
   }
 }
 }

BIN
public/favicon.ico


+ 0 - 18
public/index.html

@@ -1,18 +0,0 @@
-<!DOCTYPE html>
-<html lang="">
-  <head>
-    <meta charset="utf-8">
-    <meta http-equiv="X-UA-Compatible" content="IE=edge">
-    <meta name="viewport" content="width=device-width,initial-scale=1.0">
-    <meta name="viewport" content="initial-scale=1,maximum-scale=1, minimum-scale=1, user-scalable=no">
-    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
-    <title>Caner</title>
-  </head>
-  <body>
-    <noscript>
-      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
-    </noscript>
-    <div id="app"></div>
-    <!-- built files will be auto injected -->
-  </body>
-</html>

+ 2 - 0
public/loader.js

@@ -0,0 +1,2 @@
+const electron = require('electron');//引入electron
+window['$electron'] = electron

+ 17 - 350
src/App.vue

@@ -1,353 +1,20 @@
 <template>
 <template>
-  <div id="app">
-    <template v-if="isLogin">
-      <video id="v2" autoplay playsinline muted></video>
-      <div class="marke">
-        <!-- 手柄状态 -->
-        <div class="contrl" :style="`color:${contrlState ? '#00CED1' : 'rgba(0, 0, 0, 0.3)'}`">&#xe72a;</div>
-        <!-- 音频状态 -->
-        <Record class="audio" @callBack="sendAudio" :audioState="audioState" />
-        <!-- 喇叭状态 -->
-        <div class="arcode" :style="`color:${muted ? '#00CED1' : 'rgba(0, 0, 0, 0.3)'}`">&#xe600;</div>
-        <!-- 电量状态 -->
-        <Battery :quantity="60" />
-      </div>
-      <!-- 码数 -->
-      <div class="gauge">
-        <Gauge :value="SpeedValue" :gears="speed" />
-      </div>
-      <Loading v-if="showLoading" />
-    </template>
-    <Login v-else :err="error" @loginBack="login" />
-  </div>
+  <loading v-if="showLoading" />
+  <router-view
+    v-else
+    v-resize
+  />
 </template>
 </template>
-
-<script>
-const { io } = require("socket.io-client");
-import Login from "@/components/login";
-import Loading from "@/components/loading";
-import Record from "@/components/record";
-import Battery from "@/components/battery";
-import Gauge from "@/components/gauge";
-
-const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
-export default {
-  components: { Login, Loading, Record, Battery, Gauge },
-  data() {
-    return {
-      socket: null,
-      HOST: "wss://car.caner.top",
-      Peer: null,
-      isLogin: false,
-      error: "",
-      remoteVideo: null,
-      showLoading: true,
-      contrlState: false,
-      audioState: false,
-      mutedState: true,
-      warnAudio: false,// 鸣笛
-      speed: 1, //1低速档 | 2 高速档
-      muted: true,// 是否静音
-      SpeedValue: 0,
-      iceServers: [
-        {
-          urls: ["stun:caner.top:3478"],
-        },
-        {
-          urls: "turn:caner.top:3478",
-          username: "admin",
-          credential: "123456",
-        },
-      ],
-      num: 0
-    };
-  },
-  methods: {
-    // 网络连接
-    intSoketRtc(host) {
-      // int socket
-      this.socket = io(host, {
-        autoConnect: false,
-        transports: ["websocket"],
-      });
-
-      // socket
-      this.socket.on("connect", () => {
-        try {
-          this.isLogin = true;
-          // init webrtc
-          this.Peer = new RTCPeerConnection({
-            iceServers: this.iceServers,
-            bundlePolicy: "max-bundle",
-          });
-
-          // listen state
-          this.Peer.onicegatheringstatechange = () => {
-            console.log("GatheringState: ", this.Peer.iceGatheringState);
-            if (this.Peer.iceGatheringState === "complete") {
-              const answer = this.Peer.localDescription;
-              this.socket.emit("msg", answer);
-            }
-          };
-
-          // listen track
-          this.Peer.ontrack = async (evt) => {
-            console.log("track", evt);
-            this.remoteVideo = document.getElementById("v2");
-            this.remoteVideo.srcObject = evt.streams[0];
-          };
-
-          // listen changestate·
-          this.Peer.oniceconnectionstatechange = async () => {
-            const state = this.Peer.iceConnectionState;
-            console.log("ICE状态", state);
-            if (
-              state === "failed" ||
-              state === "disconnected" ||
-              state === "closed"
-            ) {
-              this.close("P2P通信失败");
-            }
-
-            // ICE连接成功|初始化摇杆
-            if (state === "connected") {
-              // init Control
-              window.addEventListener("gamepadconnected", this.conControl);
-              window.addEventListener("gamepaddisconnected", this.disControl);
-              await sleep(3000);
-              this.showLoading = false;
-            }
-          };
-        } catch (error) {
-          this.close('webrtc初始化失败')
-        }
-      });
-
-      this.socket.on("msg", async (data) => {
-        const key = data.type
-        if (key === 'offer') {
-          await this.Peer.setRemoteDescription(data);
-          const answer = await this.Peer.createAnswer();
-          await this.Peer.setLocalDescription(answer);
-        } else if (key === 'power') {
-          console.log("电量", data);
-        } else if (key === 'speed') {
-          const d = Math.floor(data.data)
-          this.SpeedValue = d
-        }
-      });
-
-      this.socket.on("joined", async () =>
-        this.socket.emit("msg", { type: "startRTC" })
-      );
-
-      this.socket.on("leaved", () => this.close("车端断开"));
-
-      this.socket.on("connect_error", () => this.close('服务器连接失败'));
-    },
-
-    // 手柄数据
-    ControlData() {
-      const data = navigator.getGamepads();
-      const db = data[0];
-      if (!db) return;
-      // 挡位选择AB
-      if (db.buttons[1].touched) this.speed = 2;
-      if (db.buttons[0].touched) this.speed = 1;
-      // 语音按键R2
-      this.audioState = db.buttons[7].touched
-      // 静音X3
-      this.mutedState = db.buttons[3].touched
-      // 播放警笛Y2
-      this.warnAudio = db.buttons[2].touched
-      // console.log(db.buttons);
-      const params = {
-        v0: Math.floor(db.axes[0] * 128 + 128),
-        v1: Math.floor(db.axes[1] * 128 + 128),
-        v2: Math.floor(db.axes[2] * 128 + 128),
-        v3: this.Gear(this.speed, Math.floor(db.axes[3] * 128 + 128)),
-      };
-
-      if (this.socket && this.socket.connected) this.socket.emit("msg", { type: "conctrl", conctrl: params });
-      requestAnimationFrame(this.ControlData);
-    },
-
-    // 发送语音
-    sendAudio(blob) {
-      if (!this.socket && !this.socket.connected) return;
-      this.socket.emit("msg", {
-        type: "Meadia",
-        Meadia: blob,
-      });
-    },
-
-    // 挡位
-    Gear(speed, num) {
-      // 低速档
-      if (speed === 1) {
-        if (num < 116) {
-          // 前
-          num = 120;
-        } else if (num >= 120 && num <= 131) {
-          num = 128;
-        } else if (num > 140) {
-          // 后
-          num = 140;
-        }
-      }
-      // 高速档
-      if (speed === 2) {
-        if (num < 96) {
-          num = 96;
-        } else if (num >= 120 && num <= 131) {
-          num = 128;
-        } else if (num > 160) {
-          num = 160;
-        }
-      }
-      return num;
-    },
-
-    // 登录
-    login(data) {
-      if (this.socket) {
-        this.socket.auth = {
-          roomID: data.roomID,
-          name: data.name,
-        };
-        this.socket.connect();
-      } else {
-        this.error = "服务器连接失败";
-      }
-    },
-
-    // 关闭
-    close(err) {
-      if (this.Peer) this.Peer.close();
-      if (this.remoteVideo) this.remoteVideo.srcObject = null;
-      if (this.socket) this.socket.disconnect();
-      this.isLogin = false;
-      this.showLoading = false;
-      this.error = err || "";
-      this.socket = null;
-      this.Peer = null
-      this.num = 0
-      cancelAnimationFrame(this.ControlData);
-      window.removeEventListener("gamepadconnected", this.conControl);
-      window.removeEventListener("gamepaddisconnected", this.disControl);
-    },
-
-    // 手柄连接
-    conControl() {
-      this.contrlState = true;
-      this.ControlData();
-    },
-
-    // 手柄断开连接
-    disControl() {
-      this.contrlState = false;
-      cancelAnimationFrame(this.ControlData);
-    },
-  },
-  mounted() {
-    this.intSoketRtc(this.HOST);
-  },
-  watch: {
-    // 静音
-    mutedState(v) {
-      if (v) {
-        const state = !!(this.num % 2 )
-        this.muted = state
-        if (this.socket && this.socket.connected) this.socket.emit("msg", { type: "contrlAudio", contrlAudio: state });
-        this.num++
-      }
-    },
-    // 鸣笛
-    warnAudio(v) {
-      if (v && this.socket && this.socket.connected) this.socket.emit("msg", { type: "warnAudio", warnAudio: v });
-    }
-  },
-  beforeDestroy() {
-    this.close()
+<script setup lang='ts'>
+import { ref, onMounted } from 'vue'
+import loading from '@/components/loading.vue'
+
+const showLoading = ref(false)
+onMounted(() => {
+  // 通知主进程是否完成渲染
+  const electron = window.$electron || null
+  if (electron) {
+    electron.ipcRenderer.send('close-loading')
   }
   }
-};
-</script>
-<style scoped>
-#app {
-  font-family: "fonts";
-  font-style: normal;
-}
-
-video {
-  background: none;
-  object-fit: fill;
-  font-size: 0;
-}
-
-.marke {
-  position: fixed;
-  top: 0;
-  left: 0;
-  width: 100%;
-  padding: 5px 0;
-  z-index: 1;
-  background: rgba(0, 0, 0, 0.25);
-  display: flex;
-  align-items: center;
-  justify-content: center;
-  overflow: hidden;
-}
-
-.marke>div {
-  margin: 0 18px;
-}
-
-.gauge {
-  position: fixed;
-  bottom: 0;
-  left: 50%;
-  transform: translate(-50%, 0);
-  width: 500px;
-  height: 185px;
-  z-index: 9;
-}
-
-.audio,
-.arcode {
-  font-size: 24px;
-  color: rgba(0, 0, 0, 0.3);
-}
-
-.contrl {
-  font-size: 32px;
-  color: rgba(0, 0, 0, 0.3);
-}
-
-/* 隐藏滚动条 */
-::-webkit-scrollbar {
-  width: 0 !important;
-  display: none;
-}
-
-@font-face {
-  font-family: "fonts";
-  src: url("./assets/iconfont.woff2") format("woff2"),
-    url("./assets/iconfont.woff") format("woff"),
-    url("./assets/iconfont.ttf") format("truetype");
-}
-</style>
-<style>
-video,
-#app,
-html,
-body {
-  margin: 0;
-  padding: 0;
-  user-select: none;
-  width: 100%;
-  height: 100%;
-  overflow: hidden;
-  min-width: 1000px;
-  min-height: 900px;
-}
-</style>
+})
+</script>

BIN
src/assets/iconfont.ttf


BIN
src/assets/iconfont.woff


BIN
src/assets/iconfont.woff2


+ 3 - 0
src/assets/icons/close.svg

@@ -0,0 +1,3 @@
+<svg width="12" height="12" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M6.71148 6.00003L9.89087 2.82065L9.17852 2.10829L5.99916 5.28765L2.81978 2.10828L2.10743 2.82063L5.28677 5.99998L2.10742 9.17933L2.81978 9.89169L5.99913 6.71234L9.17849 9.8917L9.89081 9.17938L6.71148 6.00003Z" />
+</svg>

+ 69 - 67
src/components/battery.vue

@@ -1,106 +1,108 @@
 <template>
 <template>
-  <div class="electric-panel" :class="bgClass">
-    <div class="panel">
-      <div class="remainder" :style="{ width: quantity + '%' }" />
+  <div class="electric" :class="bgClass">
+    <div class="electric-panel">
+      <div class="electric-panel-remainder" :style="{ width: quantity + '%' }" />
     </div>
     </div>
-    <div class="berText">50%</div>
+    <div class="electric-berText">50%</div>
   </div>
   </div>
 </template>
 </template>
 
 
-<script>
-/**
- * 电池电量Icon
- */
-export default {
-  name: "ElectricQuantity",
-  props: ["quantity"],
-  computed: {
-    bgClass() {
-      if (this.quantity >= 50) {
-        return "success";
-      } else if (this.quantity >= 20) {
-        return "warning";
-      } else if (this.quantity >= 1) {
-        return "danger";
-      } else {
-        return "danger";
-      }
-    },
-  },
-};
+<script setup lang="ts">
+import { computed } from 'vue'
+const props = defineProps<{
+  quantity: number
+}>()
+const bgClass = computed(() => {
+  if (props.quantity >= 50) {
+    return "success";
+  } else if (props.quantity >= 20) {
+    return "warning";
+  } else if (props.quantity >= 1) {
+    return "danger";
+  } else {
+    return "danger";
+  }
+})
 </script>
 </script>
 
 
-<style scoped>
-.electric-panel {
+<style scoped lang="less">
+.electric {
   display: flex;
   display: flex;
   justify-content: center;
   justify-content: center;
   align-items: center;
   align-items: center;
   position: relative;
   position: relative;
   z-index: 3;
   z-index: 3;
   color: white;
   color: white;
-}
 
 
-.panel {
-  box-sizing: border-box;
-  width: 22px;
-  height: 14px;
-  position: relative;
-  border: 2px solid #ccc;
-  padding: 1px;
-  border-radius: 3px;
-  margin-right: 5px;
-  transform: rotate(-90deg);
-}
+  &-panel {
+    box-sizing: border-box;
+    width: 0.22rem;
+    height: 0.14rem;
+    position: relative;
+    border: 0.02rem solid #ccc;
+    padding: 0.01rem;
+    border-radius: 0.03rem;
+    margin-right: 0.05rem;
+    transform: rotate(-90deg);
 
 
-.panel::before {
-  content: "";
-  border-radius: 0 1px 1px 0;
-  height: 6px;
-  background: #ccc;
-  width: 3px;
-  position: absolute;
-  top: 50%;
-  right: -4px;
-  transform: translateY(-50%);
-}
+    &::before {
+      content: "";
+      border-radius: 0 1px 1px 0;
+      height: 0.06rem;
+      background: #ccc;
+      width: 0.03rem;
+      position: absolute;
+      top: 50%;
+      right: -0.04rem;
+      transform: translateY(-50%);
 
 
-.panel .remainder {
-  border-radius: 1px;
-  position: relative;
-  height: 100%;
-  width: 0%;
-  left: 0;
-  top: 0;
-  background: #fff;
+    }
+
+    &-remainder {
+      border-radius: 1px;
+      position: relative;
+      height: 100%;
+      width: 0%;
+      left: 0;
+      top: 0;
+      background: #fff;
+    }
+  }
 }
 }
 
 
-.success .panel {
+.success .electric-panel {
   border-color: #40d7c1;
   border-color: #40d7c1;
 }
 }
-.success .panel:before {
+
+.success .electric-panel:before {
   background: #40d7c1;
   background: #40d7c1;
 }
 }
-.success .remainder {
+
+.success .electric-panel-remainder {
   background: #40d7c1;
   background: #40d7c1;
 }
 }
 
 
-.warning .panel {
+.warning .electric-panel {
   border-color: #f90;
   border-color: #f90;
 }
 }
-.warning .panel:before {
+
+.warning .electric-panel:before {
   background: #f90;
   background: #f90;
 }
 }
-.warning .remainder {
+
+.warning .electric-panel-remainder {
   background: #f90;
   background: #f90;
 }
 }
 
 
-.danger .panel {
+.danger .electric-panel {
   border-color: #ed4014;
   border-color: #ed4014;
 }
 }
-.danger .panel:before {
+
+.danger .electric-panel:before {
   background: #ed4014;
   background: #ed4014;
 }
 }
-.danger .remainder {
+
+.danger .electric-panel-remainder {
   background: #ed4014;
   background: #ed4014;
 }
 }
 </style>
 </style>

+ 101 - 101
src/components/gauge.vue

@@ -1,111 +1,111 @@
 <template>
 <template>
-  <div id="charts"></div>
+  <div ref="chartDom" id="charts"></div>
 </template>
 </template>
-<script>
-import * as echarts from "echarts/core";
-import { GaugeChart } from "echarts/charts";
-import { LabelLayout, UniversalTransition } from "echarts/features";
-import { CanvasRenderer } from "echarts/renderers";
-echarts.use([GaugeChart, LabelLayout, UniversalTransition, CanvasRenderer]);
-export default {
-  props: ["value", "gears"],
-  data() {
-    return {
-      mychart: null,
-      option: {
-        series: {
-          name: "Pressure",
-          type: "gauge",
-          itemStyle: {
-            color: "#FFFFFF",
-          },
-          startAngle: 180,
-          max: 60,
-          endAngle: 0,
-          axisLine: {
-            lineStyle: {
-              width: 1,
-            },
-          },
-          axisTick: {
-            distance: 0,
-            length: 10,
-            lineStyle: {
-              color: "#FFFFFF",
-            },
-          },
-          splitLine: {
-            length: 15,
-            distance: 0,
-            lineStyle: {
-              color: "#FFFFFF",
-            },
-          },
-          axisLabel: {
-            distance: 8,
-            color: "#FFFFFF",
-          },
-          progress: {
-            show: true,
-          },
-          radius: "160%",
-          center: ["50%", "90%"],
-          detail: {
-            offsetCenter: [0, -25],
-            valueAnimation: true,
-            formatter: (value) => {
-              return `{value|${value.toFixed(0)}}{unit|km/h}\n{num|${
-                this.gears
-              }}`;
-            },
-            rich: {
-              value: {
-                fontSize: 20,
-                fontWeight: "bolder",
-                color: "#FFFFFF",
-              },
-              unit: {
-                fontSize: 20,
-                color: "#FFFFFF",
-                padding: [0, 0, 0, 10],
-              },
-              num: {
-                fontSize: 20,
-                color: "#FFFFFF",
-                padding: [0, 0, 0, 10],
-              },
-            },
-          },
-          pointer: {
-            show: false,
-          },
-          data: [0],
+<script setup lang="ts">
+import * as echarts from 'echarts'
+import { GaugeChart } from "echarts/charts"
+import { LabelLayout, UniversalTransition } from "echarts/features"
+import { CanvasRenderer } from "echarts/renderers"
+import { onMounted, ref, watch } from 'vue';
+echarts.use([GaugeChart, LabelLayout, UniversalTransition, CanvasRenderer])
+
+const chartDom = ref()
+const chart = ref()
+const option = ref({
+  series: {
+    name: "Pressure",
+    type: "gauge",
+    itemStyle: {
+      color: "#FFFFFF",
+    },
+    startAngle: 180,
+    max: 60,
+    endAngle: 0,
+    axisLine: {
+      lineStyle: {
+        width: 1,
+      },
+    },
+    axisTick: {
+      distance: 0,
+      length: 10,
+      lineStyle: {
+        color: "#FFFFFF",
+      },
+    },
+    splitLine: {
+      length: 15,
+      distance: 0,
+      lineStyle: {
+        color: "#FFFFFF",
+      },
+    },
+    axisLabel: {
+      distance: 8,
+      color: "#FFFFFF",
+    },
+    progress: {
+      show: true,
+    },
+    radius: "160%",
+    center: ["50%", "90%"],
+    detail: {
+      offsetCenter: [0, -25],
+      valueAnimation: true,
+      formatter: (value: number) => {
+        return `{value|${value.toFixed(0)}}{unit|km/h}\n{num|${props.gears}}`;
+      },
+      rich: {
+        value: {
+          fontSize: 20,
+          fontWeight: "bolder",
+          color: "#FFFFFF",
+        },
+        unit: {
+          fontSize: 20,
+          color: "#FFFFFF",
+          padding: [0, 0, 0, 10],
+        },
+        num: {
+          fontSize: 20,
+          color: "#FFFFFF",
+          padding: [0, 0, 0, 10],
         },
         },
       },
       },
-    };
-  },
-  mounted() {
-    this.mychart = echarts.init(document.getElementById("charts"));
-    this.mychart.setOption(this.option);
-  },
-  watch: {
-    value(v) {
-      if (!this.mychart) return;
-      if (v >= 60) v = 60;
-      if (v <= 0) v = 0;
-      this.option.series.data[0] = v;
-      this.mychart.setOption(this.option);
     },
     },
-    gears(v){
-      if (!this.mychart) return;
-      this.mychart.setOption(this.option);
-    }
-  },
-};
+    pointer: {
+      show: false,
+    },
+    data: [0],
+  }
+})
+const props = defineProps<{
+  value: number,
+  gears: number
+}>()
+
+
+onMounted(() => {
+  chart.value = echarts.init(chartDom.value)
+  chart.value.setOption(option.value)
+})
+
+watch(() => props.value, (v: number) => {
+  if (!chart.value) return;
+  if (v >= 60) v = 60;
+  if (v <= 0) v = 0;
+  option.value.series.data[0] = v;
+  chart.value.setOption(option.value);
+})
+
+watch(() => props.gears, (v) => {
+  if (!chart.value) return;
+  chart.value.setOption(option.value);
+})
 </script>
 </script>
 <style scoped>
 <style scoped>
 #charts {
 #charts {
-  width: 500px;
-  height: 200px;
+  width: 5rem;
+  height: 2rem;
 }
 }
 </style>
 </style>

+ 25 - 0
src/components/icon.vue

@@ -0,0 +1,25 @@
+<script setup lang="ts">
+import { computed } from 'vue'
+const props = defineProps<{
+  name: string,
+  size?: number,
+  color?: string
+}>()
+const symbolId = computed(() => `#icon-${props.name}`)
+const newColor = computed(() => `${props.color ?? '#ccc'}`)
+const newSize = computed(() => `${props.size ?? 16}`)
+</script>
+<template>
+  <svg
+    aria-hidden="true"
+    :font-size="newSize"
+    :width="newSize"
+    :height="newSize"
+  >
+
+    <use
+      :href="symbolId"
+      :fill="newColor"
+    />
+  </svg>
+</template>

+ 15 - 125
src/components/loading.vue

@@ -1,134 +1,24 @@
 <template>
 <template>
-  <div class="loading">
-    <figure>
-      <div class="dot white"></div>
-      <div class="dot"></div>
-      <div class="dot"></div>
-      <div class="dot"></div>
-      <div class="dot"></div>
-    </figure>
-  </div>
+  <div class="loader" />
 </template>
 </template>
-
 <style scoped>
 <style scoped>
-.loading{
-    position: fixed;
-    width: 100%;
-    height: 100%;
-    top: 0;
-    left: 0;
-    z-index: 9;
-    background: rgba(0, 0, 0, 0.7);
-    font-size: 12px;
-}
-figure {
-  position: absolute;
-  margin: auto;
-  top: 0;
-  bottom: 0;
-  left: 0;
-  right: 0;
-  width: 6.25em;
-  height: 6.25em;
-  animation: rotate 2.4s linear infinite;
-}
-.white {
-  top: 0;
-  bottom: 0;
-  left: 0;
-  right: 0;
-  background: white;
-  animation: flash 2.4s linear infinite;
-  opacity: 0;
-}
-.dot {
-  position: absolute;
-  margin: auto;
-  width: 2.4em;
-  height: 2.4em;
-  border-radius: 100%;
-  transition: all 1s ease;
-}
-.dot:nth-child(2) {
-  top: 0;
-  bottom: 0;
-  left: 0;
-  background: #ff4444;
-  animation: dotsY 2.4s linear infinite;
-}
-.dot:nth-child(3) {
-  left: 0;
-  right: 0;
-  top: 0;
-  background: #ffbb33;
-  animation: dotsX 2.4s linear infinite;
-}
-.dot:nth-child(4) {
-  top: 0;
-  bottom: 0;
-  right: 0;
-  background: #99cc00;
-  animation: dotsY 2.4s linear infinite;
-}
-.dot:nth-child(5) {
-  left: 0;
-  right: 0;
-  bottom: 0;
-  background: #33b5e5;
-  animation: dotsX 2.4s linear infinite;
+.loader {
+  border: 0.05rem solid #f3f3f3;
+  border-radius: 50%;
+  border-top: 0.05rem solid #3498db;
+  width: 0.3rem;
+  height: 0.3rem;
+  -webkit-animation: spin 2s linear infinite;
+  animation: spin 2s linear infinite;
 }
 }
 
 
-@keyframes rotate {
-  0% {
-    transform: rotate(0);
-  }
-  10% {
-    width: 6.25em;
-    height: 6.25em;
-  }
-  66% {
-    width: 2.4em;
-    height: 2.4em;
-  }
-  100% {
-    transform: rotate(360deg);
-    width: 6.25em;
-    height: 6.25em;
-  }
-}
-
-@keyframes dotsY {
-  66% {
-    opacity: 0.1;
-    width: 2.4em;
-  }
-  77% {
-    opacity: 1;
-    width: 0;
-  }
-}
-@keyframes dotsX {
-  66% {
-    opacity: 0.1;
-    height: 2.4em;
-  }
-  77% {
-    opacity: 1;
-    height: 0;
-  }
+@-webkit-keyframes spin {
+  0% { -webkit-transform: rotate(0deg); }
+  100% { -webkit-transform: rotate(360deg); }
 }
 }
 
 
-@keyframes flash {
-  33% {
-    opacity: 0;
-    border-radius: 0%;
-  }
-  55% {
-    opacity: 0.6;
-    border-radius: 100%;
-  }
-  66% {
-    opacity: 0;
-  }
+@keyframes spin {
+  0% { transform: rotate(0deg); }
+  100% { transform: rotate(360deg); }
 }
 }
 </style>
 </style>

+ 76 - 79
src/components/login.vue

@@ -1,98 +1,95 @@
 <template>
 <template>
   <div class="login">
   <div class="login">
     <div @keydown.enter="login">
     <div @keydown.enter="login">
-      <div class="logo">登陆</div>
+      <div class="login-logo">登陆</div>
       <input type="text" placeholder="房间" maxlength="20" v-model="roomID" />
       <input type="text" placeholder="房间" maxlength="20" v-model="roomID" />
       <input type="text" placeholder="昵称" maxlength="20" v-model="name" />
       <input type="text" placeholder="昵称" maxlength="20" v-model="name" />
-      <div class="err">{{ err || error }}</div>
+      <div class="login-err">{{ err || error }}</div>
       <button @click="login">加入</button>
       <button @click="login">加入</button>
     </div>
     </div>
   </div>
   </div>
 </template>
 </template>
-<script>
-export default {
-  props: {
-    err: {
-      type: String,
-      default: () => {
-        return "";
-      },
-    },
-  },
-  data() {
-    return {
-      name: "",
-      roomID: "",
-      error: ""
-    };
-  },
-  methods: {
-    async login() {
-      if(!this.roomID){
-        this.error = "请输入房间号";
-      }else if(!this.name){
-        this.error = "请输入昵称";
-      }else{
-        this.$emit("loginBack", { name: this.name, roomID: this.roomID });
-      }
-    },
-  },
-};
+<script setup lang="ts">
+import { ref } from 'vue';
+const name = ref('')
+const roomID = ref('')
+const error = ref('')
+defineProps<{
+  err: string
+}>()
+const emit = defineEmits<{
+  (evt: 'loginBack', value: { name: string, roomID: string }): void;
+}>()
+async function login() {
+  if (!roomID.value) {
+    error.value = "请输入房间号";
+  } else if (!name.value) {
+    error.value = "请输入昵称";
+  } else {
+    emit("loginBack", { name: name.value, roomID: roomID.value });
+  }
+}
 </script>
 </script>
-<style scoped>
+<style scoped lang="less">
 .login {
 .login {
   width: 100%;
   width: 100%;
   height: 100%;
   height: 100%;
-  font-size: 16px;
+  font-size: 0.16rem;
   display: flex;
   display: flex;
   justify-content: center;
   justify-content: center;
   align-items: center;
   align-items: center;
-}
-.logo {
-  width: 100px;
-  height: 50px;
-  margin: 0 auto;
-  text-align: center;
-}
-input {
-  display: block;
-  border: 0;
-  border-bottom: solid 1px #ccc;
-  text-indent: 10px;
-  margin: 0 auto;
-  margin-bottom: 20px;
-  outline: none;
-  border-radius: 0;
-  background: none;
-}
 
 
-button {
-  display: block;
-  width: 130px;
-  height: 30px;
-  background: #79b8fa;
-  border: none;
-  color: white;
-  font-size: 17px;
-  font-weight: 500;
-  border-radius: 5px;
-  cursor: pointer;
-  margin: 0 auto;
-  margin-top: 20px;
-  line-height: 30px;
-}
-button:hover {
-  background: #2d8cf0;
-}
-.err {
-  width: 175px;
-  margin: 0 auto;
-  font-size: 12px;
-  color: red;
-  text-align: left;
-  text-indent: 10px;
-}
-input:nth-child(3) {
-  margin-bottom: 5px;
+  &-logo {
+    width: 1rem;
+    height: 0.5rem;
+    margin: 0 auto;
+    text-align: center;
+  }
+
+  input {
+    display: block;
+    border: 0;
+    border-bottom: solid 0.01rem #ccc;
+    text-indent: 0.1rem;
+    margin: 0 auto;
+    margin-bottom: 0.2rem;
+    outline: none;
+    border-radius: 0;
+    background: none;
+  }
+
+  button {
+    display: block;
+    width: 1.3rem;
+    height: 0.3rem;
+    background: #79b8fa;
+    border: none;
+    color: white;
+    font-size: 0.17rem;
+    font-weight: 500;
+    border-radius: 0.05rem;
+    cursor: pointer;
+    margin: 0 auto;
+    margin-top: 0.2rem;
+    line-height: 0.3rem;
+  }
+
+  button:hover {
+    background: #2d8cf0;
+  }
+
+  &-err {
+    width: 1.75rem;
+    margin: 0 auto;
+    font-size: 0.12rem;
+    color: red;
+    text-align: left;
+    text-indent: 0.1rem;
+  }
+
+  input:nth-child(3) {
+    margin-bottom: 0.05rem;
+  }
+
 }
 }
 </style>
 </style>

+ 54 - 72
src/components/record.vue

@@ -1,78 +1,60 @@
 <template>
 <template>
-  <div :style="`color:${show ? '#00CED1':'rgba(0, 0, 0, 0.3)'}`">&#xe6c1;</div>
+  <div :style="`color:${show ? '#00CED1' : 'rgba(0, 0, 0, 0.3)'}`">&#xe6c1;</div>
 </template>
 </template>
-<script lang="js">
-export default {
-  props: ["audioState"],
-  data() {
-    return {
-      chunks: [],
-      mediaRecorder: null,
-      show: false, // true 开启,false 停止
+<script setup lang="ts">
+import { ref, watch } from 'vue';
+const chunks = ref([] as Blob[])
+const mediaRecorder = ref(null as null | MediaRecorder)
+const show = ref(false)
+
+const props = defineProps<{
+  audioState: boolean
+}>()
+const emit = defineEmits<{
+  (evt: 'callBack', value: Blob): void;
+}>()
+
+// 初始化音频
+async function initRecorder() {
+  try {
+    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+    mediaRecorder.value = new MediaRecorder(stream);
+
+    // 事件监听
+    mediaRecorder.value.ondataavailable = (e: { data: Blob }) => {
+      chunks.value.push(e.data);
     };
     };
-  },
-  methods: {
-    // 初始化音频
-    async initRecorder() {
-      try {
-        const stream = await navigator.mediaDevices.getUserMedia({
-          audio: true,
-        });
-        this.mediaRecorder = new MediaRecorder(stream);
+    mediaRecorder.value.onstart = () => {
+      chunks.value = [];
+    };
+    mediaRecorder.value.onstop = () => {
+      const blob = new Blob(chunks.value, {
+        type: "audio/webm;codecs=opus",
+      });
+      emit("callBack", blob);
+    };
+  } catch (error: any) {
+    show.value = false;
+    mediaRecorder.value = null;
+    let txt = "不支持的音频";
+    if (error.toString().includes("getUserMedia")) {
+      txt = "不支持webrtc音频";
+    } else {
+      txt = "未获取到音频设备";
+    }
+    alert(txt)
+  }
+}
+
+watch(() => props.audioState, (v) => {
+  if (!mediaRecorder.value) return;
+  if (v) {
+    mediaRecorder.value.start();
+  } else {
+    mediaRecorder.value.stop();
+  }
+  show.value = v;
 
 
-        // 事件监听
-        this.mediaRecorder.ondataavailable = (e) => {
-          this.chunks.push(e.data);
-        };
-        this.mediaRecorder.onstart = () => {
-          this.chunks = [];
-        };
-        this.mediaRecorder.onstop = () => {
-          const blob = new Blob(this.chunks, {
-            type: "audio/webm;codecs=opus",
-          });
-          this.$emit("callBack", blob);
-        };
-      } catch (error) {
-        this.show = false;
-        this.mediaRecorder = null;
-        let txt = "不支持的音频";
-        if (error.toString().includes("getUserMedia")) {
-          txt = "不支持webrtc音频";
-        } else {
-          txt = "未获取到音频设备";
-        }
-        alert(txt)
-      }
-    },
+})
 
 
-    // blob2AudioBuffer
-    blob2audioBuffer(blob) {
-      const reader = new FileReader();
-      reader.onload = function () {
-        console.log(123, this.result);
-        const audioCtx = new AudioContext();
-        audioCtx.decodeAudioData(this.result, function (audioBuffer) {
-          // AudioBuffer
-          console.log(audioBuffer);
-        });
-      };
-      reader.readAsArrayBuffer(blob);
-    },
-  },
-  watch: {
-    audioState(v) {
-      if (!this.mediaRecorder) return;
-      if (v) {
-        this.mediaRecorder.start();
-      } else {
-        this.mediaRecorder.stop();
-      }
-      this.show = v;
-    },
-  },
-  mounted() {
-    this.initRecorder();
-  },
-};
 </script>
 </script>

+ 0 - 6
src/main.js

@@ -1,6 +0,0 @@
-import Vue from 'vue'
-import App from './App.vue'
-Vue.config.productionTip = false
-new Vue({
-  render: h => h(App),
-}).$mount('#app')

+ 23 - 0
src/main.ts

@@ -0,0 +1,23 @@
+import { createApp } from 'vue'
+import App from './App.vue'
+import { createRouter, RouteRecordRaw, createWebHistory } from 'vue-router'
+import Icon from '@/components/icon.vue'
+import 'virtual:svg-icons-register'
+import '@/services/rem'
+// 动态路由
+const routes = Object.values(import.meta.glob('./views/*/route.ts', { eager: true, import: 'default' })) as unknown as RouteRecordRaw[]
+routes.push({ path: '/:path(.*)', redirect: '/' })
+
+const app = createApp(App)
+const router = createRouter({
+  history: createWebHistory(),
+  routes
+})
+app.component('Icon', Icon)
+// 路由守卫
+// router.beforeEach((to, from, next) => {
+//   // do something
+//   next()
+// })
+
+app.use(router).mount('#app')

+ 19 - 0
src/services/rem.ts

@@ -0,0 +1,19 @@
+// 18fontsize = (18/100)rem
+(function (doc, win) {
+  const docEl = doc.documentElement
+  const head = docEl.getElementsByTagName('head')[0]
+  const resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize'
+  const metaEl = doc.createElement('meta')
+  metaEl.name = 'viewport'
+  metaEl.content = 'initial-scale=1,maximum-scale=1, minimum-scale=1'
+  head.appendChild(metaEl)
+  const recalc = function () {
+    // 1rem =100px
+    const width = docEl.clientWidth
+    docEl.style.fontSize = `${100 * (width / 1920)}px`
+  }
+  recalc()
+  if (!doc.addEventListener) { return }
+  win.addEventListener(resizeEvt, recalc, false)
+  console.log('rem自适应')
+}(document, window))

+ 307 - 0
src/views/index/index.vue

@@ -0,0 +1,307 @@
+<script setup lang="ts">
+import { onMounted, onUnmounted, watch } from 'vue';
+import { ref } from 'vue';
+const socket = ref(null)
+const HOST = ref("wss://car.caner.top")
+const Peer = ref(null)
+const isLogin = ref(false)
+const error = ref("")
+const remoteVideo = ref()
+const showLoading = ref(true)
+const contrlState = ref(false)
+const audioState = ref(false)
+const mutedState = ref(true)
+const warnAudio = ref(false)// 鸣笛
+const speed = ref(1) //1低速档 | 2 高速档
+const muted = ref(true)// 是否静音
+const SpeedValue = ref(0)
+const iceServers = ref([
+  {
+    urls: ["stun:caner.top:3478"],
+  },
+  {
+    urls: "turn:caner.top:3478",
+    username: "admin",
+    credential: "123456",
+  },
+])
+const num = ref(0)
+// 网络连接
+function intSoketRtc(host) {
+  // int socket
+  socket.value = io(host, {
+    autoConnect: false,
+    transports: ["websocket"],
+  });
+
+  // socket
+  socket.value.on("connect", () => {
+    try {
+      isLogin.value = true;
+      // init webrtc
+      Peer.value = new RTCPeerConnection({
+        iceServers: iceServers.value,
+        bundlePolicy: "max-bundle",
+      });
+
+      // listen state
+      Peer.value.onicegatheringstatechange = () => {
+        console.log("GatheringState: ", Peer.value.iceGatheringState);
+        if (Peer.value.iceGatheringState === "complete") {
+          const answer = Peer.value.localDescription;
+          socket.value.emit("msg", answer);
+        }
+      };
+
+      // listen track
+      Peer.value.ontrack = async (evt) => {
+        console.log("track", evt);
+        remoteVideo.value.srcObject = evt.streams[0];
+      };
+
+      // listen changestate·
+      Peer.value.oniceconnectionstatechange = async () => {
+        const state = Peer.value.iceConnectionState;
+        console.log("ICE状态", state);
+        if (
+          state === "failed" ||
+          state === "disconnected" ||
+          state === "closed"
+        ) {
+          close("P2P通信失败");
+        }
+
+        // ICE连接成功|初始化摇杆
+        if (state === "connected") {
+          // init Control
+          window.addEventListener("gamepadconnected", conControl);
+          window.addEventListener("gamepaddisconnected", disControl);
+          await sleep(3000);
+          showLoading.value = false;
+        }
+      };
+    } catch (error) {
+      close('webrtc初始化失败')
+    }
+  });
+
+  socket.value.on("msg", async (data) => {
+    const key = data.type
+    if (key === 'offer') {
+      await Peer.value.setRemoteDescription(data);
+      const answer = await Peer.createAnswer();
+      await Peer.value.setLocalDescription(answer);
+    } else if (key === 'power') {
+      console.log("电量", data);
+    } else if (key === 'speed') {
+      const d = Math.floor(data.data)
+      SpeedValue.value = d
+    }
+  });
+
+  socket.value.on("joined", async () =>
+    socket.value.emit("msg", { type: "startRTC" })
+  );
+
+  socket.value.on("leaved", () => close("车端断开"));
+
+  socket.value.on("connect_error", () => close('服务器连接失败'));
+}
+
+// 手柄数据
+function ControlData() {
+  const data = navigator.getGamepads();
+  const db = data[0];
+  if (!db) return;
+  // 挡位选择AB
+  if (db.buttons[1].touched) speed.value = 2;
+  if (db.buttons[0].touched) speed.value = 1;
+  // 语音按键R2
+  audioState.value = db.buttons[7].touched
+  // 静音X3
+  mutedState.value = db.buttons[3].touched
+  // 播放警笛Y2
+  warnAudio.value = db.buttons[2].touched
+  // console.log(db.buttons);
+  const params = {
+    v0: Math.floor(db.axes[0] * 128 + 128),
+    v1: Math.floor(db.axes[1] * 128 + 128),
+    v2: Math.floor(db.axes[2] * 128 + 128),
+    v3: Gear(speed.value, Math.floor(db.axes[3] * 128 + 128)),
+  };
+
+  if (socket.value && socket.value.connected) socket.value.emit("msg", { type: "conctrl", conctrl: params });
+  requestAnimationFrame(ControlData);
+}
+
+// 发送语音
+function sendAudio(blob) {
+  if (!socket.value && !socket.value.connected) return;
+  socket.value.emit("msg", {
+    type: "Meadia",
+    Meadia: blob,
+  });
+}
+
+// 挡位
+function Gear(speed, num) {
+  // 低速档
+  if (speed === 1) {
+    if (num < 116) {
+      // 前
+      num = 120;
+    } else if (num >= 120 && num <= 131) {
+      num = 128;
+    } else if (num > 140) {
+      // 后
+      num = 140;
+    }
+  }
+  // 高速档
+  if (speed === 2) {
+    if (num < 96) {
+      num = 96;
+    } else if (num >= 120 && num <= 131) {
+      num = 128;
+    } else if (num > 160) {
+      num = 160;
+    }
+  }
+  return num;
+}
+
+// 登录
+function login(data) {
+  if (socket.value) {
+    socket.value.auth = {
+      roomID: data.roomID,
+      name: data.name,
+    };
+    socket.value.connect();
+  } else {
+    error.value = "服务器连接失败";
+  }
+}
+
+// 关闭
+function close(err?: string) {
+  if (Peer) Peer.close();
+  if (remoteVideo) remoteVideo.srcObject = null;
+  if (socket) socket.disconnect();
+  isLogin.value = false;
+  showLoading.value = false;
+  error.value = err || "";
+  socket.value = null;
+  Peer.value = null
+  num.value = 0
+  cancelAnimationFrame(ControlData);
+  window.removeEventListener("gamepadconnected", conControl);
+  window.removeEventListener("gamepaddisconnected", disControl);
+}
+
+// 手柄连接
+function conControl() {
+  contrlState.value = true;
+  ControlData();
+}
+
+// 手柄断开连接
+function disControl() {
+  contrlState.value = false;
+  cancelAnimationFrame(ControlData);
+}
+
+watch(() => mutedState.value, (v) => {
+  if (v) {
+    const state = !!(num.value % 2)
+    muted.value = state
+    if (socket.value && socket.value.connected) socket.value.emit("msg", { type: "contrlAudio", contrlAudio: state });
+    num.value++
+  }
+})
+watch(() => warnAudio.value, (v) => {
+  if (v && socket.value && socket.value.connected) socket.value.emit("msg", { type: "warnAudio", warnAudio: v });
+})
+onMounted(() => {
+  intSoketRtc(HOST.value)
+})
+onUnmounted(() => {
+  close()
+})
+</script>
+<template>
+  <template v-if="isLogin">
+    <video ref="remoteVideo" autoplay playsinline muted></video>
+    <div class="marke">
+      <!-- 手柄状态 -->
+      <div class="marke-contrl" :style="`color:${contrlState ? '#00CED1' : 'rgba(0, 0, 0, 0.3)'}`">&#xe72a;</div>
+      <!-- 音频状态 -->
+      <Record class="marke-audio" @callBack="sendAudio" :audioState="audioState" />
+      <!-- 喇叭状态 -->
+      <div class="marke-arcode" :style="`color:${muted ? '#00CED1' : 'rgba(0, 0, 0, 0.3)'}`">&#xe600;</div>
+      <!-- 电量状态 -->
+      <Battery :quantity="60" />
+    </div>
+    <!-- 码数 -->
+    <div class="gauge">
+      <Gauge :value="SpeedValue" :gears="speed" />
+    </div>
+    <Loading v-if="showLoading" />
+  </template>
+  <Login v-else :err="error" @loginBack="login" />
+</template>
+<style scoped lang="less">
+video {
+  background: none;
+  object-fit: fill;
+  font-size: 0;
+}
+
+.marke {
+  position: fixed;
+  top: 0;
+  left: 0;
+  width: 100%;
+  padding: 5px 0;
+  z-index: 1;
+  background: rgba(0, 0, 0, 0.25);
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  overflow: hidden;
+
+  &>div {
+    margin: 0 0.18rem;
+  }
+
+  &-audio,
+  &-arcode {
+    font-size: 24px;
+    color: rgba(0, 0, 0, 0.3);
+  }
+
+  &-contrl {
+    font-size: 32px;
+    color: rgba(0, 0, 0, 0.3);
+  }
+
+
+}
+
+.gauge {
+  position: fixed;
+  bottom: 0;
+  left: 50%;
+  transform: translate(-50%, 0);
+  width: 500px;
+  height: 185px;
+  z-index: 9;
+}
+
+
+/* 隐藏滚动条 */
+::-webkit-scrollbar {
+  width: 0 !important;
+  display: none;
+}
+</style>

+ 9 - 0
src/views/index/route.ts

@@ -0,0 +1,9 @@
+import home from './index.vue'
+
+export default {
+  path: '/',
+  meta: {
+    authorize: true
+  },
+  component: home
+}

+ 11 - 0
src/vite-env.d.ts

@@ -0,0 +1,11 @@
+/// <reference types="vite/client" />
+
+declare module '*.vue' {
+  import type { DefineComponent } from 'vue'
+  const component: DefineComponent<{}, {}, any>
+  export default component
+}
+
+declare interface Window {
+  $electron: Any
+}

+ 38 - 0
tsconfig.json

@@ -0,0 +1,38 @@
+{
+  "compilerOptions": {
+    "target": "ESNext",
+    "useDefineForClassFields": true,
+    "experimentalDecorators": true,
+    "module": "ESNext",
+    "moduleResolution": "Node",
+    "strict": true,
+    "jsx": "preserve",
+    "sourceMap": true,
+    "resolveJsonModule": true,
+    "isolatedModules": true,
+    "esModuleInterop": true,
+    "lib": [
+      "ESNext",
+      "DOM"
+    ],
+    "skipLibCheck": true,
+    "baseUrl": "./",
+    "paths": {
+      "@/*": [
+        "src/*"
+      ]
+    },
+    "types": ["vite-plugin-svg-icons/client"]
+  },
+  "include": [
+    "src/**/*.ts",
+    "src/**/*.d.ts",
+    "src/**/*.tsx",
+    "src/**/*.vue"
+  ],
+  "references": [
+    {
+      "path": "./tsconfig.node.json"
+    }
+  ]
+}

+ 9 - 0
tsconfig.node.json

@@ -0,0 +1,9 @@
+{
+  "compilerOptions": {
+    "composite": true,
+    "module": "ESNext",
+    "moduleResolution": "Node",
+    "allowSyntheticDefaultImports": true
+  },
+  "include": ["vite.config.ts"]
+}

+ 57 - 0
vite.config.ts

@@ -0,0 +1,57 @@
+import { defineConfig } from 'vite'
+import vue from '@vitejs/plugin-vue'
+import eslint from 'vite-plugin-eslint'
+import viteCompression from 'vite-plugin-compression'
+import { resolve } from 'path'
+import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
+
+export default () => defineConfig({
+  base: './',
+  resolve: {
+    alias: {
+      '@': resolve(__dirname, './src')
+    }
+  },
+  plugins: [
+    vue(),
+    viteCompression(),
+    eslint({ fix: true, include: ['**/*.ts', '**/*.vue'] }),
+    createSvgIconsPlugin({
+      iconDirs: [resolve(__dirname, './src/assets/icons')],
+      // Specify symbolId format
+      symbolId: 'icon-[dir]-[name]'
+    }),
+  ],
+  server: {
+    host: '0.0.0.0',
+    port: 6547,
+    open: true,
+    strictPort: false,
+    https: false,
+  },
+  esbuild: {
+    drop: ['console', 'debugger'] // build 移除打印
+  },
+  build: {
+    rollupOptions: {
+      input: {
+        index: resolve(__dirname, 'index.html')
+      },
+      output: { // 静态资源分类打包
+        chunkFileNames: 'js/[hash].js',
+        entryFileNames: 'js/[hash].js',
+        assetFileNames: 'assets/[ext]/[hash].[ext]',
+        // 拆分node_modules包
+        manualChunks: (id) => {
+          if (id.includes('node_modules')) {
+            return id.toString().split('node_modules/')[1].split('/')[0].toString()
+          }
+          return ''
+        }
+      }
+    }
+  },
+  define: {
+    __VUE_OPTIONS_API__: false
+  }
+})

+ 0 - 48
vue.config.js

@@ -1,48 +0,0 @@
-const CompressionPlugin = require('compression-webpack-plugin');
-module.exports = {
-    publicPath: './',
-    outputDir: './www',
-    assetsDir: 'static',
-    productionSourceMap: false,
-    lintOnSave: true,
-    filenameHashing: true,
-    devServer: {
-        https: false,
-        port: 4562
-    },
-    configureWebpack: () => {
-        if (process.env.NODE_ENV === 'production') {
-            return {
-                plugins: [
-                    new CompressionPlugin({
-                        minRatio: 1, // 压缩率小于1才会压缩
-                        test: /\.js$|.html$|\.css$/, // 匹配文件名
-                        threshold: 10240, // 对超过10k的文件进行压缩
-                        deleteOriginalAssets: false // 是否删除原文件                        
-                    })
-                ],
-                optimization: {
-                    runtimeChunk: 'single',
-                    splitChunks: {
-                        chunks: 'all',
-                        maxInitialRequests: Infinity,
-                        minSize: 20000,
-                        cacheGroups: {
-                            vendor: {
-                                test: /[\\/]node_modules[\\/]/,
-                                name(module) {
-                                    // get the name. E.g. node_modules/packageName/not/this/part.js
-                                    // or node_modules/packageName
-                                    const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
-                                    // npm package names are URL-safe, but some servers don't like @ symbols
-                                    return `npm.${packageName.replace('@', '')}`
-                                }
-                            }
-                        }
-                    }
-                }
-            }
-        }
-    }
-
-}