Files
scanner_record/README.md
T

456 lines
13 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 质量追溯系统 (Scanner Record)
西门子 S7 PLC 测量数据自动采集与追溯系统。
## 目录结构
```
scanner_record/
├── project/ # TypeScript 项目(主程序)
│ ├── .env # 配置文件(gitignored)
│ ├── .env.example # 配置示例
│ ├── src/
│ │ ├── index.ts # 入口:HTTP + PLC 轮询
│ │ ├── logger.ts # 分级日志 + 按天滚动保留 7 天
│ │ ├── types.ts # 共享类型
│ │ ├── database/
│ │ │ ├── connection.ts # SQLite 连接(WAL)
│ │ │ └── schema.ts # 建表 / CRUD
│ │ ├── api/
│ │ │ ├── config.ts # 设备配置 API
│ │ │ ├── query.ts # 追溯 + 互锁 API
│ │ │ └── monitor.ts # 状态 API
│ │ ├── plc/
│ │ │ ├── protocol.ts # 地址偏移 / ControlWord
│ │ │ ├── client.ts # Snap7 读写 + TCP 探测
│ │ │ └── scanner.ts # 轮询 + 断线重连
│ │ └── services/
│ │ ├── collection.ts # 采集入库
│ │ └── interlock.ts # 工序互锁
│ ├── web/ # 前端(Vite + Tailwind CDN)
│ │ └── src/
│ │ ├── main.ts # 追溯 / 配置(二级标签)
│ │ └── api/client.ts # 后端 API 封装
│ ├── test/
│ │ ├── plc-comm.ts # PLC 通信诊断
│ │ └── README-PLC.md
│ └── data/ # SQLite(gitignored)
├── plc_protocol_design.md # PLC 协议文档
├── pc_database_design.md # PC 数据库设计
├── test_snap7.py # PLC 测试工具(Python CLI)
├── db_init.py / simulate.py # 旧版原型(参考)
├── FLOWCHART.md # Mermaid 流程图
├── README.md
└── .gitignore
```
---
## 项目进展
### ✅ 已完成
- [x] PLC 端协议设计(24 字节/工序,ControlWord 位定义)
- [x] PC 端数据库设计(按检测点分表,每天一张)
- [x] TypeScript 后端骨架(Hono + better-sqlite3 + node-snap7)
- [x] 前端 Vite 项目(Tailwind CSS,追溯查询 + 设备配置)
- [x] 数据库 CRUD API(检测点 / PLC / 工序 增删改查)
- [x] PLC 轮询扫描(每秒一次,批量读取所有工序)
- [x] 数据自动采集(DataReady=1 → 读取 → 入库 → 清标志)
- [x] 工序互锁(PrevResultReq=1 → 查数据库 → 写回结果)
- [x] 日志系统(分级 + 时间戳 + 模块标签 + 按天滚动保留 7 天)
- [x] 启动时自动建库(空数据库也能直接启动)
- [x] PLC 通信诊断工具(`npm run test:plc`)
- [x] 前端在线配置(检测点 / PLC / 工序 增删改)
- [x] `.env` 配置文件(轮询间隔、日志级别、断线参数)
- [x] PLC 断线自动重连机制(TCP 探测 + 状态机)
- [x] 批量 DB 读取(一次网络请求读完所有工序)
- [x] 测试脚本 `test_snap7.py` 命令行参数化
### 🚧 待完成
- [ ] 数据导出(CSV / Excel)
- [ ] ECharts 趋势图
- [ ] 用户登录 / 权限管理
- [ ] Windows 服务注册(开机自启)
---
## 快速开始
### 环境要求
- **Node.js** 22.x(node-snap7 不兼容 v25+)
- **npm** 11+
- **Python** 3.x(仅测试脚本需要)
### 配置
创建 `project/.env`(可从 `.env.example` 复制):
```ini
PORT=3000 # 服务端口
POLL_INTERVAL_MS=1000 # PLC 轮询间隔(毫秒)
LOG_LEVEL=1 # 日志级别: 0=DEBUG, 1=INFO, 2=WARN, 3=ERROR
PLC_FAIL_LIMIT=3 # 连续失败次数上限
PLC_PROBE_INTERVAL_MS=5000 # TCP 探测间隔(毫秒)
PLC_PROBE_TIMEOUT_MS=2000 # TCP 探测超时(毫秒)
# SKIP_PLC=1 # 跳过 PLC 连接(开发用)
```
### 启动
```bash
cd project
# 安装依赖
npm install
cd web && npm install && cd ..
# 构建前端
cd web && npm run build && cd ..
# 启动(无 PLC 模式,开发调试)
SKIP_PLC=1 npm run start
# 启动(连接真实 PLC)
npm run start
```
### 前端开发(热更新)
```bash
# 终端 1:后端
cd project && npm run dev
# 终端 2:前端(HMR)
cd project/web && npm run dev
```
---
## 架构
```
┌──────────────────────────────────────────────────────┐
│ 西门子 S7 PLC │
│ DB 块:工序 0 (偏移 0) | 工序 1 (偏移 24) | ... │
│ ControlWord: DataReady / IsQualified / PrevResultReq│
└──────────────────────┬───────────────────────────────┘
│ S7 协议 (Ethernet)
┌──────────────────────▼───────────────────────────────┐
│ Node.js 进程 (Hono) │
│ │
│ ┌─────────────┐ ┌──────────────┐ │
│ │ PLC Scanner │ │ REST API │ :3000 │
│ │ (1s 轮询) │ │ /api/* │ │
│ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │
│ ┌──────▼────────────────▼───────┐ │
│ │ better-sqlite3 │ │
│ │ data/production.db │ │
│ └──────────────────────────────┘ │
└──────┬───────────────────────────────────────────────┘
│ 静态文件 (/web/*)
┌──────▼───────────────────────────────────────────────┐
│ 前端 (Vite 构建产物) │
│ 追溯查询 / 设备配置 / 系统状态 │
└──────────────────────────────────────────────────────┘
```
---
## PLC 通信协议
| 字段 | 偏移 | 类型 | 大小 | 方向 | 说明 |
|------|------|------|------|------|------|
| ProductID | +0 | DINT | 4 | PLC→PC | 当前产品唯一编号 |
| UpperLimit | +4 | REAL | 4 | PLC→PC | 测量上限 |
| LowerLimit | +8 | REAL | 4 | PLC→PC | 测量下限 |
| MeasuredValue | +12 | REAL | 4 | PLC→PC | 实测值 |
| ControlWord | +16 | WORD | 2 | 双向 | 控制字(见下方) |
| Reserved | +18 | — | 6 | — | 保留 |
### ControlWord 位定义
| 位 | 名称 | 方向 | 说明 |
|---|------|------|------|
| Bit 0 | DataReady | PLC→PC | 1=有新的测量数据待读取 |
| Bit 1 | IsQualified | PLC→PC | 1=合格 |
| Bit 2 | PrevResultReq | PLC→PC | 1=请求上一工序结果 |
| Bit 3 | PrevResult | PC→PLC | PC 写入:1=合格,0=不合格 |
详见 `plc_protocol_design.md`。
---
## API 文档
### 基础信息
- **Base URL**: `http://localhost:3000/api`
- **Content-Type**: `application/json`
---
### 设备配置
#### `GET /api/config/plcs`
获取所有 PLC。
```json
[
{
"Id": 1,
"PLCName": "PLC01_焊接段",
"IPAddress": "192.168.0.10",
"DBNumber": 100,
"StationCount": 3
}
]
```
#### `POST /api/config/plcs`
新增 PLC。
```json
// Request
{ "PLCName": "PLC01", "IPAddress": "192.168.0.10", "DBNumber": 100 }
// Response
{ "Id": 1 }
```
#### `PUT /api/config/plcs/:id`
修改 PLC。
```json
{ "PLCName": "PLC01", "IPAddress": "192.168.0.11", "DBNumber": 200 }
```
#### `DELETE /api/config/plcs/:id`
删除 PLC(级联删除关联工序)。
---
#### `GET /api/config/measurement-points`
获取所有检测点。
```json
[
{ "Id": 1, "PointName": "焊接温度", "FieldUnit": "℃" }
]
```
#### `POST /api/config/measurement-points`
新增检测点(自动创建对应数据表)。
```json
{ "PointName": "焊接温度", "FieldUnit": "℃" }
```
---
#### `GET /api/config/stations`
获取所有工序。支持 `?plcId=1` 过滤。
```json
[
{ "Id": 1, "PLCId": 1, "StationIndex": 0, "StationName": "预焊接", "PointId": 1, "pointName": "焊接温度" }
]
```
#### `POST /api/config/stations`
新增工序。不传 `StationName` 时自动取检测点名。
```json
{ "PLCId": 1, "StationName": "预焊接", "PointId": 1, "StationIndex": 0 }
```
---
### 数据查询
#### `GET /api/query/:productId`
查询某产品在所有检测点的测量数据。
```json
{
"productId": "PROD-003",
"data": [
{
"pointId": 1,
"pointName": "焊接温度",
"fieldUnit": "℃",
"recordTime": "2026-06-08 07:54:42",
"isQualified": 1,
"inspectionCount": 1,
"upperLimit": 93.3,
"lowerLimit": 75.2,
"measuredValue": 90.2
}
]
}
```
#### `GET /api/query/:productId/interlock/:stationName`
查询某产品在某工序的上一工序合格情况。
```json
{
"currentStation": "焊后检测",
"currentPoint": "焊点直径",
"prevStation": "主焊接",
"prevPoint": "焊接电流",
"prevResult": 1
}
```
### 监控
#### `GET /api/monitor/status`
```json
{
"plcCount": 2,
"stationCount": 5,
"pointCount": 5,
"dataTableCount": 5,
"totalRecords": 60
}
```
---
## 数据流
### 采集流程
```
PLC: ControlWord.DataReady = 1
↓
PC: 读 DB 块 32 字节 → 解析 ProductID + 测量值 + ControlWord
↓
PC: 查数据库 → InspectionCount = max + 1
↓
PC: INSERT/UPDATE → MPData_P{PointId}_{日期}
↓
PC: ControlWord.DataReady = 0
```
### 互锁流程
```
PLC: ControlWord.PrevResultReq = 1
↓
PC: 读 DB → 获取 ProductID
↓
PC: 查数据库 → 前工序的最新 IsQualified
↓
PC: ControlWord.PrevResult = 1/0
↓
PC: ControlWord.PrevResultReq = 0
```
---
## 数据库结构
### 配置表
```
MeasurementPoints (Id, PointName, FieldUnit)
PLCs (Id, PLCName, IPAddress, DBNumber, StationCount)
Stations (Id, PLCId, StationIndex, StationName, PointId)
```
### 数据表(按检测点分表,每天一张)
```
MPData_P1_2026_06_08:
Id | ProductID | RecordTime | IsQualified | InspectionCount |
UpperLimit | LowerLimit | MeasuredValue
```
---
---
## PLC 断线重连机制
```
正常轮询 ── 连续失败 N 次 ──→ TCP 探测模式 ──→ 端口恢复 ──→ 重连 ──→ 正常轮询
```
- 连续读取失败 `PLC_FAIL_LIMIT`(默认 3)次后,停止对该 PLC 的 DB 读取
- 进入 TCP 探测模式,每 `PLC_PROBE_INTERVAL_MS`(默认 5s)检查一次 TCP 102 端口
- 端口恢复后自动调用 Snap7 `ConnectTo` 重连,成功后回到正常轮询
- 失败期间控制台**不刷屏**,只输出关键状态变更
---
## 测试工具
`test_snap7.py` 用于手动向 PLC 写入测试数据:
```bash
# 写入工序 0 完整数据 + 触发采集
python test_snap7.py --station 0 --product-id 10086 --upper 100.0 \
--lower 80.0 --measured 95.5 --dataready --qualified
# 工序 2 触发 PrevResultReq
python test_snap7.py --station 2 --prev-req
# 只读某一工序
python test_snap7.py --station 1 --read
# 触发 DataReady + 不合格
python test_snap7.py --station 0 --dataready --unqualified
```
### 参数说明
| 参数 | 说明 |
|------|------|
| `--ip` | PLC IP(默认 192.168.2.125)|
| `--db` | DB 块号(默认 1)|
| `--station` | 工序索引(默认 0)|
| `--read` | 读取本工序所有字段 |
| `--product-id` | 写入 ProductID (DINT) |
| `--upper / --lower / --measured` | 写入上限/下限/实测值 (REAL) |
| `--dataready` | 设置 ControlWord Bit0=1 |
| `--qualified` | 设置 Bit1=1(合格)|
| `--unqualified` | 设置 Bit1=0(不合格)|
| `--prev-req` | 设置 Bit2=1 (PrevResultReq) |
| `--value` | 直接写入 ControlWord 值 |
---
## 常见问题
### node-snap7 报 TypeError: Wrong arguments
Node.js v25+ 与 `node-snap7` 的 C++ 绑定不兼容。需降级到 Node.js 22.x:
```bash
nvm install 22
nvm use 22
npm rebuild node-snap7
```
### PLC 连接失败
使用诊断工具排查:
```bash
cd project
npm run test:plc -- <PLC_IP> 0 2
```
### 启动报 SQLITE_IOERR
删除旧的 WAL 文件后重试:
```bash
rm -f project/data/production.db*
```