费森4008s 网口通讯 ,原生串口透传网口
chenyc
7 天以前 11e1b9d3ed909b28ef8e3330d152730c4e6d67c6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const http = require('http');
 
function json(res, status, body) {
  const data = typeof body === 'string' ? body : JSON.stringify(body);
  res.writeHead(status, {
    'Content-Type': 'application/json; charset=utf-8',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type'
  });
  res.end(typeof body === 'string' ? body : JSON.stringify(body, null, 2));
}
 
function notFound(res) {
  json(res, 404, { error: 'Not Found' });
}
 
function startHttpApi({ host = '0.0.0.0', port = 8080, getDevices, getAllData, getDataBySerial }) {
  const server = http.createServer((req, res) => {
    if (req.method === 'OPTIONS') {
      res.writeHead(204, {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type'
      });
      return res.end();
    }
 
    const url = new URL(req.url, `http://${req.headers.host}`);
    const path = url.pathname;
 
    // 路由
    if (req.method === 'GET' && path === '/api/devices') {
      const list = getDevices();
      return json(res, 200, { devices: list });
    }
 
    if (req.method === 'GET' && path === '/api/data') {
      const all = getAllData();
      return json(res, 200, all);
    }
 
    if (req.method === 'GET' && path.startsWith('/api/data/')) {
      const serial = decodeURIComponent(path.substring('/api/data/'.length));
      if (!serial) return notFound(res);
      const data = getDataBySerial(serial);
      if (!data) return notFound(res);
      return json(res, 200, data);
    }
 
    return notFound(res);
  });
 
  server.listen(port, host, () => {
    console.log(`🌐 HTTP API 已启动: http://${host}:${port}`);
    console.log('  • GET /api/devices  → 已连接设备序列号列表');
    console.log('  • GET /api/data     → 全部设备最新解析数据');
    console.log('  • GET /api/data/:serial → 指定设备最新解析数据');
  });
 
  return server;
}
 
module.exports = { startHttpApi };