commit ae90bc936839d7018c55c26cf9082e5db23264d4 Author: zlm Date: Tue Jun 9 14:32:13 2026 +0800 init: PLC data collection system diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8b43ee2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +node_modules/ +dist/ +*.db +*.db-wal +*.db-shm +.env diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..4b5a294 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "python-envs.defaultEnvManager": "ms-python.python:conda", + "python-envs.defaultPackageManager": "ms-python.python:conda" +} \ No newline at end of file diff --git a/db_init.py b/db_init.py new file mode 100644 index 0000000..fc35276 --- /dev/null +++ b/db_init.py @@ -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) diff --git a/interlock_query.py b/interlock_query.py new file mode 100644 index 0000000..ea580f6 --- /dev/null +++ b/interlock_query.py @@ -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]) diff --git a/pc_database_design.md b/pc_database_design.md new file mode 100644 index 0000000..82d5626 --- /dev/null +++ b/pc_database_design.md @@ -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}_{日期}**(每个检测点一张数据表) diff --git a/plc_protocol_design.md b/plc_protocol_design.md new file mode 100644 index 0000000..c410b36 --- /dev/null +++ b/plc_protocol_design.md @@ -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** = 该工序有新的测量数据待读取
**0** = 空闲(PC 读完数据后写 0) | +| Bit 1 | `IsQualified` | PLC → PC | **1** = 当前产品该工序测量合格
**0** = 不合格 | +| Bit 2 | `PrevResultReq` | PLC → PC | **1** = PLC 请求查询上一工序的合格结果
**0** = 无请求(PC 处理完后写 0) | +| Bit 3 | `PrevResult` | PC → PLC | **1** = 上一工序合格(PC 写入)
**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 +``` diff --git a/project/package-lock.json b/project/package-lock.json new file mode 100644 index 0000000..706f114 --- /dev/null +++ b/project/package-lock.json @@ -0,0 +1,1074 @@ +{ + "name": "scanner-record", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "scanner-record", + "version": "1.0.0", + "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" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/aix-ppc64/-/aix-ppc64-0.28.0.tgz", + "integrity": "sha512-lhRUCeuOyJQURhTxl4WkpFTjIsbDayJHih5kZC1giwE+MhIzAb7mEsQMqMf18rHLsrb5qI1tafG20mLxEWcWlA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/android-arm/-/android-arm-0.28.0.tgz", + "integrity": "sha512-wqh0ByljabXLKHeWXYLqoJ5jKC4XBaw6Hk08OfMrCRd2nP2ZQ5eleDZC41XHyCNgktBGYMbqnrJKq/K/lzPMSQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/android-arm64/-/android-arm64-0.28.0.tgz", + "integrity": "sha512-+WzIXQOSaGs33tLEgYPYe/yQHf0WTU0X42Jca3y8NWMbUVhp7rUnw+vAsRC/QiDrdD31IszMrZy+qwPOPjd+rw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/android-x64/-/android-x64-0.28.0.tgz", + "integrity": "sha512-+VJggoaKhk2VNNqVL7f6S189UzShHC/mR9EE8rDdSkdpN0KflSwWY/gWjDrNxxisg8Fp1ZCD9jLMo4m0OUfeUA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/darwin-arm64/-/darwin-arm64-0.28.0.tgz", + "integrity": "sha512-0T+A9WZm+bZ84nZBtk1ckYsOvyA3x7e2Acj1KdVfV4/2tdG4fzUp91YHx+GArWLtwqp77pBXVCPn2We7Letr0Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/darwin-x64/-/darwin-x64-0.28.0.tgz", + "integrity": "sha512-fyzLm/DLDl/84OCfp2f/XQ4flmORsjU7VKt8HLjvIXChJoFFOIL6pLJPH4Yhd1n1gGFF9mPwtlN5Wf82DZs+LQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.0.tgz", + "integrity": "sha512-l9GeW5UZBT9k9brBYI+0WDffcRxgHQD8ShN2Ur4xWq/NFzUKm3k5lsH4PdaRgb2w7mI9u61nr2gI2mLI27Nh3Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/freebsd-x64/-/freebsd-x64-0.28.0.tgz", + "integrity": "sha512-BXoQai/A0wPO6Es3yFJ7APCiKGc1tdAEOgeTNy3SsB491S3aHn4S4r3e976eUnPdU+NbdtmBuLncYir2tMU9Nw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-arm/-/linux-arm-0.28.0.tgz", + "integrity": "sha512-CjaaREJagqJp7iTaNQjjidaNbCKYcd4IDkzbwwxtSvjI7NZm79qiHc8HqciMddQ6CKvJT6aBd8lO9kN/ZudLlw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-arm64/-/linux-arm64-0.28.0.tgz", + "integrity": "sha512-RVyzfb3FWsGA55n6WY0MEIEPURL1FcbhFE6BffZEMEekfCzCIMtB5yyDcFnVbTnwk+CLAgTujmV/Lgvih56W+A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-ia32/-/linux-ia32-0.28.0.tgz", + "integrity": "sha512-KBnSTt1kxl9x70q+ydterVdl+Cn0H18ngRMRCEQfrbqdUuntQQ0LoMZv47uB97NljZFzY6HcfqEZ2SAyIUTQBQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-loong64/-/linux-loong64-0.28.0.tgz", + "integrity": "sha512-zpSlUce1mnxzgBADvxKXX5sl8aYQHo2ezvMNI8I0lbblJtp8V4odlm3Yzlj7gPyt3T8ReksE6bK+pT3WD+aJRg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-mips64el/-/linux-mips64el-0.28.0.tgz", + "integrity": "sha512-2jIfP6mmjkdmeTlsX/9vmdmhBmKADrWqN7zcdtHIeNSCH1SqIoNI63cYsjQR8J+wGa4Y5izRcSHSm8K3QWmk3w==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-ppc64/-/linux-ppc64-0.28.0.tgz", + "integrity": "sha512-bc0FE9wWeC0WBm49IQMPSPILRocGTQt3j5KPCA8os6VprfuJ7KD+5PzESSrJ6GmPIPJK965ZJHTUlSA6GNYEhg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-riscv64/-/linux-riscv64-0.28.0.tgz", + "integrity": "sha512-SQPZOwoTTT/HXFXQJG/vBX8sOFagGqvZyXcgLA3NhIqcBv1BJU1d46c0rGcrij2B56Z2rNiSLaZOYW5cUk7yLQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-s390x/-/linux-s390x-0.28.0.tgz", + "integrity": "sha512-SCfR0HN8CEEjnYnySJTd2cw0k9OHB/YFzt5zgJEwa+wL/T/raGWYMBqwDNAC6dqFKmJYZoQBRfHjgwLHGSrn3Q==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-x64/-/linux-x64-0.28.0.tgz", + "integrity": "sha512-us0dSb9iFxIi8srnpl931Nvs65it/Jd2a2K3qs7fz2WfGPHqzfzZTfec7oxZJRNPXPnNYZtanmRc4AL/JwVzHQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.0.tgz", + "integrity": "sha512-CR/RYotgtCKwtftMwJlUU7xCVNg3lMYZ0RzTmAHSfLCXw3NtZtNpswLEj/Kkf6kEL3Gw+BpOekRX0BYCtklhUw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/netbsd-x64/-/netbsd-x64-0.28.0.tgz", + "integrity": "sha512-nU1yhmYutL+fQ71Kxnhg8uEOdC0pwEW9entHykTgEbna2pw2dkbFSMeqjjyHZoCmt8SBkOSvV+yNmm94aUrrqw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.0.tgz", + "integrity": "sha512-cXb5vApOsRsxsEl4mcZ1XY3D4DzcoMxR/nnc4IyqYs0rTI8ZKmW6kyyg+11Z8yvgMfAEldKzP7AdP64HnSC/6g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/openbsd-x64/-/openbsd-x64-0.28.0.tgz", + "integrity": "sha512-8wZM2qqtv9UP3mzy7HiGYNH/zjTA355mpeuA+859TyR+e+Tc08IHYpLJuMsfpDJwoLo1ikIJI8jC3GFjnRClzA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.0.tgz", + "integrity": "sha512-FLGfyizszcef5C3YtoyQDACyg95+dndv79i2EekILBofh5wpCa1KuBqOWKrEHZg3zrL3t5ouE5jgr94vA+Wb2w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/sunos-x64/-/sunos-x64-0.28.0.tgz", + "integrity": "sha512-1ZgjUoEdHZZl/YlV76TSCz9Hqj9h9YmMGAgAPYd+q4SicWNX3G5GCyx9uhQWSLcbvPW8Ni7lj4gDa1T40akdlw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/win32-arm64/-/win32-arm64-0.28.0.tgz", + "integrity": "sha512-Q9StnDmQ/enxnpxCCLSg0oo4+34B9TdXpuyPeTedN/6+iXBJ4J+zwfQI28u/Jl40nOYAxGoNi7mFP40RUtkmUA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/win32-ia32/-/win32-ia32-0.28.0.tgz", + "integrity": "sha512-zF3ag/gfiCe6U2iczcRzSYJKH1DCI+ByzSENHlM2FcDbEeo5Zd2C86Aq0tKUYAJJ1obRP84ymxIAksZUcdztHA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/win32-x64/-/win32-x64-0.28.0.tgz", + "integrity": "sha512-pEl1bO9mfAmIC+tW5btTmrKaujg3zGtUmWNdCw/xs70FBjwAL3o9OEKNHvNmnyylD6ubxUERiEhdsL0xBQ9efw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@hono/node-server": { + "version": "1.19.14", + "resolved": "https://repo.huaweicloud.com/repository/npm/@hono/node-server/-/node-server-1.19.14.tgz", + "integrity": "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==", + "license": "MIT", + "engines": { + "node": ">=18.14.1" + }, + "peerDependencies": { + "hono": "^4" + } + }, + "node_modules/@types/better-sqlite3": { + "version": "7.6.13", + "resolved": "https://repo.huaweicloud.com/repository/npm/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz", + "integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/node": { + "version": "22.19.20", + "resolved": "https://repo.huaweicloud.com/repository/npm/@types/node/-/node-22.19.20.tgz", + "integrity": "sha512-6tELRwSDYWW9EdZhbeZmYGZ1/7Djkt+Ah3/ScEYT9cDord7UJzasR/4D3VONg9tQI5CDp+/CZC1AXj2pCFOvpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/better-sqlite3": { + "version": "11.10.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/better-sqlite3/-/better-sqlite3-11.10.0.tgz", + "integrity": "sha512-EwhOpyXiOEL/lKzHz9AW1msWFNzGc/z+LzeB3/jnFJpxu+th2yqvzsSWas1v9jgs9+xiXJcD5A8CJxAG2TaghQ==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "bindings": "^1.5.0", + "prebuild-install": "^7.1.1" + } + }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "license": "MIT", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://repo.huaweicloud.com/repository/npm/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/esbuild": { + "version": "0.28.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/esbuild/-/esbuild-0.28.0.tgz", + "integrity": "sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.0", + "@esbuild/android-arm": "0.28.0", + "@esbuild/android-arm64": "0.28.0", + "@esbuild/android-x64": "0.28.0", + "@esbuild/darwin-arm64": "0.28.0", + "@esbuild/darwin-x64": "0.28.0", + "@esbuild/freebsd-arm64": "0.28.0", + "@esbuild/freebsd-x64": "0.28.0", + "@esbuild/linux-arm": "0.28.0", + "@esbuild/linux-arm64": "0.28.0", + "@esbuild/linux-ia32": "0.28.0", + "@esbuild/linux-loong64": "0.28.0", + "@esbuild/linux-mips64el": "0.28.0", + "@esbuild/linux-ppc64": "0.28.0", + "@esbuild/linux-riscv64": "0.28.0", + "@esbuild/linux-s390x": "0.28.0", + "@esbuild/linux-x64": "0.28.0", + "@esbuild/netbsd-arm64": "0.28.0", + "@esbuild/netbsd-x64": "0.28.0", + "@esbuild/openbsd-arm64": "0.28.0", + "@esbuild/openbsd-x64": "0.28.0", + "@esbuild/openharmony-arm64": "0.28.0", + "@esbuild/sunos-x64": "0.28.0", + "@esbuild/win32-arm64": "0.28.0", + "@esbuild/win32-ia32": "0.28.0", + "@esbuild/win32-x64": "0.28.0" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "license": "MIT" + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT" + }, + "node_modules/hono": { + "version": "4.12.23", + "resolved": "https://repo.huaweicloud.com/repository/npm/hono/-/hono-4.12.23.tgz", + "integrity": "sha512-eIaZ9qDgu7XV0pxOCrg7/WhnQ6Ivm22UcxhXx/A3dcbqbbYgBEkc6e/J/s7j2tS96zoB0S9VBdLwQNCWwUo4LA==", + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://repo.huaweicloud.com/repository/npm/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "license": "ISC" + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://repo.huaweicloud.com/repository/npm/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, + "node_modules/nan": { + "version": "2.27.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/nan/-/nan-2.27.0.tgz", + "integrity": "sha512-hC+0LidcL3XE4rp1C4H54KujgXKzbfyTngZTwBByQxsOxCEKZT0MPQ4hOKUH2jU1OYstqdDH4onyHPDzcV0XdQ==", + "license": "MIT" + }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT" + }, + "node_modules/node-abi": { + "version": "3.92.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/node-abi/-/node-abi-3.92.0.tgz", + "integrity": "sha512-KdHvFWZjEKDf0cakgFjebl371GPsISX2oZHcuyKqM7DtogIsHrqKeLTo8wBHxaXRAQlY2PsPlZmfo+9ZCxEREQ==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-snap7": { + "version": "1.0.9", + "resolved": "https://repo.huaweicloud.com/repository/npm/node-snap7/-/node-snap7-1.0.9.tgz", + "integrity": "sha512-U+9W8+XOs/4xKqYcn22yHESQzcSuKEhuN6pHLhyl1U5HuLm/kWxkXPzR2QwqFAs87aPfxdBrTI4xKDvwcMoyOw==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "bindings": "^1.5.0", + "nan": "^2.23.0", + "prebuild-install": "^7.1.2" + }, + "engines": { + "node": "16 || 18 || 20 || 22 || 24" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/pump": { + "version": "3.0.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://repo.huaweicloud.com/repository/npm/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/semver/-/semver-7.8.2.tgz", + "integrity": "sha512-c8jsqUZm3omBOI66G90z1Dyw5z622G8oLG+omfsHBJf3CWQTlOcwOjvOG6wtiNfW6anKm/eA39LMwMtMez2TiQ==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tar-fs": { + "version": "2.1.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/tar-fs/-/tar-fs-2.1.4.tgz", + "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tsx": { + "version": "4.22.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/tsx/-/tsx-4.22.4.tgz", + "integrity": "sha512-X8EX+XV4QR5xCsrgxaED954zTDfY8KqlDtskKEL0cHhyS/P8b4IFOvGDQpsC9Q1XnLq915wEfwwY/zzskCtmhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "~0.28.0" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + } + } +} diff --git a/project/package.json b/project/package.json new file mode 100644 index 0000000..7c875d0 --- /dev/null +++ b/project/package.json @@ -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" + } +} diff --git a/project/src/api/config.ts b/project/src/api/config.ts new file mode 100644 index 0000000..4d8bd01 --- /dev/null +++ b/project/src/api/config.ts @@ -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 diff --git a/project/src/api/monitor.ts b/project/src/api/monitor.ts new file mode 100644 index 0000000..4bffe7d --- /dev/null +++ b/project/src/api/monitor.ts @@ -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 diff --git a/project/src/api/query.ts b/project/src/api/query.ts new file mode 100644 index 0000000..5fc55f2 --- /dev/null +++ b/project/src/api/query.ts @@ -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 diff --git a/project/src/database/connection.ts b/project/src/database/connection.ts new file mode 100644 index 0000000..3763518 --- /dev/null +++ b/project/src/database/connection.ts @@ -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 + } +} diff --git a/project/src/database/init.ts b/project/src/database/init.ts new file mode 100644 index 0000000..d4f4a7f --- /dev/null +++ b/project/src/database/init.ts @@ -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() + 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() +} diff --git a/project/src/database/schema.ts b/project/src/database/schema.ts new file mode 100644 index 0000000..3d7685b --- /dev/null +++ b/project/src/database/schema.ts @@ -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 } diff --git a/project/src/index.ts b/project/src/index.ts new file mode 100644 index 0000000..8648b58 --- /dev/null +++ b/project/src/index.ts @@ -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 = { + '.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) +}) diff --git a/project/src/logger.ts b/project/src/logger.ts new file mode 100644 index 0000000..d1b8362 --- /dev/null +++ b/project/src/logger.ts @@ -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), +} diff --git a/project/src/plc/client.ts b/project/src/plc/client.ts new file mode 100644 index 0000000..96a7013 --- /dev/null +++ b/project/src/plc/client.ts @@ -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() + +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 +} diff --git a/project/src/plc/protocol.ts b/project/src/plc/protocol.ts new file mode 100644 index 0000000..3b3c00d --- /dev/null +++ b/project/src/plc/protocol.ts @@ -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) +} diff --git a/project/src/plc/scanner.ts b/project/src/plc/scanner.ts new file mode 100644 index 0000000..8818509 --- /dev/null +++ b/project/src/plc/scanner.ts @@ -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 | 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}`) + } + } + } +} diff --git a/project/src/services/collection.ts b/project/src/services/collection.ts new file mode 100644 index 0000000..3abb167 --- /dev/null +++ b/project/src/services/collection.ts @@ -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}`) + } +} diff --git a/project/src/services/interlock.ts b/project/src/services/interlock.ts new file mode 100644 index 0000000..bdf4845 --- /dev/null +++ b/project/src/services/interlock.ts @@ -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 } + } +} diff --git a/project/src/simulate.ts b/project/src/simulate.ts new file mode 100644 index 0000000..3d5c800 --- /dev/null +++ b/project/src/simulate.ts @@ -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() +} diff --git a/project/src/types.ts b/project/src/types.ts new file mode 100644 index 0000000..50d9ee8 --- /dev/null +++ b/project/src/types.ts @@ -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[] +} diff --git a/project/test/README-PLC.md b/project/test/README-PLC.md new file mode 100644 index 0000000..b3fb8ee --- /dev/null +++ b/project/test/README-PLC.md @@ -0,0 +1,45 @@ +# PLC 通信诊断说明 + +## 运行诊断 + +```bash +npm run test:plc -- [机架号] [槽号] +# 例: +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 diff --git a/project/test/plc-comm.ts b/project/test/plc-comm.ts new file mode 100644 index 0000000..b765b6f --- /dev/null +++ b/project/test/plc-comm.ts @@ -0,0 +1,163 @@ +/** + * PLC 通信诊断工具 + * 逐步骤测试 node-snap7 库的加载和连接,帮助定位 "TypeError: Wrong arguments" 错误 + * + * 用法: + * npx tsx test/plc-comm.ts [机架号] [槽号] + * 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 [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) +}) diff --git a/project/tsconfig.json b/project/tsconfig.json new file mode 100644 index 0000000..aeafae6 --- /dev/null +++ b/project/tsconfig.json @@ -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"] +} diff --git a/project/web/index.html b/project/web/index.html new file mode 100644 index 0000000..106d023 --- /dev/null +++ b/project/web/index.html @@ -0,0 +1,33 @@ + + + + + + 质量追溯系统 + + + + + +
+
+ + +
+
+
+ +
+
+
+
+ + + + diff --git a/project/web/package-lock.json b/project/web/package-lock.json new file mode 100644 index 0000000..bc653bf --- /dev/null +++ b/project/web/package-lock.json @@ -0,0 +1,1352 @@ +{ + "name": "scanner-record-web", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "scanner-record-web", + "version": "1.0.0", + "devDependencies": { + "autoprefixer": "^10.5.0", + "postcss": "^8.5.15", + "tailwindcss": "^4.3.0", + "typescript": "^5.7.0", + "vite": "^6.3.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.61.1.tgz", + "integrity": "sha512-JnBB8MdXj45cajvTuO5FmPlvFVJRQgvrz1uSEl3NwqFnReAPGwb8EanbGi4z2nRaqLzjJSv5/JmycoTKlRZxHA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.61.1.tgz", + "integrity": "sha512-Jx2g7iSjw4AOT0HDPHM9RV3GNjRXwybWtSFZiZAYUTjUwjVrYIwq3kBf+LnhqJlzXFAqTAh2F7IGI+O568exPw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.61.1.tgz", + "integrity": "sha512-0F1L/Z3Eqv8mT2n3dCpeO8GcTvHvVqkP5/t6DMsn0KzhYVcg+s7Ncl5DS8qjKYEeio6Az0Gt6nyBORay5qIlCA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.61.1.tgz", + "integrity": "sha512-qLttcH871ujY4YcVfUSShhOw+CsoTatYz8gRbHO7Bb92QH059/P0y5do1KMs41fY0BpD2x4AJH/gID0zFiqVKQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.61.1.tgz", + "integrity": "sha512-fUI4RapGE0Oh3mb8mgfvC1O2nU1RpDZUKnDQm3xB1Ipg7C2wTs5Kstz7G2uWK99a8S2yTMq8/P4uycwNa0nJyw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.61.1.tgz", + "integrity": "sha512-H5YrdvJaDtI/U9/emrD4b++xkvp3y/JvOe4rizHbxvkyMfRS/CiRYdji+Pl8D0brEaNFWUh1drQxgAGIl6Xudw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.61.1.tgz", + "integrity": "sha512-Q8CBCCQtDFrYtXoeUXSrnFXKOnyUhx6bz+SkL6A0E7V8kAiCJ5pamq1WtbfpVGhR5TSpXY6ak3avmDc5fHTyJA==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.61.1.tgz", + "integrity": "sha512-nwnhk1581l0FBVellGcVCAT0Oi06onEA3WB53sf01VO3I0UPBkMH9sXONYME2K0ovXcNayJfNtHfm6mpJElatQ==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.61.1.tgz", + "integrity": "sha512-x5Xr49hwt3hdW75UOZm3395YwwzPyauktslv29KpWL/T+vVAzoT3azLcTWv0eMciBNrx+DYjH4paehHoLpPvpg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.61.1.tgz", + "integrity": "sha512-unMS3H73DpaoPyyEVPjGKleM/s0mkmsauTENpw4INQY8y4+IuLNjkueQ5QCtC0D3N38Y38yhAU8OoZ20S2Tm6w==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.61.1.tgz", + "integrity": "sha512-zNZzGRnAhwjFEYmvphJRV5XaQGjs62cCmeYYHUT//NbvEnHauw+I85nGG+SiVg5ld4GX8D1IbKIX+ozITQnhMQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.61.1.tgz", + "integrity": "sha512-LdpWGL8X209B2SIvWjqlc8VZgM6PKfontSerGepuldQmHYrAOtnMCXeJkxXGbC+PPZVOuu5czJo7fNV6aeW8rQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.61.1.tgz", + "integrity": "sha512-EC5kTtNaNGOmbMGqar8dvJy6y/hg99GAwjfBz++pxZhQATXGcRjd6c5en5wcbru0vkRmiMGsQKdMJOOf6sza4g==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.61.1.tgz", + "integrity": "sha512-8hiwp6D4acEcNK78I4rP0/XtS1sknWIAMJBPdR4l6zUtyTm5KiTDr5bXmWt4foY7nAN7AThDHgkLIEZOWKbzWw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.61.1.tgz", + "integrity": "sha512-10dh/h/BqA7DuMPWSxkR8uks18FRwnwOEqr5zOTEl+NOwP/OMzKX8OFR/Of9xxDA7D5qef1Nzar5WDD2kCCr1g==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.61.1.tgz", + "integrity": "sha512-YKJ5lg35DP17gcAOggnihe+APw9HLyj1Xn7gsmGumBJAUDa6NGXNixJzmkWLhcK9TOuuyQjdamzvJefkO7qHZQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.61.1.tgz", + "integrity": "sha512-Mlil5G2Jj6a7B3LWGctg+XPL9vdXYuzCtNXfxOQ0nPjc2m6ueUktocPGH9bnAM0bNRKb/bAWTujUU7IJQdQA+g==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.61.1.tgz", + "integrity": "sha512-bVWIOIk6pV01p4CdUbPP7CJ/434z+OooYjDuFcR+44N35YvKUC66G8MGnvcWx5mWKW3g61J+t74l3Kj15Kwn2Q==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.61.1.tgz", + "integrity": "sha512-qy5pBvZbqNFheBz61R1rzsezjm0J7O2oNGoWtGoY89SZYLUfxAJTBAqDChqAIdB4rCiIbi9nF7yZ83GnNiLwSw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.61.1.tgz", + "integrity": "sha512-E83TXjI4zm0+5f2qO+UOudaCYIhYwpJ5jq6YCZNIZ+6CbfhKrkAGezeiASBL9ElxAxFsRS9ZhESv8mfnj6TKeg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.61.1.tgz", + "integrity": "sha512-fbWnKqVkjrJN38vNe3ahkbk6iejS/3b0Nt7EEtPpE6RBacZcGXNKbzfHN3GUUlXOPghUg0j6XUGrtjX9z1sIvA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.61.1.tgz", + "integrity": "sha512-ArMl38iVAbk0New1ogihQNY6iphLi4ZaRsa037gUzv5yeKPY8TD3Dmy4x2RNC1VztU/uqm+G+/RwFrSka3Oy2g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.61.1.tgz", + "integrity": "sha512-0mYtjHS9ucAbcATycCNK9IGBk/cCe/ma7EmSLGZdsxnOA8cjRIyU04wDpVAD9NiOfLUR9KTxdiO53uOkherqjQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.61.1.tgz", + "integrity": "sha512-gK1iCEPfpoSG9wfBihXxvBMi8ZfcWffYkEsC/Eih+iFENTaewvNcrEQ69lIOWYO5pePHKLHHO7nq5AILGO/HQQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.61.1.tgz", + "integrity": "sha512-X+zaP2x+j4RXGfbp/seSoRHWnPxzApilDszisZxbYH5C/jTxFhCtDNdPGZb9lJyYPs24wGxruPF7Y+sIXt9Gzw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://repo.huaweicloud.com/repository/npm/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/autoprefixer": { + "version": "10.5.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/autoprefixer/-/autoprefixer-10.5.0.tgz", + "integrity": "sha512-FMhOoZV4+qR6aTUALKX2rEqGG+oyATvwBt9IIzVR5rMa2HRWPkxf+P+PAJLD1I/H5/II+HuZcBJYEFBpq39ong==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/autoprefixer" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "browserslist": "^4.28.2", + "caniuse-lite": "^1.0.30001787", + "fraction.js": "^5.3.4", + "picocolors": "^1.1.1", + "postcss-value-parser": "^4.2.0" + }, + "bin": { + "autoprefixer": "bin/autoprefixer" + }, + "engines": { + "node": "^10 || ^12 || >=14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.10.34", + "resolved": "https://repo.huaweicloud.com/repository/npm/baseline-browser-mapping/-/baseline-browser-mapping-2.10.34.tgz", + "integrity": "sha512-IMDedajPifLnHNY0X9n8hKxRTQ6/eTHwr5bDo04WnuqxyKw6LYtQywCuuqPZwhl3aBXMvQpJov42GLCwRRdQzw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.28.2", + "resolved": "https://repo.huaweicloud.com/repository/npm/browserslist/-/browserslist-4.28.2.tgz", + "integrity": "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.10.12", + "caniuse-lite": "^1.0.30001782", + "electron-to-chromium": "^1.5.328", + "node-releases": "^2.0.36", + "update-browserslist-db": "^1.2.3" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001797", + "resolved": "https://repo.huaweicloud.com/repository/npm/caniuse-lite/-/caniuse-lite-1.0.30001797.tgz", + "integrity": "sha512-l8xKG+gwAIExZGl9FrF7KUwuOmk6wbEPC9Xoy/RtnWv1XG0Q4LFlagaLpUv3Kiza3W/wm27zy0yWJEieYKAP6w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/electron-to-chromium": { + "version": "1.5.368", + "resolved": "https://repo.huaweicloud.com/repository/npm/electron-to-chromium/-/electron-to-chromium-1.5.368.tgz", + "integrity": "sha512-7RckJJK4uESJF9PxvfMWd3TGqIiieUTG4HxnKaKuIpGbcr+r2ZEB3g2gAhCP3Fqm42vJSzLfgab9eva/C4/XVw==", + "dev": true, + "license": "ISC" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fraction.js": { + "version": "5.3.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/fraction.js/-/fraction.js-5.3.4.tgz", + "integrity": "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/rawify" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.12", + "resolved": "https://repo.huaweicloud.com/repository/npm/nanoid/-/nanoid-3.3.12.tgz", + "integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.47", + "resolved": "https://repo.huaweicloud.com/repository/npm/node-releases/-/node-releases-2.0.47.tgz", + "integrity": "sha512-Uzmd6LXpouKo8EUK68IjH4+E01w/hXyV3R3g/geCJo+rXLNfh1xucB+LOzYEOQPSiUK3h/xZf0cQGcSsmyL2Og==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://repo.huaweicloud.com/repository/npm/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.15", + "resolved": "https://repo.huaweicloud.com/repository/npm/postcss/-/postcss-8.5.15.tgz", + "integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.12", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/rollup": { + "version": "4.61.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/rollup/-/rollup-4.61.1.tgz", + "integrity": "sha512-I4KW6iuRpuu2uHBLraZ1wNZe0DP7lnRha+VJ9tNaYVaVgKhW0aI3h4RYnoRPeql0flHm/Co55b7snEDcOfOJrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.61.1", + "@rollup/rollup-android-arm64": "4.61.1", + "@rollup/rollup-darwin-arm64": "4.61.1", + "@rollup/rollup-darwin-x64": "4.61.1", + "@rollup/rollup-freebsd-arm64": "4.61.1", + "@rollup/rollup-freebsd-x64": "4.61.1", + "@rollup/rollup-linux-arm-gnueabihf": "4.61.1", + "@rollup/rollup-linux-arm-musleabihf": "4.61.1", + "@rollup/rollup-linux-arm64-gnu": "4.61.1", + "@rollup/rollup-linux-arm64-musl": "4.61.1", + "@rollup/rollup-linux-loong64-gnu": "4.61.1", + "@rollup/rollup-linux-loong64-musl": "4.61.1", + "@rollup/rollup-linux-ppc64-gnu": "4.61.1", + "@rollup/rollup-linux-ppc64-musl": "4.61.1", + "@rollup/rollup-linux-riscv64-gnu": "4.61.1", + "@rollup/rollup-linux-riscv64-musl": "4.61.1", + "@rollup/rollup-linux-s390x-gnu": "4.61.1", + "@rollup/rollup-linux-x64-gnu": "4.61.1", + "@rollup/rollup-linux-x64-musl": "4.61.1", + "@rollup/rollup-openbsd-x64": "4.61.1", + "@rollup/rollup-openharmony-arm64": "4.61.1", + "@rollup/rollup-win32-arm64-msvc": "4.61.1", + "@rollup/rollup-win32-ia32-msvc": "4.61.1", + "@rollup/rollup-win32-x64-gnu": "4.61.1", + "@rollup/rollup-win32-x64-msvc": "4.61.1", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://repo.huaweicloud.com/repository/npm/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tailwindcss": { + "version": "4.3.0", + "resolved": "https://repo.huaweicloud.com/repository/npm/tailwindcss/-/tailwindcss-4.3.0.tgz", + "integrity": "sha512-y6nxMGB1nMW9R6k96e5gdIFzcfL/gTJRNaqGes1YvkLnPVXzWgbqFF2yLC0T8G774n24cx3Pe8XrKoniCOAH+Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://repo.huaweicloud.com/repository/npm/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.2.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/vite": { + "version": "6.4.3", + "resolved": "https://repo.huaweicloud.com/repository/npm/vite/-/vite-6.4.3.tgz", + "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + } + } +} diff --git a/project/web/package.json b/project/web/package.json new file mode 100644 index 0000000..21ac1c7 --- /dev/null +++ b/project/web/package.json @@ -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" + } +} diff --git a/project/web/src/api/client.ts b/project/web/src/api/client.ts new file mode 100644 index 0000000..216e098 --- /dev/null +++ b/project/web/src/api/client.ts @@ -0,0 +1,56 @@ +const BASE = '/api' + +async function get(path: string): Promise { + const res = await fetch(`${BASE}${path}`) + if (!res.ok) throw new Error(`HTTP ${res.status}`) + return res.json() +} + +async function post(path: string, body: unknown): Promise { + 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(path: string, body: unknown): Promise { + 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 { + 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('/config/plcs'), + getMPs: () => get('/config/measurement-points'), + getStations: (plcId?: number) => get(`/config/stations${plcId ? `?plcId=${plcId}` : ''}`), + addPLC: (d: Partial) => post<{ Id: number }>('/config/plcs', d), + updatePLC: (id: number, d: Partial) => put(`/config/plcs/${id}`, d), + delPLC: (id: number) => del(`/config/plcs/${id}`), + addMP: (d: Partial) => post<{ Id: number }>('/config/measurement-points', d), + updateMP: (id: number, d: Partial) => put(`/config/measurement-points/${id}`, d), + delMP: (id: number) => del(`/config/measurement-points/${id}`), + addStation: (d: Partial) => post<{ Id: number }>('/config/stations', d), + updateStation: (id: number, d: Partial) => put(`/config/stations/${id}`, d), + delStation: (id: number) => del(`/config/stations/${id}`), + queryProduct: (pid: string) => get(`/query/${pid}`), + queryInterlock: (pid: string, sn: string) => get(`/query/${pid}/interlock/${encodeURIComponent(sn)}`), + getStatus: () => get('/monitor/status'), +} diff --git a/project/web/src/main.ts b/project/web/src/main.ts new file mode 100644 index 0000000..bfbc326 --- /dev/null +++ b/project/web/src/main.ts @@ -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 = '
查询中...
' + try { + const r = await api.queryProduct(pid) + qResult.innerHTML = '' + if (!r.data.length) { + qResult.innerHTML = `
${r.message || '暂无数据'}
` + return + } + for (const d of r.data) { + const ok = d.isQualified === 1, rw = d.inspectionCount > 1 + qResult.innerHTML += ` +
+
+ + ${d.pointName} + ${d.fieldUnit || ''} + ${d.recordTime} +
+
+
检测次数
${d.inspectionCount}${rw ? '(返修)' : ''}
+
合格判定
${ok ? '合格' : '不合格'}
+
实测值
${d.measuredValue ?? '-'}
+
+
+
上限
${d.upperLimit ?? '-'}
+
下限
${d.lowerLimit ?? '-'}
+
+
+
` + } + } catch (e: any) { + qResult.innerHTML = `
${e.message}
` + } +} +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 = `

检测点

+
+ + + + + ${mps.map(m => ` + + + + `).join('')} + + + + + + +
名称单位
+ + +
+
` + + 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 = `

PLC

+
+ + + + + ${plcs.map(p => ` + + + + + + + + `).join('')} + + + + + + + +
名称IPDB
+ + +
+ 工序: + ${stations.filter(s => s.PLCId === p.Id).map(s => `${s.StationName} `).join('')} +
+ + +
+
+
` + + 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() +}) + diff --git a/project/web/src/styles.css b/project/web/src/styles.css new file mode 100644 index 0000000..14ce20a --- /dev/null +++ b/project/web/src/styles.css @@ -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; } diff --git a/project/web/tsconfig.json b/project/web/tsconfig.json new file mode 100644 index 0000000..ed12acf --- /dev/null +++ b/project/web/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true + }, + "include": ["src"] +} diff --git a/project/web/vite.config.ts b/project/web/vite.config.ts new file mode 100644 index 0000000..e4dfb01 --- /dev/null +++ b/project/web/vite.config.ts @@ -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', + }, +}) diff --git a/query.py b/query.py new file mode 100644 index 0000000..669da9d --- /dev/null +++ b/query.py @@ -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) diff --git a/simulate.py b/simulate.py new file mode 100644 index 0000000..a25fcde --- /dev/null +++ b/simulate.py @@ -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) diff --git a/snap7.dll b/snap7.dll new file mode 100644 index 0000000..e1baafc Binary files /dev/null and b/snap7.dll differ diff --git a/test_snap7.py b/test_snap7.py new file mode 100644 index 0000000..b43f49b --- /dev/null +++ b/test_snap7.py @@ -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() \ No newline at end of file