| 1 | import { PerformanceObserver, performance } from 'perf_hooks'; |
| 2 | |
| 3 | import AutomaticTransactionGenerator from './AutomaticTransactionGenerator'; |
| 4 | import Configuration from '../utils/Configuration'; |
| 5 | import Constants from '../utils/Constants.js'; |
| 6 | import ElectricUtils from '../utils/ElectricUtils'; |
| 7 | import { MeasurandValues } from '../types/MeasurandValues'; |
| 8 | import OCPPError from './OcppError.js'; |
| 9 | import Statistics from '../utils/Statistics'; |
| 10 | import Utils from '../utils/Utils'; |
| 11 | import WebSocket from 'ws'; |
| 12 | import crypto from 'crypto'; |
| 13 | import fs from 'fs'; |
| 14 | import logger from '../utils/Logger'; |
| 15 | |
| 16 | export default class ChargingStation { |
| 17 | private _index: number; |
| 18 | private _stationTemplateFile: string; |
| 19 | private _stationInfo; |
| 20 | private _bootNotificationMessage; |
| 21 | private _connectors; |
| 22 | private _configuration; |
| 23 | private _connectorsConfigurationHash: string; |
| 24 | private _supervisionUrl; |
| 25 | private _wsConnectionUrl; |
| 26 | private _wsConnection: WebSocket; |
| 27 | private _isSocketRestart; |
| 28 | private _autoReconnectRetryCount: number; |
| 29 | private _autoReconnectMaxRetries: number; |
| 30 | private _autoReconnectTimeout: number; |
| 31 | private _requests; |
| 32 | private _messageQueue; |
| 33 | private _automaticTransactionGeneration: AutomaticTransactionGenerator; |
| 34 | private _authorizedTags: string[]; |
| 35 | private _heartbeatInterval: number; |
| 36 | private _heartbeatSetInterval; |
| 37 | private _statistics: Statistics; |
| 38 | private _performanceObserver: PerformanceObserver; |
| 39 | |
| 40 | constructor(index: number, stationTemplateFile: string) { |
| 41 | this._index = index; |
| 42 | this._stationTemplateFile = stationTemplateFile; |
| 43 | this._connectors = {}; |
| 44 | this._initialize(); |
| 45 | |
| 46 | this._isSocketRestart = false; |
| 47 | this._autoReconnectRetryCount = 0; |
| 48 | this._autoReconnectMaxRetries = Configuration.getAutoReconnectMaxRetries(); // -1 for unlimited |
| 49 | this._autoReconnectTimeout = Configuration.getAutoReconnectTimeout() * 1000; // Ms, zero for disabling |
| 50 | |
| 51 | this._requests = {}; |
| 52 | this._messageQueue = []; |
| 53 | |
| 54 | this._authorizedTags = this._loadAndGetAuthorizedTags(); |
| 55 | } |
| 56 | |
| 57 | _getStationName(stationTemplate): string { |
| 58 | return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + ('000000000' + this._index).substr(('000000000' + this._index).length - 4); |
| 59 | } |
| 60 | |
| 61 | _buildStationInfo() { |
| 62 | let stationTemplateFromFile; |
| 63 | try { |
| 64 | // Load template file |
| 65 | const fileDescriptor = fs.openSync(this._stationTemplateFile, 'r'); |
| 66 | stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')); |
| 67 | fs.closeSync(fileDescriptor); |
| 68 | } catch (error) { |
| 69 | logger.error('Template file ' + this._stationTemplateFile + ' loading error: ' + error); |
| 70 | throw error; |
| 71 | } |
| 72 | const stationTemplate = stationTemplateFromFile || {}; |
| 73 | if (!Utils.isEmptyArray(stationTemplateFromFile.power)) { |
| 74 | stationTemplate.maxPower = stationTemplateFromFile.power[Math.floor(Math.random() * stationTemplateFromFile.power.length)]; |
| 75 | } else { |
| 76 | stationTemplate.maxPower = stationTemplateFromFile.power; |
| 77 | } |
| 78 | stationTemplate.name = this._getStationName(stationTemplateFromFile); |
| 79 | stationTemplate.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME; |
| 80 | return stationTemplate; |
| 81 | } |
| 82 | |
| 83 | get stationInfo() { |
| 84 | return this._stationInfo; |
| 85 | } |
| 86 | |
| 87 | _initialize(): void { |
| 88 | this._stationInfo = this._buildStationInfo(); |
| 89 | this._bootNotificationMessage = { |
| 90 | chargePointModel: this._stationInfo.chargePointModel, |
| 91 | chargePointVendor: this._stationInfo.chargePointVendor, |
| 92 | ...!Utils.isUndefined(this._stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this._stationInfo.chargeBoxSerialNumberPrefix }, |
| 93 | ...!Utils.isUndefined(this._stationInfo.firmwareVersion) && { firmwareVersion: this._stationInfo.firmwareVersion }, |
| 94 | }; |
| 95 | this._configuration = this._getConfiguration(); |
| 96 | this._supervisionUrl = this._getSupervisionURL(); |
| 97 | this._wsConnectionUrl = this._supervisionUrl + '/' + this._stationInfo.name; |
| 98 | // Build connectors if needed |
| 99 | const maxConnectors = this._getMaxNumberOfConnectors(); |
| 100 | if (maxConnectors <= 0) { |
| 101 | logger.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with ${maxConnectors} connectors`); |
| 102 | } |
| 103 | const templateMaxConnectors = this._getTemplateMaxNumberOfConnectors(); |
| 104 | if (templateMaxConnectors <= 0) { |
| 105 | logger.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with no connector configurations`); |
| 106 | } |
| 107 | // Sanity check |
| 108 | if (maxConnectors > (this._stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !Utils.convertToBoolean(this._stationInfo.randomConnectors)) { |
| 109 | logger.warn(`${this._logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this._stationTemplateFile}, forcing random connector configurations affectation`); |
| 110 | this._stationInfo.randomConnectors = true; |
| 111 | } |
| 112 | const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this._stationInfo.Connectors) + maxConnectors.toString()).digest('hex'); |
| 113 | // FIXME: Handle shrinking the number of connectors |
| 114 | if (!this._connectors || (this._connectors && this._connectorsConfigurationHash !== connectorsConfigHash)) { |
| 115 | this._connectorsConfigurationHash = connectorsConfigHash; |
| 116 | // Add connector Id 0 |
| 117 | let lastConnector = '0'; |
| 118 | for (lastConnector in this._stationInfo.Connectors) { |
| 119 | if (Utils.convertToInt(lastConnector) === 0 && Utils.convertToBoolean(this._stationInfo.useConnectorId0) && this._stationInfo.Connectors[lastConnector]) { |
| 120 | this._connectors[lastConnector] = Utils.cloneObject(this._stationInfo.Connectors[lastConnector]); |
| 121 | } |
| 122 | } |
| 123 | // Generate all connectors |
| 124 | if ((this._stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) { |
| 125 | for (let index = 1; index <= maxConnectors; index++) { |
| 126 | const randConnectorID = Utils.convertToBoolean(this._stationInfo.randomConnectors) ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index; |
| 127 | this._connectors[index] = Utils.cloneObject(this._stationInfo.Connectors[randConnectorID]); |
| 128 | } |
| 129 | } |
| 130 | } |
| 131 | // Avoid duplication of connectors related information |
| 132 | delete this._stationInfo.Connectors; |
| 133 | // Initialize transaction attributes on connectors |
| 134 | for (const connector in this._connectors) { |
| 135 | if (!this.getConnector(Utils.convertToInt(connector)).transactionStarted) { |
| 136 | this._initTransactionOnConnector(connector); |
| 137 | } |
| 138 | } |
| 139 | // OCPP parameters |
| 140 | this._addConfigurationKey('NumberOfConnectors', this._getNumberOfConnectors(), true); |
| 141 | if (!this._getConfigurationKey('MeterValuesSampledData')) { |
| 142 | this._addConfigurationKey('MeterValuesSampledData', 'Energy.Active.Import.Register'); |
| 143 | } |
| 144 | this._stationInfo.powerDivider = this._getPowerDivider(); |
| 145 | if (this.getEnableStatistics()) { |
| 146 | this._statistics = Statistics.getInstance(); |
| 147 | this._statistics.objName = this._stationInfo.name; |
| 148 | this._performanceObserver = new PerformanceObserver((list) => { |
| 149 | const entry = list.getEntries()[0]; |
| 150 | this._statistics.logPerformance(entry, 'ChargingStation'); |
| 151 | this._performanceObserver.disconnect(); |
| 152 | }); |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | get connectors() { |
| 157 | return this._connectors; |
| 158 | } |
| 159 | |
| 160 | get statistics(): Statistics { |
| 161 | return this._statistics; |
| 162 | } |
| 163 | |
| 164 | _logPrefix(): string { |
| 165 | return Utils.logPrefix(` ${this._stationInfo.name}:`); |
| 166 | } |
| 167 | |
| 168 | _getConfiguration() { |
| 169 | return this._stationInfo.Configuration ? this._stationInfo.Configuration : {}; |
| 170 | } |
| 171 | |
| 172 | _getAuthorizationFile() { |
| 173 | return this._stationInfo.authorizationFile && this._stationInfo.authorizationFile; |
| 174 | } |
| 175 | |
| 176 | _loadAndGetAuthorizedTags(): string[] { |
| 177 | let authorizedTags = []; |
| 178 | const authorizationFile = this._getAuthorizationFile(); |
| 179 | if (authorizationFile) { |
| 180 | try { |
| 181 | // Load authorization file |
| 182 | const fileDescriptor = fs.openSync(authorizationFile, 'r'); |
| 183 | authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')); |
| 184 | fs.closeSync(fileDescriptor); |
| 185 | } catch (error) { |
| 186 | logger.error(this._logPrefix() + ' Authorization file ' + authorizationFile + ' loading error: ' + error); |
| 187 | throw error; |
| 188 | } |
| 189 | } else { |
| 190 | logger.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile); |
| 191 | } |
| 192 | return authorizedTags; |
| 193 | } |
| 194 | |
| 195 | getRandomTagId() { |
| 196 | const index = Math.floor(Math.random() * this._authorizedTags.length); |
| 197 | return this._authorizedTags[index]; |
| 198 | } |
| 199 | |
| 200 | hasAuthorizedTags() { |
| 201 | return !Utils.isEmptyArray(this._authorizedTags); |
| 202 | } |
| 203 | |
| 204 | getEnableStatistics() { |
| 205 | return !Utils.isUndefined(this._stationInfo.enableStatistics) ? Utils.convertToBoolean(this._stationInfo.enableStatistics) : true; |
| 206 | } |
| 207 | |
| 208 | _getNumberOfPhases(): number { |
| 209 | switch (this._getPowerOutType()) { |
| 210 | case 'AC': |
| 211 | return !Utils.isUndefined(this._stationInfo.numberOfPhases) ? Utils.convertToInt(this._stationInfo.numberOfPhases) : 3; |
| 212 | case 'DC': |
| 213 | return 0; |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | _getNumberOfRunningTransactions() { |
| 218 | let trxCount = 0; |
| 219 | for (const connector in this._connectors) { |
| 220 | if (this.getConnector(Utils.convertToInt(connector)).transactionStarted) { |
| 221 | trxCount++; |
| 222 | } |
| 223 | } |
| 224 | return trxCount; |
| 225 | } |
| 226 | |
| 227 | _getPowerDivider() { |
| 228 | let powerDivider = this._getNumberOfConnectors(); |
| 229 | if (this._stationInfo.powerSharedByConnectors) { |
| 230 | powerDivider = this._getNumberOfRunningTransactions(); |
| 231 | } |
| 232 | return powerDivider; |
| 233 | } |
| 234 | |
| 235 | getConnector(id: number) { |
| 236 | return this._connectors[id]; |
| 237 | } |
| 238 | |
| 239 | _getTemplateMaxNumberOfConnectors() { |
| 240 | return Object.keys(this._stationInfo.Connectors).length; |
| 241 | } |
| 242 | |
| 243 | _getMaxNumberOfConnectors() { |
| 244 | let maxConnectors = 0; |
| 245 | if (!Utils.isEmptyArray(this._stationInfo.numberOfConnectors)) { |
| 246 | // Distribute evenly the number of connectors |
| 247 | maxConnectors = this._stationInfo.numberOfConnectors[(this._index - 1) % this._stationInfo.numberOfConnectors.length]; |
| 248 | } else if (!Utils.isUndefined(this._stationInfo.numberOfConnectors)) { |
| 249 | maxConnectors = this._stationInfo.numberOfConnectors; |
| 250 | } else { |
| 251 | maxConnectors = this._stationInfo.Connectors[0] ? this._getTemplateMaxNumberOfConnectors() - 1 : this._getTemplateMaxNumberOfConnectors(); |
| 252 | } |
| 253 | return maxConnectors; |
| 254 | } |
| 255 | |
| 256 | _getNumberOfConnectors(): number { |
| 257 | return this._connectors[0] ? Object.keys(this._connectors).length - 1 : Object.keys(this._connectors).length; |
| 258 | } |
| 259 | |
| 260 | _getVoltageOut() { |
| 261 | const errMsg = `${this._logPrefix()} Unknown ${this._getPowerOutType()} powerOutType in template file ${this._stationTemplateFile}, cannot define default voltage out`; |
| 262 | let defaultVoltageOut; |
| 263 | switch (this._getPowerOutType()) { |
| 264 | case 'AC': |
| 265 | defaultVoltageOut = 230; |
| 266 | break; |
| 267 | case 'DC': |
| 268 | defaultVoltageOut = 400; |
| 269 | break; |
| 270 | default: |
| 271 | logger.error(errMsg); |
| 272 | throw Error(errMsg); |
| 273 | } |
| 274 | return !Utils.isUndefined(this._stationInfo.voltageOut) ? Utils.convertToInt(this._stationInfo.voltageOut) : defaultVoltageOut; |
| 275 | } |
| 276 | |
| 277 | _getPowerOutType() { |
| 278 | return !Utils.isUndefined(this._stationInfo.powerOutType) ? this._stationInfo.powerOutType : 'AC'; |
| 279 | } |
| 280 | |
| 281 | _getSupervisionURL() { |
| 282 | const supervisionUrls = Utils.cloneObject(this._stationInfo.supervisionURL ? this._stationInfo.supervisionURL : Configuration.getSupervisionURLs()); |
| 283 | let indexUrl = 0; |
| 284 | if (!Utils.isEmptyArray(supervisionUrls)) { |
| 285 | if (Configuration.getDistributeStationToTenantEqually()) { |
| 286 | indexUrl = this._index % supervisionUrls.length; |
| 287 | } else { |
| 288 | // Get a random url |
| 289 | indexUrl = Math.floor(Math.random() * supervisionUrls.length); |
| 290 | } |
| 291 | return supervisionUrls[indexUrl]; |
| 292 | } |
| 293 | return supervisionUrls; |
| 294 | } |
| 295 | |
| 296 | _getAuthorizeRemoteTxRequests() { |
| 297 | const authorizeRemoteTxRequests = this._getConfigurationKey('AuthorizeRemoteTxRequests'); |
| 298 | return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false; |
| 299 | } |
| 300 | |
| 301 | _getLocalAuthListEnabled() { |
| 302 | const localAuthListEnabled = this._getConfigurationKey('LocalAuthListEnabled'); |
| 303 | return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false; |
| 304 | } |
| 305 | |
| 306 | _startMessageSequence(): void { |
| 307 | // Start heartbeat |
| 308 | this._startHeartbeat(); |
| 309 | // Initialize connectors status |
| 310 | for (const connector in this._connectors) { |
| 311 | if (!this.getConnector(Utils.convertToInt(connector)).transactionStarted) { |
| 312 | if (this.getConnector(Utils.convertToInt(connector)).bootStatus) { |
| 313 | this.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus); |
| 314 | } else { |
| 315 | this.sendStatusNotification(Utils.convertToInt(connector), 'Available'); |
| 316 | } |
| 317 | } else { |
| 318 | this.sendStatusNotification(Utils.convertToInt(connector), 'Charging'); |
| 319 | } |
| 320 | } |
| 321 | // Start the ATG |
| 322 | if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable)) { |
| 323 | if (!this._automaticTransactionGeneration) { |
| 324 | this._automaticTransactionGeneration = new AutomaticTransactionGenerator(this); |
| 325 | } |
| 326 | if (this._automaticTransactionGeneration.timeToStop) { |
| 327 | this._automaticTransactionGeneration.start(); |
| 328 | } |
| 329 | } |
| 330 | if (this.getEnableStatistics()) { |
| 331 | this._statistics.start(); |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | async _stopMessageSequence(reason = ''): Promise<void> { |
| 336 | // Stop heartbeat |
| 337 | this._stopHeartbeat(); |
| 338 | // Stop the ATG |
| 339 | if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable) && |
| 340 | this._automaticTransactionGeneration && |
| 341 | !this._automaticTransactionGeneration.timeToStop) { |
| 342 | await this._automaticTransactionGeneration.stop(reason); |
| 343 | } else { |
| 344 | for (const connector in this._connectors) { |
| 345 | if (this.getConnector(Utils.convertToInt(connector)).transactionStarted) { |
| 346 | await this.sendStopTransaction(this.getConnector(Utils.convertToInt(connector)).transactionId, reason); |
| 347 | } |
| 348 | } |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | _startHeartbeat(): void { |
| 353 | if (this._heartbeatInterval && this._heartbeatInterval > 0 && !this._heartbeatSetInterval) { |
| 354 | this._heartbeatSetInterval = setInterval(() => { |
| 355 | this.sendHeartbeat(); |
| 356 | }, this._heartbeatInterval); |
| 357 | logger.info(this._logPrefix() + ' Heartbeat started every ' + this._heartbeatInterval.toString() + 'ms'); |
| 358 | } else { |
| 359 | logger.error(`${this._logPrefix()} Heartbeat interval set to ${this._heartbeatInterval}ms, not starting the heartbeat`); |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | _stopHeartbeat() { |
| 364 | if (this._heartbeatSetInterval) { |
| 365 | clearInterval(this._heartbeatSetInterval); |
| 366 | this._heartbeatSetInterval = null; |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | _startAuthorizationFileMonitoring() { |
| 371 | // eslint-disable-next-line no-unused-vars |
| 372 | fs.watchFile(this._getAuthorizationFile(), (current, previous) => { |
| 373 | try { |
| 374 | logger.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload'); |
| 375 | // Initialize _authorizedTags |
| 376 | this._authorizedTags = this._loadAndGetAuthorizedTags(); |
| 377 | } catch (error) { |
| 378 | logger.error(this._logPrefix() + ' Authorization file monitoring error: ' + error); |
| 379 | } |
| 380 | }); |
| 381 | } |
| 382 | |
| 383 | _startStationTemplateFileMonitoring() { |
| 384 | // eslint-disable-next-line no-unused-vars |
| 385 | fs.watchFile(this._stationTemplateFile, (current, previous) => { |
| 386 | try { |
| 387 | logger.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile + ' have changed, reload'); |
| 388 | // Initialize |
| 389 | this._initialize(); |
| 390 | if (!Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable) && |
| 391 | this._automaticTransactionGeneration) { |
| 392 | this._automaticTransactionGeneration.stop().catch(() => {}); |
| 393 | } |
| 394 | } catch (error) { |
| 395 | logger.error(this._logPrefix() + ' Charging station template file monitoring error: ' + error); |
| 396 | } |
| 397 | }); |
| 398 | } |
| 399 | |
| 400 | _startMeterValues(connectorId: number, interval: number): void { |
| 401 | if (!this.getConnector(connectorId).transactionStarted) { |
| 402 | logger.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`); |
| 403 | return; |
| 404 | } else if (this.getConnector(connectorId).transactionStarted && !this.getConnector(connectorId).transactionId) { |
| 405 | logger.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`); |
| 406 | return; |
| 407 | } |
| 408 | if (interval > 0) { |
| 409 | this.getConnector(connectorId).transactionSetInterval = setInterval(async () => { |
| 410 | // eslint-disable-next-line @typescript-eslint/no-this-alias |
| 411 | const self = this; |
| 412 | if (this.getEnableStatistics()) { |
| 413 | const sendMeterValues = performance.timerify(this.sendMeterValues); |
| 414 | this._performanceObserver.observe({ |
| 415 | entryTypes: ['function'], |
| 416 | }); |
| 417 | await sendMeterValues(connectorId, interval, self); |
| 418 | } else { |
| 419 | await this.sendMeterValues(connectorId, interval, self); |
| 420 | } |
| 421 | }, interval); |
| 422 | } else { |
| 423 | logger.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`); |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | start() { |
| 428 | if (!this._wsConnectionUrl) { |
| 429 | this._wsConnectionUrl = this._supervisionUrl + '/' + this._stationInfo.name; |
| 430 | } |
| 431 | this._wsConnection = new WebSocket(this._wsConnectionUrl, 'ocpp' + Constants.OCPP_VERSION_16); |
| 432 | logger.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl); |
| 433 | // Monitor authorization file |
| 434 | this._startAuthorizationFileMonitoring(); |
| 435 | // Monitor station template file |
| 436 | this._startStationTemplateFileMonitoring(); |
| 437 | // Handle Socket incoming messages |
| 438 | this._wsConnection.on('message', this.onMessage.bind(this)); |
| 439 | // Handle Socket error |
| 440 | this._wsConnection.on('error', this.onError.bind(this)); |
| 441 | // Handle Socket close |
| 442 | this._wsConnection.on('close', this.onClose.bind(this)); |
| 443 | // Handle Socket opening connection |
| 444 | this._wsConnection.on('open', this.onOpen.bind(this)); |
| 445 | // Handle Socket ping |
| 446 | this._wsConnection.on('ping', this.onPing.bind(this)); |
| 447 | } |
| 448 | |
| 449 | async stop(reason = '') { |
| 450 | // Stop |
| 451 | await this._stopMessageSequence(); |
| 452 | // eslint-disable-next-line guard-for-in |
| 453 | for (const connector in this._connectors) { |
| 454 | await this.sendStatusNotification(Utils.convertToInt(connector), 'Unavailable'); |
| 455 | } |
| 456 | if (this._wsConnection && this._wsConnection.readyState === WebSocket.OPEN) { |
| 457 | await this._wsConnection.close(); |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | _reconnect(error) { |
| 462 | logger.error(this._logPrefix() + ' Socket: abnormally closed', error); |
| 463 | // Stop the ATG if needed |
| 464 | if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable) && |
| 465 | Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure) && |
| 466 | this._automaticTransactionGeneration && |
| 467 | !this._automaticTransactionGeneration.timeToStop) { |
| 468 | this._automaticTransactionGeneration.stop(); |
| 469 | } |
| 470 | // Stop heartbeat |
| 471 | this._stopHeartbeat(); |
| 472 | if (this._autoReconnectTimeout !== 0 && |
| 473 | (this._autoReconnectRetryCount < this._autoReconnectMaxRetries || this._autoReconnectMaxRetries === -1)) { |
| 474 | logger.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`); |
| 475 | this._autoReconnectRetryCount++; |
| 476 | setTimeout(() => { |
| 477 | logger.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount); |
| 478 | this.start(); |
| 479 | }, this._autoReconnectTimeout); |
| 480 | } else if (this._autoReconnectTimeout !== 0 || this._autoReconnectMaxRetries !== -1) { |
| 481 | logger.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`); |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | onOpen() { |
| 486 | logger.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`); |
| 487 | if (!this._isSocketRestart) { |
| 488 | // Send BootNotification |
| 489 | this.sendBootNotification(); |
| 490 | } |
| 491 | if (this._isSocketRestart) { |
| 492 | this._startMessageSequence(); |
| 493 | if (!Utils.isEmptyArray(this._messageQueue)) { |
| 494 | this._messageQueue.forEach((message) => { |
| 495 | if (this._wsConnection && this._wsConnection.readyState === WebSocket.OPEN) { |
| 496 | this._wsConnection.send(message); |
| 497 | } |
| 498 | }); |
| 499 | } |
| 500 | } |
| 501 | this._autoReconnectRetryCount = 0; |
| 502 | this._isSocketRestart = false; |
| 503 | } |
| 504 | |
| 505 | onError(error) { |
| 506 | switch (error) { |
| 507 | case 'ECONNREFUSED': |
| 508 | this._isSocketRestart = true; |
| 509 | this._reconnect(error); |
| 510 | break; |
| 511 | default: |
| 512 | logger.error(this._logPrefix() + ' Socket error: ' + error); |
| 513 | break; |
| 514 | } |
| 515 | } |
| 516 | |
| 517 | onClose(error) { |
| 518 | switch (error) { |
| 519 | case 1000: // Normal close |
| 520 | case 1005: |
| 521 | logger.info(this._logPrefix() + ' Socket normally closed ' + error); |
| 522 | this._autoReconnectRetryCount = 0; |
| 523 | break; |
| 524 | default: // Abnormal close |
| 525 | this._isSocketRestart = true; |
| 526 | this._reconnect(error); |
| 527 | break; |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | onPing() { |
| 532 | logger.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server'); |
| 533 | } |
| 534 | |
| 535 | async onMessage(message) { |
| 536 | let [messageType, messageId, commandName, commandPayload, errorDetails] = [0, '', Constants.ENTITY_CHARGING_STATION, '', '']; |
| 537 | try { |
| 538 | // Parse the message |
| 539 | [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(message); |
| 540 | |
| 541 | // Check the Type of message |
| 542 | switch (messageType) { |
| 543 | // Incoming Message |
| 544 | case Constants.OCPP_JSON_CALL_MESSAGE: |
| 545 | // Process the call |
| 546 | await this.handleRequest(messageId, commandName, commandPayload); |
| 547 | break; |
| 548 | // Outcome Message |
| 549 | case Constants.OCPP_JSON_CALL_RESULT_MESSAGE: |
| 550 | // Respond |
| 551 | // eslint-disable-next-line no-case-declarations |
| 552 | let responseCallback; let requestPayload; |
| 553 | if (Utils.isIterable(this._requests[messageId])) { |
| 554 | [responseCallback, , requestPayload] = this._requests[messageId]; |
| 555 | } else { |
| 556 | throw new Error(`Response request for message id ${messageId} is not iterable`); |
| 557 | } |
| 558 | if (!responseCallback) { |
| 559 | // Error |
| 560 | throw new Error(`Response for unknown message id ${messageId}`); |
| 561 | } |
| 562 | delete this._requests[messageId]; |
| 563 | responseCallback(commandName, requestPayload); |
| 564 | break; |
| 565 | // Error Message |
| 566 | case Constants.OCPP_JSON_CALL_ERROR_MESSAGE: |
| 567 | if (!this._requests[messageId]) { |
| 568 | // Error |
| 569 | throw new Error(`Error for unknown message id ${messageId}`); |
| 570 | } |
| 571 | // eslint-disable-next-line no-case-declarations |
| 572 | let rejectCallback; |
| 573 | if (Utils.isIterable(this._requests[messageId])) { |
| 574 | [, rejectCallback] = this._requests[messageId]; |
| 575 | } else { |
| 576 | throw new Error(`Error request for message id ${messageId} is not iterable`); |
| 577 | } |
| 578 | delete this._requests[messageId]; |
| 579 | rejectCallback(new OCPPError(commandName, commandPayload, errorDetails)); |
| 580 | break; |
| 581 | // Error |
| 582 | default: |
| 583 | throw new Error(`Wrong message type ${messageType}`); |
| 584 | } |
| 585 | } catch (error) { |
| 586 | // Log |
| 587 | logger.error('%s Incoming message %j processing error %s on request content %s', this._logPrefix(), message, error, this._requests[messageId]); |
| 588 | // Send error |
| 589 | // await this.sendError(messageId, error); |
| 590 | } |
| 591 | } |
| 592 | |
| 593 | sendHeartbeat() { |
| 594 | try { |
| 595 | const payload = { |
| 596 | currentTime: new Date().toISOString(), |
| 597 | }; |
| 598 | this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'Heartbeat'); |
| 599 | } catch (error) { |
| 600 | logger.error(this._logPrefix() + ' Send Heartbeat error: ' + error); |
| 601 | throw error; |
| 602 | } |
| 603 | } |
| 604 | |
| 605 | sendBootNotification() { |
| 606 | try { |
| 607 | this.sendMessage(Utils.generateUUID(), this._bootNotificationMessage, Constants.OCPP_JSON_CALL_MESSAGE, 'BootNotification'); |
| 608 | } catch (error) { |
| 609 | logger.error(this._logPrefix() + ' Send BootNotification error: ' + error); |
| 610 | throw error; |
| 611 | } |
| 612 | } |
| 613 | |
| 614 | async sendStatusNotification(connectorId: number, status, errorCode = 'NoError') { |
| 615 | try { |
| 616 | const payload = { |
| 617 | connectorId, |
| 618 | errorCode, |
| 619 | status, |
| 620 | }; |
| 621 | await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StatusNotification'); |
| 622 | } catch (error) { |
| 623 | logger.error(this._logPrefix() + ' Send StatusNotification error: ' + error); |
| 624 | throw error; |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | async sendStartTransaction(connectorId: number, idTag?: string) { |
| 629 | try { |
| 630 | const payload = { |
| 631 | connectorId, |
| 632 | ...!Utils.isUndefined(idTag) ? { idTag } : { idTag: '' }, |
| 633 | meterStart: 0, |
| 634 | timestamp: new Date().toISOString(), |
| 635 | }; |
| 636 | return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StartTransaction'); |
| 637 | } catch (error) { |
| 638 | logger.error(this._logPrefix() + ' Send StartTransaction error: ' + error); |
| 639 | throw error; |
| 640 | } |
| 641 | } |
| 642 | |
| 643 | async sendStopTransaction(transactionId, reason = ''): Promise<void> { |
| 644 | try { |
| 645 | const payload = { |
| 646 | transactionId, |
| 647 | meterStop: 0, |
| 648 | timestamp: new Date().toISOString(), |
| 649 | ...reason && { reason }, |
| 650 | }; |
| 651 | await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StopTransaction'); |
| 652 | } catch (error) { |
| 653 | logger.error(this._logPrefix() + ' Send StopTransaction error: ' + error); |
| 654 | throw error; |
| 655 | } |
| 656 | } |
| 657 | |
| 658 | // eslint-disable-next-line consistent-this |
| 659 | async sendMeterValues(connectorId: number, interval: number, self, debug = false): Promise<void> { |
| 660 | try { |
| 661 | const sampledValues = { |
| 662 | timestamp: new Date().toISOString(), |
| 663 | sampledValue: [], |
| 664 | }; |
| 665 | const meterValuesTemplate = self.getConnector(connectorId).MeterValues; |
| 666 | for (let index = 0; index < meterValuesTemplate.length; index++) { |
| 667 | const connector = self.getConnector(connectorId); |
| 668 | // SoC measurand |
| 669 | if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === 'SoC' && self._getConfigurationKey('MeterValuesSampledData').value.includes('SoC')) { |
| 670 | sampledValues.sampledValue.push({ |
| 671 | ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'Percent' }, |
| 672 | ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, |
| 673 | measurand: meterValuesTemplate[index].measurand, |
| 674 | ...!Utils.isUndefined(meterValuesTemplate[index].location) ? { location: meterValuesTemplate[index].location } : { location: 'EV' }, |
| 675 | ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: Utils.getRandomInt(100) }, |
| 676 | }); |
| 677 | const sampledValuesIndex = sampledValues.sampledValue.length - 1; |
| 678 | if (sampledValues.sampledValue[sampledValuesIndex].value > 100 || debug) { |
| 679 | logger.error(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : 'Energy.Active.Import.Register'}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValues.sampledValue[sampledValuesIndex].value}/100`); |
| 680 | } |
| 681 | // Voltage measurand |
| 682 | } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === 'Voltage' && self._getConfigurationKey('MeterValuesSampledData').value.includes('Voltage')) { |
| 683 | sampledValues.sampledValue.push({ |
| 684 | ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'V' }, |
| 685 | ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, |
| 686 | measurand: meterValuesTemplate[index].measurand, |
| 687 | ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, |
| 688 | ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: self._getVoltageOut() }, |
| 689 | }); |
| 690 | for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) { |
| 691 | const voltageValue = sampledValues.sampledValue[sampledValues.sampledValue.length - 1].value; |
| 692 | let phaseValue; |
| 693 | if (voltageValue >= 0 && voltageValue <= 250) { |
| 694 | phaseValue = `L${phase}-N`; |
| 695 | } else if (voltageValue > 250) { |
| 696 | phaseValue = `L${phase}-L${(phase + 1) % self._getNumberOfPhases() !== 0 ? (phase + 1) % self._getNumberOfPhases() : self._getNumberOfPhases()}`; |
| 697 | } |
| 698 | sampledValues.sampledValue.push({ |
| 699 | ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'V' }, |
| 700 | ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, |
| 701 | measurand: meterValuesTemplate[index].measurand, |
| 702 | ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, |
| 703 | ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: self._getVoltageOut() }, |
| 704 | phase: phaseValue, |
| 705 | }); |
| 706 | } |
| 707 | // Power.Active.Import measurand |
| 708 | } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === 'Power.Active.Import' && self._getConfigurationKey('MeterValuesSampledData').value.includes('Power.Active.Import')) { |
| 709 | // FIXME: factor out powerDivider checks |
| 710 | if (Utils.isUndefined(self._stationInfo.powerDivider)) { |
| 711 | const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`; |
| 712 | logger.error(errMsg); |
| 713 | throw Error(errMsg); |
| 714 | } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) { |
| 715 | const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`; |
| 716 | logger.error(errMsg); |
| 717 | throw Error(errMsg); |
| 718 | } |
| 719 | const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} measurand value`; |
| 720 | const powerMeasurandValues = {} as MeasurandValues ; |
| 721 | const maxPower = Math.round(self._stationInfo.maxPower / self._stationInfo.powerDivider); |
| 722 | const maxPowerPerPhase = Math.round((self._stationInfo.maxPower / self._stationInfo.powerDivider) / self._getNumberOfPhases()); |
| 723 | switch (self._getPowerOutType()) { |
| 724 | case 'AC': |
| 725 | if (Utils.isUndefined(meterValuesTemplate[index].value)) { |
| 726 | powerMeasurandValues.L1 = Utils.getRandomFloatRounded(maxPowerPerPhase); |
| 727 | powerMeasurandValues.L2 = 0; |
| 728 | powerMeasurandValues.L3 = 0; |
| 729 | if (self._getNumberOfPhases() === 3) { |
| 730 | powerMeasurandValues.L2 = Utils.getRandomFloatRounded(maxPowerPerPhase); |
| 731 | powerMeasurandValues.L3 = Utils.getRandomFloatRounded(maxPowerPerPhase); |
| 732 | } |
| 733 | powerMeasurandValues.all = Utils.roundTo(powerMeasurandValues.L1 + powerMeasurandValues.L2 + powerMeasurandValues.L3, 2); |
| 734 | } |
| 735 | break; |
| 736 | case 'DC': |
| 737 | if (Utils.isUndefined(meterValuesTemplate[index].value)) { |
| 738 | powerMeasurandValues.all = Utils.getRandomFloatRounded(maxPower); |
| 739 | } |
| 740 | break; |
| 741 | default: |
| 742 | logger.error(errMsg); |
| 743 | throw Error(errMsg); |
| 744 | } |
| 745 | sampledValues.sampledValue.push({ |
| 746 | ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'W' }, |
| 747 | ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, |
| 748 | measurand: meterValuesTemplate[index].measurand, |
| 749 | ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, |
| 750 | ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: powerMeasurandValues.all }, |
| 751 | }); |
| 752 | const sampledValuesIndex = sampledValues.sampledValue.length - 1; |
| 753 | if (sampledValues.sampledValue[sampledValuesIndex].value > maxPower || debug) { |
| 754 | logger.error(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : 'Energy.Active.Import.Register'}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValues.sampledValue[sampledValuesIndex].value}/${maxPower}`); |
| 755 | } |
| 756 | for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) { |
| 757 | const phaseValue = `L${phase}-N`; |
| 758 | sampledValues.sampledValue.push({ |
| 759 | ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'W' }, |
| 760 | ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, |
| 761 | ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand }, |
| 762 | ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, |
| 763 | ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: powerMeasurandValues[`L${phase}`] }, |
| 764 | phase: phaseValue, |
| 765 | }); |
| 766 | } |
| 767 | // Current.Import measurand |
| 768 | } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === 'Current.Import' && self._getConfigurationKey('MeterValuesSampledData').value.includes('Current.Import')) { |
| 769 | // FIXME: factor out powerDivider checks |
| 770 | if (Utils.isUndefined(self._stationInfo.powerDivider)) { |
| 771 | const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`; |
| 772 | logger.error(errMsg); |
| 773 | throw Error(errMsg); |
| 774 | } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) { |
| 775 | const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`; |
| 776 | logger.error(errMsg); |
| 777 | throw Error(errMsg); |
| 778 | } |
| 779 | const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} measurand value`; |
| 780 | const currentMeasurandValues = {} as MeasurandValues; |
| 781 | let maxAmperage; |
| 782 | switch (self._getPowerOutType()) { |
| 783 | case 'AC': |
| 784 | maxAmperage = ElectricUtils.ampPerPhaseFromPower(self._getNumberOfPhases(), self._stationInfo.maxPower / self._stationInfo.powerDivider, self._getVoltageOut()); |
| 785 | if (Utils.isUndefined(meterValuesTemplate[index].value)) { |
| 786 | currentMeasurandValues.L1 = Utils.getRandomFloatRounded(maxAmperage); |
| 787 | currentMeasurandValues.L2 = 0; |
| 788 | currentMeasurandValues.L3 = 0; |
| 789 | if (self._getNumberOfPhases() === 3) { |
| 790 | currentMeasurandValues.L2 = Utils.getRandomFloatRounded(maxAmperage); |
| 791 | currentMeasurandValues.L3 = Utils.getRandomFloatRounded(maxAmperage); |
| 792 | } |
| 793 | currentMeasurandValues.all = Utils.roundTo((currentMeasurandValues.L1 + currentMeasurandValues.L2 + currentMeasurandValues.L3) / self._getNumberOfPhases(), 2); |
| 794 | } |
| 795 | break; |
| 796 | case 'DC': |
| 797 | maxAmperage = ElectricUtils.ampTotalFromPower(self._stationInfo.maxPower / self._stationInfo.powerDivider, self._getVoltageOut()); |
| 798 | if (Utils.isUndefined(meterValuesTemplate[index].value)) { |
| 799 | currentMeasurandValues.all = Utils.getRandomFloatRounded(maxAmperage); |
| 800 | } |
| 801 | break; |
| 802 | default: |
| 803 | logger.error(errMsg); |
| 804 | throw Error(errMsg); |
| 805 | } |
| 806 | sampledValues.sampledValue.push({ |
| 807 | ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'A' }, |
| 808 | ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, |
| 809 | measurand: meterValuesTemplate[index].measurand, |
| 810 | ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, |
| 811 | ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: currentMeasurandValues.all }, |
| 812 | }); |
| 813 | const sampledValuesIndex = sampledValues.sampledValue.length - 1; |
| 814 | if (sampledValues.sampledValue[sampledValuesIndex].value > maxAmperage || debug) { |
| 815 | logger.error(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : 'Energy.Active.Import.Register'}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValues.sampledValue[sampledValuesIndex].value}/${maxAmperage}`); |
| 816 | } |
| 817 | for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) { |
| 818 | const phaseValue = `L${phase}`; |
| 819 | sampledValues.sampledValue.push({ |
| 820 | ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'A' }, |
| 821 | ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, |
| 822 | ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand }, |
| 823 | ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, |
| 824 | ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: currentMeasurandValues[phaseValue] }, |
| 825 | phase: phaseValue, |
| 826 | }); |
| 827 | } |
| 828 | // Energy.Active.Import.Register measurand (default) |
| 829 | } else if (!meterValuesTemplate[index].measurand || meterValuesTemplate[index].measurand === 'Energy.Active.Import.Register') { |
| 830 | // FIXME: factor out powerDivider checks |
| 831 | if (Utils.isUndefined(self._stationInfo.powerDivider)) { |
| 832 | const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`; |
| 833 | logger.error(errMsg); |
| 834 | throw Error(errMsg); |
| 835 | } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) { |
| 836 | const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`; |
| 837 | logger.error(errMsg); |
| 838 | throw Error(errMsg); |
| 839 | } |
| 840 | if (Utils.isUndefined(meterValuesTemplate[index].value)) { |
| 841 | const measurandValue = Utils.getRandomInt(self._stationInfo.maxPower / (self._stationInfo.powerDivider * 3600000) * interval); |
| 842 | // Persist previous value in connector |
| 843 | if (connector && !Utils.isNullOrUndefined(connector.lastEnergyActiveImportRegisterValue) && connector.lastEnergyActiveImportRegisterValue >= 0) { |
| 844 | connector.lastEnergyActiveImportRegisterValue += measurandValue; |
| 845 | } else { |
| 846 | connector.lastEnergyActiveImportRegisterValue = 0; |
| 847 | } |
| 848 | } |
| 849 | sampledValues.sampledValue.push({ |
| 850 | ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: 'Wh' }, |
| 851 | ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context }, |
| 852 | ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand }, |
| 853 | ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location }, |
| 854 | ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: connector.lastEnergyActiveImportRegisterValue }, |
| 855 | }); |
| 856 | const sampledValuesIndex = sampledValues.sampledValue.length - 1; |
| 857 | const maxConsumption = Math.round(self._stationInfo.maxPower * 3600 / (self._stationInfo.powerDivider * interval)); |
| 858 | if (sampledValues.sampledValue[sampledValuesIndex].value > maxConsumption || debug) { |
| 859 | logger.error(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : 'Energy.Active.Import.Register'}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValues.sampledValue[sampledValuesIndex].value}/${maxConsumption}`); |
| 860 | } |
| 861 | // Unsupported measurand |
| 862 | } else { |
| 863 | logger.info(`${self._logPrefix()} Unsupported MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} on connectorId ${connectorId}`); |
| 864 | } |
| 865 | } |
| 866 | |
| 867 | const payload = { |
| 868 | connectorId, |
| 869 | transactionId: self.getConnector(connectorId).transactionId, |
| 870 | meterValue: sampledValues, |
| 871 | }; |
| 872 | await self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'MeterValues'); |
| 873 | } catch (error) { |
| 874 | logger.error(self._logPrefix() + ' Send MeterValues error: ' + error); |
| 875 | throw error; |
| 876 | } |
| 877 | } |
| 878 | |
| 879 | sendError(messageId, err) { |
| 880 | // Check exception: only OCPP error are accepted |
| 881 | const error = err instanceof OCPPError ? err : new OCPPError(Constants.OCPP_ERROR_INTERNAL_ERROR, err.message); |
| 882 | // Send error |
| 883 | return this.sendMessage(messageId, error, Constants.OCPP_JSON_CALL_ERROR_MESSAGE); |
| 884 | } |
| 885 | |
| 886 | sendMessage(messageId, command, messageType = Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName = '') { |
| 887 | const self = this; |
| 888 | // Send a message through wsConnection |
| 889 | return new Promise((resolve, reject) => { |
| 890 | let messageToSend; |
| 891 | // Type of message |
| 892 | switch (messageType) { |
| 893 | // Request |
| 894 | case Constants.OCPP_JSON_CALL_MESSAGE: |
| 895 | if (this.getEnableStatistics()) { |
| 896 | this._statistics.addMessage(commandName); |
| 897 | } |
| 898 | // Build request |
| 899 | this._requests[messageId] = [responseCallback, rejectCallback, command]; |
| 900 | messageToSend = JSON.stringify([messageType, messageId, commandName, command]); |
| 901 | break; |
| 902 | // Response |
| 903 | case Constants.OCPP_JSON_CALL_RESULT_MESSAGE: |
| 904 | if (this.getEnableStatistics()) { |
| 905 | this._statistics.addMessage(commandName); |
| 906 | } |
| 907 | // Build response |
| 908 | messageToSend = JSON.stringify([messageType, messageId, command]); |
| 909 | break; |
| 910 | // Error Message |
| 911 | case Constants.OCPP_JSON_CALL_ERROR_MESSAGE: |
| 912 | if (this.getEnableStatistics()) { |
| 913 | this._statistics.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`); |
| 914 | } |
| 915 | // Build Message |
| 916 | messageToSend = JSON.stringify([messageType, messageId, command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR, command.message ? command.message : '', command.details ? command.details : {}]); |
| 917 | break; |
| 918 | } |
| 919 | // Check if wsConnection is ready |
| 920 | if (this._wsConnection && this._wsConnection.readyState === WebSocket.OPEN) { |
| 921 | // Yes: Send Message |
| 922 | this._wsConnection.send(messageToSend); |
| 923 | } else { |
| 924 | // Buffer message until connection is back |
| 925 | this._messageQueue.push(messageToSend); |
| 926 | } |
| 927 | // Request? |
| 928 | if (messageType !== Constants.OCPP_JSON_CALL_MESSAGE) { |
| 929 | // Yes: send Ok |
| 930 | resolve(); |
| 931 | } else if (this._wsConnection && this._wsConnection.readyState === WebSocket.OPEN) { |
| 932 | // Send timeout in case connection is open otherwise wait for ever |
| 933 | // FIXME: Handle message on timeout |
| 934 | setTimeout(() => rejectCallback(new OCPPError(command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR, command.message ? command.message : '', command.details ? command.details : {})), Constants.OCPP_SOCKET_TIMEOUT); |
| 935 | } |
| 936 | |
| 937 | // Function that will receive the request's response |
| 938 | function responseCallback(payload, requestPayload) { |
| 939 | self.handleResponse(commandName, payload, requestPayload); |
| 940 | // Send the response |
| 941 | resolve(payload); |
| 942 | } |
| 943 | |
| 944 | // Function that will receive the request's rejection |
| 945 | function rejectCallback(error: OCPPError) { |
| 946 | logger.debug(`${self._logPrefix()} Error %j on commandName %s command %j`, error, commandName, command); |
| 947 | if (self.getEnableStatistics()) { |
| 948 | self._statistics.addMessage(`Error on commandName ${commandName}`, true); |
| 949 | } |
| 950 | // Build Exception |
| 951 | // eslint-disable-next-line no-empty-function |
| 952 | self._requests[messageId] = [() => { }, () => { }, '']; // Properly format the request |
| 953 | // Send error |
| 954 | reject(error); |
| 955 | } |
| 956 | }); |
| 957 | } |
| 958 | |
| 959 | handleResponse(commandName, payload, requestPayload) { |
| 960 | if (this.getEnableStatistics()) { |
| 961 | this._statistics.addMessage(commandName, true); |
| 962 | } |
| 963 | const responseCallbackFn = 'handleResponse' + commandName; |
| 964 | if (typeof this[responseCallbackFn] === 'function') { |
| 965 | this[responseCallbackFn](payload, requestPayload); |
| 966 | } else { |
| 967 | logger.error(this._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn); |
| 968 | } |
| 969 | } |
| 970 | |
| 971 | handleResponseBootNotification(payload, requestPayload) { |
| 972 | if (payload.status === 'Accepted') { |
| 973 | this._heartbeatInterval = payload.interval * 1000; |
| 974 | this._addConfigurationKey('HeartBeatInterval', Utils.convertToInt(payload.interval)); |
| 975 | this._addConfigurationKey('HeartbeatInterval', Utils.convertToInt(payload.interval), false, false); |
| 976 | this._startMessageSequence(); |
| 977 | } else if (payload.status === 'Pending') { |
| 978 | logger.info(this._logPrefix() + ' Charging station in pending state on the central server'); |
| 979 | } else { |
| 980 | logger.info(this._logPrefix() + ' Charging station rejected by the central server'); |
| 981 | } |
| 982 | } |
| 983 | |
| 984 | _initTransactionOnConnector(connectorId) { |
| 985 | this.getConnector(connectorId).transactionStarted = false; |
| 986 | this.getConnector(connectorId).transactionId = null; |
| 987 | this.getConnector(connectorId).idTag = null; |
| 988 | this.getConnector(connectorId).lastEnergyActiveImportRegisterValue = -1; |
| 989 | } |
| 990 | |
| 991 | _resetTransactionOnConnector(connectorId) { |
| 992 | this._initTransactionOnConnector(connectorId); |
| 993 | if (this.getConnector(connectorId).transactionSetInterval) { |
| 994 | clearInterval(this.getConnector(connectorId).transactionSetInterval); |
| 995 | } |
| 996 | } |
| 997 | |
| 998 | handleResponseStartTransaction(payload, requestPayload) { |
| 999 | if (this.getConnector(requestPayload.connectorId).transactionStarted) { |
| 1000 | logger.debug(this._logPrefix() + ' Try to start a transaction on an already used connector ' + requestPayload.connectorId + ': %s', this.getConnector(requestPayload.connectorId)); |
| 1001 | return; |
| 1002 | } |
| 1003 | |
| 1004 | let transactionConnectorId; |
| 1005 | for (const connector in this._connectors) { |
| 1006 | if (Utils.convertToInt(connector) === Utils.convertToInt(requestPayload.connectorId)) { |
| 1007 | transactionConnectorId = connector; |
| 1008 | break; |
| 1009 | } |
| 1010 | } |
| 1011 | if (!transactionConnectorId) { |
| 1012 | logger.error(this._logPrefix() + ' Try to start a transaction on a non existing connector Id ' + requestPayload.connectorId); |
| 1013 | return; |
| 1014 | } |
| 1015 | if (payload.idTagInfo && payload.idTagInfo.status === 'Accepted') { |
| 1016 | this.getConnector(requestPayload.connectorId).transactionStarted = true; |
| 1017 | this.getConnector(requestPayload.connectorId).transactionId = payload.transactionId; |
| 1018 | this.getConnector(requestPayload.connectorId).idTag = requestPayload.idTag; |
| 1019 | this.getConnector(requestPayload.connectorId).lastEnergyActiveImportRegisterValue = 0; |
| 1020 | this.sendStatusNotification(requestPayload.connectorId, 'Charging'); |
| 1021 | logger.info(this._logPrefix() + ' Transaction ' + payload.transactionId + ' STARTED on ' + this._stationInfo.name + '#' + requestPayload.connectorId + ' for idTag ' + requestPayload.idTag); |
| 1022 | if (this._stationInfo.powerSharedByConnectors) { |
| 1023 | this._stationInfo.powerDivider++; |
| 1024 | } |
| 1025 | const configuredMeterValueSampleInterval = this._getConfigurationKey('MeterValueSampleInterval'); |
| 1026 | this._startMeterValues(requestPayload.connectorId, |
| 1027 | configuredMeterValueSampleInterval ? configuredMeterValueSampleInterval.value * 1000 : 60000); |
| 1028 | } else { |
| 1029 | logger.error(this._logPrefix() + ' Starting transaction id ' + payload.transactionId + ' REJECTED with status ' + payload.idTagInfo.status + ', idTag ' + requestPayload.idTag); |
| 1030 | this._resetTransactionOnConnector(requestPayload.connectorId); |
| 1031 | this.sendStatusNotification(requestPayload.connectorId, 'Available'); |
| 1032 | } |
| 1033 | } |
| 1034 | |
| 1035 | handleResponseStopTransaction(payload, requestPayload) { |
| 1036 | let transactionConnectorId; |
| 1037 | for (const connector in this._connectors) { |
| 1038 | if (this.getConnector(Utils.convertToInt(connector)).transactionId === requestPayload.transactionId) { |
| 1039 | transactionConnectorId = connector; |
| 1040 | break; |
| 1041 | } |
| 1042 | } |
| 1043 | if (!transactionConnectorId) { |
| 1044 | logger.error(this._logPrefix() + ' Try to stop a non existing transaction ' + requestPayload.transactionId); |
| 1045 | return; |
| 1046 | } |
| 1047 | if (payload.idTagInfo && payload.idTagInfo.status === 'Accepted') { |
| 1048 | this.sendStatusNotification(transactionConnectorId, 'Available'); |
| 1049 | if (this._stationInfo.powerSharedByConnectors) { |
| 1050 | this._stationInfo.powerDivider--; |
| 1051 | } |
| 1052 | logger.info(this._logPrefix() + ' Transaction ' + requestPayload.transactionId + ' STOPPED on ' + this._stationInfo.name + '#' + transactionConnectorId); |
| 1053 | this._resetTransactionOnConnector(transactionConnectorId); |
| 1054 | } else { |
| 1055 | logger.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload.transactionId + ' REJECTED with status ' + payload.idTagInfo.status); |
| 1056 | } |
| 1057 | } |
| 1058 | |
| 1059 | handleResponseStatusNotification(payload, requestPayload) { |
| 1060 | logger.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload, requestPayload); |
| 1061 | } |
| 1062 | |
| 1063 | handleResponseMeterValues(payload, requestPayload) { |
| 1064 | logger.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload, requestPayload); |
| 1065 | } |
| 1066 | |
| 1067 | handleResponseHeartbeat(payload, requestPayload) { |
| 1068 | logger.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload, requestPayload); |
| 1069 | } |
| 1070 | |
| 1071 | async handleRequest(messageId, commandName, commandPayload) { |
| 1072 | if (this.getEnableStatistics()) { |
| 1073 | this._statistics.addMessage(commandName, true); |
| 1074 | } |
| 1075 | let response; |
| 1076 | // Call |
| 1077 | if (typeof this['handleRequest' + commandName] === 'function') { |
| 1078 | try { |
| 1079 | // Call the method to build the response |
| 1080 | response = await this['handleRequest' + commandName](commandPayload); |
| 1081 | } catch (error) { |
| 1082 | // Log |
| 1083 | logger.error(this._logPrefix() + ' Handle request error: ' + error); |
| 1084 | // Send back response to inform backend |
| 1085 | await this.sendError(messageId, error); |
| 1086 | } |
| 1087 | } else { |
| 1088 | // Throw exception |
| 1089 | await this.sendError(messageId, new OCPPError(Constants.OCPP_ERROR_NOT_IMPLEMENTED, 'Not implemented', {})); |
| 1090 | throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`); |
| 1091 | } |
| 1092 | // Send response |
| 1093 | await this.sendMessage(messageId, response, Constants.OCPP_JSON_CALL_RESULT_MESSAGE); |
| 1094 | } |
| 1095 | |
| 1096 | // Simulate charging station restart |
| 1097 | async handleRequestReset(commandPayload) { |
| 1098 | setImmediate(async () => { |
| 1099 | await this.stop(commandPayload.type + 'Reset'); |
| 1100 | await Utils.sleep(this._stationInfo.resetTime); |
| 1101 | await this.start(); |
| 1102 | }); |
| 1103 | logger.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`); |
| 1104 | return Constants.OCPP_RESPONSE_ACCEPTED; |
| 1105 | } |
| 1106 | |
| 1107 | _getConfigurationKey(key) { |
| 1108 | return this._configuration.configurationKey.find((configElement) => configElement.key === key); |
| 1109 | } |
| 1110 | |
| 1111 | _addConfigurationKey(key, value, readonly = false, visible = true, reboot = false) { |
| 1112 | const keyFound = this._getConfigurationKey(key); |
| 1113 | if (!keyFound) { |
| 1114 | this._configuration.configurationKey.push({ |
| 1115 | key, |
| 1116 | readonly, |
| 1117 | value, |
| 1118 | visible, |
| 1119 | reboot, |
| 1120 | }); |
| 1121 | } |
| 1122 | } |
| 1123 | |
| 1124 | _setConfigurationKeyValue(key, value) { |
| 1125 | const keyFound = this._getConfigurationKey(key); |
| 1126 | if (keyFound) { |
| 1127 | const keyIndex = this._configuration.configurationKey.indexOf(keyFound); |
| 1128 | this._configuration.configurationKey[keyIndex].value = value; |
| 1129 | } |
| 1130 | } |
| 1131 | |
| 1132 | async handleRequestGetConfiguration(commandPayload) { |
| 1133 | const configurationKey = []; |
| 1134 | const unknownKey = []; |
| 1135 | if (Utils.isEmptyArray(commandPayload.key)) { |
| 1136 | for (const configuration of this._configuration.configurationKey) { |
| 1137 | if (Utils.isUndefined(configuration.visible)) { |
| 1138 | configuration.visible = true; |
| 1139 | } else { |
| 1140 | configuration.visible = Utils.convertToBoolean(configuration.visible); |
| 1141 | } |
| 1142 | if (!configuration.visible) { |
| 1143 | continue; |
| 1144 | } |
| 1145 | configurationKey.push({ |
| 1146 | key: configuration.key, |
| 1147 | readonly: configuration.readonly, |
| 1148 | value: configuration.value, |
| 1149 | }); |
| 1150 | } |
| 1151 | } else { |
| 1152 | for (const configurationKey of commandPayload.key) { |
| 1153 | const keyFound = this._getConfigurationKey(configurationKey); |
| 1154 | if (keyFound) { |
| 1155 | if (Utils.isUndefined(keyFound.visible)) { |
| 1156 | keyFound.visible = true; |
| 1157 | } else { |
| 1158 | keyFound.visible = Utils.convertToBoolean(configurationKey.visible); |
| 1159 | } |
| 1160 | if (!keyFound.visible) { |
| 1161 | continue; |
| 1162 | } |
| 1163 | configurationKey.push({ |
| 1164 | key: keyFound.key, |
| 1165 | readonly: keyFound.readonly, |
| 1166 | value: keyFound.value, |
| 1167 | }); |
| 1168 | } else { |
| 1169 | unknownKey.push(configurationKey); |
| 1170 | } |
| 1171 | } |
| 1172 | } |
| 1173 | return { |
| 1174 | configurationKey, |
| 1175 | unknownKey, |
| 1176 | }; |
| 1177 | } |
| 1178 | |
| 1179 | async handleRequestChangeConfiguration(commandPayload) { |
| 1180 | const keyToChange = this._getConfigurationKey(commandPayload.key); |
| 1181 | if (!keyToChange) { |
| 1182 | return { status: Constants.OCPP_ERROR_NOT_SUPPORTED }; |
| 1183 | } else if (keyToChange && Utils.convertToBoolean(keyToChange.readonly)) { |
| 1184 | return Constants.OCPP_RESPONSE_REJECTED; |
| 1185 | } else if (keyToChange && !Utils.convertToBoolean(keyToChange.readonly)) { |
| 1186 | const keyIndex = this._configuration.configurationKey.indexOf(keyToChange); |
| 1187 | this._configuration.configurationKey[keyIndex].value = commandPayload.value; |
| 1188 | let triggerHeartbeatRestart = false; |
| 1189 | if (keyToChange.key === 'HeartBeatInterval') { |
| 1190 | this._setConfigurationKeyValue('HeartbeatInterval', commandPayload.value); |
| 1191 | triggerHeartbeatRestart = true; |
| 1192 | } |
| 1193 | if (keyToChange.key === 'HeartbeatInterval') { |
| 1194 | this._setConfigurationKeyValue('HeartBeatInterval', commandPayload.value); |
| 1195 | triggerHeartbeatRestart = true; |
| 1196 | } |
| 1197 | if (triggerHeartbeatRestart) { |
| 1198 | this._heartbeatInterval = Utils.convertToInt(commandPayload.value) * 1000; |
| 1199 | // Stop heartbeat |
| 1200 | this._stopHeartbeat(); |
| 1201 | // Start heartbeat |
| 1202 | this._startHeartbeat(); |
| 1203 | } |
| 1204 | if (Utils.convertToBoolean(keyToChange.reboot)) { |
| 1205 | return Constants.OCPP_RESPONSE_REBOOT_REQUIRED; |
| 1206 | } |
| 1207 | return Constants.OCPP_RESPONSE_ACCEPTED; |
| 1208 | } |
| 1209 | } |
| 1210 | |
| 1211 | async handleRequestRemoteStartTransaction(commandPayload) { |
| 1212 | const transactionConnectorID = commandPayload.connectorId ? commandPayload.connectorId : '1'; |
| 1213 | if (this._getAuthorizeRemoteTxRequests() && this._getLocalAuthListEnabled() && this.hasAuthorizedTags()) { |
| 1214 | // Check if authorized |
| 1215 | if (this._authorizedTags.find((value) => value === commandPayload.idTag)) { |
| 1216 | // Authorization successful start transaction |
| 1217 | this.sendStartTransaction(transactionConnectorID, commandPayload.idTag); |
| 1218 | logger.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag); |
| 1219 | return Constants.OCPP_RESPONSE_ACCEPTED; |
| 1220 | } |
| 1221 | logger.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload.idTagInfo.status + ', idTag ' + commandPayload.idTag); |
| 1222 | return Constants.OCPP_RESPONSE_REJECTED; |
| 1223 | } |
| 1224 | // No local authorization check required => start transaction |
| 1225 | this.sendStartTransaction(transactionConnectorID, commandPayload.idTag); |
| 1226 | logger.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag); |
| 1227 | return Constants.OCPP_RESPONSE_ACCEPTED; |
| 1228 | } |
| 1229 | |
| 1230 | async handleRequestRemoteStopTransaction(commandPayload) { |
| 1231 | for (const connector in this._connectors) { |
| 1232 | if (this.getConnector(Utils.convertToInt(connector)).transactionId === commandPayload.transactionId) { |
| 1233 | this.sendStopTransaction(commandPayload.transactionId); |
| 1234 | return Constants.OCPP_RESPONSE_ACCEPTED; |
| 1235 | } |
| 1236 | } |
| 1237 | logger.info(this._logPrefix() + ' Try to stop remotely a non existing transaction ' + commandPayload.transactionId); |
| 1238 | return Constants.OCPP_RESPONSE_REJECTED; |
| 1239 | } |
| 1240 | } |
| 1241 | |