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