init: PLC data collection system

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

No files matched your search

+1074
View File
File diff suppressed because it is too large. Load diff
+28
View File
@@ -0,0 +1,28 @@
{
"name": "scanner-record",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "tsx watch src/index.ts",
"start": "tsx src/index.ts",
"build": "tsc",
"build:web": "cd web && npm run build",
"db:init": "tsx src/database/init.ts",
"simulate": "tsx src/simulate.ts",
"test:e2e": "tsx src/database/init.ts && tsx src/simulate.ts",
"test:plc": "tsx test/plc-comm.ts"
},
"dependencies": {
"@hono/node-server": "^1.14.0",
"better-sqlite3": "^11.8.0",
"hono": "^4.7.0",
"node-snap7": "^1.0.9"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.12",
"@types/node": "^22.0.0",
"tsx": "^4.19.0",
"typescript": "^5.7.0"
}
}
+108
View File
@@ -0,0 +1,108 @@
import { Hono } from 'hono'
import { getDb } from '../database/connection.js'
import {
insertMeasurementPoint, updateMeasurementPoint, deleteMeasurementPoint,
insertPLC, updatePLC, deletePLC,
insertStation, updateStation, deleteStation,
createMPDataTable, dropMPDataTable,
} from '../database/schema.js'
const config = new Hono()
/* ===== GET ===== */
config.get('/plcs', (c) => {
const db = getDb()
return c.json(db.prepare('SELECT * FROM PLCs ORDER BY Id').all())
})
config.get('/plcs/:id', (c) => {
const db = getDb()
const plc = db.prepare('SELECT * FROM PLCs WHERE Id = ?').get(c.req.param('id'))
return plc ? c.json(plc) : c.json({ error: 'Not found' }, 404)
})
config.get('/stations', (c) => {
const db = getDb()
const plcId = c.req.query('plcId')
const sql = plcId
? `SELECT s.*, mp.PointName as pointName FROM Stations s JOIN MeasurementPoints mp ON mp.Id = s.PointId WHERE s.PLCId = ? ORDER BY s.Id`
: `SELECT s.*, mp.PointName as pointName FROM Stations s JOIN MeasurementPoints mp ON mp.Id = s.PointId ORDER BY s.Id`
const rows = plcId ? db.prepare(sql).all(plcId) : db.prepare(sql).all()
return c.json(rows)
})
config.get('/measurement-points', (c) => {
const db = getDb()
return c.json(db.prepare('SELECT * FROM MeasurementPoints ORDER BY Id').all())
})
/* ===== MeasurementPoints CRUD ===== */
config.post('/measurement-points', (c) => c.req.json().then(body => {
const id = insertMeasurementPoint(body.PointName, body.FieldUnit || '')
createMPDataTable(id, todayStr())
return c.json({ Id: id })
}))
config.put('/measurement-points/:id', (c) => c.req.json().then(body => {
updateMeasurementPoint(Number(c.req.param('id')), body.PointName, body.FieldUnit || '')
return c.json({ success: true })
}))
config.delete('/measurement-points/:id', (c) => {
const id = Number(c.req.param('id'))
dropMPDataTable(id, todayStr())
deleteMeasurementPoint(id)
return c.json({ success: true })
})
/* ===== PLCs CRUD ===== */
config.post('/plcs', (c) => c.req.json().then(body => {
const id = insertPLC(body.PLCName, body.IPAddress, body.DBNumber, body.StationCount || 0)
return c.json({ Id: id })
}))
config.put('/plcs/:id', (c) => c.req.json().then(body => {
updatePLC(Number(c.req.param('id')), body.PLCName, body.IPAddress, body.DBNumber, body.StationCount || 0)
return c.json({ success: true })
}))
config.delete('/plcs/:id', (c) => {
deletePLC(Number(c.req.param('id')))
return c.json({ success: true })
})
/* ===== Stations CRUD ===== */
config.post('/stations', (c) => c.req.json().then(body => {
const db = getDb()
let name = body.StationName
if (!name) {
const mp = db.prepare('SELECT PointName FROM MeasurementPoints WHERE Id=?').get(body.PointId) as any
name = mp?.PointName || ''
}
const id = insertStation(body.PLCId, body.StationIndex || 0, name, body.PointId)
return c.json({ Id: id })
}))
config.put('/stations/:id', (c) => c.req.json().then(body => {
updateStation(Number(c.req.param('id')), body.PLCId, body.StationIndex || 0, body.StationName, body.PointId)
return c.json({ success: true })
}))
config.delete('/stations/:id', (c) => {
deleteStation(Number(c.req.param('id')))
return c.json({ success: true })
})
function todayStr(): string {
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const dd = String(d.getDate()).padStart(2, '0')
return `${y}_${m}_${dd}`
}
export default config
+34
View File
@@ -0,0 +1,34 @@
import { Hono } from 'hono'
import { getDb } from '../database/connection.js'
const monitor = new Hono()
monitor.get('/status', (c) => {
const db = getDb()
const plcCount = (db.prepare('SELECT COUNT(*) as c FROM PLCs').get() as any).c
const stationCount = (db.prepare('SELECT COUNT(*) as c FROM Stations').get() as any).c
const pointCount = (db.prepare('SELECT COUNT(*) as c FROM MeasurementPoints').get() as any).c
const tables = db.prepare(
"SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'MPData_%' ORDER BY name"
).all() as any[]
let totalRows = 0
for (const t of tables) {
try {
const r = db.prepare(`SELECT COUNT(*) as c FROM ${t.name}`).get() as any
totalRows += r.c
} catch { /* skip */ }
}
return c.json({
plcCount,
stationCount,
pointCount,
dataTableCount: tables.length,
totalRecords: totalRows,
})
})
export default monitor
+104
View File
@@ -0,0 +1,104 @@
import { Hono } from 'hono'
import { getDb } from '../database/connection.js'
import { getAllStations, getMPRecord } from '../database/schema.js'
const query = new Hono()
function todayDateStr(): string {
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${y}_${m}_${day}`
}
query.get('/:productId', (c) => {
const productId = c.req.param('productId')
const dateStr = c.req.query('date') || todayDateStr()
const db = getDb()
const points = db.prepare('SELECT Id, PointName, FieldUnit FROM MeasurementPoints ORDER BY Id').all() as any[]
const result: any[] = []
for (const p of points) {
const table = `MPData_P${p.Id}_${dateStr}`
const tableExists = db.prepare(
"SELECT name FROM sqlite_master WHERE type='table' AND name=?"
).get(table)
if (!tableExists) continue
const row = db.prepare(`
SELECT RecordTime as recordTime, IsQualified as isQualified,
InspectionCount as inspectionCount,
UpperLimit as upperLimit, LowerLimit as lowerLimit,
MeasuredValue as measuredValue
FROM ${table} WHERE ProductID = ?
`).get(productId) as any
if (row) {
result.push({
pointId: p.Id,
pointName: p.PointName,
fieldUnit: p.FieldUnit,
...row,
})
}
}
if (result.length === 0) {
return c.json({ productId, data: [], message: '该产品暂无数据记录' })
}
return c.json({ productId, data: result })
})
query.get('/:productId/interlock/:stationName', (c) => {
const productId = c.req.param('productId')
const stationName = c.req.param('stationName')
const dateStr = c.req.query('date') || todayDateStr()
const stations = getAllStations()
const names = stations.map(s => s.stationName)
const idx = names.indexOf(stationName)
if (idx === -1) {
return c.json({ error: `未找到工序: ${stationName}`, available: names }, 404)
}
const current = stations[idx]
if (idx === 0) {
return c.json({
currentStation: current.stationName,
currentPoint: current.pointName,
prevStation: null,
prevResult: 1,
message: '当前为产线首个工序,视为合格',
})
}
const prev = stations[idx - 1]
const record = getMPRecord(dateStr, prev.pointId, productId)
if (!record) {
return c.json({
currentStation: current.stationName,
currentPoint: current.pointName,
prevStation: prev.stationName,
prevPoint: prev.pointName,
prevResult: 0,
message: '前工序尚未检测此产品,视为不合格',
})
}
return c.json({
currentStation: current.stationName,
currentPoint: current.pointName,
prevStation: prev.stationName,
prevPoint: prev.pointName,
prevResult: record.isQualified,
prevData: record,
})
})
export default query
+24
View File
@@ -0,0 +1,24 @@
import Database from 'better-sqlite3'
import path from 'path'
import { fileURLToPath } from 'url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const DB_PATH = path.resolve(__dirname, '../../data/production.db')
let db: Database.Database | null = null
export function getDb(): Database.Database {
if (!db) {
db = new Database(DB_PATH)
db.pragma('journal_mode = WAL')
db.pragma('foreign_keys = ON')
}
return db
}
export function closeDb(): void {
if (db) {
db.close()
db = null
}
}
+91
View File
@@ -0,0 +1,91 @@
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import { getDb, closeDb } from './connection.js'
import { createConfigTables, clearConfigData, createMPDataTable } from './schema.js'
import { logger } from '../logger.js'
import type { Config } from '../types.js'
const TAG = 'DBInit'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const CONFIG_PATH = path.resolve(__dirname, '../../config.json')
function todayDateStr(): string {
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${y}_${m}_${day}`
}
function readConfig(): Config {
if (!fs.existsSync(CONFIG_PATH)) {
logger.error(TAG, `配置文件不存在: ${CONFIG_PATH}`)
process.exit(1)
}
const raw = fs.readFileSync(CONFIG_PATH, 'utf-8')
return JSON.parse(raw) as Config
}
export function initFromConfig(configPath?: string, dateStr?: string): void {
const cfg = configPath ? (() => {
const p = path.resolve(configPath)
if (!fs.existsSync(p)) { logger.error(TAG, `文件不存在: ${p}`); process.exit(1) }
return JSON.parse(fs.readFileSync(p, 'utf-8')) as Config
})() : readConfig()
const ds = dateStr || todayDateStr()
const db = getDb()
logger.info(TAG, '创建配置表...')
createConfigTables()
logger.info(TAG, '清空旧配置数据...')
clearConfigData()
logger.info(TAG, '写入全局检测点...')
const insertMP = db.prepare(
'INSERT INTO MeasurementPoints (PointName, FieldUnit) VALUES (?, ?)'
)
const pointNameMap = new Map<string, number>()
for (const mp of cfg.measurement_points) {
const result = insertMP.run(mp.point_name, mp.field_unit ?? '')
pointNameMap.set(mp.point_name, Number(result.lastInsertRowid))
}
logger.info(TAG, '写入 PLC 和工序配置...')
const insertPLC = db.prepare(
'INSERT INTO PLCs (PLCName, IPAddress, DBNumber, StationCount) VALUES (?, ?, ?, ?)'
)
const insertStation = db.prepare(
'INSERT INTO Stations (PLCId, StationIndex, StationName, PointId) VALUES (?, ?, ?, ?)'
)
for (const plc of cfg.plcs) {
const plcResult = insertPLC.run(plc.plc_name, plc.ip_address, plc.db_number, plc.station_count)
const plcId = Number(plcResult.lastInsertRowid)
for (const st of plc.stations) {
const pointId = pointNameMap.get(st.point_name)
if (pointId === undefined) {
logger.warn(TAG, `检测点 '${st.point_name}' 未定义,跳过`)
continue
}
insertStation.run(plcId, st.station_index, st.station_name, pointId)
}
}
logger.info(TAG, '创建检测点数据表...')
for (const [pointName, pointId] of pointNameMap) {
createMPDataTable(pointId, ds)
}
logger.info(TAG, '数据库已初始化')
}
// 直接运行时
if (process.argv[1] && (process.argv[1].endsWith('init.ts') || process.argv[1].endsWith('/init.js'))) {
initFromConfig(process.argv[2], process.argv[3])
closeDb()
}
+205
View File
@@ -0,0 +1,205 @@
import Database from 'better-sqlite3'
import { getDb } from './connection.js'
import { logger } from '../logger.js'
const TAG = 'Schema'
export function createConfigTables(): void {
const db = getDb()
db.exec(`
CREATE TABLE IF NOT EXISTS MeasurementPoints (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
PointName TEXT NOT NULL,
FieldUnit TEXT DEFAULT ''
);
CREATE TABLE IF NOT EXISTS PLCs (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
PLCName TEXT NOT NULL,
IPAddress TEXT NOT NULL,
DBNumber INTEGER NOT NULL,
StationCount INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS Stations (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
PLCId INTEGER NOT NULL REFERENCES PLCs(Id),
StationIndex INTEGER NOT NULL,
StationName TEXT NOT NULL,
PointId INTEGER REFERENCES MeasurementPoints(Id)
);
`)
}
export function clearConfigData(): void {
const db = getDb()
db.exec(`
DELETE FROM Stations;
DELETE FROM MeasurementPoints;
DELETE FROM PLCs;
`)
}
export function createMPDataTable(pointId: number, dateStr: string): void {
const db = getDb()
const table = `MPData_P${pointId}_${dateStr}`
db.exec(`
CREATE TABLE IF NOT EXISTS ${table} (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
ProductID TEXT NOT NULL UNIQUE,
RecordTime DATETIME,
IsQualified INTEGER,
InspectionCount INTEGER DEFAULT 0,
UpperLimit REAL,
LowerLimit REAL,
MeasuredValue REAL
);
`)
logger.info(TAG, `${table} 已创建`)
}
export function dropMPDataTable(pointId: number, dateStr: string): void {
const db = getDb()
const table = `MPData_P${pointId}_${dateStr}`
db.exec(`DROP TABLE IF EXISTS ${table};`)
}
export function getAllMeasurementPoints(): { id: number; pointName: string; fieldUnit: string }[] {
const db = getDb()
return db.prepare('SELECT Id as id, PointName as pointName, FieldUnit as fieldUnit FROM MeasurementPoints ORDER BY Id').all() as any[]
}
export function getAllPLCs(): any[] {
const db = getDb()
return db.prepare('SELECT * FROM PLCs ORDER BY Id').all()
}
export function getStationsByPLC(plcId: number): any[] {
const db = getDb()
return db.prepare('SELECT * FROM Stations WHERE PLCId = ? ORDER BY Id').all(plcId)
}
export function getAllStations(): {
id: number
stationName: string
pointId: number
pointName: string
}[] {
const db = getDb()
return db.prepare(`
SELECT s.Id as id, s.StationName as stationName,
s.PointId as pointId, mp.PointName as pointName
FROM Stations s
JOIN MeasurementPoints mp ON mp.Id = s.PointId
ORDER BY s.Id
`).all() as any[]
}
export function getMPRecord(dateStr: string, pointId: number, productId: string): {
recordTime: string
isQualified: number
inspectionCount: number
measuredValue: number
} | null {
const db = getDb()
const table = `MPData_P${pointId}_${dateStr}`
const row = db.prepare(`
SELECT RecordTime as recordTime, IsQualified as isQualified,
InspectionCount as inspectionCount, MeasuredValue as measuredValue
FROM ${table}
WHERE ProductID = ?
`).get(productId) as any
return row || null
}
export function getAllMPRecords(dateStr: string, pointId: number, productId: string): any[] {
const db = getDb()
const table = `MPData_P${pointId}_${dateStr}`
try {
return db.prepare(`SELECT * FROM ${table} WHERE ProductID = ?`).all(productId) as any[]
} catch {
return []
}
}
/* ===== CRUD: MeasurementPoints ===== */
export function insertMeasurementPoint(name: string, unit: string): number {
const db = getDb()
const r = db.prepare('INSERT INTO MeasurementPoints (PointName, FieldUnit) VALUES (?, ?)').run(name, unit)
return Number(r.lastInsertRowid)
}
export function updateMeasurementPoint(id: number, name: string, unit: string): void {
const db = getDb()
db.prepare('UPDATE MeasurementPoints SET PointName=?, FieldUnit=? WHERE Id=?').run(name, unit, id)
}
export function deleteMeasurementPoint(id: number): void {
const db = getDb()
db.prepare('DELETE FROM Stations WHERE PointId=?').run(id)
db.prepare('DELETE FROM MeasurementPoints WHERE Id=?').run(id)
}
/* ===== CRUD: PLCs ===== */
export function insertPLC(name: string, ip: string, dbNum: number, stationCount: number): number {
const db = getDb()
const r = db.prepare('INSERT INTO PLCs (PLCName, IPAddress, DBNumber, StationCount) VALUES (?, ?, ?, ?)').run(name, ip, dbNum, stationCount)
return Number(r.lastInsertRowid)
}
export function updatePLC(id: number, name: string, ip: string, dbNum: number, stationCount: number): void {
const db = getDb()
db.prepare('UPDATE PLCs SET PLCName=?, IPAddress=?, DBNumber=?, StationCount=? WHERE Id=?').run(name, ip, dbNum, stationCount, id)
}
export function deletePLC(id: number): void {
const db = getDb()
db.prepare('DELETE FROM Stations WHERE PLCId=?').run(id)
db.prepare('DELETE FROM PLCs WHERE Id=?').run(id)
}
/* ===== CRUD: Stations ===== */
export function insertStation(plcId: number, stationIndex: number, name: string, pointId: number): number {
const db = getDb()
const r = db.prepare('INSERT INTO Stations (PLCId, StationIndex, StationName, PointId) VALUES (?, ?, ?, ?)').run(plcId, stationIndex, name, pointId)
return Number(r.lastInsertRowid)
}
export function updateStation(id: number, plcId: number, stationIndex: number, name: string, pointId: number): void {
const db = getDb()
db.prepare('UPDATE Stations SET PLCId=?, StationIndex=?, StationName=?, PointId=? WHERE Id=?').run(plcId, stationIndex, name, pointId, id)
}
export function deleteStation(id: number): void {
const db = getDb()
db.prepare('DELETE FROM Stations WHERE Id=?').run(id)
}
export function ensureDatabase(): void {
const db = getDb()
createConfigTables()
const count = (db.prepare('SELECT COUNT(*) as c FROM MeasurementPoints').get() as any).c
if (count === 0) {
logger.info(TAG, '数据库为空,请通过前端配置')
}
const points = db.prepare('SELECT Id FROM MeasurementPoints').all() as any[]
const dateStr = todayStr()
for (const p of points) {
createMPDataTable(p.Id, dateStr)
}
}
function todayStr(): string {
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const dd = String(d.getDate()).padStart(2, '0')
return `${y}_${m}_${dd}`
}
export { todayStr as getTodayStr }
+95
View File
@@ -0,0 +1,95 @@
import { serve } from '@hono/node-server'
import { Hono } from 'hono'
import { logger } from './logger.js'
import configApi from './api/config.js'
import queryApi from './api/query.js'
import monitorApi from './api/monitor.js'
import { ensureDatabase } from './database/schema.js'
import * as scanner from './plc/scanner.js'
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
const WEB_ROOT = (() => {
const candidates = [
path.resolve(process.cwd(), 'web/dist'),
path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../web/dist'),
]
for (const p of candidates) {
if (fs.existsSync(p)) return p
}
return candidates[0]
})()
logger.info('Server', `前端目录: ${WEB_ROOT}`)
const app = new Hono()
app.route('/api/config', configApi)
app.route('/api/query', queryApi)
app.route('/api/monitor', monitorApi)
app.get('/api/scanner/status', (c) => {
return c.json({ running: scanner.isRunning() })
})
app.get('/', (c) => c.redirect('/web/'))
// 手动处理前端静态文件
const MIME: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.json': 'application/json',
'.png': 'image/png',
'.svg': 'image/svg+xml',
}
app.get('/web/*', (c) => {
const reqPath = c.req.path.replace(/^\/web\//, '') || 'index.html'
const filePath = path.resolve(WEB_ROOT, reqPath)
if (!filePath.startsWith(WEB_ROOT)) {
return c.text('Forbidden', 403)
}
if (!fs.existsSync(filePath)) {
return c.text('404 Not Found', 404)
}
const ext = path.extname(filePath)
const content = fs.readFileSync(filePath)
return c.newResponse(content, 200, { 'Content-Type': MIME[ext] || 'application/octet-stream' })
})
const PORT = parseInt(process.env.PORT || '3000', 10)
serve({
fetch: app.fetch,
port: PORT,
}, (info) => {
logger.info('Server', `http://localhost:${PORT}`)
})
try {
ensureDatabase()
const skipPlc = process.env.SKIP_PLC === '1'
if (!skipPlc) {
scanner.start()
} else {
logger.info('Server', 'SKIP_PLC=1,跳过 PLC 连接')
}
} catch (err) {
logger.error('Server', '初始化失败', err)
}
process.on('SIGINT', () => {
scanner.stop()
process.exit(0)
})
process.on('SIGTERM', () => {
scanner.stop()
process.exit(0)
})
+52
View File
@@ -0,0 +1,52 @@
export enum LogLevel {
DEBUG = 0,
INFO = 1,
WARN = 2,
ERROR = 3,
}
const currentLevel = (() => {
const env = process.env.LOG_LEVEL
if (env !== undefined) {
const n = parseInt(env, 10)
if (!isNaN(n)) return n
}
return LogLevel.INFO
})()
function ts(): string {
const d = new Date()
const y = d.getFullYear()
const mo = String(d.getMonth() + 1).padStart(2, '0')
const dd = String(d.getDate()).padStart(2, '0')
const h = String(d.getHours()).padStart(2, '0')
const mi = String(d.getMinutes()).padStart(2, '0')
const s = String(d.getSeconds()).padStart(2, '0')
return `${y}-${mo}-${dd} ${h}:${mi}:${s}`
}
function log(level: LogLevel, tag: string, msg: string, ...args: any[]) {
if (level < currentLevel) return
const prefix = ['[D]', '[I]', '[W]', '[E]'][level]
const full = `${ts()} ${prefix} [${tag}] ${msg}`
if (args.length > 0) {
switch (level) {
case LogLevel.ERROR: console.error(full, ...args); break
case LogLevel.WARN: console.warn(full, ...args); break
default: console.log(full, ...args); break
}
} else {
switch (level) {
case LogLevel.ERROR: console.error(full); break
case LogLevel.WARN: console.warn(full); break
default: console.log(full); break
}
}
}
export const logger = {
debug: (tag: string, msg: string, ...args: any[]) => log(LogLevel.DEBUG, tag, msg, ...args),
info: (tag: string, msg: string, ...args: any[]) => log(LogLevel.INFO, tag, msg, ...args),
warn: (tag: string, msg: string, ...args: any[]) => log(LogLevel.WARN, tag, msg, ...args),
error: (tag: string, msg: string, ...args: any[]) => log(LogLevel.ERROR, tag, msg, ...args),
}
+170
View File
@@ -0,0 +1,170 @@
import { createRequire } from 'module'
const snap7 = createRequire(import.meta.url)('node-snap7')
import { STATION_SIZE, stationOffset, readDINT, readREAL, readWORD,
writeWORD, setControlBit, parseControlWord, CONTROL_BITS } from './protocol.js'
import { logger } from '../logger.js'
const TAG = 'PLC'
export interface PLCConfig {
id: number
plcName: string
ipAddress: string
dbNumber: number
stationCount: number
}
export interface StationData {
productID: number
upperLimit: number
lowerLimit: number
measuredValue: number
controlWord: number
dataReady: boolean
isQualified: boolean
prevResultReq: boolean
}
export interface ControlBits {
controlWord: number
dataReady: boolean
isQualified: boolean
prevResultReq: boolean
prevResult: boolean
}
const clients = new Map<number, any>()
function getS7Client(): any {
return new snap7.S7Client()
}
export function connectPLC(cfg: PLCConfig): boolean {
try {
const client = getS7Client()
const connected = client.ConnectTo(cfg.ipAddress, 0, 2)
if (connected === true) {
clients.set(cfg.id, client)
logger.info(TAG, `${cfg.plcName} (${cfg.ipAddress}) 已连接`)
return true
} else {
const errCode = client.LastError()
const errText = errCode === 0 ? '连接超时或无响应' : client.ErrorText(errCode)
logger.warn(TAG, `${cfg.plcName} (${cfg.ipAddress}) 连接失败: ${errText}`)
return false
}
} catch (err: any) {
logger.warn(TAG, `${cfg.plcName} (${cfg.ipAddress}) 连接异常: ${err.message}`)
return false
}
}
export function disconnectPLC(plcId: number): void {
const client = clients.get(plcId)
if (client) {
client.Disconnect()
clients.delete(plcId)
logger.info(TAG, `PLC#${plcId} 已断开`)
}
}
export function disconnectAll(): void {
for (const [, client] of clients) {
client.Disconnect()
}
clients.clear()
}
function readStationBlock(dbNumber: number, stationIndex: number, client: any): Buffer | null {
const offset = stationOffset(stationIndex)
const buf = Buffer.alloc(STATION_SIZE)
const result = client.DBRead(dbNumber, offset, STATION_SIZE, buf)
if (result === false) {
logger.warn(TAG, `DB${dbNumber} 读取工序 ${stationIndex} 失败: ${client.ErrorText(client.LastError())}`)
return null
}
return result instanceof Buffer ? result : buf
}
function writeStationControlWord(dbNumber: number, stationIndex: number, word: number, client: any): boolean {
const offset = stationOffset(stationIndex) + 16
const buf = Buffer.alloc(2)
writeWORD(buf, 0, word)
logger.info(TAG, `DBWrite DB${dbNumber}+${offset} = 0x${word.toString(16).padStart(4, '0')}`)
const result = client.DBWrite(dbNumber, offset, 2, buf)
if (result !== true) {
logger.warn(TAG, `DB${dbNumber} 写入工序 ${stationIndex} 控制字失败: ${client.ErrorText(client.LastError())}`)
return false
}
logger.info(TAG, `DB${dbNumber}+${offset} 写入成功`)
return true
}
export function readStationData(cfg: PLCConfig, stationIndex: number): StationData | null {
const client = clients.get(cfg.id)
if (!client) {
logger.warn(TAG, `${cfg.plcName} 未连接`)
return null
}
const buf = readStationBlock(cfg.dbNumber, stationIndex, client)
if (!buf) return null
const productID = readDINT(buf, 0)
const upperLimit = readREAL(buf, 4)
const lowerLimit = readREAL(buf, 8)
const measuredValue = readREAL(buf, 12)
const controlWord = readWORD(buf, 16)
const bits = parseControlWord(controlWord)
return {
productID,
upperLimit,
lowerLimit,
measuredValue,
controlWord,
dataReady: bits.dataReady,
isQualified: bits.isQualified,
prevResultReq: bits.prevResultReq,
}
}
export function readControlWord(cfg: PLCConfig, stationIndex: number): ControlBits | null {
const client = clients.get(cfg.id)
if (!client) return null
const offset = stationOffset(stationIndex) + 16
const buf = Buffer.alloc(2)
const result = client.DBRead(cfg.dbNumber, offset, 2, buf)
if (result === false) return null
const cw = readWORD(buf, 0)
const bits = parseControlWord(cw)
return { controlWord: cw, ...bits }
}
export function writePrevResult(cfg: PLCConfig, stationIndex: number, qualified: boolean): boolean {
const client = clients.get(cfg.id)
if (!client) return false
const buf = readStationBlock(cfg.dbNumber, stationIndex, client)
if (!buf) return false
let cw = readWORD(buf, 16)
cw = setControlBit(cw, CONTROL_BITS.PrevResult, qualified)
cw = setControlBit(cw, CONTROL_BITS.PrevResultReq, false)
return writeStationControlWord(cfg.dbNumber, stationIndex, cw, client)
}
export function clearDataReady(cfg: PLCConfig, stationIndex: number, controlWord: number): boolean {
const client = clients.get(cfg.id)
if (!client) return false
const newCw = setControlBit(controlWord, CONTROL_BITS.DataReady, false)
logger.info(TAG, `${cfg.plcName} 工序${stationIndex} clearDataReady: 0x${controlWord.toString(16).padStart(4, '0')} → 0x${newCw.toString(16).padStart(4, '0')}`)
return writeStationControlWord(cfg.dbNumber, stationIndex, newCw, client)
}
export function getConnectedCount(): number {
return clients.size
}
+78
View File
@@ -0,0 +1,78 @@
/** 每个工序固定 24 字节 */
export const STATION_SIZE = 24
/** 工序内各字段的相对偏移 */
export const OFFSET = {
ProductID: 0, // DINT, 4 bytes
UpperLimit: 4, // REAL, 4 bytes
LowerLimit: 8, // REAL, 4 bytes
MeasuredValue: 12, // REAL, 4 bytes
ControlWord: 16, // WORD, 2 bytes
} as const
/** ControlWord 位定义 */
export const CONTROL_BITS = {
DataReady: 0, // Bit 0: PLC→PC, 1=有新数据
IsQualified: 1, // Bit 1: PLC→PC, 1=合格
PrevResultReq: 2, // Bit 2: PLC→PC, 1=请求上一工序结果
PrevResult: 3, // Bit 3: PC→PLC, 1=上工序合格
} as const
/** 解析 ControlWord WORD → 各 bit */
export function parseControlWord(word: number): {
dataReady: boolean
isQualified: boolean
prevResultReq: boolean
prevResult: boolean
} {
return {
dataReady: !!(word & (1 << CONTROL_BITS.DataReady)),
isQualified: !!(word & (1 << CONTROL_BITS.IsQualified)),
prevResultReq: !!(word & (1 << CONTROL_BITS.PrevResultReq)),
prevResult: !!(word & (1 << CONTROL_BITS.PrevResult)),
}
}
/** 设置 ControlWord 的某个 bit 后返回新值 */
export function setControlBit(word: number, bit: number, value: boolean): number {
if (value) {
return word | (1 << bit)
} else {
return word & ~(1 << bit)
}
}
/** 工序 i 的起始字节偏移 */
export function stationOffset(i: number): number {
return i * STATION_SIZE
}
/** 读取 Buffer 中的 DINT (S7 DINT = signed 32-bit) */
export function readDINT(buf: Buffer, offset: number): number {
return buf.readInt32BE(offset)
}
/** 读取 Buffer 中的 REAL (S7 REAL = IEEE754 float, big-endian) */
export function readREAL(buf: Buffer, offset: number): number {
return buf.readFloatBE(offset)
}
/** 读取 Buffer 中的 WORD (16-bit unsigned) */
export function readWORD(buf: Buffer, offset: number): number {
return buf.readUInt16BE(offset)
}
/** 将 REAL 写入 Buffer (big-endian) */
export function writeREAL(buf: Buffer, offset: number, value: number): void {
buf.writeFloatBE(value, offset)
}
/** 将 WORD 写入 Buffer (big-endian) */
export function writeWORD(buf: Buffer, offset: number, value: number): void {
buf.writeUInt16BE(value, offset)
}
/** 将 DINT 写入 Buffer (big-endian) */
export function writeDINT(buf: Buffer, offset: number, value: number): void {
buf.writeInt32BE(value, offset)
}
+153
View File
@@ -0,0 +1,153 @@
import { getDb } from '../database/connection.js'
import { connectPLC, readStationData, readControlWord, clearDataReady,
writePrevResult, disconnectAll, type PLCConfig } from './client.js'
import { handleDataCollection } from '../services/collection.js'
import { handleInterlock } from '../services/interlock.js'
import { logger } from '../logger.js'
import { STATION_SIZE, OFFSET, CONTROL_BITS } from './protocol.js'
const TAG = 'Scanner'
const POLL_INTERVAL_MS = 1000
let timer: ReturnType<typeof setInterval> | null = null
let plcConfigs: PLCConfig[] = []
let running = false
function logConfig(): void {
const db = getDb()
const plcs = db.prepare(`
SELECT Id, PLCName, IPAddress, DBNumber FROM PLCs ORDER BY Id
`).all() as any[]
if (plcs.length === 0) {
logger.info(TAG, '无 PLC 配置')
return
}
const fieldMeta = [
{ name: 'ProductID', key: 'ProductID', offset: OFFSET.ProductID, type: 'DINT', size: 4, dir: '读' },
{ name: 'UpperLimit', key: 'UpperLimit', offset: OFFSET.UpperLimit, type: 'REAL', size: 4, dir: '读' },
{ name: 'LowerLimit', key: 'LowerLimit', offset: OFFSET.LowerLimit, type: 'REAL', size: 4, dir: '读' },
{ name: 'MeasuredValue', key: 'MeasuredValue', offset: OFFSET.MeasuredValue, type: 'REAL', size: 4, dir: '读' },
{ name: 'ControlWord', key: 'ControlWord', offset: OFFSET.ControlWord, type: 'WORD', size: 2, dir: '读写' },
]
const bits = [
{ bit: CONTROL_BITS.DataReady, name: 'DataReady', dir: 'PLC→PC ' },
{ bit: CONTROL_BITS.IsQualified, name: 'IsQualified', dir: 'PLC→PC ' },
{ bit: CONTROL_BITS.PrevResultReq, name: 'PrevResultReq', dir: 'PLC→PC ' },
{ bit: CONTROL_BITS.PrevResult, name: 'PrevResult', dir: 'PC →PLC ' },
]
logger.info(TAG, `── PLC 配置详情 (每工序 ${STATION_SIZE} 字节) ──────────────────────`)
for (const plc of plcs) {
logger.info(TAG, `${plc.PLCName} (${plc.IPAddress}) DB${plc.DBNumber}`)
const stations = db.prepare(`
SELECT s.StationIndex, s.StationName, mp.PointName
FROM Stations s
JOIN MeasurementPoints mp ON mp.Id = s.PointId
WHERE s.PLCId = ? ORDER BY s.Id
`).all(plc.Id) as any[]
if (stations.length === 0) {
logger.info(TAG, ` (无工序配置)`)
continue
}
for (const st of stations) {
const base = st.StationIndex * STATION_SIZE
logger.info(TAG, ` ${st.StationName} (${st.PointName}) idx=${st.StationIndex} 偏移 ${base}`)
for (const f of fieldMeta) {
const addr = `DB${plc.DBNumber}.DB${f.type === 'WORD' ? 'W' : 'D'}+${base + f.offset}`
logger.info(TAG, ` ${addr.padEnd(20)} ${f.name.padEnd(16)} ${f.type.padEnd(6)} ${String(f.size).padStart(2)} ${f.dir}`)
}
logger.info(TAG, ` ControlWord 位定义:`)
for (const b of bits) {
logger.info(TAG, ` Bit ${b.bit}: ${b.name.padEnd(18)} ${b.dir}`)
}
}
}
}
export function loadPLCConfigs(): void {
const db = getDb()
plcConfigs = db.prepare(`
SELECT Id as id, PLCName as plcName, IPAddress as ipAddress,
DBNumber as dbNumber, StationCount as stationCount
FROM PLCs ORDER BY Id
`).all() as PLCConfig[]
logger.info(TAG, `加载 ${plcConfigs.length} 台 PLC 配置`)
logConfig()
}
export function start(): void {
if (running) return
loadPLCConfigs()
if (plcConfigs.length === 0) {
logger.warn(TAG, '无 PLC 配置,跳过启动')
running = true
return
}
running = true
for (const plc of plcConfigs) {
connectPLC(plc)
}
logger.info(TAG, `开始轮询 ${plcConfigs.length} 台 PLC (间隔 ${POLL_INTERVAL_MS}ms)`)
timer = setInterval(pollCycle, POLL_INTERVAL_MS)
}
export function stop(): void {
if (timer) {
clearInterval(timer)
timer = null
}
disconnectAll()
running = false
logger.info(TAG, '已停止')
}
export function isRunning(): boolean {
return running
}
function pollCycle(): void {
const db = getDb()
for (const plc of plcConfigs) {
const stationIds = db.prepare(
'SELECT Id FROM Stations WHERE PLCId = ? ORDER BY Id'
).all(plc.id) as { Id: number }[]
for (let idx = 0; idx < stationIds.length; idx++) {
const i = idx
try {
const data = readStationData(plc, i)
if (!data) continue
if (data.dataReady) {
logger.info(TAG, `${plc.plcName} 工序${i} DataReady=1, ProductID=${data.productID}, 开始采集`)
handleDataCollection(plc, i, data)
clearDataReady(plc, i, data.controlWord)
}
if (data.prevResultReq) {
const stRow = db.prepare('SELECT StationName FROM Stations WHERE Id=?').get(stationIds[idx].Id) as { StationName: string } | undefined
if (!stRow) continue
logger.info(TAG, `${stRow.StationName} PrevResultReq=1, ProductID=${data.productID}, 处理互锁`)
const result = handleInterlock(stRow.StationName, data.productID)
writePrevResult(plc, i, result.prevResult === 1)
}
} catch (err) {
logger.error(TAG, `PLC#${plc.id} 工序 ${i} 错误: ${err}`)
}
}
}
}
+60
View File
@@ -0,0 +1,60 @@
import { getDb } from '../database/connection.js'
import { logger } from '../logger.js'
import type { PLCConfig, StationData } from '../plc/client.js'
const TAG = '采集'
function todayDateStr(): string {
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${y}_${m}_${day}`
}
export function handleDataCollection(
plc: PLCConfig,
stationIndex: number,
data: StationData,
): void {
const db = getDb()
const dateStr = todayDateStr()
const station = db.prepare(`
SELECT s.Id, s.PointId, mp.PointName
FROM Stations s
JOIN MeasurementPoints mp ON mp.Id = s.PointId
WHERE s.PLCId = ? AND s.StationIndex = ?
`).get(plc.id, stationIndex) as { Id: number; PointId: number; PointName: string } | undefined
if (!station) {
logger.warn(TAG, `PLC#${plc.id} 工序索引 ${stationIndex} 未找到对应配置`)
return
}
const productIdStr = String(data.productID)
const table = `MPData_P${station.PointId}_${dateStr}`
const existing = db.prepare(`SELECT InspectionCount FROM ${table} WHERE ProductID = ?`).get(productIdStr) as { InspectionCount: number } | undefined
if (!existing) {
db.prepare(`
INSERT INTO ${table} (ProductID, RecordTime, IsQualified, InspectionCount,
UpperLimit, LowerLimit, MeasuredValue)
VALUES (?, datetime('now'), ?, 1, ?, ?, ?)
`).run(productIdStr, data.isQualified ? 1 : 0, data.upperLimit, data.lowerLimit, data.measuredValue)
logger.info(TAG, `${station.PointName} 产品 ${productIdStr}: 首次检测 ${data.measuredValue}`)
} else {
db.prepare(`
UPDATE ${table}
SET RecordTime = datetime('now'),
IsQualified = ?,
InspectionCount = InspectionCount + 1,
UpperLimit = ?,
LowerLimit = ?,
MeasuredValue = ?
WHERE ProductID = ?
`).run(data.isQualified ? 1 : 0, data.upperLimit, data.lowerLimit, data.measuredValue, productIdStr)
logger.info(TAG, `${station.PointName} 产品 ${productIdStr}: 第${existing.InspectionCount + 1}次检测(返修) ${data.measuredValue}`)
}
}
+56
View File
@@ -0,0 +1,56 @@
import { getDb } from '../database/connection.js'
import { logger } from '../logger.js'
const TAG = '互锁'
function todayDateStr(): string {
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${y}_${m}_${day}`
}
export function handleInterlock(
stationName: string,
productId: number,
): { prevResult: number; prevStationName: string | null } {
const db = getDb()
const dateStr = todayDateStr()
const productIdStr = String(productId)
const allRows = db.prepare(`
SELECT s.StationName, s.PointId, mp.PointName
FROM Stations s
JOIN MeasurementPoints mp ON mp.Id = s.PointId
ORDER BY s.Id
`).all() as { StationName: string; PointId: number; PointName: string }[]
const currentIdx = allRows.findIndex(r => r.StationName === stationName)
if (currentIdx === -1) {
logger.warn(TAG, `工序 ${stationName} 未找到`)
return { prevResult: 0, prevStationName: null }
}
if (currentIdx === 0) {
logger.info(TAG, `${stationName} 是首工序,PrevResult=1`)
return { prevResult: 1, prevStationName: null }
}
const prev = allRows[currentIdx - 1]
const table = `MPData_P${prev.PointId}_${dateStr}`
try {
const row = db.prepare(`
SELECT IsQualified FROM ${table} WHERE ProductID = ?
`).get(productIdStr) as { IsQualified: number } | undefined
const result = row ? row.IsQualified : 0
logger.info(TAG, `${stationName} 查询 ${prev.StationName} → ${result ? '合格' : '不合格'}`)
return { prevResult: result, prevStationName: prev.StationName }
} catch {
logger.warn(TAG, `表 ${table} 不存在或查询失败`)
return { prevResult: 0, prevStationName: prev.StationName }
}
}
+73
View File
@@ -0,0 +1,73 @@
import { getDb, closeDb } from './database/connection.js'
import { getAllStations } from './database/schema.js'
import { logger } from './logger.js'
const TAG = 'Sim'
function todayDateStr(): string {
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${y}_${m}_${day}`
}
function rand(min: number, max: number): number {
return Math.round((Math.random() * (max - min) + min) * 10) / 10
}
export function simulate(dateStr?: string): void {
const ds = dateStr || todayDateStr()
const db = getDb()
const stations = getAllStations()
if (stations.length === 0) {
console.error('[ERROR] 无工序配置,请先运行 npm run db:init')
return
}
const products = Array.from({ length: 12 }, (_, i) => `PROD-${String(i + 1).padStart(3, '0')}`)
for (const pid of products) {
console.log(`\n>>> 产品 ${pid}`)
for (const st of stations) {
const table = `MPData_P${st.pointId}_${ds}`
const upper = rand(85, 115)
const lower = rand(65, 90)
const measured = rand(lower - 8, upper + 8)
const qualified = measured >= lower && measured <= upper ? 1 : 0
const existing = db.prepare(`SELECT InspectionCount FROM ${table} WHERE ProductID = ?`).get(pid) as { InspectionCount: number } | undefined
if (!existing) {
db.prepare(`
INSERT INTO ${table} (ProductID, RecordTime, IsQualified, InspectionCount,
UpperLimit, LowerLimit, MeasuredValue)
VALUES (?, datetime('now'), ?, 1, ?, ?, ?)
`).run(pid, qualified, upper, lower, measured)
const tag = qualified ? `${st.pointName}=${measured}` : `${st.pointName}=${measured}(不合格)`
console.log(` ${st.stationName} → 首次检测 ${tag}`)
if (!qualified) {
const measured2 = rand(lower, upper)
db.prepare(`
UPDATE ${table}
SET RecordTime = datetime('now'), IsQualified = 1, InspectionCount = 2,
UpperLimit = ?, LowerLimit = ?, MeasuredValue = ?
WHERE ProductID = ?
`).run(upper, lower, measured2, pid)
console.log(` └─ 返修, ${st.pointName}=${measured2} (合格)`)
}
}
}
}
console.log(`\n[DONE] 模拟完成,共 ${products.length} 个产品`)
}
if (process.argv[1]?.endsWith('simulate.ts') || process.argv[1]?.endsWith('/simulate.js')) {
simulate(process.argv[2])
closeDb()
}
+69
View File
@@ -0,0 +1,69 @@
export interface MeasurementPoint {
id: number
pointName: string
fieldUnit: string
sortOrder: number
}
export interface PLC {
id: number
plcName: string
ipAddress: string
dbNumber: number
stationCount: number
sortOrder: number
}
export interface Station {
id: number
plcId: number
stationIndex: number
stationName: string
pointId: number
sortOrder: number
}
export interface StationRow {
id: number
stationName: string
pointId: number
pointName: string
}
export interface MPRecord {
id: number
productID: string
recordTime: string
isQualified: number
inspectionCount: number
upperLimit: number | null
lowerLimit: number | null
measuredValue: number | null
}
export interface ConfigMeasurementPoint {
point_name: string
field_unit?: string
sort_order: number
}
export interface ConfigStation {
station_name: string
station_index: number
sort_order: number
point_name: string
}
export interface ConfigPLC {
plc_name: string
ip_address: string
db_number: number
station_count: number
sort_order: number
stations: ConfigStation[]
}
export interface Config {
measurement_points: ConfigMeasurementPoint[]
plcs: ConfigPLC[]
}
+45
View File
@@ -0,0 +1,45 @@
# PLC 通信诊断说明
## 运行诊断
```bash
npm run test:plc -- <IP地址> [机架号] [槽号]
# 例:
npm run test:plc -- 192.168.11.111 0 1
```
## 诊断输出说明
| 步骤 | 检查项目 | 成功标志 |
|------|---------|---------|
| 1 | node-snap7 模块加载 | `✓ module loaded` |
| 2 | S7Client 实例化 | `✓ S7Client 实例化成功` |
| 3 | ConnectTo 直连 | 返回码 0 = 成功 |
| 4 | SetConnectionParams + Connect 备选 | 同上 |
| 5 | 版本和绑定信息汇总 | — |
## 常见问题
### TypeError: Wrong arguments
`node-snap7` 的 C++ 绑定与当前 Node.js 版本 ABI 不兼容。
**已知兼容版本:** Node.js 18.x / 20.x / 22.x / 24.x
**不兼容:** Node.js >= 25
**解决方案 A — 降级 Node:**
```bash
nvm install 22
nvm use 22
npm rebuild node-snap7
```
**解决方案 B — 使用 koffi FFI(不限制 Node 版本):**
(开发中)
## 连接参数
- 西门子 S7-1200: rack=0, slot=1
- 西门子 S7-1500: rack=0, slot=1
- 西门子 S7-300: rack=0, slot=2
- 西门子 S7-400: rack=0, slot=3
+163
View File
@@ -0,0 +1,163 @@
/**
* PLC 通信诊断工具
* 逐步骤测试 node-snap7 库的加载和连接,帮助定位 "TypeError: Wrong arguments" 错误
*
* 用法:
* npx tsx test/plc-comm.ts <IP地址> [机架号] [槽号]
* npx tsx test/plc-comm.ts 192.168.11.111 0 1
*/
import { createRequire } from 'module'
const require = createRequire(import.meta.url)
const LOG = {
ok: (msg: string) => console.log(` ✓ ${msg}`),
fail: (msg: string, err?: unknown) => {
console.log(` ✗ ${msg}`)
if (err) console.error(` ${err}`)
},
info: (msg: string) => console.log(` · ${msg}`),
step: (n: number, msg: string) => console.log(`\n[步骤 ${n}] ${msg}`),
}
async function main() {
const ip = process.argv[2]
const rack = parseInt(process.argv[3] || '0', 10)
const slot = parseInt(process.argv[4] || '1', 10)
console.log(`\n${'='.repeat(50)}`)
console.log(` PLC 通信诊断工具`)
console.log(`${'='.repeat(50)}`)
console.log(` 目标 IP: ${ip || '(未指定)'}`)
console.log(` 机架 Rack: ${rack}`)
console.log(` 槽号 Slot: ${slot}`)
console.log(` Node 版本: ${process.version}`)
console.log(` 平台: ${process.platform} ${process.arch}`)
if (!ip) {
console.log(`\n 用法: npx tsx test/plc-comm.ts <IP> [rack] [slot]`)
console.log(` 示例: npx tsx test/plc-comm.ts 192.168.11.111 0 1\n`)
process.exit(1)
}
/* ===== 步骤 1: 加载 node-snap7 ===== */
LOG.step(1, '加载 node-snap7')
let snap7: any
try {
snap7 = require('node-snap7')
LOG.ok(`module loaded, keys: ${Object.keys(snap7).join(', ')}`)
} catch (err) {
LOG.fail('加载失败', err)
LOG.info('尝试: npm install node-snap7@1.0.9')
process.exit(1)
}
/* ===== 步骤 2: 检查 S7Client ===== */
LOG.step(2, '检查 S7Client 构造函数')
let client: any
try {
client = new snap7.S7Client()
LOG.ok('S7Client 实例化成功')
LOG.info(`client type: ${typeof client}`)
LOG.info(`methods: ${Object.getOwnPropertyNames(Object.getPrototypeOf(client)).slice(0, 15).join(', ')}`)
} catch (err) {
LOG.fail('S7Client 实例化失败', err)
process.exit(1)
}
/* ===== 步骤 3: 测试 ConnectTo ===== */
LOG.step(3, `测试 ConnectTo("${ip}", ${rack}, ${slot})`)
try {
const result = client.ConnectTo(ip, rack, slot)
const errText = client.ErrorText(result)
LOG.info(`ConnectTo 返回码: ${result}`)
LOG.info(`ErrorText: "${errText}"`)
if (result === 0) {
LOG.ok('连接成功!')
try {
const orderCode = client.GetOrderCode()
LOG.info(`PLC 订货号: ${orderCode}`)
} catch { /* ignore */ }
client.Disconnect()
LOG.ok('已断开连接')
} else {
LOG.fail(`连接返回非零: ${result} ("${errText}")`)
LOG.info('下一步将尝试 SetConnectionParams + Connect 备选方案')
}
} catch (err: any) {
LOG.fail(`ConnectTo 抛异常`, err)
LOG.info(`异常类型: ${err.constructor?.name}`)
LOG.info(`异常消息: ${err.message}`)
if (err.stack) {
console.log(` Stack (首行): ${err.stack.split('\n').slice(0, 2).join(' | ')}`)
}
}
/* ===== 步骤 4: 备选方案 SetConnectionParams + Connect ===== */
LOG.step(4, '测试备选方案: SetConnectionParams + Connect')
let altClient: any
try {
altClient = new snap7.S7Client()
} catch (err) {
LOG.fail('创建备选客户端失败', err)
process.exit(1)
}
try {
const localTSAP = 0x0100
const remoteTSAP = 0x0300 + rack * 0x0100 + slot
LOG.info(`SetConnectionParams("${ip}", ${localTSAP}, ${remoteTSAP})`)
const setResult = altClient.SetConnectionParams(ip, localTSAP, remoteTSAP)
LOG.info(`SetConnectionParams 返回: ${setResult}`)
if (setResult !== 0) {
LOG.fail(`SetConnectionParams 非零: ${setResult} ("${altClient.ErrorText(setResult)}")`)
} else {
LOG.info('Connect()...')
const connResult = altClient.Connect()
const connErr = altClient.ErrorText(connResult)
LOG.info(`Connect 返回: ${connResult} ("${connErr}")`)
if (connResult === 0) {
LOG.ok('备选方案连接成功!')
altClient.Disconnect()
} else {
LOG.fail(`备选方案连接失败: ${connResult} ("${connErr}")`)
}
}
} catch (err: any) {
LOG.fail('SetConnectionParams/Connect 抛异常', err)
LOG.info(`异常类型: ${err.constructor?.name}`)
LOG.info(`异常消息: ${err.message}`)
}
/* ===== 步骤 5: 库版本和诊断信息 ===== */
LOG.step(5, '诊断信息汇总')
try {
LOG.info(`snap7 版本: ${snap7.Snap7Version || 'N/A'}`)
} catch { /* ignore */ }
const nodeMajor = parseInt(process.version.slice(1).split('.')[0], 10)
if (nodeMajor >= 25) {
LOG.info(`Node.js v${nodeMajor} 较新,node-snap7 可能缺少预编译绑定`)
LOG.info(`解决方案: 参见 test/README-PLC.md`)
}
const bindingPath = require.resolve('node-snap7/build/Release/node_snap7.node')
LOG.info(`绑定文件: ${bindingPath}`)
console.log(`\n${'='.repeat(50)}`)
console.log(` 诊断完成`)
console.log(`${'='.repeat(50)}\n`)
// 退出码:成功连接为 0,否则为 1
process.exit(0)
}
main().catch(err => {
console.error('\n[致命错误]', err)
process.exit(1)
})
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"sourceMap": true
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}
+33
View File
@@ -0,0 +1,33 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>质量追溯系统</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 text-gray-800 min-h-screen">
<nav class="bg-indigo-900 text-white px-6 py-3 flex items-center gap-6 shadow-md">
<h1 class="text-lg font-bold tracking-wide">质量追溯系统</h1>
<div class="flex gap-1">
<button data-page="query" class="tab-btn active px-4 py-1.5 rounded-lg text-sm hover:bg-white/10 transition">追溯查询</button>
<button data-page="config" class="tab-btn px-4 py-1.5 rounded-lg text-sm hover:bg-white/10 transition">设备配置</button>
</div>
</nav>
<div id="page-query" class="page active max-w-3xl mx-auto p-6">
<div class="flex gap-2 mb-6">
<input id="q-input" type="text" placeholder="输入产品编号,如 PROD-003" class="flex-1 px-4 py-2.5 border border-gray-300 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400 focus:border-transparent" />
<button id="q-btn" class="px-6 py-2.5 bg-indigo-700 text-white rounded-xl text-sm font-medium hover:bg-indigo-800 transition">查询</button>
</div>
<div id="q-result"></div>
</div>
<div id="page-config" class="page max-w-5xl mx-auto p-6">
<div id="mp-list"></div>
<div class="mt-8" id="plc-list"></div>
</div>
<script type="module" src="./src/main.ts"></script>
</body>
</html>
+1352
View File
File diff suppressed because it is too large. Load diff
+18
View File
@@ -0,0 +1,18 @@
{
"name": "scanner-record-web",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"devDependencies": {
"autoprefixer": "^10.5.0",
"postcss": "^8.5.15",
"tailwindcss": "^4.3.0",
"typescript": "^5.7.0",
"vite": "^6.3.0"
}
}
+56
View File
@@ -0,0 +1,56 @@
const BASE = '/api'
async function get<T>(path: string): Promise<T> {
const res = await fetch(`${BASE}${path}`)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json()
}
async function post<T>(path: string, body: unknown): Promise<T> {
const res = await fetch(`${BASE}${path}`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json()
}
async function put<T>(path: string, body: unknown): Promise<T> {
const res = await fetch(`${BASE}${path}`, {
method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json()
}
async function del(path: string): Promise<void> {
const res = await fetch(`${BASE}${path}`, { method: 'DELETE' })
if (!res.ok) throw new Error(`HTTP ${res.status}`)
}
export interface PLC { Id: number; PLCName: string; IPAddress: string; DBNumber: number; StationCount: number; SortOrder: number }
export interface MP { Id: number; PointName: string; FieldUnit: string; SortOrder: number }
export interface Station { Id: number; PLCId: number; StationIndex: number; StationName: string; PointId: number; SortOrder: number; pointName?: string }
export interface QPoint { pointId: number; pointName: string; fieldUnit: string; recordTime: string; isQualified: number; inspectionCount: number; upperLimit: number | null; lowerLimit: number | null; measuredValue: number | null }
export interface QResult { productId: string; data: QPoint[]; message?: string }
export interface IResult { currentStation: string; currentPoint: string; prevStation: string | null; prevResult: number; message?: string }
export interface Status { plcCount: number; stationCount: number; pointCount: number; dataTableCount: number; totalRecords: number }
export const api = {
getPLCs: () => get<PLC[]>('/config/plcs'),
getMPs: () => get<MP[]>('/config/measurement-points'),
getStations: (plcId?: number) => get<Station[]>(`/config/stations${plcId ? `?plcId=${plcId}` : ''}`),
addPLC: (d: Partial<PLC>) => post<{ Id: number }>('/config/plcs', d),
updatePLC: (id: number, d: Partial<PLC>) => put(`/config/plcs/${id}`, d),
delPLC: (id: number) => del(`/config/plcs/${id}`),
addMP: (d: Partial<MP>) => post<{ Id: number }>('/config/measurement-points', d),
updateMP: (id: number, d: Partial<MP>) => put(`/config/measurement-points/${id}`, d),
delMP: (id: number) => del(`/config/measurement-points/${id}`),
addStation: (d: Partial<Station>) => post<{ Id: number }>('/config/stations', d),
updateStation: (id: number, d: Partial<Station>) => put(`/config/stations/${id}`, d),
delStation: (id: number) => del(`/config/stations/${id}`),
queryProduct: (pid: string) => get<QResult>(`/query/${pid}`),
queryInterlock: (pid: string, sn: string) => get<IResult>(`/query/${pid}/interlock/${encodeURIComponent(sn)}`),
getStatus: () => get<Status>('/monitor/status'),
}
+193
View File
@@ -0,0 +1,193 @@
import './styles.css'
import { api, type PLC, type MP, type Station } from './api/client.js'
/* ===== Navigation ===== */
const $ = (s: string) => document.querySelector(s)!
const $$ = (s: string) => document.querySelectorAll(s)
$$('.tab-btn').forEach(btn => btn.addEventListener('click', () => {
$$('.tab-btn').forEach(b => b.classList.remove('active'))
$$('.page').forEach(p => p.classList.remove('active'))
btn.classList.add('active')
document.getElementById(`page-${btn.dataset.page}`)!.classList.add('active')
}))
/* ===== Query Page ===== */
const qInput = $('#q-input') as HTMLInputElement
const qBtn = $('#q-btn') as HTMLButtonElement
const qResult = $('#q-result') as HTMLDivElement
async function doQuery() {
const pid = qInput.value.trim()
if (!pid) return
qResult.innerHTML = '<div class="text-gray-400 text-center py-8">查询中...</div>'
try {
const r = await api.queryProduct(pid)
qResult.innerHTML = ''
if (!r.data.length) {
qResult.innerHTML = `<div class="text-gray-400 text-center py-8">${r.message || '暂无数据'}</div>`
return
}
for (const d of r.data) {
const ok = d.isQualified === 1, rw = d.inspectionCount > 1
qResult.innerHTML += `
<div class="bg-white rounded-xl shadow-sm border border-gray-100 p-5 mb-3">
<div class="flex items-center gap-2 mb-3 pb-2 border-b border-gray-100">
<span class="w-2 h-2 rounded-full ${ok ? 'bg-green-500' : 'bg-red-500'}"></span>
<span class="font-semibold text-gray-800">${d.pointName}</span>
<span class="text-xs text-gray-400">${d.fieldUnit || ''}</span>
<span class="ml-auto text-xs text-gray-400">${d.recordTime}</span>
</div>
<div class="grid grid-cols-3 gap-4 text-sm">
<div><span class="text-gray-400">检测次数</span><br><span class="font-medium ${rw ? 'text-orange-600' : ''}">${d.inspectionCount}${rw ? '(返修)' : ''}</span></div>
<div><span class="text-gray-400">合格判定</span><br><span class="font-medium ${ok ? 'text-green-600' : 'text-red-600'}">${ok ? '合格' : '不合格'}</span></div>
<div><span class="text-gray-400">实测值</span><br><span class="font-medium">${d.measuredValue ?? '-'}</span></div>
</div>
<div class="grid grid-cols-3 gap-4 text-sm mt-2">
<div><span class="text-gray-400">上限</span><br><span>${d.upperLimit ?? '-'}</span></div>
<div><span class="text-gray-400">下限</span><br><span>${d.lowerLimit ?? '-'}</span></div>
<div></div>
</div>
</div>`
}
} catch (e: any) {
qResult.innerHTML = `<div class="text-red-500 text-center py-8">${e.message}</div>`
}
}
qBtn.addEventListener('click', doQuery)
qInput.addEventListener('keydown', e => { if (e.key === 'Enter') doQuery() })
/* ===== Config Page ===== */
let configLoaded = false
async function loadConfig() {
configLoaded = true
const [plcs, mps, stations] = await Promise.all([api.getPLCs(), api.getMPs(), api.getStations()])
renderMPTable(mps)
renderPLCTable(plcs, stations, mps)
}
function renderMPTable(mps: MP[]) {
const el = document.getElementById('mp-list')!
el.innerHTML = `<h3 class="text-lg font-semibold text-gray-800 mb-3">检测点</h3>
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead><tr class="bg-gray-50 text-gray-500">
<th class="text-left p-2">名称</th><th class="text-left p-2">单位</th><th class="p-2"></th>
</tr></thead><tbody>
${mps.map(m => `<tr class="border-t border-gray-100">
<td class="p-2"><input class="border rounded px-2 py-1 w-28 text-sm" value="${m.PointName}" data-mp-name="${m.Id}" /></td>
<td class="p-2"><input class="border rounded px-2 py-1 w-20 text-sm" value="${m.FieldUnit}" data-mp-unit="${m.Id}" /></td>
<td class="p-2 text-right">
<button class="text-indigo-600 hover:text-indigo-800 text-xs mr-2" data-mp-save="${m.Id}">保存</button>
<button class="text-red-500 hover:text-red-700 text-xs" data-mp-del="${m.Id}">删除</button>
</td>
</tr>`).join('')}
<tr class="border-t border-gray-100">
<td class="p-2"><input id="mp-new-name" class="border rounded px-2 py-1 w-28 text-sm" placeholder="名称" /></td>
<td class="p-2"><input id="mp-new-unit" class="border rounded px-2 py-1 w-20 text-sm" placeholder="单位" /></td>
<td class="p-2 text-right"><button id="mp-add" class="text-green-600 hover:text-green-800 text-xs">添加</button></td>
</tr>
</tbody>
</table>
</div>`
document.querySelectorAll('[data-mp-save]').forEach(b => b.addEventListener('click', () => {
const id = Number((b as HTMLElement).dataset.mpSave)
api.updateMP(id, {
PointName: (document.querySelector(`[data-mp-name="${id}"]`) as HTMLInputElement).value,
FieldUnit: (document.querySelector(`[data-mp-unit="${id}"]`) as HTMLInputElement).value,
}).then(() => loadConfig())
}))
document.querySelectorAll('[data-mp-del]').forEach(b => b.addEventListener('click', () => {
if (!confirm('删除检测点会同时删除关联的工序,确定?')) return
api.delMP(Number((b as HTMLElement).dataset.mpDel)).then(() => loadConfig())
}))
document.getElementById('mp-add')?.addEventListener('click', () => {
const name = (document.getElementById('mp-new-name') as HTMLInputElement).value
if (!name) return
api.addMP({
PointName: name,
FieldUnit: (document.getElementById('mp-new-unit') as HTMLInputElement).value,
}).then(() => loadConfig())
})
}
function renderPLCTable(plcs: PLC[], stations: Station[], mps: MP[]) {
const el = document.getElementById('plc-list')!
el.innerHTML = `<h3 class="text-lg font-semibold text-gray-800 mb-3">PLC</h3>
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead><tr class="bg-gray-50 text-gray-500">
<th class="text-left p-2">名称</th><th class="text-left p-2">IP</th><th class="text-left p-2">DB</th><th class="p-2"></th>
</tr></thead><tbody>
${plcs.map(p => `<tr class="border-t border-gray-100">
<td class="p-2"><input class="border rounded px-2 py-1 w-28 text-sm" value="${p.PLCName}" data-plc-name="${p.Id}" /></td>
<td class="p-2"><input class="border rounded px-2 py-1 w-32 text-sm" value="${p.IPAddress}" data-plc-ip="${p.Id}" /></td>
<td class="p-2"><input class="border rounded px-2 py-1 w-16 text-sm" type="number" value="${p.DBNumber}" data-plc-db="${p.Id}" /></td>
<td class="p-2 text-right">
<button class="text-indigo-600 hover:text-indigo-800 text-xs mr-2" data-plc-save="${p.Id}">保存</button>
<button class="text-red-500 hover:text-red-700 text-xs" data-plc-del="${p.Id}">删除</button>
</td>
</tr>
<tr class="bg-gray-50/50">
<td colspan="4" class="p-2 pl-8">
<span class="text-xs text-gray-400">工序: </span>
${stations.filter(s => s.PLCId === p.Id).map(s => `<span class="inline-block bg-white border rounded px-2 py-0.5 text-xs mr-1 mb-1">${s.StationName} <button class="text-red-400 hover:text-red-600 ml-1" data-sta-del="${s.Id}">×</button></span>`).join('')}
<div class="flex gap-1 items-center mt-1">
<select class="border rounded px-1 py-0.5 text-xs" data-sta-point="${p.Id}">
<option value="">选检测点</option>
${mps.map(m => `<option value="${m.Id}">${m.PointName}</option>`).join('')}
</select>
<button class="text-xs text-green-600 hover:text-green-700" data-sta-add="${p.Id}">添加</button>
</div>
</td>
</tr>`).join('')}
<tr class="border-t border-gray-100">
<td class="p-2"><input id="plc-new-name" class="border rounded px-2 py-1 w-28 text-sm" placeholder="名称" /></td>
<td class="p-2"><input id="plc-new-ip" class="border rounded px-2 py-1 w-32 text-sm" placeholder="IP" /></td>
<td class="p-2"><input id="plc-new-db" class="border rounded px-2 py-1 w-16 text-sm" type="number" placeholder="DB" /></td>
<td class="p-2 text-right"><button id="plc-add" class="text-green-600 hover:text-green-800 text-xs">添加</button></td>
</tr>
</tbody>
</table>
</div>`
document.querySelectorAll('[data-plc-save]').forEach(b => b.addEventListener('click', () => {
const id = Number((b as HTMLElement).dataset.plcSave)
api.updatePLC(id, {
PLCName: (document.querySelector(`[data-plc-name="${id}"]`) as HTMLInputElement).value,
IPAddress: (document.querySelector(`[data-plc-ip="${id}"]`) as HTMLInputElement).value,
DBNumber: Number((document.querySelector(`[data-plc-db="${id}"]`) as HTMLInputElement).value),
}).then(() => loadConfig())
}))
document.querySelectorAll('[data-plc-del]').forEach(b => b.addEventListener('click', () => {
if (!confirm('删除PLC会同时删除其工序,确定?')) return
api.delPLC(Number((b as HTMLElement).dataset.plcDel)).then(() => loadConfig())
}))
document.querySelectorAll('[data-sta-del]').forEach(b => b.addEventListener('click', () => {
api.delStation(Number((b as HTMLElement).dataset.staDel)).then(() => loadConfig())
}))
document.querySelectorAll('[data-sta-add]').forEach(b => b.addEventListener('click', async () => {
const plcId = Number((b as HTMLElement).dataset.staAdd)
const sel = document.querySelector(`[data-sta-point="${plcId}"]`) as HTMLSelectElement
const pointId = Number(sel.value)
if (!pointId) return
const pointName = sel.options[sel.selectedIndex]?.text || ''
api.addStation({ PLCId: plcId, StationName: pointName, PointId: pointId, StationIndex: 0, SortOrder: 0 }).then(() => loadConfig())
}))
document.getElementById('plc-add')?.addEventListener('click', () => {
const name = (document.getElementById('plc-new-name') as HTMLInputElement).value
if (!name) return
api.addPLC({
PLCName: name,
IPAddress: (document.getElementById('plc-new-ip') as HTMLInputElement).value,
DBNumber: Number((document.getElementById('plc-new-db') as HTMLInputElement).value),
}).then(() => loadConfig())
})
}
document.querySelector('[data-page="config"]')?.addEventListener('click', () => {
if (!configLoaded) loadConfig()
})
+3
View File
@@ -0,0 +1,3 @@
.page { display: none; }
.page.active { display: block; }
.tab-btn.active { background: rgba(255,255,255,0.2); color: #fff; font-weight: 600; }
+11
View File
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src"]
}
+17
View File
@@ -0,0 +1,17 @@
import { defineConfig } from 'vite'
export default defineConfig({
base: '/web/',
server: {
port: 5173,
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
},
},
},
build: {
outDir: 'dist',
},
})