1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
4 import path from
'path';
5 import { URL
, fileURLToPath
} from
'url';
7 import type { JSONSchemaType
} from
'ajv';
8 import { Client
, type FTPResponse
} from
'basic-ftp';
11 import OCPPError from
'../../../exception/OCPPError';
12 import type { JsonObject
, JsonType
} from
'../../../types/JsonType';
13 import { OCPP16ChargePointErrorCode
} from
'../../../types/ocpp/1.6/ChargePointErrorCode';
14 import { OCPP16ChargePointStatus
} from
'../../../types/ocpp/1.6/ChargePointStatus';
16 ChargingProfilePurposeType
,
17 type OCPP16ChargingProfile
,
18 } from
'../../../types/ocpp/1.6/ChargingProfile';
20 OCPP16StandardParametersKey
,
21 OCPP16SupportedFeatureProfiles
,
22 } from
'../../../types/ocpp/1.6/Configuration';
23 import { OCPP16DiagnosticsStatus
} from
'../../../types/ocpp/1.6/DiagnosticsStatus';
25 type ChangeAvailabilityRequest
,
26 type ChangeConfigurationRequest
,
27 type ClearChargingProfileRequest
,
28 type DiagnosticsStatusNotificationRequest
,
29 type GetConfigurationRequest
,
30 type GetDiagnosticsRequest
,
31 OCPP16AvailabilityType
,
32 type OCPP16BootNotificationRequest
,
33 type OCPP16ClearCacheRequest
,
34 type OCPP16DataTransferRequest
,
35 OCPP16DataTransferVendorId
,
36 type OCPP16HeartbeatRequest
,
37 OCPP16IncomingRequestCommand
,
40 type OCPP16StatusNotificationRequest
,
41 type OCPP16TriggerMessageRequest
,
42 type OCPP16UpdateFirmwareRequest
,
43 type RemoteStartTransactionRequest
,
44 type RemoteStopTransactionRequest
,
46 type SetChargingProfileRequest
,
47 type UnlockConnectorRequest
,
48 } from
'../../../types/ocpp/1.6/Requests';
50 type ChangeAvailabilityResponse
,
51 type ChangeConfigurationResponse
,
52 type ClearChargingProfileResponse
,
53 type DiagnosticsStatusNotificationResponse
,
54 type GetConfigurationResponse
,
55 type GetDiagnosticsResponse
,
56 type OCPP16BootNotificationResponse
,
57 type OCPP16DataTransferResponse
,
58 OCPP16DataTransferStatus
,
59 type OCPP16HeartbeatResponse
,
60 type OCPP16StatusNotificationResponse
,
61 type OCPP16TriggerMessageResponse
,
62 type OCPP16UpdateFirmwareResponse
,
63 type SetChargingProfileResponse
,
64 type UnlockConnectorResponse
,
65 } from
'../../../types/ocpp/1.6/Responses';
67 OCPP16AuthorizationStatus
,
68 type OCPP16AuthorizeRequest
,
69 type OCPP16AuthorizeResponse
,
70 type OCPP16StartTransactionRequest
,
71 type OCPP16StartTransactionResponse
,
72 OCPP16StopTransactionReason
,
73 } from
'../../../types/ocpp/1.6/Transaction';
74 import type { OCPPConfigurationKey
} from
'../../../types/ocpp/Configuration';
75 import { ErrorType
} from
'../../../types/ocpp/ErrorType';
76 import type { IncomingRequestHandler
} from
'../../../types/ocpp/Requests';
77 import type { DefaultResponse
} from
'../../../types/ocpp/Responses';
78 import Constants from
'../../../utils/Constants';
79 import logger from
'../../../utils/Logger';
80 import Utils from
'../../../utils/Utils';
81 import type ChargingStation from
'../../ChargingStation';
82 import { ChargingStationConfigurationUtils
} from
'../../ChargingStationConfigurationUtils';
83 import { ChargingStationUtils
} from
'../../ChargingStationUtils';
84 import OCPPIncomingRequestService from
'../OCPPIncomingRequestService';
85 import { OCPP16ServiceUtils
} from
'./OCPP16ServiceUtils';
87 const moduleName
= 'OCPP16IncomingRequestService';
89 export default class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
90 private incomingRequestHandlers
: Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>;
91 private jsonSchemas
: Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>;
93 public constructor() {
94 if (new.target
?.name
=== moduleName
) {
95 throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
98 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
99 [OCPP16IncomingRequestCommand
.RESET
, this.handleRequestReset
.bind(this)],
100 [OCPP16IncomingRequestCommand
.CLEAR_CACHE
, this.handleRequestClearCache
.bind(this)],
101 [OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
, this.handleRequestUnlockConnector
.bind(this)],
103 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
104 this.handleRequestGetConfiguration
.bind(this),
107 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
108 this.handleRequestChangeConfiguration
.bind(this),
111 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
112 this.handleRequestSetChargingProfile
.bind(this),
115 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
116 this.handleRequestClearChargingProfile
.bind(this),
119 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
120 this.handleRequestChangeAvailability
.bind(this),
123 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
124 this.handleRequestRemoteStartTransaction
.bind(this),
127 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
128 this.handleRequestRemoteStopTransaction
.bind(this),
130 [OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
, this.handleRequestGetDiagnostics
.bind(this)],
131 [OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
, this.handleRequestTriggerMessage
.bind(this)],
132 [OCPP16IncomingRequestCommand
.DATA_TRANSFER
, this.handleRequestDataTransfer
.bind(this)],
133 // [OCPP16IncomingRequestCommand.UPDATE_FIRMWARE, this.handleRequestUpdateFirmware.bind(this)],
135 this.jsonSchemas
= new Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>([
137 OCPP16IncomingRequestCommand
.RESET
,
141 path
.dirname(fileURLToPath(import.meta
.url
)),
142 '../../../assets/json-schemas/ocpp/1.6/Reset.json'
146 ) as JSONSchemaType
<ResetRequest
>,
149 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
153 path
.dirname(fileURLToPath(import.meta
.url
)),
154 '../../../assets/json-schemas/ocpp/1.6/ClearCache.json'
158 ) as JSONSchemaType
<OCPP16ClearCacheRequest
>,
161 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
165 path
.dirname(fileURLToPath(import.meta
.url
)),
166 '../../../assets/json-schemas/ocpp/1.6/UnlockConnector.json'
170 ) as JSONSchemaType
<UnlockConnectorRequest
>,
173 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
177 path
.dirname(fileURLToPath(import.meta
.url
)),
178 '../../../assets/json-schemas/ocpp/1.6/GetConfiguration.json'
182 ) as JSONSchemaType
<GetConfigurationRequest
>,
185 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
189 path
.dirname(fileURLToPath(import.meta
.url
)),
190 '../../../assets/json-schemas/ocpp/1.6/ChangeConfiguration.json'
194 ) as JSONSchemaType
<ChangeConfigurationRequest
>,
197 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
201 path
.dirname(fileURLToPath(import.meta
.url
)),
202 '../../../assets/json-schemas/ocpp/1.6/GetDiagnostics.json'
206 ) as JSONSchemaType
<GetDiagnosticsRequest
>,
209 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
213 path
.dirname(fileURLToPath(import.meta
.url
)),
214 '../../../assets/json-schemas/ocpp/1.6/SetChargingProfile.json'
218 ) as JSONSchemaType
<SetChargingProfileRequest
>,
221 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
225 path
.dirname(fileURLToPath(import.meta
.url
)),
226 '../../../assets/json-schemas/ocpp/1.6/ClearChargingProfile.json'
230 ) as JSONSchemaType
<ClearChargingProfileRequest
>,
233 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
237 path
.dirname(fileURLToPath(import.meta
.url
)),
238 '../../../assets/json-schemas/ocpp/1.6/ChangeAvailability.json'
242 ) as JSONSchemaType
<ChangeAvailabilityRequest
>,
245 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
249 path
.dirname(fileURLToPath(import.meta
.url
)),
250 '../../../assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json'
254 ) as JSONSchemaType
<RemoteStartTransactionRequest
>,
257 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
261 path
.dirname(fileURLToPath(import.meta
.url
)),
262 '../../../assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json'
266 ) as JSONSchemaType
<RemoteStopTransactionRequest
>,
269 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
273 path
.dirname(fileURLToPath(import.meta
.url
)),
274 '../../../assets/json-schemas/ocpp/1.6/TriggerMessage.json'
278 ) as JSONSchemaType
<OCPP16TriggerMessageRequest
>,
281 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
285 path
.dirname(fileURLToPath(import.meta
.url
)),
286 '../../../assets/json-schemas/ocpp/1.6/DataTransfer.json'
290 ) as JSONSchemaType
<OCPP16DataTransferRequest
>,
293 this.validatePayload
.bind(this);
296 public async incomingRequestHandler(
297 chargingStation
: ChargingStation
,
299 commandName
: OCPP16IncomingRequestCommand
,
300 commandPayload
: JsonType
302 let response
: JsonType
;
304 chargingStation
.getOcppStrictCompliance() === true &&
305 chargingStation
.isInPendingState() === true &&
306 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
307 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
310 ErrorType
.SECURITY_ERROR
,
311 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
315 )} while the charging station is in pending state on the central server`,
321 chargingStation
.isRegistered() === true ||
322 (chargingStation
.getOcppStrictCompliance() === false &&
323 chargingStation
.isInUnknownState() === true)
326 this.incomingRequestHandlers
.has(commandName
) === true &&
327 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
) === true
330 this.validatePayload(chargingStation
, commandName
, commandPayload
);
331 // Call the method to build the response
332 response
= await this.incomingRequestHandlers
.get(commandName
)(
339 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
347 ErrorType
.NOT_IMPLEMENTED
,
348 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
359 ErrorType
.SECURITY_ERROR
,
360 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
364 )} while the charging station is not registered on the central server.`,
369 // Send the built response
370 await chargingStation
.ocppRequestService
.sendResponse(
378 private validatePayload(
379 chargingStation
: ChargingStation
,
380 commandName
: OCPP16IncomingRequestCommand
,
381 commandPayload
: JsonType
383 if (this.jsonSchemas
.has(commandName
)) {
384 return this.validateIncomingRequestPayload(
387 this.jsonSchemas
.get(commandName
),
392 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command ${commandName} PDU validation`
397 // Simulate charging station restart
398 private handleRequestReset(
399 chargingStation
: ChargingStation
,
400 commandPayload
: ResetRequest
404 chargingStation
.reset
.bind(chargingStation
) as (
405 this: ChargingStation
,
409 (commandPayload
.type + 'Reset') as OCPP16StopTransactionReason
412 /* This is intentional */
415 `${chargingStation.logPrefix()} ${
417 } reset command received, simulating it. The station will be back online in ${Utils.formatDurationMilliSeconds(
418 chargingStation.stationInfo.resetTime
421 return Constants
.OCPP_RESPONSE_ACCEPTED
;
424 private handleRequestClearCache(chargingStation
: ChargingStation
): DefaultResponse
{
425 chargingStation
.authorizedTagsCache
.deleteAuthorizedTags(
426 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
428 return Constants
.OCPP_RESPONSE_ACCEPTED
;
431 private async handleRequestUnlockConnector(
432 chargingStation
: ChargingStation
,
433 commandPayload
: UnlockConnectorRequest
434 ): Promise
<UnlockConnectorResponse
> {
435 const connectorId
= commandPayload
.connectorId
;
436 if (chargingStation
.connectors
.has(connectorId
) === false) {
438 `${chargingStation.logPrefix()} Trying to unlock a non existing connector Id ${connectorId.toString()}`
440 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
442 if (connectorId
=== 0) {
444 chargingStation
.logPrefix() + ' Trying to unlock connector Id ' + connectorId
.toString()
446 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
448 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
449 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
451 OCPP16StopTransactionReason
.UNLOCK_COMMAND
453 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
454 return Constants
.OCPP_RESPONSE_UNLOCKED
;
456 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
458 await chargingStation
.ocppRequestService
.requestHandler
<
459 OCPP16StatusNotificationRequest
,
460 OCPP16StatusNotificationResponse
461 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
463 status: OCPP16ChargePointStatus
.AVAILABLE
,
464 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
466 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
467 return Constants
.OCPP_RESPONSE_UNLOCKED
;
470 private handleRequestGetConfiguration(
471 chargingStation
: ChargingStation
,
472 commandPayload
: GetConfigurationRequest
473 ): GetConfigurationResponse
{
474 const configurationKey
: OCPPConfigurationKey
[] = [];
475 const unknownKey
: string[] = [];
476 if (Utils
.isEmptyArray(commandPayload
.key
) === true) {
477 for (const configuration
of chargingStation
.ocppConfiguration
.configurationKey
) {
478 if (Utils
.isUndefined(configuration
.visible
) === true) {
479 configuration
.visible
= true;
481 if (configuration
.visible
=== false) {
484 configurationKey
.push({
485 key
: configuration
.key
,
486 readonly: configuration
.readonly,
487 value
: configuration
.value
,
491 for (const key
of commandPayload
.key
) {
492 const keyFound
= ChargingStationConfigurationUtils
.getConfigurationKey(
497 if (Utils
.isUndefined(keyFound
.visible
) === true) {
498 keyFound
.visible
= true;
500 if (keyFound
.visible
=== false) {
503 configurationKey
.push({
505 readonly: keyFound
.readonly,
506 value
: keyFound
.value
,
509 unknownKey
.push(key
);
519 private handleRequestChangeConfiguration(
520 chargingStation
: ChargingStation
,
521 commandPayload
: ChangeConfigurationRequest
522 ): ChangeConfigurationResponse
{
523 const keyToChange
= ChargingStationConfigurationUtils
.getConfigurationKey(
529 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
530 } else if (keyToChange
&& keyToChange
.readonly) {
531 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
532 } else if (keyToChange
&& !keyToChange
.readonly) {
533 let valueChanged
= false;
534 if (keyToChange
.value
!== commandPayload
.value
) {
535 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
538 commandPayload
.value
,
543 let triggerHeartbeatRestart
= false;
544 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
545 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
547 OCPP16StandardParametersKey
.HeartbeatInterval
,
550 triggerHeartbeatRestart
= true;
552 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
553 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
555 OCPP16StandardParametersKey
.HeartBeatInterval
,
558 triggerHeartbeatRestart
= true;
560 if (triggerHeartbeatRestart
) {
561 chargingStation
.restartHeartbeat();
563 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
564 chargingStation
.restartWebSocketPing();
566 if (keyToChange
.reboot
) {
567 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
569 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
573 private handleRequestSetChargingProfile(
574 chargingStation
: ChargingStation
,
575 commandPayload
: SetChargingProfileRequest
576 ): SetChargingProfileResponse
{
578 OCPP16ServiceUtils
.checkFeatureProfile(
580 OCPP16SupportedFeatureProfiles
.SmartCharging
,
581 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
584 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
586 if (chargingStation
.connectors
.has(commandPayload
.connectorId
) === false) {
588 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${
589 commandPayload.connectorId
592 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
595 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
596 ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
597 commandPayload
.connectorId
!== 0
599 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
602 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
603 ChargingProfilePurposeType
.TX_PROFILE
&&
604 (commandPayload
.connectorId
=== 0 ||
605 chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
===
609 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${
610 commandPayload.connectorId
611 } without a started transaction`
613 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
615 OCPP16ServiceUtils
.setChargingProfile(
617 commandPayload
.connectorId
,
618 commandPayload
.csChargingProfiles
621 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${
622 commandPayload.connectorId
623 }, dump their stack: %j`,
624 chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
626 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
629 private handleRequestClearChargingProfile(
630 chargingStation
: ChargingStation
,
631 commandPayload
: ClearChargingProfileRequest
632 ): ClearChargingProfileResponse
{
634 OCPP16ServiceUtils
.checkFeatureProfile(
636 OCPP16SupportedFeatureProfiles
.SmartCharging
,
637 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
640 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
642 if (chargingStation
.connectors
.has(commandPayload
.connectorId
) === false) {
644 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${
645 commandPayload.connectorId
648 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
650 const connectorStatus
= chargingStation
.getConnectorStatus(commandPayload
.connectorId
);
651 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(connectorStatus
.chargingProfiles
)) {
652 connectorStatus
.chargingProfiles
= [];
654 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${
655 commandPayload.connectorId
656 }, dump their stack: %j`,
657 connectorStatus
.chargingProfiles
659 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
661 if (!commandPayload
.connectorId
) {
662 let clearedCP
= false;
663 for (const connectorId
of chargingStation
.connectors
.keys()) {
664 if (!Utils
.isEmptyArray(chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
)) {
666 .getConnectorStatus(connectorId
)
667 .chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
668 let clearCurrentCP
= false;
669 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
670 clearCurrentCP
= true;
673 !commandPayload
.chargingProfilePurpose
&&
674 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
676 clearCurrentCP
= true;
679 !chargingProfile
.stackLevel
&&
680 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
682 clearCurrentCP
= true;
685 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&&
686 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
688 clearCurrentCP
= true;
690 if (clearCurrentCP
) {
691 connectorStatus
.chargingProfiles
.splice(index
, 1);
693 `${chargingStation.logPrefix()} Matching charging profile(s) cleared on connector id ${
694 commandPayload.connectorId
695 }, dump their stack: %j`,
696 connectorStatus
.chargingProfiles
704 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
707 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
710 private async handleRequestChangeAvailability(
711 chargingStation
: ChargingStation
,
712 commandPayload
: ChangeAvailabilityRequest
713 ): Promise
<ChangeAvailabilityResponse
> {
714 const connectorId
: number = commandPayload
.connectorId
;
715 if (chargingStation
.connectors
.has(connectorId
) === false) {
717 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`
719 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
721 const chargePointStatus
: OCPP16ChargePointStatus
=
722 commandPayload
.type === OCPP16AvailabilityType
.OPERATIVE
723 ? OCPP16ChargePointStatus
.AVAILABLE
724 : OCPP16ChargePointStatus
.UNAVAILABLE
;
725 if (connectorId
=== 0) {
726 let response
: ChangeAvailabilityResponse
= Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
727 for (const id
of chargingStation
.connectors
.keys()) {
728 if (chargingStation
.getConnectorStatus(id
)?.transactionStarted
=== true) {
729 response
= Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
731 chargingStation
.getConnectorStatus(id
).availability
= commandPayload
.type;
732 if (response
=== Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
) {
733 await chargingStation
.ocppRequestService
.requestHandler
<
734 OCPP16StatusNotificationRequest
,
735 OCPP16StatusNotificationResponse
736 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
738 status: chargePointStatus
,
739 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
741 chargingStation
.getConnectorStatus(id
).status = chargePointStatus
;
747 (chargingStation
.isChargingStationAvailable() === true ||
748 (chargingStation
.isChargingStationAvailable() === false &&
749 commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))
751 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
752 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
753 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
755 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
756 await chargingStation
.ocppRequestService
.requestHandler
<
757 OCPP16StatusNotificationRequest
,
758 OCPP16StatusNotificationResponse
759 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
761 status: chargePointStatus
,
762 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
764 chargingStation
.getConnectorStatus(connectorId
).status = chargePointStatus
;
765 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
767 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
770 private async handleRequestRemoteStartTransaction(
771 chargingStation
: ChargingStation
,
772 commandPayload
: RemoteStartTransactionRequest
773 ): Promise
<DefaultResponse
> {
774 const transactionConnectorId
= commandPayload
.connectorId
;
775 if (chargingStation
.connectors
.has(transactionConnectorId
) === true) {
776 const remoteStartTransactionLogMsg
=
777 chargingStation
.logPrefix() +
778 ' Transaction remotely STARTED on ' +
779 chargingStation
.stationInfo
.chargingStationId
+
781 transactionConnectorId
.toString() +
783 commandPayload
.idTag
+
785 await chargingStation
.ocppRequestService
.requestHandler
<
786 OCPP16StatusNotificationRequest
,
787 OCPP16StatusNotificationResponse
788 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
789 connectorId
: transactionConnectorId
,
790 status: OCPP16ChargePointStatus
.PREPARING
,
791 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
793 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
);
794 connectorStatus
.status = OCPP16ChargePointStatus
.PREPARING
;
795 if (chargingStation
.isChargingStationAvailable() === true) {
796 // Check if authorized
797 if (chargingStation
.getAuthorizeRemoteTxRequests() === true) {
798 let authorized
= false;
800 chargingStation
.getLocalAuthListEnabled() === true &&
801 chargingStation
.hasAuthorizedTags() === true &&
802 chargingStation
.authorizedTagsCache
804 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
806 .find((idTag
) => idTag
=== commandPayload
.idTag
)
808 connectorStatus
.localAuthorizeIdTag
= commandPayload
.idTag
;
809 connectorStatus
.idTagLocalAuthorized
= true;
811 } else if (chargingStation
.getMustAuthorizeAtRemoteStart() === true) {
812 connectorStatus
.authorizeIdTag
= commandPayload
.idTag
;
813 const authorizeResponse
: OCPP16AuthorizeResponse
=
814 await chargingStation
.ocppRequestService
.requestHandler
<
815 OCPP16AuthorizeRequest
,
816 OCPP16AuthorizeResponse
817 >(chargingStation
, OCPP16RequestCommand
.AUTHORIZE
, {
818 idTag
: commandPayload
.idTag
,
820 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
825 `${chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`
828 if (authorized
=== true) {
829 // Authorization successful, start transaction
831 this.setRemoteStartTransactionChargingProfile(
833 transactionConnectorId
,
834 commandPayload
.chargingProfile
837 connectorStatus
.transactionRemoteStarted
= true;
840 await chargingStation
.ocppRequestService
.requestHandler
<
841 OCPP16StartTransactionRequest
,
842 OCPP16StartTransactionResponse
843 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
844 connectorId
: transactionConnectorId
,
845 idTag
: commandPayload
.idTag
,
847 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
849 logger
.debug(remoteStartTransactionLogMsg
);
850 return Constants
.OCPP_RESPONSE_ACCEPTED
;
852 return this.notifyRemoteStartTransactionRejected(
854 transactionConnectorId
,
858 return this.notifyRemoteStartTransactionRejected(
860 transactionConnectorId
,
864 return this.notifyRemoteStartTransactionRejected(
866 transactionConnectorId
,
870 // No authorization check required, start transaction
872 this.setRemoteStartTransactionChargingProfile(
874 transactionConnectorId
,
875 commandPayload
.chargingProfile
878 connectorStatus
.transactionRemoteStarted
= true;
881 await chargingStation
.ocppRequestService
.requestHandler
<
882 OCPP16StartTransactionRequest
,
883 OCPP16StartTransactionResponse
884 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
885 connectorId
: transactionConnectorId
,
886 idTag
: commandPayload
.idTag
,
888 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
890 logger
.debug(remoteStartTransactionLogMsg
);
891 return Constants
.OCPP_RESPONSE_ACCEPTED
;
893 return this.notifyRemoteStartTransactionRejected(
895 transactionConnectorId
,
899 return this.notifyRemoteStartTransactionRejected(
901 transactionConnectorId
,
905 return this.notifyRemoteStartTransactionRejected(
907 transactionConnectorId
,
911 return this.notifyRemoteStartTransactionRejected(
913 transactionConnectorId
,
918 private async notifyRemoteStartTransactionRejected(
919 chargingStation
: ChargingStation
,
922 ): Promise
<DefaultResponse
> {
924 chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
926 await chargingStation
.ocppRequestService
.requestHandler
<
927 OCPP16StatusNotificationRequest
,
928 OCPP16StatusNotificationResponse
929 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
931 status: OCPP16ChargePointStatus
.AVAILABLE
,
932 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
934 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
937 chargingStation
.logPrefix() +
938 ' Remote starting transaction REJECTED on connector Id ' +
939 connectorId
.toString() +
942 "', availability '" +
943 chargingStation
.getConnectorStatus(connectorId
).availability
+
945 chargingStation
.getConnectorStatus(connectorId
).status +
948 return Constants
.OCPP_RESPONSE_REJECTED
;
951 private setRemoteStartTransactionChargingProfile(
952 chargingStation
: ChargingStation
,
954 cp
: OCPP16ChargingProfile
956 if (cp
&& cp
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
957 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, cp
);
959 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}, dump their stack: %j`,
960 chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
963 } else if (cp
&& cp
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
965 `${chargingStation.logPrefix()} Not allowed to set ${
966 cp.chargingProfilePurpose
967 } charging profile(s) at remote start transaction`
975 private async handleRequestRemoteStopTransaction(
976 chargingStation
: ChargingStation
,
977 commandPayload
: RemoteStopTransactionRequest
978 ): Promise
<DefaultResponse
> {
979 const transactionId
= commandPayload
.transactionId
;
980 for (const connectorId
of chargingStation
.connectors
.keys()) {
983 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
985 await chargingStation
.ocppRequestService
.requestHandler
<
986 OCPP16StatusNotificationRequest
,
987 OCPP16StatusNotificationResponse
988 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
990 status: OCPP16ChargePointStatus
.FINISHING
,
991 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
993 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.FINISHING
;
994 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
996 OCPP16StopTransactionReason
.REMOTE
998 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
999 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1001 return Constants
.OCPP_RESPONSE_REJECTED
;
1005 chargingStation
.logPrefix() +
1006 ' Trying to remote stop a non existing transaction ' +
1007 transactionId
.toString()
1009 return Constants
.OCPP_RESPONSE_REJECTED
;
1012 private handleRequestUpdateFirmware(
1013 chargingStation
: ChargingStation
,
1014 commandPayload
: OCPP16UpdateFirmwareRequest
1015 ): OCPP16UpdateFirmwareResponse
{
1017 OCPP16ServiceUtils
.checkFeatureProfile(
1019 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1020 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
1023 return Constants
.OCPP_RESPONSE_EMPTY
;
1026 chargingStation
.logPrefix() +
1028 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
+
1029 ' request received: %j',
1034 private async handleRequestGetDiagnostics(
1035 chargingStation
: ChargingStation
,
1036 commandPayload
: GetDiagnosticsRequest
1037 ): Promise
<GetDiagnosticsResponse
> {
1039 OCPP16ServiceUtils
.checkFeatureProfile(
1041 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1042 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1045 return Constants
.OCPP_RESPONSE_EMPTY
;
1048 chargingStation
.logPrefix() +
1050 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
+
1051 ' request received: %j',
1054 const uri
= new URL(commandPayload
.location
);
1055 if (uri
.protocol
.startsWith('ftp:')) {
1056 let ftpClient
: Client
;
1059 .readdirSync(path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'))
1060 .filter((file
) => file
.endsWith('.log'))
1061 .map((file
) => path
.join('./', file
));
1062 const diagnosticsArchive
= chargingStation
.stationInfo
.chargingStationId
+ '_logs.tar.gz';
1063 tar
.create({ gzip
: true }, logFiles
).pipe(fs
.createWriteStream(diagnosticsArchive
));
1064 ftpClient
= new Client();
1065 const accessResponse
= await ftpClient
.access({
1067 ...(!Utils
.isEmptyString(uri
.port
) && { port
: Utils
.convertToInt(uri
.port
) }),
1068 ...(!Utils
.isEmptyString(uri
.username
) && { user
: uri
.username
}),
1069 ...(!Utils
.isEmptyString(uri
.password
) && { password
: uri
.password
}),
1071 let uploadResponse
: FTPResponse
;
1072 if (accessResponse
.code
=== 220) {
1073 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1074 ftpClient
.trackProgress(async (info
) => {
1076 `${chargingStation.logPrefix()} ${
1078 } bytes transferred from diagnostics archive ${info.name}`
1080 await chargingStation
.ocppRequestService
.requestHandler
<
1081 DiagnosticsStatusNotificationRequest
,
1082 DiagnosticsStatusNotificationResponse
1083 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1084 status: OCPP16DiagnosticsStatus
.Uploading
,
1087 uploadResponse
= await ftpClient
.uploadFrom(
1089 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'),
1092 uri
.pathname
+ diagnosticsArchive
1094 if (uploadResponse
.code
=== 226) {
1095 await chargingStation
.ocppRequestService
.requestHandler
<
1096 DiagnosticsStatusNotificationRequest
,
1097 DiagnosticsStatusNotificationResponse
1098 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1099 status: OCPP16DiagnosticsStatus
.Uploaded
,
1104 return { fileName
: diagnosticsArchive
};
1106 throw new OCPPError(
1107 ErrorType
.GENERIC_ERROR
,
1108 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1109 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1111 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1114 throw new OCPPError(
1115 ErrorType
.GENERIC_ERROR
,
1116 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1117 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1119 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1122 await chargingStation
.ocppRequestService
.requestHandler
<
1123 DiagnosticsStatusNotificationRequest
,
1124 DiagnosticsStatusNotificationResponse
1125 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1126 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1131 return this.handleIncomingRequestError(
1133 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1135 { errorResponse
: Constants
.OCPP_RESPONSE_EMPTY
}
1140 `${chargingStation.logPrefix()} Unsupported protocol ${
1142 } to transfer the diagnostic logs archive`
1144 await chargingStation
.ocppRequestService
.requestHandler
<
1145 DiagnosticsStatusNotificationRequest
,
1146 DiagnosticsStatusNotificationResponse
1147 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1148 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1150 return Constants
.OCPP_RESPONSE_EMPTY
;
1154 private handleRequestTriggerMessage(
1155 chargingStation
: ChargingStation
,
1156 commandPayload
: OCPP16TriggerMessageRequest
1157 ): OCPP16TriggerMessageResponse
{
1159 !OCPP16ServiceUtils
.checkFeatureProfile(
1161 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1162 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1164 !OCPP16ServiceUtils
.isMessageTriggerSupported(
1166 commandPayload
.requestedMessage
1169 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1172 !OCPP16ServiceUtils
.isConnectorIdValid(
1174 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1175 commandPayload
.connectorId
1178 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1181 switch (commandPayload
.requestedMessage
) {
1182 case OCPP16MessageTrigger
.BootNotification
:
1184 chargingStation
.ocppRequestService
1185 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1187 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1188 chargingStation
.bootNotificationRequest
,
1189 { skipBufferingOnError
: true, triggerMessage
: true }
1191 .then((response
) => {
1192 chargingStation
.bootNotificationResponse
= response
;
1195 /* This is intentional */
1197 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1198 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1199 case OCPP16MessageTrigger
.Heartbeat
:
1201 chargingStation
.ocppRequestService
1202 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1204 OCPP16RequestCommand
.HEARTBEAT
,
1207 triggerMessage
: true,
1211 /* This is intentional */
1213 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1214 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1215 case OCPP16MessageTrigger
.StatusNotification
:
1217 if (commandPayload
?.connectorId
) {
1218 chargingStation
.ocppRequestService
1219 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1221 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1223 connectorId
: commandPayload
.connectorId
,
1224 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1225 status: chargingStation
.getConnectorStatus(commandPayload
.connectorId
).status,
1228 triggerMessage
: true,
1232 /* This is intentional */
1235 for (const connectorId
of chargingStation
.connectors
.keys()) {
1236 chargingStation
.ocppRequestService
1238 OCPP16StatusNotificationRequest
,
1239 OCPP16StatusNotificationResponse
1242 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1245 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1246 status: chargingStation
.getConnectorStatus(connectorId
).status,
1249 triggerMessage
: true,
1253 /* This is intentional */
1257 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1258 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1260 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1263 return this.handleIncomingRequestError(
1265 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1267 { errorResponse
: Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
}
1272 private handleRequestDataTransfer(
1273 chargingStation
: ChargingStation
,
1274 commandPayload
: OCPP16DataTransferRequest
1275 ): OCPP16DataTransferResponse
{
1277 if (Object.values(OCPP16DataTransferVendorId
).includes(commandPayload
.vendorId
)) {
1279 status: OCPP16DataTransferStatus
.ACCEPTED
,
1283 status: OCPP16DataTransferStatus
.UNKNOWN_VENDOR_ID
,
1286 return this.handleIncomingRequestError(
1288 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1290 { errorResponse
: Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
}