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