Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions src/charging-station/ChargingStation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,20 +209,20 @@ export class ChargingStation extends EventEmitter {

private automaticTransactionGeneratorConfiguration?: AutomaticTransactionGeneratorConfiguration
private readonly chargingStationWorkerBroadcastChannel: ChargingStationWorkerBroadcastChannel
private configurationFile!: string
private configurationFileHash!: string
private configurationFile: string
private configurationFileHash: string
private configuredSupervisionUrl!: URL
private readonly connectors: Map<number, ConnectorStatus>
private connectorsConfigurationHash!: string
private connectorsConfigurationHash: string
private readonly evses: Map<number, EvseStatus>
private evsesConfigurationHash!: string
private evsesConfigurationHash: string
private flushingMessageBuffer: boolean
private flushMessageBufferSetInterval?: NodeJS.Timeout
private readonly messageQueue: string[]
private ocppIncomingRequestService!: OCPPIncomingRequestService
private readonly sharedLRUCache: SharedLRUCache
private stopping: boolean
private templateFileHash!: string
private templateFileHash: string
private templateFileWatcher?: FSWatcher
private wsConnectionRetryCount: number
private wsPingSetInterval?: NodeJS.Timeout
Expand All @@ -244,6 +244,11 @@ export class ChargingStation extends EventEmitter {
this.sharedLRUCache = SharedLRUCache.getInstance()
this.idTagsCache = IdTagsCache.getInstance()
this.chargingStationWorkerBroadcastChannel = new ChargingStationWorkerBroadcastChannel(this)
this.configurationFile = ''
this.configurationFileHash = ''
this.connectorsConfigurationHash = ''
this.evsesConfigurationHash = ''
this.templateFileHash = ''

this.on(ChargingStationEvents.added, () => {
parentPort?.postMessage(buildAddedMessage(this))
Expand Down
12 changes: 9 additions & 3 deletions src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -590,14 +590,16 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
)
})
} else {
// Unref: fire-and-forget deferred firmware update must not
// block node.js exit.
setTimeout(() => {
this.updateFirmwareSimulation(chargingStation).catch((error: unknown) => {
logger.error(
`${chargingStation.logPrefix()} ${moduleName}.constructor: UpdateFirmware simulation error:`,
error
)
})
}, retrieveDate.getTime() - now)
}, retrieveDate.getTime() - now).unref()
}
}
)
Expand Down Expand Up @@ -1301,10 +1303,14 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
connectorId <= chargingStation.getNumberOfConnectors();
connectorId++
) {
const connectorStatus = chargingStation.getConnectorStatus(connectorId)
const isReservedForOther =
connectorStatus?.status === OCPP16ChargePointStatus.Reserved &&
!OCPP16ServiceUtils.hasReservation(chargingStation, connectorId, commandPayload.idTag)
if (
chargingStation.isConnectorAvailable(connectorId) &&
chargingStation.getConnectorStatus(connectorId)?.transactionStarted === false &&
!OCPP16ServiceUtils.hasReservation(chargingStation, connectorId, commandPayload.idTag)
connectorStatus?.transactionStarted === false &&
!isReservedForOther
Comment on lines +1306 to +1313

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logic Error: The isReservedForOther guard is only checked after isConnectorAvailable, but isConnectorAvailable already returns false for a Reserved connector (since its availability is not Operative). This means the entire if block can never be entered for a Reserved connector regardless of the isReservedForOther value, making the H6 fix a no-op for the connector auto-select path.

To verify: isConnectorAvailable checks connectorStatus.availability === AvailabilityType.Operative (line 824-828 of ChargingStation.ts), and a Reserved connector has its availability set as part of the ReserveNow flow. If Reserved connectors have availability !== Operative, then isConnectorAvailable already excludes them and the isReservedForOther guard is unreachable.

Should verify whether a Reserved connector retains Operative availability in this codebase. If not, the isReservedForOther check is dead code and the fix should instead be applied after the isConnectorAvailable check is replaced/widened.


Please provide feedback on the review comment by checking the appropriate box:

  • 🌟 Awesome comment, a human might have missed that.
  • ✅ Helpful comment
  • 🤷 Neutral
  • ❌ This comment is not helpful

Comment on lines +1306 to +1313

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logic Error: The isReservedForOther guard is evaluated only when chargingStation.isConnectorAvailable(connectorId) is true. isConnectorAvailable checks connectorStatus.availability === AvailabilityType.Operative (see ChargingStation.ts lines 824–828). A Reserved connector's status is Reserved, but if its availability field remains Operative (i.e. the reservation only changes status, not availability), then isConnectorAvailable returns true and the isReservedForOther guard correctly fires.

However, if the ReserveNow handler sets availability to anything other than Operative on reservation, then isConnectorAvailable would already return false and isReservedForOther would be unreachable dead code, making the H6 fix a no-op. Please add a code comment or test confirming which case applies — if Reserved connectors keep availability === Operative, this fix is correct; otherwise the predicate needs to be restructured (e.g. replacing isConnectorAvailable with a combined availability+reservation check).


Please provide feedback on the review comment by checking the appropriate box:

  • 🌟 Awesome comment, a human might have missed that.
  • ✅ Helpful comment
  • 🤷 Neutral
  • ❌ This comment is not helpful

) {
commandPayload.connectorId = connectorId
break
Expand Down
7 changes: 7 additions & 0 deletions src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -949,6 +949,13 @@ export class OCPP16ServiceUtils {
connectorId: number,
reason?: StopTransactionReason
): Promise<StopTransactionResponse> {
const connectorStatus = chargingStation.getConnectorStatus(connectorId)
if (connectorStatus?.status !== OCPP16ChargePointStatus.Finishing) {
await sendAndSetConnectorStatus(chargingStation, {
connectorId,
status: OCPP16ChargePointStatus.Finishing,
} as OCPP16StatusNotificationRequest)
}
Comment on lines +952 to +958

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logic Error: remoteStopTransaction sends StatusNotification(Finishing) before calling stopTransactionOnConnector, which now also unconditionally sends StatusNotification(Finishing) unless the connector is already in Finishing state. The guard in stopTransactionOnConnector (connectorStatus?.status !== OCPP16ChargePointStatus.Finishing) is intended to prevent a duplicate, relying on sendAndSetConnectorStatus having already updated the connector status in memory by the time stopTransactionOnConnector runs.

While this works today (because remoteStopTransaction awaits the emission), it is fragile: the deduplication is implicit and relies on ordering rather than an explicit contract. Consider simply removing the explicit sendAndSetConnectorStatus call from remoteStopTransaction since stopTransactionOnConnector now handles it, which eliminates the dependency entirely and makes the spec compliance visible in one place only.


Please provide feedback on the review comment by checking the appropriate box:

  • 🌟 Awesome comment, a human might have missed that.
  • ✅ Helpful comment
  • 🤷 Neutral
  • ❌ This comment is not helpful

const rawTransactionId = chargingStation.getConnectorStatus(connectorId)?.transactionId
const transactionId = rawTransactionId != null ? convertToInt(rawTransactionId) : undefined
if (
Expand Down
15 changes: 11 additions & 4 deletions src/charging-station/ocpp/2.0/OCPP20IncomingRequestService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3319,6 +3319,8 @@ export class OCPP20IncomingRequestService extends OCPPIncomingRequestService {
logger.info(
`${chargingStation.logPrefix()} ${moduleName}.scheduleEvseReset: Executing EVSE ${evseId.toString()} reset${hasActiveTransactions ? ' after transaction termination' : ''}`
)
// Unref: fire-and-forget pending EVSE reset must not block
// node.js exit.
setTimeout(() => {
const evse = chargingStation.getEvseStatus(evseId)
if (evse) {
Expand All @@ -3337,7 +3339,7 @@ export class OCPP20IncomingRequestService extends OCPPIncomingRequestService {
`${chargingStation.logPrefix()} ${moduleName}.scheduleEvseReset: EVSE ${evseId.toString()} reset completed`
)
}
}, OCPP20Constants.RESET_DELAY_MS)
}, OCPP20Constants.RESET_DELAY_MS).unref()
})
}

Expand All @@ -3347,6 +3349,8 @@ export class OCPP20IncomingRequestService extends OCPPIncomingRequestService {
* @param evseId - The EVSE identifier to reset
*/
private scheduleEvseResetOnIdle (chargingStation: ChargingStation, evseId: number): void {
// Unref: idle-monitor poll must not block node.js exit; the interval
// self-clears once the EVSE is idle or its state is gone.
const monitorInterval = setInterval(() => {
const evse = chargingStation.getEvseStatus(evseId)
if (evse != null) {
Expand All @@ -3360,14 +3364,16 @@ export class OCPP20IncomingRequestService extends OCPPIncomingRequestService {
} else {
clearInterval(monitorInterval)
}
}, OCPP20Constants.RESET_IDLE_MONITOR_INTERVAL_MS)
}, OCPP20Constants.RESET_IDLE_MONITOR_INTERVAL_MS).unref()
}

/**
* Schedules charging station reset on idle (when no active transactions)
* @param chargingStation - The charging station instance
*/
private scheduleResetOnIdle (chargingStation: ChargingStation): void {
// Unref: idle-monitor poll must not block node.js exit; the interval
// self-clears once the station reports idle.
const monitorInterval = setInterval(() => {
if (this.isChargingStationIdle(chargingStation)) {
clearInterval(monitorInterval)
Expand All @@ -3381,7 +3387,7 @@ export class OCPP20IncomingRequestService extends OCPPIncomingRequestService {
)
})
}
}, OCPP20Constants.RESET_IDLE_MONITOR_INTERVAL_MS)
}, OCPP20Constants.RESET_IDLE_MONITOR_INTERVAL_MS).unref()
}

private selectAvailableEvse (chargingStation: ChargingStation): number | undefined {
Expand Down Expand Up @@ -3611,9 +3617,10 @@ export class OCPP20IncomingRequestService extends OCPPIncomingRequestService {
)
queue.unshift({ ...event, retryCount })
stationState.isDrainingSecurityEvents = false
// Unref: fire-and-forget retry must not block node.js exit.
setTimeout(() => {
this.sendQueuedSecurityEvents(chargingStation)
}, OCPP20Constants.SECURITY_EVENT_RETRY_DELAY_MS)
}, OCPP20Constants.SECURITY_EVENT_RETRY_DELAY_MS).unref()
})
}
drainNextEvent()
Expand Down
2 changes: 1 addition & 1 deletion src/charging-station/ocpp/OCPPRequestService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ export abstract class OCPPRequestService {
chargingStation.inRejectedState()) &&
commandName === RequestCommand.BOOT_NOTIFICATION) ||
(chargingStation.stationInfo?.ocppStrictCompliance === false &&
(chargingStation.inUnknownState() || chargingStation.inPendingState())) ||
chargingStation.inUnknownState()) ||
chargingStation.inAcceptedState() ||
(chargingStation.inPendingState() &&
(params.triggerMessage === true || messageType === MessageType.CALL_RESULT_MESSAGE))
Expand Down
14 changes: 12 additions & 2 deletions src/charging-station/ui-server/AbstractUIServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,12 @@ export abstract class AbstractUIServer {
.finally(() => {
registry.clear()
})
.catch(() => undefined)
.catch((error: unknown) => {
logger.warn(
`${this.logPrefix()} ${moduleName}.stop: metrics registry cleanup failed`,
error
)
})
this.metricsRegistry = undefined
}
// detachTransport() / uiService.stop() are subclass hooks — see
Expand Down Expand Up @@ -1268,7 +1273,12 @@ export abstract class AbstractUIServer {
registry: Registry
): Promise<void> {
this.metricsScrapeChain = this.metricsScrapeChain
.catch(() => undefined)
.catch((error: unknown) => {
logger.warn(
`${this.logPrefix()} ${moduleName}.runMetricsScrape: previous scrape errored; absorbing rejection so next scrape can proceed`,
error
)
})
.then(async () => {
this.metricsSampleCount = 0
// prom-client's sync prefix runs every collect() (each writing
Expand Down
13 changes: 9 additions & 4 deletions tests/charging-station/ocpp/OCPPServiceOperations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ await describe('OCPPServiceOperations', async () => {
})

await describe('stopTransactionOnConnector', async () => {
await it('should send StopTransaction for OCPP 1.6 stations and return accepted: true', async () => {
await it('should send StatusNotification(Finishing) then StopTransaction for OCPP 1.6 stations (matches remote-stop message sequence)', async () => {
const { requestHandler, station } = createStationWithRequestHandler()
requestHandler.mock.mockImplementation(async (..._args: unknown[]) =>
Promise.resolve({ idTagInfo: { status: 'Accepted' } })
Expand All @@ -67,10 +67,15 @@ await describe('OCPPServiceOperations', async () => {

assert.strictEqual(result.accepted, true)
assert.ok(
requestHandler.mock.calls.length >= 1,
'request handler should have been called at least once'
requestHandler.mock.calls.length >= 2,
'request handler should have been called at least twice (StatusNotification + StopTransaction)'
)
assert.strictEqual(requestHandler.mock.calls[0].arguments[1], 'StatusNotification')
assert.strictEqual(
(requestHandler.mock.calls[0].arguments[2] as { status: string }).status,
'Finishing'
)
assert.strictEqual(requestHandler.mock.calls[0].arguments[1], 'StopTransaction')
assert.strictEqual(requestHandler.mock.calls[1].arguments[1], 'StopTransaction')
})

await it('should send TransactionEvent(Ended) for OCPP 2.0 stations and return accepted: true', async () => {
Expand Down
Loading