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