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