feat(csms): 优化充电桩重连处理逻辑

This commit is contained in:
2026-04-20 13:55:39 +08:00
parent 3bdb3d7351
commit d688a8497d

View File

@@ -130,6 +130,17 @@ async function updateTransportState(
.where(eq(chargePoint.chargePointIdentifier, chargePointIdentifier)) .where(eq(chargePoint.chargePointIdentifier, chargePointIdentifier))
} }
async function getRegistrationStatus(chargePointIdentifier: string) {
const db = useDrizzle()
const [cp] = await db
.select({ registrationStatus: chargePoint.registrationStatus })
.from(chargePoint)
.where(eq(chargePoint.chargePointIdentifier, chargePointIdentifier))
.limit(1)
return cp?.registrationStatus ?? null
}
function getCommandChannelStatus(chargePointIdentifier: string): CommandChannelStatus { function getCommandChannelStatus(chargePointIdentifier: string): CommandChannelStatus {
return ocppConnections.has(chargePointIdentifier) ? 'online' : 'unavailable' return ocppConnections.has(chargePointIdentifier) ? 'online' : 'unavailable'
} }
@@ -211,6 +222,19 @@ export function createOcppHandler(chargePointIdentifier: string, remoteAddr?: st
ws.close(1002, 'Unsupported subprotocol') ws.close(1002, 'Unsupported subprotocol')
return return
} }
const registrationStatus = await getRegistrationStatus(chargePointIdentifier)
ctx.isRegistered = registrationStatus === 'Accepted'
const previous = ocppConnections.get(chargePointIdentifier)
if (previous && previous.sessionId !== sessionId) {
try {
previous.ws.close(1012, 'Replaced by newer connection')
} catch {
// Ignore close race when the old socket is already gone.
}
}
ocppConnections.set(chargePointIdentifier, { ocppConnections.set(chargePointIdentifier, {
ws, ws,
sessionId, sessionId,
@@ -226,15 +250,24 @@ export function createOcppHandler(chargePointIdentifier: string, remoteAddr?: st
`[OCPP] ${chargePointIdentifier} connected` + `[OCPP] ${chargePointIdentifier} connected` +
(remoteAddr ? ` from ${remoteAddr}` : ''), (remoteAddr ? ` from ${remoteAddr}` : ''),
) )
if (previous && previous.sessionId !== sessionId) {
console.log(`[OCPP] ${chargePointIdentifier} replaced previous connection`)
}
}, },
async onMessage(evt: MessageEvent, ws: WSContext) { async onMessage(evt: MessageEvent, ws: WSContext) {
let uniqueId = '(unknown)' let uniqueId = '(unknown)'
try { try {
const current = ocppConnections.get(chargePointIdentifier) const current = ocppConnections.get(chargePointIdentifier)
if (current) { if (!current || current.sessionId !== sessionId) {
current.lastMessageAt = new Date() try {
ws.close(1008, 'Stale connection')
} catch {
// Ignore close errors on stale sockets.
}
return
} }
current.lastMessageAt = new Date()
const raw = evt.data const raw = evt.data
if (typeof raw !== 'string') return if (typeof raw !== 'string') return