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