run-process.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/env node
  2. /**
  3. * run-process.js
  4. * 接收两个参数:ip 数组 (JSON)、脚本名
  5. * 异步根据每个 ip 执行脚本;执行前先 adb connect 该设备,确保连接成功再跑流程。
  6. *
  7. * 调用示例:node run-process.js '["192.168.2.5","192.168.2.6"]' 'RedNoteAIThumbsUp'
  8. */
  9. const path = require('path')
  10. const fs = require('fs')
  11. const { execSync } = require('child_process')
  12. const projectRoot = path.resolve(path.join(__dirname, '..'))
  13. const staticRoot = process.env.STATIC_ROOT ? path.resolve(process.env.STATIC_ROOT) : path.join(projectRoot, 'static')
  14. const config = require(path.join(projectRoot, 'configs', 'config.js'))
  15. const adbPath = config.adbPath?.path
  16. ? path.resolve(projectRoot, config.adbPath.path)
  17. : path.join(projectRoot, 'lib', 'scrcpy-adb', 'adb.exe')
  18. const ADB_PORT = 5555
  19. const ipListJson = process.argv[2]
  20. const scriptName = process.argv[3]
  21. const folderPath = path.resolve(path.join(staticRoot, 'process', scriptName))
  22. const ipList = JSON.parse(ipListJson)
  23. let shouldStop = false
  24. const { parseWorkflow } = require('./ef-compiler/ef-compiler.js')
  25. const actions = parseWorkflow(JSON.parse(fs.readFileSync(path.join(folderPath, 'process.json'), 'utf8'))).actions
  26. const { executeActionSequence } = require('./ef-compiler/ef-compiler.js')
  27. const resolution = { width: 1080, height: 1920 }
  28. /** 对指定 IP 执行 adb connect,确保设备在列表中后再跑流程 */
  29. function ensureDeviceConnected(ip, port) {
  30. const out = execSync(`"${adbPath}" connect ${ip}:${port}`, { encoding: 'utf-8' }).trim()
  31. return out.includes('connected') || out.includes('already connected')
  32. }
  33. /** 启动执行:遍历 ip 列表并异步执行脚本;任一台失败则停止全部并返回失败设备 IP */
  34. async function start() {
  35. let failedIp = null
  36. const runOne = async (ip) => {
  37. if (shouldStop) return { ip, success: false, stopped: true }
  38. const connected = ensureDeviceConnected(ip, ADB_PORT)
  39. if (!connected) return { ip, success: false }
  40. const result = await executeActionSequence(actions, `${ip}:${ADB_PORT}`, folderPath, resolution, 1000, null, () => shouldStop)
  41. if (!result.success) {
  42. if (!failedIp) { failedIp = ip; shouldStop = true }
  43. }
  44. return { ip, success: result.success }
  45. }
  46. const results = await Promise.all(ipList.map(ip => runOne(ip)))
  47. const output = failedIp
  48. ? { success: false, failedIp, results }
  49. : { success: true, results }
  50. process.stdout.write(JSON.stringify(output) + '\n')
  51. process.exit(failedIp ? 1 : 0)
  52. }
  53. /** 停止执行(SIGTERM/SIGINT 时调用) */
  54. function stop() {
  55. shouldStop = true
  56. }
  57. process.on('SIGTERM', () => { stop(); process.exit(130) })
  58. process.on('SIGINT', () => { stop(); process.exit(130) })
  59. start()