| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165 |
- #!/usr/bin/env node
- /**
- * run-process.js
- * 接收两个参数:ip 数组 (JSON)、脚本名
- * 异步根据每个 ip 执行脚本;执行前先 adb connect 该设备,确保连接成功再跑流程。
- * 运行日志与错误一律写入 static/process/<脚本名>/log.txt,便于打包后排查。
- *
- * 调用示例: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')
- // 先确定 process 目录和 log 路径(仅依赖 env 和 argv),确保失败时也能写 log.txt
- const staticRoot = process.env.STATIC_ROOT ? path.resolve(process.env.STATIC_ROOT) : path.join(__dirname, '..', 'static')
- const scriptName = process.argv[3] || 'Unknown'
- const folderPath = path.resolve(path.join(staticRoot, 'process', scriptName))
- const logFilePath = path.join(folderPath, 'log.txt')
- function ensureProcessDirAndLog() {
- try {
- if (!fs.existsSync(folderPath)) fs.mkdirSync(folderPath, { recursive: true })
- } catch (e) {}
- }
- const UTF8_BOM = Buffer.from('\uFEFF', 'utf8')
- function appendLog(text) {
- ensureProcessDirAndLog()
- try {
- const str = typeof text === 'string' ? text : String(text)
- const exists = fs.existsSync(logFilePath)
- const needsBom = !exists || (exists && fs.statSync(logFilePath).size === 0)
- if (needsBom) fs.appendFileSync(logFilePath, UTF8_BOM)
- fs.appendFileSync(logFilePath, Buffer.from(str, 'utf8'))
- } catch (e) {}
- }
- function writeErrorAndExit(message, err) {
- const line = `[${new Date().toISOString()}] [run-process] ERROR: ${message}${err ? ' ' + (err.stack || err.message) : ''}\n`
- process.stderr.write(line)
- appendLog(line)
- process.exit(1)
- }
- ensureProcessDirAndLog()
- let config, projectRoot, adbPath, ipListJson, ipList, actions, resolution, executeActionSequence
- try {
- const configPath = process.env.STATIC_ROOT ? path.join(path.dirname(staticRoot), 'configs', 'config.js') : path.join(__dirname, '..', 'configs', 'config.js')
- projectRoot = path.dirname(path.dirname(path.resolve(configPath)))
- config = require(configPath)
- adbPath = config.adbPath?.path
- ? (path.isAbsolute(config.adbPath.path) ? config.adbPath.path : path.resolve(projectRoot, config.adbPath.path))
- : path.join(projectRoot, 'lib', 'scrcpy-adb', process.platform === 'win32' ? 'adb.exe' : 'adb')
- ipListJson = process.argv[2]
- ipList = JSON.parse(ipListJson || '[]')
- const processJsonPath = path.join(folderPath, 'process.json')
- if (!fs.existsSync(processJsonPath)) {
- writeErrorAndExit(`process.json not found: ${processJsonPath}`)
- }
- const efCompiler = require('./ef-compiler/ef-compiler.js')
- const workflow = JSON.parse(fs.readFileSync(processJsonPath, 'utf8'))
- actions = efCompiler.parseWorkflow(workflow).actions
- executeActionSequence = efCompiler.executeActionSequence
- resolution = { width: 1080, height: 1920 }
- } catch (e) {
- writeErrorAndExit('run-process init failed', e)
- }
- const ADB_PORT = 5555
- let shouldStop = false
- function logLine(msg) {
- const line = `[${new Date().toISOString()}] [run-process] ${msg}\n`
- process.stdout.write(line)
- appendLog(line)
- }
- function sleep(ms) {
- return new Promise((resolve) => setTimeout(resolve, ms))
- }
- /** Windows 下 cmd/adb 的 stderr 多为 GBK,需按 GBK 解码再写入 log 才能正确显示中文 */
- function decodeStderrForLog(stderr) {
- if (stderr == null) return ''
- if (Buffer.isBuffer(stderr) && process.platform === 'win32') {
- try {
- const iconv = require('iconv-lite')
- return (iconv.decode(stderr, 'gbk') || stderr.toString('utf8')).trim()
- } catch (_) {
- return stderr.toString('utf8').trim()
- }
- }
- const s = typeof stderr === 'string' ? stderr : (stderr && stderr.toString ? stderr.toString() : '')
- return s.trim()
- }
- /** 对指定 IP 执行 adb connect,与 bat-tool/adb-connect-test 行为一致:可重试、短延迟,确保设备就绪 */
- async function ensureDeviceConnected(ip, port, logLineFn) {
- const deviceId = `${ip}:${port}`
- const maxTries = 3
- const delayMs = 2000
- const execOpts = process.platform === 'win32' ? { encoding: null } : { encoding: 'utf-8' }
- for (let i = 0; i < maxTries; i++) {
- try {
- const out = execSync(`"${adbPath}" connect ${deviceId}`, execOpts)
- const outStr = Buffer.isBuffer(out) ? out.toString('utf8') : String(out)
- if (outStr.trim().includes('connected') || outStr.trim().includes('already connected')) return true
- } catch (e) {
- const errText = process.platform === 'win32' ? decodeStderrForLog(e.stderr) : (e.stderr || e.message || '').trim()
- const pathExists = fs.existsSync(adbPath) ? 'exists' : 'NOT FOUND'
- if (logLineFn) logLineFn(`Connect attempt ${i + 1}/${maxTries}: ${errText || e.message || 'failed'} (adb path: ${adbPath}, ${pathExists})`)
- }
- if (i < maxTries - 1) {
- if (logLineFn) logLineFn(`Wait ${delayMs / 1000}s, retry connect ${deviceId} ...`)
- await sleep(delayMs)
- }
- }
- return false
- }
- /** 启动执行:遍历 ip 列表并异步执行脚本;任一台失败则停止全部并返回失败设备 IP;log.txt 仅写入报错与带 log:true 的 echo */
- async function start() {
- 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)
- 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().catch((e) => {
- writeErrorAndExit('run-process start failed', e)
- })
|