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