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