'use strict'; const { Controller } = require('egg'); /** * 设备态:边缘任务通道(**需长期设备 JWT**) * * 打包仓库的扫码服务没有公网 IP,只能自己出站来领任务: * - `POST /api/scanner/tasks/poll?wait=25`:没有任务就挂住,有任务立刻返回; * - `POST /api/scanner/tasks/:id/result`:回执行结果。 * * 云端从不主动连设备 —— 这也正是跨公司场景能成立的原因。 */ class DeviceEdgeController extends Controller { /** * 领任务(长轮询) * * 返回 204 表示这段时间没有任务,客户端立刻再发起下一次即可。 */ async poll() { const { ctx } = this; const scanner = ctx.state.scanner; // 上限 25 秒:比心跳间隔短,也能避开大多数反代的读超时(默认 60s) const wait = Math.min(Math.max(Number(ctx.query.wait) || 25, 1), 25); const task = await ctx.service.edgeTask.poll(scanner.id, wait * 1000); if (!task) { ctx.status = 204; return; } ctx.logger.info('[edge] 设备 %s 领取任务 %s(%s)', scanner.sn, task.id, task.type); ctx.body = { ok: true, data: task }; } /** * 回任务结果 * * body: `{ ok: true, ... }` 或 `{ ok: false, error: '...' }` */ async result() { const { ctx } = this; const id = String(ctx.params.id || '').trim(); if (!id) ctx.throw(400, '缺少任务 id'); const body = ctx.request.body || {}; await ctx.service.edgeTask.submitResult(id, body); ctx.logger.info('[edge] 设备 %s 回任务 %s:ok=%s', ctx.state.scanner.sn, id, body.ok); ctx.body = { ok: true }; } } module.exports = DeviceEdgeController;