init: PLC data collection system

This commit is contained in:
zlm committed 2026-06-09 14:32:13 +08:00
commit ae90bc9368
38 files changed
+5234

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
node_modules/
dist/
*.db
*.db-wal
*.db-shm
.env
+4
View File
@@ -0,0 +1,4 @@
{
"python-envs.defaultEnvManager": "ms-python.python:conda",
"python-envs.defaultPackageManager": "ms-python.python:conda"
}
+184
View File
@@ -0,0 +1,184 @@
import sqlite3
import json
import sys
import os
from datetime import date
DB_PATH = "production.db"
CONFIG_PATH = "config.json"
def create_config_tables(cursor):
cursor.executescript("""
CREATE TABLE IF NOT EXISTS MeasurementPoints (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
PointName TEXT NOT NULL,
FieldUnit TEXT DEFAULT '',
SortOrder INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS PLCs (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
PLCName TEXT NOT NULL,
IPAddress TEXT NOT NULL,
DBNumber INTEGER NOT NULL,
StationCount INTEGER NOT NULL,
SortOrder INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS Stations (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
PLCId INTEGER NOT NULL REFERENCES PLCs(Id),
StationIndex INTEGER NOT NULL,
StationName TEXT NOT NULL,
PointId INTEGER REFERENCES MeasurementPoints(Id),
SortOrder INTEGER DEFAULT 0
);
""")
def create_mp_data_tables(cursor, date_str: str):
cursor.execute("SELECT Id, PointName FROM MeasurementPoints ORDER BY Id")
points = cursor.fetchall()
if not points:
print(" [WARN] 没有注册检测点,跳过建表")
return
for pid, pname in points:
table = f"MPData_P{pid}_{date_str}"
cursor.execute(f"""
CREATE TABLE IF NOT EXISTS {table} (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
ProductID TEXT NOT NULL UNIQUE,
RecordTime DATETIME,
IsQualified INTEGER,
InspectionCount INTEGER DEFAULT 0,
UpperLimit REAL,
LowerLimit REAL,
MeasuredValue REAL
);
""")
print(f" [OK] {table}")
def clear_config_data(cursor):
cursor.executescript("""
DELETE FROM Stations;
DELETE FROM MeasurementPoints;
DELETE FROM PLCs;
""")
def init_from_config(config_path: str, db_path: str, date_str: str):
if not os.path.exists(config_path):
print(f"[ERROR] 配置文件不存在: {config_path}")
sys.exit(1)
with open(config_path, "r", encoding="utf-8") as f:
config = json.load(f)
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
print(">>> 创建配置表...")
create_config_tables(cursor)
print(">>> 清空旧配置数据...")
clear_config_data(cursor)
print(">>> 写入全局检测点...")
point_name_map = {}
for mp in config["measurement_points"]:
cursor.execute(
"""INSERT INTO MeasurementPoints (PointName, FieldUnit, SortOrder)
VALUES (?, ?, ?)""",
(mp["point_name"], mp.get("field_unit", ""), mp["sort_order"]),
)
point_name_map[mp["point_name"]] = cursor.lastrowid
print(">>> 写入 PLC 和工序配置...")
for plc in config["plcs"]:
cursor.execute(
"""INSERT INTO PLCs (PLCName, IPAddress, DBNumber, StationCount, SortOrder)
VALUES (?, ?, ?, ?, ?)""",
(plc["plc_name"], plc["ip_address"], plc["db_number"],
plc["station_count"], plc["sort_order"]),
)
plc_id = cursor.lastrowid
for st in plc["stations"]:
point_id = point_name_map.get(st["point_name"])
if point_id is None:
print(f" [WARN] 检测点 '{st['point_name']}' 未定义,跳过")
continue
cursor.execute(
"""INSERT INTO Stations (PLCId, StationIndex, StationName, PointId, SortOrder)
VALUES (?, ?, ?, ?, ?)""",
(plc_id, st["station_index"], st["station_name"], point_id, st["sort_order"]),
)
print(">>> 创建检测点数据表...")
create_mp_data_tables(cursor, date_str)
conn.commit()
conn.close()
print(f"\n[DONE] 数据库已初始化: {db_path}")
def show_summary(db_path: str, date_str: str):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
print("\n=== 全局检测点 ===")
cursor.execute("SELECT Id, PointName, FieldUnit FROM MeasurementPoints ORDER BY SortOrder")
for mp in cursor.fetchall():
unit = f" ({mp[2]})" if mp[2] else ""
print(f" P{mp[0]}: {mp[1]}{unit}")
print("\n=== 产线配置 ===")
cursor.execute("SELECT Id, PLCName, IPAddress, DBNumber, StationCount FROM PLCs ORDER BY SortOrder")
for plc in cursor.fetchall():
print(f"\nPLC: {plc[1]} ({plc[2]}, DB{plc[3]}, {plc[4]} 工序)")
cursor.execute("""
SELECT s.Id, s.StationName, s.StationIndex, s.PointId, mp.PointName
FROM Stations s
LEFT JOIN MeasurementPoints mp ON mp.Id = s.PointId
WHERE s.PLCId=? ORDER BY s.SortOrder
""", (plc[0],))
for st in cursor.fetchall():
print(f" ├─ {st[1]} (idx={st[2]})")
print(f" │ └─ P{st[3]}: {st[4]}")
print(f"\n=== 数据表 ===")
cursor.execute("SELECT Id, PointName FROM MeasurementPoints ORDER BY Id")
for pid, pname in cursor.fetchall():
table = f"MPData_P{pid}_{date_str}"
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table,))
if cursor.fetchone():
cursor.execute(f"PRAGMA table_info({table})")
cols = cursor.fetchall()
print(f" [OK] {table} ({len(cols)} 列) <- {pname}")
else:
print(f" [MISSING] {table}")
conn.close()
if __name__ == "__main__":
force = "-f" in sys.argv or "--force" in sys.argv
args = [a for a in sys.argv[1:] if not a.startswith("-")]
config_path = args[0] if len(args) > 0 else CONFIG_PATH
db_path = args[1] if len(args) > 1 else DB_PATH
date_str = date.today().strftime("%Y_%m_%d")
if os.path.exists(db_path):
if not force:
ans = input(f"数据库 {db_path} 已存在,重新初始化将清空数据。[y/N] ")
if ans.lower() != "y":
print("已取消")
sys.exit(0)
os.remove(db_path)
init_from_config(config_path, db_path, date_str)
show_summary(db_path, date_str)
+105
View File
@@ -0,0 +1,105 @@
import sqlite3
import sys
DB_PATH = "production.db"
def get_prev_station_result(product_id: str, current_station_name: str):
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# 获取所有工序(按 PLC 排序 → 工序排序)
cursor.execute(
"""SELECT s.Id, s.StationName, s.SortOrder AS s_order,
plc.SortOrder AS plc_order, s.PointId, mp.PointName
FROM Stations s
JOIN PLCs plc ON plc.Id = s.PLCId
JOIN MeasurementPoints mp ON mp.Id = s.PointId
ORDER BY plc.SortOrder, s.SortOrder"""
)
all_stations = cursor.fetchall()
station_names = [s[1] for s in all_stations]
if current_station_name not in station_names:
print(f"[ERROR] 未找到工序: {current_station_name}")
print(f" 可用工序: {', '.join(station_names)}")
conn.close()
return
idx = station_names.index(current_station_name)
cur = all_stations[idx]
cur_id, cur_name, _, _, cur_pid, cur_pname = cur
print(f"\n{'=' * 55}")
print(f" 工序互锁查询")
print(f"{'=' * 55}")
print(f"\n 当前工序: {cur_name} (检测点: {cur_pname})")
print(f" 产品编号: {product_id}")
if idx == 0:
print(f"\n → 当前为产线首个工序,无前工序")
print(f" → PrevResult = 1 (视为合格)")
print(f"{'=' * 55}\n")
conn.close()
return
prev = all_stations[idx - 1]
_, prev_name, _, _, prev_pid, prev_pname = prev
table = f"MPData_P{prev_pid}_2026_06_08"
cursor.execute(
f"""SELECT RecordTime, IsQualified, InspectionCount, MeasuredValue
FROM {table}
WHERE ProductID = ?""",
(product_id,),
)
prev_data = cursor.fetchone()
print(f" 前工序: {prev_name} (检测点: {prev_pname})")
print(f"{'─' * 55}")
if prev_data is None:
print(f" [结果] 前工序尚未检测此产品")
print(f" → PrevResult = 0 (视为不合格)")
else:
record_time, is_qualified, count, value = prev_data
status = "✓ 合格" if is_qualified else "✗ 不合格"
rework = "返修" if count > 1 else "首检"
print(f" 检测时间: {record_time}")
print(f" 实测值: {value}")
print(f" 检测次数: {count} ({rework})")
print(f" 是否合格: {status}")
print(f" → PrevResult = {is_qualified}")
print(f"{'=' * 55}\n")
conn.close()
def list_stations():
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(
"""SELECT s.StationName, mp.PointName, plc.PLCName
FROM Stations s
JOIN PLCs plc ON plc.Id = s.PLCId
JOIN MeasurementPoints mp ON mp.Id = s.PointId
ORDER BY plc.SortOrder, s.SortOrder"""
)
stations = cursor.fetchall()
print("\n产线工序顺序:")
for i, (name, pname, plc) in enumerate(stations):
arrow = " " if i == 0 else "→ "
print(f" {arrow}[{i}] {name} ({pname}) [{plc}]")
print()
conn.close()
if __name__ == "__main__":
if len(sys.argv) < 3:
print("用法: python interlock_query.py <产品ID> <工序名称>")
print("示例: python interlock_query.py PROD-001 主焊接")
list_stations()
sys.exit(1)
get_prev_station_result(sys.argv[1], sys.argv[2])
+197
View File
@@ -0,0 +1,197 @@
# PC 端数据库设计文档
## 1. 概述
PC 端采用 **设备注册 + 按检测点分表** 方式:
- 用户通过 GUI 配置 PLC、工序、检测点
- 系统自动为每个检测点创建**按天的数据表**(MPData_P{PointId}_{日期})
- **一个产品一行**,只存该检测点的测量数据
---
## 2. 配置表(设备注册)
### 2.1 MeasurementPoints — 全局检测点注册
每个检测点代表一个完整的测量类型,固有 4 个字段:上限、下限、测量值、是否合格。
| 列 | 类型 | 约束 | 说明 |
|---|------|------|------|
| Id | INTEGER | PK | 检测点 ID |
| PointName | TEXT | NOT NULL | 检测点名称,如"焊接温度" |
| FieldUnit | TEXT | DEFAULT '' | 单位,如 "mm"、"℃"、"kN" |
| SortOrder | INTEGER | DEFAULT 0 | 排序 |
### 2.2 PLCs — PLC 设备注册
| 列 | 类型 | 约束 | 说明 |
|---|------|------|------|
| Id | INTEGER | PK | |
| PLCName | TEXT | NOT NULL | 名称,如"PLC01" |
| IPAddress | TEXT | NOT NULL | IP 地址 |
| DBNumber | INTEGER | NOT NULL | DB 块号 |
| StationCount | INTEGER | NOT NULL | 工序数量 |
| SortOrder | INTEGER | DEFAULT 0 | 排序 |
### 2.3 Stations — 工序注册
| 列 | 类型 | 约束 | 说明 |
|---|------|------|------|
| Id | INTEGER | PK | |
| PLCId | INTEGER | FK → PLCs.Id | 所属 PLC |
| StationIndex | INTEGER | NOT NULL | 工序索引(0-based,对应 DB 偏移 i×24)|
| StationName | TEXT | NOT NULL | 工序名称 |
| PointId | INTEGER | FK → MeasurementPoints.Id | 该工序对应的检测点 |
| SortOrder | INTEGER | DEFAULT 0 | 排序 |
> 工序通过 PointId 关联一个检测点。数据就绪时,PC 根据 PointId 找到对应的数据表写入。
---
## 3. 数据表
系统为每个检测点按天创建数据表。
### 3.1 表名规则
```
MPData_P{PointId}_{YYYY_MM_DD}
```
**示例:**
| 表名 | 对应检测点 |
|------|-----------|
| MPData_P1_2026_06_08 | 焊接温度 |
| MPData_P2_2026_06_08 | 焊接电流 |
| MPData_P3_2026_06_08 | 焊点直径 |
| MPData_P4_2026_06_08 | 压装力 |
| MPData_P5_2026_06_08 | 泄漏量 |
### 3.2 表结构(每张固定)
```sql
CREATE TABLE MPData_P1_2026_06_08 (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
ProductID TEXT NOT NULL UNIQUE,
RecordTime DATETIME,
IsQualified INTEGER,
InspectionCount INTEGER DEFAULT 0,
UpperLimit REAL,
LowerLimit REAL,
MeasuredValue REAL
);
```
| 列 | 类型 | 说明 |
|---|------|------|
| Id | INTEGER PK | 自增主键 |
| ProductID | TEXT NOT NULL UNIQUE | 产品唯一编号 |
| RecordTime | DATETIME | 检测时间 |
| IsQualified | INTEGER | 是否合格 |
| InspectionCount | INTEGER DEFAULT 0 | 检测次数(1=首检,2+=返修) |
| UpperLimit | REAL | 测量上限 |
| LowerLimit | REAL | 测量下限 |
| MeasuredValue | REAL | 实测值 |
---
## 4. 数据写入逻辑
### 4.1 首次测量
产品在某工序首次被检测:
```sql
INSERT INTO MPData_P1_2026_06_08
(ProductID, RecordTime, IsQualified, InspectionCount,
UpperLimit, LowerLimit, MeasuredValue)
VALUES
('PROD-001', datetime('now'), 1, 1,
100.0, 80.0, 95.5);
```
### 4.2 其他工序写入同一检测点
同一产品、同一检测点被另一个工序采集时 → UPDATE:
```sql
UPDATE MPData_P1_2026_06_08
SET RecordTime = datetime('now'),
IsQualified = 1,
InspectionCount = 1,
UpperLimit = 200.0,
LowerLimit = 150.0,
MeasuredValue = 180.0
WHERE ProductID = 'PROD-001';
```
### 4.3 返修
同一工序再次检测 → UPDATE,InspectionCount + 1:
```sql
UPDATE MPData_P1_2026_06_08
SET RecordTime = datetime('now'),
IsQualified = 0,
InspectionCount = InspectionCount + 1,
UpperLimit = 100.0,
LowerLimit = 80.0,
MeasuredValue = 102.0
WHERE ProductID = 'PROD-001';
```
### 数据路由逻辑
```
PLC 某工序 DataReady=1
↓
PC 读取 ProductID + 测量值
↓
查 Stations 表,获取该工序的 PointId
↓
查 PointId 对应的数据表:MPData_P{PointId}_{today}
↓
INSERT(新行)或 UPDATE(返修)
```
---
## 5. 工序互锁逻辑
```
1. PLC 侧: ControlWord.Bit2 (PrevResultReq) = 1
2. PC 检测到 PrevResultReq = 1
3. PC 读取该工序 ProductID
4. PC 找到前工序(SortOrder 上一位),获取其 PointId
5. PC 查找该 PointId 对应的数据表中,该产品的最新 IsQualified
6. PC 写入:
- ControlWord.Bit3 (PrevResult) = 1(合格) 或 0(不合格)
- ControlWord.Bit2 (PrevResultReq) = 0
```
---
## 6. 配置变更管理
| 操作 | 行为 |
|------|------|
| 新增检测点 | 次日自动创建新表 |
| 新增工序并关联已有检测点 | 写入已有的对应数据表 |
| 修改检测点名称/单位 | 仅改 MeasurementPoints,表名不变(基于 ID) |
| 删除检测点 | 仅标记禁用,不删已有数据表 |
---
## 7. 表关系总图
```
MeasurementPoints ──→ MPData_P{Id}_{日期}
↑
PLCs ──→ Stations ──────────┘
(PointId)
```
- **MeasurementPoints** 1 : N **Stations**(一个检测点可被多个工序引用)
- **PLCs** 1 : N **Stations**
- **MeasurementPoints** 1 : 1 **MPData_P{Id}_{日期}**(每个检测点一张数据表)
+181
View File
@@ -0,0 +1,181 @@
# PLC 地址规划与通信协议设计
## 1. 概述
本软件与西门子 S7 系列 PLC 通过 S7 协议通信,读写 PLC 的 DB 块中的数据。
- **通信方式**:S7 协议(以太网)
- **PLC 类型**:西门子 S7-1200 / S7-1500
- **数据区域**:DB 块
- **每台 PLC 使用一个独立的 DB 块**(如 DB100、DB101 ...),具体块号在 PC 端配置
---
## 2. DB 块总体结构
- **无全局头区**,DB 块中只包含工序数据
- 所有工序**连续排列**,每个工序占用 **固定 24 字节**
- 第 i 个工序的起始偏移:`i × 24 字节`
### 示意图
```
DB 块(如 DB100):
┌─────────────────────────┐
│ 工序 0 (偏移 0 ~ 23) │ 24 字节
├─────────────────────────┤
│ 工序 1 (偏移 24 ~ 47) │ 24 字节
├─────────────────────────┤
│ 工序 2 (偏移 48 ~ 71) │ 24 字节
├─────────────────────────┤
│ ... │
└─────────────────────────┘
```
### DB 块大小
DB 块大小 = `工序数量 × 24` 字节。
例如 10 个工序,DB 块设为 240 字节(或略大)。
---
## 3. 单工序数据模板
每个工序占用 24 字节,布局如下:
| 相对偏移 | 字节数 | S7 类型 | 名称 | 方向 | 说明 |
|---------|--------|---------|------|------|------|
| +0 | 4 | DINT | `ProductID` | PLC → PC | 当前产品唯一编号(条码转数值) |
| +4 | 4 | REAL | `UpperLimit` | PLC → PC | 测量上限 |
| +8 | 4 | REAL | `LowerLimit` | PLC → PC | 测量下限 |
| +12 | 4 | REAL | `MeasuredValue` | PLC → PC | 实测值 |
| +16 | 2 | WORD | `ControlWord` | 双向 | 控制字(位定义见下文) |
| +18 | 6 | — | `Reserved` | — | 保留,供将来扩展 |
### 数据类型说明
| PLC 侧声明 | TIA Portal 数据类型 | 说明 |
|-----------|-------------------|------|
| ProductID | `DINT` | 32 位有符号整数 |
| UpperLimit | `REAL` | 32 位浮点数 |
| LowerLimit | `REAL` | 32 位浮点数 |
| MeasuredValue | `REAL` | 32 位浮点数 |
| ControlWord | `WORD` | 16 位无符号字 |
### PLC 侧(TIA Portal)DB 定义示例
```
DB100 作为"软件接口数据块":
ProductID_0 : DINT; // 工序 0 产品ID
UpperLimit_0 : REAL; // 工序 0 测量上限
LowerLimit_0 : REAL; // 工序 0 测量下限
MeasuredValue_0 : REAL; // 工序 0 实测值
ControlWord_0 : WORD; // 工序 0 控制字
Reserved_0[6] : BYTE; // 工序 0 保留
ProductID_1 : DINT; // 工序 1
UpperLimit_1 : REAL;
LowerLimit_1 : REAL;
MeasuredValue_1 : REAL;
ControlWord_1 : WORD;
Reserved_1[6] : BYTE;
// ...以此类推
```
---
## 4. ControlWord 位定义
ControlWord 是一个 16 位 WORD(2 字节),各 bit 定义如下:
| 位 | 名称 | 方向 | 说明 |
|---|------|------|------|
| Bit 0 | `DataReady` | PLC → PC | **1** = 该工序有新的测量数据待读取<br>**0** = 空闲(PC 读完数据后写 0) |
| Bit 1 | `IsQualified` | PLC → PC | **1** = 当前产品该工序测量合格<br>**0** = 不合格 |
| Bit 2 | `PrevResultReq` | PLC → PC | **1** = PLC 请求查询上一工序的合格结果<br>**0** = 无请求(PC 处理完后写 0) |
| Bit 3 | `PrevResult` | PC → PLC | **1** = 上一工序合格(PC 写入)<br>**0** = 上一工序不合格(PC 写入) |
| Bit 4~15 | 保留 | — | 置 0 |
### 方向说明
- **PLC → PC**:PLC 写入,PC 读取(只读方向)
- **PC → PLC**:PC 写入,PLC 读取(只写方向)
- **双向**:双方均可读写(具体按位定义)
---
## 5. 通信流程
### 5.1 数据采集流程(DataReady 触发)
```
步骤 1:PLC 完成测量后,将测量数据写入 DB 对应区域
ProductID = 当前产品编号
UpperLimit / LowerLimit / MeasuredValue = 测量值
ControlWord.Bit0 (DataReady) = 1
ControlWord.Bit1 (IsQualified) = 合格则1,不合格则0
步骤 2:PC 周期性轮询,读到 DataReady = 1
步骤 3:PC 读取该工序的完整数据:
- ProductID
- UpperLimit, LowerLimit, MeasuredValue
- ControlWord(获取 IsQualified)
步骤 4:PC 将数据写入数据库
步骤 5:PC 将 ControlWord.Bit0 (DataReady) 写 0
(通知 PLC 本批数据已读取完毕)
```
### 5.2 工序互锁流程(PrevResultReq 触发)
```
步骤 1:PLC 需要查询上一工序结果时,置位:
ControlWord.Bit2 (PrevResultReq) = 1
步骤 2:PC 轮询检测到 PrevResultReq = 1
步骤 3:PC 查询数据库,根据当前 ProductID 找到上一工序的测量记录,
判断是否合格
步骤 4:PC 将结果写入:
ControlWord.Bit3 (PrevResult) = 1(合格)或 0(不合格)
步骤 5:PC 将 ControlWord.Bit2 (PrevResultReq) 写 0
(通知 PLC 请求已处理,PLC 可以读取 Bit3 的结果)
```
---
## 6. 附录:地址分配示例
以某产线 3 台 PLC 为例:
| PLC | IP 地址 | DB 块号 | 工序数 | DB 块大小 |
|-----|---------|---------|--------|-----------|
| PLC1 | 192.168.0.10 | 100 | 4 | 96 字节 |
| PLC2 | 192.168.0.11 | 100 | 6 | 144 字节 |
| PLC3 | 192.168.0.12 | 100 | 5 | 120 字节 |
### PLC1 地址表
| 工序索引 | 偏移 | 数据分布 |
|---------|------|---------|
| 0 | 0~23 | DB100.DBD0: ProductID, DB100.DBD4: UpperLimit, DB100.DBD8: LowerLimit, DB100.DBD12: MeasuredValue, DB100.DBW16: ControlWord |
| 1 | 24~47 | DB100.DBD24 ... DB100.DBW40 |
| 2 | 48~71 | DB100.DBD48 ... DB100.DBW64 |
| 3 | 72~95 | DB100.DBD72 ... DB100.DBW88 |
### 地址计算公式
```
第 i 工序的 ProductID 偏移: i × 24 + 0
第 i 工序的 UpperLimit 偏移: i × 24 + 4
第 i 工序的 LowerLimit 偏移: i × 24 + 8
第 i 工序的 MeasuredValue 偏移: i × 24 + 12
第 i 工序的 ControlWord 偏移: i × 24 + 16
```
+1074
View File
File diff suppressed because it is too large. Load diff
+28
View File
@@ -0,0 +1,28 @@
{
"name": "scanner-record",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "tsx watch src/index.ts",
"start": "tsx src/index.ts",
"build": "tsc",
"build:web": "cd web && npm run build",
"db:init": "tsx src/database/init.ts",
"simulate": "tsx src/simulate.ts",
"test:e2e": "tsx src/database/init.ts && tsx src/simulate.ts",
"test:plc": "tsx test/plc-comm.ts"
},
"dependencies": {
"@hono/node-server": "^1.14.0",
"better-sqlite3": "^11.8.0",
"hono": "^4.7.0",
"node-snap7": "^1.0.9"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.12",
"@types/node": "^22.0.0",
"tsx": "^4.19.0",
"typescript": "^5.7.0"
}
}
+108
View File
@@ -0,0 +1,108 @@
import { Hono } from 'hono'
import { getDb } from '../database/connection.js'
import {
insertMeasurementPoint, updateMeasurementPoint, deleteMeasurementPoint,
insertPLC, updatePLC, deletePLC,
insertStation, updateStation, deleteStation,
createMPDataTable, dropMPDataTable,
} from '../database/schema.js'
const config = new Hono()
/* ===== GET ===== */
config.get('/plcs', (c) => {
const db = getDb()
return c.json(db.prepare('SELECT * FROM PLCs ORDER BY Id').all())
})
config.get('/plcs/:id', (c) => {
const db = getDb()
const plc = db.prepare('SELECT * FROM PLCs WHERE Id = ?').get(c.req.param('id'))
return plc ? c.json(plc) : c.json({ error: 'Not found' }, 404)
})
config.get('/stations', (c) => {
const db = getDb()
const plcId = c.req.query('plcId')
const sql = plcId
? `SELECT s.*, mp.PointName as pointName FROM Stations s JOIN MeasurementPoints mp ON mp.Id = s.PointId WHERE s.PLCId = ? ORDER BY s.Id`
: `SELECT s.*, mp.PointName as pointName FROM Stations s JOIN MeasurementPoints mp ON mp.Id = s.PointId ORDER BY s.Id`
const rows = plcId ? db.prepare(sql).all(plcId) : db.prepare(sql).all()
return c.json(rows)
})
config.get('/measurement-points', (c) => {
const db = getDb()
return c.json(db.prepare('SELECT * FROM MeasurementPoints ORDER BY Id').all())
})
/* ===== MeasurementPoints CRUD ===== */
config.post('/measurement-points', (c) => c.req.json().then(body => {
const id = insertMeasurementPoint(body.PointName, body.FieldUnit || '')
createMPDataTable(id, todayStr())
return c.json({ Id: id })
}))
config.put('/measurement-points/:id', (c) => c.req.json().then(body => {
updateMeasurementPoint(Number(c.req.param('id')), body.PointName, body.FieldUnit || '')
return c.json({ success: true })
}))
config.delete('/measurement-points/:id', (c) => {
const id = Number(c.req.param('id'))
dropMPDataTable(id, todayStr())
deleteMeasurementPoint(id)
return c.json({ success: true })
})
/* ===== PLCs CRUD ===== */
config.post('/plcs', (c) => c.req.json().then(body => {
const id = insertPLC(body.PLCName, body.IPAddress, body.DBNumber, body.StationCount || 0)
return c.json({ Id: id })
}))
config.put('/plcs/:id', (c) => c.req.json().then(body => {
updatePLC(Number(c.req.param('id')), body.PLCName, body.IPAddress, body.DBNumber, body.StationCount || 0)
return c.json({ success: true })
}))
config.delete('/plcs/:id', (c) => {
deletePLC(Number(c.req.param('id')))
return c.json({ success: true })
})
/* ===== Stations CRUD ===== */
config.post('/stations', (c) => c.req.json().then(body => {
const db = getDb()
let name = body.StationName
if (!name) {
const mp = db.prepare('SELECT PointName FROM MeasurementPoints WHERE Id=?').get(body.PointId) as any
name = mp?.PointName || ''
}
const id = insertStation(body.PLCId, body.StationIndex || 0, name, body.PointId)
return c.json({ Id: id })
}))
config.put('/stations/:id', (c) => c.req.json().then(body => {
updateStation(Number(c.req.param('id')), body.PLCId, body.StationIndex || 0, body.StationName, body.PointId)
return c.json({ success: true })
}))
config.delete('/stations/:id', (c) => {
deleteStation(Number(c.req.param('id')))
return c.json({ success: true })
})
function todayStr(): string {
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const dd = String(d.getDate()).padStart(2, '0')
return `${y}_${m}_${dd}`
}
export default config
+34
View File
@@ -0,0 +1,34 @@
import { Hono } from 'hono'
import { getDb } from '../database/connection.js'
const monitor = new Hono()
monitor.get('/status', (c) => {
const db = getDb()
const plcCount = (db.prepare('SELECT COUNT(*) as c FROM PLCs').get() as any).c
const stationCount = (db.prepare('SELECT COUNT(*) as c FROM Stations').get() as any).c
const pointCount = (db.prepare('SELECT COUNT(*) as c FROM MeasurementPoints').get() as any).c
const tables = db.prepare(
"SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'MPData_%' ORDER BY name"
).all() as any[]
let totalRows = 0
for (const t of tables) {
try {
const r = db.prepare(`SELECT COUNT(*) as c FROM ${t.name}`).get() as any
totalRows += r.c
} catch { /* skip */ }
}
return c.json({
plcCount,
stationCount,
pointCount,
dataTableCount: tables.length,
totalRecords: totalRows,
})
})
export default monitor
+104
View File
@@ -0,0 +1,104 @@
import { Hono } from 'hono'
import { getDb } from '../database/connection.js'
import { getAllStations, getMPRecord } from '../database/schema.js'
const query = new Hono()
function todayDateStr(): string {
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${y}_${m}_${day}`
}
query.get('/:productId', (c) => {
const productId = c.req.param('productId')
const dateStr = c.req.query('date') || todayDateStr()
const db = getDb()
const points = db.prepare('SELECT Id, PointName, FieldUnit FROM MeasurementPoints ORDER BY Id').all() as any[]
const result: any[] = []
for (const p of points) {
const table = `MPData_P${p.Id}_${dateStr}`
const tableExists = db.prepare(
"SELECT name FROM sqlite_master WHERE type='table' AND name=?"
).get(table)
if (!tableExists) continue
const row = db.prepare(`
SELECT RecordTime as recordTime, IsQualified as isQualified,
InspectionCount as inspectionCount,
UpperLimit as upperLimit, LowerLimit as lowerLimit,
MeasuredValue as measuredValue
FROM ${table} WHERE ProductID = ?
`).get(productId) as any
if (row) {
result.push({
pointId: p.Id,
pointName: p.PointName,
fieldUnit: p.FieldUnit,
...row,
})
}
}
if (result.length === 0) {
return c.json({ productId, data: [], message: '该产品暂无数据记录' })
}
return c.json({ productId, data: result })
})
query.get('/:productId/interlock/:stationName', (c) => {
const productId = c.req.param('productId')
const stationName = c.req.param('stationName')
const dateStr = c.req.query('date') || todayDateStr()
const stations = getAllStations()
const names = stations.map(s => s.stationName)
const idx = names.indexOf(stationName)
if (idx === -1) {
return c.json({ error: `未找到工序: ${stationName}`, available: names }, 404)
}
const current = stations[idx]
if (idx === 0) {
return c.json({
currentStation: current.stationName,
currentPoint: current.pointName,
prevStation: null,
prevResult: 1,
message: '当前为产线首个工序,视为合格',
})
}
const prev = stations[idx - 1]
const record = getMPRecord(dateStr, prev.pointId, productId)
if (!record) {
return c.json({
currentStation: current.stationName,
currentPoint: current.pointName,
prevStation: prev.stationName,
prevPoint: prev.pointName,
prevResult: 0,
message: '前工序尚未检测此产品,视为不合格',
})
}
return c.json({
currentStation: current.stationName,
currentPoint: current.pointName,
prevStation: prev.stationName,
prevPoint: prev.pointName,
prevResult: record.isQualified,
prevData: record,
})
})
export default query
+24
View File
@@ -0,0 +1,24 @@
import Database from 'better-sqlite3'
import path from 'path'
import { fileURLToPath } from 'url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const DB_PATH = path.resolve(__dirname, '../../data/production.db')
let db: Database.Database | null = null
export function getDb(): Database.Database {
if (!db) {
db = new Database(DB_PATH)
db.pragma('journal_mode = WAL')
db.pragma('foreign_keys = ON')
}
return db
}
export function closeDb(): void {
if (db) {
db.close()
db = null
}
}
+91
View File
@@ -0,0 +1,91 @@
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import { getDb, closeDb } from './connection.js'
import { createConfigTables, clearConfigData, createMPDataTable } from './schema.js'
import { logger } from '../logger.js'
import type { Config } from '../types.js'
const TAG = 'DBInit'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const CONFIG_PATH = path.resolve(__dirname, '../../config.json')
function todayDateStr(): string {
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${y}_${m}_${day}`
}
function readConfig(): Config {
if (!fs.existsSync(CONFIG_PATH)) {
logger.error(TAG, `配置文件不存在: ${CONFIG_PATH}`)
process.exit(1)
}
const raw = fs.readFileSync(CONFIG_PATH, 'utf-8')
return JSON.parse(raw) as Config
}
export function initFromConfig(configPath?: string, dateStr?: string): void {
const cfg = configPath ? (() => {
const p = path.resolve(configPath)
if (!fs.existsSync(p)) { logger.error(TAG, `文件不存在: ${p}`); process.exit(1) }
return JSON.parse(fs.readFileSync(p, 'utf-8')) as Config
})() : readConfig()
const ds = dateStr || todayDateStr()
const db = getDb()
logger.info(TAG, '创建配置表...')
createConfigTables()
logger.info(TAG, '清空旧配置数据...')
clearConfigData()
logger.info(TAG, '写入全局检测点...')
const insertMP = db.prepare(
'INSERT INTO MeasurementPoints (PointName, FieldUnit) VALUES (?, ?)'
)
const pointNameMap = new Map<string, number>()
for (const mp of cfg.measurement_points) {
const result = insertMP.run(mp.point_name, mp.field_unit ?? '')
pointNameMap.set(mp.point_name, Number(result.lastInsertRowid))
}
logger.info(TAG, '写入 PLC 和工序配置...')
const insertPLC = db.prepare(
'INSERT INTO PLCs (PLCName, IPAddress, DBNumber, StationCount) VALUES (?, ?, ?, ?)'
)
const insertStation = db.prepare(
'INSERT INTO Stations (PLCId, StationIndex, StationName, PointId) VALUES (?, ?, ?, ?)'
)
for (const plc of cfg.plcs) {
const plcResult = insertPLC.run(plc.plc_name, plc.ip_address, plc.db_number, plc.station_count)
const plcId = Number(plcResult.lastInsertRowid)
for (const st of plc.stations) {
const pointId = pointNameMap.get(st.point_name)
if (pointId === undefined) {
logger.warn(TAG, `检测点 '${st.point_name}' 未定义,跳过`)
continue
}
insertStation.run(plcId, st.station_index, st.station_name, pointId)
}
}
logger.info(TAG, '创建检测点数据表...')
for (const [pointName, pointId] of pointNameMap) {
createMPDataTable(pointId, ds)
}
logger.info(TAG, '数据库已初始化')
}
// 直接运行时
if (process.argv[1] && (process.argv[1].endsWith('init.ts') || process.argv[1].endsWith('/init.js'))) {
initFromConfig(process.argv[2], process.argv[3])
closeDb()
}
+205
View File
@@ -0,0 +1,205 @@
import Database from 'better-sqlite3'
import { getDb } from './connection.js'
import { logger } from '../logger.js'
const TAG = 'Schema'
export function createConfigTables(): void {
const db = getDb()
db.exec(`
CREATE TABLE IF NOT EXISTS MeasurementPoints (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
PointName TEXT NOT NULL,
FieldUnit TEXT DEFAULT ''
);
CREATE TABLE IF NOT EXISTS PLCs (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
PLCName TEXT NOT NULL,
IPAddress TEXT NOT NULL,
DBNumber INTEGER NOT NULL,
StationCount INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS Stations (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
PLCId INTEGER NOT NULL REFERENCES PLCs(Id),
StationIndex INTEGER NOT NULL,
StationName TEXT NOT NULL,
PointId INTEGER REFERENCES MeasurementPoints(Id)
);
`)
}
export function clearConfigData(): void {
const db = getDb()
db.exec(`
DELETE FROM Stations;
DELETE FROM MeasurementPoints;
DELETE FROM PLCs;
`)
}
export function createMPDataTable(pointId: number, dateStr: string): void {
const db = getDb()
const table = `MPData_P${pointId}_${dateStr}`
db.exec(`
CREATE TABLE IF NOT EXISTS ${table} (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
ProductID TEXT NOT NULL UNIQUE,
RecordTime DATETIME,
IsQualified INTEGER,
InspectionCount INTEGER DEFAULT 0,
UpperLimit REAL,
LowerLimit REAL,
MeasuredValue REAL
);
`)
logger.info(TAG, `${table} 已创建`)
}
export function dropMPDataTable(pointId: number, dateStr: string): void {
const db = getDb()
const table = `MPData_P${pointId}_${dateStr}`
db.exec(`DROP TABLE IF EXISTS ${table};`)
}
export function getAllMeasurementPoints(): { id: number; pointName: string; fieldUnit: string }[] {
const db = getDb()
return db.prepare('SELECT Id as id, PointName as pointName, FieldUnit as fieldUnit FROM MeasurementPoints ORDER BY Id').all() as any[]
}
export function getAllPLCs(): any[] {
const db = getDb()
return db.prepare('SELECT * FROM PLCs ORDER BY Id').all()
}
export function getStationsByPLC(plcId: number): any[] {
const db = getDb()
return db.prepare('SELECT * FROM Stations WHERE PLCId = ? ORDER BY Id').all(plcId)
}
export function getAllStations(): {
id: number
stationName: string
pointId: number
pointName: string
}[] {
const db = getDb()
return db.prepare(`
SELECT s.Id as id, s.StationName as stationName,
s.PointId as pointId, mp.PointName as pointName
FROM Stations s
JOIN MeasurementPoints mp ON mp.Id = s.PointId
ORDER BY s.Id
`).all() as any[]
}
export function getMPRecord(dateStr: string, pointId: number, productId: string): {
recordTime: string
isQualified: number
inspectionCount: number
measuredValue: number
} | null {
const db = getDb()
const table = `MPData_P${pointId}_${dateStr}`
const row = db.prepare(`
SELECT RecordTime as recordTime, IsQualified as isQualified,
InspectionCount as inspectionCount, MeasuredValue as measuredValue
FROM ${table}
WHERE ProductID = ?
`).get(productId) as any
return row || null
}
export function getAllMPRecords(dateStr: string, pointId: number, productId: string): any[] {
const db = getDb()
const table = `MPData_P${pointId}_${dateStr}`
try {
return db.prepare(`SELECT * FROM ${table} WHERE ProductID = ?`).all(productId) as any[]
} catch {
return []
}
}
/* ===== CRUD: MeasurementPoints ===== */
export function insertMeasurementPoint(name: string, unit: string): number {
const db = getDb()
const r = db.prepare('INSERT INTO MeasurementPoints (PointName, FieldUnit) VALUES (?, ?)').run(name, unit)
return Number(r.lastInsertRowid)
}
export function updateMeasurementPoint(id: number, name: string, unit: string): void {
const db = getDb()
db.prepare('UPDATE MeasurementPoints SET PointName=?, FieldUnit=? WHERE Id=?').run(name, unit, id)
}
export function deleteMeasurementPoint(id: number): void {
const db = getDb()
db.prepare('DELETE FROM Stations WHERE PointId=?').run(id)
db.prepare('DELETE FROM MeasurementPoints WHERE Id=?').run(id)
}
/* ===== CRUD: PLCs ===== */
export function insertPLC(name: string, ip: string, dbNum: number, stationCount: number): number {
const db = getDb()
const r = db.prepare('INSERT INTO PLCs (PLCName, IPAddress, DBNumber, StationCount) VALUES (?, ?, ?, ?)').run(name, ip, dbNum, stationCount)
return Number(r.lastInsertRowid)
}
export function updatePLC(id: number, name: string, ip: string, dbNum: number, stationCount: number): void {
const db = getDb()
db.prepare('UPDATE PLCs SET PLCName=?, IPAddress=?, DBNumber=?, StationCount=? WHERE Id=?').run(name, ip, dbNum, stationCount, id)
}
export function deletePLC(id: number): void {
const db = getDb()
db.prepare('DELETE FROM Stations WHERE PLCId=?').run(id)
db.prepare('DELETE FROM PLCs WHERE Id=?').run(id)
}
/* ===== CRUD: Stations ===== */
export function insertStation(plcId: number, stationIndex: number, name: string, pointId: number): number {
const db = getDb()
const r = db.prepare('INSERT INTO Stations (PLCId, StationIndex, StationName, PointId) VALUES (?, ?, ?, ?)').run(plcId, stationIndex, name, pointId)
return Number(r.lastInsertRowid)
}
export function updateStation(id: number, plcId: number, stationIndex: number, name: string, pointId: number): void {
const db = getDb()
db.prepare('UPDATE Stations SET PLCId=?, StationIndex=?, StationName=?, PointId=? WHERE Id=?').run(plcId, stationIndex, name, pointId, id)
}
export function deleteStation(id: number): void {
const db = getDb()
db.prepare('DELETE FROM Stations WHERE Id=?').run(id)
}
export function ensureDatabase(): void {
const db = getDb()
createConfigTables()
const count = (db.prepare('SELECT COUNT(*) as c FROM MeasurementPoints').get() as any).c
if (count === 0) {
logger.info(TAG, '数据库为空,请通过前端配置')
}
const points = db.prepare('SELECT Id FROM MeasurementPoints').all() as any[]
const dateStr = todayStr()
for (const p of points) {
createMPDataTable(p.Id, dateStr)
}
}
function todayStr(): string {
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const dd = String(d.getDate()).padStart(2, '0')
return `${y}_${m}_${dd}`
}
export { todayStr as getTodayStr }
+95
View File
@@ -0,0 +1,95 @@
import { serve } from '@hono/node-server'
import { Hono } from 'hono'
import { logger } from './logger.js'
import configApi from './api/config.js'
import queryApi from './api/query.js'
import monitorApi from './api/monitor.js'
import { ensureDatabase } from './database/schema.js'
import * as scanner from './plc/scanner.js'
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
const WEB_ROOT = (() => {
const candidates = [
path.resolve(process.cwd(), 'web/dist'),
path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../web/dist'),
]
for (const p of candidates) {
if (fs.existsSync(p)) return p
}
return candidates[0]
})()
logger.info('Server', `前端目录: ${WEB_ROOT}`)
const app = new Hono()
app.route('/api/config', configApi)
app.route('/api/query', queryApi)
app.route('/api/monitor', monitorApi)
app.get('/api/scanner/status', (c) => {
return c.json({ running: scanner.isRunning() })
})
app.get('/', (c) => c.redirect('/web/'))
// 手动处理前端静态文件
const MIME: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.json': 'application/json',
'.png': 'image/png',
'.svg': 'image/svg+xml',
}
app.get('/web/*', (c) => {
const reqPath = c.req.path.replace(/^\/web\//, '') || 'index.html'
const filePath = path.resolve(WEB_ROOT, reqPath)
if (!filePath.startsWith(WEB_ROOT)) {
return c.text('Forbidden', 403)
}
if (!fs.existsSync(filePath)) {
return c.text('404 Not Found', 404)
}
const ext = path.extname(filePath)
const content = fs.readFileSync(filePath)
return c.newResponse(content, 200, { 'Content-Type': MIME[ext] || 'application/octet-stream' })
})
const PORT = parseInt(process.env.PORT || '3000', 10)
serve({
fetch: app.fetch,
port: PORT,
}, (info) => {
logger.info('Server', `http://localhost:${PORT}`)
})
try {
ensureDatabase()
const skipPlc = process.env.SKIP_PLC === '1'
if (!skipPlc) {
scanner.start()
} else {
logger.info('Server', 'SKIP_PLC=1,跳过 PLC 连接')
}
} catch (err) {
logger.error('Server', '初始化失败', err)
}
process.on('SIGINT', () => {
scanner.stop()
process.exit(0)
})
process.on('SIGTERM', () => {
scanner.stop()
process.exit(0)
})
+52
View File
@@ -0,0 +1,52 @@
export enum LogLevel {
DEBUG = 0,
INFO = 1,
WARN = 2,
ERROR = 3,
}
const currentLevel = (() => {
const env = process.env.LOG_LEVEL
if (env !== undefined) {
const n = parseInt(env, 10)
if (!isNaN(n)) return n
}
return LogLevel.INFO
})()
function ts(): string {
const d = new Date()
const y = d.getFullYear()
const mo = String(d.getMonth() + 1).padStart(2, '0')
const dd = String(d.getDate()).padStart(2, '0')
const h = String(d.getHours()).padStart(2, '0')
const mi = String(d.getMinutes()).padStart(2, '0')
const s = String(d.getSeconds()).padStart(2, '0')
return `${y}-${mo}-${dd} ${h}:${mi}:${s}`
}
function log(level: LogLevel, tag: string, msg: string, ...args: any[]) {
if (level < currentLevel) return
const prefix = ['[D]', '[I]', '[W]', '[E]'][level]
const full = `${ts()} ${prefix} [${tag}] ${msg}`
if (args.length > 0) {
switch (level) {
case LogLevel.ERROR: console.error(full, ...args); break
case LogLevel.WARN: console.warn(full, ...args); break
default: console.log(full, ...args); break
}
} else {
switch (level) {
case LogLevel.ERROR: console.error(full); break
case LogLevel.WARN: console.warn(full); break
default: console.log(full); break
}
}
}
export const logger = {
debug: (tag: string, msg: string, ...args: any[]) => log(LogLevel.DEBUG, tag, msg, ...args),
info: (tag: string, msg: string, ...args: any[]) => log(LogLevel.INFO, tag, msg, ...args),
warn: (tag: string, msg: string, ...args: any[]) => log(LogLevel.WARN, tag, msg, ...args),
error: (tag: string, msg: string, ...args: any[]) => log(LogLevel.ERROR, tag, msg, ...args),
}
+170
View File
@@ -0,0 +1,170 @@
import { createRequire } from 'module'
const snap7 = createRequire(import.meta.url)('node-snap7')
import { STATION_SIZE, stationOffset, readDINT, readREAL, readWORD,
writeWORD, setControlBit, parseControlWord, CONTROL_BITS } from './protocol.js'
import { logger } from '../logger.js'
const TAG = 'PLC'
export interface PLCConfig {
id: number
plcName: string
ipAddress: string
dbNumber: number
stationCount: number
}
export interface StationData {
productID: number
upperLimit: number
lowerLimit: number
measuredValue: number
controlWord: number
dataReady: boolean
isQualified: boolean
prevResultReq: boolean
}
export interface ControlBits {
controlWord: number
dataReady: boolean
isQualified: boolean
prevResultReq: boolean
prevResult: boolean
}
const clients = new Map<number, any>()
function getS7Client(): any {
return new snap7.S7Client()
}
export function connectPLC(cfg: PLCConfig): boolean {
try {
const client = getS7Client()
const connected = client.ConnectTo(cfg.ipAddress, 0, 2)
if (connected === true) {
clients.set(cfg.id, client)
logger.info(TAG, `${cfg.plcName} (${cfg.ipAddress}) 已连接`)
return true
} else {
const errCode = client.LastError()
const errText = errCode === 0 ? '连接超时或无响应' : client.ErrorText(errCode)
logger.warn(TAG, `${cfg.plcName} (${cfg.ipAddress}) 连接失败: ${errText}`)
return false
}
} catch (err: any) {
logger.warn(TAG, `${cfg.plcName} (${cfg.ipAddress}) 连接异常: ${err.message}`)
return false
}
}
export function disconnectPLC(plcId: number): void {
const client = clients.get(plcId)
if (client) {
client.Disconnect()
clients.delete(plcId)
logger.info(TAG, `PLC#${plcId} 已断开`)
}
}
export function disconnectAll(): void {
for (const [, client] of clients) {
client.Disconnect()
}
clients.clear()
}
function readStationBlock(dbNumber: number, stationIndex: number, client: any): Buffer | null {
const offset = stationOffset(stationIndex)
const buf = Buffer.alloc(STATION_SIZE)
const result = client.DBRead(dbNumber, offset, STATION_SIZE, buf)
if (result === false) {
logger.warn(TAG, `DB${dbNumber} 读取工序 ${stationIndex} 失败: ${client.ErrorText(client.LastError())}`)
return null
}
return result instanceof Buffer ? result : buf
}
function writeStationControlWord(dbNumber: number, stationIndex: number, word: number, client: any): boolean {
const offset = stationOffset(stationIndex) + 16
const buf = Buffer.alloc(2)
writeWORD(buf, 0, word)
logger.info(TAG, `DBWrite DB${dbNumber}+${offset} = 0x${word.toString(16).padStart(4, '0')}`)
const result = client.DBWrite(dbNumber, offset, 2, buf)
if (result !== true) {
logger.warn(TAG, `DB${dbNumber} 写入工序 ${stationIndex} 控制字失败: ${client.ErrorText(client.LastError())}`)
return false
}
logger.info(TAG, `DB${dbNumber}+${offset} 写入成功`)
return true
}
export function readStationData(cfg: PLCConfig, stationIndex: number): StationData | null {
const client = clients.get(cfg.id)
if (!client) {
logger.warn(TAG, `${cfg.plcName} 未连接`)
return null
}
const buf = readStationBlock(cfg.dbNumber, stationIndex, client)
if (!buf) return null
const productID = readDINT(buf, 0)
const upperLimit = readREAL(buf, 4)
const lowerLimit = readREAL(buf, 8)
const measuredValue = readREAL(buf, 12)
const controlWord = readWORD(buf, 16)
const bits = parseControlWord(controlWord)
return {
productID,
upperLimit,
lowerLimit,
measuredValue,
controlWord,
dataReady: bits.dataReady,
isQualified: bits.isQualified,
prevResultReq: bits.prevResultReq,
}
}
export function readControlWord(cfg: PLCConfig, stationIndex: number): ControlBits | null {
const client = clients.get(cfg.id)
if (!client) return null
const offset = stationOffset(stationIndex) + 16
const buf = Buffer.alloc(2)
const result = client.DBRead(cfg.dbNumber, offset, 2, buf)
if (result === false) return null
const cw = readWORD(buf, 0)
const bits = parseControlWord(cw)
return { controlWord: cw, ...bits }
}
export function writePrevResult(cfg: PLCConfig, stationIndex: number, qualified: boolean): boolean {
const client = clients.get(cfg.id)
if (!client) return false
const buf = readStationBlock(cfg.dbNumber, stationIndex, client)
if (!buf) return false
let cw = readWORD(buf, 16)
cw = setControlBit(cw, CONTROL_BITS.PrevResult, qualified)
cw = setControlBit(cw, CONTROL_BITS.PrevResultReq, false)
return writeStationControlWord(cfg.dbNumber, stationIndex, cw, client)
}
export function clearDataReady(cfg: PLCConfig, stationIndex: number, controlWord: number): boolean {
const client = clients.get(cfg.id)
if (!client) return false
const newCw = setControlBit(controlWord, CONTROL_BITS.DataReady, false)
logger.info(TAG, `${cfg.plcName} 工序${stationIndex} clearDataReady: 0x${controlWord.toString(16).padStart(4, '0')} → 0x${newCw.toString(16).padStart(4, '0')}`)
return writeStationControlWord(cfg.dbNumber, stationIndex, newCw, client)
}
export function getConnectedCount(): number {
return clients.size
}
+78
View File
@@ -0,0 +1,78 @@
/** 每个工序固定 24 字节 */
export const STATION_SIZE = 24
/** 工序内各字段的相对偏移 */
export const OFFSET = {
ProductID: 0, // DINT, 4 bytes
UpperLimit: 4, // REAL, 4 bytes
LowerLimit: 8, // REAL, 4 bytes
MeasuredValue: 12, // REAL, 4 bytes
ControlWord: 16, // WORD, 2 bytes
} as const
/** ControlWord 位定义 */
export const CONTROL_BITS = {
DataReady: 0, // Bit 0: PLC→PC, 1=有新数据
IsQualified: 1, // Bit 1: PLC→PC, 1=合格
PrevResultReq: 2, // Bit 2: PLC→PC, 1=请求上一工序结果
PrevResult: 3, // Bit 3: PC→PLC, 1=上工序合格
} as const
/** 解析 ControlWord WORD → 各 bit */
export function parseControlWord(word: number): {
dataReady: boolean
isQualified: boolean
prevResultReq: boolean
prevResult: boolean
} {
return {
dataReady: !!(word & (1 << CONTROL_BITS.DataReady)),
isQualified: !!(word & (1 << CONTROL_BITS.IsQualified)),
prevResultReq: !!(word & (1 << CONTROL_BITS.PrevResultReq)),
prevResult: !!(word & (1 << CONTROL_BITS.PrevResult)),
}
}
/** 设置 ControlWord 的某个 bit 后返回新值 */
export function setControlBit(word: number, bit: number, value: boolean): number {
if (value) {
return word | (1 << bit)
} else {
return word & ~(1 << bit)
}
}
/** 工序 i 的起始字节偏移 */
export function stationOffset(i: number): number {
return i * STATION_SIZE
}
/** 读取 Buffer 中的 DINT (S7 DINT = signed 32-bit) */
export function readDINT(buf: Buffer, offset: number): number {
return buf.readInt32BE(offset)
}
/** 读取 Buffer 中的 REAL (S7 REAL = IEEE754 float, big-endian) */
export function readREAL(buf: Buffer, offset: number): number {
return buf.readFloatBE(offset)
}
/** 读取 Buffer 中的 WORD (16-bit unsigned) */
export function readWORD(buf: Buffer, offset: number): number {
return buf.readUInt16BE(offset)
}
/** 将 REAL 写入 Buffer (big-endian) */
export function writeREAL(buf: Buffer, offset: number, value: number): void {
buf.writeFloatBE(value, offset)
}
/** 将 WORD 写入 Buffer (big-endian) */
export function writeWORD(buf: Buffer, offset: number, value: number): void {
buf.writeUInt16BE(value, offset)
}
/** 将 DINT 写入 Buffer (big-endian) */
export function writeDINT(buf: Buffer, offset: number, value: number): void {
buf.writeInt32BE(value, offset)
}
+153
View File
@@ -0,0 +1,153 @@
import { getDb } from '../database/connection.js'
import { connectPLC, readStationData, readControlWord, clearDataReady,
writePrevResult, disconnectAll, type PLCConfig } from './client.js'
import { handleDataCollection } from '../services/collection.js'
import { handleInterlock } from '../services/interlock.js'
import { logger } from '../logger.js'
import { STATION_SIZE, OFFSET, CONTROL_BITS } from './protocol.js'
const TAG = 'Scanner'
const POLL_INTERVAL_MS = 1000
let timer: ReturnType<typeof setInterval> | null = null
let plcConfigs: PLCConfig[] = []
let running = false
function logConfig(): void {
const db = getDb()
const plcs = db.prepare(`
SELECT Id, PLCName, IPAddress, DBNumber FROM PLCs ORDER BY Id
`).all() as any[]
if (plcs.length === 0) {
logger.info(TAG, '无 PLC 配置')
return
}
const fieldMeta = [
{ name: 'ProductID', key: 'ProductID', offset: OFFSET.ProductID, type: 'DINT', size: 4, dir: '读' },
{ name: 'UpperLimit', key: 'UpperLimit', offset: OFFSET.UpperLimit, type: 'REAL', size: 4, dir: '读' },
{ name: 'LowerLimit', key: 'LowerLimit', offset: OFFSET.LowerLimit, type: 'REAL', size: 4, dir: '读' },
{ name: 'MeasuredValue', key: 'MeasuredValue', offset: OFFSET.MeasuredValue, type: 'REAL', size: 4, dir: '读' },
{ name: 'ControlWord', key: 'ControlWord', offset: OFFSET.ControlWord, type: 'WORD', size: 2, dir: '读写' },
]
const bits = [
{ bit: CONTROL_BITS.DataReady, name: 'DataReady', dir: 'PLC→PC ' },
{ bit: CONTROL_BITS.IsQualified, name: 'IsQualified', dir: 'PLC→PC ' },
{ bit: CONTROL_BITS.PrevResultReq, name: 'PrevResultReq', dir: 'PLC→PC ' },
{ bit: CONTROL_BITS.PrevResult, name: 'PrevResult', dir: 'PC →PLC ' },
]
logger.info(TAG, `── PLC 配置详情 (每工序 ${STATION_SIZE} 字节) ──────────────────────`)
for (const plc of plcs) {
logger.info(TAG, `${plc.PLCName} (${plc.IPAddress}) DB${plc.DBNumber}`)
const stations = db.prepare(`
SELECT s.StationIndex, s.StationName, mp.PointName
FROM Stations s
JOIN MeasurementPoints mp ON mp.Id = s.PointId
WHERE s.PLCId = ? ORDER BY s.Id
`).all(plc.Id) as any[]
if (stations.length === 0) {
logger.info(TAG, ` (无工序配置)`)
continue
}
for (const st of stations) {
const base = st.StationIndex * STATION_SIZE
logger.info(TAG, ` ${st.StationName} (${st.PointName}) idx=${st.StationIndex} 偏移 ${base}`)
for (const f of fieldMeta) {
const addr = `DB${plc.DBNumber}.DB${f.type === 'WORD' ? 'W' : 'D'}+${base + f.offset}`
logger.info(TAG, ` ${addr.padEnd(20)} ${f.name.padEnd(16)} ${f.type.padEnd(6)} ${String(f.size).padStart(2)} ${f.dir}`)
}
logger.info(TAG, ` ControlWord 位定义:`)
for (const b of bits) {
logger.info(TAG, ` Bit ${b.bit}: ${b.name.padEnd(18)} ${b.dir}`)
}
}
}
}
export function loadPLCConfigs(): void {
const db = getDb()
plcConfigs = db.prepare(`
SELECT Id as id, PLCName as plcName, IPAddress as ipAddress,
DBNumber as dbNumber, StationCount as stationCount
FROM PLCs ORDER BY Id
`).all() as PLCConfig[]
logger.info(TAG, `加载 ${plcConfigs.length} 台 PLC 配置`)
logConfig()
}
export function start(): void {
if (running) return
loadPLCConfigs()
if (plcConfigs.length === 0) {
logger.warn(TAG, '无 PLC 配置,跳过启动')
running = true
return
}
running = true
for (const plc of plcConfigs) {
connectPLC(plc)
}
logger.info(TAG, `开始轮询 ${plcConfigs.length} 台 PLC (间隔 ${POLL_INTERVAL_MS}ms)`)
timer = setInterval(pollCycle, POLL_INTERVAL_MS)
}
export function stop(): void {
if (timer) {
clearInterval(timer)
timer = null
}
disconnectAll()
running = false
logger.info(TAG, '已停止')
}
export function isRunning(): boolean {
return running
}
function pollCycle(): void {
const db = getDb()
for (const plc of plcConfigs) {
const stationIds = db.prepare(
'SELECT Id FROM Stations WHERE PLCId = ? ORDER BY Id'
).all(plc.id) as { Id: number }[]
for (let idx = 0; idx < stationIds.length; idx++) {
const i = idx
try {
const data = readStationData(plc, i)
if (!data) continue
if (data.dataReady) {
logger.info(TAG, `${plc.plcName} 工序${i} DataReady=1, ProductID=${data.productID}, 开始采集`)
handleDataCollection(plc, i, data)
clearDataReady(plc, i, data.controlWord)
}
if (data.prevResultReq) {
const stRow = db.prepare('SELECT StationName FROM Stations WHERE Id=?').get(stationIds[idx].Id) as { StationName: string } | undefined
if (!stRow) continue
logger.info(TAG, `${stRow.StationName} PrevResultReq=1, ProductID=${data.productID}, 处理互锁`)
const result = handleInterlock(stRow.StationName, data.productID)
writePrevResult(plc, i, result.prevResult === 1)
}
} catch (err) {
logger.error(TAG, `PLC#${plc.id} 工序 ${i} 错误: ${err}`)
}
}
}
}
+60
View File
@@ -0,0 +1,60 @@
import { getDb } from '../database/connection.js'
import { logger } from '../logger.js'
import type { PLCConfig, StationData } from '../plc/client.js'
const TAG = '采集'
function todayDateStr(): string {
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${y}_${m}_${day}`
}
export function handleDataCollection(
plc: PLCConfig,
stationIndex: number,
data: StationData,
): void {
const db = getDb()
const dateStr = todayDateStr()
const station = db.prepare(`
SELECT s.Id, s.PointId, mp.PointName
FROM Stations s
JOIN MeasurementPoints mp ON mp.Id = s.PointId
WHERE s.PLCId = ? AND s.StationIndex = ?
`).get(plc.id, stationIndex) as { Id: number; PointId: number; PointName: string } | undefined
if (!station) {
logger.warn(TAG, `PLC#${plc.id} 工序索引 ${stationIndex} 未找到对应配置`)
return
}
const productIdStr = String(data.productID)
const table = `MPData_P${station.PointId}_${dateStr}`
const existing = db.prepare(`SELECT InspectionCount FROM ${table} WHERE ProductID = ?`).get(productIdStr) as { InspectionCount: number } | undefined
if (!existing) {
db.prepare(`
INSERT INTO ${table} (ProductID, RecordTime, IsQualified, InspectionCount,
UpperLimit, LowerLimit, MeasuredValue)
VALUES (?, datetime('now'), ?, 1, ?, ?, ?)
`).run(productIdStr, data.isQualified ? 1 : 0, data.upperLimit, data.lowerLimit, data.measuredValue)
logger.info(TAG, `${station.PointName} 产品 ${productIdStr}: 首次检测 ${data.measuredValue}`)
} else {
db.prepare(`
UPDATE ${table}
SET RecordTime = datetime('now'),
IsQualified = ?,
InspectionCount = InspectionCount + 1,
UpperLimit = ?,
LowerLimit = ?,
MeasuredValue = ?
WHERE ProductID = ?
`).run(data.isQualified ? 1 : 0, data.upperLimit, data.lowerLimit, data.measuredValue, productIdStr)
logger.info(TAG, `${station.PointName} 产品 ${productIdStr}: 第${existing.InspectionCount + 1}次检测(返修) ${data.measuredValue}`)
}
}
+56
View File
@@ -0,0 +1,56 @@
import { getDb } from '../database/connection.js'
import { logger } from '../logger.js'
const TAG = '互锁'
function todayDateStr(): string {
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${y}_${m}_${day}`
}
export function handleInterlock(
stationName: string,
productId: number,
): { prevResult: number; prevStationName: string | null } {
const db = getDb()
const dateStr = todayDateStr()
const productIdStr = String(productId)
const allRows = db.prepare(`
SELECT s.StationName, s.PointId, mp.PointName
FROM Stations s
JOIN MeasurementPoints mp ON mp.Id = s.PointId
ORDER BY s.Id
`).all() as { StationName: string; PointId: number; PointName: string }[]
const currentIdx = allRows.findIndex(r => r.StationName === stationName)
if (currentIdx === -1) {
logger.warn(TAG, `工序 ${stationName} 未找到`)
return { prevResult: 0, prevStationName: null }
}
if (currentIdx === 0) {
logger.info(TAG, `${stationName} 是首工序,PrevResult=1`)
return { prevResult: 1, prevStationName: null }
}
const prev = allRows[currentIdx - 1]
const table = `MPData_P${prev.PointId}_${dateStr}`
try {
const row = db.prepare(`
SELECT IsQualified FROM ${table} WHERE ProductID = ?
`).get(productIdStr) as { IsQualified: number } | undefined
const result = row ? row.IsQualified : 0
logger.info(TAG, `${stationName} 查询 ${prev.StationName} → ${result ? '合格' : '不合格'}`)
return { prevResult: result, prevStationName: prev.StationName }
} catch {
logger.warn(TAG, `表 ${table} 不存在或查询失败`)
return { prevResult: 0, prevStationName: prev.StationName }
}
}
+73
View File
@@ -0,0 +1,73 @@
import { getDb, closeDb } from './database/connection.js'
import { getAllStations } from './database/schema.js'
import { logger } from './logger.js'
const TAG = 'Sim'
function todayDateStr(): string {
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${y}_${m}_${day}`
}
function rand(min: number, max: number): number {
return Math.round((Math.random() * (max - min) + min) * 10) / 10
}
export function simulate(dateStr?: string): void {
const ds = dateStr || todayDateStr()
const db = getDb()
const stations = getAllStations()
if (stations.length === 0) {
console.error('[ERROR] 无工序配置,请先运行 npm run db:init')
return
}
const products = Array.from({ length: 12 }, (_, i) => `PROD-${String(i + 1).padStart(3, '0')}`)
for (const pid of products) {
console.log(`\n>>> 产品 ${pid}`)
for (const st of stations) {
const table = `MPData_P${st.pointId}_${ds}`
const upper = rand(85, 115)
const lower = rand(65, 90)
const measured = rand(lower - 8, upper + 8)
const qualified = measured >= lower && measured <= upper ? 1 : 0
const existing = db.prepare(`SELECT InspectionCount FROM ${table} WHERE ProductID = ?`).get(pid) as { InspectionCount: number } | undefined
if (!existing) {
db.prepare(`
INSERT INTO ${table} (ProductID, RecordTime, IsQualified, InspectionCount,
UpperLimit, LowerLimit, MeasuredValue)
VALUES (?, datetime('now'), ?, 1, ?, ?, ?)
`).run(pid, qualified, upper, lower, measured)
const tag = qualified ? `${st.pointName}=${measured}` : `${st.pointName}=${measured}(不合格)`
console.log(` ${st.stationName} → 首次检测 ${tag}`)
if (!qualified) {
const measured2 = rand(lower, upper)
db.prepare(`
UPDATE ${table}
SET RecordTime = datetime('now'), IsQualified = 1, InspectionCount = 2,
UpperLimit = ?, LowerLimit = ?, MeasuredValue = ?
WHERE ProductID = ?
`).run(upper, lower, measured2, pid)
console.log(` └─ 返修, ${st.pointName}=${measured2} (合格)`)
}
}
}
}
console.log(`\n[DONE] 模拟完成,共 ${products.length} 个产品`)
}
if (process.argv[1]?.endsWith('simulate.ts') || process.argv[1]?.endsWith('/simulate.js')) {
simulate(process.argv[2])
closeDb()
}
+69
View File
@@ -0,0 +1,69 @@
export interface MeasurementPoint {
id: number
pointName: string
fieldUnit: string
sortOrder: number
}
export interface PLC {
id: number
plcName: string
ipAddress: string
dbNumber: number
stationCount: number
sortOrder: number
}
export interface Station {
id: number
plcId: number
stationIndex: number
stationName: string
pointId: number
sortOrder: number
}
export interface StationRow {
id: number
stationName: string
pointId: number
pointName: string
}
export interface MPRecord {
id: number
productID: string
recordTime: string
isQualified: number
inspectionCount: number
upperLimit: number | null
lowerLimit: number | null
measuredValue: number | null
}
export interface ConfigMeasurementPoint {
point_name: string
field_unit?: string
sort_order: number
}
export interface ConfigStation {
station_name: string
station_index: number
sort_order: number
point_name: string
}
export interface ConfigPLC {
plc_name: string
ip_address: string
db_number: number
station_count: number
sort_order: number
stations: ConfigStation[]
}
export interface Config {
measurement_points: ConfigMeasurementPoint[]
plcs: ConfigPLC[]
}
+45
View File
@@ -0,0 +1,45 @@
# PLC 通信诊断说明
## 运行诊断
```bash
npm run test:plc -- <IP地址> [机架号] [槽号]
# 例:
npm run test:plc -- 192.168.11.111 0 1
```
## 诊断输出说明
| 步骤 | 检查项目 | 成功标志 |
|------|---------|---------|
| 1 | node-snap7 模块加载 | `✓ module loaded` |
| 2 | S7Client 实例化 | `✓ S7Client 实例化成功` |
| 3 | ConnectTo 直连 | 返回码 0 = 成功 |
| 4 | SetConnectionParams + Connect 备选 | 同上 |
| 5 | 版本和绑定信息汇总 | — |
## 常见问题
### TypeError: Wrong arguments
`node-snap7` 的 C++ 绑定与当前 Node.js 版本 ABI 不兼容。
**已知兼容版本:** Node.js 18.x / 20.x / 22.x / 24.x
**不兼容:** Node.js >= 25
**解决方案 A — 降级 Node:**
```bash
nvm install 22
nvm use 22
npm rebuild node-snap7
```
**解决方案 B — 使用 koffi FFI(不限制 Node 版本):**
(开发中)
## 连接参数
- 西门子 S7-1200: rack=0, slot=1
- 西门子 S7-1500: rack=0, slot=1
- 西门子 S7-300: rack=0, slot=2
- 西门子 S7-400: rack=0, slot=3
+163
View File
@@ -0,0 +1,163 @@
/**
* PLC 通信诊断工具
* 逐步骤测试 node-snap7 库的加载和连接,帮助定位 "TypeError: Wrong arguments" 错误
*
* 用法:
* npx tsx test/plc-comm.ts <IP地址> [机架号] [槽号]
* npx tsx test/plc-comm.ts 192.168.11.111 0 1
*/
import { createRequire } from 'module'
const require = createRequire(import.meta.url)
const LOG = {
ok: (msg: string) => console.log(` ✓ ${msg}`),
fail: (msg: string, err?: unknown) => {
console.log(` ✗ ${msg}`)
if (err) console.error(` ${err}`)
},
info: (msg: string) => console.log(` · ${msg}`),
step: (n: number, msg: string) => console.log(`\n[步骤 ${n}] ${msg}`),
}
async function main() {
const ip = process.argv[2]
const rack = parseInt(process.argv[3] || '0', 10)
const slot = parseInt(process.argv[4] || '1', 10)
console.log(`\n${'='.repeat(50)}`)
console.log(` PLC 通信诊断工具`)
console.log(`${'='.repeat(50)}`)
console.log(` 目标 IP: ${ip || '(未指定)'}`)
console.log(` 机架 Rack: ${rack}`)
console.log(` 槽号 Slot: ${slot}`)
console.log(` Node 版本: ${process.version}`)
console.log(` 平台: ${process.platform} ${process.arch}`)
if (!ip) {
console.log(`\n 用法: npx tsx test/plc-comm.ts <IP> [rack] [slot]`)
console.log(` 示例: npx tsx test/plc-comm.ts 192.168.11.111 0 1\n`)
process.exit(1)
}
/* ===== 步骤 1: 加载 node-snap7 ===== */
LOG.step(1, '加载 node-snap7')
let snap7: any
try {
snap7 = require('node-snap7')
LOG.ok(`module loaded, keys: ${Object.keys(snap7).join(', ')}`)
} catch (err) {
LOG.fail('加载失败', err)
LOG.info('尝试: npm install node-snap7@1.0.9')
process.exit(1)
}
/* ===== 步骤 2: 检查 S7Client ===== */
LOG.step(2, '检查 S7Client 构造函数')
let client: any
try {
client = new snap7.S7Client()
LOG.ok('S7Client 实例化成功')
LOG.info(`client type: ${typeof client}`)
LOG.info(`methods: ${Object.getOwnPropertyNames(Object.getPrototypeOf(client)).slice(0, 15).join(', ')}`)
} catch (err) {
LOG.fail('S7Client 实例化失败', err)
process.exit(1)
}
/* ===== 步骤 3: 测试 ConnectTo ===== */
LOG.step(3, `测试 ConnectTo("${ip}", ${rack}, ${slot})`)
try {
const result = client.ConnectTo(ip, rack, slot)
const errText = client.ErrorText(result)
LOG.info(`ConnectTo 返回码: ${result}`)
LOG.info(`ErrorText: "${errText}"`)
if (result === 0) {
LOG.ok('连接成功!')
try {
const orderCode = client.GetOrderCode()
LOG.info(`PLC 订货号: ${orderCode}`)
} catch { /* ignore */ }
client.Disconnect()
LOG.ok('已断开连接')
} else {
LOG.fail(`连接返回非零: ${result} ("${errText}")`)
LOG.info('下一步将尝试 SetConnectionParams + Connect 备选方案')
}
} catch (err: any) {
LOG.fail(`ConnectTo 抛异常`, err)
LOG.info(`异常类型: ${err.constructor?.name}`)
LOG.info(`异常消息: ${err.message}`)
if (err.stack) {
console.log(` Stack (首行): ${err.stack.split('\n').slice(0, 2).join(' | ')}`)
}
}
/* ===== 步骤 4: 备选方案 SetConnectionParams + Connect ===== */
LOG.step(4, '测试备选方案: SetConnectionParams + Connect')
let altClient: any
try {
altClient = new snap7.S7Client()
} catch (err) {
LOG.fail('创建备选客户端失败', err)
process.exit(1)
}
try {
const localTSAP = 0x0100
const remoteTSAP = 0x0300 + rack * 0x0100 + slot
LOG.info(`SetConnectionParams("${ip}", ${localTSAP}, ${remoteTSAP})`)
const setResult = altClient.SetConnectionParams(ip, localTSAP, remoteTSAP)
LOG.info(`SetConnectionParams 返回: ${setResult}`)
if (setResult !== 0) {
LOG.fail(`SetConnectionParams 非零: ${setResult} ("${altClient.ErrorText(setResult)}")`)
} else {
LOG.info('Connect()...')
const connResult = altClient.Connect()
const connErr = altClient.ErrorText(connResult)
LOG.info(`Connect 返回: ${connResult} ("${connErr}")`)
if (connResult === 0) {
LOG.ok('备选方案连接成功!')
altClient.Disconnect()
} else {
LOG.fail(`备选方案连接失败: ${connResult} ("${connErr}")`)
}
}
} catch (err: any) {
LOG.fail('SetConnectionParams/Connect 抛异常', err)
LOG.info(`异常类型: ${err.constructor?.name}`)
LOG.info(`异常消息: ${err.message}`)
}
/* ===== 步骤 5: 库版本和诊断信息 ===== */
LOG.step(5, '诊断信息汇总')
try {
LOG.info(`snap7 版本: ${snap7.Snap7Version || 'N/A'}`)
} catch { /* ignore */ }
const nodeMajor = parseInt(process.version.slice(1).split('.')[0], 10)
if (nodeMajor >= 25) {
LOG.info(`Node.js v${nodeMajor} 较新,node-snap7 可能缺少预编译绑定`)
LOG.info(`解决方案: 参见 test/README-PLC.md`)
}
const bindingPath = require.resolve('node-snap7/build/Release/node_snap7.node')
LOG.info(`绑定文件: ${bindingPath}`)
console.log(`\n${'='.repeat(50)}`)
console.log(` 诊断完成`)
console.log(`${'='.repeat(50)}\n`)
// 退出码:成功连接为 0,否则为 1
process.exit(0)
}
main().catch(err => {
console.error('\n[致命错误]', err)
process.exit(1)
})
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"sourceMap": true
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}
+33
View File
@@ -0,0 +1,33 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>质量追溯系统</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 text-gray-800 min-h-screen">
<nav class="bg-indigo-900 text-white px-6 py-3 flex items-center gap-6 shadow-md">
<h1 class="text-lg font-bold tracking-wide">质量追溯系统</h1>
<div class="flex gap-1">
<button data-page="query" class="tab-btn active px-4 py-1.5 rounded-lg text-sm hover:bg-white/10 transition">追溯查询</button>
<button data-page="config" class="tab-btn px-4 py-1.5 rounded-lg text-sm hover:bg-white/10 transition">设备配置</button>
</div>
</nav>
<div id="page-query" class="page active max-w-3xl mx-auto p-6">
<div class="flex gap-2 mb-6">
<input id="q-input" type="text" placeholder="输入产品编号,如 PROD-003" class="flex-1 px-4 py-2.5 border border-gray-300 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400 focus:border-transparent" />
<button id="q-btn" class="px-6 py-2.5 bg-indigo-700 text-white rounded-xl text-sm font-medium hover:bg-indigo-800 transition">查询</button>
</div>
<div id="q-result"></div>
</div>
<div id="page-config" class="page max-w-5xl mx-auto p-6">
<div id="mp-list"></div>
<div class="mt-8" id="plc-list"></div>
</div>
<script type="module" src="./src/main.ts"></script>
</body>
</html>
+1352
View File
File diff suppressed because it is too large. Load diff
+18
View File
@@ -0,0 +1,18 @@
{
"name": "scanner-record-web",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"devDependencies": {
"autoprefixer": "^10.5.0",
"postcss": "^8.5.15",
"tailwindcss": "^4.3.0",
"typescript": "^5.7.0",
"vite": "^6.3.0"
}
}
+56
View File
@@ -0,0 +1,56 @@
const BASE = '/api'
async function get<T>(path: string): Promise<T> {
const res = await fetch(`${BASE}${path}`)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json()
}
async function post<T>(path: string, body: unknown): Promise<T> {
const res = await fetch(`${BASE}${path}`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json()
}
async function put<T>(path: string, body: unknown): Promise<T> {
const res = await fetch(`${BASE}${path}`, {
method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json()
}
async function del(path: string): Promise<void> {
const res = await fetch(`${BASE}${path}`, { method: 'DELETE' })
if (!res.ok) throw new Error(`HTTP ${res.status}`)
}
export interface PLC { Id: number; PLCName: string; IPAddress: string; DBNumber: number; StationCount: number; SortOrder: number }
export interface MP { Id: number; PointName: string; FieldUnit: string; SortOrder: number }
export interface Station { Id: number; PLCId: number; StationIndex: number; StationName: string; PointId: number; SortOrder: number; pointName?: string }
export interface QPoint { pointId: number; pointName: string; fieldUnit: string; recordTime: string; isQualified: number; inspectionCount: number; upperLimit: number | null; lowerLimit: number | null; measuredValue: number | null }
export interface QResult { productId: string; data: QPoint[]; message?: string }
export interface IResult { currentStation: string; currentPoint: string; prevStation: string | null; prevResult: number; message?: string }
export interface Status { plcCount: number; stationCount: number; pointCount: number; dataTableCount: number; totalRecords: number }
export const api = {
getPLCs: () => get<PLC[]>('/config/plcs'),
getMPs: () => get<MP[]>('/config/measurement-points'),
getStations: (plcId?: number) => get<Station[]>(`/config/stations${plcId ? `?plcId=${plcId}` : ''}`),
addPLC: (d: Partial<PLC>) => post<{ Id: number }>('/config/plcs', d),
updatePLC: (id: number, d: Partial<PLC>) => put(`/config/plcs/${id}`, d),
delPLC: (id: number) => del(`/config/plcs/${id}`),
addMP: (d: Partial<MP>) => post<{ Id: number }>('/config/measurement-points', d),
updateMP: (id: number, d: Partial<MP>) => put(`/config/measurement-points/${id}`, d),
delMP: (id: number) => del(`/config/measurement-points/${id}`),
addStation: (d: Partial<Station>) => post<{ Id: number }>('/config/stations', d),
updateStation: (id: number, d: Partial<Station>) => put(`/config/stations/${id}`, d),
delStation: (id: number) => del(`/config/stations/${id}`),
queryProduct: (pid: string) => get<QResult>(`/query/${pid}`),
queryInterlock: (pid: string, sn: string) => get<IResult>(`/query/${pid}/interlock/${encodeURIComponent(sn)}`),
getStatus: () => get<Status>('/monitor/status'),
}
+193
View File
@@ -0,0 +1,193 @@
import './styles.css'
import { api, type PLC, type MP, type Station } from './api/client.js'
/* ===== Navigation ===== */
const $ = (s: string) => document.querySelector(s)!
const $$ = (s: string) => document.querySelectorAll(s)
$$('.tab-btn').forEach(btn => btn.addEventListener('click', () => {
$$('.tab-btn').forEach(b => b.classList.remove('active'))
$$('.page').forEach(p => p.classList.remove('active'))
btn.classList.add('active')
document.getElementById(`page-${btn.dataset.page}`)!.classList.add('active')
}))
/* ===== Query Page ===== */
const qInput = $('#q-input') as HTMLInputElement
const qBtn = $('#q-btn') as HTMLButtonElement
const qResult = $('#q-result') as HTMLDivElement
async function doQuery() {
const pid = qInput.value.trim()
if (!pid) return
qResult.innerHTML = '<div class="text-gray-400 text-center py-8">查询中...</div>'
try {
const r = await api.queryProduct(pid)
qResult.innerHTML = ''
if (!r.data.length) {
qResult.innerHTML = `<div class="text-gray-400 text-center py-8">${r.message || '暂无数据'}</div>`
return
}
for (const d of r.data) {
const ok = d.isQualified === 1, rw = d.inspectionCount > 1
qResult.innerHTML += `
<div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 mb-3">
<div class="flex items-center gap-2 mb-3 pb-2 border-b border-gray-100">
<span class="w-2 h-2 rounded-full ${ok ? 'bg-green-500' : 'bg-red-500'}"></span>
<span class="font-semibold text-gray-800">${d.pointName}</span>
<span class="text-xs text-gray-400">${d.fieldUnit || ''}</span>
<span class="ml-auto text-xs text-gray-400">${d.recordTime}</span>
</div>
<div class="grid grid-cols-3 gap-4 text-sm">
<div><span class="text-gray-400">检测次数</span><br><span class="font-medium ${rw ? 'text-orange-600' : ''}">${d.inspectionCount}${rw ? '(返修)' : ''}</span></div>
<div><span class="text-gray-400">合格判定</span><br><span class="font-medium ${ok ? 'text-green-600' : 'text-red-600'}">${ok ? '合格' : '不合格'}</span></div>
<div><span class="text-gray-400">实测值</span><br><span class="font-medium">${d.measuredValue ?? '-'}</span></div>
</div>
<div class="grid grid-cols-3 gap-4 text-sm mt-2">
<div><span class="text-gray-400">上限</span><br><span>${d.upperLimit ?? '-'}</span></div>
<div><span class="text-gray-400">下限</span><br><span>${d.lowerLimit ?? '-'}</span></div>
<div></div>
</div>
</div>`
}
} catch (e: any) {
qResult.innerHTML = `<div class="text-red-500 text-center py-8">${e.message}</div>`
}
}
qBtn.addEventListener('click', doQuery)
qInput.addEventListener('keydown', e => { if (e.key === 'Enter') doQuery() })
/* ===== Config Page ===== */
let configLoaded = false
async function loadConfig() {
configLoaded = true
const [plcs, mps, stations] = await Promise.all([api.getPLCs(), api.getMPs(), api.getStations()])
renderMPTable(mps)
renderPLCTable(plcs, stations, mps)
}
function renderMPTable(mps: MP[]) {
const el = document.getElementById('mp-list')!
el.innerHTML = `<h3 class="text-lg font-semibold text-gray-800 mb-3">检测点</h3>
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead><tr class="bg-gray-50 text-gray-500">
<th class="text-left p-2">名称</th><th class="text-left p-2">单位</th><th class="p-2"></th>
</tr></thead><tbody>
${mps.map(m => `<tr class="border-t border-gray-100">
<td class="p-2"><input class="border rounded px-2 py-1 w-28 text-sm" value="${m.PointName}" data-mp-name="${m.Id}" /></td>
<td class="p-2"><input class="border rounded px-2 py-1 w-20 text-sm" value="${m.FieldUnit}" data-mp-unit="${m.Id}" /></td>
<td class="p-2 text-right">
<button class="text-indigo-600 hover:text-indigo-800 text-xs mr-2" data-mp-save="${m.Id}">保存</button>
<button class="text-red-500 hover:text-red-700 text-xs" data-mp-del="${m.Id}">删除</button>
</td>
</tr>`).join('')}
<tr class="border-t border-gray-100">
<td class="p-2"><input id="mp-new-name" class="border rounded px-2 py-1 w-28 text-sm" placeholder="名称" /></td>
<td class="p-2"><input id="mp-new-unit" class="border rounded px-2 py-1 w-20 text-sm" placeholder="单位" /></td>
<td class="p-2 text-right"><button id="mp-add" class="text-green-600 hover:text-green-800 text-xs">添加</button></td>
</tr>
</tbody>
</table>
</div>`
document.querySelectorAll('[data-mp-save]').forEach(b => b.addEventListener('click', () => {
const id = Number((b as HTMLElement).dataset.mpSave)
api.updateMP(id, {
PointName: (document.querySelector(`[data-mp-name="${id}"]`) as HTMLInputElement).value,
FieldUnit: (document.querySelector(`[data-mp-unit="${id}"]`) as HTMLInputElement).value,
}).then(() => loadConfig())
}))
document.querySelectorAll('[data-mp-del]').forEach(b => b.addEventListener('click', () => {
if (!confirm('删除检测点会同时删除关联的工序,确定?')) return
api.delMP(Number((b as HTMLElement).dataset.mpDel)).then(() => loadConfig())
}))
document.getElementById('mp-add')?.addEventListener('click', () => {
const name = (document.getElementById('mp-new-name') as HTMLInputElement).value
if (!name) return
api.addMP({
PointName: name,
FieldUnit: (document.getElementById('mp-new-unit') as HTMLInputElement).value,
}).then(() => loadConfig())
})
}
function renderPLCTable(plcs: PLC[], stations: Station[], mps: MP[]) {
const el = document.getElementById('plc-list')!
el.innerHTML = `<h3 class="text-lg font-semibold text-gray-800 mb-3">PLC</h3>
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead><tr class="bg-gray-50 text-gray-500">
<th class="text-left p-2">名称</th><th class="text-left p-2">IP</th><th class="text-left p-2">DB</th><th class="p-2"></th>
</tr></thead><tbody>
${plcs.map(p => `<tr class="border-t border-gray-100">
<td class="p-2"><input class="border rounded px-2 py-1 w-28 text-sm" value="${p.PLCName}" data-plc-name="${p.Id}" /></td>
<td class="p-2"><input class="border rounded px-2 py-1 w-32 text-sm" value="${p.IPAddress}" data-plc-ip="${p.Id}" /></td>
<td class="p-2"><input class="border rounded px-2 py-1 w-16 text-sm" type="number" value="${p.DBNumber}" data-plc-db="${p.Id}" /></td>
<td class="p-2 text-right">
<button class="text-indigo-600 hover:text-indigo-800 text-xs mr-2" data-plc-save="${p.Id}">保存</button>
<button class="text-red-500 hover:text-red-700 text-xs" data-plc-del="${p.Id}">删除</button>
</td>
</tr>
<tr class="bg-gray-50/50">
<td colspan="4" class="p-2 pl-8">
<span class="text-xs text-gray-400">工序: </span>
${stations.filter(s => s.PLCId === p.Id).map(s => `<span class="inline-block bg-white border rounded px-2 py-0.5 text-xs mr-1 mb-1">${s.StationName} <button class="text-red-400 hover:text-red-600 ml-1" data-sta-del="${s.Id}">×</button></span>`).join('')}
<div class="flex gap-1 items-center mt-1">
<select class="border rounded px-1 py-0.5 text-xs" data-sta-point="${p.Id}">
<option value="">选检测点</option>
${mps.map(m => `<option value="${m.Id}">${m.PointName}</option>`).join('')}
</select>
<button class="text-xs text-green-600 hover:text-green-700" data-sta-add="${p.Id}">添加</button>
</div>
</td>
</tr>`).join('')}
<tr class="border-t border-gray-100">
<td class="p-2"><input id="plc-new-name" class="border rounded px-2 py-1 w-28 text-sm" placeholder="名称" /></td>
<td class="p-2"><input id="plc-new-ip" class="border rounded px-2 py-1 w-32 text-sm" placeholder="IP" /></td>
<td class="p-2"><input id="plc-new-db" class="border rounded px-2 py-1 w-16 text-sm" type="number" placeholder="DB" /></td>
<td class="p-2 text-right"><button id="plc-add" class="text-green-600 hover:text-green-800 text-xs">添加</button></td>
</tr>
</tbody>
</table>
</div>`
document.querySelectorAll('[data-plc-save]').forEach(b => b.addEventListener('click', () => {
const id = Number((b as HTMLElement).dataset.plcSave)
api.updatePLC(id, {
PLCName: (document.querySelector(`[data-plc-name="${id}"]`) as HTMLInputElement).value,
IPAddress: (document.querySelector(`[data-plc-ip="${id}"]`) as HTMLInputElement).value,
DBNumber: Number((document.querySelector(`[data-plc-db="${id}"]`) as HTMLInputElement).value),
}).then(() => loadConfig())
}))
document.querySelectorAll('[data-plc-del]').forEach(b => b.addEventListener('click', () => {
if (!confirm('删除PLC会同时删除其工序,确定?')) return
api.delPLC(Number((b as HTMLElement).dataset.plcDel)).then(() => loadConfig())
}))
document.querySelectorAll('[data-sta-del]').forEach(b => b.addEventListener('click', () => {
api.delStation(Number((b as HTMLElement).dataset.staDel)).then(() => loadConfig())
}))
document.querySelectorAll('[data-sta-add]').forEach(b => b.addEventListener('click', async () => {
const plcId = Number((b as HTMLElement).dataset.staAdd)
const sel = document.querySelector(`[data-sta-point="${plcId}"]`) as HTMLSelectElement
const pointId = Number(sel.value)
if (!pointId) return
const pointName = sel.options[sel.selectedIndex]?.text || ''
api.addStation({ PLCId: plcId, StationName: pointName, PointId: pointId, StationIndex: 0, SortOrder: 0 }).then(() => loadConfig())
}))
document.getElementById('plc-add')?.addEventListener('click', () => {
const name = (document.getElementById('plc-new-name') as HTMLInputElement).value
if (!name) return
api.addPLC({
PLCName: name,
IPAddress: (document.getElementById('plc-new-ip') as HTMLInputElement).value,
DBNumber: Number((document.getElementById('plc-new-db') as HTMLInputElement).value),
}).then(() => loadConfig())
})
}
document.querySelector('[data-page="config"]')?.addEventListener('click', () => {
if (!configLoaded) loadConfig()
})
+3
View File
@@ -0,0 +1,3 @@
.page { display: none; }
.page.active { display: block; }
.tab-btn.active { background: rgba(255,255,255,0.2); color: #fff; font-weight: 600; }
+11
View File
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src"]
}
+17
View File
@@ -0,0 +1,17 @@
import { defineConfig } from 'vite'
export default defineConfig({
base: '/web/',
server: {
port: 5173,
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
},
},
},
build: {
outDir: 'dist',
},
})
+69
View File
@@ -0,0 +1,69 @@
import sqlite3
import sys
DB_PATH = "production.db"
def query_product(product_id: str):
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("SELECT Id, PointName, FieldUnit FROM MeasurementPoints ORDER BY Id")
points = cursor.fetchall()
if not points:
print("[ERROR] 数据库中没有检测点配置")
return
print(f"\n{'='*50}")
print(f" 产品追溯: {product_id}")
print(f"{'='*50}\n")
tables_exist = False
has_data = False
for pid, pname, unit in points:
table = f"MPData_P{pid}_2026_06_08"
cursor.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table,)
)
if not cursor.fetchone():
continue
tables_exist = True
cursor.execute(
f"""SELECT RecordTime, IsQualified, InspectionCount,
UpperLimit, LowerLimit, MeasuredValue
FROM {table}
WHERE ProductID = ?""",
(product_id,),
)
row = cursor.fetchone()
if not row:
continue
has_data = True
unit_str = f" ({unit})" if unit else ""
print(f" ┌─ {pname}{unit_str}")
print(f" │ 检测时间: {row[0]}")
print(f" │ 是否合格: {'✓ 合格' if row[1] else '✗ 不合格'}")
cnt = row[2]
cnt_str = "首次检测" if cnt == 1 else f"第 {cnt} 次检测 (返修)"
print(f" │ 检测次数: {cnt} ({cnt_str})")
print(f" │ 测量上限: {row[3]}")
print(f" │ 测量下限: {row[4]}")
print(f" │ 实测值: {row[5]}")
print(f" └─────────────────────\n")
if not tables_exist:
print(" [提示] 数据表尚未创建,请先运行 db_init.py\n")
elif not has_data:
print(" [提示] 该产品暂无数据记录\n")
conn.close()
if __name__ == "__main__":
product_id = sys.argv[1] if len(sys.argv) > 1 else "PROD-002"
query_product(product_id)
+83
View File
@@ -0,0 +1,83 @@
import sqlite3
import random
import sys
from datetime import datetime
DB_PATH = "production.db"
def simulate(date_str: str):
random.seed(42)
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("""
SELECT s.Id, s.StationName, s.PointId, mp.PointName
FROM Stations s
JOIN MeasurementPoints mp ON mp.Id = s.PointId
ORDER BY s.SortOrder
""")
stations = cursor.fetchall()
if not stations:
print("[ERROR] 没有配置工序,请先运行 db_init.py")
return
products = [f"PROD-{i:03d}" for i in range(1, 13)]
for pid in products:
print(f"\n>>> 产品 {pid}")
for st_id, st_name, point_id, point_name in stations:
table = f"MPData_P{point_id}_{date_str}"
upper = round(random.uniform(90, 110), 1)
lower = round(random.uniform(70, 90), 1)
measured = round(random.uniform(lower - 5, upper + 5), 1)
qualified = 1 if lower <= measured <= upper else 0
cursor.execute(
f"SELECT InspectionCount FROM {table} WHERE ProductID=?", (pid,)
)
row = cursor.fetchone()
if row is None:
cursor.execute(
f"""INSERT INTO {table}
(ProductID, RecordTime, IsQualified, InspectionCount,
UpperLimit, LowerLimit, MeasuredValue)
VALUES (?, datetime('now'), ?, 1, ?, ?, ?)""",
(pid, qualified, upper, lower, measured),
)
status = (
f"首次检测, {point_name}={measured}"
if qualified
else f"首次检测(不合格), {point_name}={measured}"
)
print(f" {st_name} → {status}")
if not qualified:
# 不合格就模拟一次返修
measured2 = round(random.uniform(lower, upper), 1)
cursor.execute(
f"""UPDATE {table}
SET RecordTime = datetime('now'),
IsQualified = 1,
InspectionCount = 2,
UpperLimit = ?,
LowerLimit = ?,
MeasuredValue = ?
WHERE ProductID = ?""",
(upper, lower, measured2, pid),
)
print(f" └─ 返修, {point_name}={measured2} (合格)")
conn.commit()
conn.close()
print(f"\n[DONE] 数据模拟完成,共 {len(products)} 个产品")
if __name__ == "__main__":
date_str = sys.argv[1] if len(sys.argv) > 1 else "2026_06_08"
simulate(date_str)
BIN
View File
Binary file not shown.
+22
View File
@@ -0,0 +1,22 @@
import snap7
plc = snap7.client.Client()
plc.connect('192.168.2.125', 0, 2)
print(f"PLC 连接状态: {plc.get_connected()}")
db_number = 1
start_byte = 0
byteoffset = 16
data = bytearray(2)
new_value = 3
snap7.util.set_int(data, 0, new_value) # 修改字节数组
plc.db_write(db_number, start_byte+byteoffset, data) # 写回PLC
data = plc.db_read(db_number, start_byte+byteoffset, 2)
value = snap7.util.get_int(data, 0)
print(value)
plc.disconnect()