enable-wirless-connect.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/env node
  2. const { execSync } = require('child_process')
  3. const path = require('path')
  4. // 项目根 = 脚本所在目录的上一级(nodejs -> 项目根)
  5. // 打包后 nodejs 在 app.asar 内执行,但 lib/configs 在 app.asar.unpacked,需用 unpacked 路径才能找到 adb
  6. let PROJECT_ROOT = path.resolve(__dirname, '..')
  7. if (PROJECT_ROOT.includes('app.asar') && !PROJECT_ROOT.includes('app.asar.unpacked')) {
  8. PROJECT_ROOT = PROJECT_ROOT.replace('app.asar', 'app.asar.unpacked')
  9. }
  10. const TCPIP_PORT = 5555
  11. /** 从配置解析并返回 ADB 可执行文件路径 */
  12. function getAdbPath() {
  13. const configPath = path.join(PROJECT_ROOT, 'configs', 'config.js')
  14. const config = require(configPath)
  15. return config.adbPath?.path
  16. ? path.resolve(PROJECT_ROOT, config.adbPath.path)
  17. : path.join(PROJECT_ROOT, 'lib', 'scrcpy-adb', 'adb.exe')
  18. }
  19. /** 返回当前通过 USB 连接的设备 ID 列表(仅 status 为 device 且非 IP:port,排除无线设备) */
  20. function getConnectedDeviceIds(adbPath) {
  21. const out = execSync(`"${adbPath}" devices`, { encoding: 'utf-8' })
  22. return out
  23. .split('\n')
  24. .filter((line) => line.trim() && !line.startsWith('List') && line.includes('\tdevice'))
  25. .map((line) => line.trim().split('\t')[0])
  26. .filter((id) => id && !id.includes(':'))
  27. }
  28. /** 操作一:在 USB 设备上开启无线调试(settings adb_wifi_enabled 1) */
  29. function enableWirelessSetting(adbPath, deviceId) {
  30. execSync(`"${adbPath}" -s ${deviceId} shell settings put global adb_wifi_enabled 1`, { encoding: 'utf-8' })
  31. }
  32. /** 操作二:在 USB 设备上激活 5555 端口(tcpip),用于无线连接 */
  33. function enableTcpipPort(adbPath, deviceId, port) {
  34. return execSync(`"${adbPath}" -s ${deviceId} tcpip ${port}`, { encoding: 'utf-8' }).trim()
  35. }
  36. /** 主流程:取 USB 设备,依次执行「开启无线调试」「激活 5555 端口」 */
  37. function run() {
  38. const adbPath = getAdbPath()
  39. const devices = getConnectedDeviceIds(adbPath)
  40. if (devices.length === 0) {
  41. process.stderr.write('No devices found. Please connect a device via USB.\n')
  42. process.exit(1)
  43. }
  44. const deviceId = devices[0]
  45. enableWirelessSetting(adbPath, deviceId)
  46. const tcpipOut = enableTcpipPort(adbPath, deviceId, TCPIP_PORT)
  47. process.stdout.write(tcpipOut + '\n')
  48. process.exit(0)
  49. }
  50. run()