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