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