1 import { AuthorizationStatus
, StartTransactionRequest
, StartTransactionResponse
, StopTransactionReason
, StopTransactionRequest
, StopTransactionResponse
} from
'../types/ocpp/1.6/Transaction';
2 import { BootNotificationResponse
, ChangeConfigurationResponse
, DefaultResponse
, GetConfigurationResponse
, HeartbeatResponse
, RegistrationStatus
, SetChargingProfileResponse
, StatusNotificationResponse
, UnlockConnectorResponse
} from
'../types/ocpp/1.6/RequestResponses';
3 import { ChargingProfile
, ChargingProfilePurposeType
} from
'../types/ocpp/1.6/ChargingProfile';
4 import ChargingStationConfiguration
, { ConfigurationKey
} from
'../types/ChargingStationConfiguration';
5 import ChargingStationTemplate
, { PowerOutType
} from
'../types/ChargingStationTemplate';
6 import Connectors
, { Connector
} from
'../types/Connectors';
7 import { MeterValue
, MeterValueLocation
, MeterValueMeasurand
, MeterValuePhase
, MeterValueUnit
, MeterValuesRequest
, MeterValuesResponse
, SampledValue
} from
'../types/ocpp/1.6/MeterValues';
8 import { PerformanceObserver
, performance
} from
'perf_hooks';
9 import Requests
, { BootNotificationRequest
, ChangeConfigurationRequest
, GetConfigurationRequest
, HeartbeatRequest
, RemoteStartTransactionRequest
, RemoteStopTransactionRequest
, ResetRequest
, SetChargingProfileRequest
, StatusNotificationRequest
, UnlockConnectorRequest
} from
'../types/ocpp/1.6/Requests';
10 import WebSocket
, { MessageEvent
} from
'ws';
12 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
13 import { ChargePointErrorCode
} from
'../types/ocpp/1.6/ChargePointErrorCode';
14 import { ChargePointStatus
} from
'../types/ocpp/1.6/ChargePointStatus';
15 import ChargingStationInfo from
'../types/ChargingStationInfo';
16 import Configuration from
'../utils/Configuration';
17 import Constants from
'../utils/Constants';
18 import ElectricUtils from
'../utils/ElectricUtils';
19 import MeasurandValues from
'../types/MeasurandValues';
20 import OCPPError from
'./OcppError';
21 import Statistics from
'../utils/Statistics';
22 import Utils from
'../utils/Utils';
23 import crypto from
'crypto';
25 import logger from
'../utils/Logger';
27 export default class ChargingStation
{
28 private _index
: number;
29 private _stationTemplateFile
: string;
30 private _stationInfo
: ChargingStationInfo
;
31 private _bootNotificationRequest
: BootNotificationRequest
;
32 private _bootNotificationResponse
: BootNotificationResponse
;
33 private _connectors
: Connectors
;
34 private _configuration
: ChargingStationConfiguration
;
35 private _connectorsConfigurationHash
: string;
36 private _supervisionUrl
: string;
37 private _wsConnectionUrl
: string;
38 private _wsConnection
: WebSocket
;
39 private _hasStopped
: boolean;
40 private _hasSocketRestarted
: boolean;
41 private _connectionTimeout
: number;
42 private _autoReconnectRetryCount
: number;
43 private _autoReconnectMaxRetries
: number;
44 private _requests
: Requests
;
45 private _messageQueue
: string[];
46 private _automaticTransactionGeneration
: AutomaticTransactionGenerator
;
47 private _authorizedTags
: string[];
48 private _heartbeatInterval
: number;
49 private _heartbeatSetInterval
: NodeJS
.Timeout
;
50 private _webSocketPingSetInterval
: NodeJS
.Timeout
;
51 private _statistics
: Statistics
;
52 private _performanceObserver
: PerformanceObserver
;
54 constructor(index
: number, stationTemplateFile
: string) {
56 this._stationTemplateFile
= stationTemplateFile
;
57 this._connectors
= {} as Connectors
;
60 this._hasStopped
= false;
61 this._hasSocketRestarted
= false;
62 this._autoReconnectRetryCount
= 0;
64 this._requests
= {} as Requests
;
65 this._messageQueue
= [] as string[];
67 this._authorizedTags
= this._loadAndGetAuthorizedTags();
70 _getStationName(stationTemplate
: ChargingStationTemplate
): string {
71 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + ('000000000' + this._index
.toString()).substr(('000000000' + this._index
.toString()).length
- 4);
74 _buildStationInfo(): ChargingStationInfo
{
75 let stationTemplateFromFile
: ChargingStationTemplate
;
78 const fileDescriptor
= fs
.openSync(this._stationTemplateFile
, 'r');
79 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as ChargingStationTemplate
;
80 fs
.closeSync(fileDescriptor
);
82 logger
.error('Template file ' + this._stationTemplateFile
+ ' loading error: %j', error
);
85 const stationInfo
: ChargingStationInfo
= stationTemplateFromFile
|| {} as ChargingStationInfo
;
86 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
87 stationTemplateFromFile
.power
= stationTemplateFromFile
.power
as number[];
88 stationInfo
.maxPower
= stationTemplateFromFile
.power
[Math.floor(Math.random() * stationTemplateFromFile
.power
.length
)];
90 stationInfo
.maxPower
= stationTemplateFromFile
.power
as number;
92 stationInfo
.name
= this._getStationName(stationTemplateFromFile
);
93 stationInfo
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
97 get
stationInfo(): ChargingStationInfo
{
98 return this._stationInfo
;
101 _initialize(): void {
102 this._stationInfo
= this._buildStationInfo();
103 this._bootNotificationRequest
= {
104 chargePointModel
: this._stationInfo
.chargePointModel
,
105 chargePointVendor
: this._stationInfo
.chargePointVendor
,
106 ...!Utils
.isUndefined(this._stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this._stationInfo
.chargeBoxSerialNumberPrefix
},
107 ...!Utils
.isUndefined(this._stationInfo
.firmwareVersion
) && { firmwareVersion
: this._stationInfo
.firmwareVersion
},
109 this._configuration
= this._getTemplateChargingStationConfiguration();
110 this._supervisionUrl
= this._getSupervisionURL();
111 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
112 this._connectionTimeout
= this._getConnectionTimeout() * 1000; // Ms, zero for disabling
113 this._autoReconnectMaxRetries
= this._getAutoReconnectMaxRetries(); // -1 for unlimited
114 // Build connectors if needed
115 const maxConnectors
= this._getMaxNumberOfConnectors();
116 if (maxConnectors
<= 0) {
117 logger
.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with ${maxConnectors} connectors`);
119 const templateMaxConnectors
= this._getTemplateMaxNumberOfConnectors();
120 if (templateMaxConnectors
<= 0) {
121 logger
.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with no connector configuration`);
123 if (!this._stationInfo
.Connectors
[0]) {
124 logger
.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with no connector Id 0 configuration`);
127 if (maxConnectors
> (this._stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !this._stationInfo
.randomConnectors
) {
128 logger
.warn(`${this._logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this._stationTemplateFile}, forcing random connector configurations affectation`);
129 this._stationInfo
.randomConnectors
= true;
131 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this._stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
132 // FIXME: Handle shrinking the number of connectors
133 if (!this._connectors
|| (this._connectors
&& this._connectorsConfigurationHash
!== connectorsConfigHash
)) {
134 this._connectorsConfigurationHash
= connectorsConfigHash
;
135 // Add connector Id 0
136 let lastConnector
= '0';
137 for (lastConnector
in this._stationInfo
.Connectors
) {
138 if (Utils
.convertToInt(lastConnector
) === 0 && this._getUseConnectorId0() && this._stationInfo
.Connectors
[lastConnector
]) {
139 this._connectors
[lastConnector
] = Utils
.cloneObject(this._stationInfo
.Connectors
[lastConnector
]) as Connector
;
142 // Generate all connectors
143 if ((this._stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
144 for (let index
= 1; index
<= maxConnectors
; index
++) {
145 const randConnectorID
= this._stationInfo
.randomConnectors
? Utils
.getRandomInt(Utils
.convertToInt(lastConnector
), 1) : index
;
146 this._connectors
[index
] = Utils
.cloneObject(this._stationInfo
.Connectors
[randConnectorID
]) as Connector
;
150 // Avoid duplication of connectors related information
151 delete this._stationInfo
.Connectors
;
152 // Initialize transaction attributes on connectors
153 for (const connector
in this._connectors
) {
154 if (Utils
.convertToInt(connector
) > 0 && !this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
155 this._initTransactionOnConnector(Utils
.convertToInt(connector
));
159 this._addConfigurationKey('NumberOfConnectors', this._getNumberOfConnectors().toString(), true);
160 if (!this._getConfigurationKey('MeterValuesSampledData')) {
161 this._addConfigurationKey('MeterValuesSampledData', MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
);
163 this._stationInfo
.powerDivider
= this._getPowerDivider();
164 if (this.getEnableStatistics()) {
165 this._statistics
= Statistics
.getInstance();
166 this._statistics
.objName
= this._stationInfo
.name
;
167 this._performanceObserver
= new PerformanceObserver((list
) => {
168 const entry
= list
.getEntries()[0];
169 this._statistics
.logPerformance(entry
, Constants
.ENTITY_CHARGING_STATION
);
170 this._performanceObserver
.disconnect();
175 get
connectors(): Connectors
{
176 return this._connectors
;
179 get
statistics(): Statistics
{
180 return this._statistics
;
183 _logPrefix(): string {
184 return Utils
.logPrefix(` ${this._stationInfo.name}:`);
187 _getTemplateChargingStationConfiguration(): ChargingStationConfiguration
{
188 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {} as ChargingStationConfiguration
;
191 _getAuthorizationFile(): string {
192 return this._stationInfo
.authorizationFile
&& this._stationInfo
.authorizationFile
;
195 _getUseConnectorId0(): boolean {
196 return !Utils
.isUndefined(this._stationInfo
.useConnectorId0
) ? this._stationInfo
.useConnectorId0
: true;
199 _loadAndGetAuthorizedTags(): string[] {
200 let authorizedTags
: string[] = [];
201 const authorizationFile
= this._getAuthorizationFile();
202 if (authorizationFile
) {
204 // Load authorization file
205 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
206 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8')) as string[];
207 fs
.closeSync(fileDescriptor
);
209 logger
.error(this._logPrefix() + ' Authorization file ' + authorizationFile
+ ' loading error: %j', error
);
213 logger
.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile
);
215 return authorizedTags
;
218 getRandomTagId(): string {
219 const index
= Math.floor(Math.random() * this._authorizedTags
.length
);
220 return this._authorizedTags
[index
];
223 hasAuthorizedTags(): boolean {
224 return !Utils
.isEmptyArray(this._authorizedTags
);
227 getEnableStatistics(): boolean {
228 return !Utils
.isUndefined(this._stationInfo
.enableStatistics
) ? this._stationInfo
.enableStatistics
: true;
231 _getNumberOfPhases(): number {
232 switch (this._getPowerOutType()) {
233 case PowerOutType
.AC
:
234 return !Utils
.isUndefined(this._stationInfo
.numberOfPhases
) ? Utils
.convertToInt(this._stationInfo
.numberOfPhases
) : 3;
235 case PowerOutType
.DC
:
240 _getNumberOfRunningTransactions(): number {
242 for (const connector
in this._connectors
) {
243 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
250 _getConnectionTimeout(): number {
251 if (!Utils
.isUndefined(this._stationInfo
.connectionTimeout
)) {
252 return this._stationInfo
.connectionTimeout
;
254 if (!Utils
.isUndefined(Configuration
.getConnectionTimeout())) {
255 return Configuration
.getConnectionTimeout();
260 _getAutoReconnectMaxRetries(): number {
261 if (!Utils
.isUndefined(this._stationInfo
.autoReconnectMaxRetries
)) {
262 return this._stationInfo
.autoReconnectMaxRetries
;
264 if (!Utils
.isUndefined(Configuration
.getAutoReconnectMaxRetries())) {
265 return Configuration
.getAutoReconnectMaxRetries();
270 _getPowerDivider(): number {
271 let powerDivider
= this._getNumberOfConnectors();
272 if (this._stationInfo
.powerSharedByConnectors
) {
273 powerDivider
= this._getNumberOfRunningTransactions();
278 getConnector(id
: number): Connector
{
279 return this._connectors
[id
];
282 _getTemplateMaxNumberOfConnectors(): number {
283 return Object.keys(this._stationInfo
.Connectors
).length
;
286 _getMaxNumberOfConnectors(): number {
287 let maxConnectors
= 0;
288 if (!Utils
.isEmptyArray(this._stationInfo
.numberOfConnectors
)) {
289 const numberOfConnectors
= this._stationInfo
.numberOfConnectors
as number[];
290 // Distribute evenly the number of connectors
291 maxConnectors
= numberOfConnectors
[(this._index
- 1) % numberOfConnectors
.length
];
292 } else if (!Utils
.isUndefined(this._stationInfo
.numberOfConnectors
)) {
293 maxConnectors
= this._stationInfo
.numberOfConnectors
as number;
295 maxConnectors
= this._stationInfo
.Connectors
[0] ? this._getTemplateMaxNumberOfConnectors() - 1 : this._getTemplateMaxNumberOfConnectors();
297 return maxConnectors
;
300 _getNumberOfConnectors(): number {
301 return this._connectors
[0] ? Object.keys(this._connectors
).length
- 1 : Object.keys(this._connectors
).length
;
304 _getVoltageOut(): number {
305 const errMsg
= `${this._logPrefix()} Unknown ${this._getPowerOutType()} powerOutType in template file ${this._stationTemplateFile}, cannot define default voltage out`;
306 let defaultVoltageOut
: number;
307 switch (this._getPowerOutType()) {
308 case PowerOutType
.AC
:
309 defaultVoltageOut
= 230;
311 case PowerOutType
.DC
:
312 defaultVoltageOut
= 400;
315 logger
.error(errMsg
);
318 return !Utils
.isUndefined(this._stationInfo
.voltageOut
) ? Utils
.convertToInt(this._stationInfo
.voltageOut
) : defaultVoltageOut
;
321 _getTransactionIdTag(transactionId
: number): string {
322 for (const connector
in this._connectors
) {
323 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
324 return this.getConnector(Utils
.convertToInt(connector
)).idTag
;
329 _getTransactionMeterStop(transactionId
: number): number {
330 for (const connector
in this._connectors
) {
331 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
332 return this.getConnector(Utils
.convertToInt(connector
)).lastEnergyActiveImportRegisterValue
;
337 _getPowerOutType(): PowerOutType
{
338 return !Utils
.isUndefined(this._stationInfo
.powerOutType
) ? this._stationInfo
.powerOutType
: PowerOutType
.AC
;
341 _getSupervisionURL(): string {
342 const supervisionUrls
= Utils
.cloneObject(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs()) as string | string[];
344 if (!Utils
.isEmptyArray(supervisionUrls
)) {
345 if (Configuration
.getDistributeStationsToTenantsEqually()) {
346 indexUrl
= this._index
% supervisionUrls
.length
;
349 indexUrl
= Math.floor(Math.random() * supervisionUrls
.length
);
351 return supervisionUrls
[indexUrl
];
353 return supervisionUrls
as string;
356 _getReconnectExponentialDelay(): boolean {
357 return !Utils
.isUndefined(this._stationInfo
.reconnectExponentialDelay
) ? this._stationInfo
.reconnectExponentialDelay
: false;
360 _getAuthorizeRemoteTxRequests(): boolean {
361 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
362 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
365 _getLocalAuthListEnabled(): boolean {
366 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
367 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
370 async _startMessageSequence(): Promise
<void> {
371 // Start WebSocket ping
372 this._startWebSocketPing();
374 this._startHeartbeat();
375 // Initialize connectors status
376 for (const connector
in this._connectors
) {
377 if (Utils
.convertToInt(connector
) === 0) {
379 } else if (!this._hasStopped
&& !this.getConnector(Utils
.convertToInt(connector
)).status && this.getConnector(Utils
.convertToInt(connector
)).bootStatus
) {
380 // Send status in template at startup
381 await this.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
382 } else if (this._hasStopped
&& this.getConnector(Utils
.convertToInt(connector
)).bootStatus
) {
383 // Send status in template after reset
384 await this.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
385 } else if (!this._hasStopped
&& this.getConnector(Utils
.convertToInt(connector
)).status) {
386 // Send previous status at template reload
387 await this.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).status);
389 // Send default status
390 await this.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.AVAILABLE
);
394 if (this._stationInfo
.AutomaticTransactionGenerator
.enable
) {
395 if (!this._automaticTransactionGeneration
) {
396 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
398 if (this._automaticTransactionGeneration
.timeToStop
) {
399 this._automaticTransactionGeneration
.start();
402 if (this.getEnableStatistics()) {
403 this._statistics
.start();
407 async _stopMessageSequence(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
408 // Stop WebSocket ping
409 this._stopWebSocketPing();
411 this._stopHeartbeat();
413 if (this._stationInfo
.AutomaticTransactionGenerator
.enable
&&
414 this._automaticTransactionGeneration
&&
415 !this._automaticTransactionGeneration
.timeToStop
) {
416 await this._automaticTransactionGeneration
.stop(reason
);
418 for (const connector
in this._connectors
) {
419 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
420 await this.sendStopTransaction(this.getConnector(Utils
.convertToInt(connector
)).transactionId
, reason
);
426 _startWebSocketPing(): void {
427 const webSocketPingInterval
: number = this._getConfigurationKey('WebSocketPingInterval') ? Utils
.convertToInt(this._getConfigurationKey('WebSocketPingInterval').value
) : 0;
428 if (webSocketPingInterval
> 0 && !this._webSocketPingSetInterval
) {
429 this._webSocketPingSetInterval
= setInterval(() => {
430 if (this._wsConnection
?.readyState
=== WebSocket
.OPEN
) {
431 this._wsConnection
.ping((): void => { });
433 }, webSocketPingInterval
* 1000);
434 logger
.info(this._logPrefix() + ' WebSocket ping started every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
));
435 } else if (this._webSocketPingSetInterval
) {
436 logger
.info(this._logPrefix() + ' WebSocket ping every ' + Utils
.secondsToHHMMSS(webSocketPingInterval
) + ' already started');
438 logger
.error(`${this._logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
442 _stopWebSocketPing(): void {
443 if (this._webSocketPingSetInterval
) {
444 clearInterval(this._webSocketPingSetInterval
);
445 this._webSocketPingSetInterval
= null;
449 _restartWebSocketPing(): void {
450 // Stop WebSocket ping
451 this._stopWebSocketPing();
452 // Start WebSocket ping
453 this._startWebSocketPing();
456 _startHeartbeat(): void {
457 if (this._heartbeatInterval
&& this._heartbeatInterval
> 0 && !this._heartbeatSetInterval
) {
458 this._heartbeatSetInterval
= setInterval(async () => {
459 await this.sendHeartbeat();
460 }, this._heartbeatInterval
);
461 logger
.info(this._logPrefix() + ' Heartbeat started every ' + Utils
.milliSecondsToHHMMSS(this._heartbeatInterval
));
462 } else if (this._heartbeatSetInterval
) {
463 logger
.info(this._logPrefix() + ' Heartbeat every ' + Utils
.milliSecondsToHHMMSS(this._heartbeatInterval
) + ' already started');
465 logger
.error(`${this._logPrefix()} Heartbeat interval set to ${this._heartbeatInterval ? Utils.milliSecondsToHHMMSS(this._heartbeatInterval) : this._heartbeatInterval}, not starting the heartbeat`);
469 _stopHeartbeat(): void {
470 if (this._heartbeatSetInterval
) {
471 clearInterval(this._heartbeatSetInterval
);
472 this._heartbeatSetInterval
= null;
476 _restartHeartbeat(): void {
478 this._stopHeartbeat();
480 this._startHeartbeat();
483 _startAuthorizationFileMonitoring(): void {
484 // eslint-disable-next-line @typescript-eslint/no-unused-vars
485 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
487 logger
.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
488 // Initialize _authorizedTags
489 this._authorizedTags
= this._loadAndGetAuthorizedTags();
491 logger
.error(this._logPrefix() + ' Authorization file monitoring error: %j', error
);
496 _startStationTemplateFileMonitoring(): void {
497 // eslint-disable-next-line @typescript-eslint/no-unused-vars
498 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
500 logger
.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
503 if (!this._stationInfo
.AutomaticTransactionGenerator
.enable
&&
504 this._automaticTransactionGeneration
) {
505 this._automaticTransactionGeneration
.stop().catch(() => { });
507 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
509 logger
.error(this._logPrefix() + ' Charging station template file monitoring error: %j', error
);
514 _startMeterValues(connectorId
: number, interval
: number): void {
515 if (!this.getConnector(connectorId
).transactionStarted
) {
516 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
518 } else if (this.getConnector(connectorId
).transactionStarted
&& !this.getConnector(connectorId
).transactionId
) {
519 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
523 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async () => {
524 if (this.getEnableStatistics()) {
525 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
526 this._performanceObserver
.observe({
527 entryTypes
: ['function'],
529 await sendMeterValues(connectorId
, interval
, this);
531 await this.sendMeterValues(connectorId
, interval
, this);
535 logger
.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${Utils.milliSecondsToHHMMSS(interval)}, not sending MeterValues`);
539 _openWSConnection(options
?: WebSocket
.ClientOptions
): void {
540 if (Utils
.isUndefined(options
)) {
541 options
= {} as WebSocket
.ClientOptions
;
543 if (Utils
.isUndefined(options
.handshakeTimeout
)) {
544 options
.handshakeTimeout
= this._connectionTimeout
;
546 this._wsConnection
= new WebSocket(this._wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
, options
);
547 logger
.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl
);
551 this._openWSConnection();
552 // Monitor authorization file
553 this._startAuthorizationFileMonitoring();
554 // Monitor station template file
555 this._startStationTemplateFileMonitoring();
556 // Handle Socket incoming messages
557 this._wsConnection
.on('message', this.onMessage
.bind(this));
558 // Handle Socket error
559 this._wsConnection
.on('error', this.onError
.bind(this));
560 // Handle Socket close
561 this._wsConnection
.on('close', this.onClose
.bind(this));
562 // Handle Socket opening connection
563 this._wsConnection
.on('open', this.onOpen
.bind(this));
564 // Handle Socket ping
565 this._wsConnection
.on('ping', this.onPing
.bind(this));
566 // Handle Socket pong
567 this._wsConnection
.on('pong', this.onPong
.bind(this));
570 async stop(reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<void> {
571 // Stop message sequence
572 await this._stopMessageSequence(reason
);
573 for (const connector
in this._connectors
) {
574 if (Utils
.convertToInt(connector
) > 0) {
575 await this.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.UNAVAILABLE
);
578 if (this._wsConnection
?.readyState
=== WebSocket
.OPEN
) {
579 this._wsConnection
.close();
581 this._bootNotificationResponse
= null;
582 this._hasStopped
= true;
585 async _reconnect(error
): Promise
<void> {
586 logger
.error(this._logPrefix() + ' Socket: abnormally closed: %j', error
);
588 this._stopHeartbeat();
589 // Stop the ATG if needed
590 if (this._stationInfo
.AutomaticTransactionGenerator
.enable
&&
591 this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
&&
592 this._automaticTransactionGeneration
&&
593 !this._automaticTransactionGeneration
.timeToStop
) {
594 this._automaticTransactionGeneration
.stop().catch(() => { });
596 if (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1) {
597 this._autoReconnectRetryCount
++;
598 const reconnectDelay
= (this._getReconnectExponentialDelay() ? Utils
.exponentialDelay(this._autoReconnectRetryCount
) : this._connectionTimeout
);
599 logger
.error(`${this._logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
600 await Utils
.sleep(reconnectDelay
);
601 logger
.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
.toString());
602 this._openWSConnection({ handshakeTimeout
: reconnectDelay
- 100 });
603 } else if (this._autoReconnectMaxRetries
!== -1) {
604 logger
.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectMaxRetries})`);
608 async onOpen(): Promise
<void> {
609 logger
.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
610 if (!this._hasSocketRestarted
|| this._hasStopped
) {
611 // Send BootNotification
612 this._bootNotificationResponse
= await this.sendBootNotification();
614 if (this._bootNotificationResponse
.status === RegistrationStatus
.ACCEPTED
) {
615 await this._startMessageSequence();
618 await Utils
.sleep(this._bootNotificationResponse
.interval
* 1000);
619 // Resend BootNotification
620 this._bootNotificationResponse
= await this.sendBootNotification();
621 } while (this._bootNotificationResponse
.status !== RegistrationStatus
.ACCEPTED
);
623 if (this._hasSocketRestarted
&& this._bootNotificationResponse
.status === RegistrationStatus
.ACCEPTED
) {
624 if (!Utils
.isEmptyArray(this._messageQueue
)) {
625 this._messageQueue
.forEach((message
, index
) => {
626 if (this._wsConnection
?.readyState
=== WebSocket
.OPEN
) {
627 this._messageQueue
.splice(index
, 1);
628 this._wsConnection
.send(message
);
633 this._autoReconnectRetryCount
= 0;
634 this._hasSocketRestarted
= false;
637 async onError(errorEvent
): Promise
<void> {
638 switch (errorEvent
.code
) {
640 this._hasSocketRestarted
= true;
641 await this._reconnect(errorEvent
);
644 logger
.error(this._logPrefix() + ' Socket error: %j', errorEvent
);
649 async onClose(closeEvent
): Promise
<void> {
650 switch (closeEvent
) {
651 case 1000: // Normal close
653 logger
.info(this._logPrefix() + ' Socket normally closed: %j', closeEvent
);
654 this._autoReconnectRetryCount
= 0;
656 default: // Abnormal close
657 this._hasSocketRestarted
= true;
658 await this._reconnect(closeEvent
);
664 logger
.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
668 logger
.debug(this._logPrefix() + ' Has received a WS pong (rfc6455) from the server');
671 async onMessage(messageEvent
: MessageEvent
): Promise
<void> {
672 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
675 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(messageEvent
.toString());
677 // Check the Type of message
678 switch (messageType
) {
680 case Constants
.OCPP_JSON_CALL_MESSAGE
:
681 if (this.getEnableStatistics()) {
682 this._statistics
.addMessage(commandName
, messageType
);
685 await this.handleRequest(messageId
, commandName
, commandPayload
);
688 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
690 // eslint-disable-next-line no-case-declarations
691 let responseCallback
; let requestPayload
;
692 if (Utils
.isIterable(this._requests
[messageId
])) {
693 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
695 throw new Error(`Response request for message id ${messageId} is not iterable`);
697 if (!responseCallback
) {
699 throw new Error(`Response request for unknown message id ${messageId}`);
701 delete this._requests
[messageId
];
702 responseCallback(commandName
, requestPayload
);
705 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
706 if (!this._requests
[messageId
]) {
708 throw new Error(`Error request for unknown message id ${messageId}`);
710 // eslint-disable-next-line no-case-declarations
712 if (Utils
.isIterable(this._requests
[messageId
])) {
713 [, rejectCallback
] = this._requests
[messageId
];
715 throw new Error(`Error request for message id ${messageId} is not iterable`);
717 delete this._requests
[messageId
];
718 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
722 // eslint-disable-next-line no-case-declarations
723 const errMsg
= `${this._logPrefix()} Wrong message type ${messageType}`;
724 logger
.error(errMsg
);
725 throw new Error(errMsg
);
729 logger
.error('%s Incoming message %j processing error %s on request content type %s', this._logPrefix(), messageEvent
, error
, this._requests
[messageId
]);
731 messageType
!== Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
&& await this.sendError(messageId
, error
, commandName
);
735 async sendHeartbeat(): Promise
<void> {
737 const payload
: HeartbeatRequest
= {};
738 await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
740 logger
.error(this._logPrefix() + ' Send Heartbeat error: %j', error
);
745 async sendBootNotification(): Promise
<BootNotificationResponse
> {
747 return await this.sendMessage(Utils
.generateUUID(), this._bootNotificationRequest
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification') as BootNotificationResponse
;
749 logger
.error(this._logPrefix() + ' Send BootNotification error: %j', error
);
754 async sendStatusNotification(connectorId
: number, status: ChargePointStatus
, errorCode
: ChargePointErrorCode
= ChargePointErrorCode
.NO_ERROR
): Promise
<void> {
755 this.getConnector(connectorId
).status = status;
757 const payload
: StatusNotificationRequest
= {
762 await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
764 logger
.error(this._logPrefix() + ' Send StatusNotification error: %j', error
);
769 async sendStartTransaction(connectorId
: number, idTag
?: string): Promise
<StartTransactionResponse
> {
771 const payload
: StartTransactionRequest
= {
773 ...!Utils
.isUndefined(idTag
) ? { idTag
} : { idTag
: Constants
.TRANSACTION_DEFAULT_IDTAG
},
775 timestamp
: new Date().toISOString(),
777 return await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction') as StartTransactionResponse
;
779 logger
.error(this._logPrefix() + ' Send StartTransaction error: %j', error
);
784 async sendStopTransaction(transactionId
: number, reason
: StopTransactionReason
= StopTransactionReason
.NONE
): Promise
<StopTransactionResponse
> {
785 const idTag
= this._getTransactionIdTag(transactionId
);
787 const payload
: StopTransactionRequest
= {
789 ...!Utils
.isUndefined(idTag
) && { idTag
: idTag
},
790 meterStop
: this._getTransactionMeterStop(transactionId
),
791 timestamp
: new Date().toISOString(),
792 ...reason
&& { reason
},
794 return await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction') as StartTransactionResponse
;
796 logger
.error(this._logPrefix() + ' Send StopTransaction error: %j', error
);
801 // eslint-disable-next-line consistent-this
802 async sendMeterValues(connectorId
: number, interval
: number, self: ChargingStation
, debug
= false): Promise
<void> {
804 const meterValue
: MeterValue
= {
805 timestamp
: new Date().toISOString(),
808 const meterValuesTemplate
: SampledValue
[] = self.getConnector(connectorId
).MeterValues
;
809 for (let index
= 0; index
< meterValuesTemplate
.length
; index
++) {
810 const connector
= self.getConnector(connectorId
);
812 if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.STATE_OF_CHARGE
&& self._getConfigurationKey('MeterValuesSampledData').value
.includes(MeterValueMeasurand
.STATE_OF_CHARGE
)) {
813 meterValue
.sampledValue
.push({
814 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.PERCENT
},
815 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
816 measurand
: meterValuesTemplate
[index
].measurand
,
817 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) ? { location
: meterValuesTemplate
[index
].location
} : { location
: MeterValueLocation
.EV
},
818 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: Utils
.getRandomInt(100).toString() },
820 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
821 if (Utils
.convertToInt(meterValue
.sampledValue
[sampledValuesIndex
].value
) > 100 || debug
) {
822 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`);
825 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.VOLTAGE
&& self._getConfigurationKey('MeterValuesSampledData').value
.includes(MeterValueMeasurand
.VOLTAGE
)) {
826 const voltageMeasurandValue
= Utils
.getRandomFloatRounded(self._getVoltageOut() + self._getVoltageOut() * 0.1, self._getVoltageOut() - self._getVoltageOut() * 0.1);
827 meterValue
.sampledValue
.push({
828 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.VOLT
},
829 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
830 measurand
: meterValuesTemplate
[index
].measurand
,
831 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
832 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: voltageMeasurandValue
.toString() },
834 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
835 let phaseValue
: string;
836 if (self._getVoltageOut() >= 0 && self._getVoltageOut() <= 250) {
837 phaseValue
= `L${phase}-N`;
838 } else if (self._getVoltageOut() > 250) {
839 phaseValue
= `L${phase}-L${(phase + 1) % self._getNumberOfPhases() !== 0 ? (phase + 1) % self._getNumberOfPhases() : self._getNumberOfPhases()}`;
841 meterValue
.sampledValue
.push({
842 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.VOLT
},
843 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
844 measurand
: meterValuesTemplate
[index
].measurand
,
845 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
846 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: voltageMeasurandValue
.toString() },
847 phase
: phaseValue
as MeterValuePhase
,
850 // Power.Active.Import measurand
851 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.POWER_ACTIVE_IMPORT
&& self._getConfigurationKey('MeterValuesSampledData').value
.includes(MeterValueMeasurand
.POWER_ACTIVE_IMPORT
)) {
852 // FIXME: factor out powerDivider checks
853 if (Utils
.isUndefined(self._stationInfo
.powerDivider
)) {
854 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
855 logger
.error(errMsg
);
857 } else if (self._stationInfo
.powerDivider
&& self._stationInfo
.powerDivider
<= 0) {
858 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}`;
859 logger
.error(errMsg
);
862 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`;
863 const powerMeasurandValues
= {} as MeasurandValues
;
864 const maxPower
= Math.round(self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
);
865 const maxPowerPerPhase
= Math.round((self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
) / self._getNumberOfPhases());
866 switch (self._getPowerOutType()) {
867 case PowerOutType
.AC
:
868 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
869 powerMeasurandValues
.L1
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
870 powerMeasurandValues
.L2
= 0;
871 powerMeasurandValues
.L3
= 0;
872 if (self._getNumberOfPhases() === 3) {
873 powerMeasurandValues
.L2
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
874 powerMeasurandValues
.L3
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
876 powerMeasurandValues
.allPhases
= Utils
.roundTo(powerMeasurandValues
.L1
+ powerMeasurandValues
.L2
+ powerMeasurandValues
.L3
, 2);
879 case PowerOutType
.DC
:
880 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
881 powerMeasurandValues
.allPhases
= Utils
.getRandomFloatRounded(maxPower
);
885 logger
.error(errMsg
);
888 meterValue
.sampledValue
.push({
889 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.WATT
},
890 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
891 measurand
: meterValuesTemplate
[index
].measurand
,
892 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
893 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: powerMeasurandValues
.allPhases
.toString() },
895 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
896 if (Utils
.convertToFloat(meterValue
.sampledValue
[sampledValuesIndex
].value
) > maxPower
|| debug
) {
897 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}`);
899 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
900 const phaseValue
= `L${phase}-N`;
901 meterValue
.sampledValue
.push({
902 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.WATT
},
903 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
904 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
905 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
906 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: powerMeasurandValues
[`L${phase}`] as string },
907 phase
: phaseValue
as MeterValuePhase
,
910 // Current.Import measurand
911 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.CURRENT_IMPORT
&& self._getConfigurationKey('MeterValuesSampledData').value
.includes(MeterValueMeasurand
.CURRENT_IMPORT
)) {
912 // FIXME: factor out powerDivider checks
913 if (Utils
.isUndefined(self._stationInfo
.powerDivider
)) {
914 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
915 logger
.error(errMsg
);
917 } else if (self._stationInfo
.powerDivider
&& self._stationInfo
.powerDivider
<= 0) {
918 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}`;
919 logger
.error(errMsg
);
922 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`;
923 const currentMeasurandValues
: MeasurandValues
= {} as MeasurandValues
;
924 let maxAmperage
: number;
925 switch (self._getPowerOutType()) {
926 case PowerOutType
.AC
:
927 maxAmperage
= ElectricUtils
.ampPerPhaseFromPower(self._getNumberOfPhases(), self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
, self._getVoltageOut());
928 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
929 currentMeasurandValues
.L1
= Utils
.getRandomFloatRounded(maxAmperage
);
930 currentMeasurandValues
.L2
= 0;
931 currentMeasurandValues
.L3
= 0;
932 if (self._getNumberOfPhases() === 3) {
933 currentMeasurandValues
.L2
= Utils
.getRandomFloatRounded(maxAmperage
);
934 currentMeasurandValues
.L3
= Utils
.getRandomFloatRounded(maxAmperage
);
936 currentMeasurandValues
.allPhases
= Utils
.roundTo((currentMeasurandValues
.L1
+ currentMeasurandValues
.L2
+ currentMeasurandValues
.L3
) / self._getNumberOfPhases(), 2);
939 case PowerOutType
.DC
:
940 maxAmperage
= ElectricUtils
.ampTotalFromPower(self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
, self._getVoltageOut());
941 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
942 currentMeasurandValues
.allPhases
= Utils
.getRandomFloatRounded(maxAmperage
);
946 logger
.error(errMsg
);
949 meterValue
.sampledValue
.push({
950 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.AMP
},
951 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
952 measurand
: meterValuesTemplate
[index
].measurand
,
953 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
954 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: currentMeasurandValues
.allPhases
.toString() },
956 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
957 if (Utils
.convertToFloat(meterValue
.sampledValue
[sampledValuesIndex
].value
) > maxAmperage
|| debug
) {
958 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}`);
960 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
961 const phaseValue
= `L${phase}`;
962 meterValue
.sampledValue
.push({
963 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.AMP
},
964 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
965 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
966 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
967 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: currentMeasurandValues
[phaseValue
] as string },
968 phase
: phaseValue
as MeterValuePhase
,
971 // Energy.Active.Import.Register measurand (default)
972 } else if (!meterValuesTemplate
[index
].measurand
|| meterValuesTemplate
[index
].measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
973 // FIXME: factor out powerDivider checks
974 if (Utils
.isUndefined(self._stationInfo
.powerDivider
)) {
975 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
976 logger
.error(errMsg
);
978 } else if (self._stationInfo
.powerDivider
&& self._stationInfo
.powerDivider
<= 0) {
979 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}`;
980 logger
.error(errMsg
);
983 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
984 const measurandValue
= Utils
.getRandomInt(self._stationInfo
.maxPower
/ (self._stationInfo
.powerDivider
* 3600000) * interval
);
985 // Persist previous value in connector
986 if (connector
&& !Utils
.isNullOrUndefined(connector
.lastEnergyActiveImportRegisterValue
) && connector
.lastEnergyActiveImportRegisterValue
>= 0) {
987 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
989 connector
.lastEnergyActiveImportRegisterValue
= 0;
992 meterValue
.sampledValue
.push({
993 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: MeterValueUnit
.WATT_HOUR
},
994 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
995 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
996 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
997 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} :
998 { value
: connector
.lastEnergyActiveImportRegisterValue
.toString() },
1000 const sampledValuesIndex
= meterValue
.sampledValue
.length
- 1;
1001 const maxConsumption
= Math.round(self._stationInfo
.maxPower
* 3600 / (self._stationInfo
.powerDivider
* interval
));
1002 if (Utils
.convertToFloat(meterValue
.sampledValue
[sampledValuesIndex
].value
) > maxConsumption
|| debug
) {
1003 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}`);
1005 // Unsupported measurand
1007 logger
.info(`${self._logPrefix()} Unsupported MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} on connectorId ${connectorId}`);
1010 const payload
: MeterValuesRequest
= {
1012 transactionId
: self.getConnector(connectorId
).transactionId
,
1013 meterValue
: meterValue
,
1015 await self.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
1017 logger
.error(self._logPrefix() + ' Send MeterValues error: %j', error
);
1022 async sendError(messageId
: string, err
: Error | OCPPError
, commandName
: string): Promise
<unknown
> {
1023 // Check exception type: only OCPP error are accepted
1024 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
, err
.stack
&& err
.stack
);
1026 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
, commandName
);
1029 async sendMessage(messageId
: string, commandParams
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
: string): Promise
<any> {
1030 // eslint-disable-next-line @typescript-eslint/no-this-alias
1032 // Send a message through wsConnection
1033 return new Promise((resolve
: (value
?: any | PromiseLike
<any>) => void, reject
: (reason
?: any) => void) => {
1036 switch (messageType
) {
1038 case Constants
.OCPP_JSON_CALL_MESSAGE
:
1040 this._requests
[messageId
] = [responseCallback
, rejectCallback
, commandParams
];
1041 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, commandParams
]);
1044 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
1046 messageToSend
= JSON
.stringify([messageType
, messageId
, commandParams
]);
1049 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
1050 // Build Error Message
1051 messageToSend
= JSON
.stringify([messageType
, messageId
, commandParams
.code
? commandParams
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, commandParams
.message
? commandParams
.message
: '', commandParams
.details
? commandParams
.details
: {}]);
1054 // Check if wsConnection is ready
1055 if (this._wsConnection
?.readyState
=== WebSocket
.OPEN
) {
1056 if (this.getEnableStatistics()) {
1057 this._statistics
.addMessage(commandName
, messageType
);
1059 // Yes: Send Message
1060 this._wsConnection
.send(messageToSend
);
1063 // Handle dups in buffer
1064 for (const message
of this._messageQueue
) {
1066 if (JSON
.stringify(messageToSend
) === JSON
.stringify(message
)) {
1073 this._messageQueue
.push(messageToSend
);
1076 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
: {}));
1079 if (messageType
=== Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
) {
1082 } else if (messageType
=== Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
) {
1084 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
);
1087 // Function that will receive the request's response
1088 async function responseCallback(payload
, requestPayload
): Promise
<void> {
1089 if (self.getEnableStatistics()) {
1090 self._statistics
.addMessage(commandName
, messageType
);
1092 // Send the response
1093 await self.handleResponse(commandName
, payload
, requestPayload
);
1097 // Function that will receive the request's rejection
1098 function rejectCallback(error
: OCPPError
): void {
1099 if (self.getEnableStatistics()) {
1100 self._statistics
.addMessage(commandName
, messageType
);
1102 logger
.debug(`${self._logPrefix()} Error: %j occurred when calling command %s with parameters: %j`, error
, commandName
, commandParams
);
1104 // eslint-disable-next-line no-empty-function
1105 self._requests
[messageId
] = [() => { }, () => { }, {}]; // Properly format the request
1112 async handleResponse(commandName
: string, payload
, requestPayload
): Promise
<void> {
1113 const responseCallbackFn
= 'handleResponse' + commandName
;
1114 if (typeof this[responseCallbackFn
] === 'function') {
1115 await this[responseCallbackFn
](payload
, requestPayload
);
1117 logger
.error(this._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
1121 handleResponseBootNotification(payload
: BootNotificationResponse
, requestPayload
: BootNotificationRequest
): void {
1122 if (payload
.status === RegistrationStatus
.ACCEPTED
) {
1123 this._heartbeatInterval
= Utils
.convertToInt(payload
.interval
) * 1000;
1124 this._heartbeatSetInterval
? this._restartHeartbeat() : this._startHeartbeat();
1125 this._addConfigurationKey('HeartBeatInterval', payload
.interval
.toString());
1126 this._addConfigurationKey('HeartbeatInterval', payload
.interval
.toString(), false, false);
1127 this._hasStopped
&& (this._hasStopped
= false);
1128 } else if (payload
.status === RegistrationStatus
.PENDING
) {
1129 logger
.info(this._logPrefix() + ' Charging station in pending state on the central server');
1131 logger
.info(this._logPrefix() + ' Charging station rejected by the central server');
1135 _initTransactionOnConnector(connectorId
: number): void {
1136 this.getConnector(connectorId
).transactionStarted
= false;
1137 this.getConnector(connectorId
).transactionId
= null;
1138 this.getConnector(connectorId
).idTag
= null;
1139 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;
1142 _resetTransactionOnConnector(connectorId
: number): void {
1143 this._initTransactionOnConnector(connectorId
);
1144 if (this.getConnector(connectorId
).transactionSetInterval
) {
1145 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
1149 async handleResponseStartTransaction(payload
: StartTransactionResponse
, requestPayload
: StartTransactionRequest
): Promise
<void> {
1150 const connectorId
= Utils
.convertToInt(requestPayload
.connectorId
);
1151 if (this.getConnector(connectorId
).transactionStarted
) {
1152 logger
.debug(this._logPrefix() + ' Trying to start a transaction on an already used connector ' + connectorId
.toString() + ': %j', this.getConnector(connectorId
));
1156 let transactionConnectorId
: number;
1157 for (const connector
in this._connectors
) {
1158 if (Utils
.convertToInt(connector
) > 0 && Utils
.convertToInt(connector
) === connectorId
) {
1159 transactionConnectorId
= Utils
.convertToInt(connector
);
1163 if (!transactionConnectorId
) {
1164 logger
.error(this._logPrefix() + ' Trying to start a transaction on a non existing connector Id ' + connectorId
.toString());
1167 if (payload
.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
1168 this.getConnector(connectorId
).transactionStarted
= true;
1169 this.getConnector(connectorId
).transactionId
= payload
.transactionId
;
1170 this.getConnector(connectorId
).idTag
= requestPayload
.idTag
;
1171 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= 0;
1172 await this.sendStatusNotification(connectorId
, ChargePointStatus
.CHARGING
);
1173 logger
.info(this._logPrefix() + ' Transaction ' + payload
.transactionId
.toString() + ' STARTED on ' + this._stationInfo
.name
+ '#' + connectorId
.toString() + ' for idTag ' + requestPayload
.idTag
);
1174 if (this._stationInfo
.powerSharedByConnectors
) {
1175 this._stationInfo
.powerDivider
++;
1177 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
1178 this._startMeterValues(connectorId
,
1179 configuredMeterValueSampleInterval
? Utils
.convertToInt(configuredMeterValueSampleInterval
.value
) * 1000 : 60000);
1181 logger
.error(this._logPrefix() + ' Starting transaction id ' + payload
.transactionId
.toString() + ' REJECTED with status ' + payload
.idTagInfo
.status + ', idTag ' + requestPayload
.idTag
);
1182 this._resetTransactionOnConnector(connectorId
);
1183 await this.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
);
1187 async handleResponseStopTransaction(payload
: StopTransactionResponse
, requestPayload
: StopTransactionRequest
): Promise
<void> {
1188 let transactionConnectorId
: number;
1189 for (const connector
in this._connectors
) {
1190 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== Utils
.convertToInt(requestPayload
.transactionId
)) {
1191 transactionConnectorId
= Utils
.convertToInt(connector
);
1195 if (!transactionConnectorId
) {
1196 logger
.error(this._logPrefix() + ' Trying to stop a non existing transaction ' + requestPayload
.transactionId
.toString());
1199 if (payload
.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
1200 await this.sendStatusNotification(transactionConnectorId
, ChargePointStatus
.AVAILABLE
);
1201 if (this._stationInfo
.powerSharedByConnectors
) {
1202 this._stationInfo
.powerDivider
--;
1204 logger
.info(this._logPrefix() + ' Transaction ' + requestPayload
.transactionId
.toString() + ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
.toString());
1205 this._resetTransactionOnConnector(transactionConnectorId
);
1207 logger
.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
.toString() + ' REJECTED with status ' + payload
.idTagInfo
?.status);
1211 handleResponseStatusNotification(payload
: StatusNotificationRequest
, requestPayload
: StatusNotificationResponse
): void {
1212 logger
.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
1215 handleResponseMeterValues(payload
: MeterValuesRequest
, requestPayload
: MeterValuesResponse
): void {
1216 logger
.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
1219 handleResponseHeartbeat(payload
: HeartbeatResponse
, requestPayload
: HeartbeatRequest
): void {
1220 logger
.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
1223 async handleRequest(messageId
: string, commandName
: string, commandPayload
): Promise
<void> {
1226 if (typeof this['handleRequest' + commandName
] === 'function') {
1228 // Call the method to build the response
1229 response
= await this['handleRequest' + commandName
](commandPayload
);
1232 logger
.error(this._logPrefix() + ' Handle request error: %j', error
);
1233 // Send back response to inform backend
1234 await this.sendError(messageId
, error
, commandName
);
1239 await this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, `${commandName} is not implemented`, {}), commandName
);
1240 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
1243 await this.sendMessage(messageId
, response
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
);
1246 // Simulate charging station restart
1247 handleRequestReset(commandPayload
: ResetRequest
): DefaultResponse
{
1248 setImmediate(async () => {
1249 await this.stop(commandPayload
.type + 'Reset' as StopTransactionReason
);
1250 await Utils
.sleep(this._stationInfo
.resetTime
);
1253 logger
.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${Utils.milliSecondsToHHMMSS(this._stationInfo.resetTime)}`);
1254 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1257 handleRequestClearCache(): DefaultResponse
{
1258 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1261 async handleRequestUnlockConnector(commandPayload
: UnlockConnectorRequest
): Promise
<UnlockConnectorResponse
> {
1262 const connectorId
= Utils
.convertToInt(commandPayload
.connectorId
);
1263 if (connectorId
=== 0) {
1264 logger
.error(this._logPrefix() + ' Trying to unlock connector ' + connectorId
.toString());
1265 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
1267 if (this.getConnector(connectorId
).transactionStarted
) {
1268 const stopResponse
= await this.sendStopTransaction(this.getConnector(connectorId
).transactionId
, StopTransactionReason
.UNLOCK_COMMAND
);
1269 if (stopResponse
.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
) {
1270 return Constants
.OCPP_RESPONSE_UNLOCKED
;
1272 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
1274 await this.sendStatusNotification(connectorId
, ChargePointStatus
.AVAILABLE
);
1275 return Constants
.OCPP_RESPONSE_UNLOCKED
;
1278 _getConfigurationKey(key
: string): ConfigurationKey
{
1279 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
1282 _addConfigurationKey(key
: string, value
: string, readonly = false, visible
= true, reboot
= false): void {
1283 const keyFound
= this._getConfigurationKey(key
);
1285 this._configuration
.configurationKey
.push({
1295 _setConfigurationKeyValue(key
: string, value
: string): void {
1296 const keyFound
= this._getConfigurationKey(key
);
1298 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
1299 this._configuration
.configurationKey
[keyIndex
].value
= value
;
1303 handleRequestGetConfiguration(commandPayload
: GetConfigurationRequest
): GetConfigurationResponse
{
1304 const configurationKey
: ConfigurationKey
[] = [];
1305 const unknownKey
: string[] = [];
1306 if (Utils
.isEmptyArray(commandPayload
.key
)) {
1307 for (const configuration
of this._configuration
.configurationKey
) {
1308 if (Utils
.isUndefined(configuration
.visible
)) {
1309 configuration
.visible
= true;
1311 if (!configuration
.visible
) {
1314 configurationKey
.push({
1315 key
: configuration
.key
,
1316 readonly: configuration
.readonly,
1317 value
: configuration
.value
,
1321 for (const key
of commandPayload
.key
) {
1322 const keyFound
= this._getConfigurationKey(key
);
1324 if (Utils
.isUndefined(keyFound
.visible
)) {
1325 keyFound
.visible
= true;
1327 if (!keyFound
.visible
) {
1330 configurationKey
.push({
1332 readonly: keyFound
.readonly,
1333 value
: keyFound
.value
,
1336 unknownKey
.push(key
);
1346 handleRequestChangeConfiguration(commandPayload
: ChangeConfigurationRequest
): ChangeConfigurationResponse
{
1347 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
1349 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
1350 } else if (keyToChange
&& keyToChange
.readonly) {
1351 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
1352 } else if (keyToChange
&& !keyToChange
.readonly) {
1353 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
1354 let valueChanged
= false;
1355 if (this._configuration
.configurationKey
[keyIndex
].value
!== commandPayload
.value
) {
1356 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
1357 valueChanged
= true;
1359 let triggerHeartbeatRestart
= false;
1360 if (keyToChange
.key
=== 'HeartBeatInterval' && valueChanged
) {
1361 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
1362 triggerHeartbeatRestart
= true;
1364 if (keyToChange
.key
=== 'HeartbeatInterval' && valueChanged
) {
1365 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
1366 triggerHeartbeatRestart
= true;
1368 if (triggerHeartbeatRestart
) {
1369 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
1370 this._restartHeartbeat();
1372 if (keyToChange
.key
=== 'WebSocketPingInterval' && valueChanged
) {
1373 this._restartWebSocketPing();
1375 if (keyToChange
.reboot
) {
1376 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
1378 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
1382 handleRequestSetChargingProfile(commandPayload
: SetChargingProfileRequest
): SetChargingProfileResponse
{
1383 if (!this.getConnector(commandPayload
.connectorId
)) {
1384 logger
.error(`${this._logPrefix()} Trying to set a charging profile to a non existing connector Id ${commandPayload.connectorId}`);
1385 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_REJECTED
;
1387 if (commandPayload
.csChargingProfiles
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
&& !this.getConnector(commandPayload
.connectorId
)?.transactionStarted
) {
1388 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_REJECTED
;
1390 this.getConnector(commandPayload
.connectorId
).chargingProfiles
.forEach((chargingProfile
: ChargingProfile
, index
: number) => {
1391 if (chargingProfile
.chargingProfileId
=== commandPayload
.csChargingProfiles
.chargingProfileId
1392 || (chargingProfile
.stackLevel
=== commandPayload
.csChargingProfiles
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== commandPayload
.csChargingProfiles
.chargingProfilePurpose
)) {
1393 this.getConnector(commandPayload
.connectorId
).chargingProfiles
[index
] = chargingProfile
;
1394 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
1397 this.getConnector(commandPayload
.connectorId
).chargingProfiles
.push(commandPayload
.csChargingProfiles
);
1398 return Constants
.OCPP_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
1401 async handleRequestRemoteStartTransaction(commandPayload
: RemoteStartTransactionRequest
): Promise
<DefaultResponse
> {
1402 const transactionConnectorID
: number = commandPayload
.connectorId
? Utils
.convertToInt(commandPayload
.connectorId
) : 1;
1403 if (this._getAuthorizeRemoteTxRequests() && this._getLocalAuthListEnabled() && this.hasAuthorizedTags()) {
1404 // Check if authorized
1405 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
1406 // Authorization successful start transaction
1407 await this.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
);
1408 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
.toString() + ' for idTag ' + commandPayload
.idTag
);
1409 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1411 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED, idTag ' + commandPayload
.idTag
);
1412 return Constants
.OCPP_RESPONSE_REJECTED
;
1414 // No local authorization check required => start transaction
1415 await this.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
);
1416 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
.toString() + ' for idTag ' + commandPayload
.idTag
);
1417 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1420 async handleRequestRemoteStopTransaction(commandPayload
: RemoteStopTransactionRequest
): Promise
<DefaultResponse
> {
1421 const transactionId
= Utils
.convertToInt(commandPayload
.transactionId
);
1422 for (const connector
in this._connectors
) {
1423 if (Utils
.convertToInt(connector
) > 0 && this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== transactionId
) {
1424 await this.sendStopTransaction(transactionId
);
1425 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1428 logger
.info(this._logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId
.toString());
1429 return Constants
.OCPP_RESPONSE_REJECTED
;