Files
scanner_record/project/src/plc/scanner.ts
T
2026-06-09 14:32:13 +08:00

154 lines
5.1 KiB
TypeScript

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