| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- #!/usr/bin/env node
- /**
- * run-process.js
- * 接收两个参数:ip 数组 (JSON)、脚本名
- * 异步根据每个 ip 执行脚本;执行前先 adb connect 该设备,确保连接成功再跑流程。
- *
- * 调用示例:node run-process.js '["192.168.2.5","192.168.2.6"]' 'RedNoteAIThumbsUp'
- */
- const path = require('path')
- const fs = require('fs')
- const { execSync } = require('child_process')
- const projectRoot = path.resolve(path.join(__dirname, '..'))
- const staticRoot = process.env.STATIC_ROOT ? path.resolve(process.env.STATIC_ROOT) : path.join(projectRoot, 'static')
- const config = require(path.join(projectRoot, 'configs', 'config.js'))
- const adbPath = config.adbPath?.path
- ? path.resolve(projectRoot, config.adbPath.path)
- : path.join(projectRoot, 'lib', 'scrcpy-adb', 'adb.exe')
- const ADB_PORT = 5555
- const ipListJson = process.argv[2]
- const scriptName = process.argv[3]
- const folderPath = path.resolve(path.join(staticRoot, 'process', scriptName))
- const logFilePath = path.join(folderPath, 'log.txt')
- const ipList = JSON.parse(ipListJson)
- let shouldStop = false
- function appendLog(text) {
- try {
- fs.appendFileSync(logFilePath, text, 'utf8')
- } catch (e) {}
- }
- function logLine(msg) {
- const line = `[${new Date().toISOString()}] ${msg}\n`
- process.stdout.write(line)
- appendLog(line)
- }
- const { parseWorkflow } = require('./ef-compiler/ef-compiler.js')
- const actions = parseWorkflow(JSON.parse(fs.readFileSync(path.join(folderPath, 'process.json'), 'utf8'))).actions
- const { executeActionSequence } = require('./ef-compiler/ef-compiler.js')
- const resolution = { width: 1080, height: 1920 }
- function sleep(ms) {
- return new Promise((resolve) => setTimeout(resolve, ms))
- }
- /** 对指定 IP 执行 adb connect,与 bat-tool/adb-connect-test 行为一致:可重试、短延迟,确保设备就绪 */
- async function ensureDeviceConnected(ip, port, logLineFn) {
- const deviceId = `${ip}:${port}`
- const maxTries = 3
- const delayMs = 2000
- for (let i = 0; i < maxTries; i++) {
- try {
- const out = execSync(`"${adbPath}" connect ${deviceId}`, { encoding: 'utf-8' }).trim()
- if (out.includes('connected') || out.includes('already connected')) return true
- } catch (e) {
- // execSync 抛错(如 adb 未找到)时不再重试
- if (logLineFn) logLineFn(`Connect attempt ${i + 1}/${maxTries}: ${(e.stderr || e.message || '').trim() || 'failed'}`)
- }
- if (i < maxTries - 1) {
- if (logLineFn) logLineFn(`Wait ${delayMs / 1000}s, retry connect ${deviceId} ...`)
- await sleep(delayMs)
- }
- }
- return false
- }
- /** 启动执行:遍历 ip 列表并异步执行脚本;任一台失败则停止全部并返回失败设备 IP */
- async function start() {
- appendLog(`\n========== Run ${new Date().toISOString()} ==========\n`)
- logLine(`Process "${scriptName}" start, devices: ${ipList.length}`)
- let failedIp = null
- const runOne = async (ip) => {
- if (shouldStop) return { ip, success: false, stopped: true }
- const deviceId = ip.includes(':') ? ip : `${ip}:${ADB_PORT}`
- const [deviceIp, devicePort] = deviceId.includes(':') ? deviceId.split(':') : [ip, ADB_PORT]
- logLine(`Connecting ${deviceId} ...`)
- const connected = await ensureDeviceConnected(deviceIp, devicePort, logLine)
- if (!connected) {
- logLine(`Failed to connect ${deviceId}`)
- return { ip, success: false }
- }
- logLine(`Running on ${deviceId}`)
- const result = await executeActionSequence(actions, deviceId, folderPath, resolution, 1000, null, () => shouldStop)
- if (!result.success) {
- if (!failedIp) { failedIp = ip; shouldStop = true }
- }
- return { ip, success: result.success }
- }
- const results = await Promise.all(ipList.map(ip => runOne(ip)))
- const output = failedIp
- ? { success: false, failedIp, results }
- : { success: true, results }
- logLine(failedIp ? `Process finished with failed device: ${failedIp}` : 'Process finished successfully.')
- const resultLine = JSON.stringify(output) + '\n'
- process.stdout.write(resultLine)
- appendLog(resultLine)
- process.exit(failedIp ? 1 : 0)
- }
- /** 停止执行(SIGTERM/SIGINT 时调用) */
- function stop() {
- shouldStop = true
- }
- process.on('SIGTERM', () => { stop(); process.exit(130) })
- process.on('SIGINT', () => { stop(); process.exit(130) })
- start()
|