refactor: simplify startup logs, batch DB read, remove per-read log

This commit is contained in:
zlm committed 2026-06-10 09:13:34 +08:00
1 parent 33d5442941
commit 11b79075a5
5 files changed
+55 -62

No files matched your search

+16
View File
@@ -75,6 +75,22 @@ export function disconnectAll(): void {
clients.clear() clients.clear()
} }
export function readAllStationsBlock(cfg: PLCConfig): Buffer | null {
const client = clients.get(cfg.id)
if (!client) return null
const totalSize = cfg.stationCount * STATION_SIZE
if (totalSize === 0) return null
const buf = Buffer.alloc(totalSize)
const result = client.DBRead(cfg.dbNumber, 0, totalSize, buf)
if (result === false) {
logger.warn(TAG, `DB${cfg.dbNumber} 批量读取 ${cfg.stationCount} 个工序失败: ${client.ErrorText(client.LastError())}`)
return null
}
return result instanceof Buffer ? result : buf
}
function readStationBlock(dbNumber: number, stationIndex: number, client: any): Buffer | null { function readStationBlock(dbNumber: number, stationIndex: number, client: any): Buffer | null {
const offset = stationOffset(stationIndex) const offset = stationOffset(stationIndex)
const buf = Buffer.alloc(STATION_SIZE) const buf = Buffer.alloc(STATION_SIZE)
+32 -55
View File
@@ -1,10 +1,11 @@
import { getDb } from '../database/connection.js' import { getDb } from '../database/connection.js'
import { connectPLC, readStationData, readControlWord, clearDataReady, import { connectPLC, readAllStationsBlock, clearDataReady,
writePrevResult, disconnectAll, type PLCConfig } from './client.js' writePrevResult, disconnectAll, type PLCConfig } from './client.js'
import { handleDataCollection } from '../services/collection.js' import { handleDataCollection } from '../services/collection.js'
import { handleInterlock } from '../services/interlock.js' import { handleInterlock } from '../services/interlock.js'
import { logger } from '../logger.js' import { logger } from '../logger.js'
import { STATION_SIZE, OFFSET, CONTROL_BITS } from './protocol.js' import { STATION_SIZE, OFFSET,
readDINT, readREAL, readWORD, parseControlWord } from './protocol.js'
const TAG = 'Scanner' const TAG = 'Scanner'
const POLL_INTERVAL_MS = 1000 const POLL_INTERVAL_MS = 1000
@@ -24,52 +25,16 @@ function logConfig(): void {
return 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) { for (const plc of plcs) {
logger.info(TAG, `${plc.PLCName} (${plc.IPAddress}) DB${plc.DBNumber}`)
const stations = db.prepare(` const stations = db.prepare(`
SELECT s.StationIndex, s.StationName, mp.PointName SELECT s.StationName, mp.PointName
FROM Stations s FROM Stations s
JOIN MeasurementPoints mp ON mp.Id = s.PointId JOIN MeasurementPoints mp ON mp.Id = s.PointId
WHERE s.PLCId = ? ORDER BY s.Id WHERE s.PLCId = ? ORDER BY s.Id
`).all(plc.Id) as any[] `).all(plc.Id) as any[]
if (stations.length === 0) { const names = stations.map((s: any) => s.StationName).join(', ')
logger.info(TAG, ` (无工序配置)`) logger.info(TAG, `${plc.PLCName} DB${plc.DBNumber} → ${names || '(无工序)'}`)
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}`)
}
}
} }
} }
@@ -126,27 +91,39 @@ function pollCycle(): void {
'SELECT Id FROM Stations WHERE PLCId = ? ORDER BY Id' 'SELECT Id FROM Stations WHERE PLCId = ? ORDER BY Id'
).all(plc.id) as { Id: number }[] ).all(plc.id) as { Id: number }[]
for (let idx = 0; idx < stationIds.length; idx++) { if (stationIds.length === 0) continue
const i = idx
try {
const data = readStationData(plc, i)
if (!data) continue
if (data.dataReady) { const bigBuf = readAllStationsBlock({ id: plc.id, plcName: plc.plcName, ipAddress: plc.ipAddress, dbNumber: plc.dbNumber, stationCount: stationIds.length })
logger.info(TAG, `${plc.plcName} 工序${i} DataReady=1, ProductID=${data.productID}, 开始采集`) if (!bigBuf) continue
handleDataCollection(plc, i, data)
clearDataReady(plc, i, data.controlWord) for (let idx = 0; idx < stationIds.length; idx++) {
const offset = idx * STATION_SIZE
const buf = bigBuf.subarray(offset, offset + STATION_SIZE)
try {
const productID = readDINT(buf, OFFSET.ProductID)
const upperLimit = readREAL(buf, OFFSET.UpperLimit)
const lowerLimit = readREAL(buf, OFFSET.LowerLimit)
const measuredValue = readREAL(buf, OFFSET.MeasuredValue)
const controlWord = readWORD(buf, OFFSET.ControlWord)
const bits = parseControlWord(controlWord)
if (bits.dataReady) {
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)
} }
if (data.prevResultReq) { if (bits.prevResultReq) {
const stRow = db.prepare('SELECT StationName FROM Stations WHERE Id=?').get(stationIds[idx].Id) as { StationName: string } | undefined const stRow = db.prepare('SELECT StationName FROM Stations WHERE Id=?').get(stationIds[idx].Id) as { StationName: string } | undefined
if (!stRow) continue if (!stRow) continue
logger.info(TAG, `${stRow.StationName} PrevResultReq=1, ProductID=${data.productID}, 处理互锁`) logger.info(TAG, `${stRow.StationName} PrevResultReq=1, ProductID=${productID}, 处理互锁`)
const result = handleInterlock(stRow.StationName, data.productID) const result = handleInterlock(stRow.StationName, productID)
writePrevResult(plc, i, result.prevResult === 1) writePrevResult(plc, idx, result.prevResult === 1)
} }
} catch (err) { } catch (err) {
logger.error(TAG, `PLC#${plc.id} 工序 ${i} 错误: ${err}`) logger.error(TAG, `PLC#${plc.id} 工序${idx} 错误: ${err}`)
} }
} }
} }
+1 -1
View File
@@ -17,7 +17,7 @@
<div id="page-query" class="page active max-w-3xl mx-auto p-6"> <div id="page-query" class="page active max-w-3xl mx-auto p-6">
<div class="flex gap-2 mb-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" /> <input id="q-input" type="text" placeholder="输入产品编号" 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> <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>
<div id="q-result"></div> <div id="q-result"></div>
+5 -5
View File
@@ -65,15 +65,15 @@ let activeSubTab: 'mp' | 'plc' = 'mp'
async function loadConfig() { async function loadConfig() {
configLoaded = true configLoaded = true
plcTabLoaded = false plcTabLoaded = false
activeSubTab = 'mp'
const el = document.getElementById('page-config')! const el = document.getElementById('page-config')!
const mpActive = activeSubTab === 'mp'
el.innerHTML = ` el.innerHTML = `
<div class="flex gap-1 mb-4 border-b border-gray-200 pb-0"> <div class="flex gap-1 mb-4 border-b border-gray-200 pb-0">
<button id="sub-tab-mp" class="sub-tab active px-4 py-2 text-sm font-medium border-b-2 border-indigo-600 text-indigo-700">检测点配置</button> <button id="sub-tab-mp" class="sub-tab px-4 py-2 text-sm font-medium border-b-2 ${mpActive ? 'border-indigo-600 text-indigo-700' : 'border-transparent text-gray-500 hover:text-gray-700'}">检测点配置</button>
<button id="sub-tab-plc" class="sub-tab px-4 py-2 text-sm font-medium text-gray-500 border-b-2 border-transparent hover:text-gray-700">PLC配置</button> <button id="sub-tab-plc" class="sub-tab px-4 py-2 text-sm font-medium border-b-2 ${mpActive ? 'border-transparent text-gray-500 hover:text-gray-700' : 'border-indigo-600 text-indigo-700'}">PLC配置</button>
</div> </div>
<div id="mp-panel"></div> <div id="mp-panel" class="${mpActive ? '' : 'hidden'}"></div>
<div id="plc-panel" class="hidden"></div>` <div id="plc-panel" class="${mpActive ? 'hidden' : ''}"></div>`
document.getElementById('sub-tab-mp')!.addEventListener('click', () => switchTab('mp')) document.getElementById('sub-tab-mp')!.addEventListener('click', () => switchTab('mp'))
document.getElementById('sub-tab-plc')!.addEventListener('click', () => switchTab('plc')) document.getElementById('sub-tab-plc')!.addEventListener('click', () => switchTab('plc'))
+1 -1
View File
@@ -7,7 +7,7 @@ print(f"PLC 连接状态: {plc.get_connected()}")
db_number = 1 db_number = 1
start_byte = 0 start_byte = 0
byteoffset = 16 byteoffset = 4
data = bytearray(2) data = bytearray(2)