| 1 | // Partial Copyright Jerome Benoit. 2021. All Rights Reserved. |
| 2 | |
| 3 | import { ACElectricUtils, DCElectricUtils } from '../utils/ElectricUtils'; |
| 4 | import { |
| 5 | AvailabilityType, |
| 6 | BootNotificationRequest, |
| 7 | CachedRequest, |
| 8 | HeartbeatRequest, |
| 9 | IncomingRequest, |
| 10 | IncomingRequestCommand, |
| 11 | MeterValuesRequest, |
| 12 | RequestCommand, |
| 13 | StatusNotificationRequest, |
| 14 | } from '../types/ocpp/Requests'; |
| 15 | import { |
| 16 | BootNotificationResponse, |
| 17 | ErrorResponse, |
| 18 | HeartbeatResponse, |
| 19 | MeterValuesResponse, |
| 20 | RegistrationStatus, |
| 21 | Response, |
| 22 | StatusNotificationResponse, |
| 23 | } from '../types/ocpp/Responses'; |
| 24 | import { |
| 25 | ChargingProfile, |
| 26 | ChargingRateUnitType, |
| 27 | ChargingSchedulePeriod, |
| 28 | } from '../types/ocpp/ChargingProfile'; |
| 29 | import ChargingStationConfiguration, { Section } from '../types/ChargingStationConfiguration'; |
| 30 | import ChargingStationOcppConfiguration, { |
| 31 | ConfigurationKey, |
| 32 | } from '../types/ChargingStationOcppConfiguration'; |
| 33 | import ChargingStationTemplate, { |
| 34 | AmpereUnits, |
| 35 | CurrentType, |
| 36 | PowerUnits, |
| 37 | Voltage, |
| 38 | WsOptions, |
| 39 | } from '../types/ChargingStationTemplate'; |
| 40 | import { |
| 41 | ConnectorPhaseRotation, |
| 42 | StandardParametersKey, |
| 43 | SupportedFeatureProfiles, |
| 44 | VendorDefaultParametersKey, |
| 45 | } from '../types/ocpp/Configuration'; |
| 46 | import { MeterValue, MeterValueMeasurand, MeterValuePhase } from '../types/ocpp/MeterValues'; |
| 47 | import { |
| 48 | StopTransactionReason, |
| 49 | StopTransactionRequest, |
| 50 | StopTransactionResponse, |
| 51 | } from '../types/ocpp/Transaction'; |
| 52 | import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket'; |
| 53 | import WebSocket, { Data, OPEN, RawData } from 'ws'; |
| 54 | |
| 55 | import AutomaticTransactionGenerator from './AutomaticTransactionGenerator'; |
| 56 | import { ChargePointErrorCode } from '../types/ocpp/ChargePointErrorCode'; |
| 57 | import { ChargePointStatus } from '../types/ocpp/ChargePointStatus'; |
| 58 | import ChargingStationInfo from '../types/ChargingStationInfo'; |
| 59 | import { ChargingStationWorkerMessageEvents } from '../types/ChargingStationWorker'; |
| 60 | import Configuration from '../utils/Configuration'; |
| 61 | import { ConnectorStatus } from '../types/ConnectorStatus'; |
| 62 | import Constants from '../utils/Constants'; |
| 63 | import { ErrorType } from '../types/ocpp/ErrorType'; |
| 64 | import { FileType } from '../types/FileType'; |
| 65 | import FileUtils from '../utils/FileUtils'; |
| 66 | import { JsonType } from '../types/JsonType'; |
| 67 | import { MessageType } from '../types/ocpp/MessageType'; |
| 68 | import OCPP16IncomingRequestService from './ocpp/1.6/OCPP16IncomingRequestService'; |
| 69 | import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService'; |
| 70 | import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService'; |
| 71 | import { OCPP16ServiceUtils } from './ocpp/1.6/OCPP16ServiceUtils'; |
| 72 | import OCPPError from '../exception/OCPPError'; |
| 73 | import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService'; |
| 74 | import OCPPRequestService from './ocpp/OCPPRequestService'; |
| 75 | import { OCPPVersion } from '../types/ocpp/OCPPVersion'; |
| 76 | import PerformanceStatistics from '../performance/PerformanceStatistics'; |
| 77 | import { SampledValueTemplate } from '../types/MeasurandPerPhaseSampledValueTemplates'; |
| 78 | import { SupervisionUrlDistribution } from '../types/ConfigurationData'; |
| 79 | import { URL } from 'url'; |
| 80 | import Utils from '../utils/Utils'; |
| 81 | import crypto from 'crypto'; |
| 82 | import fs from 'fs'; |
| 83 | import logger from '../utils/Logger'; |
| 84 | import { parentPort } from 'worker_threads'; |
| 85 | import path from 'path'; |
| 86 | |
| 87 | export default class ChargingStation { |
| 88 | public hashId!: string; |
| 89 | public readonly templateFile: string; |
| 90 | public authorizedTags: string[]; |
| 91 | public stationInfo!: ChargingStationInfo; |
| 92 | public readonly connectors: Map<number, ConnectorStatus>; |
| 93 | public ocppConfiguration!: ChargingStationOcppConfiguration; |
| 94 | public wsConnection!: WebSocket; |
| 95 | public readonly requests: Map<string, CachedRequest>; |
| 96 | public performanceStatistics!: PerformanceStatistics; |
| 97 | public heartbeatSetInterval!: NodeJS.Timeout; |
| 98 | public ocppRequestService!: OCPPRequestService; |
| 99 | public bootNotificationResponse!: BootNotificationResponse | null; |
| 100 | private readonly index: number; |
| 101 | private configurationFile!: string; |
| 102 | private bootNotificationRequest!: BootNotificationRequest; |
| 103 | private connectorsConfigurationHash!: string; |
| 104 | private ocppIncomingRequestService!: OCPPIncomingRequestService; |
| 105 | private readonly messageBuffer: Set<string>; |
| 106 | private wsConfiguredConnectionUrl!: URL; |
| 107 | private wsConnectionRestarted: boolean; |
| 108 | private stopped: boolean; |
| 109 | private autoReconnectRetryCount: number; |
| 110 | private automaticTransactionGenerator!: AutomaticTransactionGenerator; |
| 111 | private webSocketPingSetInterval!: NodeJS.Timeout; |
| 112 | |
| 113 | constructor(index: number, templateFile: string) { |
| 114 | this.index = index; |
| 115 | this.templateFile = templateFile; |
| 116 | this.stopped = false; |
| 117 | this.wsConnectionRestarted = false; |
| 118 | this.autoReconnectRetryCount = 0; |
| 119 | this.connectors = new Map<number, ConnectorStatus>(); |
| 120 | this.requests = new Map<string, CachedRequest>(); |
| 121 | this.messageBuffer = new Set<string>(); |
| 122 | this.initialize(); |
| 123 | this.authorizedTags = this.getAuthorizedTags(); |
| 124 | } |
| 125 | |
| 126 | private get wsConnectionUrl(): URL { |
| 127 | return this.getSupervisionUrlOcppConfiguration() |
| 128 | ? new URL( |
| 129 | this.getConfigurationKey(this.getSupervisionUrlOcppKey()).value + |
| 130 | '/' + |
| 131 | this.stationInfo.chargingStationId |
| 132 | ) |
| 133 | : this.wsConfiguredConnectionUrl; |
| 134 | } |
| 135 | |
| 136 | public logPrefix(): string { |
| 137 | return Utils.logPrefix(` ${this.stationInfo.chargingStationId} |`); |
| 138 | } |
| 139 | |
| 140 | public getBootNotificationRequest(): BootNotificationRequest { |
| 141 | return this.bootNotificationRequest; |
| 142 | } |
| 143 | |
| 144 | public getRandomIdTag(): string { |
| 145 | const index = Math.floor(Utils.secureRandom() * this.authorizedTags.length); |
| 146 | return this.authorizedTags[index]; |
| 147 | } |
| 148 | |
| 149 | public hasAuthorizedTags(): boolean { |
| 150 | return !Utils.isEmptyArray(this.authorizedTags); |
| 151 | } |
| 152 | |
| 153 | public getEnableStatistics(): boolean | undefined { |
| 154 | return !Utils.isUndefined(this.stationInfo.enableStatistics) |
| 155 | ? this.stationInfo.enableStatistics |
| 156 | : true; |
| 157 | } |
| 158 | |
| 159 | public getMayAuthorizeAtRemoteStart(): boolean | undefined { |
| 160 | return this.stationInfo.mayAuthorizeAtRemoteStart ?? true; |
| 161 | } |
| 162 | |
| 163 | public getNumberOfPhases(): number | undefined { |
| 164 | switch (this.getCurrentOutType()) { |
| 165 | case CurrentType.AC: |
| 166 | return !Utils.isUndefined(this.stationInfo.numberOfPhases) |
| 167 | ? this.stationInfo.numberOfPhases |
| 168 | : 3; |
| 169 | case CurrentType.DC: |
| 170 | return 0; |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | public isWebSocketConnectionOpened(): boolean { |
| 175 | return this?.wsConnection?.readyState === OPEN; |
| 176 | } |
| 177 | |
| 178 | public getRegistrationStatus(): RegistrationStatus { |
| 179 | return this?.bootNotificationResponse?.status; |
| 180 | } |
| 181 | |
| 182 | public isInUnknownState(): boolean { |
| 183 | return Utils.isNullOrUndefined(this?.bootNotificationResponse?.status); |
| 184 | } |
| 185 | |
| 186 | public isInPendingState(): boolean { |
| 187 | return this?.bootNotificationResponse?.status === RegistrationStatus.PENDING; |
| 188 | } |
| 189 | |
| 190 | public isInAcceptedState(): boolean { |
| 191 | return this?.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED; |
| 192 | } |
| 193 | |
| 194 | public isInRejectedState(): boolean { |
| 195 | return this?.bootNotificationResponse?.status === RegistrationStatus.REJECTED; |
| 196 | } |
| 197 | |
| 198 | public isRegistered(): boolean { |
| 199 | return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState()); |
| 200 | } |
| 201 | |
| 202 | public isChargingStationAvailable(): boolean { |
| 203 | return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE; |
| 204 | } |
| 205 | |
| 206 | public isConnectorAvailable(id: number): boolean { |
| 207 | return id > 0 && this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE; |
| 208 | } |
| 209 | |
| 210 | public getNumberOfConnectors(): number { |
| 211 | return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size; |
| 212 | } |
| 213 | |
| 214 | public getConnectorStatus(id: number): ConnectorStatus { |
| 215 | return this.connectors.get(id); |
| 216 | } |
| 217 | |
| 218 | public getCurrentOutType(): CurrentType | undefined { |
| 219 | return this.stationInfo.currentOutType ?? CurrentType.AC; |
| 220 | } |
| 221 | |
| 222 | public getOcppStrictCompliance(): boolean { |
| 223 | return this.stationInfo.ocppStrictCompliance ?? false; |
| 224 | } |
| 225 | |
| 226 | public getVoltageOut(): number | undefined { |
| 227 | const errMsg = `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${ |
| 228 | this.templateFile |
| 229 | }, cannot define default voltage out`; |
| 230 | let defaultVoltageOut: number; |
| 231 | switch (this.getCurrentOutType()) { |
| 232 | case CurrentType.AC: |
| 233 | defaultVoltageOut = Voltage.VOLTAGE_230; |
| 234 | break; |
| 235 | case CurrentType.DC: |
| 236 | defaultVoltageOut = Voltage.VOLTAGE_400; |
| 237 | break; |
| 238 | default: |
| 239 | logger.error(errMsg); |
| 240 | throw new Error(errMsg); |
| 241 | } |
| 242 | return !Utils.isUndefined(this.stationInfo.voltageOut) |
| 243 | ? this.stationInfo.voltageOut |
| 244 | : defaultVoltageOut; |
| 245 | } |
| 246 | |
| 247 | public getConnectorMaximumAvailablePower(connectorId: number): number { |
| 248 | let connectorAmperageLimitationPowerLimit: number; |
| 249 | if ( |
| 250 | !Utils.isNullOrUndefined(this.getAmperageLimitation()) && |
| 251 | this.getAmperageLimitation() < this.stationInfo.maximumAmperage |
| 252 | ) { |
| 253 | connectorAmperageLimitationPowerLimit = |
| 254 | (this.getCurrentOutType() === CurrentType.AC |
| 255 | ? ACElectricUtils.powerTotal( |
| 256 | this.getNumberOfPhases(), |
| 257 | this.getVoltageOut(), |
| 258 | this.getAmperageLimitation() * this.getNumberOfConnectors() |
| 259 | ) |
| 260 | : DCElectricUtils.power(this.getVoltageOut(), this.getAmperageLimitation())) / |
| 261 | this.stationInfo.powerDivider; |
| 262 | } |
| 263 | const connectorMaximumPower = this.getMaximumPower() / this.stationInfo.powerDivider; |
| 264 | const connectorChargingProfilePowerLimit = this.getChargingProfilePowerLimit(connectorId); |
| 265 | return Math.min( |
| 266 | isNaN(connectorMaximumPower) ? Infinity : connectorMaximumPower, |
| 267 | isNaN(connectorAmperageLimitationPowerLimit) |
| 268 | ? Infinity |
| 269 | : connectorAmperageLimitationPowerLimit, |
| 270 | isNaN(connectorChargingProfilePowerLimit) ? Infinity : connectorChargingProfilePowerLimit |
| 271 | ); |
| 272 | } |
| 273 | |
| 274 | public getTransactionIdTag(transactionId: number): string | undefined { |
| 275 | for (const connectorId of this.connectors.keys()) { |
| 276 | if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) { |
| 277 | return this.getConnectorStatus(connectorId).transactionIdTag; |
| 278 | } |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | public getOutOfOrderEndMeterValues(): boolean { |
| 283 | return this.stationInfo.outOfOrderEndMeterValues ?? false; |
| 284 | } |
| 285 | |
| 286 | public getBeginEndMeterValues(): boolean { |
| 287 | return this.stationInfo.beginEndMeterValues ?? false; |
| 288 | } |
| 289 | |
| 290 | public getMeteringPerTransaction(): boolean { |
| 291 | return this.stationInfo.meteringPerTransaction ?? true; |
| 292 | } |
| 293 | |
| 294 | public getTransactionDataMeterValues(): boolean { |
| 295 | return this.stationInfo.transactionDataMeterValues ?? false; |
| 296 | } |
| 297 | |
| 298 | public getMainVoltageMeterValues(): boolean { |
| 299 | return this.stationInfo.mainVoltageMeterValues ?? true; |
| 300 | } |
| 301 | |
| 302 | public getPhaseLineToLineVoltageMeterValues(): boolean { |
| 303 | return this.stationInfo.phaseLineToLineVoltageMeterValues ?? false; |
| 304 | } |
| 305 | |
| 306 | public getConnectorIdByTransactionId(transactionId: number): number | undefined { |
| 307 | for (const connectorId of this.connectors.keys()) { |
| 308 | if ( |
| 309 | connectorId > 0 && |
| 310 | this.getConnectorStatus(connectorId)?.transactionId === transactionId |
| 311 | ) { |
| 312 | return connectorId; |
| 313 | } |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined { |
| 318 | const transactionConnectorStatus = this.getConnectorStatus( |
| 319 | this.getConnectorIdByTransactionId(transactionId) |
| 320 | ); |
| 321 | if (this.getMeteringPerTransaction()) { |
| 322 | return transactionConnectorStatus?.transactionEnergyActiveImportRegisterValue; |
| 323 | } |
| 324 | return transactionConnectorStatus?.energyActiveImportRegisterValue; |
| 325 | } |
| 326 | |
| 327 | public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined { |
| 328 | const connectorStatus = this.getConnectorStatus(connectorId); |
| 329 | if (this.getMeteringPerTransaction()) { |
| 330 | return connectorStatus?.transactionEnergyActiveImportRegisterValue; |
| 331 | } |
| 332 | return connectorStatus?.energyActiveImportRegisterValue; |
| 333 | } |
| 334 | |
| 335 | public getAuthorizeRemoteTxRequests(): boolean { |
| 336 | const authorizeRemoteTxRequests = this.getConfigurationKey( |
| 337 | StandardParametersKey.AuthorizeRemoteTxRequests |
| 338 | ); |
| 339 | return authorizeRemoteTxRequests |
| 340 | ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) |
| 341 | : false; |
| 342 | } |
| 343 | |
| 344 | public getLocalAuthListEnabled(): boolean { |
| 345 | const localAuthListEnabled = this.getConfigurationKey( |
| 346 | StandardParametersKey.LocalAuthListEnabled |
| 347 | ); |
| 348 | return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false; |
| 349 | } |
| 350 | |
| 351 | public restartWebSocketPing(): void { |
| 352 | // Stop WebSocket ping |
| 353 | this.stopWebSocketPing(); |
| 354 | // Start WebSocket ping |
| 355 | this.startWebSocketPing(); |
| 356 | } |
| 357 | |
| 358 | public getSampledValueTemplate( |
| 359 | connectorId: number, |
| 360 | measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER, |
| 361 | phase?: MeterValuePhase |
| 362 | ): SampledValueTemplate | undefined { |
| 363 | const onPhaseStr = phase ? `on phase ${phase} ` : ''; |
| 364 | if (!Constants.SUPPORTED_MEASURANDS.includes(measurand)) { |
| 365 | logger.warn( |
| 366 | `${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}` |
| 367 | ); |
| 368 | return; |
| 369 | } |
| 370 | if ( |
| 371 | measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && |
| 372 | !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)?.value.includes( |
| 373 | measurand |
| 374 | ) |
| 375 | ) { |
| 376 | logger.debug( |
| 377 | `${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${ |
| 378 | StandardParametersKey.MeterValuesSampledData |
| 379 | }' OCPP parameter` |
| 380 | ); |
| 381 | return; |
| 382 | } |
| 383 | const sampledValueTemplates: SampledValueTemplate[] = |
| 384 | this.getConnectorStatus(connectorId).MeterValues; |
| 385 | for ( |
| 386 | let index = 0; |
| 387 | !Utils.isEmptyArray(sampledValueTemplates) && index < sampledValueTemplates.length; |
| 388 | index++ |
| 389 | ) { |
| 390 | if ( |
| 391 | !Constants.SUPPORTED_MEASURANDS.includes( |
| 392 | sampledValueTemplates[index]?.measurand ?? |
| 393 | MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER |
| 394 | ) |
| 395 | ) { |
| 396 | logger.warn( |
| 397 | `${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}` |
| 398 | ); |
| 399 | } else if ( |
| 400 | phase && |
| 401 | sampledValueTemplates[index]?.phase === phase && |
| 402 | sampledValueTemplates[index]?.measurand === measurand && |
| 403 | this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)?.value.includes( |
| 404 | measurand |
| 405 | ) |
| 406 | ) { |
| 407 | return sampledValueTemplates[index]; |
| 408 | } else if ( |
| 409 | !phase && |
| 410 | !sampledValueTemplates[index].phase && |
| 411 | sampledValueTemplates[index]?.measurand === measurand && |
| 412 | this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)?.value.includes( |
| 413 | measurand |
| 414 | ) |
| 415 | ) { |
| 416 | return sampledValueTemplates[index]; |
| 417 | } else if ( |
| 418 | measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && |
| 419 | (!sampledValueTemplates[index].measurand || |
| 420 | sampledValueTemplates[index].measurand === measurand) |
| 421 | ) { |
| 422 | return sampledValueTemplates[index]; |
| 423 | } |
| 424 | } |
| 425 | if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) { |
| 426 | const errorMsg = `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`; |
| 427 | logger.error(errorMsg); |
| 428 | throw new Error(errorMsg); |
| 429 | } |
| 430 | logger.debug( |
| 431 | `${this.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}` |
| 432 | ); |
| 433 | } |
| 434 | |
| 435 | public getAutomaticTransactionGeneratorRequireAuthorize(): boolean { |
| 436 | return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true; |
| 437 | } |
| 438 | |
| 439 | public startHeartbeat(): void { |
| 440 | if ( |
| 441 | this.getHeartbeatInterval() && |
| 442 | this.getHeartbeatInterval() > 0 && |
| 443 | !this.heartbeatSetInterval |
| 444 | ) { |
| 445 | // eslint-disable-next-line @typescript-eslint/no-misused-promises |
| 446 | this.heartbeatSetInterval = setInterval(async (): Promise<void> => { |
| 447 | await this.ocppRequestService.requestHandler<HeartbeatRequest, HeartbeatResponse>( |
| 448 | RequestCommand.HEARTBEAT |
| 449 | ); |
| 450 | }, this.getHeartbeatInterval()); |
| 451 | logger.info( |
| 452 | this.logPrefix() + |
| 453 | ' Heartbeat started every ' + |
| 454 | Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) |
| 455 | ); |
| 456 | } else if (this.heartbeatSetInterval) { |
| 457 | logger.info( |
| 458 | this.logPrefix() + |
| 459 | ' Heartbeat already started every ' + |
| 460 | Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) |
| 461 | ); |
| 462 | } else { |
| 463 | logger.error( |
| 464 | `${this.logPrefix()} Heartbeat interval set to ${ |
| 465 | this.getHeartbeatInterval() |
| 466 | ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval()) |
| 467 | : this.getHeartbeatInterval() |
| 468 | }, not starting the heartbeat` |
| 469 | ); |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | public restartHeartbeat(): void { |
| 474 | // Stop heartbeat |
| 475 | this.stopHeartbeat(); |
| 476 | // Start heartbeat |
| 477 | this.startHeartbeat(); |
| 478 | } |
| 479 | |
| 480 | public startMeterValues(connectorId: number, interval: number): void { |
| 481 | if (connectorId === 0) { |
| 482 | logger.error( |
| 483 | `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}` |
| 484 | ); |
| 485 | return; |
| 486 | } |
| 487 | if (!this.getConnectorStatus(connectorId)) { |
| 488 | logger.error( |
| 489 | `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}` |
| 490 | ); |
| 491 | return; |
| 492 | } |
| 493 | if (!this.getConnectorStatus(connectorId)?.transactionStarted) { |
| 494 | logger.error( |
| 495 | `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started` |
| 496 | ); |
| 497 | return; |
| 498 | } else if ( |
| 499 | this.getConnectorStatus(connectorId)?.transactionStarted && |
| 500 | !this.getConnectorStatus(connectorId)?.transactionId |
| 501 | ) { |
| 502 | logger.error( |
| 503 | `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id` |
| 504 | ); |
| 505 | return; |
| 506 | } |
| 507 | if (interval > 0) { |
| 508 | // eslint-disable-next-line @typescript-eslint/no-misused-promises |
| 509 | this.getConnectorStatus(connectorId).transactionSetInterval = setInterval( |
| 510 | // eslint-disable-next-line @typescript-eslint/no-misused-promises |
| 511 | async (): Promise<void> => { |
| 512 | // FIXME: Implement OCPP version agnostic helpers |
| 513 | const meterValue: MeterValue = OCPP16ServiceUtils.buildMeterValue( |
| 514 | this, |
| 515 | connectorId, |
| 516 | this.getConnectorStatus(connectorId).transactionId, |
| 517 | interval |
| 518 | ); |
| 519 | await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>( |
| 520 | RequestCommand.METER_VALUES, |
| 521 | { |
| 522 | connectorId, |
| 523 | transactionId: this.getConnectorStatus(connectorId).transactionId, |
| 524 | meterValue: [meterValue], |
| 525 | } |
| 526 | ); |
| 527 | }, |
| 528 | interval |
| 529 | ); |
| 530 | } else { |
| 531 | logger.error( |
| 532 | `${this.logPrefix()} Charging station ${ |
| 533 | StandardParametersKey.MeterValueSampleInterval |
| 534 | } configuration set to ${ |
| 535 | interval ? Utils.formatDurationMilliSeconds(interval) : interval |
| 536 | }, not sending MeterValues` |
| 537 | ); |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | public start(): void { |
| 542 | if (this.getEnableStatistics()) { |
| 543 | this.performanceStatistics.start(); |
| 544 | } |
| 545 | this.openWSConnection(); |
| 546 | // Handle WebSocket message |
| 547 | this.wsConnection.on( |
| 548 | 'message', |
| 549 | this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void |
| 550 | ); |
| 551 | // Handle WebSocket error |
| 552 | this.wsConnection.on( |
| 553 | 'error', |
| 554 | this.onError.bind(this) as (this: WebSocket, error: Error) => void |
| 555 | ); |
| 556 | // Handle WebSocket close |
| 557 | this.wsConnection.on( |
| 558 | 'close', |
| 559 | this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void |
| 560 | ); |
| 561 | // Handle WebSocket open |
| 562 | this.wsConnection.on('open', this.onOpen.bind(this) as (this: WebSocket) => void); |
| 563 | // Handle WebSocket ping |
| 564 | this.wsConnection.on('ping', this.onPing.bind(this) as (this: WebSocket, data: Buffer) => void); |
| 565 | // Handle WebSocket pong |
| 566 | this.wsConnection.on('pong', this.onPong.bind(this) as (this: WebSocket, data: Buffer) => void); |
| 567 | // Monitor authorization file |
| 568 | FileUtils.watchJsonFile<string[]>( |
| 569 | this.logPrefix(), |
| 570 | FileType.Authorization, |
| 571 | this.getAuthorizationFile(), |
| 572 | this.authorizedTags |
| 573 | ); |
| 574 | // Monitor charging station template file |
| 575 | FileUtils.watchJsonFile( |
| 576 | this.logPrefix(), |
| 577 | FileType.ChargingStationTemplate, |
| 578 | this.templateFile, |
| 579 | null, |
| 580 | (event, filename): void => { |
| 581 | if (filename && event === 'change') { |
| 582 | try { |
| 583 | logger.debug( |
| 584 | `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${ |
| 585 | this.templateFile |
| 586 | } file have changed, reload` |
| 587 | ); |
| 588 | // Initialize |
| 589 | this.initialize(); |
| 590 | // Restart the ATG |
| 591 | if ( |
| 592 | !this.stationInfo.AutomaticTransactionGenerator.enable && |
| 593 | this.automaticTransactionGenerator |
| 594 | ) { |
| 595 | this.automaticTransactionGenerator.stop(); |
| 596 | } |
| 597 | this.startAutomaticTransactionGenerator(); |
| 598 | if (this.getEnableStatistics()) { |
| 599 | this.performanceStatistics.restart(); |
| 600 | } else { |
| 601 | this.performanceStatistics.stop(); |
| 602 | } |
| 603 | // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed |
| 604 | } catch (error) { |
| 605 | logger.error( |
| 606 | `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`, |
| 607 | error |
| 608 | ); |
| 609 | } |
| 610 | } |
| 611 | } |
| 612 | ); |
| 613 | parentPort.postMessage({ |
| 614 | id: ChargingStationWorkerMessageEvents.STARTED, |
| 615 | data: { id: this.stationInfo.chargingStationId }, |
| 616 | }); |
| 617 | } |
| 618 | |
| 619 | public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> { |
| 620 | // Stop message sequence |
| 621 | await this.stopMessageSequence(reason); |
| 622 | for (const connectorId of this.connectors.keys()) { |
| 623 | if (connectorId > 0) { |
| 624 | await this.ocppRequestService.requestHandler< |
| 625 | StatusNotificationRequest, |
| 626 | StatusNotificationResponse |
| 627 | >(RequestCommand.STATUS_NOTIFICATION, { |
| 628 | connectorId, |
| 629 | status: ChargePointStatus.UNAVAILABLE, |
| 630 | errorCode: ChargePointErrorCode.NO_ERROR, |
| 631 | }); |
| 632 | this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE; |
| 633 | } |
| 634 | } |
| 635 | if (this.isWebSocketConnectionOpened()) { |
| 636 | this.wsConnection.close(); |
| 637 | } |
| 638 | if (this.getEnableStatistics()) { |
| 639 | this.performanceStatistics.stop(); |
| 640 | } |
| 641 | this.bootNotificationResponse = null; |
| 642 | parentPort.postMessage({ |
| 643 | id: ChargingStationWorkerMessageEvents.STOPPED, |
| 644 | data: { id: this.stationInfo.chargingStationId }, |
| 645 | }); |
| 646 | this.stopped = true; |
| 647 | } |
| 648 | |
| 649 | public getConfigurationKey( |
| 650 | key: string | StandardParametersKey, |
| 651 | caseInsensitive = false |
| 652 | ): ConfigurationKey | undefined { |
| 653 | return this.ocppConfiguration.configurationKey.find((configElement) => { |
| 654 | if (caseInsensitive) { |
| 655 | return configElement.key.toLowerCase() === key.toLowerCase(); |
| 656 | } |
| 657 | return configElement.key === key; |
| 658 | }); |
| 659 | } |
| 660 | |
| 661 | public addConfigurationKey( |
| 662 | key: string | StandardParametersKey, |
| 663 | value: string, |
| 664 | options: { readonly?: boolean; visible?: boolean; reboot?: boolean } = { |
| 665 | readonly: false, |
| 666 | visible: true, |
| 667 | reboot: false, |
| 668 | }, |
| 669 | params: { overwrite?: boolean; save?: boolean } = { overwrite: false, save: false } |
| 670 | ): void { |
| 671 | options = options ?? ({} as { readonly?: boolean; visible?: boolean; reboot?: boolean }); |
| 672 | options.readonly = options?.readonly ?? false; |
| 673 | options.visible = options?.visible ?? true; |
| 674 | options.reboot = options?.reboot ?? false; |
| 675 | let keyFound = this.getConfigurationKey(key); |
| 676 | if (keyFound && params?.overwrite) { |
| 677 | this.deleteConfigurationKey(keyFound.key, { save: false }); |
| 678 | keyFound = undefined; |
| 679 | } |
| 680 | if (!keyFound) { |
| 681 | this.ocppConfiguration.configurationKey.push({ |
| 682 | key, |
| 683 | readonly: options.readonly, |
| 684 | value, |
| 685 | visible: options.visible, |
| 686 | reboot: options.reboot, |
| 687 | }); |
| 688 | params?.save && this.saveOcppConfiguration(); |
| 689 | } else { |
| 690 | logger.error( |
| 691 | `${this.logPrefix()} Trying to add an already existing configuration key: %j`, |
| 692 | keyFound |
| 693 | ); |
| 694 | } |
| 695 | } |
| 696 | |
| 697 | public setConfigurationKeyValue( |
| 698 | key: string | StandardParametersKey, |
| 699 | value: string, |
| 700 | caseInsensitive = false |
| 701 | ): void { |
| 702 | const keyFound = this.getConfigurationKey(key, caseInsensitive); |
| 703 | if (keyFound) { |
| 704 | this.ocppConfiguration.configurationKey[ |
| 705 | this.ocppConfiguration.configurationKey.indexOf(keyFound) |
| 706 | ].value = value; |
| 707 | this.saveOcppConfiguration(); |
| 708 | } else { |
| 709 | logger.error( |
| 710 | `${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, |
| 711 | { key, value } |
| 712 | ); |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | public deleteConfigurationKey( |
| 717 | key: string | StandardParametersKey, |
| 718 | params: { save?: boolean; caseInsensitive?: boolean } = { save: true, caseInsensitive: false } |
| 719 | ): ConfigurationKey[] { |
| 720 | const keyFound = this.getConfigurationKey(key, params?.caseInsensitive); |
| 721 | if (keyFound) { |
| 722 | const deletedConfigurationKey = this.ocppConfiguration.configurationKey.splice( |
| 723 | this.ocppConfiguration.configurationKey.indexOf(keyFound), |
| 724 | 1 |
| 725 | ); |
| 726 | params?.save && this.saveOcppConfiguration(); |
| 727 | return deletedConfigurationKey; |
| 728 | } |
| 729 | } |
| 730 | |
| 731 | public getChargingProfilePowerLimit(connectorId: number): number | undefined { |
| 732 | const timestamp = new Date().getTime(); |
| 733 | let matchingChargingProfile: ChargingProfile; |
| 734 | let chargingSchedulePeriods: ChargingSchedulePeriod[] = []; |
| 735 | if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId)?.chargingProfiles)) { |
| 736 | const chargingProfiles: ChargingProfile[] = this.getConnectorStatus( |
| 737 | connectorId |
| 738 | ).chargingProfiles.filter( |
| 739 | (chargingProfile) => |
| 740 | timestamp >= chargingProfile.chargingSchedule?.startSchedule.getTime() && |
| 741 | timestamp < |
| 742 | chargingProfile.chargingSchedule?.startSchedule.getTime() + |
| 743 | chargingProfile.chargingSchedule.duration * 1000 && |
| 744 | chargingProfile?.stackLevel === Math.max(...chargingProfiles.map((cp) => cp?.stackLevel)) |
| 745 | ); |
| 746 | if (!Utils.isEmptyArray(chargingProfiles)) { |
| 747 | for (const chargingProfile of chargingProfiles) { |
| 748 | if (!Utils.isEmptyArray(chargingProfile.chargingSchedule.chargingSchedulePeriod)) { |
| 749 | chargingSchedulePeriods = |
| 750 | chargingProfile.chargingSchedule.chargingSchedulePeriod.filter( |
| 751 | (chargingSchedulePeriod, index) => { |
| 752 | timestamp >= |
| 753 | chargingProfile.chargingSchedule.startSchedule.getTime() + |
| 754 | chargingSchedulePeriod.startPeriod * 1000 && |
| 755 | ((chargingProfile.chargingSchedule.chargingSchedulePeriod[index + 1] && |
| 756 | timestamp < |
| 757 | chargingProfile.chargingSchedule.startSchedule.getTime() + |
| 758 | chargingProfile.chargingSchedule.chargingSchedulePeriod[index + 1] |
| 759 | ?.startPeriod * |
| 760 | 1000) || |
| 761 | !chargingProfile.chargingSchedule.chargingSchedulePeriod[index + 1]); |
| 762 | } |
| 763 | ); |
| 764 | if (!Utils.isEmptyArray(chargingSchedulePeriods)) { |
| 765 | matchingChargingProfile = chargingProfile; |
| 766 | break; |
| 767 | } |
| 768 | } |
| 769 | } |
| 770 | } |
| 771 | } |
| 772 | let limit: number; |
| 773 | if (!Utils.isEmptyArray(chargingSchedulePeriods)) { |
| 774 | switch (this.getCurrentOutType()) { |
| 775 | case CurrentType.AC: |
| 776 | limit = |
| 777 | matchingChargingProfile.chargingSchedule.chargingRateUnit === ChargingRateUnitType.WATT |
| 778 | ? chargingSchedulePeriods[0].limit |
| 779 | : ACElectricUtils.powerTotal( |
| 780 | this.getNumberOfPhases(), |
| 781 | this.getVoltageOut(), |
| 782 | chargingSchedulePeriods[0].limit |
| 783 | ); |
| 784 | break; |
| 785 | case CurrentType.DC: |
| 786 | limit = |
| 787 | matchingChargingProfile.chargingSchedule.chargingRateUnit === ChargingRateUnitType.WATT |
| 788 | ? chargingSchedulePeriods[0].limit |
| 789 | : DCElectricUtils.power(this.getVoltageOut(), chargingSchedulePeriods[0].limit); |
| 790 | } |
| 791 | } |
| 792 | const connectorMaximumPower = this.getMaximumPower() / this.stationInfo.powerDivider; |
| 793 | if (limit > connectorMaximumPower) { |
| 794 | logger.error( |
| 795 | `${this.logPrefix()} Charging profile id ${ |
| 796 | matchingChargingProfile.chargingProfileId |
| 797 | } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`, |
| 798 | this.getConnectorStatus(connectorId).chargingProfiles |
| 799 | ); |
| 800 | limit = connectorMaximumPower; |
| 801 | } |
| 802 | return limit; |
| 803 | } |
| 804 | |
| 805 | public setChargingProfile(connectorId: number, cp: ChargingProfile): void { |
| 806 | let cpReplaced = false; |
| 807 | if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) { |
| 808 | this.getConnectorStatus(connectorId).chargingProfiles?.forEach( |
| 809 | (chargingProfile: ChargingProfile, index: number) => { |
| 810 | if ( |
| 811 | chargingProfile.chargingProfileId === cp.chargingProfileId || |
| 812 | (chargingProfile.stackLevel === cp.stackLevel && |
| 813 | chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose) |
| 814 | ) { |
| 815 | this.getConnectorStatus(connectorId).chargingProfiles[index] = cp; |
| 816 | cpReplaced = true; |
| 817 | } |
| 818 | } |
| 819 | ); |
| 820 | } |
| 821 | !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp); |
| 822 | } |
| 823 | |
| 824 | public resetConnectorStatus(connectorId: number): void { |
| 825 | this.getConnectorStatus(connectorId).idTagLocalAuthorized = false; |
| 826 | this.getConnectorStatus(connectorId).idTagAuthorized = false; |
| 827 | this.getConnectorStatus(connectorId).transactionRemoteStarted = false; |
| 828 | this.getConnectorStatus(connectorId).transactionStarted = false; |
| 829 | delete this.getConnectorStatus(connectorId).localAuthorizeIdTag; |
| 830 | delete this.getConnectorStatus(connectorId).authorizeIdTag; |
| 831 | delete this.getConnectorStatus(connectorId).transactionId; |
| 832 | delete this.getConnectorStatus(connectorId).transactionIdTag; |
| 833 | this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0; |
| 834 | delete this.getConnectorStatus(connectorId).transactionBeginMeterValue; |
| 835 | this.stopMeterValues(connectorId); |
| 836 | } |
| 837 | |
| 838 | public hasFeatureProfile(featureProfile: SupportedFeatureProfiles) { |
| 839 | return this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)?.value.includes( |
| 840 | featureProfile |
| 841 | ); |
| 842 | } |
| 843 | |
| 844 | public bufferMessage(message: string): void { |
| 845 | this.messageBuffer.add(message); |
| 846 | } |
| 847 | |
| 848 | private flushMessageBuffer() { |
| 849 | if (this.messageBuffer.size > 0) { |
| 850 | this.messageBuffer.forEach((message) => { |
| 851 | // TODO: evaluate the need to track performance |
| 852 | this.wsConnection.send(message); |
| 853 | this.messageBuffer.delete(message); |
| 854 | }); |
| 855 | } |
| 856 | } |
| 857 | |
| 858 | private getSupervisionUrlOcppConfiguration(): boolean { |
| 859 | return this.stationInfo.supervisionUrlOcppConfiguration ?? false; |
| 860 | } |
| 861 | |
| 862 | private getSupervisionUrlOcppKey(): string { |
| 863 | return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl; |
| 864 | } |
| 865 | |
| 866 | private getChargingStationId(stationTemplate: ChargingStationTemplate): string { |
| 867 | // In case of multiple instances: add instance index to charging station id |
| 868 | const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0; |
| 869 | const idSuffix = stationTemplate.nameSuffix ?? ''; |
| 870 | const idStr = '000000000' + this.index.toString(); |
| 871 | return stationTemplate.fixedName |
| 872 | ? stationTemplate.baseName |
| 873 | : stationTemplate.baseName + |
| 874 | '-' + |
| 875 | instanceIndex.toString() + |
| 876 | idStr.substring(idStr.length - 4) + |
| 877 | idSuffix; |
| 878 | } |
| 879 | |
| 880 | private getRandomSerialNumberSuffix(params?: { |
| 881 | randomBytesLength?: number; |
| 882 | upperCase?: boolean; |
| 883 | }): string { |
| 884 | const randomSerialNumberSuffix = crypto |
| 885 | .randomBytes(params?.randomBytesLength ?? 16) |
| 886 | .toString('hex'); |
| 887 | if (params?.upperCase) { |
| 888 | return randomSerialNumberSuffix.toUpperCase(); |
| 889 | } |
| 890 | return randomSerialNumberSuffix; |
| 891 | } |
| 892 | |
| 893 | private getTemplateFromFile(): ChargingStationTemplate | null { |
| 894 | let template: ChargingStationTemplate = null; |
| 895 | try { |
| 896 | const measureId = `${FileType.ChargingStationTemplate} read`; |
| 897 | const beginId = PerformanceStatistics.beginMeasure(measureId); |
| 898 | template = |
| 899 | (JSON.parse(fs.readFileSync(this.templateFile, 'utf8')) as ChargingStationTemplate) ?? |
| 900 | ({} as ChargingStationTemplate); |
| 901 | PerformanceStatistics.endMeasure(measureId, beginId); |
| 902 | template.templateHash = crypto |
| 903 | .createHash(Constants.DEFAULT_HASH_ALGORITHM) |
| 904 | .update(JSON.stringify(template)) |
| 905 | .digest('hex'); |
| 906 | } catch (error) { |
| 907 | FileUtils.handleFileException( |
| 908 | this.logPrefix(), |
| 909 | FileType.ChargingStationTemplate, |
| 910 | this.templateFile, |
| 911 | error as NodeJS.ErrnoException |
| 912 | ); |
| 913 | } |
| 914 | return template; |
| 915 | } |
| 916 | |
| 917 | private createSerialNumber( |
| 918 | stationInfo: ChargingStationInfo, |
| 919 | existingStationInfo?: ChargingStationInfo, |
| 920 | params: { randomSerialNumberUpperCase?: boolean; randomSerialNumber?: boolean } = { |
| 921 | randomSerialNumberUpperCase: true, |
| 922 | randomSerialNumber: true, |
| 923 | } |
| 924 | ): void { |
| 925 | params = params ?? {}; |
| 926 | params.randomSerialNumberUpperCase = params?.randomSerialNumberUpperCase ?? true; |
| 927 | params.randomSerialNumber = params?.randomSerialNumber ?? true; |
| 928 | if (existingStationInfo) { |
| 929 | existingStationInfo?.chargePointSerialNumber && |
| 930 | (stationInfo.chargePointSerialNumber = existingStationInfo.chargePointSerialNumber); |
| 931 | existingStationInfo?.chargeBoxSerialNumber && |
| 932 | (stationInfo.chargeBoxSerialNumber = existingStationInfo.chargeBoxSerialNumber); |
| 933 | existingStationInfo?.meterSerialNumber && |
| 934 | (stationInfo.meterSerialNumber = existingStationInfo.meterSerialNumber); |
| 935 | } else { |
| 936 | const serialNumberSuffix = params?.randomSerialNumber |
| 937 | ? this.getRandomSerialNumberSuffix({ upperCase: params.randomSerialNumberUpperCase }) |
| 938 | : ''; |
| 939 | stationInfo.chargePointSerialNumber = |
| 940 | stationInfo?.chargePointSerialNumberPrefix && |
| 941 | stationInfo.chargePointSerialNumberPrefix + serialNumberSuffix; |
| 942 | stationInfo.chargeBoxSerialNumber = |
| 943 | stationInfo?.chargeBoxSerialNumberPrefix && |
| 944 | stationInfo.chargeBoxSerialNumberPrefix + serialNumberSuffix; |
| 945 | stationInfo.meterSerialNumber = |
| 946 | stationInfo?.meterSerialNumberPrefix && |
| 947 | stationInfo.meterSerialNumberPrefix + serialNumberSuffix; |
| 948 | } |
| 949 | } |
| 950 | |
| 951 | private getStationInfoFromTemplate(): ChargingStationInfo { |
| 952 | const stationInfo: ChargingStationInfo = this.getTemplateFromFile(); |
| 953 | const chargingStationId = this.getChargingStationId(stationInfo); |
| 954 | // Deprecation template keys section |
| 955 | this.warnDeprecatedTemplateKey( |
| 956 | stationInfo, |
| 957 | 'supervisionUrl', |
| 958 | chargingStationId, |
| 959 | "Use 'supervisionUrls' instead" |
| 960 | ); |
| 961 | this.convertDeprecatedTemplateKey(stationInfo, 'supervisionUrl', 'supervisionUrls'); |
| 962 | stationInfo.wsOptions = stationInfo?.wsOptions ?? {}; |
| 963 | if (!Utils.isEmptyArray(stationInfo.power)) { |
| 964 | stationInfo.power = stationInfo.power as number[]; |
| 965 | const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationInfo.power.length); |
| 966 | stationInfo.maximumPower = |
| 967 | stationInfo.powerUnit === PowerUnits.KILO_WATT |
| 968 | ? stationInfo.power[powerArrayRandomIndex] * 1000 |
| 969 | : stationInfo.power[powerArrayRandomIndex]; |
| 970 | } else { |
| 971 | stationInfo.power = stationInfo.power as number; |
| 972 | stationInfo.maximumPower = |
| 973 | stationInfo.powerUnit === PowerUnits.KILO_WATT |
| 974 | ? stationInfo.power * 1000 |
| 975 | : stationInfo.power; |
| 976 | } |
| 977 | delete stationInfo.power; |
| 978 | delete stationInfo.powerUnit; |
| 979 | stationInfo.chargingStationId = chargingStationId; |
| 980 | stationInfo.resetTime = stationInfo.resetTime |
| 981 | ? stationInfo.resetTime * 1000 |
| 982 | : Constants.CHARGING_STATION_DEFAULT_RESET_TIME; |
| 983 | return stationInfo; |
| 984 | } |
| 985 | |
| 986 | private getStationInfoFromFile(): ChargingStationInfo { |
| 987 | const stationInfo = this.getConfigurationFromFile()?.stationInfo ?? ({} as ChargingStationInfo); |
| 988 | stationInfo.infoHash = crypto |
| 989 | .createHash(Constants.DEFAULT_HASH_ALGORITHM) |
| 990 | .update(JSON.stringify(stationInfo)) |
| 991 | .digest('hex'); |
| 992 | return stationInfo; |
| 993 | } |
| 994 | |
| 995 | private getStationInfo(): ChargingStationInfo { |
| 996 | const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate(); |
| 997 | this.hashId = this.getHashId(stationInfoFromTemplate); |
| 998 | this.configurationFile = path.join( |
| 999 | path.resolve(__dirname, '../'), |
| 1000 | 'assets', |
| 1001 | 'configurations', |
| 1002 | this.hashId + '.json' |
| 1003 | ); |
| 1004 | const stationInfoFromFile: ChargingStationInfo = this.getStationInfoFromFile(); |
| 1005 | // Priority: charging station info from template > charging station info from configuration file > charging station info attribute |
| 1006 | if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) { |
| 1007 | return stationInfoFromFile; |
| 1008 | } else if (stationInfoFromFile?.templateHash !== stationInfoFromTemplate.templateHash) { |
| 1009 | this.createSerialNumber(stationInfoFromTemplate, stationInfoFromFile); |
| 1010 | return stationInfoFromTemplate; |
| 1011 | } |
| 1012 | if (this.stationInfo?.infoHash === stationInfoFromFile?.infoHash) { |
| 1013 | return this.stationInfo; |
| 1014 | } |
| 1015 | return stationInfoFromFile; |
| 1016 | } |
| 1017 | |
| 1018 | private saveStationInfo(): void { |
| 1019 | this.saveConfiguration(Section.stationInfo); |
| 1020 | } |
| 1021 | |
| 1022 | private getOcppVersion(): OCPPVersion { |
| 1023 | return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16; |
| 1024 | } |
| 1025 | |
| 1026 | private getOcppPersistentConfiguration(): boolean { |
| 1027 | return this.stationInfo.ocppPersistentConfiguration ?? true; |
| 1028 | } |
| 1029 | |
| 1030 | private handleUnsupportedVersion(version: OCPPVersion) { |
| 1031 | const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${ |
| 1032 | this.templateFile |
| 1033 | }`; |
| 1034 | logger.error(errMsg); |
| 1035 | throw new Error(errMsg); |
| 1036 | } |
| 1037 | |
| 1038 | private createBootNotificationRequest(stationInfo: ChargingStationInfo): BootNotificationRequest { |
| 1039 | return { |
| 1040 | chargePointModel: stationInfo.chargePointModel, |
| 1041 | chargePointVendor: stationInfo.chargePointVendor, |
| 1042 | ...(!Utils.isUndefined(stationInfo.chargeBoxSerialNumber) && { |
| 1043 | chargeBoxSerialNumber: stationInfo.chargeBoxSerialNumber, |
| 1044 | }), |
| 1045 | ...(!Utils.isUndefined(stationInfo.chargePointSerialNumber) && { |
| 1046 | chargePointSerialNumber: stationInfo.chargePointSerialNumber, |
| 1047 | }), |
| 1048 | ...(!Utils.isUndefined(stationInfo.firmwareVersion) && { |
| 1049 | firmwareVersion: stationInfo.firmwareVersion, |
| 1050 | }), |
| 1051 | ...(!Utils.isUndefined(stationInfo.iccid) && { iccid: stationInfo.iccid }), |
| 1052 | ...(!Utils.isUndefined(stationInfo.imsi) && { imsi: stationInfo.imsi }), |
| 1053 | ...(!Utils.isUndefined(stationInfo.meterSerialNumber) && { |
| 1054 | meterSerialNumber: stationInfo.meterSerialNumber, |
| 1055 | }), |
| 1056 | ...(!Utils.isUndefined(stationInfo.meterType) && { |
| 1057 | meterType: stationInfo.meterType, |
| 1058 | }), |
| 1059 | }; |
| 1060 | } |
| 1061 | |
| 1062 | private getHashId(stationInfo: ChargingStationInfo): string { |
| 1063 | const hashBootNotificationRequest = { |
| 1064 | chargePointModel: stationInfo.chargePointModel, |
| 1065 | chargePointVendor: stationInfo.chargePointVendor, |
| 1066 | ...(!Utils.isUndefined(stationInfo.chargeBoxSerialNumberPrefix) && { |
| 1067 | chargeBoxSerialNumber: stationInfo.chargeBoxSerialNumberPrefix, |
| 1068 | }), |
| 1069 | ...(!Utils.isUndefined(stationInfo.chargePointSerialNumberPrefix) && { |
| 1070 | chargePointSerialNumber: stationInfo.chargePointSerialNumberPrefix, |
| 1071 | }), |
| 1072 | ...(!Utils.isUndefined(stationInfo.firmwareVersion) && { |
| 1073 | firmwareVersion: stationInfo.firmwareVersion, |
| 1074 | }), |
| 1075 | ...(!Utils.isUndefined(stationInfo.iccid) && { iccid: stationInfo.iccid }), |
| 1076 | ...(!Utils.isUndefined(stationInfo.imsi) && { imsi: stationInfo.imsi }), |
| 1077 | ...(!Utils.isUndefined(stationInfo.meterSerialNumberPrefix) && { |
| 1078 | meterSerialNumber: stationInfo.meterSerialNumberPrefix, |
| 1079 | }), |
| 1080 | ...(!Utils.isUndefined(stationInfo.meterType) && { |
| 1081 | meterType: stationInfo.meterType, |
| 1082 | }), |
| 1083 | }; |
| 1084 | return crypto |
| 1085 | .createHash(Constants.DEFAULT_HASH_ALGORITHM) |
| 1086 | .update(JSON.stringify(hashBootNotificationRequest) + stationInfo.chargingStationId) |
| 1087 | .digest('hex'); |
| 1088 | } |
| 1089 | |
| 1090 | private initialize(): void { |
| 1091 | this.stationInfo = this.getStationInfo(); |
| 1092 | logger.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`); |
| 1093 | this.bootNotificationRequest = this.createBootNotificationRequest(this.stationInfo); |
| 1094 | this.ocppConfiguration = this.getOcppConfiguration(); |
| 1095 | delete this.stationInfo.Configuration; |
| 1096 | this.wsConfiguredConnectionUrl = new URL( |
| 1097 | this.getConfiguredSupervisionUrl().href + '/' + this.stationInfo.chargingStationId |
| 1098 | ); |
| 1099 | // Build connectors if needed |
| 1100 | const maxConnectors = this.getMaxNumberOfConnectors(); |
| 1101 | if (maxConnectors <= 0) { |
| 1102 | logger.warn( |
| 1103 | `${this.logPrefix()} Charging station template ${ |
| 1104 | this.templateFile |
| 1105 | } with ${maxConnectors} connectors` |
| 1106 | ); |
| 1107 | } |
| 1108 | const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors(); |
| 1109 | if (templateMaxConnectors <= 0) { |
| 1110 | logger.warn( |
| 1111 | `${this.logPrefix()} Charging station template ${ |
| 1112 | this.templateFile |
| 1113 | } with no connector configuration` |
| 1114 | ); |
| 1115 | } |
| 1116 | if (!this.stationInfo.Connectors[0]) { |
| 1117 | logger.warn( |
| 1118 | `${this.logPrefix()} Charging station template ${ |
| 1119 | this.templateFile |
| 1120 | } with no connector Id 0 configuration` |
| 1121 | ); |
| 1122 | } |
| 1123 | // Sanity check |
| 1124 | if ( |
| 1125 | maxConnectors > |
| 1126 | (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && |
| 1127 | !this.stationInfo.randomConnectors |
| 1128 | ) { |
| 1129 | logger.warn( |
| 1130 | `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${ |
| 1131 | this.templateFile |
| 1132 | }, forcing random connector configurations affectation` |
| 1133 | ); |
| 1134 | this.stationInfo.randomConnectors = true; |
| 1135 | } |
| 1136 | const connectorsConfigHash = crypto |
| 1137 | .createHash(Constants.DEFAULT_HASH_ALGORITHM) |
| 1138 | .update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()) |
| 1139 | .digest('hex'); |
| 1140 | const connectorsConfigChanged = |
| 1141 | this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash; |
| 1142 | if (this.connectors?.size === 0 || connectorsConfigChanged) { |
| 1143 | connectorsConfigChanged && this.connectors.clear(); |
| 1144 | this.connectorsConfigurationHash = connectorsConfigHash; |
| 1145 | // Add connector Id 0 |
| 1146 | let lastConnector = '0'; |
| 1147 | for (lastConnector in this.stationInfo.Connectors) { |
| 1148 | const lastConnectorId = Utils.convertToInt(lastConnector); |
| 1149 | if ( |
| 1150 | lastConnectorId === 0 && |
| 1151 | this.getUseConnectorId0() && |
| 1152 | this.stationInfo.Connectors[lastConnector] |
| 1153 | ) { |
| 1154 | this.connectors.set( |
| 1155 | lastConnectorId, |
| 1156 | Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[lastConnector]) |
| 1157 | ); |
| 1158 | this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE; |
| 1159 | if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) { |
| 1160 | this.getConnectorStatus(lastConnectorId).chargingProfiles = []; |
| 1161 | } |
| 1162 | } |
| 1163 | } |
| 1164 | // Generate all connectors |
| 1165 | if ( |
| 1166 | (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0 |
| 1167 | ) { |
| 1168 | for (let index = 1; index <= maxConnectors; index++) { |
| 1169 | const randConnectorId = this.stationInfo.randomConnectors |
| 1170 | ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1) |
| 1171 | : index; |
| 1172 | this.connectors.set( |
| 1173 | index, |
| 1174 | Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[randConnectorId]) |
| 1175 | ); |
| 1176 | this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE; |
| 1177 | if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) { |
| 1178 | this.getConnectorStatus(index).chargingProfiles = []; |
| 1179 | } |
| 1180 | } |
| 1181 | } |
| 1182 | } |
| 1183 | this.stationInfo.maximumAmperage = this.getMaximumAmperage(); |
| 1184 | this.saveStationInfo(); |
| 1185 | // Avoid duplication of connectors related information in RAM |
| 1186 | delete this.stationInfo.Connectors; |
| 1187 | // Initialize transaction attributes on connectors |
| 1188 | for (const connectorId of this.connectors.keys()) { |
| 1189 | if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) { |
| 1190 | this.initializeConnectorStatus(connectorId); |
| 1191 | } |
| 1192 | } |
| 1193 | // OCPP configuration |
| 1194 | this.initializeOcppConfiguration(); |
| 1195 | if (this.getEnableStatistics()) { |
| 1196 | this.performanceStatistics = PerformanceStatistics.getInstance( |
| 1197 | this.hashId, |
| 1198 | this.stationInfo.chargingStationId, |
| 1199 | this.wsConnectionUrl |
| 1200 | ); |
| 1201 | } |
| 1202 | switch (this.getOcppVersion()) { |
| 1203 | case OCPPVersion.VERSION_16: |
| 1204 | this.ocppIncomingRequestService = |
| 1205 | OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>(this); |
| 1206 | this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>( |
| 1207 | this, |
| 1208 | OCPP16ResponseService.getInstance<OCPP16ResponseService>(this) |
| 1209 | ); |
| 1210 | break; |
| 1211 | default: |
| 1212 | this.handleUnsupportedVersion(this.getOcppVersion()); |
| 1213 | break; |
| 1214 | } |
| 1215 | if (this.stationInfo.autoRegister) { |
| 1216 | this.bootNotificationResponse = { |
| 1217 | currentTime: new Date().toISOString(), |
| 1218 | interval: this.getHeartbeatInterval() / 1000, |
| 1219 | status: RegistrationStatus.ACCEPTED, |
| 1220 | }; |
| 1221 | } |
| 1222 | this.stationInfo.powerDivider = this.getPowerDivider(); |
| 1223 | } |
| 1224 | |
| 1225 | private initializeOcppConfiguration(): void { |
| 1226 | if ( |
| 1227 | this.getSupervisionUrlOcppConfiguration() && |
| 1228 | !this.getConfigurationKey(this.getSupervisionUrlOcppKey()) |
| 1229 | ) { |
| 1230 | this.addConfigurationKey( |
| 1231 | this.getSupervisionUrlOcppKey(), |
| 1232 | this.getConfiguredSupervisionUrl().href, |
| 1233 | { reboot: true } |
| 1234 | ); |
| 1235 | } else if ( |
| 1236 | !this.getSupervisionUrlOcppConfiguration() && |
| 1237 | this.getConfigurationKey(this.getSupervisionUrlOcppKey()) |
| 1238 | ) { |
| 1239 | this.deleteConfigurationKey(this.getSupervisionUrlOcppKey(), { save: false }); |
| 1240 | } |
| 1241 | if ( |
| 1242 | this.stationInfo.amperageLimitationOcppKey && |
| 1243 | !this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey) |
| 1244 | ) { |
| 1245 | this.addConfigurationKey( |
| 1246 | this.stationInfo.amperageLimitationOcppKey, |
| 1247 | (this.stationInfo.maximumAmperage * this.getAmperageLimitationUnitDivider()).toString() |
| 1248 | ); |
| 1249 | } |
| 1250 | if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) { |
| 1251 | this.addConfigurationKey( |
| 1252 | StandardParametersKey.SupportedFeatureProfiles, |
| 1253 | `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}` |
| 1254 | ); |
| 1255 | } |
| 1256 | this.addConfigurationKey( |
| 1257 | StandardParametersKey.NumberOfConnectors, |
| 1258 | this.getNumberOfConnectors().toString(), |
| 1259 | { readonly: true }, |
| 1260 | { overwrite: true } |
| 1261 | ); |
| 1262 | if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) { |
| 1263 | this.addConfigurationKey( |
| 1264 | StandardParametersKey.MeterValuesSampledData, |
| 1265 | MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER |
| 1266 | ); |
| 1267 | } |
| 1268 | if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) { |
| 1269 | const connectorPhaseRotation = []; |
| 1270 | for (const connectorId of this.connectors.keys()) { |
| 1271 | // AC/DC |
| 1272 | if (connectorId === 0 && this.getNumberOfPhases() === 0) { |
| 1273 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`); |
| 1274 | } else if (connectorId > 0 && this.getNumberOfPhases() === 0) { |
| 1275 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`); |
| 1276 | // AC |
| 1277 | } else if (connectorId > 0 && this.getNumberOfPhases() === 1) { |
| 1278 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`); |
| 1279 | } else if (connectorId > 0 && this.getNumberOfPhases() === 3) { |
| 1280 | connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`); |
| 1281 | } |
| 1282 | } |
| 1283 | this.addConfigurationKey( |
| 1284 | StandardParametersKey.ConnectorPhaseRotation, |
| 1285 | connectorPhaseRotation.toString() |
| 1286 | ); |
| 1287 | } |
| 1288 | if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) { |
| 1289 | this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true'); |
| 1290 | } |
| 1291 | if ( |
| 1292 | !this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled) && |
| 1293 | this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)?.value.includes( |
| 1294 | SupportedFeatureProfiles.LocalAuthListManagement |
| 1295 | ) |
| 1296 | ) { |
| 1297 | this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false'); |
| 1298 | } |
| 1299 | if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) { |
| 1300 | this.addConfigurationKey( |
| 1301 | StandardParametersKey.ConnectionTimeOut, |
| 1302 | Constants.DEFAULT_CONNECTION_TIMEOUT.toString() |
| 1303 | ); |
| 1304 | } |
| 1305 | this.saveOcppConfiguration(); |
| 1306 | } |
| 1307 | |
| 1308 | private getConfigurationFromFile(): ChargingStationConfiguration | null { |
| 1309 | let configuration: ChargingStationConfiguration = null; |
| 1310 | if (this.configurationFile && fs.existsSync(this.configurationFile)) { |
| 1311 | try { |
| 1312 | const measureId = `${FileType.ChargingStationConfiguration} read`; |
| 1313 | const beginId = PerformanceStatistics.beginMeasure(measureId); |
| 1314 | configuration = JSON.parse( |
| 1315 | fs.readFileSync(this.configurationFile, 'utf8') |
| 1316 | ) as ChargingStationConfiguration; |
| 1317 | PerformanceStatistics.endMeasure(measureId, beginId); |
| 1318 | } catch (error) { |
| 1319 | FileUtils.handleFileException( |
| 1320 | this.logPrefix(), |
| 1321 | FileType.ChargingStationConfiguration, |
| 1322 | this.configurationFile, |
| 1323 | error as NodeJS.ErrnoException |
| 1324 | ); |
| 1325 | } |
| 1326 | } |
| 1327 | return configuration; |
| 1328 | } |
| 1329 | |
| 1330 | private saveConfiguration(section?: Section): void { |
| 1331 | if (this.configurationFile) { |
| 1332 | try { |
| 1333 | const configurationData: ChargingStationConfiguration = |
| 1334 | this.getConfigurationFromFile() ?? {}; |
| 1335 | if (!fs.existsSync(path.dirname(this.configurationFile))) { |
| 1336 | fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true }); |
| 1337 | } |
| 1338 | switch (section) { |
| 1339 | case Section.ocppConfiguration: |
| 1340 | configurationData.configurationKey = this.ocppConfiguration.configurationKey; |
| 1341 | break; |
| 1342 | case Section.stationInfo: |
| 1343 | configurationData.stationInfo = this.stationInfo; |
| 1344 | break; |
| 1345 | default: |
| 1346 | configurationData.configurationKey = this.ocppConfiguration.configurationKey; |
| 1347 | configurationData.stationInfo = this.stationInfo; |
| 1348 | break; |
| 1349 | } |
| 1350 | const measureId = `${FileType.ChargingStationConfiguration} write`; |
| 1351 | const beginId = PerformanceStatistics.beginMeasure(measureId); |
| 1352 | const fileDescriptor = fs.openSync(this.configurationFile, 'w'); |
| 1353 | fs.writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8'); |
| 1354 | fs.closeSync(fileDescriptor); |
| 1355 | PerformanceStatistics.endMeasure(measureId, beginId); |
| 1356 | } catch (error) { |
| 1357 | FileUtils.handleFileException( |
| 1358 | this.logPrefix(), |
| 1359 | FileType.ChargingStationConfiguration, |
| 1360 | this.configurationFile, |
| 1361 | error as NodeJS.ErrnoException |
| 1362 | ); |
| 1363 | } |
| 1364 | } else { |
| 1365 | logger.error( |
| 1366 | `${this.logPrefix()} Trying to save charging station configuration to undefined file` |
| 1367 | ); |
| 1368 | } |
| 1369 | } |
| 1370 | |
| 1371 | private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration { |
| 1372 | return this.getTemplateFromFile().Configuration ?? ({} as ChargingStationOcppConfiguration); |
| 1373 | } |
| 1374 | |
| 1375 | private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | null { |
| 1376 | let configuration: ChargingStationConfiguration = null; |
| 1377 | if (this.getOcppPersistentConfiguration()) { |
| 1378 | const configurationFromFile = this.getConfigurationFromFile(); |
| 1379 | configuration = configurationFromFile?.configurationKey && configurationFromFile; |
| 1380 | } |
| 1381 | configuration && delete configuration.stationInfo; |
| 1382 | return configuration; |
| 1383 | } |
| 1384 | |
| 1385 | private getOcppConfiguration(): ChargingStationOcppConfiguration { |
| 1386 | let ocppConfiguration: ChargingStationOcppConfiguration = this.getOcppConfigurationFromFile(); |
| 1387 | if (!ocppConfiguration) { |
| 1388 | ocppConfiguration = this.getOcppConfigurationFromTemplate(); |
| 1389 | } |
| 1390 | return ocppConfiguration; |
| 1391 | } |
| 1392 | |
| 1393 | private saveOcppConfiguration(): void { |
| 1394 | if (this.getOcppPersistentConfiguration()) { |
| 1395 | this.saveConfiguration(Section.ocppConfiguration); |
| 1396 | } |
| 1397 | } |
| 1398 | |
| 1399 | private async onOpen(): Promise<void> { |
| 1400 | if (this.isWebSocketConnectionOpened()) { |
| 1401 | logger.info( |
| 1402 | `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded` |
| 1403 | ); |
| 1404 | if (!this.isRegistered()) { |
| 1405 | // Send BootNotification |
| 1406 | let registrationRetryCount = 0; |
| 1407 | do { |
| 1408 | this.bootNotificationResponse = await this.ocppRequestService.requestHandler< |
| 1409 | BootNotificationRequest, |
| 1410 | BootNotificationResponse |
| 1411 | >( |
| 1412 | RequestCommand.BOOT_NOTIFICATION, |
| 1413 | { |
| 1414 | chargePointModel: this.bootNotificationRequest.chargePointModel, |
| 1415 | chargePointVendor: this.bootNotificationRequest.chargePointVendor, |
| 1416 | chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber, |
| 1417 | firmwareVersion: this.bootNotificationRequest.firmwareVersion, |
| 1418 | chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber, |
| 1419 | iccid: this.bootNotificationRequest.iccid, |
| 1420 | imsi: this.bootNotificationRequest.imsi, |
| 1421 | meterSerialNumber: this.bootNotificationRequest.meterSerialNumber, |
| 1422 | meterType: this.bootNotificationRequest.meterType, |
| 1423 | }, |
| 1424 | { skipBufferingOnError: true } |
| 1425 | ); |
| 1426 | if (!this.isRegistered()) { |
| 1427 | this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++; |
| 1428 | await Utils.sleep( |
| 1429 | this.bootNotificationResponse?.interval |
| 1430 | ? this.bootNotificationResponse.interval * 1000 |
| 1431 | : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL |
| 1432 | ); |
| 1433 | } |
| 1434 | } while ( |
| 1435 | !this.isRegistered() && |
| 1436 | (registrationRetryCount <= this.getRegistrationMaxRetries() || |
| 1437 | this.getRegistrationMaxRetries() === -1) |
| 1438 | ); |
| 1439 | } |
| 1440 | if (this.isRegistered()) { |
| 1441 | if (this.isInAcceptedState()) { |
| 1442 | await this.startMessageSequence(); |
| 1443 | this.wsConnectionRestarted && this.flushMessageBuffer(); |
| 1444 | } |
| 1445 | } else { |
| 1446 | logger.error( |
| 1447 | `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})` |
| 1448 | ); |
| 1449 | } |
| 1450 | this.stopped && (this.stopped = false); |
| 1451 | this.autoReconnectRetryCount = 0; |
| 1452 | this.wsConnectionRestarted = false; |
| 1453 | } else { |
| 1454 | logger.warn( |
| 1455 | `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed` |
| 1456 | ); |
| 1457 | } |
| 1458 | } |
| 1459 | |
| 1460 | private async onClose(code: number, reason: string): Promise<void> { |
| 1461 | switch (code) { |
| 1462 | // Normal close |
| 1463 | case WebSocketCloseEventStatusCode.CLOSE_NORMAL: |
| 1464 | case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS: |
| 1465 | logger.info( |
| 1466 | `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString( |
| 1467 | code |
| 1468 | )}' and reason '${reason}'` |
| 1469 | ); |
| 1470 | this.autoReconnectRetryCount = 0; |
| 1471 | break; |
| 1472 | // Abnormal close |
| 1473 | default: |
| 1474 | logger.error( |
| 1475 | `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString( |
| 1476 | code |
| 1477 | )}' and reason '${reason}'` |
| 1478 | ); |
| 1479 | await this.reconnect(code); |
| 1480 | break; |
| 1481 | } |
| 1482 | } |
| 1483 | |
| 1484 | private async onMessage(data: Data): Promise<void> { |
| 1485 | let messageType: number; |
| 1486 | let messageId: string; |
| 1487 | let commandName: IncomingRequestCommand; |
| 1488 | let commandPayload: JsonType; |
| 1489 | let errorType: ErrorType; |
| 1490 | let errorMessage: string; |
| 1491 | let errorDetails: JsonType; |
| 1492 | let responseCallback: (payload: JsonType, requestPayload: JsonType) => void; |
| 1493 | let rejectCallback: (error: OCPPError, requestStatistic?: boolean) => void; |
| 1494 | let requestCommandName: RequestCommand | IncomingRequestCommand; |
| 1495 | let requestPayload: JsonType; |
| 1496 | let cachedRequest: CachedRequest; |
| 1497 | let errMsg: string; |
| 1498 | try { |
| 1499 | const request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse; |
| 1500 | if (Utils.isIterable(request)) { |
| 1501 | [messageType, messageId] = request; |
| 1502 | // Check the type of message |
| 1503 | switch (messageType) { |
| 1504 | // Incoming Message |
| 1505 | case MessageType.CALL_MESSAGE: |
| 1506 | [, , commandName, commandPayload] = request as IncomingRequest; |
| 1507 | if (this.getEnableStatistics()) { |
| 1508 | this.performanceStatistics.addRequestStatistic(commandName, messageType); |
| 1509 | } |
| 1510 | logger.debug( |
| 1511 | `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify( |
| 1512 | request |
| 1513 | )}` |
| 1514 | ); |
| 1515 | // Process the message |
| 1516 | await this.ocppIncomingRequestService.incomingRequestHandler( |
| 1517 | messageId, |
| 1518 | commandName, |
| 1519 | commandPayload |
| 1520 | ); |
| 1521 | break; |
| 1522 | // Outcome Message |
| 1523 | case MessageType.CALL_RESULT_MESSAGE: |
| 1524 | [, , commandPayload] = request as Response; |
| 1525 | // Respond |
| 1526 | cachedRequest = this.requests.get(messageId); |
| 1527 | if (Utils.isIterable(cachedRequest)) { |
| 1528 | [responseCallback, , requestCommandName, requestPayload] = cachedRequest; |
| 1529 | } else { |
| 1530 | throw new OCPPError( |
| 1531 | ErrorType.PROTOCOL_ERROR, |
| 1532 | `Cached request for message id ${messageId} response is not iterable`, |
| 1533 | null, |
| 1534 | cachedRequest as unknown as JsonType |
| 1535 | ); |
| 1536 | } |
| 1537 | logger.debug( |
| 1538 | `${this.logPrefix()} << Command '${ |
| 1539 | requestCommandName ?? '' |
| 1540 | }' received response payload: ${JSON.stringify(request)}` |
| 1541 | ); |
| 1542 | if (!responseCallback) { |
| 1543 | // Error |
| 1544 | throw new OCPPError( |
| 1545 | ErrorType.INTERNAL_ERROR, |
| 1546 | `Response for unknown message id ${messageId}`, |
| 1547 | null, |
| 1548 | commandPayload |
| 1549 | ); |
| 1550 | } |
| 1551 | responseCallback(commandPayload, requestPayload); |
| 1552 | break; |
| 1553 | // Error Message |
| 1554 | case MessageType.CALL_ERROR_MESSAGE: |
| 1555 | [, , errorType, errorMessage, errorDetails] = request as ErrorResponse; |
| 1556 | cachedRequest = this.requests.get(messageId); |
| 1557 | if (Utils.isIterable(cachedRequest)) { |
| 1558 | [, rejectCallback, requestCommandName] = cachedRequest; |
| 1559 | } else { |
| 1560 | throw new OCPPError( |
| 1561 | ErrorType.PROTOCOL_ERROR, |
| 1562 | `Cached request for message id ${messageId} error response is not iterable`, |
| 1563 | null, |
| 1564 | cachedRequest as unknown as JsonType |
| 1565 | ); |
| 1566 | } |
| 1567 | logger.debug( |
| 1568 | `${this.logPrefix()} << Command '${ |
| 1569 | requestCommandName ?? '' |
| 1570 | }' received error payload: ${JSON.stringify(request)}` |
| 1571 | ); |
| 1572 | if (!rejectCallback) { |
| 1573 | // Error |
| 1574 | throw new OCPPError( |
| 1575 | ErrorType.INTERNAL_ERROR, |
| 1576 | `Error response for unknown message id ${messageId}`, |
| 1577 | null, |
| 1578 | { errorType, errorMessage, errorDetails } |
| 1579 | ); |
| 1580 | } |
| 1581 | rejectCallback( |
| 1582 | new OCPPError(errorType, errorMessage, requestCommandName, errorDetails) |
| 1583 | ); |
| 1584 | break; |
| 1585 | // Error |
| 1586 | default: |
| 1587 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions |
| 1588 | errMsg = `${this.logPrefix()} Wrong message type ${messageType}`; |
| 1589 | logger.error(errMsg); |
| 1590 | throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg); |
| 1591 | } |
| 1592 | } else { |
| 1593 | throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming message is not iterable', null, { |
| 1594 | payload: request, |
| 1595 | }); |
| 1596 | } |
| 1597 | } catch (error) { |
| 1598 | // Log |
| 1599 | logger.error( |
| 1600 | '%s Incoming OCPP message %j matching cached request %j processing error %j', |
| 1601 | this.logPrefix(), |
| 1602 | data.toString(), |
| 1603 | this.requests.get(messageId), |
| 1604 | error |
| 1605 | ); |
| 1606 | // Send error |
| 1607 | messageType === MessageType.CALL_MESSAGE && |
| 1608 | (await this.ocppRequestService.sendError( |
| 1609 | messageId, |
| 1610 | error as OCPPError, |
| 1611 | Utils.isString(commandName) ? commandName : requestCommandName ?? null |
| 1612 | )); |
| 1613 | } |
| 1614 | } |
| 1615 | |
| 1616 | private onPing(): void { |
| 1617 | logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server'); |
| 1618 | } |
| 1619 | |
| 1620 | private onPong(): void { |
| 1621 | logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server'); |
| 1622 | } |
| 1623 | |
| 1624 | private onError(error: WSError): void { |
| 1625 | logger.error(this.logPrefix() + ' WebSocket error: %j', error); |
| 1626 | } |
| 1627 | |
| 1628 | private getAuthorizationFile(): string | undefined { |
| 1629 | return ( |
| 1630 | this.stationInfo.authorizationFile && |
| 1631 | path.join( |
| 1632 | path.resolve(__dirname, '../'), |
| 1633 | 'assets', |
| 1634 | path.basename(this.stationInfo.authorizationFile) |
| 1635 | ) |
| 1636 | ); |
| 1637 | } |
| 1638 | |
| 1639 | private getAuthorizedTags(): string[] { |
| 1640 | let authorizedTags: string[] = []; |
| 1641 | const authorizationFile = this.getAuthorizationFile(); |
| 1642 | if (authorizationFile) { |
| 1643 | try { |
| 1644 | // Load authorization file |
| 1645 | authorizedTags = JSON.parse(fs.readFileSync(authorizationFile, 'utf8')) as string[]; |
| 1646 | } catch (error) { |
| 1647 | FileUtils.handleFileException( |
| 1648 | this.logPrefix(), |
| 1649 | FileType.Authorization, |
| 1650 | authorizationFile, |
| 1651 | error as NodeJS.ErrnoException |
| 1652 | ); |
| 1653 | } |
| 1654 | } else { |
| 1655 | logger.info( |
| 1656 | this.logPrefix() + ' No authorization file given in template file ' + this.templateFile |
| 1657 | ); |
| 1658 | } |
| 1659 | return authorizedTags; |
| 1660 | } |
| 1661 | |
| 1662 | private getUseConnectorId0(): boolean | undefined { |
| 1663 | return !Utils.isUndefined(this.stationInfo.useConnectorId0) |
| 1664 | ? this.stationInfo.useConnectorId0 |
| 1665 | : true; |
| 1666 | } |
| 1667 | |
| 1668 | private getNumberOfRunningTransactions(): number { |
| 1669 | let trxCount = 0; |
| 1670 | for (const connectorId of this.connectors.keys()) { |
| 1671 | if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) { |
| 1672 | trxCount++; |
| 1673 | } |
| 1674 | } |
| 1675 | return trxCount; |
| 1676 | } |
| 1677 | |
| 1678 | // 0 for disabling |
| 1679 | private getConnectionTimeout(): number | undefined { |
| 1680 | if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) { |
| 1681 | return ( |
| 1682 | parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ?? |
| 1683 | Constants.DEFAULT_CONNECTION_TIMEOUT |
| 1684 | ); |
| 1685 | } |
| 1686 | return Constants.DEFAULT_CONNECTION_TIMEOUT; |
| 1687 | } |
| 1688 | |
| 1689 | // -1 for unlimited, 0 for disabling |
| 1690 | private getAutoReconnectMaxRetries(): number | undefined { |
| 1691 | if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) { |
| 1692 | return this.stationInfo.autoReconnectMaxRetries; |
| 1693 | } |
| 1694 | if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) { |
| 1695 | return Configuration.getAutoReconnectMaxRetries(); |
| 1696 | } |
| 1697 | return -1; |
| 1698 | } |
| 1699 | |
| 1700 | // 0 for disabling |
| 1701 | private getRegistrationMaxRetries(): number | undefined { |
| 1702 | if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) { |
| 1703 | return this.stationInfo.registrationMaxRetries; |
| 1704 | } |
| 1705 | return -1; |
| 1706 | } |
| 1707 | |
| 1708 | private getPowerDivider(): number { |
| 1709 | let powerDivider = this.getNumberOfConnectors(); |
| 1710 | if (this.stationInfo.powerSharedByConnectors) { |
| 1711 | powerDivider = this.getNumberOfRunningTransactions(); |
| 1712 | } |
| 1713 | return powerDivider; |
| 1714 | } |
| 1715 | |
| 1716 | private getTemplateMaxNumberOfConnectors(): number { |
| 1717 | return Object.keys(this.stationInfo.Connectors).length; |
| 1718 | } |
| 1719 | |
| 1720 | private getMaxNumberOfConnectors(): number { |
| 1721 | let maxConnectors: number; |
| 1722 | if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) { |
| 1723 | const numberOfConnectors = this.stationInfo.numberOfConnectors as number[]; |
| 1724 | // Distribute evenly the number of connectors |
| 1725 | maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length]; |
| 1726 | } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) { |
| 1727 | maxConnectors = this.stationInfo.numberOfConnectors as number; |
| 1728 | } else { |
| 1729 | maxConnectors = this.stationInfo.Connectors[0] |
| 1730 | ? this.getTemplateMaxNumberOfConnectors() - 1 |
| 1731 | : this.getTemplateMaxNumberOfConnectors(); |
| 1732 | } |
| 1733 | return maxConnectors; |
| 1734 | } |
| 1735 | |
| 1736 | private getMaximumPower(): number { |
| 1737 | return (this.stationInfo['maxPower'] as number) ?? this.stationInfo.maximumPower; |
| 1738 | } |
| 1739 | |
| 1740 | private getMaximumAmperage(): number | undefined { |
| 1741 | const maximumPower = this.getMaximumPower(); |
| 1742 | switch (this.getCurrentOutType()) { |
| 1743 | case CurrentType.AC: |
| 1744 | return ACElectricUtils.amperagePerPhaseFromPower( |
| 1745 | this.getNumberOfPhases(), |
| 1746 | maximumPower / this.getNumberOfConnectors(), |
| 1747 | this.getVoltageOut() |
| 1748 | ); |
| 1749 | case CurrentType.DC: |
| 1750 | return DCElectricUtils.amperage(maximumPower, this.getVoltageOut()); |
| 1751 | } |
| 1752 | } |
| 1753 | |
| 1754 | private getAmperageLimitationUnitDivider(): number { |
| 1755 | let unitDivider = 1; |
| 1756 | switch (this.stationInfo.amperageLimitationUnit) { |
| 1757 | case AmpereUnits.DECI_AMPERE: |
| 1758 | unitDivider = 10; |
| 1759 | break; |
| 1760 | case AmpereUnits.CENTI_AMPERE: |
| 1761 | unitDivider = 100; |
| 1762 | break; |
| 1763 | case AmpereUnits.MILLI_AMPERE: |
| 1764 | unitDivider = 1000; |
| 1765 | break; |
| 1766 | } |
| 1767 | return unitDivider; |
| 1768 | } |
| 1769 | |
| 1770 | private getAmperageLimitation(): number | undefined { |
| 1771 | if ( |
| 1772 | this.stationInfo.amperageLimitationOcppKey && |
| 1773 | this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey) |
| 1774 | ) { |
| 1775 | return ( |
| 1776 | Utils.convertToInt( |
| 1777 | this.getConfigurationKey(this.stationInfo.amperageLimitationOcppKey).value |
| 1778 | ) / this.getAmperageLimitationUnitDivider() |
| 1779 | ); |
| 1780 | } |
| 1781 | } |
| 1782 | |
| 1783 | private async startMessageSequence(): Promise<void> { |
| 1784 | if (this.stationInfo.autoRegister) { |
| 1785 | await this.ocppRequestService.requestHandler< |
| 1786 | BootNotificationRequest, |
| 1787 | BootNotificationResponse |
| 1788 | >( |
| 1789 | RequestCommand.BOOT_NOTIFICATION, |
| 1790 | { |
| 1791 | chargePointModel: this.bootNotificationRequest.chargePointModel, |
| 1792 | chargePointVendor: this.bootNotificationRequest.chargePointVendor, |
| 1793 | chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber, |
| 1794 | firmwareVersion: this.bootNotificationRequest.firmwareVersion, |
| 1795 | chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber, |
| 1796 | iccid: this.bootNotificationRequest.iccid, |
| 1797 | imsi: this.bootNotificationRequest.imsi, |
| 1798 | meterSerialNumber: this.bootNotificationRequest.meterSerialNumber, |
| 1799 | meterType: this.bootNotificationRequest.meterType, |
| 1800 | }, |
| 1801 | { skipBufferingOnError: true } |
| 1802 | ); |
| 1803 | } |
| 1804 | // Start WebSocket ping |
| 1805 | this.startWebSocketPing(); |
| 1806 | // Start heartbeat |
| 1807 | this.startHeartbeat(); |
| 1808 | // Initialize connectors status |
| 1809 | for (const connectorId of this.connectors.keys()) { |
| 1810 | if (connectorId === 0) { |
| 1811 | continue; |
| 1812 | } else if ( |
| 1813 | !this.stopped && |
| 1814 | !this.getConnectorStatus(connectorId)?.status && |
| 1815 | this.getConnectorStatus(connectorId)?.bootStatus |
| 1816 | ) { |
| 1817 | // Send status in template at startup |
| 1818 | await this.ocppRequestService.requestHandler< |
| 1819 | StatusNotificationRequest, |
| 1820 | StatusNotificationResponse |
| 1821 | >(RequestCommand.STATUS_NOTIFICATION, { |
| 1822 | connectorId, |
| 1823 | status: this.getConnectorStatus(connectorId).bootStatus, |
| 1824 | errorCode: ChargePointErrorCode.NO_ERROR, |
| 1825 | }); |
| 1826 | this.getConnectorStatus(connectorId).status = |
| 1827 | this.getConnectorStatus(connectorId).bootStatus; |
| 1828 | } else if ( |
| 1829 | this.stopped && |
| 1830 | this.getConnectorStatus(connectorId)?.status && |
| 1831 | this.getConnectorStatus(connectorId)?.bootStatus |
| 1832 | ) { |
| 1833 | // Send status in template after reset |
| 1834 | await this.ocppRequestService.requestHandler< |
| 1835 | StatusNotificationRequest, |
| 1836 | StatusNotificationResponse |
| 1837 | >(RequestCommand.STATUS_NOTIFICATION, { |
| 1838 | connectorId, |
| 1839 | status: this.getConnectorStatus(connectorId).bootStatus, |
| 1840 | errorCode: ChargePointErrorCode.NO_ERROR, |
| 1841 | }); |
| 1842 | this.getConnectorStatus(connectorId).status = |
| 1843 | this.getConnectorStatus(connectorId).bootStatus; |
| 1844 | } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) { |
| 1845 | // Send previous status at template reload |
| 1846 | await this.ocppRequestService.requestHandler< |
| 1847 | StatusNotificationRequest, |
| 1848 | StatusNotificationResponse |
| 1849 | >(RequestCommand.STATUS_NOTIFICATION, { |
| 1850 | connectorId, |
| 1851 | status: this.getConnectorStatus(connectorId).status, |
| 1852 | errorCode: ChargePointErrorCode.NO_ERROR, |
| 1853 | }); |
| 1854 | } else { |
| 1855 | // Send default status |
| 1856 | await this.ocppRequestService.requestHandler< |
| 1857 | StatusNotificationRequest, |
| 1858 | StatusNotificationResponse |
| 1859 | >(RequestCommand.STATUS_NOTIFICATION, { |
| 1860 | connectorId, |
| 1861 | status: ChargePointStatus.AVAILABLE, |
| 1862 | errorCode: ChargePointErrorCode.NO_ERROR, |
| 1863 | }); |
| 1864 | this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE; |
| 1865 | } |
| 1866 | } |
| 1867 | // Start the ATG |
| 1868 | this.startAutomaticTransactionGenerator(); |
| 1869 | } |
| 1870 | |
| 1871 | private startAutomaticTransactionGenerator() { |
| 1872 | if (this.stationInfo.AutomaticTransactionGenerator.enable) { |
| 1873 | if (!this.automaticTransactionGenerator) { |
| 1874 | this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(this); |
| 1875 | } |
| 1876 | if (!this.automaticTransactionGenerator.started) { |
| 1877 | this.automaticTransactionGenerator.start(); |
| 1878 | } |
| 1879 | } |
| 1880 | } |
| 1881 | |
| 1882 | private async stopMessageSequence( |
| 1883 | reason: StopTransactionReason = StopTransactionReason.NONE |
| 1884 | ): Promise<void> { |
| 1885 | // Stop WebSocket ping |
| 1886 | this.stopWebSocketPing(); |
| 1887 | // Stop heartbeat |
| 1888 | this.stopHeartbeat(); |
| 1889 | // Stop the ATG |
| 1890 | if ( |
| 1891 | this.stationInfo.AutomaticTransactionGenerator.enable && |
| 1892 | this.automaticTransactionGenerator?.started |
| 1893 | ) { |
| 1894 | this.automaticTransactionGenerator.stop(); |
| 1895 | } else { |
| 1896 | for (const connectorId of this.connectors.keys()) { |
| 1897 | if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) { |
| 1898 | const transactionId = this.getConnectorStatus(connectorId).transactionId; |
| 1899 | if ( |
| 1900 | this.getBeginEndMeterValues() && |
| 1901 | this.getOcppStrictCompliance() && |
| 1902 | !this.getOutOfOrderEndMeterValues() |
| 1903 | ) { |
| 1904 | // FIXME: Implement OCPP version agnostic helpers |
| 1905 | const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue( |
| 1906 | this, |
| 1907 | connectorId, |
| 1908 | this.getEnergyActiveImportRegisterByTransactionId(transactionId) |
| 1909 | ); |
| 1910 | await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>( |
| 1911 | RequestCommand.METER_VALUES, |
| 1912 | { |
| 1913 | connectorId, |
| 1914 | transactionId, |
| 1915 | meterValue: transactionEndMeterValue, |
| 1916 | } |
| 1917 | ); |
| 1918 | } |
| 1919 | await this.ocppRequestService.requestHandler< |
| 1920 | StopTransactionRequest, |
| 1921 | StopTransactionResponse |
| 1922 | >(RequestCommand.STOP_TRANSACTION, { |
| 1923 | transactionId, |
| 1924 | meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId), |
| 1925 | idTag: this.getTransactionIdTag(transactionId), |
| 1926 | reason, |
| 1927 | }); |
| 1928 | } |
| 1929 | } |
| 1930 | } |
| 1931 | } |
| 1932 | |
| 1933 | private startWebSocketPing(): void { |
| 1934 | const webSocketPingInterval: number = this.getConfigurationKey( |
| 1935 | StandardParametersKey.WebSocketPingInterval |
| 1936 | ) |
| 1937 | ? Utils.convertToInt( |
| 1938 | this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value |
| 1939 | ) |
| 1940 | : 0; |
| 1941 | if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) { |
| 1942 | this.webSocketPingSetInterval = setInterval(() => { |
| 1943 | if (this.isWebSocketConnectionOpened()) { |
| 1944 | this.wsConnection.ping((): void => { |
| 1945 | /* This is intentional */ |
| 1946 | }); |
| 1947 | } |
| 1948 | }, webSocketPingInterval * 1000); |
| 1949 | logger.info( |
| 1950 | this.logPrefix() + |
| 1951 | ' WebSocket ping started every ' + |
| 1952 | Utils.formatDurationSeconds(webSocketPingInterval) |
| 1953 | ); |
| 1954 | } else if (this.webSocketPingSetInterval) { |
| 1955 | logger.info( |
| 1956 | this.logPrefix() + |
| 1957 | ' WebSocket ping every ' + |
| 1958 | Utils.formatDurationSeconds(webSocketPingInterval) + |
| 1959 | ' already started' |
| 1960 | ); |
| 1961 | } else { |
| 1962 | logger.error( |
| 1963 | `${this.logPrefix()} WebSocket ping interval set to ${ |
| 1964 | webSocketPingInterval |
| 1965 | ? Utils.formatDurationSeconds(webSocketPingInterval) |
| 1966 | : webSocketPingInterval |
| 1967 | }, not starting the WebSocket ping` |
| 1968 | ); |
| 1969 | } |
| 1970 | } |
| 1971 | |
| 1972 | private stopWebSocketPing(): void { |
| 1973 | if (this.webSocketPingSetInterval) { |
| 1974 | clearInterval(this.webSocketPingSetInterval); |
| 1975 | } |
| 1976 | } |
| 1977 | |
| 1978 | private warnDeprecatedTemplateKey( |
| 1979 | template: ChargingStationTemplate, |
| 1980 | key: string, |
| 1981 | chargingStationId: string, |
| 1982 | logMsgToAppend = '' |
| 1983 | ): void { |
| 1984 | if (!Utils.isUndefined(template[key])) { |
| 1985 | const logPrefixStr = ` ${chargingStationId} |`; |
| 1986 | logger.warn( |
| 1987 | `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${ |
| 1988 | this.templateFile |
| 1989 | }'${logMsgToAppend && '. ' + logMsgToAppend}` |
| 1990 | ); |
| 1991 | } |
| 1992 | } |
| 1993 | |
| 1994 | private convertDeprecatedTemplateKey( |
| 1995 | template: ChargingStationTemplate, |
| 1996 | deprecatedKey: string, |
| 1997 | key: string |
| 1998 | ): void { |
| 1999 | if (!Utils.isUndefined(template[deprecatedKey])) { |
| 2000 | template[key] = template[deprecatedKey] as unknown; |
| 2001 | delete template[deprecatedKey]; |
| 2002 | } |
| 2003 | } |
| 2004 | |
| 2005 | private getConfiguredSupervisionUrl(): URL { |
| 2006 | const supervisionUrls = Utils.cloneObject<string | string[]>( |
| 2007 | this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls() |
| 2008 | ); |
| 2009 | if (!Utils.isEmptyArray(supervisionUrls)) { |
| 2010 | let urlIndex = 0; |
| 2011 | switch (Configuration.getSupervisionUrlDistribution()) { |
| 2012 | case SupervisionUrlDistribution.ROUND_ROBIN: |
| 2013 | urlIndex = (this.index - 1) % supervisionUrls.length; |
| 2014 | break; |
| 2015 | case SupervisionUrlDistribution.RANDOM: |
| 2016 | // Get a random url |
| 2017 | urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length); |
| 2018 | break; |
| 2019 | case SupervisionUrlDistribution.SEQUENTIAL: |
| 2020 | if (this.index <= supervisionUrls.length) { |
| 2021 | urlIndex = this.index - 1; |
| 2022 | } else { |
| 2023 | logger.warn( |
| 2024 | `${this.logPrefix()} No more configured supervision urls available, using the first one` |
| 2025 | ); |
| 2026 | } |
| 2027 | break; |
| 2028 | default: |
| 2029 | logger.error( |
| 2030 | `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${ |
| 2031 | SupervisionUrlDistribution.ROUND_ROBIN |
| 2032 | }` |
| 2033 | ); |
| 2034 | urlIndex = (this.index - 1) % supervisionUrls.length; |
| 2035 | break; |
| 2036 | } |
| 2037 | return new URL(supervisionUrls[urlIndex]); |
| 2038 | } |
| 2039 | return new URL(supervisionUrls as string); |
| 2040 | } |
| 2041 | |
| 2042 | private getHeartbeatInterval(): number | undefined { |
| 2043 | const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval); |
| 2044 | if (HeartbeatInterval) { |
| 2045 | return Utils.convertToInt(HeartbeatInterval.value) * 1000; |
| 2046 | } |
| 2047 | const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval); |
| 2048 | if (HeartBeatInterval) { |
| 2049 | return Utils.convertToInt(HeartBeatInterval.value) * 1000; |
| 2050 | } |
| 2051 | !this.stationInfo.autoRegister && |
| 2052 | logger.warn( |
| 2053 | `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${ |
| 2054 | Constants.DEFAULT_HEARTBEAT_INTERVAL |
| 2055 | }` |
| 2056 | ); |
| 2057 | return Constants.DEFAULT_HEARTBEAT_INTERVAL; |
| 2058 | } |
| 2059 | |
| 2060 | private stopHeartbeat(): void { |
| 2061 | if (this.heartbeatSetInterval) { |
| 2062 | clearInterval(this.heartbeatSetInterval); |
| 2063 | } |
| 2064 | } |
| 2065 | |
| 2066 | private openWSConnection( |
| 2067 | options: WsOptions = this.stationInfo.wsOptions, |
| 2068 | forceCloseOpened = false |
| 2069 | ): void { |
| 2070 | options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000; |
| 2071 | if ( |
| 2072 | !Utils.isNullOrUndefined(this.stationInfo.supervisionUser) && |
| 2073 | !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword) |
| 2074 | ) { |
| 2075 | options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`; |
| 2076 | } |
| 2077 | if (this.isWebSocketConnectionOpened() && forceCloseOpened) { |
| 2078 | this.wsConnection.close(); |
| 2079 | } |
| 2080 | let protocol: string; |
| 2081 | switch (this.getOcppVersion()) { |
| 2082 | case OCPPVersion.VERSION_16: |
| 2083 | protocol = 'ocpp' + OCPPVersion.VERSION_16; |
| 2084 | break; |
| 2085 | default: |
| 2086 | this.handleUnsupportedVersion(this.getOcppVersion()); |
| 2087 | break; |
| 2088 | } |
| 2089 | this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options); |
| 2090 | logger.info( |
| 2091 | this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString() |
| 2092 | ); |
| 2093 | } |
| 2094 | |
| 2095 | private stopMeterValues(connectorId: number) { |
| 2096 | if (this.getConnectorStatus(connectorId)?.transactionSetInterval) { |
| 2097 | clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval); |
| 2098 | } |
| 2099 | } |
| 2100 | |
| 2101 | private getReconnectExponentialDelay(): boolean | undefined { |
| 2102 | return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) |
| 2103 | ? this.stationInfo.reconnectExponentialDelay |
| 2104 | : false; |
| 2105 | } |
| 2106 | |
| 2107 | private async reconnect(code: number): Promise<void> { |
| 2108 | // Stop WebSocket ping |
| 2109 | this.stopWebSocketPing(); |
| 2110 | // Stop heartbeat |
| 2111 | this.stopHeartbeat(); |
| 2112 | // Stop the ATG if needed |
| 2113 | if ( |
| 2114 | this.stationInfo.AutomaticTransactionGenerator.enable && |
| 2115 | this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure && |
| 2116 | this.automaticTransactionGenerator?.started |
| 2117 | ) { |
| 2118 | this.automaticTransactionGenerator.stop(); |
| 2119 | } |
| 2120 | if ( |
| 2121 | this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || |
| 2122 | this.getAutoReconnectMaxRetries() === -1 |
| 2123 | ) { |
| 2124 | this.autoReconnectRetryCount++; |
| 2125 | const reconnectDelay = this.getReconnectExponentialDelay() |
| 2126 | ? Utils.exponentialDelay(this.autoReconnectRetryCount) |
| 2127 | : this.getConnectionTimeout() * 1000; |
| 2128 | const reconnectTimeout = reconnectDelay - 100 > 0 && reconnectDelay; |
| 2129 | logger.error( |
| 2130 | `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo( |
| 2131 | reconnectDelay, |
| 2132 | 2 |
| 2133 | )}ms, timeout ${reconnectTimeout}ms` |
| 2134 | ); |
| 2135 | await Utils.sleep(reconnectDelay); |
| 2136 | logger.error( |
| 2137 | this.logPrefix() + |
| 2138 | ' WebSocket: reconnecting try #' + |
| 2139 | this.autoReconnectRetryCount.toString() |
| 2140 | ); |
| 2141 | this.openWSConnection( |
| 2142 | { ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout }, |
| 2143 | true |
| 2144 | ); |
| 2145 | this.wsConnectionRestarted = true; |
| 2146 | } else if (this.getAutoReconnectMaxRetries() !== -1) { |
| 2147 | logger.error( |
| 2148 | `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${ |
| 2149 | this.autoReconnectRetryCount |
| 2150 | }) or retry disabled (${this.getAutoReconnectMaxRetries()})` |
| 2151 | ); |
| 2152 | } |
| 2153 | } |
| 2154 | |
| 2155 | private initializeConnectorStatus(connectorId: number): void { |
| 2156 | this.getConnectorStatus(connectorId).idTagLocalAuthorized = false; |
| 2157 | this.getConnectorStatus(connectorId).idTagAuthorized = false; |
| 2158 | this.getConnectorStatus(connectorId).transactionRemoteStarted = false; |
| 2159 | this.getConnectorStatus(connectorId).transactionStarted = false; |
| 2160 | this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0; |
| 2161 | this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0; |
| 2162 | } |
| 2163 | } |