| 1 | import { AuthorizationStatus, AuthorizeRequest, AuthorizeResponse, StartTransactionRequest, StartTransactionResponse, StopTransactionReason, StopTransactionRequest, StopTransactionResponse } from '../types/ocpp/1.6/Transaction'; |
| 2 | import { AvailabilityType, BootNotificationRequest, ChangeAvailabilityRequest, ChangeConfigurationRequest, GetConfigurationRequest, HeartbeatRequest, IncomingRequestCommand, RemoteStartTransactionRequest, RemoteStopTransactionRequest, RequestCommand, ResetRequest, SetChargingProfileRequest, StatusNotificationRequest, UnlockConnectorRequest } from '../types/ocpp/1.6/Requests'; |
| 3 | import { BootNotificationResponse, ChangeAvailabilityResponse, ChangeConfigurationResponse, DefaultResponse, GetConfigurationResponse, HeartbeatResponse, RegistrationStatus, SetChargingProfileResponse, StatusNotificationResponse, UnlockConnectorResponse } from '../types/ocpp/1.6/RequestResponses'; |
| 4 | import { ChargingProfile, ChargingProfilePurposeType } from '../types/ocpp/1.6/ChargingProfile'; |
| 5 | import ChargingStationConfiguration, { ConfigurationKey } from '../types/ChargingStationConfiguration'; |
| 6 | import ChargingStationTemplate, { PowerOutType, VoltageOut } from '../types/ChargingStationTemplate'; |
| 7 | import Connectors, { Connector } from '../types/Connectors'; |
| 8 | import { MeterValue, MeterValueLocation, MeterValueMeasurand, MeterValuePhase, MeterValueUnit, MeterValuesRequest, MeterValuesResponse, SampledValue } from '../types/ocpp/1.6/MeterValues'; |
| 9 | import { PerformanceObserver, performance } from 'perf_hooks'; |
| 10 | import Requests, { IncomingRequest, Request } from '../types/ocpp/Requests'; |
| 11 | import WebSocket, { MessageEvent } from 'ws'; |
| 12 | |
| 13 | import AutomaticTransactionGenerator from './AutomaticTransactionGenerator'; |
| 14 | import { ChargePointErrorCode } from '../types/ocpp/1.6/ChargePointErrorCode'; |
| 15 | import { ChargePointStatus } from '../types/ocpp/1.6/ChargePointStatus'; |
| 16 | import ChargingStationInfo from '../types/ChargingStationInfo'; |
| 17 | import Configuration from '../utils/Configuration'; |
| 18 | import Constants from '../utils/Constants'; |
| 19 | import ElectricUtils from '../utils/ElectricUtils'; |
| 20 | import { ErrorType } from '../types/ocpp/ErrorType'; |
| 21 | import MeasurandValues from '../types/MeasurandValues'; |
| 22 | import { MessageType } from '../types/ocpp/MessageType'; |
| 23 | import { OCPPConfigurationKey } from '../types/ocpp/Configuration'; |
| 24 | import OCPPError from './OcppError'; |
| 25 | import { StandardParametersKey } from '../types/ocpp/1.6/Configuration'; |
| 26 | import Statistics from '../utils/Statistics'; |
| 27 | import Utils from '../utils/Utils'; |
| 28 | import { WebSocketCloseEventStatusCode } from '../types/WebSocket'; |
| 29 | import crypto from 'crypto'; |
| 30 | import fs from 'fs'; |
| 31 | import logger from '../utils/Logger'; |
| 32 | |
| 33 | export default class ChargingStation { |
| 34 | private _index: number; |
| 35 | private _stationTemplateFile: string; |
| 36 | private _stationInfo: ChargingStationInfo; |
| 37 | private _bootNotificationRequest: BootNotificationRequest; |
| 38 | private _bootNotificationResponse: BootNotificationResponse; |
| 39 | private _connectors: Connectors; |
| 40 | private _configuration: ChargingStationConfiguration; |
| 41 | private _connectorsConfigurationHash: string; |
| 42 | private _supervisionUrl: string; |
| 43 | private _wsConnectionUrl: string; |
| 44 | private _wsConnection: WebSocket; |
| 45 | private _hasStopped: boolean; |
| 46 | private _hasSocketRestarted: boolean; |
| 47 | private _autoReconnectRetryCount: number; |
| 48 | private _requests: Requests; |
| 49 | private _messageQueue: string[]; |
| 50 | private _automaticTransactionGeneration: AutomaticTransactionGenerator; |
| 51 | private _authorizedTags: string[]; |
| 52 | private _heartbeatSetInterval: NodeJS.Timeout; |
| 53 | private _webSocketPingSetInterval: NodeJS.Timeout; |
| 54 | private _statistics: Statistics; |
| 55 | private _performanceObserver: PerformanceObserver; |
| 56 | |
| 57 | constructor(index: number, stationTemplateFile: string) { |
| 58 | this._index = index; |
| 59 | this._stationTemplateFile = stationTemplateFile; |
| 60 | this._connectors = {} as Connectors; |
| 61 | this._initialize(); |
| 62 | |
| 63 | this._hasStopped = false; |
| 64 | this._hasSocketRestarted = false; |
| 65 | this._autoReconnectRetryCount = 0; |
| 66 | |
| 67 | this._requests = {} as Requests; |
| 68 | this._messageQueue = [] as string[]; |
| 69 | |
| 70 | this._authorizedTags = this._loadAndGetAuthorizedTags(); |
| 71 | } |
| 72 | |
| 73 | _getStationName(stationTemplate: ChargingStationTemplate): string { |
| 74 | // In case of multiple instances: add instance index to charging station id |
| 75 | let instanceIndex = process.env.CF_INSTANCE_INDEX ? process.env.CF_INSTANCE_INDEX : 0; |
| 76 | instanceIndex = instanceIndex > 0 ? instanceIndex : ''; |
| 77 | |
| 78 | const idSuffix = Configuration.getChargingStationIdSuffix(); |
| 79 | |
| 80 | return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + instanceIndex + ('000000000' + this._index.toString()).substr(('000000000' + this._index.toString()).length - 4) + idSuffix; |
| 81 | } |
| 82 | |
| 83 | _buildStationInfo(): ChargingStationInfo { |
| 84 | let stationTemplateFromFile: ChargingStationTemplate; |
| 85 | try { |
| 86 | // Load template file |
| 87 | const fileDescriptor = fs.openSync(this._stationTemplateFile, 'r'); |
| 88 | stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate; |
| 89 | fs.closeSync(fileDescriptor); |
| 90 | } catch (error) { |
| 91 | logger.error('Template file ' + this._stationTemplateFile + ' loading error: %j', error); |
| 92 | throw error; |
| 93 | } |
| 94 | const stationInfo: ChargingStationInfo = stationTemplateFromFile || {} as ChargingStationInfo; |
| 95 | if (!Utils.isEmptyArray(stationTemplateFromFile.power)) { |
| 96 | stationTemplateFromFile.power = stationTemplateFromFile.power as number[]; |
| 97 | stationInfo.maxPower = stationTemplateFromFile.power[Math.floor(Math.random() * stationTemplateFromFile.power.length)]; |
| 98 | } else { |
| 99 | stationInfo.maxPower = stationTemplateFromFile.power as number; |
| 100 | } |
| 101 | stationInfo.name = this._getStationName(stationTemplateFromFile); |
| 102 | stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME; |
| 103 | return stationInfo; |
| 104 | } |
| 105 | |
| 106 | get stationInfo(): ChargingStationInfo { |
| 107 | return this._stationInfo; |
| 108 | } |
| 109 | |
| 110 | _initialize(): void { |
| 111 | this._stationInfo = this._buildStationInfo(); |
| 112 | this._bootNotificationRequest = { |
| 113 | chargePointModel: this._stationInfo.chargePointModel, |
| 114 | chargePointVendor: this._stationInfo.chargePointVendor, |
| 115 | ...!Utils.isUndefined(this._stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this._stationInfo.chargeBoxSerialNumberPrefix }, |
| 116 | ...!Utils.isUndefined(this._stationInfo.firmwareVersion) && { firmwareVersion: this._stationInfo.firmwareVersion }, |
| 117 | }; |
| 118 | this._configuration = this._getTemplateChargingStationConfiguration(); |
| 119 | this._supervisionUrl = this._getSupervisionURL(); |
| 120 | this._wsConnectionUrl = this._supervisionUrl + '/' + this._stationInfo.name; |
| 121 | // Build connectors if needed |
| 122 | const maxConnectors = this._getMaxNumberOfConnectors(); |
| 123 | if (maxConnectors <= 0) { |
| 124 | logger.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with ${maxConnectors} connectors`); |
| 125 | } |
| 126 | const templateMaxConnectors = this._getTemplateMaxNumberOfConnectors(); |
| 127 | if (templateMaxConnectors <= 0) { |
| 128 | logger.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with no connector configuration`); |
| 129 | } |
| 130 | if (!this._stationInfo.Connectors[0]) { |
| 131 | logger.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with no connector Id 0 configuration`); |
| 132 | } |
| 133 | // Sanity check |
| 134 | if (maxConnectors > (this._stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this._stationInfo.randomConnectors) { |
| 135 | logger.warn(`${this._logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this._stationTemplateFile}, forcing random connector configurations affectation`); |
| 136 | this._stationInfo.randomConnectors = true; |
| 137 | } |
| 138 | const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this._stationInfo.Connectors) + maxConnectors.toString()).digest('hex'); |
| 139 | // FIXME: Handle shrinking the number of connectors |
| 140 | if (!this._connectors || (this._connectors && this._connectorsConfigurationHash !== connectorsConfigHash)) { |
| 141 | this._connectorsConfigurationHash = connectorsConfigHash; |
| 142 | // Add connector Id 0 |
| 143 | let lastConnector = '0'; |
| 144 | for (lastConnector in this._stationInfo.Connectors) { |
| 145 | if (Utils.convertToInt(lastConnector) === 0 && this._getUseConnectorId0() && this._stationInfo.Connectors[lastConnector]) { |
| 146 | this._connectors[lastConnector] = Utils.cloneObject<Connector>(this._stationInfo.Connectors[lastConnector]); |
| 147 | this._connectors[lastConnector].availability = AvailabilityType.OPERATIVE; |
| 148 | } |
| 149 | } |
| 150 | // Generate all connectors |
| 151 | if ((this._stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) { |
| 152 | for (let index = 1; index <= maxConnectors; index++) { |
| 153 | const randConnectorID = this._stationInfo.randomConnectors ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index; |
| 154 | this._connectors[index] = Utils.cloneObject<Connector>(this._stationInfo.Connectors[randConnectorID]); |
| 155 | this._connectors[index].availability = AvailabilityType.OPERATIVE; |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | // Avoid duplication of connectors related information |
| 160 | delete this._stationInfo.Connectors; |
| 161 | // Initialize transaction attributes on connectors |
| 162 | for (const connector in this._connectors) { |
| 163 | if (Utils.convertToInt(connector) > 0 && !this.getConnector(Utils.convertToInt(connector)).transactionStarted) { |
| 164 | this._initTransactionOnConnector(Utils.convertToInt(connector)); |
| 165 | } |
| 166 | } |
| 167 | // OCPP parameters |
| 168 | this._addConfigurationKey(StandardParametersKey.NumberOfConnectors, this._getNumberOfConnectors().toString(), true); |
| 169 | if (!this._getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) { |
| 170 | this._addConfigurationKey(StandardParametersKey.MeterValuesSampledData, MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER); |
| 171 | } |
| 172 | this._stationInfo.powerDivider = this._getPowerDivider(); |
| 173 | if (this.getEnableStatistics()) { |
| 174 | this._statistics = Statistics.getInstance(); |
| 175 | this._statistics.objName = this._stationInfo.name; |
| 176 | this._performanceObserver = new PerformanceObserver((list) => { |
| 177 | const entry = list.getEntries()[0]; |
| 178 | this._statistics.logPerformance(entry, Constants.ENTITY_CHARGING_STATION); |
| 179 | this._performanceObserver.disconnect(); |
| 180 | }); |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | get connectors(): Connectors { |
| 185 | return this._connectors; |
| 186 | } |
| 187 | |
| 188 | get statistics(): Statistics { |
| 189 | return this._statistics; |
| 190 | } |
| 191 | |
| 192 | _logPrefix(): string { |
| 193 | return Utils.logPrefix(` ${this._stationInfo.name}:`); |
| 194 | } |
| 195 | |
| 196 | _isWebSocketOpen(): boolean { |
| 197 | return this._wsConnection?.readyState === WebSocket.OPEN; |
| 198 | } |
| 199 | |
| 200 | _isRegistered(): boolean { |
| 201 | return this._bootNotificationResponse?.status === RegistrationStatus.ACCEPTED; |
| 202 | } |
| 203 | |
| 204 | _getTemplateChargingStationConfiguration(): ChargingStationConfiguration { |
| 205 | return this._stationInfo.Configuration ? this._stationInfo.Configuration : {} as ChargingStationConfiguration; |
| 206 | } |
| 207 | |
| 208 | _getAuthorizationFile(): string { |
| 209 | return this._stationInfo.authorizationFile && this._stationInfo.authorizationFile; |
| 210 | } |
| 211 | |
| 212 | _getUseConnectorId0(): boolean { |
| 213 | return !Utils.isUndefined(this._stationInfo.useConnectorId0) ? this._stationInfo.useConnectorId0 : true; |
| 214 | } |
| 215 | |
| 216 | _loadAndGetAuthorizedTags(): string[] { |
| 217 | let authorizedTags: string[] = []; |
| 218 | const authorizationFile = this._getAuthorizationFile(); |
| 219 | if (authorizationFile) { |
| 220 | try { |
| 221 | // Load authorization file |
| 222 | const fileDescriptor = fs.openSync(authorizationFile, 'r'); |
| 223 | authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[]; |
| 224 | fs.closeSync(fileDescriptor); |
| 225 | } catch (error) { |
| 226 | logger.error(this._logPrefix() + ' Authorization file ' + authorizationFile + ' loading error: %j', error); |
| 227 | throw error; |
| 228 | } |
| 229 | } else { |
| 230 | logger.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile); |
| 231 | } |
| 232 | return authorizedTags; |
| 233 | } |
| 234 | |
| 235 | getRandomTagId(): string { |
| 236 | const index = Math.floor(Math.random() * this._authorizedTags.length); |
| 237 | return this._authorizedTags[index]; |
| 238 | } |
| 239 | |
| 240 | hasAuthorizedTags(): boolean { |
| 241 | return !Utils.isEmptyArray(this._authorizedTags); |
| 242 | } |
| 243 | |
| 244 | getEnableStatistics(): boolean { |
| 245 | return !Utils.isUndefined(this._stationInfo.enableStatistics) ? this._stationInfo.enableStatistics : true; |
| 246 | } |
| 247 | |
| 248 | _getNumberOfPhases(): number { |
| 249 | switch (this._getPowerOutType()) { |
| 250 | case PowerOutType.AC: |
| 251 | return !Utils.isUndefined(this._stationInfo.numberOfPhases) ? this._stationInfo.numberOfPhases : 3; |
| 252 | case PowerOutType.DC: |
| 253 | return 0; |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | _getNumberOfRunningTransactions(): number { |
| 258 | let trxCount = 0; |
| 259 | for (const connector in this._connectors) { |
| 260 | if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) { |
| 261 | trxCount++; |
| 262 | } |
| 263 | } |
| 264 | return trxCount; |
| 265 | } |
| 266 | |
| 267 | // 0 for disabling |
| 268 | _getConnectionTimeout(): number { |
| 269 | if (!Utils.isUndefined(this._stationInfo.connectionTimeout)) { |
| 270 | return this._stationInfo.connectionTimeout; |
| 271 | } |
| 272 | if (!Utils.isUndefined(Configuration.getConnectionTimeout())) { |
| 273 | return Configuration.getConnectionTimeout(); |
| 274 | } |
| 275 | return 30; |
| 276 | } |
| 277 | |
| 278 | // -1 for unlimited, 0 for disabling |
| 279 | _getAutoReconnectMaxRetries(): number { |
| 280 | if (!Utils.isUndefined(this._stationInfo.autoReconnectMaxRetries)) { |
| 281 | return this._stationInfo.autoReconnectMaxRetries; |
| 282 | } |
| 283 | if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) { |
| 284 | return Configuration.getAutoReconnectMaxRetries(); |
| 285 | } |
| 286 | return -1; |
| 287 | } |
| 288 | |
| 289 | // 0 for disabling |
| 290 | _getRegistrationMaxRetries(): number { |
| 291 | if (!Utils.isUndefined(this._stationInfo.registrationMaxRetries)) { |
| 292 | return this._stationInfo.registrationMaxRetries; |
| 293 | } |
| 294 | return -1; |
| 295 | } |
| 296 | |
| 297 | _getPowerDivider(): number { |
| 298 | let powerDivider = this._getNumberOfConnectors(); |
| 299 | if (this._stationInfo.powerSharedByConnectors) { |
| 300 | powerDivider = this._getNumberOfRunningTransactions(); |
| 301 | } |
| 302 | return powerDivider; |
| 303 | } |
| 304 | |
| 305 | getConnector(id: number): Connector { |
| 306 | return this._connectors[id]; |
| 307 | } |
| 308 | |
| 309 | _isConnectorAvailable(id: number): boolean { |
| 310 | return this.getConnector(id).availability === AvailabilityType.OPERATIVE; |
| 311 | } |
| 312 | |
| 313 | _isChargingStationAvailable(): boolean { |
| 314 | return this.getConnector(0).availability === AvailabilityType.OPERATIVE; |
| 315 | } |
| 316 | |
| 317 | _getTemplateMaxNumberOfConnectors(): number { |
| 318 | return Object.keys(this._stationInfo.Connectors).length; |
| 319 | } |
| 320 | |
| 321 | _getMaxNumberOfConnectors(): number { |
| 322 | let maxConnectors = 0; |
| 323 | if (!Utils.isEmptyArray(this._stationInfo.numberOfConnectors)) { |
| 324 | const numberOfConnectors = this._stationInfo.numberOfConnectors as number[]; |
| 325 | // Distribute evenly the number of connectors |
| 326 | maxConnectors = numberOfConnectors[(this._index - 1) % numberOfConnectors.length]; |
| 327 | } else if (!Utils.isUndefined(this._stationInfo.numberOfConnectors)) { |
| 328 | maxConnectors = this._stationInfo.numberOfConnectors as number; |
| 329 | } else { |
| 330 | maxConnectors = this._stationInfo.Connectors[0] ? this._getTemplateMaxNumberOfConnectors() - 1 : this._getTemplateMaxNumberOfConnectors(); |
| 331 | } |
| 332 | return maxConnectors; |
| 333 | } |
| 334 | |
| 335 | _getNumberOfConnectors(): number { |
| 336 | return this._connectors[0] ? Object.keys(this._connectors).length - 1 : Object.keys(this._connectors).length; |
| 337 | } |
| 338 | |
| 339 | _getVoltageOut(): number { |
| 340 | const errMsg = `${this._logPrefix()} Unknown ${this._getPowerOutType()} powerOutType in template file ${this._stationTemplateFile}, cannot define default voltage out`; |
| 341 | let defaultVoltageOut: number; |
| 342 | switch (this._getPowerOutType()) { |
| 343 | case PowerOutType.AC: |
| 344 | defaultVoltageOut = VoltageOut.VOLTAGE_230; |
| 345 | break; |
| 346 | case PowerOutType.DC: |
| 347 | defaultVoltageOut = VoltageOut.VOLTAGE_400; |
| 348 | break; |
| 349 | default: |
| 350 | logger.error(errMsg); |
| 351 | throw Error(errMsg); |
| 352 | } |
| 353 | return !Utils.isUndefined(this._stationInfo.voltageOut) ? this._stationInfo.voltageOut : defaultVoltageOut; |
| 354 | } |
| 355 | |
| 356 | _getTransactionIdTag(transactionId: number): string { |
| 357 | for (const connector in this._connectors) { |
| 358 | if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) { |
| 359 | return this.getConnector(Utils.convertToInt(connector)).idTag; |
| 360 | } |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | _getTransactionMeterStop(transactionId: number): number { |
| 365 | for (const connector in this._connectors) { |
| 366 | if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) { |
| 367 | return this.getConnector(Utils.convertToInt(connector)).lastEnergyActiveImportRegisterValue; |
| 368 | } |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | _getPowerOutType(): PowerOutType { |
| 373 | return !Utils.isUndefined(this._stationInfo.powerOutType) ? this._stationInfo.powerOutType : PowerOutType.AC; |
| 374 | } |
| 375 | |
| 376 | _getSupervisionURL(): string { |
| 377 | const supervisionUrls = Utils.cloneObject<string | string[]>(this._stationInfo.supervisionURL ? this._stationInfo.supervisionURL : Configuration.getSupervisionURLs()); |
| 378 | let indexUrl = 0; |
| 379 | if (!Utils.isEmptyArray(supervisionUrls)) { |
| 380 | if (Configuration.getDistributeStationsToTenantsEqually()) { |
| 381 | indexUrl = this._index % supervisionUrls.length; |
| 382 | } else { |
| 383 | // Get a random url |
| 384 | indexUrl = Math.floor(Math.random() * supervisionUrls.length); |
| 385 | } |
| 386 | return supervisionUrls[indexUrl]; |
| 387 | } |
| 388 | return supervisionUrls as string; |
| 389 | } |
| 390 | |
| 391 | _getReconnectExponentialDelay(): boolean { |
| 392 | return !Utils.isUndefined(this._stationInfo.reconnectExponentialDelay) ? this._stationInfo.reconnectExponentialDelay : false; |
| 393 | } |
| 394 | |
| 395 | _getHeartbeatInterval(): number { |
| 396 | const HeartbeatInterval = this._getConfigurationKey(StandardParametersKey.HeartbeatInterval); |
| 397 | if (HeartbeatInterval) { |
| 398 | return Utils.convertToInt(HeartbeatInterval.value) * 1000; |
| 399 | } |
| 400 | const HeartBeatInterval = this._getConfigurationKey(StandardParametersKey.HeartBeatInterval); |
| 401 | if (HeartBeatInterval) { |
| 402 | return Utils.convertToInt(HeartBeatInterval.value) * 1000; |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | _getAuthorizeRemoteTxRequests(): boolean { |
| 407 | const authorizeRemoteTxRequests = this._getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests); |
| 408 | return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false; |
| 409 | } |
| 410 | |
| 411 | _getLocalAuthListEnabled(): boolean { |
| 412 | const localAuthListEnabled = this._getConfigurationKey(StandardParametersKey.LocalAuthListEnabled); |
| 413 | return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false; |
| 414 | } |
| 415 | |
| 416 | async _startMessageSequence(): Promise<void> { |
| 417 | // Start WebSocket ping |
| 418 | this._startWebSocketPing(); |
| 419 | // Start heartbeat |
| 420 | this._startHeartbeat(); |
| 421 | // Initialize connectors status |
| 422 | for (const connector in this._connectors) { |
| 423 | if (Utils.convertToInt(connector) === 0) { |
| 424 | continue; |
| 425 | } else if (!this._hasStopped && !this.getConnector(Utils.convertToInt(connector))?.status && this.getConnector(Utils.convertToInt(connector))?.bootStatus) { |
| 426 | // Send status in template at startup |
| 427 | await this.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus); |
| 428 | } else if (this._hasStopped && this.getConnector(Utils.convertToInt(connector))?.bootStatus) { |
| 429 | // Send status in template after reset |
| 430 | await this.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus); |
| 431 | } else if (!this._hasStopped && this.getConnector(Utils.convertToInt(connector))?.status) { |
| 432 | // Send previous status at template reload |
| 433 | await this.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).status); |
| 434 | } else { |
| 435 | // Send default status |
| 436 | await this.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.AVAILABLE); |
| 437 | } |
| 438 | } |
| 439 | // Start the ATG |
| 440 | if (this._stationInfo.AutomaticTransactionGenerator.enable) { |
| 441 | if (!this._automaticTransactionGeneration) { |
| 442 | this._automaticTransactionGeneration = new AutomaticTransactionGenerator(this); |
| 443 | } |
| 444 | if (this._automaticTransactionGeneration.timeToStop) { |
| 445 | this._automaticTransactionGeneration.start(); |
| 446 | } |
| 447 | } |
| 448 | if (this.getEnableStatistics()) { |
| 449 | this._statistics.start(); |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | async _stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> { |
| 454 | // Stop WebSocket ping |
| 455 | this._stopWebSocketPing(); |
| 456 | // Stop heartbeat |
| 457 | this._stopHeartbeat(); |
| 458 | // Stop the ATG |
| 459 | if (this._stationInfo.AutomaticTransactionGenerator.enable && |
| 460 | this._automaticTransactionGeneration && |
| 461 | !this._automaticTransactionGeneration.timeToStop) { |
| 462 | await this._automaticTransactionGeneration.stop(reason); |
| 463 | } else { |
| 464 | for (const connector in this._connectors) { |
| 465 | if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector)).transactionStarted) { |
| 466 | await this.sendStopTransaction(this.getConnector(Utils.convertToInt(connector)).transactionId, reason); |
| 467 | } |
| 468 | } |
| 469 | } |
| 470 | } |
| 471 | |
| 472 | _startWebSocketPing(): void { |
| 473 | const webSocketPingInterval: number = this._getConfigurationKey(StandardParametersKey.WebSocketPingInterval) ? Utils.convertToInt(this._getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value) : 0; |
| 474 | if (webSocketPingInterval > 0 && !this._webSocketPingSetInterval) { |
| 475 | this._webSocketPingSetInterval = setInterval(() => { |
| 476 | if (this._isWebSocketOpen()) { |
| 477 | this._wsConnection.ping((): void => { }); |
| 478 | } |
| 479 | }, webSocketPingInterval * 1000); |
| 480 | logger.info(this._logPrefix() + ' WebSocket ping started every ' + Utils.secondsToHHMMSS(webSocketPingInterval)); |
| 481 | } else if (this._webSocketPingSetInterval) { |
| 482 | logger.info(this._logPrefix() + ' WebSocket ping every ' + Utils.secondsToHHMMSS(webSocketPingInterval) + ' already started'); |
| 483 | } else { |
| 484 | logger.error(`${this._logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`); |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | _stopWebSocketPing(): void { |
| 489 | if (this._webSocketPingSetInterval) { |
| 490 | clearInterval(this._webSocketPingSetInterval); |
| 491 | this._webSocketPingSetInterval = null; |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | _restartWebSocketPing(): void { |
| 496 | // Stop WebSocket ping |
| 497 | this._stopWebSocketPing(); |
| 498 | // Start WebSocket ping |
| 499 | this._startWebSocketPing(); |
| 500 | } |
| 501 | |
| 502 | _startHeartbeat(): void { |
| 503 | if (this._getHeartbeatInterval() && this._getHeartbeatInterval() > 0 && !this._heartbeatSetInterval) { |
| 504 | this._heartbeatSetInterval = setInterval(async () => { |
| 505 | await this.sendHeartbeat(); |
| 506 | }, this._getHeartbeatInterval()); |
| 507 | logger.info(this._logPrefix() + ' Heartbeat started every ' + Utils.milliSecondsToHHMMSS(this._getHeartbeatInterval())); |
| 508 | } else if (this._heartbeatSetInterval) { |
| 509 | logger.info(this._logPrefix() + ' Heartbeat every ' + Utils.milliSecondsToHHMMSS(this._getHeartbeatInterval()) + ' already started'); |
| 510 | } else { |
| 511 | logger.error(`${this._logPrefix()} Heartbeat interval set to ${this._getHeartbeatInterval() ? Utils.milliSecondsToHHMMSS(this._getHeartbeatInterval()) : this._getHeartbeatInterval()}, not starting the heartbeat`); |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | _stopHeartbeat(): void { |
| 516 | if (this._heartbeatSetInterval) { |
| 517 | clearInterval(this._heartbeatSetInterval); |
| 518 | this._heartbeatSetInterval = null; |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | _restartHeartbeat(): void { |
| 523 | // Stop heartbeat |
| 524 | this._stopHeartbeat(); |
| 525 | // Start heartbeat |
| 526 | this._startHeartbeat(); |
| 527 | } |
| 528 | |
| 529 | _startAuthorizationFileMonitoring(): void { |
| 530 | fs.watch(this._getAuthorizationFile()).on("change", e => { |
| 531 | try { |
| 532 | logger.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload'); |
| 533 | // Initialize _authorizedTags |
| 534 | this._authorizedTags = this._loadAndGetAuthorizedTags(); |
| 535 | } catch (error) { |
| 536 | logger.error(this._logPrefix() + ' Authorization file monitoring error: %j', error); |
| 537 | } |
| 538 | }); |
| 539 | } |
| 540 | |
| 541 | _startStationTemplateFileMonitoring(): void { |
| 542 | fs.watch(this._stationTemplateFile).on("change", e => { |
| 543 | try { |
| 544 | logger.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile + ' have changed, reload'); |
| 545 | // Initialize |
| 546 | this._initialize(); |
| 547 | // Stop the ATG |
| 548 | if (!this._stationInfo.AutomaticTransactionGenerator.enable && |
| 549 | this._automaticTransactionGeneration) { |
| 550 | this._automaticTransactionGeneration.stop().catch(() => { }); |
| 551 | } |
| 552 | // Start the ATG |
| 553 | if (this._stationInfo.AutomaticTransactionGenerator.enable) { |
| 554 | if (!this._automaticTransactionGeneration) { |
| 555 | this._automaticTransactionGeneration = new AutomaticTransactionGenerator(this); |
| 556 | } |
| 557 | if (this._automaticTransactionGeneration.timeToStop) { |
| 558 | this._automaticTransactionGeneration.start(); |
| 559 | } |
| 560 | } |
| 561 | // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed |
| 562 | } catch (error) { |
| 563 | logger.error(this._logPrefix() + ' Charging station template file monitoring error: %j', error); |
| 564 | } |
| 565 | }); |
| 566 | } |
| 567 | |
| 568 | _startMeterValues(connectorId: number, interval: number): void { |
| 569 | if (connectorId === 0) { |
| 570 | logger.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`); |
| 571 | return; |
| 572 | } |
| 573 | if (!this.getConnector(connectorId)) { |
| 574 | logger.error(`${this._logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`); |
| 575 | return; |
| 576 | } |
| 577 | if (!this.getConnector(connectorId)?.transactionStarted) { |
| 578 | logger.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`); |
| 579 | return; |
| 580 | } else if (this.getConnector(connectorId)?.transactionStarted && !this.getConnector(connectorId)?.transactionId) { |
| 581 | logger.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`); |
| 582 | return; |
| 583 | } |
| 584 | if (interval > 0) { |
| 585 | this.getConnector(connectorId).transactionSetInterval = setInterval(async () => { |
| 586 | if (this.getEnableStatistics()) { |
| 587 | const sendMeterValues = performance.timerify(this.sendMeterValues); |
| 588 | this._performanceObserver.observe({ |
| 589 | entryTypes: ['function'], |
| 590 | }); |
| 591 | await sendMeterValues(connectorId, interval, this); |
| 592 | } else { |
| 593 | await this.sendMeterValues(connectorId, interval, this); |
| 594 | } |
| 595 | }, interval); |
| 596 | } else { |
| 597 | logger.error(`${this._logPrefix()} Charging station ${StandardParametersKey.MeterValueSampleInterval} configuration set to ${Utils.milliSecondsToHHMMSS(interval)}, not sending MeterValues`); |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | _openWSConnection(options?: WebSocket.ClientOptions, forceCloseOpened = false): void { |
| 602 | if (Utils.isUndefined(options)) { |
| 603 | options = {} as WebSocket.ClientOptions; |
| 604 | } |
| 605 | if (Utils.isUndefined(options.handshakeTimeout)) { |
| 606 | options.handshakeTimeout = this._getConnectionTimeout() * 1000; |
| 607 | } |
| 608 | if (this._isWebSocketOpen() && forceCloseOpened) { |
| 609 | this._wsConnection.close(); |
| 610 | } |
| 611 | this._wsConnection = new WebSocket(this._wsConnectionUrl, 'ocpp' + Constants.OCPP_VERSION_16, options); |
| 612 | logger.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl); |
| 613 | } |
| 614 | |
| 615 | start(): void { |
| 616 | this._openWSConnection(); |
| 617 | // Monitor authorization file |
| 618 | this._startAuthorizationFileMonitoring(); |
| 619 | // Monitor station template file |
| 620 | this._startStationTemplateFileMonitoring(); |
| 621 | // Handle Socket incoming messages |
| 622 | this._wsConnection.on('message', this.onMessage.bind(this)); |
| 623 | // Handle Socket error |
| 624 | this._wsConnection.on('error', this.onError.bind(this)); |
| 625 | // Handle Socket close |
| 626 | this._wsConnection.on('close', this.onClose.bind(this)); |
| 627 | // Handle Socket opening connection |
| 628 | this._wsConnection.on('open', this.onOpen.bind(this)); |
| 629 | // Handle Socket ping |
| 630 | this._wsConnection.on('ping', this.onPing.bind(this)); |
| 631 | // Handle Socket pong |
| 632 | this._wsConnection.on('pong', this.onPong.bind(this)); |
| 633 | } |
| 634 | |
| 635 | async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> { |
| 636 | // Stop message sequence |
| 637 | await this._stopMessageSequence(reason); |
| 638 | for (const connector in this._connectors) { |
| 639 | if (Utils.convertToInt(connector) > 0) { |
| 640 | await this.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.UNAVAILABLE); |
| 641 | } |
| 642 | } |
| 643 | if (this._isWebSocketOpen()) { |
| 644 | this._wsConnection.close(); |
| 645 | } |
| 646 | this._bootNotificationResponse = null; |
| 647 | this._hasStopped = true; |
| 648 | } |
| 649 | |
| 650 | async _reconnect(error): Promise<void> { |
| 651 | // Stop heartbeat |
| 652 | this._stopHeartbeat(); |
| 653 | // Stop the ATG if needed |
| 654 | if (this._stationInfo.AutomaticTransactionGenerator.enable && |
| 655 | this._stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure && |
| 656 | this._automaticTransactionGeneration && |
| 657 | !this._automaticTransactionGeneration.timeToStop) { |
| 658 | this._automaticTransactionGeneration.stop().catch(() => { }); |
| 659 | } |
| 660 | if (this._autoReconnectRetryCount < this._getAutoReconnectMaxRetries() || this._getAutoReconnectMaxRetries() === -1) { |
| 661 | this._autoReconnectRetryCount++; |
| 662 | const reconnectDelay = (this._getReconnectExponentialDelay() ? Utils.exponentialDelay(this._autoReconnectRetryCount) : this._getConnectionTimeout() * 1000); |
| 663 | logger.error(`${this._logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`); |
| 664 | await Utils.sleep(reconnectDelay); |
| 665 | logger.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount.toString()); |
| 666 | this._openWSConnection({ handshakeTimeout: reconnectDelay - 100 }); |
| 667 | this._hasSocketRestarted = true; |
| 668 | } else if (this._getAutoReconnectMaxRetries() !== -1) { |
| 669 | logger.error(`${this._logPrefix()} Socket reconnect failure: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._getAutoReconnectMaxRetries()})`); |
| 670 | } |
| 671 | } |
| 672 | |
| 673 | async onOpen(): Promise<void> { |
| 674 | logger.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`); |
| 675 | if (!this._isRegistered()) { |
| 676 | // Send BootNotification |
| 677 | let registrationRetryCount = 0; |
| 678 | do { |
| 679 | this._bootNotificationResponse = await this.sendBootNotification(); |
| 680 | if (!this._isRegistered()) { |
| 681 | registrationRetryCount++; |
| 682 | await Utils.sleep(this._bootNotificationResponse?.interval ? this._bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL); |
| 683 | } |
| 684 | } while (!this._isRegistered() && (registrationRetryCount <= this._getRegistrationMaxRetries() || this._getRegistrationMaxRetries() === -1)); |
| 685 | } |
| 686 | if (this._isRegistered()) { |
| 687 | await this._startMessageSequence(); |
| 688 | if (this._hasSocketRestarted && this._isWebSocketOpen()) { |
| 689 | if (!Utils.isEmptyArray(this._messageQueue)) { |
| 690 | this._messageQueue.forEach((message, index) => { |
| 691 | this._messageQueue.splice(index, 1); |
| 692 | this._wsConnection.send(message); |
| 693 | }); |
| 694 | } |
| 695 | } |
| 696 | } else { |
| 697 | logger.error(`${this._logPrefix()} Registration failure: max retries reached (${this._getRegistrationMaxRetries()}) or retry disabled (${this._getRegistrationMaxRetries()})`); |
| 698 | } |
| 699 | this._autoReconnectRetryCount = 0; |
| 700 | this._hasSocketRestarted = false; |
| 701 | } |
| 702 | |
| 703 | async onError(errorEvent): Promise<void> { |
| 704 | logger.error(this._logPrefix() + ' Socket error: %j', errorEvent); |
| 705 | // pragma switch (errorEvent.code) { |
| 706 | // case 'ECONNREFUSED': |
| 707 | // await this._reconnect(errorEvent); |
| 708 | // break; |
| 709 | // } |
| 710 | } |
| 711 | |
| 712 | async onClose(closeEvent): Promise<void> { |
| 713 | switch (closeEvent) { |
| 714 | case WebSocketCloseEventStatusCode.CLOSE_NORMAL: // Normal close |
| 715 | case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS: |
| 716 | logger.info(`${this._logPrefix()} Socket normally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`); |
| 717 | this._autoReconnectRetryCount = 0; |
| 718 | break; |
| 719 | default: // Abnormal close |
| 720 | logger.error(`${this._logPrefix()} Socket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(closeEvent)}'`); |
| 721 | await this._reconnect(closeEvent); |
| 722 | break; |
| 723 | } |
| 724 | } |
| 725 | |
| 726 | onPing(): void { |
| 727 | logger.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server'); |
| 728 | } |
| 729 | |
| 730 | onPong(): void { |
| 731 | logger.debug(this._logPrefix() + ' Has received a WS pong (rfc6455) from the server'); |
| 732 | } |
| 733 | |
| 734 | async onMessage(messageEvent: MessageEvent): Promise<void> { |
| 735 | let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [0, '', '' as IncomingRequestCommand, {}, {}]; |
| 736 | let responseCallback: (payload?: Record<string, unknown> | string, requestPayload?: Record<string, unknown>) => void; |
| 737 | let rejectCallback: (error: OCPPError) => void; |
| 738 | let requestPayload: Record<string, unknown>; |
| 739 | let errMsg: string; |
| 740 | try { |
| 741 | // Parse the message |
| 742 | [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(messageEvent.toString()) as IncomingRequest; |
| 743 | |
| 744 | // Check the Type of message |
| 745 | switch (messageType) { |
| 746 | // Incoming Message |
| 747 | case MessageType.CALL_MESSAGE: |
| 748 | if (this.getEnableStatistics()) { |
| 749 | this._statistics.addMessage(commandName, messageType); |
| 750 | } |
| 751 | // Process the call |
| 752 | await this.handleRequest(messageId, commandName, commandPayload); |
| 753 | break; |
| 754 | // Outcome Message |
| 755 | case MessageType.CALL_RESULT_MESSAGE: |
| 756 | // Respond |
| 757 | if (Utils.isIterable(this._requests[messageId])) { |
| 758 | [responseCallback, , requestPayload] = this._requests[messageId]; |
| 759 | } else { |
| 760 | throw new Error(`Response request for message id ${messageId} is not iterable`); |
| 761 | } |
| 762 | if (!responseCallback) { |
| 763 | // Error |
| 764 | throw new Error(`Response request for unknown message id ${messageId}`); |
| 765 | } |
| 766 | delete this._requests[messageId]; |
| 767 | responseCallback(commandName, requestPayload); |
| 768 | break; |
| 769 | // Error Message |
| 770 | case MessageType.CALL_ERROR_MESSAGE: |
| 771 | if (!this._requests[messageId]) { |
| 772 | // Error |
| 773 | throw new Error(`Error request for unknown message id ${messageId}`); |
| 774 | } |
| 775 | if (Utils.isIterable(this._requests[messageId])) { |
| 776 | [, rejectCallback] = this._requests[messageId]; |
| 777 | } else { |
| 778 | throw new Error(`Error request for message id ${messageId} is not iterable`); |
| 779 | } |
| 780 | delete this._requests[messageId]; |
| 781 | rejectCallback(new OCPPError(commandName, commandPayload.toString(), errorDetails)); |
| 782 | break; |
| 783 | // Error |
| 784 | default: |
| 785 | errMsg = `${this._logPrefix()} Wrong message type ${messageType}`; |
| 786 | logger.error(errMsg); |
| 787 | throw new Error(errMsg); |
| 788 | } |
| 789 | } catch (error) { |
| 790 | // Log |
| 791 | logger.error('%s Incoming message %j processing error %j on request content type %j', this._logPrefix(), messageEvent, error, this._requests[messageId]); |
| 792 | // Send error |
| 793 | messageType !== MessageType.CALL_ERROR_MESSAGE && await this.sendError(messageId, error, commandName); |
| 794 | } |
| 795 | } |
| 796 | |
| 797 | async sendHeartbeat(): Promise<void> { |
| 798 | try { |
| 799 | const payload: HeartbeatRequest = {}; |
| 800 | await this.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, RequestCommand.HEARTBEAT); |
| 801 | } catch (error) { |
| 802 | this.handleRequestError(RequestCommand.HEARTBEAT, error); |
| 803 | } |
| 804 | } |
| 805 | |
| 806 | async sendBootNotification(): Promise<BootNotificationResponse> { |
| 807 | try { |
| 808 | return await this.sendMessage(Utils.generateUUID(), this._bootNotificationRequest, MessageType.CALL_MESSAGE, RequestCommand.BOOT_NOTIFICATION) as BootNotificationResponse; |
| 809 | } catch (error) { |
| 810 | this.handleRequestError(RequestCommand.BOOT_NOTIFICATION, error); |
| 811 | } |
| 812 | } |
| 813 | |
| 814 | async sendStatusNotification(connectorId: number, status: ChargePointStatus, errorCode: ChargePointErrorCode = ChargePointErrorCode.NO_ERROR): Promise<void> { |
| 815 | this.getConnector(connectorId).status = status; |
| 816 | try { |
| 817 | const payload: StatusNotificationRequest = { |
| 818 | connectorId, |
| 819 | errorCode, |
| 820 | status, |
| 821 | }; |
| 822 | await this.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, RequestCommand.STATUS_NOTIFICATION); |
| 823 | } catch (error) { |
| 824 | this.handleRequestError(RequestCommand.STATUS_NOTIFICATION, error); |
| 825 | } |
| 826 | } |
| 827 | |
| 828 | async sendAuthorize(idTag?: string): Promise<AuthorizeResponse> { |
| 829 | try { |
| 830 | const payload: AuthorizeRequest = { |
| 831 | ...!Utils.isUndefined(idTag) ? { idTag } : { idTag: Constants.TRANSACTION_DEFAULT_IDTAG }, |
| 832 | }; |
| 833 | return await this.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, RequestCommand.AUTHORIZE) as AuthorizeResponse; |
| 834 | } catch (error) { |
| 835 | this.handleRequestError(RequestCommand.AUTHORIZE, error); |
| 836 | } |
| 837 | } |
| 838 | |
| 839 | async sendStartTransaction(connectorId: number, idTag?: string): Promise<StartTransactionResponse> { |
| 840 | try { |
| 841 | const payload: StartTransactionRequest = { |
| 842 | connectorId, |
| 843 | ...!Utils.isUndefined(idTag) ? { idTag } : { idTag: Constants.TRANSACTION_DEFAULT_IDTAG }, |
| 844 | meterStart: 0, |
| 845 | timestamp: new Date().toISOString(), |
| 846 | }; |
| 847 | return await this.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, RequestCommand.START_TRANSACTION) as StartTransactionResponse; |
| 848 | } catch (error) { |
| 849 | this.handleRequestError(RequestCommand.START_TRANSACTION, error); |
| 850 | } |
| 851 | } |
| 852 | |
| 853 | async sendStopTransaction(transactionId: number, reason: StopTransactionReason = StopTransactionReason.NONE): Promise<StopTransactionResponse> { |
| 854 | const idTag = this._getTransactionIdTag(transactionId); |
| 855 | try { |
| 856 | const payload: StopTransactionRequest = { |
| 857 | transactionId, |
| 858 | ...!Utils.isUndefined(idTag) && { idTag: idTag }, |
| 859 | meterStop: this._getTransactionMeterStop(transactionId), |
| 860 | timestamp: new Date().toISOString(), |
| 861 | ...reason && { reason }, |
| 862 | }; |
| 863 | return await this.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, RequestCommand.STOP_TRANSACTION) as StartTransactionResponse; |
| 864 | } catch (error) { |
| 865 | this.handleRequestError(RequestCommand.STOP_TRANSACTION, error); |
| 866 | } |
| 867 | } |
| 868 | |
| 869 | async sendError(messageId: string, error: OCPPError, commandName: RequestCommand | IncomingRequestCommand): Promise<unknown> { |
| 870 | // Send error |
| 871 | return this.sendMessage(messageId, error, MessageType.CALL_ERROR_MESSAGE, commandName); |
| 872 | } |
| 873 | |
| 874 | async sendMessage(messageId: string, commandParams: any, messageType: MessageType = MessageType.CALL_RESULT_MESSAGE, commandName: RequestCommand | IncomingRequestCommand): Promise<any> { |
| 875 | // eslint-disable-next-line @typescript-eslint/no-this-alias |
| 876 | const self = this; |
| 877 | // Send a message through wsConnection |
| 878 | return new Promise((resolve: (value?: any | PromiseLike<any>) => void, reject: (reason?: any) => void) => { |
| 879 | let messageToSend: string; |
| 880 | // Type of message |
| 881 | switch (messageType) { |
| 882 | // Request |
| 883 | case MessageType.CALL_MESSAGE: |
| 884 | // Build request |
| 885 | this._requests[messageId] = [responseCallback, rejectCallback, commandParams] as Request; |
| 886 | messageToSend = JSON.stringify([messageType, messageId, commandName, commandParams]); |
| 887 | break; |
| 888 | // Response |
| 889 | case MessageType.CALL_RESULT_MESSAGE: |
| 890 | // Build response |
| 891 | messageToSend = JSON.stringify([messageType, messageId, commandParams]); |
| 892 | break; |
| 893 | // Error Message |
| 894 | case MessageType.CALL_ERROR_MESSAGE: |
| 895 | // Build Error Message |
| 896 | messageToSend = JSON.stringify([messageType, messageId, commandParams.code ? commandParams.code : ErrorType.GENERIC_ERROR, commandParams.message ? commandParams.message : '', commandParams.details ? commandParams.details : {}]); |
| 897 | break; |
| 898 | } |
| 899 | // Check if wsConnection opened and charging station registered |
| 900 | if (this._isWebSocketOpen() && (this._isRegistered() || commandName === RequestCommand.BOOT_NOTIFICATION)) { |
| 901 | if (this.getEnableStatistics()) { |
| 902 | this._statistics.addMessage(commandName, messageType); |
| 903 | } |
| 904 | // Yes: Send Message |
| 905 | this._wsConnection.send(messageToSend); |
| 906 | } else if (commandName !== RequestCommand.BOOT_NOTIFICATION) { |
| 907 | let dups = false; |
| 908 | // Handle dups in buffer |
| 909 | for (const message of this._messageQueue) { |
| 910 | // Same message |
| 911 | if (messageToSend === message) { |
| 912 | dups = true; |
| 913 | break; |
| 914 | } |
| 915 | } |
| 916 | if (!dups) { |
| 917 | // Buffer message |
| 918 | this._messageQueue.push(messageToSend); |
| 919 | } |
| 920 | // Reject it |
| 921 | return rejectCallback(new OCPPError(commandParams.code ? commandParams.code : ErrorType.GENERIC_ERROR, commandParams.message ? commandParams.message : `WebSocket closed for message id '${messageId}' with content '${messageToSend}', message buffered`, commandParams.details ? commandParams.details : {})); |
| 922 | } |
| 923 | // Response? |
| 924 | if (messageType === MessageType.CALL_RESULT_MESSAGE) { |
| 925 | // Yes: send Ok |
| 926 | resolve(); |
| 927 | } else if (messageType === MessageType.CALL_ERROR_MESSAGE) { |
| 928 | // Send timeout |
| 929 | setTimeout(() => rejectCallback(new OCPPError(commandParams.code ? commandParams.code : ErrorType.GENERIC_ERROR, commandParams.message ? commandParams.message : `Timeout for message id '${messageId}' with content '${messageToSend}'`, commandParams.details ? commandParams.details : {})), Constants.OCPP_ERROR_TIMEOUT); |
| 930 | } |
| 931 | |
| 932 | // Function that will receive the request's response |
| 933 | async function responseCallback(payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>): Promise<void> { |
| 934 | if (self.getEnableStatistics()) { |
| 935 | self._statistics.addMessage(commandName, messageType); |
| 936 | } |
| 937 | // Send the response |
| 938 | await self.handleResponse(commandName as RequestCommand, payload, requestPayload); |
| 939 | resolve(payload); |
| 940 | } |
| 941 | |
| 942 | // Function that will receive the request's rejection |
| 943 | function rejectCallback(error: OCPPError): void { |
| 944 | if (self.getEnableStatistics()) { |
| 945 | self._statistics.addMessage(commandName, messageType); |
| 946 | } |
| 947 | logger.debug(`${self._logPrefix()} Error: %j occurred when calling command %s with parameters: %j`, error, commandName, commandParams); |
| 948 | // Build Exception |
| 949 | // eslint-disable-next-line no-empty-function |
| 950 | self._requests[messageId] = [() => { }, () => { }, {}]; // Properly format the request |
| 951 | // Send error |
| 952 | reject(error); |
| 953 | } |
| 954 | }); |
| 955 | } |
| 956 | |
| 957 | async handleResponse(commandName: RequestCommand, payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>): Promise<void> { |
| 958 | const responseCallbackFn = 'handleResponse' + commandName; |
| 959 | if (typeof this[responseCallbackFn] === 'function') { |
| 960 | await this[responseCallbackFn](payload, requestPayload); |
| 961 | } else { |
| 962 | logger.error(this._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn); |
| 963 | } |
| 964 | } |
| 965 | |
| 966 | handleResponseBootNotification(payload: BootNotificationResponse, requestPayload: BootNotificationRequest): void { |
| 967 | if (payload.status === RegistrationStatus.ACCEPTED) { |
| 968 | this._heartbeatSetInterval ? this._restartHeartbeat() : this._startHeartbeat(); |
| 969 | this._addConfigurationKey(StandardParametersKey.HeartBeatInterval, payload.interval.toString()); |
| 970 | this._addConfigurationKey(StandardParametersKey.HeartbeatInterval, payload.interval.toString(), false, false); |
| 971 | this._hasStopped && (this._hasStopped = false); |
| 972 | } else if (payload.status === RegistrationStatus.PENDING) { |
| 973 | logger.info(this._logPrefix() + ' Charging station in pending state on the central server'); |
| 974 | } else { |
| 975 | logger.info(this._logPrefix() + ' Charging station rejected by the central server'); |
| 976 | } |
| 977 | } |
| 978 | |
| 979 | _initTransactionOnConnector(connectorId: number): void { |
| 980 | this.getConnector(connectorId).transactionStarted = false; |
| 981 | this.getConnector(connectorId).transactionId = null; |
| 982 | this.getConnector(connectorId).idTag = null; |
| 983 | this.getConnector(connectorId).lastEnergyActiveImportRegisterValue = -1; |
| 984 | } |
| 985 | |
| 986 | _resetTransactionOnConnector(connectorId: number): void { |
| 987 | this._initTransactionOnConnector(connectorId); |
| 988 | if (this.getConnector(connectorId)?.transactionSetInterval) { |
| 989 | clearInterval(this.getConnector(connectorId).transactionSetInterval); |
| 990 | } |
| 991 | } |
| 992 | |
| 993 | async handleResponseStartTransaction(payload: StartTransactionResponse, requestPayload: StartTransactionRequest): Promise<void> { |
| 994 | const connectorId = requestPayload.connectorId; |
| 995 | |
| 996 | let transactionConnectorId: number; |
| 997 | for (const connector in this._connectors) { |
| 998 | if (Utils.convertToInt(connector) > 0 && Utils.convertToInt(connector) === connectorId) { |
| 999 | transactionConnectorId = Utils.convertToInt(connector); |
| 1000 | break; |
| 1001 | } |
| 1002 | } |
| 1003 | if (!transactionConnectorId) { |
| 1004 | logger.error(this._logPrefix() + ' Trying to start a transaction on a non existing connector Id ' + connectorId.toString()); |
| 1005 | return; |
| 1006 | } |
| 1007 | if (this.getConnector(connectorId)?.transactionStarted) { |
| 1008 | logger.debug(this._logPrefix() + ' Trying to start a transaction on an already used connector ' + connectorId.toString() + ': %j', this.getConnector(connectorId)); |
| 1009 | return; |
| 1010 | } |
| 1011 | |
| 1012 | if (payload.idTagInfo.status === AuthorizationStatus.ACCEPTED) { |
| 1013 | this.getConnector(connectorId).transactionStarted = true; |
| 1014 | this.getConnector(connectorId).transactionId = payload.transactionId; |
| 1015 | this.getConnector(connectorId).idTag = requestPayload.idTag; |
| 1016 | this.getConnector(connectorId).lastEnergyActiveImportRegisterValue = 0; |
| 1017 | await this.sendStatusNotification(connectorId, ChargePointStatus.CHARGING); |
| 1018 | logger.info(this._logPrefix() + ' Transaction ' + payload.transactionId.toString() + ' STARTED on ' + this._stationInfo.name + '#' + connectorId.toString() + ' for idTag ' + requestPayload.idTag); |
| 1019 | if (this._stationInfo.powerSharedByConnectors) { |
| 1020 | this._stationInfo.powerDivider++; |
| 1021 | } |
| 1022 | const configuredMeterValueSampleInterval = this._getConfigurationKey(StandardParametersKey.MeterValueSampleInterval); |
| 1023 | this._startMeterValues(connectorId, |
| 1024 | configuredMeterValueSampleInterval ? Utils.convertToInt(configuredMeterValueSampleInterval.value) * 1000 : 60000); |
| 1025 | } else { |
| 1026 | logger.error(this._logPrefix() + ' Starting transaction id ' + payload.transactionId.toString() + ' REJECTED with status ' + payload.idTagInfo.status + ', idTag ' + requestPayload.idTag); |
| 1027 | this._resetTransactionOnConnector(connectorId); |
| 1028 | await this.sendStatusNotification(connectorId, ChargePointStatus.AVAILABLE); |
| 1029 | } |
| 1030 | } |
| 1031 | |
| 1032 | async handleResponseStopTransaction(payload: StopTransactionResponse, requestPayload: StopTransactionRequest): Promise<void> { |
| 1033 | let transactionConnectorId: number; |
| 1034 | for (const connector in this._connectors) { |
| 1035 | if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector))?.transactionId === requestPayload.transactionId) { |
| 1036 | transactionConnectorId = Utils.convertToInt(connector); |
| 1037 | break; |
| 1038 | } |
| 1039 | } |
| 1040 | if (!transactionConnectorId) { |
| 1041 | logger.error(this._logPrefix() + ' Trying to stop a non existing transaction ' + requestPayload.transactionId.toString()); |
| 1042 | return; |
| 1043 | } |
| 1044 | if (payload.idTagInfo?.status === AuthorizationStatus.ACCEPTED) { |
| 1045 | if (!this._isChargingStationAvailable() || !this._isConnectorAvailable(transactionConnectorId)) { |
| 1046 | await this.sendStatusNotification(transactionConnectorId, ChargePointStatus.UNAVAILABLE); |
| 1047 | } else { |
| 1048 | await this.sendStatusNotification(transactionConnectorId, ChargePointStatus.AVAILABLE); |
| 1049 | } |
| 1050 | if (this._stationInfo.powerSharedByConnectors) { |
| 1051 | this._stationInfo.powerDivider--; |
| 1052 | } |
| 1053 | logger.info(this._logPrefix() + ' Transaction ' + requestPayload.transactionId.toString() + ' STOPPED on ' + this._stationInfo.name + '#' + transactionConnectorId.toString()); |
| 1054 | this._resetTransactionOnConnector(transactionConnectorId); |
| 1055 | } else { |
| 1056 | logger.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload.transactionId.toString() + ' REJECTED with status ' + payload.idTagInfo?.status); |
| 1057 | } |
| 1058 | } |
| 1059 | |
| 1060 | handleResponseStatusNotification(payload: StatusNotificationRequest, requestPayload: StatusNotificationResponse): void { |
| 1061 | logger.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload, requestPayload); |
| 1062 | } |
| 1063 | |
| 1064 | handleResponseMeterValues(payload: MeterValuesRequest, requestPayload: MeterValuesResponse): void { |
| 1065 | logger.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload, requestPayload); |
| 1066 | } |
| 1067 | |
| 1068 | handleResponseHeartbeat(payload: HeartbeatResponse, requestPayload: HeartbeatRequest): void { |
| 1069 | logger.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload, requestPayload); |
| 1070 | } |
| 1071 | |
| 1072 | async handleRequest(messageId: string, commandName: IncomingRequestCommand, commandPayload: Record<string, unknown>): Promise<void> { |
| 1073 | let response; |
| 1074 | // Call |
| 1075 | if (typeof this['handleRequest' + commandName] === 'function') { |
| 1076 | try { |
| 1077 | // Call the method to build the response |
| 1078 | response = await this['handleRequest' + commandName](commandPayload); |
| 1079 | } catch (error) { |
| 1080 | // Log |
| 1081 | logger.error(this._logPrefix() + ' Handle request error: %j', error); |
| 1082 | // Send back response to inform backend |
| 1083 | await this.sendError(messageId, error, commandName); |
| 1084 | throw error; |
| 1085 | } |
| 1086 | } else { |
| 1087 | // Throw exception |
| 1088 | await this.sendError(messageId, new OCPPError(ErrorType.NOT_IMPLEMENTED, `${commandName} is not implemented`, {}), commandName); |
| 1089 | throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`); |
| 1090 | } |
| 1091 | // Send response |
| 1092 | await this.sendMessage(messageId, response, MessageType.CALL_RESULT_MESSAGE, commandName); |
| 1093 | } |
| 1094 | |
| 1095 | // Simulate charging station restart |
| 1096 | handleRequestReset(commandPayload: ResetRequest): DefaultResponse { |
| 1097 | setImmediate(async () => { |
| 1098 | await this.stop(commandPayload.type + 'Reset' as StopTransactionReason); |
| 1099 | await Utils.sleep(this._stationInfo.resetTime); |
| 1100 | await this.start(); |
| 1101 | }); |
| 1102 | logger.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${Utils.milliSecondsToHHMMSS(this._stationInfo.resetTime)}`); |
| 1103 | return Constants.OCPP_RESPONSE_ACCEPTED; |
| 1104 | } |
| 1105 | |
| 1106 | handleRequestClearCache(): DefaultResponse { |
| 1107 | return Constants.OCPP_RESPONSE_ACCEPTED; |
| 1108 | } |
| 1109 | |
| 1110 | async handleRequestUnlockConnector(commandPayload: UnlockConnectorRequest): Promise<UnlockConnectorResponse> { |
| 1111 | const connectorId = commandPayload.connectorId; |
| 1112 | if (connectorId === 0) { |
| 1113 | logger.error(this._logPrefix() + ' Trying to unlock connector ' + connectorId.toString()); |
| 1114 | return Constants.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED; |
| 1115 | } |
| 1116 | if (this.getConnector(connectorId)?.transactionStarted) { |
| 1117 | const stopResponse = await this.sendStopTransaction(this.getConnector(connectorId).transactionId, StopTransactionReason.UNLOCK_COMMAND); |
| 1118 | if (stopResponse.idTagInfo?.status === AuthorizationStatus.ACCEPTED) { |
| 1119 | return Constants.OCPP_RESPONSE_UNLOCKED; |
| 1120 | } |
| 1121 | return Constants.OCPP_RESPONSE_UNLOCK_FAILED; |
| 1122 | } |
| 1123 | await this.sendStatusNotification(connectorId, ChargePointStatus.AVAILABLE); |
| 1124 | return Constants.OCPP_RESPONSE_UNLOCKED; |
| 1125 | } |
| 1126 | |
| 1127 | _getConfigurationKey(key: string | StandardParametersKey, caseInsensitive = false): ConfigurationKey { |
| 1128 | const configurationKey: ConfigurationKey = this._configuration.configurationKey.find((configElement) => { |
| 1129 | if (caseInsensitive) { |
| 1130 | return configElement.key.toLowerCase() === key.toLowerCase(); |
| 1131 | } |
| 1132 | return configElement.key === key; |
| 1133 | }); |
| 1134 | return configurationKey; |
| 1135 | } |
| 1136 | |
| 1137 | _addConfigurationKey(key: string | StandardParametersKey, value: string, readonly = false, visible = true, reboot = false): void { |
| 1138 | const keyFound = this._getConfigurationKey(key); |
| 1139 | if (!keyFound) { |
| 1140 | this._configuration.configurationKey.push({ |
| 1141 | key, |
| 1142 | readonly, |
| 1143 | value, |
| 1144 | visible, |
| 1145 | reboot, |
| 1146 | }); |
| 1147 | } else { |
| 1148 | logger.error(`${this._logPrefix()} Trying to add an already existing configuration key: %j`, keyFound); |
| 1149 | } |
| 1150 | } |
| 1151 | |
| 1152 | _setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void { |
| 1153 | const keyFound = this._getConfigurationKey(key); |
| 1154 | if (keyFound) { |
| 1155 | const keyIndex = this._configuration.configurationKey.indexOf(keyFound); |
| 1156 | this._configuration.configurationKey[keyIndex].value = value; |
| 1157 | } else { |
| 1158 | logger.error(`${this._logPrefix()} Trying to set a value on a non existing configuration key: %j`, { key, value }); |
| 1159 | } |
| 1160 | } |
| 1161 | |
| 1162 | handleRequestGetConfiguration(commandPayload: GetConfigurationRequest): GetConfigurationResponse { |
| 1163 | const configurationKey: OCPPConfigurationKey[] = []; |
| 1164 | const unknownKey: string[] = []; |
| 1165 | if (Utils.isEmptyArray(commandPayload.key)) { |
| 1166 | for (const configuration of this._configuration.configurationKey) { |
| 1167 | if (Utils.isUndefined(configuration.visible)) { |
| 1168 | configuration.visible = true; |
| 1169 | } |
| 1170 | if (!configuration.visible) { |
| 1171 | continue; |
| 1172 | } |
| 1173 | configurationKey.push({ |
| 1174 | key: configuration.key, |
| 1175 | readonly: configuration.readonly, |
| 1176 | value: configuration.value, |
| 1177 | }); |
| 1178 | } |
| 1179 | } else { |
| 1180 | for (const key of commandPayload.key) { |
| 1181 | const keyFound = this._getConfigurationKey(key); |
| 1182 | if (keyFound) { |
| 1183 | if (Utils.isUndefined(keyFound.visible)) { |
| 1184 | keyFound.visible = true; |
| 1185 | } |
| 1186 | if (!keyFound.visible) { |
| 1187 | continue; |
| 1188 | } |
| 1189 | configurationKey.push({ |
| 1190 | key: keyFound.key, |
| 1191 | readonly: keyFound.readonly, |
| 1192 | value: keyFound.value, |
| 1193 | }); |
| 1194 | } else { |
| 1195 | unknownKey.push(key); |
| 1196 | } |
| 1197 | } |
| 1198 | } |
| 1199 | return { |
| 1200 | configurationKey, |
| 1201 | unknownKey, |
| 1202 | }; |
| 1203 | } |
| 1204 | |
| 1205 | handleRequestChangeConfiguration(commandPayload: ChangeConfigurationRequest): ChangeConfigurationResponse { |
| 1206 | // JSON request fields type sanity check |
| 1207 | if (!Utils.isString(commandPayload.key)) { |
| 1208 | logger.error(`${this._logPrefix()} ChangeConfiguration request key field is not a string:`, commandPayload); |
| 1209 | } |
| 1210 | if (!Utils.isString(commandPayload.value)) { |
| 1211 | logger.error(`${this._logPrefix()} ChangeConfiguration request value field is not a string:`, commandPayload); |
| 1212 | } |
| 1213 | const keyToChange = this._getConfigurationKey(commandPayload.key, true); |
| 1214 | if (!keyToChange) { |
| 1215 | return Constants.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED; |
| 1216 | } else if (keyToChange && keyToChange.readonly) { |
| 1217 | return Constants.OCPP_CONFIGURATION_RESPONSE_REJECTED; |
| 1218 | } else if (keyToChange && !keyToChange.readonly) { |
| 1219 | const keyIndex = this._configuration.configurationKey.indexOf(keyToChange); |
| 1220 | let valueChanged = false; |
| 1221 | if (this._configuration.configurationKey[keyIndex].value !== commandPayload.value) { |
| 1222 | this._configuration.configurationKey[keyIndex].value = commandPayload.value; |
| 1223 | valueChanged = true; |
| 1224 | } |
| 1225 | let triggerHeartbeatRestart = false; |
| 1226 | if (keyToChange.key === StandardParametersKey.HeartBeatInterval && valueChanged) { |
| 1227 | this._setConfigurationKeyValue(StandardParametersKey.HeartbeatInterval, commandPayload.value); |
| 1228 | triggerHeartbeatRestart = true; |
| 1229 | } |
| 1230 | if (keyToChange.key === StandardParametersKey.HeartbeatInterval && valueChanged) { |
| 1231 | this._setConfigurationKeyValue(StandardParametersKey.HeartBeatInterval, commandPayload.value); |
| 1232 | triggerHeartbeatRestart = true; |
| 1233 | } |
| 1234 | if (triggerHeartbeatRestart) { |
| 1235 | this._restartHeartbeat(); |
| 1236 | } |
| 1237 | if (keyToChange.key === StandardParametersKey.WebSocketPingInterval && valueChanged) { |
| 1238 | this._restartWebSocketPing(); |
| 1239 | } |
| 1240 | if (keyToChange.reboot) { |
| 1241 | return Constants.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED; |
| 1242 | } |
| 1243 | return Constants.OCPP_CONFIGURATION_RESPONSE_ACCEPTED; |
| 1244 | } |
| 1245 | } |
| 1246 | |
| 1247 | handleRequestSetChargingProfile(commandPayload: SetChargingProfileRequest): SetChargingProfileResponse { |
| 1248 | if (!this.getConnector(commandPayload.connectorId)) { |
| 1249 | logger.error(`${this._logPrefix()} Trying to set a charging profile to a non existing connector Id ${commandPayload.connectorId}`); |
| 1250 | return Constants.OCPP_CHARGING_PROFILE_RESPONSE_REJECTED; |
| 1251 | } |
| 1252 | if (commandPayload.csChargingProfiles.chargingProfilePurpose === ChargingProfilePurposeType.TX_PROFILE && !this.getConnector(commandPayload.connectorId)?.transactionStarted) { |
| 1253 | return Constants.OCPP_CHARGING_PROFILE_RESPONSE_REJECTED; |
| 1254 | } |
| 1255 | this.getConnector(commandPayload.connectorId).chargingProfiles.forEach((chargingProfile: ChargingProfile, index: number) => { |
| 1256 | if (chargingProfile.chargingProfileId === commandPayload.csChargingProfiles.chargingProfileId |
| 1257 | || (chargingProfile.stackLevel === commandPayload.csChargingProfiles.stackLevel && chargingProfile.chargingProfilePurpose === commandPayload.csChargingProfiles.chargingProfilePurpose)) { |
| 1258 | this.getConnector(commandPayload.connectorId).chargingProfiles[index] = chargingProfile; |
| 1259 | return Constants.OCPP_CHARGING_PROFILE_RESPONSE_ACCEPTED; |
| 1260 | } |
| 1261 | }); |
| 1262 | this.getConnector(commandPayload.connectorId).chargingProfiles.push(commandPayload.csChargingProfiles); |
| 1263 | return Constants.OCPP_CHARGING_PROFILE_RESPONSE_ACCEPTED; |
| 1264 | } |
| 1265 | |
| 1266 | handleRequestChangeAvailability(commandPayload: ChangeAvailabilityRequest): ChangeAvailabilityResponse { |
| 1267 | const connectorId: number = commandPayload.connectorId; |
| 1268 | if (!this.getConnector(connectorId)) { |
| 1269 | logger.error(`${this._logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`); |
| 1270 | return Constants.OCPP_AVAILABILITY_RESPONSE_REJECTED; |
| 1271 | } |
| 1272 | const chargePointStatus: ChargePointStatus = commandPayload.type === AvailabilityType.OPERATIVE ? ChargePointStatus.AVAILABLE : ChargePointStatus.UNAVAILABLE; |
| 1273 | if (connectorId === 0) { |
| 1274 | let response: ChangeAvailabilityResponse = Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED; |
| 1275 | for (const connector in this._connectors) { |
| 1276 | if (this.getConnector(Utils.convertToInt(connector)).transactionStarted) { |
| 1277 | response = Constants.OCPP_AVAILABILITY_RESPONSE_SCHEDULED; |
| 1278 | } |
| 1279 | this.getConnector(Utils.convertToInt(connector)).availability = commandPayload.type; |
| 1280 | response === Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED && this.sendStatusNotification(Utils.convertToInt(connector), chargePointStatus); |
| 1281 | } |
| 1282 | return response; |
| 1283 | } else if (connectorId > 0 && (this.getConnector(0).availability === AvailabilityType.OPERATIVE || (this.getConnector(0).availability === AvailabilityType.INOPERATIVE && commandPayload.type === AvailabilityType.INOPERATIVE))) { |
| 1284 | if (this.getConnector(connectorId)?.transactionStarted) { |
| 1285 | this.getConnector(connectorId).availability = commandPayload.type; |
| 1286 | return Constants.OCPP_AVAILABILITY_RESPONSE_SCHEDULED; |
| 1287 | } |
| 1288 | this.getConnector(connectorId).availability = commandPayload.type; |
| 1289 | void this.sendStatusNotification(connectorId, chargePointStatus); |
| 1290 | return Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED; |
| 1291 | } |
| 1292 | return Constants.OCPP_AVAILABILITY_RESPONSE_REJECTED; |
| 1293 | } |
| 1294 | |
| 1295 | async handleRequestRemoteStartTransaction(commandPayload: RemoteStartTransactionRequest): Promise<DefaultResponse> { |
| 1296 | const transactionConnectorID: number = commandPayload.connectorId ? commandPayload.connectorId : 1; |
| 1297 | if (this._isChargingStationAvailable() && this._isConnectorAvailable(transactionConnectorID)) { |
| 1298 | if (this._getAuthorizeRemoteTxRequests() && this._getLocalAuthListEnabled() && this.hasAuthorizedTags()) { |
| 1299 | // Check if authorized |
| 1300 | if (this._authorizedTags.find((value) => value === commandPayload.idTag)) { |
| 1301 | await this.sendStatusNotification(transactionConnectorID, ChargePointStatus.PREPARING); |
| 1302 | // Authorization successful start transaction |
| 1303 | await this.sendStartTransaction(transactionConnectorID, commandPayload.idTag); |
| 1304 | logger.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID.toString() + ' for idTag ' + commandPayload.idTag); |
| 1305 | return Constants.OCPP_RESPONSE_ACCEPTED; |
| 1306 | } |
| 1307 | logger.error(this._logPrefix() + ' Remote starting transaction REJECTED on connector Id ' + transactionConnectorID.toString() + ', idTag ' + commandPayload.idTag); |
| 1308 | return Constants.OCPP_RESPONSE_REJECTED; |
| 1309 | } |
| 1310 | await this.sendStatusNotification(transactionConnectorID, ChargePointStatus.PREPARING); |
| 1311 | // No local authorization check required => start transaction |
| 1312 | await this.sendStartTransaction(transactionConnectorID, commandPayload.idTag); |
| 1313 | logger.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID.toString() + ' for idTag ' + commandPayload.idTag); |
| 1314 | return Constants.OCPP_RESPONSE_ACCEPTED; |
| 1315 | } |
| 1316 | logger.error(this._logPrefix() + ' Remote starting transaction REJECTED on unavailable connector Id ' + transactionConnectorID.toString() + ', idTag ' + commandPayload.idTag); |
| 1317 | return Constants.OCPP_RESPONSE_REJECTED; |
| 1318 | } |
| 1319 | |
| 1320 | async handleRequestRemoteStopTransaction(commandPayload: RemoteStopTransactionRequest): Promise<DefaultResponse> { |
| 1321 | const transactionId = commandPayload.transactionId; |
| 1322 | for (const connector in this._connectors) { |
| 1323 | if (Utils.convertToInt(connector) > 0 && this.getConnector(Utils.convertToInt(connector))?.transactionId === transactionId) { |
| 1324 | await this.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.FINISHING); |
| 1325 | await this.sendStopTransaction(transactionId); |
| 1326 | return Constants.OCPP_RESPONSE_ACCEPTED; |
| 1327 | } |
| 1328 | } |
| 1329 | logger.info(this._logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId.toString()); |
| 1330 | return Constants.OCPP_RESPONSE_REJECTED; |
| 1331 | } |
| 1332 | |
| 1333 | // eslint-disable-next-line consistent-this |
| 1334 | private async sendMeterValues(connectorId: number, interval: number, self: ChargingStation, debug = false): Promise<void> { |
| 1335 | try { |
| 1336 | const meterValue: MeterValue = { |
| 1337 | timestamp: new Date().toISOString(), |
| 1338 | sampledValue: [], |
| 1339 | }; |
| 1340 | const meterValuesTemplate: SampledValue[] = self.getConnector(connectorId).MeterValues; |
| 1341 | for (let index = 0; index < meterValuesTemplate.length; index++) { |
| 1342 | const connector = self.getConnector(connectorId); |
| 1343 | // SoC measurand |
| 1344 | if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === MeterValueMeasurand.STATE_OF_CHARGE && self._getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(MeterValueMeasurand.STATE_OF_CHARGE)) { |
| 1345 | meterValue.sampledValue.push({ |
| 1346 | ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.PERCENT }, |
| 1347 | ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, |
| 1348 | measurand: meterValuesTemplate[index].measurand, |
| 1349 | ...!Utils.isUndefined(meterValuesTemplate[index].location) ? { location: meterValuesTemplate[index].location } : { location: MeterValueLocation.EV }, |
| 1350 | ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: Utils.getRandomInt(100).toString() }, |
| 1351 | }); |
| 1352 | const sampledValuesIndex = meterValue.sampledValue.length - 1; |
| 1353 | if (Utils.convertToInt(meterValue.sampledValue[sampledValuesIndex].value) > 100 || debug) { |
| 1354 | logger.error(`${self._logPrefix()} MeterValues measurand ${meterValue.sampledValue[sampledValuesIndex].measurand ? meterValue.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${meterValue.sampledValue[sampledValuesIndex].value}/100`); |
| 1355 | } |
| 1356 | // Voltage measurand |
| 1357 | } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === MeterValueMeasurand.VOLTAGE && self._getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(MeterValueMeasurand.VOLTAGE)) { |
| 1358 | const voltageMeasurandValue = Utils.getRandomFloatRounded(self._getVoltageOut() + self._getVoltageOut() * 0.1, self._getVoltageOut() - self._getVoltageOut() * 0.1); |
| 1359 | meterValue.sampledValue.push({ |
| 1360 | ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.VOLT }, |
| 1361 | ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, |
| 1362 | measurand: meterValuesTemplate[index].measurand, |
| 1363 | ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, |
| 1364 | ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: voltageMeasurandValue.toString() }, |
| 1365 | }); |
| 1366 | for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) { |
| 1367 | let phaseValue: string; |
| 1368 | if (self._getVoltageOut() >= 0 && self._getVoltageOut() <= 250) { |
| 1369 | phaseValue = `L${phase}-N`; |
| 1370 | } else if (self._getVoltageOut() > 250) { |
| 1371 | phaseValue = `L${phase}-L${(phase + 1) % self._getNumberOfPhases() !== 0 ? (phase + 1) % self._getNumberOfPhases() : self._getNumberOfPhases()}`; |
| 1372 | } |
| 1373 | meterValue.sampledValue.push({ |
| 1374 | ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.VOLT }, |
| 1375 | ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, |
| 1376 | measurand: meterValuesTemplate[index].measurand, |
| 1377 | ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, |
| 1378 | ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: voltageMeasurandValue.toString() }, |
| 1379 | phase: phaseValue as MeterValuePhase, |
| 1380 | }); |
| 1381 | } |
| 1382 | // Power.Active.Import measurand |
| 1383 | } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === MeterValueMeasurand.POWER_ACTIVE_IMPORT && self._getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(MeterValueMeasurand.POWER_ACTIVE_IMPORT)) { |
| 1384 | // FIXME: factor out powerDivider checks |
| 1385 | if (Utils.isUndefined(self._stationInfo.powerDivider)) { |
| 1386 | const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`; |
| 1387 | logger.error(errMsg); |
| 1388 | throw Error(errMsg); |
| 1389 | } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) { |
| 1390 | const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`; |
| 1391 | logger.error(errMsg); |
| 1392 | throw Error(errMsg); |
| 1393 | } |
| 1394 | const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} measurand value`; |
| 1395 | const powerMeasurandValues = {} as MeasurandValues; |
| 1396 | const maxPower = Math.round(self._stationInfo.maxPower / self._stationInfo.powerDivider); |
| 1397 | const maxPowerPerPhase = Math.round((self._stationInfo.maxPower / self._stationInfo.powerDivider) / self._getNumberOfPhases()); |
| 1398 | switch (self._getPowerOutType()) { |
| 1399 | case PowerOutType.AC: |
| 1400 | if (Utils.isUndefined(meterValuesTemplate[index].value)) { |
| 1401 | powerMeasurandValues.L1 = Utils.getRandomFloatRounded(maxPowerPerPhase); |
| 1402 | powerMeasurandValues.L2 = 0; |
| 1403 | powerMeasurandValues.L3 = 0; |
| 1404 | if (self._getNumberOfPhases() === 3) { |
| 1405 | powerMeasurandValues.L2 = Utils.getRandomFloatRounded(maxPowerPerPhase); |
| 1406 | powerMeasurandValues.L3 = Utils.getRandomFloatRounded(maxPowerPerPhase); |
| 1407 | } |
| 1408 | powerMeasurandValues.allPhases = Utils.roundTo(powerMeasurandValues.L1 + powerMeasurandValues.L2 + powerMeasurandValues.L3, 2); |
| 1409 | } |
| 1410 | break; |
| 1411 | case PowerOutType.DC: |
| 1412 | if (Utils.isUndefined(meterValuesTemplate[index].value)) { |
| 1413 | powerMeasurandValues.allPhases = Utils.getRandomFloatRounded(maxPower); |
| 1414 | } |
| 1415 | break; |
| 1416 | default: |
| 1417 | logger.error(errMsg); |
| 1418 | throw Error(errMsg); |
| 1419 | } |
| 1420 | meterValue.sampledValue.push({ |
| 1421 | ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.WATT }, |
| 1422 | ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, |
| 1423 | measurand: meterValuesTemplate[index].measurand, |
| 1424 | ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, |
| 1425 | ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: powerMeasurandValues.allPhases.toString() }, |
| 1426 | }); |
| 1427 | const sampledValuesIndex = meterValue.sampledValue.length - 1; |
| 1428 | if (Utils.convertToFloat(meterValue.sampledValue[sampledValuesIndex].value) > maxPower || debug) { |
| 1429 | logger.error(`${self._logPrefix()} MeterValues measurand ${meterValue.sampledValue[sampledValuesIndex].measurand ? meterValue.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${meterValue.sampledValue[sampledValuesIndex].value}/${maxPower}`); |
| 1430 | } |
| 1431 | for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) { |
| 1432 | const phaseValue = `L${phase}-N`; |
| 1433 | meterValue.sampledValue.push({ |
| 1434 | ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.WATT }, |
| 1435 | ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, |
| 1436 | ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand }, |
| 1437 | ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, |
| 1438 | ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: powerMeasurandValues[`L${phase}`] as string }, |
| 1439 | phase: phaseValue as MeterValuePhase, |
| 1440 | }); |
| 1441 | } |
| 1442 | // Current.Import measurand |
| 1443 | } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === MeterValueMeasurand.CURRENT_IMPORT && self._getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(MeterValueMeasurand.CURRENT_IMPORT)) { |
| 1444 | // FIXME: factor out powerDivider checks |
| 1445 | if (Utils.isUndefined(self._stationInfo.powerDivider)) { |
| 1446 | const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`; |
| 1447 | logger.error(errMsg); |
| 1448 | throw Error(errMsg); |
| 1449 | } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) { |
| 1450 | const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`; |
| 1451 | logger.error(errMsg); |
| 1452 | throw Error(errMsg); |
| 1453 | } |
| 1454 | const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} measurand value`; |
| 1455 | const currentMeasurandValues: MeasurandValues = {} as MeasurandValues; |
| 1456 | let maxAmperage: number; |
| 1457 | switch (self._getPowerOutType()) { |
| 1458 | case PowerOutType.AC: |
| 1459 | maxAmperage = ElectricUtils.ampPerPhaseFromPower(self._getNumberOfPhases(), self._stationInfo.maxPower / self._stationInfo.powerDivider, self._getVoltageOut()); |
| 1460 | if (Utils.isUndefined(meterValuesTemplate[index].value)) { |
| 1461 | currentMeasurandValues.L1 = Utils.getRandomFloatRounded(maxAmperage); |
| 1462 | currentMeasurandValues.L2 = 0; |
| 1463 | currentMeasurandValues.L3 = 0; |
| 1464 | if (self._getNumberOfPhases() === 3) { |
| 1465 | currentMeasurandValues.L2 = Utils.getRandomFloatRounded(maxAmperage); |
| 1466 | currentMeasurandValues.L3 = Utils.getRandomFloatRounded(maxAmperage); |
| 1467 | } |
| 1468 | currentMeasurandValues.allPhases = Utils.roundTo((currentMeasurandValues.L1 + currentMeasurandValues.L2 + currentMeasurandValues.L3) / self._getNumberOfPhases(), 2); |
| 1469 | } |
| 1470 | break; |
| 1471 | case PowerOutType.DC: |
| 1472 | maxAmperage = ElectricUtils.ampTotalFromPower(self._stationInfo.maxPower / self._stationInfo.powerDivider, self._getVoltageOut()); |
| 1473 | if (Utils.isUndefined(meterValuesTemplate[index].value)) { |
| 1474 | currentMeasurandValues.allPhases = Utils.getRandomFloatRounded(maxAmperage); |
| 1475 | } |
| 1476 | break; |
| 1477 | default: |
| 1478 | logger.error(errMsg); |
| 1479 | throw Error(errMsg); |
| 1480 | } |
| 1481 | meterValue.sampledValue.push({ |
| 1482 | ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.AMP }, |
| 1483 | ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, |
| 1484 | measurand: meterValuesTemplate[index].measurand, |
| 1485 | ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, |
| 1486 | ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: currentMeasurandValues.allPhases.toString() }, |
| 1487 | }); |
| 1488 | const sampledValuesIndex = meterValue.sampledValue.length - 1; |
| 1489 | if (Utils.convertToFloat(meterValue.sampledValue[sampledValuesIndex].value) > maxAmperage || debug) { |
| 1490 | logger.error(`${self._logPrefix()} MeterValues measurand ${meterValue.sampledValue[sampledValuesIndex].measurand ? meterValue.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${meterValue.sampledValue[sampledValuesIndex].value}/${maxAmperage}`); |
| 1491 | } |
| 1492 | for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) { |
| 1493 | const phaseValue = `L${phase}`; |
| 1494 | meterValue.sampledValue.push({ |
| 1495 | ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.AMP }, |
| 1496 | ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, |
| 1497 | ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand }, |
| 1498 | ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, |
| 1499 | ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: currentMeasurandValues[phaseValue] as string }, |
| 1500 | phase: phaseValue as MeterValuePhase, |
| 1501 | }); |
| 1502 | } |
| 1503 | // Energy.Active.Import.Register measurand (default) |
| 1504 | } else if (!meterValuesTemplate[index].measurand || meterValuesTemplate[index].measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) { |
| 1505 | // FIXME: factor out powerDivider checks |
| 1506 | if (Utils.isUndefined(self._stationInfo.powerDivider)) { |
| 1507 | const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`; |
| 1508 | logger.error(errMsg); |
| 1509 | throw Error(errMsg); |
| 1510 | } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) { |
| 1511 | const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`; |
| 1512 | logger.error(errMsg); |
| 1513 | throw Error(errMsg); |
| 1514 | } |
| 1515 | if (Utils.isUndefined(meterValuesTemplate[index].value)) { |
| 1516 | const measurandValue = Utils.getRandomInt(self._stationInfo.maxPower / (self._stationInfo.powerDivider * 3600000) * interval); |
| 1517 | // Persist previous value in connector |
| 1518 | if (connector && !Utils.isNullOrUndefined(connector.lastEnergyActiveImportRegisterValue) && connector.lastEnergyActiveImportRegisterValue >= 0) { |
| 1519 | connector.lastEnergyActiveImportRegisterValue += measurandValue; |
| 1520 | } else { |
| 1521 | connector.lastEnergyActiveImportRegisterValue = 0; |
| 1522 | } |
| 1523 | } |
| 1524 | meterValue.sampledValue.push({ |
| 1525 | ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.WATT_HOUR }, |
| 1526 | ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, |
| 1527 | ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand }, |
| 1528 | ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, |
| 1529 | ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : |
| 1530 | { value: connector.lastEnergyActiveImportRegisterValue.toString() }, |
| 1531 | }); |
| 1532 | const sampledValuesIndex = meterValue.sampledValue.length - 1; |
| 1533 | const maxConsumption = Math.round(self._stationInfo.maxPower * 3600 / (self._stationInfo.powerDivider * interval)); |
| 1534 | if (Utils.convertToFloat(meterValue.sampledValue[sampledValuesIndex].value) > maxConsumption || debug) { |
| 1535 | logger.error(`${self._logPrefix()} MeterValues measurand ${meterValue.sampledValue[sampledValuesIndex].measurand ? meterValue.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${meterValue.sampledValue[sampledValuesIndex].value}/${maxConsumption}`); |
| 1536 | } |
| 1537 | // Unsupported measurand |
| 1538 | } else { |
| 1539 | logger.info(`${self._logPrefix()} Unsupported MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} on connectorId ${connectorId}`); |
| 1540 | } |
| 1541 | } |
| 1542 | const payload: MeterValuesRequest = { |
| 1543 | connectorId, |
| 1544 | transactionId: self.getConnector(connectorId).transactionId, |
| 1545 | meterValue: meterValue, |
| 1546 | }; |
| 1547 | await self.sendMessage(Utils.generateUUID(), payload, MessageType.CALL_MESSAGE, RequestCommand.METERVALUES); |
| 1548 | } catch (error) { |
| 1549 | this.handleRequestError(RequestCommand.METERVALUES, error); |
| 1550 | } |
| 1551 | } |
| 1552 | |
| 1553 | private handleRequestError(commandName: RequestCommand, error: Error) { |
| 1554 | logger.error(this._logPrefix() + ' Send ' + commandName + ' error: %j', error); |
| 1555 | throw error; |
| 1556 | } |
| 1557 | } |
| 1558 | |