adb-sys-btn.js 2.3 KB

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