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

+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}`)
}
}
}
}