hasFeatureProfile,
hasReservationExpired,
initializeConnectorsMapStatus,
+ prepareConnectorStatus,
propagateSerialNumber,
setChargingStationOptions,
stationTemplateToStationInfo,
private ocppIncomingRequestService!: OCPPIncomingRequestService
private readonly messageBuffer: Set<string>
private configuredSupervisionUrl!: URL
- private wsConnectionRetried: boolean
private wsConnectionRetryCount: number
private templateFileWatcher?: FSWatcher
private templateFileHash!: string
this.starting = false
this.stopping = false
this.wsConnection = null
- this.wsConnectionRetried = false
this.wsConnectionRetryCount = 0
this.index = index
this.templateFile = templateFile
})
this.on(ChargingStationEvents.accepted, () => {
this.startMessageSequence(
- this.wsConnectionRetried
+ this.wsConnectionRetryCount > 0
? true
: this.getAutomaticTransactionGeneratorConfiguration()?.stopAbsoluteDuration
- ).catch(error => {
+ ).catch((error: unknown) => {
logger.error(`${this.logPrefix()} Error while starting the message sequence:`, error)
})
- this.wsConnectionRetried = false
+ this.wsConnectionRetryCount = 0
})
this.on(ChargingStationEvents.rejected, () => {
- this.wsConnectionRetried = false
+ this.wsConnectionRetryCount = 0
+ })
+ this.on(ChargingStationEvents.connected, () => {
+ if (this.wsPingSetInterval == null) {
+ this.startWebSocketPing()
+ }
})
this.on(ChargingStationEvents.disconnected, () => {
try {
}
public get wsConnectionUrl (): URL {
+ const wsConnectionBaseUrlStr = `${
+ this.stationInfo?.supervisionUrlOcppConfiguration === true &&
+ isNotEmptyString(this.stationInfo.supervisionUrlOcppKey) &&
+ isNotEmptyString(getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey)?.value)
+ ? getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey)?.value
+ : this.configuredSupervisionUrl.href
+ }`
return new URL(
- `${
- this.stationInfo?.supervisionUrlOcppConfiguration === true &&
- isNotEmptyString(this.stationInfo.supervisionUrlOcppKey) &&
- isNotEmptyString(getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey)?.value)
- ? getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey)?.value
- : this.configuredSupervisionUrl.href
- }/${this.stationInfo?.chargingStationId}`
+ `${wsConnectionBaseUrlStr}${
+ !wsConnectionBaseUrlStr.endsWith('/') ? '/' : ''
+ }${this.stationInfo?.chargingStationId}`
)
}
readFileSync(this.templateFile, 'utf8')
) as ChargingStationTemplate
} catch {
- stationTemplate = undefined
+ // Ignore
}
return logPrefix(` ${getChargingStationId(this.index, stationTemplate)} |`)
}
const connectorChargingProfilesPowerLimit =
getChargingStationConnectorChargingProfilesPowerLimit(this, connectorId)
return min(
- isNaN(connectorMaximumPower) ? Infinity : connectorMaximumPower,
+ isNaN(connectorMaximumPower) ? Number.POSITIVE_INFINITY : connectorMaximumPower,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
isNaN(connectorAmperageLimitationPowerLimit!)
- ? Infinity
+ ? Number.POSITIVE_INFINITY
: // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
connectorAmperageLimitationPowerLimit!,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
- isNaN(connectorChargingProfilesPowerLimit!) ? Infinity : connectorChargingProfilesPowerLimit!
+ isNaN(connectorChargingProfilesPowerLimit!)
+ ? Number.POSITIVE_INFINITY
+ : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ connectorChargingProfilesPowerLimit!
)
}
}
public startHeartbeat (): void {
- if (this.getHeartbeatInterval() > 0 && this.heartbeatSetInterval == null) {
+ const heartbeatInterval = this.getHeartbeatInterval()
+ if (heartbeatInterval > 0 && this.heartbeatSetInterval == null) {
this.heartbeatSetInterval = setInterval(() => {
this.ocppRequestService
.requestHandler<HeartbeatRequest, HeartbeatResponse>(this, RequestCommand.HEARTBEAT)
- .catch(error => {
+ .catch((error: unknown) => {
logger.error(
`${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
error
)
})
- }, this.getHeartbeatInterval())
+ }, heartbeatInterval)
logger.info(
`${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds(
- this.getHeartbeatInterval()
+ heartbeatInterval
)}`
)
} else if (this.heartbeatSetInterval != null) {
logger.info(
`${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds(
- this.getHeartbeatInterval()
+ heartbeatInterval
)}`
)
} else {
logger.error(
- `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, not starting the heartbeat`
+ `${this.logPrefix()} Heartbeat interval set to ${heartbeatInterval}, not starting the heartbeat`
)
}
}
meterValue: [meterValue]
}
)
- .catch(error => {
+ .catch((error: unknown) => {
logger.error(
`${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
error
}
}
+ public restartMeterValues (connectorId: number, interval: number): void {
+ this.stopMeterValues(connectorId)
+ this.startMeterValues(connectorId, interval)
+ }
+
private add (): void {
this.emit(ChargingStationEvents.added)
}
this.wsConnection.on('close', this.onClose.bind(this))
// Handle WebSocket open
this.wsConnection.on('open', () => {
- this.onOpen().catch(error =>
+ this.onOpen().catch((error: unknown) =>
logger.error(`${this.logPrefix()} Error while opening WebSocket connection:`, error)
)
})
)
}
return await this.ocppRequestService.requestHandler<
- StopTransactionRequest,
+ Partial<StopTransactionRequest>,
StopTransactionResponse
>(this, RequestCommand.STOP_TRANSACTION, {
transactionId,
} does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`
)
}
- stationInfo.firmwareUpgrade = mergeDeepRight(
- {
- versionUpgrade: {
- step: 1
- },
- reset: true
- },
- stationTemplate.firmwareUpgrade ?? {}
- )
if (stationTemplate.resetTime != null) {
stationInfo.resetTime = secondsToMilliseconds(stationTemplate.resetTime)
}
const stationInfoFromFile = this.getStationInfoFromFile(
stationInfoFromTemplate.stationInfoPersistentConfiguration
)
+ let stationInfo: ChargingStationInfo
// Priority:
// 1. charging station info from template
// 2. charging station info from configuration file
stationInfoFromFile != null &&
stationInfoFromFile.templateHash === stationInfoFromTemplate.templateHash
) {
- return setChargingStationOptions(
- { ...Constants.DEFAULT_STATION_INFO, ...stationInfoFromFile },
- options
- )
+ stationInfo = stationInfoFromFile
+ } else {
+ stationInfo = stationInfoFromTemplate
+ stationInfoFromFile != null &&
+ propagateSerialNumber(this.getTemplateFromFile(), stationInfoFromFile, stationInfo)
}
- stationInfoFromFile != null &&
- propagateSerialNumber(
- this.getTemplateFromFile(),
- stationInfoFromFile,
- stationInfoFromTemplate
- )
return setChargingStationOptions(
- { ...Constants.DEFAULT_STATION_INFO, ...stationInfoFromTemplate },
+ mergeDeepRight(Constants.DEFAULT_STATION_INFO, stationInfo),
options
)
}
addConfigurationKey(this, StandardParametersKey.HeartbeatInterval, '0')
}
if (getConfigurationKey(this, StandardParametersKey.HeartBeatInterval) == null) {
- addConfigurationKey(this, StandardParametersKey.HeartBeatInterval, '0', { visible: false })
+ addConfigurationKey(this, StandardParametersKey.HeartBeatInterval, '0', {
+ visible: false
+ })
}
if (
this.stationInfo?.supervisionUrlOcppConfiguration === true &&
isNotEmptyString(this.stationInfo.supervisionUrlOcppKey) &&
getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey) != null
) {
- deleteConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey, { save: false })
+ deleteConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey, {
+ save: false
+ })
}
if (
isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) &&
private initializeConnectorsOrEvsesFromFile (configuration: ChargingStationConfiguration): void {
if (configuration.connectorsStatus != null && configuration.evsesStatus == null) {
for (const [connectorId, connectorStatus] of configuration.connectorsStatus.entries()) {
- this.connectors.set(connectorId, clone<ConnectorStatus>(connectorStatus))
+ this.connectors.set(
+ connectorId,
+ prepareConnectorStatus(clone<ConnectorStatus>(connectorStatus))
+ )
}
} else if (configuration.evsesStatus != null && configuration.connectorsStatus == null) {
for (const [evseId, evseStatusConfiguration] of configuration.evsesStatus.entries()) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
evseStatusConfiguration.connectorsStatus!.map((connectorStatus, connectorId) => [
connectorId,
- connectorStatus
+ prepareConnectorStatus(connectorStatus)
])
)
})
...(this.connectors.size > 0 && {
connectorsStatus: configurationData.connectorsStatus
}),
- ...(this.evses.size > 0 && { evsesStatus: configurationData.evsesStatus })
+ ...(this.evses.size > 0 && {
+ evsesStatus: configurationData.evsesStatus
+ })
} satisfies ChargingStationConfiguration)
)
.digest('hex')
this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash)
this.sharedLRUCache.setChargingStationConfiguration(configurationData)
this.configurationFileHash = configurationHash
- }).catch(error => {
+ }).catch((error: unknown) => {
handleFileException(
this.configurationFile,
FileType.ChargingStationConfiguration,
private async onOpen (): Promise<void> {
if (this.isWebSocketConnectionOpened()) {
+ this.emit(ChargingStationEvents.connected)
this.emit(ChargingStationEvents.updated)
logger.info(
- `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.href} succeeded`
+ `${this.logPrefix()} Connection to OCPP server through ${
+ this.wsConnectionUrl.href
+ } succeeded`
)
let registrationRetryCount = 0
if (!this.isRegistered()) {
// Send BootNotification
do {
- this.bootNotificationResponse = await this.ocppRequestService.requestHandler<
+ await this.ocppRequestService.requestHandler<
BootNotificationRequest,
BootNotificationResponse
>(this, RequestCommand.BOOT_NOTIFICATION, this.bootNotificationRequest, {
skipBufferingOnError: true
})
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
- if (this.bootNotificationResponse?.currentTime != null) {
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
- this.bootNotificationResponse.currentTime = convertToDate(
- this.bootNotificationResponse.currentTime
- )!
- }
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ this.bootNotificationResponse!.currentTime = convertToDate(
+ this.bootNotificationResponse?.currentTime
+ )!
if (!this.isRegistered()) {
this.stationInfo?.registrationMaxRetries !== -1 && ++registrationRetryCount
await sleep(
this.stationInfo?.registrationMaxRetries === -1)
)
}
- if (this.isRegistered()) {
- this.emit(ChargingStationEvents.registered)
- if (this.inAcceptedState()) {
- this.emit(ChargingStationEvents.accepted)
- }
- } else {
- if (this.inRejectedState()) {
- this.emit(ChargingStationEvents.rejected)
- }
+ if (!this.isRegistered()) {
logger.error(
`${this.logPrefix()} Registration failure: maximum retries reached (${registrationRetryCount}) or retry disabled (${
this.stationInfo?.registrationMaxRetries
})`
)
}
- this.wsConnectionRetryCount = 0
this.emit(ChargingStationEvents.updated)
} else {
logger.warn(
.then(() => {
this.emit(ChargingStationEvents.updated)
})
- .catch(error => logger.error(`${this.logPrefix()} Error while reconnecting:`, error))
+ .catch((error: unknown) =>
+ logger.error(`${this.logPrefix()} Error while reconnecting:`, error)
+ )
break
}
}
}
throw new OCPPError(
ErrorType.PROTOCOL_ERROR,
- `Cached request for message id ${messageId} ${getMessageTypeString(
+ `Cached request for message id '${messageId}' ${getMessageTypeString(
messageType
)} is not an array`,
undefined,
private async handleIncomingMessage (request: IncomingRequest): Promise<void> {
const [messageType, messageId, commandName, commandPayload] = request
+ if (this.requests.has(messageId)) {
+ throw new OCPPError(
+ ErrorType.SECURITY_ERROR,
+ `Received message with duplicate message id '${messageId}'`,
+ commandName,
+ commandPayload
+ )
+ }
if (this.stationInfo?.enableStatistics === true) {
this.performanceStatistics?.addRequestStatistic(commandName, messageType)
}
// Error
throw new OCPPError(
ErrorType.INTERNAL_ERROR,
- `Response for unknown message id ${messageId}`,
+ `Response for unknown message id '${messageId}'`,
undefined,
commandPayload
)
// Error
throw new OCPPError(
ErrorType.INTERNAL_ERROR,
- `Error response for unknown message id ${messageId}`,
+ `Error response for unknown message id '${messageId}'`,
undefined,
{ errorType, errorMessage, errorDetails }
)
}
if (!(error instanceof OCPPError)) {
logger.warn(
- `${this.logPrefix()} Error thrown at incoming OCPP command '${
+ `${this.logPrefix()} Error thrown at incoming OCPP command ${
commandName ?? requestCommandName ?? Constants.UNKNOWN_OCPP_COMMAND
// eslint-disable-next-line @typescript-eslint/no-base-to-string
- }' message '${data.toString()}' handling is not an OCPPError:`,
+ } message '${data.toString()}' handling is not an OCPPError:`,
error
)
}
// eslint-disable-next-line @typescript-eslint/no-base-to-string
}' message '${data.toString()}'${
this.requests.has(messageId)
- ? ` matching cached request '${JSON.stringify(this.getCachedRequest(messageType, messageId))}'`
+ ? ` matching cached request '${JSON.stringify(
+ this.getCachedRequest(messageType, messageId)
+ )}'`
: ''
} processing error:`,
error
})
}
// Start WebSocket ping
- this.startWebSocketPing()
+ if (this.wsPingSetInterval == null) {
+ this.startWebSocketPing()
+ }
// Start heartbeat
- this.startHeartbeat()
+ if (this.heartbeatSetInterval == null) {
+ this.startHeartbeat()
+ }
// Initialize connectors status
if (this.hasEvses) {
for (const [evseId, evseStatus] of this.evses) {
if (evseId > 0) {
for (const [connectorId, connectorStatus] of evseStatus.connectors) {
- const connectorBootStatus = getBootConnectorStatus(this, connectorId, connectorStatus)
- await sendAndSetConnectorStatus(this, connectorId, connectorBootStatus, evseId)
+ await sendAndSetConnectorStatus(
+ this,
+ connectorId,
+ getBootConnectorStatus(this, connectorId, connectorStatus),
+ evseId
+ )
}
}
}
} else {
for (const connectorId of this.connectors.keys()) {
if (connectorId > 0) {
- const connectorBootStatus = getBootConnectorStatus(
+ await sendAndSetConnectorStatus(
this,
connectorId,
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
- this.getConnectorStatus(connectorId)!
+ getBootConnectorStatus(
+ this,
+ connectorId,
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ this.getConnectorStatus(connectorId)!
+ )
)
- await sendAndSetConnectorStatus(this, connectorId, connectorBootStatus)
}
}
}
}
}
+ private getWebSocketPingInterval (): number {
+ return getConfigurationKey(this, StandardParametersKey.WebSocketPingInterval) != null
+ ? convertToInt(getConfigurationKey(this, StandardParametersKey.WebSocketPingInterval)?.value)
+ : 0
+ }
+
private startWebSocketPing (): void {
- const webSocketPingInterval =
- getConfigurationKey(this, StandardParametersKey.WebSocketPingInterval) != null
- ? convertToInt(
- getConfigurationKey(this, StandardParametersKey.WebSocketPingInterval)?.value
- )
- : 0
+ const webSocketPingInterval = this.getWebSocketPingInterval()
if (webSocketPingInterval > 0 && this.wsPingSetInterval == null) {
this.wsPingSetInterval = setInterval(() => {
if (this.isWebSocketConnectionOpened()) {
this.wsConnectionRetryCount < this.stationInfo!.autoReconnectMaxRetries! ||
this.stationInfo?.autoReconnectMaxRetries === -1
) {
- this.wsConnectionRetried = true
++this.wsConnectionRetryCount
const reconnectDelay =
this.stationInfo?.reconnectExponentialDelay === true
)
} else if (this.stationInfo?.autoReconnectMaxRetries !== -1) {
logger.error(
- `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${
- this.wsConnectionRetryCount
- }) or retries disabled (${this.stationInfo?.autoReconnectMaxRetries})`
+ `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${this.wsConnectionRetryCount.toString()}) or retries disabled (${this.stationInfo?.autoReconnectMaxRetries?.toString()})`
)
}
}