| 1 | import { BootNotificationResponse, RegistrationStatus } from '../types/ocpp/Responses'; |
| 2 | import ChargingStationConfiguration, { ConfigurationKey } from '../types/ChargingStationConfiguration'; |
| 3 | import ChargingStationTemplate, { CurrentType, PowerUnits, Voltage } from '../types/ChargingStationTemplate'; |
| 4 | import { ConnectorPhaseRotation, StandardParametersKey, SupportedFeatureProfiles } from '../types/ocpp/Configuration'; |
| 5 | import Connectors, { Connector, SampledValueTemplate } from '../types/Connectors'; |
| 6 | import { MeterValueMeasurand, MeterValuePhase } from '../types/ocpp/MeterValues'; |
| 7 | import Requests, { AvailabilityType, BootNotificationRequest, IncomingRequest, IncomingRequestCommand } from '../types/ocpp/Requests'; |
| 8 | import WebSocket, { MessageEvent } from 'ws'; |
| 9 | |
| 10 | import AutomaticTransactionGenerator from './AutomaticTransactionGenerator'; |
| 11 | import { ChargePointStatus } from '../types/ocpp/ChargePointStatus'; |
| 12 | import { ChargingProfile } from '../types/ocpp/ChargingProfile'; |
| 13 | import ChargingStationInfo from '../types/ChargingStationInfo'; |
| 14 | import Configuration from '../utils/Configuration'; |
| 15 | import Constants from '../utils/Constants'; |
| 16 | import FileUtils from '../utils/FileUtils'; |
| 17 | import { MessageType } from '../types/ocpp/MessageType'; |
| 18 | import OCPP16IncomingRequestService from './ocpp/1.6/OCCP16IncomingRequestService'; |
| 19 | import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService'; |
| 20 | import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService'; |
| 21 | import OCPPError from './OCPPError'; |
| 22 | import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService'; |
| 23 | import OCPPRequestService from './ocpp/OCPPRequestService'; |
| 24 | import { OCPPVersion } from '../types/ocpp/OCPPVersion'; |
| 25 | import PerformanceStatistics from '../utils/PerformanceStatistics'; |
| 26 | import { StopTransactionReason } from '../types/ocpp/Transaction'; |
| 27 | import { URL } from 'url'; |
| 28 | import Utils from '../utils/Utils'; |
| 29 | import { WebSocketCloseEventStatusCode } from '../types/WebSocket'; |
| 30 | import crypto from 'crypto'; |
| 31 | import fs from 'fs'; |
| 32 | import logger from '../utils/Logger'; |
| 33 | import path from 'path'; |
| 34 | |
| 35 | export default class ChargingStation { |
| 36 | public stationTemplateFile: string; |
| 37 | public authorizedTags: string[]; |
| 38 | public stationInfo!: ChargingStationInfo; |
| 39 | public connectors: Connectors; |
| 40 | public configuration!: ChargingStationConfiguration; |
| 41 | public hasStopped: boolean; |
| 42 | public wsConnection!: WebSocket; |
| 43 | public requests: Requests; |
| 44 | public messageQueue: string[]; |
| 45 | public performanceStatistics!: PerformanceStatistics; |
| 46 | public heartbeatSetInterval!: NodeJS.Timeout; |
| 47 | public ocppIncomingRequestService!: OCPPIncomingRequestService; |
| 48 | public ocppRequestService!: OCPPRequestService; |
| 49 | private index: number; |
| 50 | private bootNotificationRequest!: BootNotificationRequest; |
| 51 | private bootNotificationResponse!: BootNotificationResponse | null; |
| 52 | private connectorsConfigurationHash!: string; |
| 53 | private wsConnectionUrl!: URL; |
| 54 | private hasSocketRestarted: boolean; |
| 55 | private autoReconnectRetryCount: number; |
| 56 | private automaticTransactionGeneration!: AutomaticTransactionGenerator; |
| 57 | private webSocketPingSetInterval!: NodeJS.Timeout; |
| 58 | |
| 59 | constructor(index: number, stationTemplateFile: string) { |
| 60 | this.index = index; |
| 61 | this.stationTemplateFile = stationTemplateFile; |
| 62 | this.connectors = {} as Connectors; |
| 63 | this.initialize(); |
| 64 | |
| 65 | this.hasStopped = false; |
| 66 | this.hasSocketRestarted = false; |
| 67 | this.autoReconnectRetryCount = 0; |
| 68 | |
| 69 | this.requests = {} as Requests; |
| 70 | this.messageQueue = [] as string[]; |
| 71 | |
| 72 | this.authorizedTags = this.getAuthorizedTags(); |
| 73 | } |
| 74 | |
| 75 | public logPrefix(): string { |
| 76 | return Utils.logPrefix(` ${this.stationInfo.chargingStationId} |`); |
| 77 | } |
| 78 | |
| 79 | public getRandomTagId(): string { |
| 80 | const index = Math.floor(Math.random() * this.authorizedTags.length); |
| 81 | return this.authorizedTags[index]; |
| 82 | } |
| 83 | |
| 84 | public hasAuthorizedTags(): boolean { |
| 85 | return !Utils.isEmptyArray(this.authorizedTags); |
| 86 | } |
| 87 | |
| 88 | public getEnableStatistics(): boolean | undefined { |
| 89 | return !Utils.isUndefined(this.stationInfo.enableStatistics) ? this.stationInfo.enableStatistics : true; |
| 90 | } |
| 91 | |
| 92 | public getMayAuthorizeAtRemoteStart(): boolean | undefined { |
| 93 | return this.stationInfo.mayAuthorizeAtRemoteStart ?? true; |
| 94 | } |
| 95 | |
| 96 | public getNumberOfPhases(): number | undefined { |
| 97 | switch (this.getCurrentOutType()) { |
| 98 | case CurrentType.AC: |
| 99 | return !Utils.isUndefined(this.stationInfo.numberOfPhases) ? this.stationInfo.numberOfPhases : 3; |
| 100 | case CurrentType.DC: |
| 101 | return 0; |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | public isWebSocketOpen(): boolean { |
| 106 | return this.wsConnection?.readyState === WebSocket.OPEN; |
| 107 | } |
| 108 | |
| 109 | public isRegistered(): boolean { |
| 110 | return this.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED; |
| 111 | } |
| 112 | |
| 113 | public isChargingStationAvailable(): boolean { |
| 114 | return this.getConnector(0).availability === AvailabilityType.OPERATIVE; |
| 115 | } |
| 116 | |
| 117 | public isConnectorAvailable(id: number): boolean { |
| 118 | return this.getConnector(id).availability === AvailabilityType.OPERATIVE; |
| 119 | } |
| 120 | |
| 121 | public getConnector(id: number): Connector { |
| 122 | return this.connectors[id]; |
| 123 | } |
| 124 | |
| 125 | public getCurrentOutType(): CurrentType | undefined { |
| 126 | return this.stationInfo.currentOutType ?? CurrentType.AC; |
| 127 | } |
| 128 | |
| 129 | public getVoltageOut(): number | undefined { |
| 130 | const errMsg = `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${this.stationTemplateFile}, cannot define default voltage out`; |
| 131 | let defaultVoltageOut: number; |
| 132 | switch (this.getCurrentOutType()) { |
| 133 | case CurrentType.AC: |
| 134 | defaultVoltageOut = Voltage.VOLTAGE_230; |
| 135 | break; |
| 136 | case CurrentType.DC: |
| 137 | defaultVoltageOut = Voltage.VOLTAGE_400; |
| 138 | break; |
| 139 | default: |
| 140 | logger.error(errMsg); |
| 141 | throw new Error(errMsg); |
| 142 | } |
| 143 | return !Utils.isUndefined(this.stationInfo.voltageOut) ? this.stationInfo.voltageOut : defaultVoltageOut; |
| 144 | } |
| 145 | |
| 146 | public getTransactionIdTag(transactionId: number): string | undefined { |
| 147 | for (const connector in this.connectors) { |
| 148 | if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) { |
| 149 | return this.getConnector(Utils.convertToInt(connector)).transactionIdTag; |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | public getOutOfOrderEndMeterValues(): boolean { |
| 155 | return this.stationInfo.outOfOrderEndMeterValues ?? false; |
| 156 | } |
| 157 | |
| 158 | public getBeginEndMeterValues(): boolean { |
| 159 | return this.stationInfo.beginEndMeterValues ?? false; |
| 160 | } |
| 161 | |
| 162 | public getMeteringPerTransaction(): boolean { |
| 163 | return this.stationInfo.meteringPerTransaction ?? true; |
| 164 | } |
| 165 | |
| 166 | public getTransactionDataMeterValues(): boolean { |
| 167 | return this.stationInfo.transactionDataMeterValues ?? false; |
| 168 | } |
| 169 | |
| 170 | public getMainVoltageMeterValues(): boolean { |
| 171 | return this.stationInfo.mainVoltageMeterValues ?? true; |
| 172 | } |
| 173 | |
| 174 | public getPhaseLineToLineVoltageMeterValues(): boolean { |
| 175 | return this.stationInfo.phaseLineToLineVoltageMeterValues ?? false; |
| 176 | } |
| 177 | |
| 178 | public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined { |
| 179 | if (this.getMeteringPerTransaction()) { |
| 180 | for (const connector in this.connectors) { |
| 181 | if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) { |
| 182 | return this.getConnector(Utils.convertToInt(connector)).transactionEnergyActiveImportRegisterValue; |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | for (const connector in this.connectors) { |
| 187 | if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) { |
| 188 | return this.getConnector(Utils.convertToInt(connector)).energyActiveImportRegisterValue; |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined { |
| 194 | if (this.getMeteringPerTransaction()) { |
| 195 | return this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue; |
| 196 | } |
| 197 | return this.getConnector(connectorId).energyActiveImportRegisterValue; |
| 198 | } |
| 199 | |
| 200 | public getAuthorizeRemoteTxRequests(): boolean { |
| 201 | const authorizeRemoteTxRequests = this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests); |
| 202 | return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false; |
| 203 | } |
| 204 | |
| 205 | public getLocalAuthListEnabled(): boolean { |
| 206 | const localAuthListEnabled = this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled); |
| 207 | return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false; |
| 208 | } |
| 209 | |
| 210 | public restartWebSocketPing(): void { |
| 211 | // Stop WebSocket ping |
| 212 | this.stopWebSocketPing(); |
| 213 | // Start WebSocket ping |
| 214 | this.startWebSocketPing(); |
| 215 | } |
| 216 | |
| 217 | public getSampledValueTemplate(connectorId: number, measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER, |
| 218 | phase?: MeterValuePhase): SampledValueTemplate | undefined { |
| 219 | if (!Constants.SUPPORTED_MEASURANDS.includes(measurand)) { |
| 220 | logger.warn(`${this.logPrefix()} Trying to get unsupported MeterValues measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`); |
| 221 | return; |
| 222 | } |
| 223 | if (measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) { |
| 224 | logger.debug(`${this.logPrefix()} Trying to get MeterValues measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId} not found in '${StandardParametersKey.MeterValuesSampledData}' OCPP parameter`); |
| 225 | return; |
| 226 | } |
| 227 | const sampledValueTemplates: SampledValueTemplate[] = this.getConnector(connectorId).MeterValues; |
| 228 | for (let index = 0; !Utils.isEmptyArray(sampledValueTemplates) && index < sampledValueTemplates.length; index++) { |
| 229 | if (!Constants.SUPPORTED_MEASURANDS.includes(sampledValueTemplates[index]?.measurand ?? MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER)) { |
| 230 | logger.warn(`${this.logPrefix()} Unsupported MeterValues measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`); |
| 231 | continue; |
| 232 | } else if (phase && sampledValueTemplates[index]?.phase === phase && sampledValueTemplates[index]?.measurand === measurand |
| 233 | && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) { |
| 234 | return sampledValueTemplates[index]; |
| 235 | } else if (!phase && !sampledValueTemplates[index].phase && sampledValueTemplates[index]?.measurand === measurand |
| 236 | && this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(measurand)) { |
| 237 | return sampledValueTemplates[index]; |
| 238 | } else if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER |
| 239 | && (!sampledValueTemplates[index].measurand || sampledValueTemplates[index].measurand === measurand)) { |
| 240 | return sampledValueTemplates[index]; |
| 241 | } |
| 242 | } |
| 243 | if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) { |
| 244 | logger.error(`${this.logPrefix()} Missing MeterValues for default measurand ${measurand} in template on connectorId ${connectorId}`); |
| 245 | } |
| 246 | logger.debug(`${this.logPrefix()} No MeterValues for measurand ${measurand} ${phase ? `on phase ${phase} ` : ''}in template on connectorId ${connectorId}`); |
| 247 | } |
| 248 | |
| 249 | public getAutomaticTransactionGeneratorRequireAuthorize(): boolean { |
| 250 | return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true; |
| 251 | } |
| 252 | |
| 253 | public startHeartbeat(): void { |
| 254 | if (this.getHeartbeatInterval() && this.getHeartbeatInterval() > 0 && !this.heartbeatSetInterval) { |
| 255 | // eslint-disable-next-line @typescript-eslint/no-misused-promises |
| 256 | this.heartbeatSetInterval = setInterval(async (): Promise<void> => { |
| 257 | await this.ocppRequestService.sendHeartbeat(); |
| 258 | }, this.getHeartbeatInterval()); |
| 259 | logger.info(this.logPrefix() + ' Heartbeat started every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval())); |
| 260 | } else if (this.heartbeatSetInterval) { |
| 261 | logger.info(this.logPrefix() + ' Heartbeat already started every ' + Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval())); |
| 262 | } else { |
| 263 | logger.error(`${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this.getHeartbeatInterval()) : this.getHeartbeatInterval()}, not starting the heartbeat`); |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | public restartHeartbeat(): void { |
| 268 | // Stop heartbeat |
| 269 | this.stopHeartbeat(); |
| 270 | // Start heartbeat |
| 271 | this.startHeartbeat(); |
| 272 | } |
| 273 | |
| 274 | public startMeterValues(connectorId: number, interval: number): void { |
| 275 | if (connectorId === 0) { |
| 276 | logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`); |
| 277 | return; |
| 278 | } |
| 279 | if (!this.getConnector(connectorId)) { |
| 280 | logger.error(`${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`); |
| 281 | return; |
| 282 | } |
| 283 | if (!this.getConnector(connectorId)?.transactionStarted) { |
| 284 | logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`); |
| 285 | return; |
| 286 | } else if (this.getConnector(connectorId)?.transactionStarted && !this.getConnector(connectorId)?.transactionId) { |
| 287 | logger.error(`${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`); |
| 288 | return; |
| 289 | } |
| 290 | if (interval > 0) { |
| 291 | // eslint-disable-next-line @typescript-eslint/no-misused-promises |
| 292 | this.getConnector(connectorId).transactionSetInterval = setInterval(async (): Promise<void> => { |
| 293 | await this.ocppRequestService.sendMeterValues(connectorId, this.getConnector(connectorId).transactionId, interval); |
| 294 | }, interval); |
| 295 | } else { |
| 296 | logger.error(`${this.logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${interval ? Utils.milliSecondsToHHMMSS(interval) : interval}, not sending MeterValues`); |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | public start(): void { |
| 301 | if (this.getEnableStatistics()) { |
| 302 | this.performanceStatistics.start(); |
| 303 | } |
| 304 | this.openWSConnection(); |
| 305 | // Monitor authorization file |
| 306 | this.startAuthorizationFileMonitoring(); |
| 307 | // Monitor station template file |
| 308 | this.startStationTemplateFileMonitoring(); |
| 309 | // Handle Socket incoming messages |
| 310 | this.wsConnection.on('message', this.onMessage.bind(this)); |
| 311 | // Handle Socket error |
| 312 | this.wsConnection.on('error', this.onError.bind(this)); |
| 313 | // Handle Socket close |
| 314 | this.wsConnection.on('close', this.onClose.bind(this)); |
| 315 | // Handle Socket opening connection |
| 316 | this.wsConnection.on('open', this.onOpen.bind(this)); |
| 317 | // Handle Socket ping |
| 318 | this.wsConnection.on('ping', this.onPing.bind(this)); |
| 319 | // Handle Socket pong |
| 320 | this.wsConnection.on('pong', this.onPong.bind(this)); |
| 321 | } |
| 322 | |
| 323 | public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> { |
| 324 | // Stop message sequence |
| 325 | await this.stopMessageSequence(reason); |
| 326 | for (const connector in this.connectors) { |
| 327 | if (Utils.convertToInt(connector) > 0) { |
| 328 | await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.UNAVAILABLE); |
| 329 | this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.UNAVAILABLE; |
| 330 | } |
| 331 | } |
| 332 | if (this.isWebSocketOpen()) { |
| 333 | this.wsConnection.close(); |
| 334 | } |
| 335 | if (this.getEnableStatistics()) { |
| 336 | this.performanceStatistics.stop(); |
| 337 | } |
| 338 | this.bootNotificationResponse = null; |
| 339 | this.hasStopped = true; |
| 340 | } |
| 341 | |
| 342 | public getConfigurationKey(key: string | StandardParametersKey, caseInsensitive = false): ConfigurationKey | undefined { |
| 343 | return this.configuration.configurationKey.find((configElement) => { |
| 344 | if (caseInsensitive) { |
| 345 | return configElement.key.toLowerCase() === key.toLowerCase(); |
| 346 | } |
| 347 | return configElement.key === key; |
| 348 | }); |
| 349 | } |
| 350 | |
| 351 | public addConfigurationKey(key: string | StandardParametersKey, value: string, readonly = false, visible = true, reboot = false): void { |
| 352 | const keyFound = this.getConfigurationKey(key); |
| 353 | if (!keyFound) { |
| 354 | this.configuration.configurationKey.push({ |
| 355 | key, |
| 356 | readonly, |
| 357 | value, |
| 358 | visible, |
| 359 | reboot, |
| 360 | }); |
| 361 | } else { |
| 362 | logger.error(`${this.logPrefix()} Trying to add an already existing configuration key: %j`, keyFound); |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void { |
| 367 | const keyFound = this.getConfigurationKey(key); |
| 368 | if (keyFound) { |
| 369 | const keyIndex = this.configuration.configurationKey.indexOf(keyFound); |
| 370 | this.configuration.configurationKey[keyIndex].value = value; |
| 371 | } else { |
| 372 | logger.error(`${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key, value }); |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | public setChargingProfile(connectorId: number, cp: ChargingProfile): void { |
| 377 | let cpReplaced = false; |
| 378 | if (!Utils.isEmptyArray(this.getConnector(connectorId).chargingProfiles)) { |
| 379 | this.getConnector(connectorId).chargingProfiles?.forEach((chargingProfile: ChargingProfile, index: number) => { |
| 380 | if (chargingProfile.chargingProfileId === cp.chargingProfileId |
| 381 | || (chargingProfile.stackLevel === cp.stackLevel && chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)) { |
| 382 | this.getConnector(connectorId).chargingProfiles[index] = cp; |
| 383 | cpReplaced = true; |
| 384 | } |
| 385 | }); |
| 386 | } |
| 387 | !cpReplaced && this.getConnector(connectorId).chargingProfiles?.push(cp); |
| 388 | } |
| 389 | |
| 390 | public resetTransactionOnConnector(connectorId: number): void { |
| 391 | this.getConnector(connectorId).authorized = false; |
| 392 | this.getConnector(connectorId).transactionStarted = false; |
| 393 | delete this.getConnector(connectorId).authorizeIdTag; |
| 394 | delete this.getConnector(connectorId).transactionId; |
| 395 | delete this.getConnector(connectorId).transactionIdTag; |
| 396 | this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue = 0; |
| 397 | delete this.getConnector(connectorId).transactionBeginMeterValue; |
| 398 | this.stopMeterValues(connectorId); |
| 399 | } |
| 400 | |
| 401 | public addToMessageQueue(message: string): void { |
| 402 | let dups = false; |
| 403 | // Handle dups in message queue |
| 404 | for (const bufferedMessage of this.messageQueue) { |
| 405 | // Message already in the queue |
| 406 | if (message === bufferedMessage) { |
| 407 | dups = true; |
| 408 | break; |
| 409 | } |
| 410 | } |
| 411 | if (!dups) { |
| 412 | // Queue message |
| 413 | this.messageQueue.push(message); |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | private flushMessageQueue() { |
| 418 | if (!Utils.isEmptyArray(this.messageQueue)) { |
| 419 | this.messageQueue.forEach((message, index) => { |
| 420 | this.messageQueue.splice(index, 1); |
| 421 | // TODO: evaluate the need to track performance |
| 422 | this.wsConnection.send(message); |
| 423 | }); |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | private getChargingStationId(stationTemplate: ChargingStationTemplate): string { |
| 428 | // In case of multiple instances: add instance index to charging station id |
| 429 | let instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0; |
| 430 | instanceIndex = instanceIndex > 0 ? instanceIndex : ''; |
| 431 | const idSuffix = stationTemplate.nameSuffix ?? ''; |
| 432 | return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex.toString() + ('000000000' + this.index.toString()).substr(('000000000' + this.index.toString()).length - 4) + idSuffix; |
| 433 | } |
| 434 | |
| 435 | private buildStationInfo(): ChargingStationInfo { |
| 436 | let stationTemplateFromFile: ChargingStationTemplate; |
| 437 | try { |
| 438 | // Load template file |
| 439 | const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r'); |
| 440 | stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate; |
| 441 | fs.closeSync(fileDescriptor); |
| 442 | } catch (error) { |
| 443 | FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error); |
| 444 | } |
| 445 | const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? {} as ChargingStationInfo; |
| 446 | if (!Utils.isEmptyArray(stationTemplateFromFile.power)) { |
| 447 | stationTemplateFromFile.power = stationTemplateFromFile.power as number[]; |
| 448 | const powerArrayRandomIndex = Math.floor(Math.random() * stationTemplateFromFile.power.length); |
| 449 | stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT |
| 450 | ? stationTemplateFromFile.power[powerArrayRandomIndex] * 1000 |
| 451 | : stationTemplateFromFile.power[powerArrayRandomIndex]; |
| 452 | } else { |
| 453 | stationTemplateFromFile.power = stationTemplateFromFile.power as number; |
| 454 | stationInfo.maxPower = stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT |
| 455 | ? stationTemplateFromFile.power * 1000 |
| 456 | : stationTemplateFromFile.power; |
| 457 | } |
| 458 | delete stationInfo.power; |
| 459 | delete stationInfo.powerUnit; |
| 460 | stationInfo.chargingStationId = this.getChargingStationId(stationTemplateFromFile); |
| 461 | stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME; |
| 462 | return stationInfo; |
| 463 | } |
| 464 | |
| 465 | private getOCPPVersion(): OCPPVersion { |
| 466 | return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16; |
| 467 | } |
| 468 | |
| 469 | private handleUnsupportedVersion(version: OCPPVersion) { |
| 470 | const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${this.stationTemplateFile}`; |
| 471 | logger.error(errMsg); |
| 472 | throw new Error(errMsg); |
| 473 | } |
| 474 | |
| 475 | private initialize(): void { |
| 476 | this.stationInfo = this.buildStationInfo(); |
| 477 | this.bootNotificationRequest = { |
| 478 | chargePointModel: this.stationInfo.chargePointModel, |
| 479 | chargePointVendor: this.stationInfo.chargePointVendor, |
| 480 | ...!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix }, |
| 481 | ...!Utils.isUndefined(this.stationInfo.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion }, |
| 482 | }; |
| 483 | this.configuration = this.getTemplateChargingStationConfiguration(); |
| 484 | this.wsConnectionUrl = new URL(this.getSupervisionURL().href + '/' + this.stationInfo.chargingStationId); |
| 485 | // Build connectors if needed |
| 486 | const maxConnectors = this.getMaxNumberOfConnectors(); |
| 487 | if (maxConnectors <= 0) { |
| 488 | logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with ${maxConnectors} connectors`); |
| 489 | } |
| 490 | const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors(); |
| 491 | if (templateMaxConnectors <= 0) { |
| 492 | logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector configuration`); |
| 493 | } |
| 494 | if (!this.stationInfo.Connectors[0]) { |
| 495 | logger.warn(`${this.logPrefix()} Charging station template ${this.stationTemplateFile} with no connector Id 0 configuration`); |
| 496 | } |
| 497 | // Sanity check |
| 498 | if (maxConnectors > (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this.stationInfo.randomConnectors) { |
| 499 | logger.warn(`${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this.stationTemplateFile}, forcing random connector configurations affectation`); |
| 500 | this.stationInfo.randomConnectors = true; |
| 501 | } |
| 502 | const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString()).digest('hex'); |
| 503 | // FIXME: Handle shrinking the number of connectors |
| 504 | if (!this.connectors || (this.connectors && this.connectorsConfigurationHash !== connectorsConfigHash)) { |
| 505 | this.connectorsConfigurationHash = connectorsConfigHash; |
| 506 | // Add connector Id 0 |
| 507 | let lastConnector = '0'; |
| 508 | for (lastConnector in this.stationInfo.Connectors) { |
| 509 | if (Utils.convertToInt(lastConnector) === 0 && this.getUseConnectorId0() && this.stationInfo.Connectors[lastConnector]) { |
| 510 | this.connectors[lastConnector] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[lastConnector]); |
| 511 | this.connectors[lastConnector].availability = AvailabilityType.OPERATIVE; |
| 512 | if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) { |
| 513 | this.connectors[lastConnector].chargingProfiles = []; |
| 514 | } |
| 515 | } |
| 516 | } |
| 517 | // Generate all connectors |
| 518 | if ((this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) { |
| 519 | for (let index = 1; index <= maxConnectors; index++) { |
| 520 | const randConnectorId = this.stationInfo.randomConnectors ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index; |
| 521 | this.connectors[index] = Utils.cloneObject<Connector>(this.stationInfo.Connectors[randConnectorId]); |
| 522 | this.connectors[index].availability = AvailabilityType.OPERATIVE; |
| 523 | if (Utils.isUndefined(this.connectors[lastConnector]?.chargingProfiles)) { |
| 524 | this.connectors[index].chargingProfiles = []; |
| 525 | } |
| 526 | } |
| 527 | } |
| 528 | } |
| 529 | // Avoid duplication of connectors related information |
| 530 | delete this.stationInfo.Connectors; |
| 531 | // Initialize transaction attributes on connectors |
| 532 | for (const connector in this.connectors) { |
| 533 | if (Utils.convertToInt(connector) > 0 && !this.getConnector(Utils.convertToInt(connector)).transactionStarted) { |
| 534 | this.initTransactionAttributesOnConnector(Utils.convertToInt(connector)); |
| 535 | } |
| 536 | } |
| 537 | switch (this.getOCPPVersion()) { |
| 538 | case OCPPVersion.VERSION_16: |
| 539 | this.ocppIncomingRequestService = new OCPP16IncomingRequestService(this); |
| 540 | this.ocppRequestService = new OCPP16RequestService(this, new OCPP16ResponseService(this)); |
| 541 | break; |
| 542 | default: |
| 543 | this.handleUnsupportedVersion(this.getOCPPVersion()); |
| 544 | break; |
| 545 | } |
| 546 | // OCPP parameters |
| 547 | this.initOCPPParameters(); |
| 548 | if (this.stationInfo.autoRegister) { |
| 549 | this.bootNotificationResponse = { |
| 550 | currentTime: new Date().toISOString(), |
| 551 | interval: this.getHeartbeatInterval() / 1000, |
| 552 | status: RegistrationStatus.ACCEPTED |
| 553 | }; |
| 554 | } |
| 555 | this.stationInfo.powerDivider = this.getPowerDivider(); |
| 556 | if (this.getEnableStatistics()) { |
| 557 | this.performanceStatistics = new PerformanceStatistics(this.stationInfo.chargingStationId); |
| 558 | } |
| 559 | } |
| 560 | |
| 561 | private initOCPPParameters(): void { |
| 562 | if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) { |
| 563 | this.addConfigurationKey(StandardParametersKey.SupportedFeatureProfiles, `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`); |
| 564 | } |
| 565 | this.addConfigurationKey(StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), true); |
| 566 | if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) { |
| 567 | this.addConfigurationKey(StandardParametersKey.MeterValuesSampledData, MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER); |
| 568 | } |
| 569 | if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) { |
| 570 | const connectorPhaseRotation = []; |
| 571 | for (const connector in this.connectors) { |
| 572 | // AC/DC |
| 573 | if (Utils.convertToInt(connector) === 0 && this.getNumberOfPhases() === 0) { |
| 574 | connectorPhaseRotation.push(`${connector}.${ConnectorPhaseRotation.RST}`); |
| 575 | } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 0) { |
| 576 | connectorPhaseRotation.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`); |
| 577 | // AC |
| 578 | } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 1) { |
| 579 | connectorPhaseRotation.push(`${connector}.${ConnectorPhaseRotation.NotApplicable}`); |
| 580 | } else if (Utils.convertToInt(connector) > 0 && this.getNumberOfPhases() === 3) { |
| 581 | connectorPhaseRotation.push(`${connector}.${ConnectorPhaseRotation.RST}`); |
| 582 | } |
| 583 | } |
| 584 | this.addConfigurationKey(StandardParametersKey.ConnectorPhaseRotation, connectorPhaseRotation.toString()); |
| 585 | } |
| 586 | if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) { |
| 587 | this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true'); |
| 588 | } |
| 589 | if (!this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled) |
| 590 | && this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles).value.includes(SupportedFeatureProfiles.Local_Auth_List_Management)) { |
| 591 | this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false'); |
| 592 | } |
| 593 | if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) { |
| 594 | this.addConfigurationKey(StandardParametersKey.ConnectionTimeOut, Constants.DEFAULT_CONNECTION_TIMEOUT.toString()); |
| 595 | } |
| 596 | } |
| 597 | |
| 598 | private async onOpen(): Promise<void> { |
| 599 | logger.info(`${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`); |
| 600 | if (!this.isRegistered()) { |
| 601 | // Send BootNotification |
| 602 | let registrationRetryCount = 0; |
| 603 | do { |
| 604 | this.bootNotificationResponse = await this.ocppRequestService.sendBootNotification(this.bootNotificationRequest.chargePointModel, |
| 605 | this.bootNotificationRequest.chargePointVendor, this.bootNotificationRequest.chargeBoxSerialNumber, this.bootNotificationRequest.firmwareVersion); |
| 606 | if (!this.isRegistered()) { |
| 607 | registrationRetryCount++; |
| 608 | await Utils.sleep(this.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL); |
| 609 | } |
| 610 | } while (!this.isRegistered() && (registrationRetryCount <= this.getRegistrationMaxRetries() || this.getRegistrationMaxRetries() === -1)); |
| 611 | } |
| 612 | if (this.isRegistered()) { |
| 613 | await this.startMessageSequence(); |
| 614 | this.hasStopped && (this.hasStopped = false); |
| 615 | if (this.hasSocketRestarted && this.isWebSocketOpen()) { |
| 616 | this.flushMessageQueue(); |
| 617 | } |
| 618 | } else { |
| 619 | logger.error(`${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`); |
| 620 | } |
| 621 | this.autoReconnectRetryCount = 0; |
| 622 | this.hasSocketRestarted = false; |
| 623 | } |
| 624 | |
| 625 | private async onClose(closeEvent: any): Promise<void> { |
| 626 | switch (closeEvent) { |
| 627 | case WebSocketCloseEventStatusCode.CLOSE_NORMAL: // Normal close |
| 628 | case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS: |
| 629 | logger.info(`${this.logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`); |
| 630 | this.autoReconnectRetryCount = 0; |
| 631 | break; |
| 632 | default: // Abnormal close |
| 633 | logger.error(`${this.logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`); |
| 634 | await this.reconnect(closeEvent); |
| 635 | break; |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | private async onMessage(messageEvent: MessageEvent): Promise<void> { |
| 640 | let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, {}, {}]; |
| 641 | let responseCallback: (payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>) => void; |
| 642 | let rejectCallback: (error: OCPPError) => void; |
| 643 | let requestPayload: Record<string, unknown>; |
| 644 | let errMsg: string; |
| 645 | try { |
| 646 | const request = JSON.parse(messageEvent.toString()) as IncomingRequest; |
| 647 | if (Utils.isIterable(request)) { |
| 648 | // Parse the message |
| 649 | [messageType, messageId, commandName, commandPayload, errorDetails] = request; |
| 650 | } else { |
| 651 | throw new Error('Incoming request is not iterable'); |
| 652 | } |
| 653 | // Check the Type of message |
| 654 | switch (messageType) { |
| 655 | // Incoming Message |
| 656 | case MessageType.CALL_MESSAGE: |
| 657 | if (this.getEnableStatistics()) { |
| 658 | this.performanceStatistics.addRequestStatistic(commandName, messageType); |
| 659 | } |
| 660 | // Process the call |
| 661 | await this.ocppIncomingRequestService.handleRequest(messageId, commandName, commandPayload); |
| 662 | break; |
| 663 | // Outcome Message |
| 664 | case MessageType.CALL_RESULT_MESSAGE: |
| 665 | // Respond |
| 666 | if (Utils.isIterable(this.requests[messageId])) { |
| 667 | [responseCallback, , requestPayload] = this.requests[messageId]; |
| 668 | } else { |
| 669 | throw new Error(`Response request for message id ${messageId} is not iterable`); |
| 670 | } |
| 671 | if (!responseCallback) { |
| 672 | // Error |
| 673 | throw new Error(`Response request for unknown message id ${messageId}`); |
| 674 | } |
| 675 | delete this.requests[messageId]; |
| 676 | responseCallback(commandName, requestPayload); |
| 677 | break; |
| 678 | // Error Message |
| 679 | case MessageType.CALL_ERROR_MESSAGE: |
| 680 | if (!this.requests[messageId]) { |
| 681 | // Error |
| 682 | throw new Error(`Error request for unknown message id ${messageId}`); |
| 683 | } |
| 684 | if (Utils.isIterable(this.requests[messageId])) { |
| 685 | [, rejectCallback] = this.requests[messageId]; |
| 686 | } else { |
| 687 | throw new Error(`Error request for message id ${messageId} is not iterable`); |
| 688 | } |
| 689 | delete this.requests[messageId]; |
| 690 | rejectCallback(new OCPPError(commandName, commandPayload.toString(), errorDetails)); |
| 691 | break; |
| 692 | // Error |
| 693 | default: |
| 694 | errMsg = `${this.logPrefix()} Wrong message type ${messageType}`; |
| 695 | logger.error(errMsg); |
| 696 | throw new Error(errMsg); |
| 697 | } |
| 698 | } catch (error) { |
| 699 | // Log |
| 700 | logger.error('%s Incoming request message %j processing error %j on content type %j', this.logPrefix(), messageEvent, error, this.requests[messageId]); |
| 701 | // Send error |
| 702 | messageType !== MessageType.CALL_ERROR_MESSAGE && await this.ocppRequestService.sendError(messageId, error, commandName); |
| 703 | } |
| 704 | } |
| 705 | |
| 706 | private onPing(): void { |
| 707 | logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server'); |
| 708 | } |
| 709 | |
| 710 | private onPong(): void { |
| 711 | logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server'); |
| 712 | } |
| 713 | |
| 714 | private async onError(errorEvent: any): Promise<void> { |
| 715 | logger.error(this.logPrefix() + ' Socket error: %j', errorEvent); |
| 716 | // switch (errorEvent.code) { |
| 717 | // case 'ECONNREFUSED': |
| 718 | // await this._reconnect(errorEvent); |
| 719 | // break; |
| 720 | // } |
| 721 | } |
| 722 | |
| 723 | private getTemplateChargingStationConfiguration(): ChargingStationConfiguration { |
| 724 | return this.stationInfo.Configuration ?? {} as ChargingStationConfiguration; |
| 725 | } |
| 726 | |
| 727 | private getAuthorizationFile(): string | undefined { |
| 728 | return this.stationInfo.authorizationFile && path.join(path.resolve(__dirname, '../'), 'assets', path.basename(this.stationInfo.authorizationFile)); |
| 729 | } |
| 730 | |
| 731 | private getAuthorizedTags(): string[] { |
| 732 | let authorizedTags: string[] = []; |
| 733 | const authorizationFile = this.getAuthorizationFile(); |
| 734 | if (authorizationFile) { |
| 735 | try { |
| 736 | // Load authorization file |
| 737 | const fileDescriptor = fs.openSync(authorizationFile, 'r'); |
| 738 | authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[]; |
| 739 | fs.closeSync(fileDescriptor); |
| 740 | } catch (error) { |
| 741 | FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error); |
| 742 | } |
| 743 | } else { |
| 744 | logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile); |
| 745 | } |
| 746 | return authorizedTags; |
| 747 | } |
| 748 | |
| 749 | private getUseConnectorId0(): boolean | undefined { |
| 750 | return !Utils.isUndefined(this.stationInfo.useConnectorId0) ? this.stationInfo.useConnectorId0 : true; |
| 751 | } |
| 752 | |
| 753 | private getNumberOfRunningTransactions(): number { |
| 754 | let trxCount = 0; |
| 755 | for (const connector in this.connectors) { |
| 756 | if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) { |
| 757 | trxCount++; |
| 758 | } |
| 759 | } |
| 760 | return trxCount; |
| 761 | } |
| 762 | |
| 763 | // 0 for disabling |
| 764 | private getConnectionTimeout(): number | undefined { |
| 765 | if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) { |
| 766 | return parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ?? Constants.DEFAULT_CONNECTION_TIMEOUT; |
| 767 | } |
| 768 | return Constants.DEFAULT_CONNECTION_TIMEOUT; |
| 769 | } |
| 770 | |
| 771 | // -1 for unlimited, 0 for disabling |
| 772 | private getAutoReconnectMaxRetries(): number | undefined { |
| 773 | if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) { |
| 774 | return this.stationInfo.autoReconnectMaxRetries; |
| 775 | } |
| 776 | if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) { |
| 777 | return Configuration.getAutoReconnectMaxRetries(); |
| 778 | } |
| 779 | return -1; |
| 780 | } |
| 781 | |
| 782 | // 0 for disabling |
| 783 | private getRegistrationMaxRetries(): number | undefined { |
| 784 | if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) { |
| 785 | return this.stationInfo.registrationMaxRetries; |
| 786 | } |
| 787 | return -1; |
| 788 | } |
| 789 | |
| 790 | private getPowerDivider(): number { |
| 791 | let powerDivider = this.getNumberOfConnectors(); |
| 792 | if (this.stationInfo.powerSharedByConnectors) { |
| 793 | powerDivider = this.getNumberOfRunningTransactions(); |
| 794 | } |
| 795 | return powerDivider; |
| 796 | } |
| 797 | |
| 798 | private getTemplateMaxNumberOfConnectors(): number { |
| 799 | return Object.keys(this.stationInfo.Connectors).length; |
| 800 | } |
| 801 | |
| 802 | private getMaxNumberOfConnectors(): number { |
| 803 | let maxConnectors = 0; |
| 804 | if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) { |
| 805 | const numberOfConnectors = this.stationInfo.numberOfConnectors as number[]; |
| 806 | // Distribute evenly the number of connectors |
| 807 | maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length]; |
| 808 | } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) { |
| 809 | maxConnectors = this.stationInfo.numberOfConnectors as number; |
| 810 | } else { |
| 811 | maxConnectors = this.stationInfo.Connectors[0] ? this.getTemplateMaxNumberOfConnectors() - 1 : this.getTemplateMaxNumberOfConnectors(); |
| 812 | } |
| 813 | return maxConnectors; |
| 814 | } |
| 815 | |
| 816 | private getNumberOfConnectors(): number { |
| 817 | return this.connectors[0] ? Object.keys(this.connectors).length - 1 : Object.keys(this.connectors).length; |
| 818 | } |
| 819 | |
| 820 | private async startMessageSequence(): Promise<void> { |
| 821 | // Start WebSocket ping |
| 822 | this.startWebSocketPing(); |
| 823 | // Start heartbeat |
| 824 | this.startHeartbeat(); |
| 825 | // Initialize connectors status |
| 826 | for (const connector in this.connectors) { |
| 827 | if (Utils.convertToInt(connector) === 0) { |
| 828 | continue; |
| 829 | } else if (!this.hasStopped && !this.getConnector(Utils.convertToInt(connector))?.status && this.getConnector(Utils.convertToInt(connector))?.bootStatus) { |
| 830 | // Send status in template at startup |
| 831 | await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus); |
| 832 | this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus; |
| 833 | } else if (this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.bootStatus) { |
| 834 | // Send status in template after reset |
| 835 | await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus); |
| 836 | this.getConnector(Utils.convertToInt(connector)).status = this.getConnector(Utils.convertToInt(connector)).bootStatus; |
| 837 | } else if (!this.hasStopped && this.getConnector(Utils.convertToInt(connector))?.status) { |
| 838 | // Send previous status at template reload |
| 839 | await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).status); |
| 840 | } else { |
| 841 | // Send default status |
| 842 | await this.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.AVAILABLE); |
| 843 | this.getConnector(Utils.convertToInt(connector)).status = ChargePointStatus.AVAILABLE; |
| 844 | } |
| 845 | } |
| 846 | // Start the ATG |
| 847 | this.startAutomaticTransactionGenerator(); |
| 848 | } |
| 849 | |
| 850 | private startAutomaticTransactionGenerator() { |
| 851 | if (this.stationInfo.AutomaticTransactionGenerator.enable) { |
| 852 | if (!this.automaticTransactionGeneration) { |
| 853 | this.automaticTransactionGeneration = new AutomaticTransactionGenerator(this); |
| 854 | } |
| 855 | if (this.automaticTransactionGeneration.timeToStop) { |
| 856 | // The ATG might sleep |
| 857 | void this.automaticTransactionGeneration.start(); |
| 858 | } |
| 859 | } |
| 860 | } |
| 861 | |
| 862 | private async stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> { |
| 863 | // Stop WebSocket ping |
| 864 | this.stopWebSocketPing(); |
| 865 | // Stop heartbeat |
| 866 | this.stopHeartbeat(); |
| 867 | // Stop the ATG |
| 868 | if (this.stationInfo.AutomaticTransactionGenerator.enable && |
| 869 | this.automaticTransactionGeneration && |
| 870 | !this.automaticTransactionGeneration.timeToStop) { |
| 871 | await this.automaticTransactionGeneration.stop(reason); |
| 872 | } else { |
| 873 | for (const connector in this.connectors) { |
| 874 | if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) { |
| 875 | const transactionId = this.getConnector(Utils.convertToInt(connector)).transactionId; |
| 876 | await this.ocppRequestService.sendStopTransaction(transactionId, this.getEnergyActiveImportRegisterByTransactionId(transactionId), |
| 877 | this.getTransactionIdTag(transactionId), reason); |
| 878 | } |
| 879 | } |
| 880 | } |
| 881 | } |
| 882 | |
| 883 | private startWebSocketPing(): void { |
| 884 | const webSocketPingInterval: number = this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval) |
| 885 | ? Utils.convertToInt(this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value) |
| 886 | : 0; |
| 887 | if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) { |
| 888 | this.webSocketPingSetInterval = setInterval(() => { |
| 889 | if (this.isWebSocketOpen()) { |
| 890 | this.wsConnection.ping((): void => { }); |
| 891 | } |
| 892 | }, webSocketPingInterval * 1000); |
| 893 | logger.info(this.logPrefix() + ' WebSocket ping started every ' + Utils.secondsToHHMMSS(webSocketPingInterval)); |
| 894 | } else if (this.webSocketPingSetInterval) { |
| 895 | logger.info(this.logPrefix() + ' WebSocket ping every ' + Utils.secondsToHHMMSS(webSocketPingInterval) + ' already started'); |
| 896 | } else { |
| 897 | logger.error(`${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`); |
| 898 | } |
| 899 | } |
| 900 | |
| 901 | private stopWebSocketPing(): void { |
| 902 | if (this.webSocketPingSetInterval) { |
| 903 | clearInterval(this.webSocketPingSetInterval); |
| 904 | } |
| 905 | } |
| 906 | |
| 907 | private getSupervisionURL(): URL { |
| 908 | const supervisionUrls = Utils.cloneObject<string | string[]>(this.stationInfo.supervisionURL ? this.stationInfo.supervisionURL : Configuration.getSupervisionURLs()); |
| 909 | let indexUrl = 0; |
| 910 | if (!Utils.isEmptyArray(supervisionUrls)) { |
| 911 | if (Configuration.getDistributeStationsToTenantsEqually()) { |
| 912 | indexUrl = this.index % supervisionUrls.length; |
| 913 | } else { |
| 914 | // Get a random url |
| 915 | indexUrl = Math.floor(Math.random() * supervisionUrls.length); |
| 916 | } |
| 917 | return new URL(supervisionUrls[indexUrl]); |
| 918 | } |
| 919 | return new URL(supervisionUrls as string); |
| 920 | } |
| 921 | |
| 922 | private getHeartbeatInterval(): number | undefined { |
| 923 | const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval); |
| 924 | if (HeartbeatInterval) { |
| 925 | return Utils.convertToInt(HeartbeatInterval.value) * 1000; |
| 926 | } |
| 927 | const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval); |
| 928 | if (HeartBeatInterval) { |
| 929 | return Utils.convertToInt(HeartBeatInterval.value) * 1000; |
| 930 | } |
| 931 | !this.stationInfo.autoRegister && logger.warn(`${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${Constants.DEFAULT_HEARTBEAT_INTERVAL}`); |
| 932 | return Constants.DEFAULT_HEARTBEAT_INTERVAL; |
| 933 | } |
| 934 | |
| 935 | private stopHeartbeat(): void { |
| 936 | if (this.heartbeatSetInterval) { |
| 937 | clearInterval(this.heartbeatSetInterval); |
| 938 | } |
| 939 | } |
| 940 | |
| 941 | private openWSConnection(options?: WebSocket.ClientOptions, forceCloseOpened = false): void { |
| 942 | options ?? {} as WebSocket.ClientOptions; |
| 943 | options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000; |
| 944 | if (this.isWebSocketOpen() && forceCloseOpened) { |
| 945 | this.wsConnection.close(); |
| 946 | } |
| 947 | let protocol; |
| 948 | switch (this.getOCPPVersion()) { |
| 949 | case OCPPVersion.VERSION_16: |
| 950 | protocol = 'ocpp' + OCPPVersion.VERSION_16; |
| 951 | break; |
| 952 | default: |
| 953 | this.handleUnsupportedVersion(this.getOCPPVersion()); |
| 954 | break; |
| 955 | } |
| 956 | this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options); |
| 957 | logger.info(this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString()); |
| 958 | } |
| 959 | |
| 960 | private stopMeterValues(connectorId: number) { |
| 961 | if (this.getConnector(connectorId)?.transactionSetInterval) { |
| 962 | clearInterval(this.getConnector(connectorId).transactionSetInterval); |
| 963 | } |
| 964 | } |
| 965 | |
| 966 | private startAuthorizationFileMonitoring(): void { |
| 967 | const authorizationFile = this.getAuthorizationFile(); |
| 968 | if (authorizationFile) { |
| 969 | try { |
| 970 | fs.watch(authorizationFile).on('change', () => { |
| 971 | try { |
| 972 | logger.debug(this.logPrefix() + ' Authorization file ' + authorizationFile + ' have changed, reload'); |
| 973 | // Initialize authorizedTags |
| 974 | this.authorizedTags = this.getAuthorizedTags(); |
| 975 | } catch (error) { |
| 976 | logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error); |
| 977 | } |
| 978 | }); |
| 979 | } catch (error) { |
| 980 | FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, error); |
| 981 | } |
| 982 | } else { |
| 983 | logger.info(this.logPrefix() + ' No authorization file given in template file ' + this.stationTemplateFile + '. Not monitoring changes'); |
| 984 | } |
| 985 | } |
| 986 | |
| 987 | private startStationTemplateFileMonitoring(): void { |
| 988 | try { |
| 989 | // eslint-disable-next-line @typescript-eslint/no-misused-promises |
| 990 | fs.watch(this.stationTemplateFile).on('change', async (): Promise<void> => { |
| 991 | try { |
| 992 | logger.debug(this.logPrefix() + ' Template file ' + this.stationTemplateFile + ' have changed, reload'); |
| 993 | // Initialize |
| 994 | this.initialize(); |
| 995 | // Restart the ATG |
| 996 | if (!this.stationInfo.AutomaticTransactionGenerator.enable && |
| 997 | this.automaticTransactionGeneration) { |
| 998 | await this.automaticTransactionGeneration.stop(); |
| 999 | } |
| 1000 | this.startAutomaticTransactionGenerator(); |
| 1001 | if (this.getEnableStatistics()) { |
| 1002 | this.performanceStatistics.restart(); |
| 1003 | } else { |
| 1004 | this.performanceStatistics.stop(); |
| 1005 | } |
| 1006 | // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed |
| 1007 | } catch (error) { |
| 1008 | logger.error(this.logPrefix() + ' Charging station template file monitoring error: %j', error); |
| 1009 | } |
| 1010 | }); |
| 1011 | } catch (error) { |
| 1012 | FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error); |
| 1013 | } |
| 1014 | } |
| 1015 | |
| 1016 | private getReconnectExponentialDelay(): boolean | undefined { |
| 1017 | return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay) ? this.stationInfo.reconnectExponentialDelay : false; |
| 1018 | } |
| 1019 | |
| 1020 | private async reconnect(error: any): Promise<void> { |
| 1021 | // Stop WebSocket ping |
| 1022 | this.stopWebSocketPing(); |
| 1023 | // Stop heartbeat |
| 1024 | this.stopHeartbeat(); |
| 1025 | // Stop the ATG if needed |
| 1026 | if (this.stationInfo.AutomaticTransactionGenerator.enable && |
| 1027 | this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure && |
| 1028 | this.automaticTransactionGeneration && |
| 1029 | !this.automaticTransactionGeneration.timeToStop) { |
| 1030 | await this.automaticTransactionGeneration.stop(); |
| 1031 | } |
| 1032 | if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) { |
| 1033 | this.autoReconnectRetryCount++; |
| 1034 | const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000); |
| 1035 | logger.error(`${this.logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`); |
| 1036 | await Utils.sleep(reconnectDelay); |
| 1037 | logger.error(this.logPrefix() + ' Socket: reconnecting try #' + this.autoReconnectRetryCount.toString()); |
| 1038 | this.openWSConnection({ handshakeTimeout: reconnectDelay - 100 }); |
| 1039 | this.hasSocketRestarted = true; |
| 1040 | } else if (this.getAutoReconnectMaxRetries() !== -1) { |
| 1041 | logger.error(`${this.logPrefix()} Socket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`); |
| 1042 | } |
| 1043 | } |
| 1044 | |
| 1045 | private initTransactionAttributesOnConnector(connectorId: number): void { |
| 1046 | this.getConnector(connectorId).authorized = false; |
| 1047 | this.getConnector(connectorId).transactionStarted = false; |
| 1048 | this.getConnector(connectorId).energyActiveImportRegisterValue = 0; |
| 1049 | this.getConnector(connectorId).transactionEnergyActiveImportRegisterValue = 0; |
| 1050 | } |
| 1051 | } |
| 1052 | |