run-process.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. #!/usr/bin/env node
  2. /**
  3. * run-process.js
  4. * 接收两个参数:ip 数组 (JSON)、脚本名
  5. * 异步根据每个 ip 执行脚本;执行前先 adb connect 该设备,确保连接成功再跑流程。
  6. * 运行日志与错误一律写入 static/process/<脚本名>/log.txt,便于打包后排查。
  7. *
  8. * 调用示例:node run-process.js '["192.168.2.5","192.168.2.6"]' 'RedNoteAIThumbsUp'
  9. */
  10. const path = require('path')
  11. const fs = require('fs')
  12. const { execSync } = require('child_process')
  13. // 先确定 process 目录和 log 路径(仅依赖 env 和 argv),确保失败时也能写 log.txt
  14. const staticRoot = process.env.STATIC_ROOT ? path.resolve(process.env.STATIC_ROOT) : path.join(__dirname, '..', 'static')
  15. const scriptName = process.argv[3] || 'Unknown'
  16. const folderPath = path.resolve(path.join(staticRoot, 'process', scriptName))
  17. const logFilePath = path.join(folderPath, 'log.txt')
  18. function ensureProcessDirAndLog() {
  19. try {
  20. if (!fs.existsSync(folderPath)) fs.mkdirSync(folderPath, { recursive: true })
  21. } catch (e) {}
  22. }
  23. const UTF8_BOM = Buffer.from('\uFEFF', 'utf8')
  24. function appendLog(text) {
  25. ensureProcessDirAndLog()
  26. try {
  27. const str = typeof text === 'string' ? text : String(text)
  28. const exists = fs.existsSync(logFilePath)
  29. const needsBom = !exists || (exists && fs.statSync(logFilePath).size === 0)
  30. if (needsBom) fs.appendFileSync(logFilePath, UTF8_BOM)
  31. fs.appendFileSync(logFilePath, Buffer.from(str, 'utf8'))
  32. } catch (e) {}
  33. }
  34. function writeErrorAndExit(message, err) {
  35. const line = `[${new Date().toISOString()}] [run-process] ERROR: ${message}${err ? ' ' + (err.stack || err.message) : ''}\n`
  36. process.stderr.write(line)
  37. appendLog(line)
  38. process.exit(1)
  39. }
  40. ensureProcessDirAndLog()
  41. let config, projectRoot, adbPath, ipListJson, ipList, actions, resolution, executeActionSequence
  42. try {
  43. const configPath = process.env.STATIC_ROOT ? path.join(path.dirname(staticRoot), 'configs', 'config.js') : path.join(__dirname, '..', 'configs', 'config.js')
  44. projectRoot = path.dirname(path.dirname(path.resolve(configPath)))
  45. config = require(configPath)
  46. adbPath = config.adbPath?.path
  47. ? (path.isAbsolute(config.adbPath.path) ? config.adbPath.path : path.resolve(projectRoot, config.adbPath.path))
  48. : path.join(projectRoot, 'lib', 'scrcpy-adb', process.platform === 'win32' ? 'adb.exe' : 'adb')
  49. ipListJson = process.argv[2]
  50. ipList = JSON.parse(ipListJson || '[]')
  51. const processJsonPath = path.join(folderPath, 'process.json')
  52. if (!fs.existsSync(processJsonPath)) {
  53. writeErrorAndExit(`process.json not found: ${processJsonPath}`)
  54. }
  55. const efCompiler = require('./ef-compiler/ef-compiler.js')
  56. const workflow = JSON.parse(fs.readFileSync(processJsonPath, 'utf8'))
  57. actions = efCompiler.parseWorkflow(workflow).actions
  58. executeActionSequence = efCompiler.executeActionSequence
  59. resolution = { width: 1080, height: 1920 }
  60. } catch (e) {
  61. writeErrorAndExit('run-process init failed', e)
  62. }
  63. const ADB_PORT = 5555
  64. let shouldStop = false
  65. function logLine(msg) {
  66. const line = `[${new Date().toISOString()}] [run-process] ${msg}\n`
  67. process.stdout.write(line)
  68. appendLog(line)
  69. }
  70. function sleep(ms) {
  71. return new Promise((resolve) => setTimeout(resolve, ms))
  72. }
  73. /** Windows 下 cmd/adb 的 stderr 多为 GBK,需按 GBK 解码再写入 log 才能正确显示中文 */
  74. function decodeStderrForLog(stderr) {
  75. if (stderr == null) return ''
  76. if (Buffer.isBuffer(stderr) && process.platform === 'win32') {
  77. try {
  78. const iconv = require('iconv-lite')
  79. return (iconv.decode(stderr, 'gbk') || stderr.toString('utf8')).trim()
  80. } catch (_) {
  81. return stderr.toString('utf8').trim()
  82. }
  83. }
  84. const s = typeof stderr === 'string' ? stderr : (stderr && stderr.toString ? stderr.toString() : '')
  85. return s.trim()
  86. }
  87. /** 对指定 IP 执行 adb connect,与 bat-tool/adb-connect-test 行为一致:可重试、短延迟,确保设备就绪 */
  88. async function ensureDeviceConnected(ip, port, logLineFn) {
  89. const deviceId = `${ip}:${port}`
  90. const maxTries = 3
  91. const delayMs = 2000
  92. const execOpts = process.platform === 'win32' ? { encoding: null } : { encoding: 'utf-8' }
  93. for (let i = 0; i < maxTries; i++) {
  94. try {
  95. const out = execSync(`"${adbPath}" connect ${deviceId}`, execOpts)
  96. const outStr = Buffer.isBuffer(out) ? out.toString('utf8') : String(out)
  97. if (outStr.trim().includes('connected') || outStr.trim().includes('already connected')) return true
  98. } catch (e) {
  99. const errText = process.platform === 'win32' ? decodeStderrForLog(e.stderr) : (e.stderr || e.message || '').trim()
  100. const pathExists = fs.existsSync(adbPath) ? 'exists' : 'NOT FOUND'
  101. if (logLineFn) logLineFn(`Connect attempt ${i + 1}/${maxTries}: ${errText || e.message || 'failed'} (adb path: ${adbPath}, ${pathExists})`)
  102. }
  103. if (i < maxTries - 1) {
  104. if (logLineFn) logLineFn(`Wait ${delayMs / 1000}s, retry connect ${deviceId} ...`)
  105. await sleep(delayMs)
  106. }
  107. }
  108. return false
  109. }
  110. /** 启动执行:遍历 ip 列表并异步执行脚本;任一台失败则停止全部并返回失败设备 IP;log.txt 仅写入报错与带 log:true 的 echo */
  111. async function start() {
  112. logLine(`Process "${scriptName}" start, devices: ${ipList.length}`)
  113. let failedIp = null
  114. const runOne = async (ip) => {
  115. if (shouldStop) return { ip, success: false, stopped: true }
  116. const deviceId = ip.includes(':') ? ip : `${ip}:${ADB_PORT}`
  117. const [deviceIp, devicePort] = deviceId.includes(':') ? deviceId.split(':') : [ip, ADB_PORT]
  118. logLine(`Connecting ${deviceId} ...`)
  119. const connected = await ensureDeviceConnected(deviceIp, devicePort, logLine)
  120. if (!connected) {
  121. logLine(`Failed to connect ${deviceId}`)
  122. return { ip, success: false }
  123. }
  124. logLine(`Running on ${deviceId}`)
  125. const result = await executeActionSequence(actions, deviceId, folderPath, resolution, 1000, null, () => shouldStop)
  126. if (!result.success) {
  127. if (!failedIp) { failedIp = ip; shouldStop = true }
  128. }
  129. return { ip, success: result.success }
  130. }
  131. const results = await Promise.all(ipList.map(ip => runOne(ip)))
  132. const output = failedIp
  133. ? { success: false, failedIp, results }
  134. : { success: true, results }
  135. logLine(failedIp ? `Process finished with failed device: ${failedIp}` : 'Process finished successfully.')
  136. const resultLine = JSON.stringify(output) + '\n'
  137. process.stdout.write(resultLine)
  138. process.exit(failedIp ? 1 : 0)
  139. }
  140. /** 停止执行(SIGTERM/SIGINT 时调用) */
  141. function stop() {
  142. shouldStop = true
  143. }
  144. process.on('SIGTERM', () => { stop(); process.exit(130) })
  145. process.on('SIGINT', () => { stop(); process.exit(130) })
  146. start().catch((e) => {
  147. writeErrorAndExit('run-process start failed', e)
  148. })