Commit | Line | Data |
---|---|---|
7dde0b73 JB |
1 | const Configuration = require('../utils/Configuration'); |
2 | const logger = require('../utils/Logger'); | |
3 | const WebSocket = require('ws'); | |
f7869514 | 4 | const Constants = require('../utils/Constants'); |
7dde0b73 JB |
5 | const Utils = require('../utils/Utils'); |
6 | const OCPPError = require('./OcppError'); | |
7dde0b73 JB |
7 | const AutomaticTransactionGenerator = require('./AutomaticTransactionGenerator'); |
8 | const Statistics = require('../utils/Statistics'); | |
9 | const fs = require('fs'); | |
10 | const {performance, PerformanceObserver} = require('perf_hooks'); | |
11 | ||
12 | class ChargingStation { | |
2e6f5966 JB |
13 | constructor(index, stationTemplateFile) { |
14 | this._index = index; | |
15 | this._stationTemplateFile = stationTemplateFile; | |
16 | this._initialize(); | |
17 | ||
7dde0b73 JB |
18 | this._autoReconnectRetryCount = 0; |
19 | this._autoReconnectMaxRetries = Configuration.getAutoReconnectMaxRetries(); // -1 for unlimited | |
20 | this._autoReconnectTimeout = Configuration.getAutoReconnectTimeout() * 1000; // ms, zero for disabling | |
2e6f5966 JB |
21 | |
22 | this._requests = {}; | |
23 | this._messageQueue = []; | |
24 | ||
7dde0b73 | 25 | this._isSocketRestart = false; |
34dcb3b5 | 26 | |
83045896 | 27 | this._authorizedTags = this._loadAndGetAuthorizedTags(); |
2e6f5966 JB |
28 | } |
29 | ||
30 | _initialize() { | |
31 | this._stationInfo = this._buildStationInfo(); | |
32 | this._bootNotificationMessage = { | |
33 | chargePointModel: this._stationInfo.chargePointModel, | |
34 | chargePointVendor: this._stationInfo.chargePointVendor, | |
6958152c | 35 | chargePointSerialNumber: this._stationInfo.chargePointSerialNumberPrefix ? this._stationInfo.chargePointSerialNumberPrefix : '', |
34dcb3b5 | 36 | firmwareVersion: this._stationInfo.firmwareVersion ? this._stationInfo.firmwareVersion : '', |
2e6f5966 JB |
37 | }; |
38 | this._configuration = this._getConfiguration(); | |
2e6f5966 | 39 | this._supervisionUrl = this._getSupervisionURL(); |
7dde0b73 JB |
40 | this._statistics = new Statistics(this._stationInfo.name); |
41 | this._performanceObserver = new PerformanceObserver((list) => { | |
42 | const entry = list.getEntries()[0]; | |
43 | this._statistics.logPerformance(entry, 'ChargingStation'); | |
44 | this._performanceObserver.disconnect(); | |
45 | }); | |
7dde0b73 JB |
46 | } |
47 | ||
48 | _basicFormatLog() { | |
49 | return Utils.basicFormatLog(` ${this._stationInfo.name}:`); | |
50 | } | |
51 | ||
2e6f5966 JB |
52 | _getConfiguration() { |
53 | return this._stationInfo.Configuration ? this._stationInfo.Configuration : {}; | |
7dde0b73 JB |
54 | } |
55 | ||
2e6f5966 JB |
56 | _getAuthorizationFile() { |
57 | return this._stationInfo.authorizationFile ? this._stationInfo.authorizationFile : ''; | |
7dde0b73 JB |
58 | } |
59 | ||
83045896 | 60 | _loadAndGetAuthorizedTags() { |
2e6f5966 JB |
61 | let authorizedTags = []; |
62 | const authorizationFile = this._getAuthorizationFile(); | |
63 | if (authorizationFile) { | |
64 | try { | |
65 | // Load authorization file | |
66 | const fileDescriptor = fs.openSync(authorizationFile, 'r'); | |
67 | authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')); | |
68 | fs.closeSync(fileDescriptor); | |
69 | } catch (error) { | |
70 | logger.error(this._basicFormatLog() + ' Authorization file loading error: ' + error); | |
71 | } | |
72 | } else { | |
73 | logger.info(this._basicFormatLog() + ' No authorization file given in template file ' + this._stationTemplateFile); | |
74 | } | |
75 | return authorizedTags; | |
76 | } | |
77 | ||
78 | _startAuthorizationFileMonitoring() { | |
79 | // eslint-disable-next-line no-unused-vars | |
80 | fs.watchFile(this._getAuthorizationFile(), (current, previous) => { | |
81 | try { | |
82 | logger.debug(this._basicFormatLog() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload'); | |
83 | // Initialize _authorizedTags | |
83045896 | 84 | this._authorizedTags = this._loadAndGetAuthorizedTags(); |
2e6f5966 JB |
85 | } catch (error) { |
86 | logger.error(this._basicFormatLog() + ' Authorization file monitoring error: ' + error); | |
87 | } | |
88 | }); | |
89 | } | |
90 | ||
91 | _startStationTemplateFileMonitoring() { | |
92 | // eslint-disable-next-line no-unused-vars | |
93 | fs.watchFile(this._stationTemplateFile, (current, previous) => { | |
94 | try { | |
95 | logger.debug(this._basicFormatLog() + ' Template file ' + this._stationTemplateFile + ' have changed, reload'); | |
96 | // Initialize | |
97 | this._initialize(); | |
98 | } catch (error) { | |
99 | logger.error(this._basicFormatLog() + ' Charging station template file monitoring error: ' + error); | |
100 | } | |
101 | }); | |
102 | } | |
103 | ||
104 | _getSupervisionURL() { | |
105 | const supervisionUrls = Utils.cloneJSonDocument(this._stationInfo.supervisionURL ? this._stationInfo.supervisionURL : Configuration.getSupervisionURLs()); | |
7dde0b73 JB |
106 | let indexUrl = 0; |
107 | if (Array.isArray(supervisionUrls)) { | |
2e6f5966 JB |
108 | if (Configuration.getDistributeStationToTenantEqually()) { |
109 | indexUrl = this._index % supervisionUrls.length; | |
7dde0b73 JB |
110 | } else { |
111 | // Get a random url | |
112 | indexUrl = Math.floor(Math.random() * supervisionUrls.length); | |
113 | } | |
114 | return supervisionUrls[indexUrl]; | |
115 | } | |
116 | return supervisionUrls; | |
117 | } | |
118 | ||
2e6f5966 JB |
119 | _getStationName(stationTemplate) { |
120 | return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + ('000000000' + this._index).substr(('000000000' + this._index).length - 4); | |
7dde0b73 JB |
121 | } |
122 | ||
123 | _getAuthorizeRemoteTxRequests() { | |
124 | const authorizeRemoteTxRequests = this._configuration.configurationKey.find((configElement) => configElement.key === 'AuthorizeRemoteTxRequests'); | |
a6e68f34 | 125 | return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false; |
7dde0b73 JB |
126 | } |
127 | ||
def3d48e JB |
128 | _getLocalAuthListEnabled() { |
129 | const localAuthListEnabled = this._configuration.configurationKey.find((configElement) => configElement.key === 'LocalAuthListEnabled'); | |
130 | return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false; | |
131 | } | |
132 | ||
2e6f5966 JB |
133 | _buildStationInfo() { |
134 | let stationTemplateFromFile; | |
135 | try { | |
136 | // Load template file | |
137 | const fileDescriptor = fs.openSync(this._stationTemplateFile, 'r'); | |
138 | stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')); | |
139 | fs.closeSync(fileDescriptor); | |
140 | } catch (error) { | |
141 | logger.error(this._basicFormatLog() + ' Template file loading error: ' + error); | |
142 | } | |
143 | const stationTemplate = stationTemplateFromFile || {}; | |
144 | if (Array.isArray(stationTemplateFromFile.power)) { | |
145 | stationTemplate.maxPower = stationTemplateFromFile.power[Math.floor(Math.random() * stationTemplateFromFile.power.length)]; | |
7dde0b73 | 146 | } else { |
2e6f5966 | 147 | stationTemplate.maxPower = stationTemplateFromFile.power; |
7dde0b73 | 148 | } |
2e6f5966 | 149 | stationTemplate.name = this._getStationName(stationTemplateFromFile); |
7dde0b73 JB |
150 | return stationTemplate; |
151 | } | |
152 | ||
153 | async start() { | |
34dcb3b5 JB |
154 | this._url = this._supervisionUrl + '/' + this._stationInfo.name; |
155 | this._wsConnection = new WebSocket(this._url, 'ocpp1.6'); | |
7dde0b73 | 156 | logger.info(this._basicFormatLog() + ' Will communicate with ' + this._supervisionUrl); |
2e6f5966 JB |
157 | // Monitor authorization file |
158 | this._startAuthorizationFileMonitoring(); | |
159 | // Monitor station template file | |
160 | this._startStationTemplateFileMonitoring(); | |
7dde0b73 JB |
161 | // Handle Socket incoming messages |
162 | this._wsConnection.on('message', this.onMessage.bind(this)); | |
163 | // Handle Socket error | |
164 | this._wsConnection.on('error', this.onError.bind(this)); | |
165 | // Handle Socket close | |
166 | this._wsConnection.on('close', this.onClose.bind(this)); | |
167 | // Handle Socket opening connection | |
168 | this._wsConnection.on('open', this.onOpen.bind(this)); | |
169 | // Handle Socket ping | |
170 | this._wsConnection.on('ping', this.onPing.bind(this)); | |
171 | } | |
172 | ||
173 | onOpen() { | |
174 | logger.info(`${this._basicFormatLog()} Is connected to server through ${this._url}`); | |
0bbcb3dc JB |
175 | if (!this._heartbeatInterval) { |
176 | // Send BootNotification | |
177 | try { | |
178 | this.sendMessage(Utils.generateUUID(), this._bootNotificationMessage, Constants.OCPP_JSON_CALL_MESSAGE, 'BootNotification'); | |
179 | } catch (error) { | |
180 | logger.error(this._basicFormatLog() + ' Send boot notification error: ' + error); | |
181 | } | |
182 | } | |
7dde0b73 | 183 | if (this._isSocketRestart) { |
027b409a | 184 | this._basicStartMessageSequence(); |
7dde0b73 JB |
185 | if (this._messageQueue.length > 0) { |
186 | this._messageQueue.forEach((message) => { | |
187 | if (this._wsConnection.readyState === WebSocket.OPEN) { | |
188 | this._wsConnection.send(message); | |
189 | } | |
190 | }); | |
191 | } | |
7dde0b73 JB |
192 | } |
193 | this._autoReconnectRetryCount = 0; | |
194 | this._isSocketRestart = false; | |
195 | } | |
196 | ||
197 | onError(error) { | |
198 | switch (error) { | |
199 | case 'ECONNREFUSED': | |
200 | this._isSocketRestart = true; | |
201 | this._reconnect(error); | |
202 | break; | |
203 | default: | |
204 | logger.error(this._basicFormatLog() + ' Socket error: ' + error); | |
205 | break; | |
206 | } | |
207 | } | |
208 | ||
209 | onClose(error) { | |
210 | switch (error) { | |
211 | case 1000: // Normal close | |
212 | case 1005: | |
213 | logger.info(this._basicFormatLog() + ' Socket normally closed ' + error); | |
214 | this._autoReconnectRetryCount = 0; | |
215 | break; | |
216 | default: // Abnormal close | |
217 | this._isSocketRestart = true; | |
218 | this._reconnect(error); | |
219 | break; | |
220 | } | |
221 | } | |
222 | ||
223 | onPing() { | |
027b409a | 224 | logger.debug(this._basicFormatLog() + ' Has received a WS ping (rfc6455) from the server'); |
7dde0b73 JB |
225 | } |
226 | ||
227 | async onMessage(message) { | |
2d8cee5a | 228 | let [messageType, messageId, commandName, commandPayload, errorDetails] = [0, '', Constants.ENTITY_CHARGING_STATION, '', '']; |
7dde0b73 | 229 | try { |
2d8cee5a JB |
230 | // Parse the message |
231 | [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(message); | |
232 | ||
7dde0b73 JB |
233 | // Check the Type of message |
234 | switch (messageType) { | |
235 | // Incoming Message | |
f7869514 | 236 | case Constants.OCPP_JSON_CALL_MESSAGE: |
7dde0b73 JB |
237 | // Process the call |
238 | this._statistics.addMessage(commandName); | |
239 | await this.handleRequest(messageId, commandName, commandPayload); | |
240 | break; | |
241 | // Outcome Message | |
f7869514 | 242 | case Constants.OCPP_JSON_CALL_RESULT_MESSAGE: |
7dde0b73 JB |
243 | // Respond |
244 | // eslint-disable-next-line no-case-declarations | |
245 | let responseCallback; let requestPayload; | |
246 | if (Utils.isIterable(this._requests[messageId])) { | |
247 | [responseCallback, , requestPayload] = this._requests[messageId]; | |
248 | } else { | |
249 | throw new Error(`Response request for unknown message id ${messageId} is not iterable`); | |
250 | } | |
251 | if (!responseCallback) { | |
252 | // Error | |
253 | throw new Error(`Response for unknown message id ${messageId}`); | |
254 | } | |
255 | delete this._requests[messageId]; | |
256 | // this._statistics.addMessage(commandName) | |
257 | responseCallback(commandName, requestPayload); | |
258 | break; | |
259 | // Error Message | |
f7869514 | 260 | case Constants.OCPP_JSON_CALL_ERROR_MESSAGE: |
7dde0b73 JB |
261 | if (!this._requests[messageId]) { |
262 | // Error | |
263 | throw new Error(`Error for unknown message id ${messageId}`); | |
264 | } | |
265 | // eslint-disable-next-line no-case-declarations | |
266 | let rejectCallback; | |
267 | if (Utils.isIterable(this._requests[messageId])) { | |
268 | [, rejectCallback] = this._requests[messageId]; | |
269 | } else { | |
270 | throw new Error(`Error request for unknown message id ${messageId} is not iterable`); | |
271 | } | |
272 | delete this._requests[messageId]; | |
273 | rejectCallback(new OCPPError(commandName, commandPayload, errorDetails)); | |
274 | break; | |
275 | // Error | |
276 | default: | |
277 | throw new Error(`Wrong message type ${messageType}`); | |
278 | } | |
279 | } catch (error) { | |
280 | // Log | |
281 | logger.error('%s Incoming message %j processing error %s on request content %s', this._basicFormatLog(), message, error, this._requests[messageId]); | |
282 | // Send error | |
283 | // await this.sendError(messageId, error); | |
284 | } | |
285 | } | |
286 | ||
027b409a JB |
287 | // eslint-disable-next-line class-methods-use-this |
288 | async _startHeartbeat(self) { | |
289 | if (self._heartbeatInterval && !self._heartbeatSetInterval) { | |
027b409a JB |
290 | self._heartbeatSetInterval = setInterval(() => { |
291 | try { | |
292 | const payload = { | |
293 | currentTime: new Date().toISOString(), | |
294 | }; | |
295 | self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'Heartbeat'); | |
296 | } catch (error) { | |
297 | logger.error(self._basicFormatLog() + ' Send heartbeat error: ' + error); | |
298 | } | |
299 | }, self._heartbeatInterval); | |
0bbcb3dc | 300 | logger.info(self._basicFormatLog() + ' Heartbeat started every ' + self._heartbeatInterval + 'ms'); |
027b409a JB |
301 | } else { |
302 | logger.error(self._basicFormatLog() + ' Heartbeat interval undefined, not starting the heartbeat'); | |
303 | } | |
304 | } | |
305 | ||
7dde0b73 JB |
306 | _reconnect(error) { |
307 | logger.error(this._basicFormatLog() + ' Socket: abnormally closed', error); | |
308 | // Stop heartbeat interval | |
309 | if (this._heartbeatSetInterval) { | |
310 | clearInterval(this._heartbeatSetInterval); | |
311 | this._heartbeatSetInterval = null; | |
312 | } | |
34dcb3b5 JB |
313 | // Stop the ATG if needed |
314 | if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable) && | |
315 | Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure) && | |
316 | this._automaticTransactionGeneration && | |
317 | !this._automaticTransactionGeneration.timeToStop) { | |
7dde0b73 JB |
318 | this._automaticTransactionGeneration.stop(); |
319 | } | |
320 | if (this._autoReconnectTimeout !== 0 && | |
321 | (this._autoReconnectRetryCount < this._autoReconnectMaxRetries || this._autoReconnectMaxRetries === -1)) { | |
322 | logger.error(`${this._basicFormatLog()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`); | |
323 | this._autoReconnectRetryCount++; | |
324 | setTimeout(() => { | |
325 | logger.error(this._basicFormatLog() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount); | |
326 | this.start(); | |
327 | }, this._autoReconnectTimeout); | |
328 | } else if (this._autoReconnectTimeout !== 0 || this._autoReconnectMaxRetries !== -1) { | |
329 | logger.error(`${this._basicFormatLog()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`); | |
330 | } | |
331 | } | |
332 | ||
f7869514 | 333 | send(command, messageType = Constants.OCPP_JSON_CALL_MESSAGE) { |
7dde0b73 | 334 | // Send Message |
027b409a | 335 | return this.sendMessage(Utils.generateUUID(), command, messageType); |
7dde0b73 JB |
336 | } |
337 | ||
338 | sendError(messageId, err) { | |
339 | // Check exception: only OCPP error are accepted | |
72766a82 | 340 | const error = err instanceof OCPPError ? err : new OCPPError(Constants.OCPP_ERROR_INTERNAL_ERROR, err.message); |
7dde0b73 | 341 | // Send error |
f7869514 | 342 | return this.sendMessage(messageId, error, Constants.OCPP_JSON_CALL_ERROR_MESSAGE); |
7dde0b73 JB |
343 | } |
344 | ||
027b409a JB |
345 | async sendStatusNotification(connectorId, status, errorCode = 'NoError') { |
346 | try { | |
347 | const payload = { | |
348 | connectorId, | |
349 | errorCode, | |
350 | status, | |
351 | }; | |
352 | await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StatusNotification'); | |
353 | } catch (error) { | |
354 | logger.error(this._basicFormatLog() + ' Send status error: ' + error); | |
355 | } | |
356 | } | |
357 | ||
358 | async sendStatusNotificationWithTimeout(connectorId, status, errorCode = 'NoError', timeout = Constants.STATUS_NOTIFICATION_TIMEOUT) { | |
359 | setTimeout(() => this.sendStatusNotification(connectorId, status, errorCode), timeout); | |
360 | } | |
361 | ||
f7869514 | 362 | sendMessage(messageId, command, messageType = Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName = '') { |
7dde0b73 JB |
363 | // Send a message through wsConnection |
364 | const self = this; | |
365 | // Create a promise | |
366 | return new Promise((resolve, reject) => { | |
367 | let messageToSend; | |
368 | // Type of message | |
369 | switch (messageType) { | |
370 | // Request | |
f7869514 | 371 | case Constants.OCPP_JSON_CALL_MESSAGE: |
7dde0b73 JB |
372 | this._statistics.addMessage(commandName); |
373 | // Build request | |
374 | this._requests[messageId] = [responseCallback, rejectCallback, command]; | |
375 | messageToSend = JSON.stringify([messageType, messageId, commandName, command]); | |
376 | break; | |
377 | // Response | |
f7869514 | 378 | case Constants.OCPP_JSON_CALL_RESULT_MESSAGE: |
7dde0b73 JB |
379 | // Build response |
380 | messageToSend = JSON.stringify([messageType, messageId, command]); | |
381 | break; | |
382 | // Error Message | |
f7869514 | 383 | case Constants.OCPP_JSON_CALL_ERROR_MESSAGE: |
7dde0b73 | 384 | // Build Message |
894a1780 JB |
385 | this._statistics.addMessage(`Error ${command.code}`); |
386 | messageToSend = JSON.stringify([messageType, messageId, command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR, command.message ? command.message : '', command.details ? command.details : {}]); | |
7dde0b73 JB |
387 | break; |
388 | } | |
2e6f5966 | 389 | // Check if wsConnection is ready |
7dde0b73 JB |
390 | if (this._wsConnection.readyState === WebSocket.OPEN) { |
391 | // Yes: Send Message | |
392 | this._wsConnection.send(messageToSend); | |
393 | } else { | |
394 | // Buffer message until connection is back | |
395 | this._messageQueue.push(messageToSend); | |
396 | } | |
397 | // Request? | |
f7869514 | 398 | if (messageType !== Constants.OCPP_JSON_CALL_MESSAGE) { |
7dde0b73 JB |
399 | // Yes: send Ok |
400 | resolve(); | |
401 | } else if (this._wsConnection.readyState === WebSocket.OPEN) { | |
402 | // Send timeout in case connection is open otherwise wait for ever | |
403 | // FIXME: Handle message on timeout | |
f7869514 | 404 | setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants.OCPP_SOCKET_TIMEOUT); |
7dde0b73 JB |
405 | } |
406 | ||
407 | // Function that will receive the request's response | |
408 | function responseCallback(payload, requestPayload) { | |
409 | self._statistics.addMessage(commandName, true); | |
410 | const responseCallbackFn = 'handleResponse' + commandName; | |
411 | if (typeof self[responseCallbackFn] === 'function') { | |
412 | self[responseCallbackFn](payload, requestPayload, self); | |
413 | } else { | |
2e6f5966 | 414 | logger.debug(self._basicFormatLog() + ' Trying to call an undefined callback function: ' + responseCallbackFn); |
7dde0b73 JB |
415 | } |
416 | // Send the response | |
417 | resolve(payload); | |
418 | } | |
419 | ||
420 | // Function that will receive the request's rejection | |
421 | function rejectCallback(reason) { | |
422 | // Build Exception | |
423 | // eslint-disable-next-line no-empty-function | |
424 | self._requests[messageId] = [() => { }, () => { }, '']; // Properly format the request | |
425 | const error = reason instanceof OCPPError ? reason : new Error(reason); | |
426 | // Send error | |
427 | reject(error); | |
428 | } | |
429 | }); | |
430 | } | |
431 | ||
027b409a | 432 | async _basicStartMessageSequence() { |
7dde0b73 | 433 | this._startHeartbeat(this); |
2e6f5966 JB |
434 | // build connectors |
435 | if (!this._connectors) { | |
7dde0b73 | 436 | this._connectors = {}; |
2e6f5966 | 437 | const connectorsConfig = Utils.cloneJSonDocument(this._stationInfo.Connectors); |
7dde0b73 JB |
438 | // determine number of customized connectors |
439 | let lastConnector; | |
440 | for (lastConnector in connectorsConfig) { | |
2e6f5966 | 441 | // add connector 0, OCPP specification violation that for example KEBA have |
34dcb3b5 | 442 | if (Utils.convertToInt(lastConnector) === 0 && Utils.convertToBoolean(this._stationInfo.useConnectorId0)) { |
7dde0b73 JB |
443 | this._connectors[lastConnector] = connectorsConfig[lastConnector]; |
444 | } | |
445 | } | |
446 | let maxConnectors = 0; | |
447 | if (Array.isArray(this._stationInfo.numberOfConnectors)) { | |
448 | // generate some connectors | |
449 | maxConnectors = this._stationInfo.numberOfConnectors[(this._index - 1) % this._stationInfo.numberOfConnectors.length]; | |
450 | } else { | |
451 | maxConnectors = this._stationInfo.numberOfConnectors; | |
452 | } | |
453 | // generate all connectors | |
454 | for (let index = 1; index <= maxConnectors; index++) { | |
34dcb3b5 | 455 | const randConnectorID = Utils.convertToBoolean(this._stationInfo.randomConnectors) ? Utils.getRandomInt(lastConnector, 1) : index; |
7dde0b73 JB |
456 | this._connectors[index] = connectorsConfig[randConnectorID]; |
457 | } | |
458 | } | |
459 | ||
460 | for (const connector in this._connectors) { | |
461 | if (!this._connectors[connector].transactionStarted) { | |
462 | if (this._connectors[connector].bootStatus) { | |
027b409a | 463 | this.sendStatusNotificationWithTimeout(connector, this._connectors[connector].bootStatus); |
7dde0b73 | 464 | } else { |
027b409a | 465 | this.sendStatusNotificationWithTimeout(connector, 'Available'); |
7dde0b73 JB |
466 | } |
467 | } else { | |
027b409a | 468 | this.sendStatusNotificationWithTimeout(connector, 'Charging'); |
7dde0b73 JB |
469 | } |
470 | } | |
471 | ||
34dcb3b5 | 472 | if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable)) { |
7dde0b73 JB |
473 | if (!this._automaticTransactionGeneration) { |
474 | this._automaticTransactionGeneration = new AutomaticTransactionGenerator(this); | |
475 | } | |
34dcb3b5 JB |
476 | if (this._automaticTransactionGeneration.timeToStop) { |
477 | this._automaticTransactionGeneration.start(); | |
478 | } | |
7dde0b73 JB |
479 | } |
480 | this._statistics.start(); | |
481 | } | |
482 | ||
027b409a JB |
483 | _resetTransactionOnConnector(connectorID) { |
484 | this._connectors[connectorID].transactionStarted = false; | |
485 | this._connectors[connectorID].transactionId = null; | |
486 | this._connectors[connectorID].lastConsumptionValue = -1; | |
487 | this._connectors[connectorID].lastSoC = -1; | |
488 | if (this._connectors[connectorID].transactionInterval) { | |
489 | clearInterval(this._connectors[connectorID].transactionInterval); | |
490 | } | |
491 | } | |
492 | ||
493 | handleResponseBootNotification(payload) { | |
494 | if (payload.status === 'Accepted') { | |
495 | this._heartbeatInterval = payload.interval * 1000; | |
496 | this._basicStartMessageSequence(); | |
497 | } else { | |
498 | logger.info(this._basicFormatLog() + ' Boot Notification rejected'); | |
499 | } | |
500 | } | |
501 | ||
7dde0b73 | 502 | handleResponseStartTransaction(payload, requestPayload) { |
34dcb3b5 | 503 | // Set connector transaction related attributes |
84393381 JB |
504 | this._connectors[requestPayload.connectorId].transactionStarted = false; |
505 | this._connectors[requestPayload.connectorId].idTag = requestPayload.idTag; | |
506 | ||
7dde0b73 JB |
507 | if (payload.idTagInfo.status === 'Accepted') { |
508 | for (const connector in this._connectors) { | |
def3d48e | 509 | if (Utils.convertToInt(connector) === Utils.convertToInt(requestPayload.connectorId)) { |
7dde0b73 JB |
510 | this._connectors[connector].transactionStarted = true; |
511 | this._connectors[connector].transactionId = payload.transactionId; | |
512 | this._connectors[connector].lastConsumptionValue = 0; | |
513 | this._connectors[connector].lastSoC = 0; | |
027b409a | 514 | logger.info(this._basicFormatLog() + ' Transaction ' + this._connectors[connector].transactionId + ' STARTED on ' + this._stationInfo.name + '#' + requestPayload.connectorId + ' for idTag ' + requestPayload.idTag); |
7dde0b73 | 515 | this.sendStatusNotification(requestPayload.connectorId, 'Charging'); |
a6e68f34 | 516 | const configuredMeterValueSampleInterval = this._configuration.configurationKey.find((value) => value.key === 'MeterValueSampleInterval'); |
7dde0b73 | 517 | this.startMeterValues(requestPayload.connectorId, |
72766a82 JB |
518 | configuredMeterValueSampleInterval ? configuredMeterValueSampleInterval.value * 1000 : 60000, |
519 | this); | |
7dde0b73 JB |
520 | } |
521 | } | |
522 | } else { | |
523 | logger.error(this._basicFormatLog() + ' Starting transaction id ' + payload.transactionId + ' REJECTED with status ' + payload.idTagInfo.status + ', idTag ' + requestPayload.idTag); | |
524 | for (const connector in this._connectors) { | |
def3d48e | 525 | if (Utils.convertToInt(connector) === Utils.convertToInt(requestPayload.connectorId)) { |
7dde0b73 JB |
526 | this._resetTransactionOnConnector(connector); |
527 | } | |
528 | } | |
529 | this.sendStatusNotification(requestPayload.connectorId, 'Available'); | |
530 | } | |
531 | } | |
532 | ||
34dcb3b5 JB |
533 | handleResponseStopTransaction(payload, requestPayload) { |
534 | if (payload.idTagInfo && payload.idTagInfo.status) { | |
facd8ebd | 535 | logger.debug(this._basicFormatLog() + ' Stop transaction ' + requestPayload.transactionId + ' response status: ' + payload.idTagInfo.status); |
34dcb3b5 JB |
536 | } else { |
537 | logger.debug(this._basicFormatLog() + ' Stop transaction ' + requestPayload.transactionId + ' response status: Unknown'); | |
538 | } | |
539 | } | |
540 | ||
facd8ebd JB |
541 | handleResponseStatusNotification(payload, requestPayload) { |
542 | logger.debug(this._basicFormatLog() + ' Status notification response received: %j to status notification request: %j', payload, requestPayload); | |
7dde0b73 JB |
543 | } |
544 | ||
facd8ebd JB |
545 | handleResponseMeterValues(payload, requestPayload) { |
546 | logger.debug(this._basicFormatLog() + ' MeterValues response received: %j to MeterValues request: %j', payload, requestPayload); | |
027b409a JB |
547 | } |
548 | ||
facd8ebd JB |
549 | handleResponseHeartbeat(payload, requestPayload) { |
550 | logger.debug(this._basicFormatLog() + ' Heartbeat response received: %j to Heartbeat request: %j', payload, requestPayload); | |
7dde0b73 JB |
551 | } |
552 | ||
553 | async handleRequest(messageId, commandName, commandPayload) { | |
554 | let result; | |
555 | this._statistics.addMessage(commandName, true); | |
556 | // Call | |
557 | if (typeof this['handle' + commandName] === 'function') { | |
558 | try { | |
559 | // Call the method | |
560 | result = await this['handle' + commandName](commandPayload); | |
561 | } catch (error) { | |
562 | // Log | |
563 | logger.error(this._basicFormatLog() + ' Handle request error: ' + error); | |
facd8ebd | 564 | // Send back response to inform backend |
7dde0b73 JB |
565 | await this.sendError(messageId, error); |
566 | } | |
567 | } else { | |
84393381 | 568 | // Throw exception |
f7869514 | 569 | await this.sendError(messageId, new OCPPError(Constants.OCPP_ERROR_NOT_IMPLEMENTED, 'Not implemented', {})); |
7dde0b73 JB |
570 | throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`); |
571 | } | |
84393381 | 572 | // Send response |
f7869514 | 573 | await this.sendMessage(messageId, result, Constants.OCPP_JSON_CALL_RESULT_MESSAGE); |
7dde0b73 JB |
574 | } |
575 | ||
34dcb3b5 | 576 | async handleGetConfiguration(commandPayload) { |
facd8ebd JB |
577 | const configurationKey = []; |
578 | const unknownKey = []; | |
579 | for (const configuration of this._configuration.configurationKey) { | |
580 | if (Utils.isUndefined(configuration.visible)) { | |
581 | configuration.visible = true; | |
582 | } else { | |
583 | configuration.visible = Utils.convertToBoolean(configuration.visible); | |
584 | } | |
585 | if (!configuration.visible) { | |
586 | continue; | |
587 | } | |
588 | configurationKey.push({ | |
589 | key: configuration.key, | |
590 | readonly: configuration.readonly, | |
591 | value: configuration.value, | |
592 | }); | |
593 | } | |
594 | return { | |
595 | configurationKey, | |
596 | unknownKey, | |
597 | }; | |
7dde0b73 JB |
598 | } |
599 | ||
600 | async handleChangeConfiguration(commandPayload) { | |
601 | const keyToChange = this._configuration.configurationKey.find((element) => element.key === commandPayload.key); | |
a6e68f34 JB |
602 | if (keyToChange && !Utils.convertToBoolean(keyToChange.readonly)) { |
603 | const keyIndex = this._configuration.configurationKey.indexOf(keyToChange); | |
604 | this._configuration.configurationKey[keyIndex].value = commandPayload.value; | |
dcab13bd | 605 | return Constants.OCPP_RESPONSE_ACCEPTED; |
7dde0b73 | 606 | } |
dcab13bd | 607 | return Constants.OCPP_RESPONSE_REJECTED; |
7dde0b73 JB |
608 | } |
609 | ||
610 | async handleRemoteStartTransaction(commandPayload) { | |
72766a82 | 611 | const transactionConnectorID = commandPayload.connectorId ? commandPayload.connectorId : '1'; |
2e6f5966 | 612 | if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) { |
dcab13bd | 613 | // Check if authorized |
2e6f5966 | 614 | if (this._authorizedTags.find((value) => value === commandPayload.idTag)) { |
7dde0b73 | 615 | // Authorization successful start transaction |
2e6f5966 | 616 | setTimeout(() => this.sendStartTransaction(transactionConnectorID, commandPayload.idTag), Constants.START_TRANSACTION_TIMEOUT); |
027b409a | 617 | logger.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag); |
dcab13bd | 618 | return Constants.OCPP_RESPONSE_ACCEPTED; |
7dde0b73 | 619 | } |
84393381 | 620 | logger.error(this._basicFormatLog() + ' Remote starting transaction REJECTED with status ' + commandPayload.idTagInfo.status + ', idTag ' + commandPayload.idTag); |
dcab13bd | 621 | return Constants.OCPP_RESPONSE_REJECTED; |
7dde0b73 | 622 | } |
dcab13bd | 623 | // No local authorization check required => start transaction |
2e6f5966 | 624 | setTimeout(() => this.sendStartTransaction(transactionConnectorID, commandPayload.idTag), Constants.START_TRANSACTION_TIMEOUT); |
027b409a JB |
625 | logger.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag); |
626 | return Constants.OCPP_RESPONSE_ACCEPTED; | |
627 | } | |
628 | ||
629 | async handleRemoteStopTransaction(commandPayload) { | |
630 | for (const connector in this._connectors) { | |
631 | if (this._connectors[connector].transactionId === commandPayload.transactionId) { | |
632 | this.sendStopTransaction(commandPayload.transactionId, connector); | |
633 | } | |
634 | } | |
dcab13bd | 635 | return Constants.OCPP_RESPONSE_ACCEPTED; |
7dde0b73 JB |
636 | } |
637 | ||
638 | async sendStartTransaction(connectorID, idTag) { | |
639 | try { | |
640 | const payload = { | |
641 | connectorId: connectorID, | |
642 | idTag, | |
643 | meterStart: 0, | |
644 | timestamp: new Date().toISOString(), | |
645 | }; | |
027b409a | 646 | return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StartTransaction'); |
7dde0b73 JB |
647 | } catch (error) { |
648 | logger.error(this._basicFormatLog() + ' Send start transaction error: ' + error); | |
649 | this._resetTransactionOnConnector(connectorID); | |
650 | throw error; | |
651 | } | |
652 | } | |
653 | ||
654 | async sendStopTransaction(transactionId, connectorID) { | |
655 | try { | |
656 | const payload = { | |
657 | transactionId, | |
658 | meterStop: 0, | |
659 | timestamp: new Date().toISOString(), | |
660 | }; | |
027b409a | 661 | await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StopTransaction'); |
7dde0b73 JB |
662 | logger.info(this._basicFormatLog() + ' Transaction ' + this._connectors[connectorID].transactionId + ' STOPPED on ' + this._stationInfo.name + '#' + connectorID); |
663 | this.sendStatusNotification(connectorID, 'Available'); | |
664 | } catch (error) { | |
665 | logger.error(this._basicFormatLog() + ' Send stop transaction error: ' + error); | |
666 | throw error; | |
667 | } finally { | |
668 | this._resetTransactionOnConnector(connectorID); | |
669 | } | |
670 | } | |
671 | ||
7dde0b73 JB |
672 | // eslint-disable-next-line class-methods-use-this |
673 | async sendMeterValues(connectorID, interval, self) { | |
674 | try { | |
675 | const sampledValueLcl = { | |
676 | timestamp: new Date().toISOString(), | |
677 | }; | |
2e6f5966 | 678 | const meterValuesClone = Utils.cloneJSonDocument(self._getConnector(connectorID).MeterValues); |
7dde0b73 JB |
679 | if (Array.isArray(meterValuesClone)) { |
680 | sampledValueLcl.sampledValue = meterValuesClone; | |
681 | } else { | |
682 | sampledValueLcl.sampledValue = [meterValuesClone]; | |
683 | } | |
684 | for (let index = 0; index < sampledValueLcl.sampledValue.length; index++) { | |
685 | if (sampledValueLcl.sampledValue[index].measurand && sampledValueLcl.sampledValue[index].measurand === 'SoC') { | |
686 | sampledValueLcl.sampledValue[index].value = Math.floor(Math.random() * 100) + 1; | |
687 | if (sampledValueLcl.sampledValue[index].value > 100) { | |
34dcb3b5 | 688 | logger.info(self._basicFormatLog() + ' MeterValues measurand: ' + |
72766a82 | 689 | sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register' + |
027b409a | 690 | ', value: ' + sampledValueLcl.sampledValue[index].value); |
7dde0b73 JB |
691 | } |
692 | } else { | |
693 | // Persist previous value in connector | |
694 | const connector = self._connectors[connectorID]; | |
695 | let consumption; | |
a6e68f34 | 696 | consumption = Utils.getRandomInt(self._stationInfo.maxPower / 3600000 * interval, 4); |
7dde0b73 JB |
697 | if (connector && connector.lastConsumptionValue >= 0) { |
698 | connector.lastConsumptionValue += consumption; | |
699 | } else { | |
700 | connector.lastConsumptionValue = 0; | |
701 | } | |
702 | consumption = Math.round(connector.lastConsumptionValue * 3600 / interval); | |
34dcb3b5 | 703 | logger.info(self._basicFormatLog() + ' MeterValues: connectorID ' + connectorID + ', transaction ' + connector.transactionId + ', value ' + connector.lastConsumptionValue); |
7dde0b73 JB |
704 | sampledValueLcl.sampledValue[index].value = connector.lastConsumptionValue; |
705 | if (sampledValueLcl.sampledValue[index].value > (self._stationInfo.maxPower * 3600 / interval) || sampledValueLcl.sampledValue[index].value < 500) { | |
34dcb3b5 | 706 | logger.info(self._basicFormatLog() + ' MeterValues measurand: ' + |
72766a82 | 707 | sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register' + |
027b409a | 708 | ', value: ' + sampledValueLcl.sampledValue[index].value + '/' + (self._stationInfo.maxPower * 3600 / interval)); |
7dde0b73 JB |
709 | } |
710 | } | |
711 | } | |
712 | ||
713 | const payload = { | |
714 | connectorId: connectorID, | |
715 | transactionId: self._connectors[connectorID].transactionId, | |
716 | meterValue: [sampledValueLcl], | |
717 | }; | |
027b409a | 718 | await self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'MeterValues'); |
7dde0b73 | 719 | } catch (error) { |
34dcb3b5 | 720 | logger.error(self._basicFormatLog() + ' Send MeterValues error: ' + error); |
7dde0b73 JB |
721 | } |
722 | } | |
723 | ||
724 | async startMeterValues(connectorID, interval, self) { | |
84393381 | 725 | if (!this._connectors[connectorID].transactionStarted) { |
34dcb3b5 | 726 | logger.debug(`${self._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction started`); |
84393381 | 727 | } else if (this._connectors[connectorID].transactionStarted && !this._connectors[connectorID].transactionId) { |
34dcb3b5 | 728 | logger.debug(`${self._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction id`); |
84393381 | 729 | } |
7dde0b73 JB |
730 | this._connectors[connectorID].transactionInterval = setInterval(async () => { |
731 | const sendMeterValues = performance.timerify(this.sendMeterValues); | |
732 | this._performanceObserver.observe({ | |
733 | entryTypes: ['function'], | |
734 | }); | |
735 | await sendMeterValues(connectorID, interval, self); | |
736 | }, interval); | |
737 | } | |
738 | ||
2e6f5966 JB |
739 | hasAuthorizedTags() { |
740 | return Array.isArray(this._authorizedTags) && this._authorizedTags.length > 0; | |
7dde0b73 JB |
741 | } |
742 | ||
743 | getRandomTagId() { | |
2e6f5966 JB |
744 | const index = Math.round(Math.floor(Math.random() * this._authorizedTags.length - 1)); |
745 | return this._authorizedTags[index]; | |
7dde0b73 JB |
746 | } |
747 | ||
748 | _getConnector(number) { | |
749 | return this._stationInfo.Connectors[number]; | |
750 | } | |
751 | } | |
752 | ||
753 | module.exports = ChargingStation; |