1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
4 import path from
'path';
5 import { URL
, fileURLToPath
} from
'url';
7 import { Client
, FTPResponse
} from
'basic-ftp';
10 import OCPPError from
'../../../exception/OCPPError';
11 import { JsonType
} from
'../../../types/JsonType';
12 import { OCPP16ChargePointErrorCode
} from
'../../../types/ocpp/1.6/ChargePointErrorCode';
13 import { OCPP16ChargePointStatus
} from
'../../../types/ocpp/1.6/ChargePointStatus';
15 ChargingProfilePurposeType
,
16 OCPP16ChargingProfile
,
17 } from
'../../../types/ocpp/1.6/ChargingProfile';
19 OCPP16StandardParametersKey
,
20 OCPP16SupportedFeatureProfiles
,
21 } from
'../../../types/ocpp/1.6/Configuration';
22 import { OCPP16DiagnosticsStatus
} from
'../../../types/ocpp/1.6/DiagnosticsStatus';
24 OCPP16MeterValuesRequest
,
25 OCPP16MeterValuesResponse
,
26 } from
'../../../types/ocpp/1.6/MeterValues';
28 ChangeAvailabilityRequest
,
29 ChangeConfigurationRequest
,
30 ClearChargingProfileRequest
,
31 DiagnosticsStatusNotificationRequest
,
32 GetConfigurationRequest
,
33 GetDiagnosticsRequest
,
35 OCPP16AvailabilityType
,
36 OCPP16BootNotificationRequest
,
37 OCPP16HeartbeatRequest
,
38 OCPP16IncomingRequestCommand
,
40 OCPP16StatusNotificationRequest
,
41 OCPP16TriggerMessageRequest
,
42 RemoteStartTransactionRequest
,
43 RemoteStopTransactionRequest
,
45 SetChargingProfileRequest
,
46 UnlockConnectorRequest
,
47 } from
'../../../types/ocpp/1.6/Requests';
49 ChangeAvailabilityResponse
,
50 ChangeConfigurationResponse
,
51 ClearChargingProfileResponse
,
52 DiagnosticsStatusNotificationResponse
,
53 GetConfigurationResponse
,
54 GetDiagnosticsResponse
,
55 OCPP16BootNotificationResponse
,
56 OCPP16HeartbeatResponse
,
57 OCPP16StatusNotificationResponse
,
58 OCPP16TriggerMessageResponse
,
59 SetChargingProfileResponse
,
60 UnlockConnectorResponse
,
61 } from
'../../../types/ocpp/1.6/Responses';
63 OCPP16AuthorizationStatus
,
64 OCPP16AuthorizeRequest
,
65 OCPP16AuthorizeResponse
,
66 OCPP16StartTransactionRequest
,
67 OCPP16StartTransactionResponse
,
68 OCPP16StopTransactionReason
,
69 OCPP16StopTransactionRequest
,
70 OCPP16StopTransactionResponse
,
71 } from
'../../../types/ocpp/1.6/Transaction';
72 import { OCPPConfigurationKey
} from
'../../../types/ocpp/Configuration';
73 import { ErrorType
} from
'../../../types/ocpp/ErrorType';
74 import { IncomingRequestHandler
} from
'../../../types/ocpp/Requests';
75 import { DefaultResponse
} from
'../../../types/ocpp/Responses';
76 import Constants from
'../../../utils/Constants';
77 import logger from
'../../../utils/Logger';
78 import Utils from
'../../../utils/Utils';
79 import type ChargingStation from
'../../ChargingStation';
80 import { ChargingStationConfigurationUtils
} from
'../../ChargingStationConfigurationUtils';
81 import { ChargingStationUtils
} from
'../../ChargingStationUtils';
82 import OCPPIncomingRequestService from
'../OCPPIncomingRequestService';
83 import { OCPP16ServiceUtils
} from
'./OCPP16ServiceUtils';
85 const moduleName
= 'OCPP16IncomingRequestService';
87 export default class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
88 private incomingRequestHandlers
: Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>;
90 public constructor() {
91 if (new.target
?.name
=== moduleName
) {
92 throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
95 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
96 [OCPP16IncomingRequestCommand
.RESET
, this.handleRequestReset
.bind(this)],
97 [OCPP16IncomingRequestCommand
.CLEAR_CACHE
, this.handleRequestClearCache
.bind(this)],
98 [OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
, this.handleRequestUnlockConnector
.bind(this)],
100 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
101 this.handleRequestGetConfiguration
.bind(this),
104 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
105 this.handleRequestChangeConfiguration
.bind(this),
108 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
109 this.handleRequestSetChargingProfile
.bind(this),
112 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
113 this.handleRequestClearChargingProfile
.bind(this),
116 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
117 this.handleRequestChangeAvailability
.bind(this),
120 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
121 this.handleRequestRemoteStartTransaction
.bind(this),
124 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
125 this.handleRequestRemoteStopTransaction
.bind(this),
127 [OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
, this.handleRequestGetDiagnostics
.bind(this)],
128 [OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
, this.handleRequestTriggerMessage
.bind(this)],
132 public async incomingRequestHandler(
133 chargingStation
: ChargingStation
,
135 commandName
: OCPP16IncomingRequestCommand
,
136 commandPayload
: JsonType
138 let response
: JsonType
;
140 chargingStation
.getOcppStrictCompliance() &&
141 chargingStation
.isInPendingState() &&
142 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
143 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
146 ErrorType
.SECURITY_ERROR
,
147 `${commandName} cannot be issued to handle request payload ${JSON.stringify(
151 )} while the charging station is in pending state on the central server`,
157 chargingStation
.isRegistered() ||
158 (!chargingStation
.getOcppStrictCompliance() && chargingStation
.isInUnknownState())
161 this.incomingRequestHandlers
.has(commandName
) &&
162 ChargingStationUtils
.isCommandSupported(commandName
, chargingStation
.stationInfo
)
165 // Call the method to build the response
166 response
= await this.incomingRequestHandlers
.get(commandName
)(
172 logger
.error(chargingStation
.logPrefix() + ' Handle request error: %j', error
);
178 ErrorType
.NOT_IMPLEMENTED
,
179 `${commandName} is not implemented to handle request payload ${JSON.stringify(
190 ErrorType
.SECURITY_ERROR
,
191 `${commandName} cannot be issued to handle request payload ${JSON.stringify(
195 )} while the charging station is not registered on the central server.`,
200 // Send the built response
201 await chargingStation
.ocppRequestService
.sendResponse(
209 // Simulate charging station restart
210 private handleRequestReset(
211 chargingStation
: ChargingStation
,
212 commandPayload
: ResetRequest
214 // eslint-disable-next-line @typescript-eslint/no-misused-promises
215 setImmediate(async (): Promise
<void> => {
216 await chargingStation
.reset((commandPayload
.type + 'Reset') as OCPP16StopTransactionReason
);
219 `${chargingStation.logPrefix()} ${
221 } reset command received, simulating it. The station will be back online in ${Utils.formatDurationMilliSeconds(
222 chargingStation.stationInfo.resetTime
225 return Constants
.OCPP_RESPONSE_ACCEPTED
;
228 private handleRequestClearCache(): DefaultResponse
{
229 return Constants
.OCPP_RESPONSE_ACCEPTED
;
232 private async handleRequestUnlockConnector(
233 chargingStation
: ChargingStation
,
234 commandPayload
: UnlockConnectorRequest
235 ): Promise
<UnlockConnectorResponse
> {
236 const connectorId
= commandPayload
.connectorId
;
237 if (connectorId
=== 0) {
239 chargingStation
.logPrefix() + ' Trying to unlock connector ' + connectorId
.toString()
241 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
243 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
244 const transactionId
= chargingStation
.getConnectorStatus(connectorId
).transactionId
;
246 chargingStation
.getBeginEndMeterValues() &&
247 chargingStation
.getOcppStrictCompliance() &&
248 !chargingStation
.getOutOfOrderEndMeterValues()
250 // FIXME: Implement OCPP version agnostic helpers
251 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
254 chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
)
256 await chargingStation
.ocppRequestService
.requestHandler
<
257 OCPP16MeterValuesRequest
,
258 OCPP16MeterValuesResponse
259 >(chargingStation
, OCPP16RequestCommand
.METER_VALUES
, {
262 meterValue
: [transactionEndMeterValue
],
265 const stopResponse
= await chargingStation
.ocppRequestService
.requestHandler
<
266 OCPP16StopTransactionRequest
,
267 OCPP16StopTransactionResponse
268 >(chargingStation
, OCPP16RequestCommand
.STOP_TRANSACTION
, {
270 meterStop
: chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
271 idTag
: chargingStation
.getTransactionIdTag(transactionId
),
272 reason
: OCPP16StopTransactionReason
.UNLOCK_COMMAND
,
274 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
275 return Constants
.OCPP_RESPONSE_UNLOCKED
;
277 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
279 await chargingStation
.ocppRequestService
.requestHandler
<
280 OCPP16StatusNotificationRequest
,
281 OCPP16StatusNotificationResponse
282 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
284 status: OCPP16ChargePointStatus
.AVAILABLE
,
285 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
287 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
288 return Constants
.OCPP_RESPONSE_UNLOCKED
;
291 private handleRequestGetConfiguration(
292 chargingStation
: ChargingStation
,
293 commandPayload
: GetConfigurationRequest
294 ): GetConfigurationResponse
{
295 const configurationKey
: OCPPConfigurationKey
[] = [];
296 const unknownKey
: string[] = [];
297 if (Utils
.isEmptyArray(commandPayload
.key
)) {
298 for (const configuration
of chargingStation
.ocppConfiguration
.configurationKey
) {
299 if (Utils
.isUndefined(configuration
.visible
)) {
300 configuration
.visible
= true;
302 if (!configuration
.visible
) {
305 configurationKey
.push({
306 key
: configuration
.key
,
307 readonly: configuration
.readonly,
308 value
: configuration
.value
,
312 for (const key
of commandPayload
.key
) {
313 const keyFound
= ChargingStationConfigurationUtils
.getConfigurationKey(
318 if (Utils
.isUndefined(keyFound
.visible
)) {
319 keyFound
.visible
= true;
321 if (!keyFound
.visible
) {
324 configurationKey
.push({
326 readonly: keyFound
.readonly,
327 value
: keyFound
.value
,
330 unknownKey
.push(key
);
340 private handleRequestChangeConfiguration(
341 chargingStation
: ChargingStation
,
342 commandPayload
: ChangeConfigurationRequest
343 ): ChangeConfigurationResponse
{
344 // JSON request fields type sanity check
345 if (!Utils
.isString(commandPayload
.key
)) {
347 `${chargingStation.logPrefix()} ${
348 OCPP16IncomingRequestCommand.CHANGE_CONFIGURATION
349 } request key field is not a string:`,
353 if (!Utils
.isString(commandPayload
.value
)) {
355 `${chargingStation.logPrefix()} ${
356 OCPP16IncomingRequestCommand.CHANGE_CONFIGURATION
357 } request value field is not a string:`,
361 const keyToChange
= ChargingStationConfigurationUtils
.getConfigurationKey(
367 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
368 } else if (keyToChange
&& keyToChange
.readonly) {
369 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
370 } else if (keyToChange
&& !keyToChange
.readonly) {
371 let valueChanged
= false;
372 if (keyToChange
.value
!== commandPayload
.value
) {
373 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
376 commandPayload
.value
,
381 let triggerHeartbeatRestart
= false;
382 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
383 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
385 OCPP16StandardParametersKey
.HeartbeatInterval
,
388 triggerHeartbeatRestart
= true;
390 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
391 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
393 OCPP16StandardParametersKey
.HeartBeatInterval
,
396 triggerHeartbeatRestart
= true;
398 if (triggerHeartbeatRestart
) {
399 chargingStation
.restartHeartbeat();
401 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
402 chargingStation
.restartWebSocketPing();
404 if (keyToChange
.reboot
) {
405 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
407 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
411 private handleRequestSetChargingProfile(
412 chargingStation
: ChargingStation
,
413 commandPayload
: SetChargingProfileRequest
414 ): SetChargingProfileResponse
{
416 !OCPP16ServiceUtils
.checkFeatureProfile(
418 OCPP16SupportedFeatureProfiles
.SmartCharging
,
419 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
422 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
424 if (!chargingStation
.getConnectorStatus(commandPayload
.connectorId
)) {
426 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${
427 commandPayload.connectorId
430 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
433 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
434 ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
435 commandPayload
.connectorId
!== 0
437 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
440 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
441 ChargingProfilePurposeType
.TX_PROFILE
&&
442 (commandPayload
.connectorId
=== 0 ||
443 !chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
)
445 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
447 chargingStation
.setChargingProfile(
448 commandPayload
.connectorId
,
449 commandPayload
.csChargingProfiles
452 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${
453 commandPayload.connectorId
454 }, dump their stack: %j`,
455 chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
457 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
460 private handleRequestClearChargingProfile(
461 chargingStation
: ChargingStation
,
462 commandPayload
: ClearChargingProfileRequest
463 ): ClearChargingProfileResponse
{
465 !OCPP16ServiceUtils
.checkFeatureProfile(
467 OCPP16SupportedFeatureProfiles
.SmartCharging
,
468 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
471 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
473 const connectorStatus
= chargingStation
.getConnectorStatus(commandPayload
.connectorId
);
474 if (!connectorStatus
) {
476 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${
477 commandPayload.connectorId
480 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
482 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(connectorStatus
.chargingProfiles
)) {
483 connectorStatus
.chargingProfiles
= [];
485 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${
486 commandPayload.connectorId
487 }, dump their stack: %j`,
488 connectorStatus
.chargingProfiles
490 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
492 if (!commandPayload
.connectorId
) {
493 let clearedCP
= false;
494 for (const connectorId
of chargingStation
.connectors
.keys()) {
495 if (!Utils
.isEmptyArray(chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
)) {
497 .getConnectorStatus(connectorId
)
498 .chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
499 let clearCurrentCP
= false;
500 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
501 clearCurrentCP
= true;
504 !commandPayload
.chargingProfilePurpose
&&
505 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
507 clearCurrentCP
= true;
510 !chargingProfile
.stackLevel
&&
511 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
513 clearCurrentCP
= true;
516 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&&
517 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
519 clearCurrentCP
= true;
521 if (clearCurrentCP
) {
522 connectorStatus
.chargingProfiles
.splice(index
, 1);
524 `${chargingStation.logPrefix()} Matching charging profile(s) cleared on connector id ${
525 commandPayload.connectorId
526 }, dump their stack: %j`,
527 connectorStatus
.chargingProfiles
535 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
538 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
541 private async handleRequestChangeAvailability(
542 chargingStation
: ChargingStation
,
543 commandPayload
: ChangeAvailabilityRequest
544 ): Promise
<ChangeAvailabilityResponse
> {
545 const connectorId
: number = commandPayload
.connectorId
;
546 if (!chargingStation
.getConnectorStatus(connectorId
)) {
548 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`
550 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
552 const chargePointStatus
: OCPP16ChargePointStatus
=
553 commandPayload
.type === OCPP16AvailabilityType
.OPERATIVE
554 ? OCPP16ChargePointStatus
.AVAILABLE
555 : OCPP16ChargePointStatus
.UNAVAILABLE
;
556 if (connectorId
=== 0) {
557 let response
: ChangeAvailabilityResponse
= Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
558 for (const id
of chargingStation
.connectors
.keys()) {
559 if (chargingStation
.getConnectorStatus(id
)?.transactionStarted
) {
560 response
= Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
562 chargingStation
.getConnectorStatus(id
).availability
= commandPayload
.type;
563 if (response
=== Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
) {
564 await chargingStation
.ocppRequestService
.requestHandler
<
565 OCPP16StatusNotificationRequest
,
566 OCPP16StatusNotificationResponse
567 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
569 status: chargePointStatus
,
570 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
572 chargingStation
.getConnectorStatus(id
).status = chargePointStatus
;
578 (chargingStation
.getConnectorStatus(0).availability
=== OCPP16AvailabilityType
.OPERATIVE
||
579 (chargingStation
.getConnectorStatus(0).availability
===
580 OCPP16AvailabilityType
.INOPERATIVE
&&
581 commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))
583 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
584 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
585 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
587 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
588 await chargingStation
.ocppRequestService
.requestHandler
<
589 OCPP16StatusNotificationRequest
,
590 OCPP16StatusNotificationResponse
591 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
593 status: chargePointStatus
,
594 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
596 chargingStation
.getConnectorStatus(connectorId
).status = chargePointStatus
;
597 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
599 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
602 private async handleRequestRemoteStartTransaction(
603 chargingStation
: ChargingStation
,
604 commandPayload
: RemoteStartTransactionRequest
605 ): Promise
<DefaultResponse
> {
606 const transactionConnectorId
= commandPayload
.connectorId
;
607 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
);
608 if (transactionConnectorId
) {
609 await chargingStation
.ocppRequestService
.requestHandler
<
610 OCPP16StatusNotificationRequest
,
611 OCPP16StatusNotificationResponse
612 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
613 connectorId
: transactionConnectorId
,
614 status: OCPP16ChargePointStatus
.PREPARING
,
615 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
617 connectorStatus
.status = OCPP16ChargePointStatus
.PREPARING
;
618 if (chargingStation
.isChargingStationAvailable() && connectorStatus
) {
619 // Check if authorized
620 if (chargingStation
.getAuthorizeRemoteTxRequests()) {
621 let authorized
= false;
623 chargingStation
.getLocalAuthListEnabled() &&
624 chargingStation
.hasAuthorizedTags() &&
625 chargingStation
.authorizedTagsCache
627 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
629 .find((value
) => value
=== commandPayload
.idTag
)
631 connectorStatus
.localAuthorizeIdTag
= commandPayload
.idTag
;
632 connectorStatus
.idTagLocalAuthorized
= true;
634 } else if (chargingStation
.getMayAuthorizeAtRemoteStart()) {
635 connectorStatus
.authorizeIdTag
= commandPayload
.idTag
;
636 const authorizeResponse
: OCPP16AuthorizeResponse
=
637 await chargingStation
.ocppRequestService
.requestHandler
<
638 OCPP16AuthorizeRequest
,
639 OCPP16AuthorizeResponse
640 >(chargingStation
, OCPP16RequestCommand
.AUTHORIZE
, {
641 idTag
: commandPayload
.idTag
,
643 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
648 `${chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`
652 // Authorization successful, start transaction
654 this.setRemoteStartTransactionChargingProfile(
656 transactionConnectorId
,
657 commandPayload
.chargingProfile
660 connectorStatus
.transactionRemoteStarted
= true;
663 await chargingStation
.ocppRequestService
.requestHandler
<
664 OCPP16StartTransactionRequest
,
665 OCPP16StartTransactionResponse
666 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
667 connectorId
: transactionConnectorId
,
668 idTag
: commandPayload
.idTag
,
670 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
673 chargingStation
.logPrefix() +
674 ' Transaction remotely STARTED on ' +
675 chargingStation
.stationInfo
.chargingStationId
+
677 transactionConnectorId
.toString() +
681 return Constants
.OCPP_RESPONSE_ACCEPTED
;
683 return this.notifyRemoteStartTransactionRejected(
685 transactionConnectorId
,
689 return this.notifyRemoteStartTransactionRejected(
691 transactionConnectorId
,
695 return this.notifyRemoteStartTransactionRejected(
697 transactionConnectorId
,
701 // No authorization check required, start transaction
703 this.setRemoteStartTransactionChargingProfile(
705 transactionConnectorId
,
706 commandPayload
.chargingProfile
709 connectorStatus
.transactionRemoteStarted
= true;
712 await chargingStation
.ocppRequestService
.requestHandler
<
713 OCPP16StartTransactionRequest
,
714 OCPP16StartTransactionResponse
715 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
716 connectorId
: transactionConnectorId
,
717 idTag
: commandPayload
.idTag
,
719 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
722 chargingStation
.logPrefix() +
723 ' Transaction remotely STARTED on ' +
724 chargingStation
.stationInfo
.chargingStationId
+
726 transactionConnectorId
.toString() +
730 return Constants
.OCPP_RESPONSE_ACCEPTED
;
732 return this.notifyRemoteStartTransactionRejected(
734 transactionConnectorId
,
738 return this.notifyRemoteStartTransactionRejected(
740 transactionConnectorId
,
744 return this.notifyRemoteStartTransactionRejected(
746 transactionConnectorId
,
750 return this.notifyRemoteStartTransactionRejected(
752 transactionConnectorId
,
757 private async notifyRemoteStartTransactionRejected(
758 chargingStation
: ChargingStation
,
761 ): Promise
<DefaultResponse
> {
763 chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
765 await chargingStation
.ocppRequestService
.requestHandler
<
766 OCPP16StatusNotificationRequest
,
767 OCPP16StatusNotificationResponse
768 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
770 status: OCPP16ChargePointStatus
.AVAILABLE
,
771 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
773 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
776 chargingStation
.logPrefix() +
777 ' Remote starting transaction REJECTED on connector Id ' +
778 connectorId
.toString() +
782 chargingStation
.getConnectorStatus(connectorId
).availability
+
784 chargingStation
.getConnectorStatus(connectorId
).status
786 return Constants
.OCPP_RESPONSE_REJECTED
;
789 private setRemoteStartTransactionChargingProfile(
790 chargingStation
: ChargingStation
,
792 cp
: OCPP16ChargingProfile
794 if (cp
&& cp
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
795 chargingStation
.setChargingProfile(connectorId
, cp
);
797 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}, dump their stack: %j`,
798 chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
801 } else if (cp
&& cp
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
803 `${chargingStation.logPrefix()} Not allowed to set ${
804 cp.chargingProfilePurpose
805 } charging profile(s) at remote start transaction`
813 private async handleRequestRemoteStopTransaction(
814 chargingStation
: ChargingStation
,
815 commandPayload
: RemoteStopTransactionRequest
816 ): Promise
<DefaultResponse
> {
817 const transactionId
= commandPayload
.transactionId
;
818 for (const connectorId
of chargingStation
.connectors
.keys()) {
821 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
823 await chargingStation
.ocppRequestService
.requestHandler
<
824 OCPP16StatusNotificationRequest
,
825 OCPP16StatusNotificationResponse
826 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
828 status: OCPP16ChargePointStatus
.FINISHING
,
829 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
831 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.FINISHING
;
833 chargingStation
.getBeginEndMeterValues() &&
834 chargingStation
.getOcppStrictCompliance() &&
835 !chargingStation
.getOutOfOrderEndMeterValues()
837 // FIXME: Implement OCPP version agnostic helpers
838 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
841 chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
)
843 await chargingStation
.ocppRequestService
.requestHandler
<
844 OCPP16MeterValuesRequest
,
845 OCPP16MeterValuesResponse
846 >(chargingStation
, OCPP16RequestCommand
.METER_VALUES
, {
849 meterValue
: [transactionEndMeterValue
],
852 await chargingStation
.ocppRequestService
.requestHandler
<
853 OCPP16StopTransactionRequest
,
854 OCPP16StopTransactionResponse
855 >(chargingStation
, OCPP16RequestCommand
.STOP_TRANSACTION
, {
857 meterStop
: chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
858 idTag
: chargingStation
.getTransactionIdTag(transactionId
),
860 return Constants
.OCPP_RESPONSE_ACCEPTED
;
864 chargingStation
.logPrefix() +
865 ' Trying to remote stop a non existing transaction ' +
866 transactionId
.toString()
868 return Constants
.OCPP_RESPONSE_REJECTED
;
871 private async handleRequestGetDiagnostics(
872 chargingStation
: ChargingStation
,
873 commandPayload
: GetDiagnosticsRequest
874 ): Promise
<GetDiagnosticsResponse
> {
876 !OCPP16ServiceUtils
.checkFeatureProfile(
878 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
879 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
882 return Constants
.OCPP_RESPONSE_EMPTY
;
885 chargingStation
.logPrefix() +
887 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
+
888 ' request received: %j',
891 const uri
= new URL(commandPayload
.location
);
892 if (uri
.protocol
.startsWith('ftp:')) {
893 let ftpClient
: Client
;
896 .readdirSync(path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'))
897 .filter((file
) => file
.endsWith('.log'))
898 .map((file
) => path
.join('./', file
));
899 const diagnosticsArchive
= chargingStation
.stationInfo
.chargingStationId
+ '_logs.tar.gz';
900 tar
.create({ gzip
: true }, logFiles
).pipe(fs
.createWriteStream(diagnosticsArchive
));
901 ftpClient
= new Client();
902 const accessResponse
= await ftpClient
.access({
904 ...(!Utils
.isEmptyString(uri
.port
) && { port
: Utils
.convertToInt(uri
.port
) }),
905 ...(!Utils
.isEmptyString(uri
.username
) && { user
: uri
.username
}),
906 ...(!Utils
.isEmptyString(uri
.password
) && { password
: uri
.password
}),
908 let uploadResponse
: FTPResponse
;
909 if (accessResponse
.code
=== 220) {
910 // eslint-disable-next-line @typescript-eslint/no-misused-promises
911 ftpClient
.trackProgress(async (info
) => {
913 `${chargingStation.logPrefix()} ${
915 } bytes transferred from diagnostics archive ${info.name}`
917 await chargingStation
.ocppRequestService
.requestHandler
<
918 DiagnosticsStatusNotificationRequest
,
919 DiagnosticsStatusNotificationResponse
920 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
921 status: OCPP16DiagnosticsStatus
.Uploading
,
924 uploadResponse
= await ftpClient
.uploadFrom(
926 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'),
929 uri
.pathname
+ diagnosticsArchive
931 if (uploadResponse
.code
=== 226) {
932 await chargingStation
.ocppRequestService
.requestHandler
<
933 DiagnosticsStatusNotificationRequest
,
934 DiagnosticsStatusNotificationResponse
935 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
936 status: OCPP16DiagnosticsStatus
.Uploaded
,
941 return { fileName
: diagnosticsArchive
};
944 ErrorType
.GENERIC_ERROR
,
945 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
946 uploadResponse?.code && '|' + uploadResponse?.code.toString()
948 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
952 ErrorType
.GENERIC_ERROR
,
953 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
954 uploadResponse?.code && '|' + uploadResponse?.code.toString()
956 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
959 await chargingStation
.ocppRequestService
.requestHandler
<
960 DiagnosticsStatusNotificationRequest
,
961 DiagnosticsStatusNotificationResponse
962 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
963 status: OCPP16DiagnosticsStatus
.UploadFailed
,
968 return this.handleIncomingRequestError(
970 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
972 { errorResponse
: Constants
.OCPP_RESPONSE_EMPTY
}
977 `${chargingStation.logPrefix()} Unsupported protocol ${
979 } to transfer the diagnostic logs archive`
981 await chargingStation
.ocppRequestService
.requestHandler
<
982 DiagnosticsStatusNotificationRequest
,
983 DiagnosticsStatusNotificationResponse
984 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
985 status: OCPP16DiagnosticsStatus
.UploadFailed
,
987 return Constants
.OCPP_RESPONSE_EMPTY
;
991 private handleRequestTriggerMessage(
992 chargingStation
: ChargingStation
,
993 commandPayload
: OCPP16TriggerMessageRequest
994 ): OCPP16TriggerMessageResponse
{
996 !OCPP16ServiceUtils
.checkFeatureProfile(
998 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
999 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1002 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1004 // TODO: factor out the check on connector id
1005 if (commandPayload
?.connectorId
< 0) {
1007 `${chargingStation.logPrefix()} ${
1008 OCPP16IncomingRequestCommand.TRIGGER_MESSAGE
1009 } incoming request received with invalid connectorId ${commandPayload.connectorId}`
1011 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1014 switch (commandPayload
.requestedMessage
) {
1015 case MessageTrigger
.BootNotification
:
1017 chargingStation
.ocppRequestService
1018 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1020 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1022 chargePointModel
: chargingStation
.getBootNotificationRequest().chargePointModel
,
1023 chargePointVendor
: chargingStation
.getBootNotificationRequest().chargePointVendor
,
1024 chargeBoxSerialNumber
:
1025 chargingStation
.getBootNotificationRequest().chargeBoxSerialNumber
,
1026 firmwareVersion
: chargingStation
.getBootNotificationRequest().firmwareVersion
,
1027 chargePointSerialNumber
:
1028 chargingStation
.getBootNotificationRequest().chargePointSerialNumber
,
1029 iccid
: chargingStation
.getBootNotificationRequest().iccid
,
1030 imsi
: chargingStation
.getBootNotificationRequest().imsi
,
1031 meterSerialNumber
: chargingStation
.getBootNotificationRequest().meterSerialNumber
,
1032 meterType
: chargingStation
.getBootNotificationRequest().meterType
,
1034 { skipBufferingOnError
: true, triggerMessage
: true }
1037 chargingStation
.bootNotificationResponse
= value
;
1040 /* This is intentional */
1042 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1043 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1044 case MessageTrigger
.Heartbeat
:
1046 chargingStation
.ocppRequestService
1047 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1049 OCPP16RequestCommand
.HEARTBEAT
,
1052 triggerMessage
: true,
1056 /* This is intentional */
1058 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1059 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1060 case MessageTrigger
.StatusNotification
:
1062 if (commandPayload
?.connectorId
) {
1063 chargingStation
.ocppRequestService
1064 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1066 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1068 connectorId
: commandPayload
.connectorId
,
1069 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1070 status: chargingStation
.getConnectorStatus(commandPayload
.connectorId
).status,
1073 triggerMessage
: true,
1077 /* This is intentional */
1080 for (const connectorId
of chargingStation
.connectors
.keys()) {
1081 chargingStation
.ocppRequestService
1083 OCPP16StatusNotificationRequest
,
1084 OCPP16StatusNotificationResponse
1087 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1090 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1091 status: chargingStation
.getConnectorStatus(connectorId
).status,
1094 triggerMessage
: true,
1098 /* This is intentional */
1102 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1103 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1105 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1108 return this.handleIncomingRequestError(
1110 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1112 { errorResponse
: Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
}