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