#!/usr/bin/env node /** * 模拟系统按键:home、返回 * 用法:node adb-sys-btn.js [deviceId] * 或: node adb-sys-btn.js <3|4> [deviceId] (3=Home 4=Back) * 也可被 require 后调用:sendSystemButton(button, deviceId) => { success, error } */ const path = require('path') const { execSync } = require('child_process') const config = require(path.join(__dirname, '..', '..', 'configs', 'config.js')) const projectRoot = path.resolve(__dirname, '..', '..') const adbPath = config.adbPath?.path ? path.resolve(projectRoot, config.adbPath.path) : path.join(projectRoot, 'lib', 'scrcpy-adb', 'adb.exe') const keycodeMap = { home: '3', back: '4', '3': '3', '4': '4', } /** * 发送系统按键(可被 ef-compiler 等 require 调用) * @param {string} button - 'home' | 'back' | '3' | '4' * @param {string} [deviceId] - 设备 ID,如 192.168.2.5:5555 * @returns {{ success: boolean, error?: string }} */ function sendSystemButton(button, deviceId = '') { const keyCode = keycodeMap[String(button).toLowerCase()] if (!keyCode) { return { success: false, error: `不支持的按键: ${button},支持 home/back/3/4` } } const deviceFlag = deviceId && String(deviceId).includes(':') ? `-s ${deviceId} ` : '' const quoted = adbPath.includes(' ') ? `"${adbPath}"` : adbPath try { execSync(`${quoted} ${deviceFlag}shell input keyevent ${keyCode}`, { encoding: 'utf-8', timeout: 3000 }) return { success: true } } catch (e) { return { success: false, error: e.message || String(e) } } } // CLI 入口 if (require.main === module) { const button = (process.argv[2] || '').toLowerCase() const deviceId = process.argv[3] || '' const keyCode = keycodeMap[button] if (!keyCode) { process.stderr.write('用法: node adb-sys-btn.js [deviceId]\n') process.exit(1) } const result = sendSystemButton(button, deviceId) if (!result.success) { process.stderr.write(result.error || '未知错误') process.exit(1) } process.exit(0) } module.exports = { sendSystemButton }