init: PLC data collection system
This commit is contained in:
commit
ae90bc9368
38 files changed
+5234
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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 }
|
||||
@@ -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)
|
||||
})
|
||||
@@ -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),
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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}`)
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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[]
|
||||
}
|
||||
Reference in new issue
Block a user