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