| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- #!/usr/bin/env node
- const { execSync } = require('child_process')
- const path = require('path')
- // 项目根 = 脚本所在目录的上一级(nodejs -> 项目根)
- // 打包后 nodejs 在 app.asar 内执行,但 lib/configs 在 app.asar.unpacked,需用 unpacked 路径才能找到 adb
- let PROJECT_ROOT = path.resolve(__dirname, '..')
- if (PROJECT_ROOT.includes('app.asar') && !PROJECT_ROOT.includes('app.asar.unpacked')) {
- PROJECT_ROOT = PROJECT_ROOT.replace('app.asar', 'app.asar.unpacked')
- }
- const TCPIP_PORT = 5555
- /** 从配置解析并返回 ADB 可执行文件路径 */
- function getAdbPath() {
- const configPath = path.join(PROJECT_ROOT, 'configs', 'config.js')
- const config = require(configPath)
- return config.adbPath?.path
- ? path.resolve(PROJECT_ROOT, config.adbPath.path)
- : path.join(PROJECT_ROOT, 'lib', 'scrcpy-adb', 'adb.exe')
- }
- /** 返回当前通过 USB 连接的设备 ID 列表(仅 status 为 device 且非 IP:port,排除无线设备) */
- function getConnectedDeviceIds(adbPath) {
- const out = execSync(`"${adbPath}" devices`, { encoding: 'utf-8' })
- return out
- .split('\n')
- .filter((line) => line.trim() && !line.startsWith('List') && line.includes('\tdevice'))
- .map((line) => line.trim().split('\t')[0])
- .filter((id) => id && !id.includes(':'))
- }
- /** 操作一:在 USB 设备上开启无线调试(settings adb_wifi_enabled 1) */
- function enableWirelessSetting(adbPath, deviceId) {
- execSync(`"${adbPath}" -s ${deviceId} shell settings put global adb_wifi_enabled 1`, { encoding: 'utf-8' })
- }
- /** 操作二:在 USB 设备上激活 5555 端口(tcpip),用于无线连接 */
- function enableTcpipPort(adbPath, deviceId, port) {
- return execSync(`"${adbPath}" -s ${deviceId} tcpip ${port}`, { encoding: 'utf-8' }).trim()
- }
- /** 主流程:取 USB 设备,依次执行「开启无线调试」「激活 5555 端口」 */
- function run() {
- const adbPath = getAdbPath()
- const devices = getConnectedDeviceIds(adbPath)
- if (devices.length === 0) {
- process.stderr.write('No devices found. Please connect a device via USB.\n')
- process.exit(1)
- }
- const deviceId = devices[0]
- enableWirelessSetting(adbPath, deviceId)
- const tcpipOut = enableTcpipPort(adbPath, deviceId, TCPIP_PORT)
- process.stdout.write(tcpipOut + '\n')
- process.exit(0)
- }
- run()
|