adb-sys-btn.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/env node
  2. /**
  3. * 模拟系统按键:home、返回
  4. * 用法:node adb-sys-btn.js <home|back> [deviceId]
  5. * 或: node adb-sys-btn.js <3|4> [deviceId] (3=Home 4=Back)
  6. * 也可被 require 后调用:sendSystemButton(button, deviceId) => { success, error }
  7. */
  8. const path = require('path')
  9. const { execSync } = require('child_process')
  10. const config = require(path.join(__dirname, '..', '..', 'configs', 'config.js'))
  11. const projectRoot = path.resolve(__dirname, '..', '..')
  12. const adbPath = config.adbPath?.path
  13. ? path.resolve(projectRoot, config.adbPath.path)
  14. : path.join(projectRoot, 'lib', 'scrcpy-adb', 'adb.exe')
  15. const keycodeMap = {
  16. home: '3',
  17. back: '4',
  18. '3': '3',
  19. '4': '4',
  20. }
  21. /**
  22. * 发送系统按键(可被 ef-compiler 等 require 调用)
  23. * @param {string} button - 'home' | 'back' | '3' | '4'
  24. * @param {string} [deviceId] - 设备 ID,如 192.168.2.5:5555
  25. * @returns {{ success: boolean, error?: string }}
  26. */
  27. function sendSystemButton(button, deviceId = '') {
  28. const keyCode = keycodeMap[String(button).toLowerCase()]
  29. if (!keyCode) {
  30. return { success: false, error: `不支持的按键: ${button},支持 home/back/3/4` }
  31. }
  32. const deviceFlag = deviceId && String(deviceId).includes(':') ? `-s ${deviceId} ` : ''
  33. const quoted = adbPath.includes(' ') ? `"${adbPath}"` : adbPath
  34. try {
  35. execSync(`${quoted} ${deviceFlag}shell input keyevent ${keyCode}`, { encoding: 'utf-8', timeout: 3000 })
  36. return { success: true }
  37. } catch (e) {
  38. return { success: false, error: e.message || String(e) }
  39. }
  40. }
  41. // CLI 入口
  42. if (require.main === module) {
  43. const button = (process.argv[2] || '').toLowerCase()
  44. const deviceId = process.argv[3] || ''
  45. const keyCode = keycodeMap[button]
  46. if (!keyCode) {
  47. process.stderr.write('用法: node adb-sys-btn.js <home|back> [deviceId]\n')
  48. process.exit(1)
  49. }
  50. const result = sendSystemButton(button, deviceId)
  51. if (!result.success) {
  52. process.stderr.write(result.error || '未知错误')
  53. process.exit(1)
  54. }
  55. process.exit(0)
  56. }
  57. module.exports = { sendSystemButton }