feat: PLC failover state machine with TCP probe

This commit is contained in:
zlm committed 2026-06-10 09:54:23 +08:00
1 parent feaa4a027a
commit cf3d482646
3 files changed
+134 -35

No files matched your search

+9
View File
@@ -9,3 +9,12 @@ LOG_LEVEL=1
# 跳过 PLC 连接(开发时用)
# SKIP_PLC=1
# PLC 连续失败次数上限(超过后进入 TCP 探测模式)
PLC_FAIL_LIMIT=3
# TCP 探测间隔(毫秒,失败后多久检查一次端口)
PLC_PROBE_INTERVAL_MS=5000
# TCP 探测超时(毫秒,每次连接端口等待时间)
PLC_PROBE_TIMEOUT_MS=2000
+12
View File
@@ -1,4 +1,5 @@
import { createRequire } from 'module'
import net from 'net'
const snap7 = createRequire(import.meta.url)('node-snap7')
import { STATION_SIZE, stationOffset, readDINT, readREAL, readWORD,
writeWORD, setControlBit, parseControlWord, CONTROL_BITS } from './protocol.js'
@@ -184,3 +185,14 @@ export function clearDataReady(cfg: PLCConfig, stationIndex: number, controlWord
export function getConnectedCount(): number {
return clients.size
}
export function testTcpConnection(ip: string, timeoutMs: number): Promise<boolean> {
return new Promise(resolve => {
const sock = new net.Socket()
sock.setTimeout(timeoutMs)
sock.on('connect', () => { sock.destroy(); resolve(true) })
sock.on('error', () => { sock.destroy(); resolve(false) })
sock.on('timeout', () => { sock.destroy(); resolve(false) })
sock.connect(102, ip)
})
}
+113 -35
View File
@@ -1,6 +1,7 @@
import { getDb } from '../database/connection.js'
import { connectPLC, readAllStationsBlock, clearDataReady,
writePrevResult, disconnectAll, type PLCConfig } from './client.js'
writePrevResult, disconnectAll, testTcpConnection,
disconnectPLC, type PLCConfig } from './client.js'
import { handleDataCollection } from '../services/collection.js'
import { handleInterlock } from '../services/interlock.js'
import { logger } from '../logger.js'
@@ -8,33 +9,30 @@ import { STATION_SIZE, OFFSET,
readDINT, readREAL, readWORD, parseControlWord } from './protocol.js'
const TAG = 'Scanner'
const POLL_INTERVAL_MS = parseInt(process.env.POLL_INTERVAL_MS || '1000', 10)
const FAIL_LIMIT = parseInt(process.env.PLC_FAIL_LIMIT || '3', 10)
const PROBE_INTERVAL_MS = parseInt(process.env.PLC_PROBE_INTERVAL_MS || '5000', 10)
const PROBE_TIMEOUT_MS = parseInt(process.env.PLC_PROBE_TIMEOUT_MS || '2000', 10)
let timer: ReturnType<typeof setInterval> | null = null
let plcConfigs: PLCConfig[] = []
let plcStates: Map<number, { failCount: number; connected: boolean }> = new Map()
let running = false
let pollTimer: ReturnType<typeof setInterval> | null = null
let probeTimer: ReturnType<typeof setInterval> | null = null
/* ===== Config log ===== */
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 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 }
for (const plc of plcs) {
const stations = db.prepare(`
SELECT s.StationName, mp.PointName
FROM Stations s
JOIN MeasurementPoints mp ON mp.Id = s.PointId
SELECT s.StationName FROM Stations s
WHERE s.PLCId = ? ORDER BY s.Id
`).all(plc.Id) as any[]
const names = stations.map((s: any) => s.StationName).join(', ')
logger.info(TAG, `${plc.PLCName} DB${plc.DBNumber} → ${names || '(无工序)'}`)
logger.info(TAG, `${plc.PLCName} DB${plc.DBNumber} → ${stations.map((s: any) => s.StationName).join(', ') || '(无工序)'}`)
}
}
@@ -49,52 +47,132 @@ export function loadPLCConfigs(): void {
logConfig()
}
/* ===== State management ===== */
function initStates(): void {
for (const plc of plcConfigs) {
if (!plcStates.has(plc.id)) {
plcStates.set(plc.id, { failCount: 0, connected: true })
}
}
}
function markFail(plcId: number): number {
const s = plcStates.get(plcId)
if (!s) return 0
s.failCount++
return s.failCount
}
function markSuccess(plcId: number): void {
const s = plcStates.get(plcId)
if (!s) return
s.failCount = 0
}
function setConnected(plcId: number, v: boolean): void {
const s = plcStates.get(plcId)
if (!s) return
s.connected = v
}
/* ===== Start / Stop ===== */
export function start(): void {
if (running) return
loadPLCConfigs()
if (plcConfigs.length === 0) {
logger.warn(TAG, '无 PLC 配置,跳过启动')
running = true
return
}
if (plcConfigs.length === 0) { logger.warn(TAG, '无 PLC 配置,跳过启动'); running = true; return }
running = true
initStates()
for (const plc of plcConfigs) {
connectPLC(plc)
const ok = connectPLC(plc)
setConnected(plc.id, ok)
}
logger.info(TAG, `开始轮询 ${plcConfigs.length} 台 PLC (间隔 ${POLL_INTERVAL_MS}ms)`)
timer = setInterval(pollCycle, POLL_INTERVAL_MS)
pollTimer = setInterval(pollCycle, POLL_INTERVAL_MS)
}
export function stop(): void {
if (timer) {
clearInterval(timer)
timer = null
}
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
if (probeTimer) { clearInterval(probeTimer); probeTimer = null }
disconnectAll()
running = false
logger.info(TAG, '已停止')
}
export function isRunning(): boolean {
return running
export function isRunning(): boolean { return running }
/* ===== Probe cycle — check TCP port ===== */
async function probeCycle(): Promise<void> {
const probing: PLCConfig[] = []
for (const plc of plcConfigs) {
const s = plcStates.get(plc.id)
if (s && !s.connected && s.failCount >= FAIL_LIMIT) probing.push(plc)
}
if (probing.length === 0) {
if (probeTimer) { clearInterval(probeTimer); probeTimer = null }
return
}
for (const plc of probing) {
const alive = await testTcpConnection(plc.ipAddress, PROBE_TIMEOUT_MS)
if (alive) {
logger.info(TAG, `${plc.plcName} (${plc.ipAddress}) 端口已恢复,重连中...`)
const ok = connectPLC(plc)
if (ok) {
setConnected(plc.id, true)
markSuccess(plc.id)
logger.info(TAG, `${plc.plcName} 重连成功`)
} else {
logger.warn(TAG, `${plc.plcName} 重连失败,继续探测`)
}
}
}
}
/* ===== Poll cycle ===== */
function pollCycle(): void {
const db = getDb()
for (const plc of plcConfigs) {
const state = plcStates.get(plc.id)
if (!state) continue
/* ------ Probe mode ------ */
if (!state.connected || state.failCount >= FAIL_LIMIT) {
if (!probeTimer) {
logger.warn(TAG, `${plc.plcName} 已断开,进入探测模式 (${PROBE_INTERVAL_MS}ms)`)
probeTimer = setInterval(probeCycle, PROBE_INTERVAL_MS)
probeCycle() // fire immediately
}
continue
}
/* ------ Normal poll ------ */
const stationIds = db.prepare(
'SELECT Id FROM Stations WHERE PLCId = ? ORDER BY Id'
).all(plc.id) as { Id: number }[]
if (stationIds.length === 0) continue
const bigBuf = readAllStationsBlock({ id: plc.id, plcName: plc.plcName, ipAddress: plc.ipAddress, dbNumber: plc.dbNumber, stationCount: stationIds.length })
if (!bigBuf) continue
const bigBuf = readAllStationsBlock({
id: plc.id, plcName: plc.plcName, ipAddress: plc.ipAddress,
dbNumber: plc.dbNumber, stationCount: stationIds.length,
})
if (!bigBuf) {
const cnt = markFail(plc.id)
if (cnt === 1) logger.warn(TAG, `DB${plc.dbNumber} 批量读取失败,即将断连 (上限${FAIL_LIMIT}次)`)
if (cnt >= FAIL_LIMIT) {
disconnectPLC(plc.id)
setConnected(plc.id, false)
}
continue
}
// success — reset counter
markSuccess(plc.id)
for (let idx = 0; idx < stationIds.length; idx++) {
const offset = idx * STATION_SIZE
@@ -109,7 +187,7 @@ function pollCycle(): void {
const bits = parseControlWord(controlWord)
if (bits.dataReady) {
logger.info(TAG, `${plc.plcName} 工序${idx} DataReady=1, ProductID=${productID}, 开始采集`)
logger.info(TAG, `${plc.plcName} 工序${idx} DataReady=1, ProductID=${productID}`)
const data = { productID, upperLimit, lowerLimit, measuredValue, controlWord, ...bits }
handleDataCollection(plc, idx, data)
clearDataReady(plc, idx, controlWord)
@@ -118,7 +196,7 @@ function pollCycle(): void {
if (bits.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=${productID}, 处理互锁`)
logger.info(TAG, `${stRow.StationName} PrevResultReq=1, ProductID=${productID}`)
const result = handleInterlock(stRow.StationName, productID)
writePrevResult(plc, idx, result.prevResult === 1)
}