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