1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
4 import path from
'path';
5 import { URL
, fileURLToPath
} from
'url';
7 import type { JSONSchemaType
} from
'ajv';
8 import { Client
, 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 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 ChangeAvailabilityRequest
,
26 ChangeConfigurationRequest
,
27 ClearChargingProfileRequest
,
28 DiagnosticsStatusNotificationRequest
,
29 GetConfigurationRequest
,
30 GetDiagnosticsRequest
,
31 OCPP16AvailabilityType
,
32 OCPP16BootNotificationRequest
,
33 OCPP16ClearCacheRequest
,
34 OCPP16HeartbeatRequest
,
35 OCPP16IncomingRequestCommand
,
38 OCPP16StatusNotificationRequest
,
39 OCPP16TriggerMessageRequest
,
40 RemoteStartTransactionRequest
,
41 RemoteStopTransactionRequest
,
43 SetChargingProfileRequest
,
44 UnlockConnectorRequest
,
45 } from
'../../../types/ocpp/1.6/Requests';
47 ChangeAvailabilityResponse
,
48 ChangeConfigurationResponse
,
49 ClearChargingProfileResponse
,
50 DiagnosticsStatusNotificationResponse
,
51 GetConfigurationResponse
,
52 GetDiagnosticsResponse
,
53 OCPP16BootNotificationResponse
,
54 OCPP16HeartbeatResponse
,
55 OCPP16StatusNotificationResponse
,
56 OCPP16TriggerMessageResponse
,
57 SetChargingProfileResponse
,
58 UnlockConnectorResponse
,
59 } from
'../../../types/ocpp/1.6/Responses';
61 OCPP16AuthorizationStatus
,
62 OCPP16AuthorizeRequest
,
63 OCPP16AuthorizeResponse
,
64 OCPP16StartTransactionRequest
,
65 OCPP16StartTransactionResponse
,
66 OCPP16StopTransactionReason
,
67 } from
'../../../types/ocpp/1.6/Transaction';
68 import type { OCPPConfigurationKey
} from
'../../../types/ocpp/Configuration';
69 import { ErrorType
} from
'../../../types/ocpp/ErrorType';
70 import type { IncomingRequestHandler
} from
'../../../types/ocpp/Requests';
71 import type { DefaultResponse
} from
'../../../types/ocpp/Responses';
72 import Constants from
'../../../utils/Constants';
73 import logger from
'../../../utils/Logger';
74 import Utils from
'../../../utils/Utils';
75 import type ChargingStation from
'../../ChargingStation';
76 import { ChargingStationConfigurationUtils
} from
'../../ChargingStationConfigurationUtils';
77 import { ChargingStationUtils
} from
'../../ChargingStationUtils';
78 import OCPPIncomingRequestService from
'../OCPPIncomingRequestService';
79 import { OCPP16ServiceUtils
} from
'./OCPP16ServiceUtils';
81 const moduleName
= 'OCPP16IncomingRequestService';
83 export default class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
84 private incomingRequestHandlers
: Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>;
85 private jsonSchemas
: Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>;
87 public constructor() {
88 if (new.target
?.name
=== moduleName
) {
89 throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
92 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
93 [OCPP16IncomingRequestCommand
.RESET
, this.handleRequestReset
.bind(this)],
94 [OCPP16IncomingRequestCommand
.CLEAR_CACHE
, this.handleRequestClearCache
.bind(this)],
95 [OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
, this.handleRequestUnlockConnector
.bind(this)],
97 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
98 this.handleRequestGetConfiguration
.bind(this),
101 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
102 this.handleRequestChangeConfiguration
.bind(this),
105 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
106 this.handleRequestSetChargingProfile
.bind(this),
109 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
110 this.handleRequestClearChargingProfile
.bind(this),
113 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
114 this.handleRequestChangeAvailability
.bind(this),
117 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
118 this.handleRequestRemoteStartTransaction
.bind(this),
121 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
122 this.handleRequestRemoteStopTransaction
.bind(this),
124 [OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
, this.handleRequestGetDiagnostics
.bind(this)],
125 [OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
, this.handleRequestTriggerMessage
.bind(this)],
127 this.jsonSchemas
= new Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>([
129 OCPP16IncomingRequestCommand
.RESET
,
133 path
.dirname(fileURLToPath(import.meta
.url
)),
134 '../../../assets/json-schemas/ocpp/1.6/Reset.json'
138 ) as JSONSchemaType
<ResetRequest
>,
141 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
145 path
.dirname(fileURLToPath(import.meta
.url
)),
146 '../../../assets/json-schemas/ocpp/1.6/ClearCache.json'
150 ) as JSONSchemaType
<OCPP16ClearCacheRequest
>,
153 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
157 path
.dirname(fileURLToPath(import.meta
.url
)),
158 '../../../assets/json-schemas/ocpp/1.6/UnlockConnector.json'
162 ) as JSONSchemaType
<UnlockConnectorRequest
>,
165 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
169 path
.dirname(fileURLToPath(import.meta
.url
)),
170 '../../../assets/json-schemas/ocpp/1.6/GetConfiguration.json'
174 ) as JSONSchemaType
<GetConfigurationRequest
>,
177 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
181 path
.dirname(fileURLToPath(import.meta
.url
)),
182 '../../../assets/json-schemas/ocpp/1.6/ChangeConfiguration.json'
186 ) as JSONSchemaType
<ChangeConfigurationRequest
>,
189 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
193 path
.dirname(fileURLToPath(import.meta
.url
)),
194 '../../../assets/json-schemas/ocpp/1.6/GetDiagnostics.json'
198 ) as JSONSchemaType
<GetDiagnosticsRequest
>,
201 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
205 path
.dirname(fileURLToPath(import.meta
.url
)),
206 '../../../assets/json-schemas/ocpp/1.6/SetChargingProfile.json'
210 ) as JSONSchemaType
<SetChargingProfileRequest
>,
213 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
217 path
.dirname(fileURLToPath(import.meta
.url
)),
218 '../../../assets/json-schemas/ocpp/1.6/ClearChargingProfile.json'
222 ) as JSONSchemaType
<ClearChargingProfileRequest
>,
225 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
229 path
.dirname(fileURLToPath(import.meta
.url
)),
230 '../../../assets/json-schemas/ocpp/1.6/ChangeAvailability.json'
234 ) as JSONSchemaType
<ChangeAvailabilityRequest
>,
237 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
241 path
.dirname(fileURLToPath(import.meta
.url
)),
242 '../../../assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json'
246 ) as JSONSchemaType
<RemoteStartTransactionRequest
>,
249 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
253 path
.dirname(fileURLToPath(import.meta
.url
)),
254 '../../../assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json'
258 ) as JSONSchemaType
<RemoteStopTransactionRequest
>,
261 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
265 path
.dirname(fileURLToPath(import.meta
.url
)),
266 '../../../assets/json-schemas/ocpp/1.6/TriggerMessage.json'
270 ) as JSONSchemaType
<OCPP16TriggerMessageRequest
>,
273 this.validatePayload
.bind(this);
276 public async incomingRequestHandler(
277 chargingStation
: ChargingStation
,
279 commandName
: OCPP16IncomingRequestCommand
,
280 commandPayload
: JsonType
282 let response
: JsonType
;
284 chargingStation
.getOcppStrictCompliance() === true &&
285 chargingStation
.isInPendingState() === true &&
286 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
287 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
290 ErrorType
.SECURITY_ERROR
,
291 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
295 )} while the charging station is in pending state on the central server`,
301 chargingStation
.isRegistered() === true ||
302 (chargingStation
.getOcppStrictCompliance() === false &&
303 chargingStation
.isInUnknownState() === true)
306 this.incomingRequestHandlers
.has(commandName
) === true &&
307 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
) === true
310 this.validatePayload(chargingStation
, commandName
, commandPayload
);
311 // Call the method to build the response
312 response
= await this.incomingRequestHandlers
.get(commandName
)(
319 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
327 ErrorType
.NOT_IMPLEMENTED
,
328 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
339 ErrorType
.SECURITY_ERROR
,
340 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
344 )} while the charging station is not registered on the central server.`,
349 // Send the built response
350 await chargingStation
.ocppRequestService
.sendResponse(
358 private validatePayload(
359 chargingStation
: ChargingStation
,
360 commandName
: OCPP16IncomingRequestCommand
,
361 commandPayload
: JsonType
363 if (this.jsonSchemas
.has(commandName
)) {
364 return this.validateIncomingRequestPayload(
367 this.jsonSchemas
.get(commandName
),
372 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command ${commandName} PDU validation`
377 // Simulate charging station restart
378 private handleRequestReset(
379 chargingStation
: ChargingStation
,
380 commandPayload
: ResetRequest
384 chargingStation
.reset
.bind(chargingStation
) as (
385 this: ChargingStation
,
389 (commandPayload
.type + 'Reset') as OCPP16StopTransactionReason
392 /* This is intentional */
395 `${chargingStation.logPrefix()} ${
397 } reset command received, simulating it. The station will be back online in ${Utils.formatDurationMilliSeconds(
398 chargingStation.stationInfo.resetTime
401 return Constants
.OCPP_RESPONSE_ACCEPTED
;
404 private handleRequestClearCache(chargingStation
: ChargingStation
): DefaultResponse
{
405 chargingStation
.authorizedTagsCache
.deleteAuthorizedTags(
406 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
408 return Constants
.OCPP_RESPONSE_ACCEPTED
;
411 private async handleRequestUnlockConnector(
412 chargingStation
: ChargingStation
,
413 commandPayload
: UnlockConnectorRequest
414 ): Promise
<UnlockConnectorResponse
> {
415 const connectorId
= commandPayload
.connectorId
;
416 if (chargingStation
.connectors
.has(connectorId
) === false) {
418 `${chargingStation.logPrefix()} Trying to unlock a non existing connector Id ${connectorId.toString()}`
420 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
422 if (connectorId
=== 0) {
424 chargingStation
.logPrefix() + ' Trying to unlock connector Id ' + connectorId
.toString()
426 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
428 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
429 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
431 OCPP16StopTransactionReason
.UNLOCK_COMMAND
433 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
434 return Constants
.OCPP_RESPONSE_UNLOCKED
;
436 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
438 await chargingStation
.ocppRequestService
.requestHandler
<
439 OCPP16StatusNotificationRequest
,
440 OCPP16StatusNotificationResponse
441 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
443 status: OCPP16ChargePointStatus
.AVAILABLE
,
444 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
446 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
447 return Constants
.OCPP_RESPONSE_UNLOCKED
;
450 private handleRequestGetConfiguration(
451 chargingStation
: ChargingStation
,
452 commandPayload
: GetConfigurationRequest
453 ): GetConfigurationResponse
{
454 const configurationKey
: OCPPConfigurationKey
[] = [];
455 const unknownKey
: string[] = [];
456 if (Utils
.isEmptyArray(commandPayload
.key
) === true) {
457 for (const configuration
of chargingStation
.ocppConfiguration
.configurationKey
) {
458 if (Utils
.isUndefined(configuration
.visible
) === true) {
459 configuration
.visible
= true;
461 if (configuration
.visible
=== false) {
464 configurationKey
.push({
465 key
: configuration
.key
,
466 readonly: configuration
.readonly,
467 value
: configuration
.value
,
471 for (const key
of commandPayload
.key
) {
472 const keyFound
= ChargingStationConfigurationUtils
.getConfigurationKey(
477 if (Utils
.isUndefined(keyFound
.visible
) === true) {
478 keyFound
.visible
= true;
480 if (keyFound
.visible
=== false) {
483 configurationKey
.push({
485 readonly: keyFound
.readonly,
486 value
: keyFound
.value
,
489 unknownKey
.push(key
);
499 private handleRequestChangeConfiguration(
500 chargingStation
: ChargingStation
,
501 commandPayload
: ChangeConfigurationRequest
502 ): ChangeConfigurationResponse
{
503 const keyToChange
= ChargingStationConfigurationUtils
.getConfigurationKey(
509 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
510 } else if (keyToChange
&& keyToChange
.readonly) {
511 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
512 } else if (keyToChange
&& !keyToChange
.readonly) {
513 let valueChanged
= false;
514 if (keyToChange
.value
!== commandPayload
.value
) {
515 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
518 commandPayload
.value
,
523 let triggerHeartbeatRestart
= false;
524 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
525 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
527 OCPP16StandardParametersKey
.HeartbeatInterval
,
530 triggerHeartbeatRestart
= true;
532 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
533 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
535 OCPP16StandardParametersKey
.HeartBeatInterval
,
538 triggerHeartbeatRestart
= true;
540 if (triggerHeartbeatRestart
) {
541 chargingStation
.restartHeartbeat();
543 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
544 chargingStation
.restartWebSocketPing();
546 if (keyToChange
.reboot
) {
547 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
549 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
553 private handleRequestSetChargingProfile(
554 chargingStation
: ChargingStation
,
555 commandPayload
: SetChargingProfileRequest
556 ): SetChargingProfileResponse
{
558 OCPP16ServiceUtils
.checkFeatureProfile(
560 OCPP16SupportedFeatureProfiles
.SmartCharging
,
561 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
564 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
566 if (chargingStation
.connectors
.has(commandPayload
.connectorId
) === false) {
568 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${
569 commandPayload.connectorId
572 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
575 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
576 ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
577 commandPayload
.connectorId
!== 0
579 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
582 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
583 ChargingProfilePurposeType
.TX_PROFILE
&&
584 (commandPayload
.connectorId
=== 0 ||
585 chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
===
589 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${
590 commandPayload.connectorId
591 } without a started transaction`
593 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
595 OCPP16ServiceUtils
.setChargingProfile(
597 commandPayload
.connectorId
,
598 commandPayload
.csChargingProfiles
601 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${
602 commandPayload.connectorId
603 }, dump their stack: %j`,
604 chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
606 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
609 private handleRequestClearChargingProfile(
610 chargingStation
: ChargingStation
,
611 commandPayload
: ClearChargingProfileRequest
612 ): ClearChargingProfileResponse
{
614 OCPP16ServiceUtils
.checkFeatureProfile(
616 OCPP16SupportedFeatureProfiles
.SmartCharging
,
617 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
620 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
622 if (chargingStation
.connectors
.has(commandPayload
.connectorId
) === false) {
624 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${
625 commandPayload.connectorId
628 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
630 const connectorStatus
= chargingStation
.getConnectorStatus(commandPayload
.connectorId
);
631 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(connectorStatus
.chargingProfiles
)) {
632 connectorStatus
.chargingProfiles
= [];
634 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${
635 commandPayload.connectorId
636 }, dump their stack: %j`,
637 connectorStatus
.chargingProfiles
639 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
641 if (!commandPayload
.connectorId
) {
642 let clearedCP
= false;
643 for (const connectorId
of chargingStation
.connectors
.keys()) {
644 if (!Utils
.isEmptyArray(chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
)) {
646 .getConnectorStatus(connectorId
)
647 .chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
648 let clearCurrentCP
= false;
649 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
650 clearCurrentCP
= true;
653 !commandPayload
.chargingProfilePurpose
&&
654 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
656 clearCurrentCP
= true;
659 !chargingProfile
.stackLevel
&&
660 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
662 clearCurrentCP
= true;
665 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&&
666 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
668 clearCurrentCP
= true;
670 if (clearCurrentCP
) {
671 connectorStatus
.chargingProfiles
.splice(index
, 1);
673 `${chargingStation.logPrefix()} Matching charging profile(s) cleared on connector id ${
674 commandPayload.connectorId
675 }, dump their stack: %j`,
676 connectorStatus
.chargingProfiles
684 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
687 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
690 private async handleRequestChangeAvailability(
691 chargingStation
: ChargingStation
,
692 commandPayload
: ChangeAvailabilityRequest
693 ): Promise
<ChangeAvailabilityResponse
> {
694 const connectorId
: number = commandPayload
.connectorId
;
695 if (chargingStation
.connectors
.has(connectorId
) === false) {
697 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`
699 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
701 const chargePointStatus
: OCPP16ChargePointStatus
=
702 commandPayload
.type === OCPP16AvailabilityType
.OPERATIVE
703 ? OCPP16ChargePointStatus
.AVAILABLE
704 : OCPP16ChargePointStatus
.UNAVAILABLE
;
705 if (connectorId
=== 0) {
706 let response
: ChangeAvailabilityResponse
= Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
707 for (const id
of chargingStation
.connectors
.keys()) {
708 if (chargingStation
.getConnectorStatus(id
)?.transactionStarted
=== true) {
709 response
= Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
711 chargingStation
.getConnectorStatus(id
).availability
= commandPayload
.type;
712 if (response
=== Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
) {
713 await chargingStation
.ocppRequestService
.requestHandler
<
714 OCPP16StatusNotificationRequest
,
715 OCPP16StatusNotificationResponse
716 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
718 status: chargePointStatus
,
719 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
721 chargingStation
.getConnectorStatus(id
).status = chargePointStatus
;
727 (chargingStation
.isChargingStationAvailable() === true ||
728 (chargingStation
.isChargingStationAvailable() === false &&
729 commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))
731 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
732 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
733 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
735 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
736 await chargingStation
.ocppRequestService
.requestHandler
<
737 OCPP16StatusNotificationRequest
,
738 OCPP16StatusNotificationResponse
739 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
741 status: chargePointStatus
,
742 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
744 chargingStation
.getConnectorStatus(connectorId
).status = chargePointStatus
;
745 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
747 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
750 private async handleRequestRemoteStartTransaction(
751 chargingStation
: ChargingStation
,
752 commandPayload
: RemoteStartTransactionRequest
753 ): Promise
<DefaultResponse
> {
754 const transactionConnectorId
= commandPayload
.connectorId
;
755 if (chargingStation
.connectors
.has(transactionConnectorId
) === true) {
756 const remoteStartTransactionLogMsg
=
757 chargingStation
.logPrefix() +
758 ' Transaction remotely STARTED on ' +
759 chargingStation
.stationInfo
.chargingStationId
+
761 transactionConnectorId
.toString() +
763 commandPayload
.idTag
+
765 await chargingStation
.ocppRequestService
.requestHandler
<
766 OCPP16StatusNotificationRequest
,
767 OCPP16StatusNotificationResponse
768 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
769 connectorId
: transactionConnectorId
,
770 status: OCPP16ChargePointStatus
.PREPARING
,
771 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
773 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
);
774 connectorStatus
.status = OCPP16ChargePointStatus
.PREPARING
;
775 if (chargingStation
.isChargingStationAvailable() === true) {
776 // Check if authorized
777 if (chargingStation
.getAuthorizeRemoteTxRequests() === true) {
778 let authorized
= false;
780 chargingStation
.getLocalAuthListEnabled() === true &&
781 chargingStation
.hasAuthorizedTags() === true &&
782 chargingStation
.authorizedTagsCache
784 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
786 .find((idTag
) => idTag
=== commandPayload
.idTag
)
788 connectorStatus
.localAuthorizeIdTag
= commandPayload
.idTag
;
789 connectorStatus
.idTagLocalAuthorized
= true;
791 } else if (chargingStation
.getMustAuthorizeAtRemoteStart() === true) {
792 connectorStatus
.authorizeIdTag
= commandPayload
.idTag
;
793 const authorizeResponse
: OCPP16AuthorizeResponse
=
794 await chargingStation
.ocppRequestService
.requestHandler
<
795 OCPP16AuthorizeRequest
,
796 OCPP16AuthorizeResponse
797 >(chargingStation
, OCPP16RequestCommand
.AUTHORIZE
, {
798 idTag
: commandPayload
.idTag
,
800 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
805 `${chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`
808 if (authorized
=== true) {
809 // Authorization successful, start transaction
811 this.setRemoteStartTransactionChargingProfile(
813 transactionConnectorId
,
814 commandPayload
.chargingProfile
817 connectorStatus
.transactionRemoteStarted
= true;
820 await chargingStation
.ocppRequestService
.requestHandler
<
821 OCPP16StartTransactionRequest
,
822 OCPP16StartTransactionResponse
823 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
824 connectorId
: transactionConnectorId
,
825 idTag
: commandPayload
.idTag
,
827 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
829 logger
.debug(remoteStartTransactionLogMsg
);
830 return Constants
.OCPP_RESPONSE_ACCEPTED
;
832 return this.notifyRemoteStartTransactionRejected(
834 transactionConnectorId
,
838 return this.notifyRemoteStartTransactionRejected(
840 transactionConnectorId
,
844 return this.notifyRemoteStartTransactionRejected(
846 transactionConnectorId
,
850 // No authorization check required, start transaction
852 this.setRemoteStartTransactionChargingProfile(
854 transactionConnectorId
,
855 commandPayload
.chargingProfile
858 connectorStatus
.transactionRemoteStarted
= true;
861 await chargingStation
.ocppRequestService
.requestHandler
<
862 OCPP16StartTransactionRequest
,
863 OCPP16StartTransactionResponse
864 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
865 connectorId
: transactionConnectorId
,
866 idTag
: commandPayload
.idTag
,
868 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
870 logger
.debug(remoteStartTransactionLogMsg
);
871 return Constants
.OCPP_RESPONSE_ACCEPTED
;
873 return this.notifyRemoteStartTransactionRejected(
875 transactionConnectorId
,
879 return this.notifyRemoteStartTransactionRejected(
881 transactionConnectorId
,
885 return this.notifyRemoteStartTransactionRejected(
887 transactionConnectorId
,
891 return this.notifyRemoteStartTransactionRejected(
893 transactionConnectorId
,
898 private async notifyRemoteStartTransactionRejected(
899 chargingStation
: ChargingStation
,
902 ): Promise
<DefaultResponse
> {
904 chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
906 await chargingStation
.ocppRequestService
.requestHandler
<
907 OCPP16StatusNotificationRequest
,
908 OCPP16StatusNotificationResponse
909 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
911 status: OCPP16ChargePointStatus
.AVAILABLE
,
912 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
914 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
917 chargingStation
.logPrefix() +
918 ' Remote starting transaction REJECTED on connector Id ' +
919 connectorId
.toString() +
922 "', availability '" +
923 chargingStation
.getConnectorStatus(connectorId
).availability
+
925 chargingStation
.getConnectorStatus(connectorId
).status +
928 return Constants
.OCPP_RESPONSE_REJECTED
;
931 private setRemoteStartTransactionChargingProfile(
932 chargingStation
: ChargingStation
,
934 cp
: OCPP16ChargingProfile
936 if (cp
&& cp
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
937 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, cp
);
939 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}, dump their stack: %j`,
940 chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
943 } else if (cp
&& cp
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
945 `${chargingStation.logPrefix()} Not allowed to set ${
946 cp.chargingProfilePurpose
947 } charging profile(s) at remote start transaction`
955 private async handleRequestRemoteStopTransaction(
956 chargingStation
: ChargingStation
,
957 commandPayload
: RemoteStopTransactionRequest
958 ): Promise
<DefaultResponse
> {
959 const transactionId
= commandPayload
.transactionId
;
960 for (const connectorId
of chargingStation
.connectors
.keys()) {
963 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
965 await chargingStation
.ocppRequestService
.requestHandler
<
966 OCPP16StatusNotificationRequest
,
967 OCPP16StatusNotificationResponse
968 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
970 status: OCPP16ChargePointStatus
.FINISHING
,
971 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
973 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.FINISHING
;
974 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
976 OCPP16StopTransactionReason
.REMOTE
978 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
979 return Constants
.OCPP_RESPONSE_ACCEPTED
;
981 return Constants
.OCPP_RESPONSE_REJECTED
;
985 chargingStation
.logPrefix() +
986 ' Trying to remote stop a non existing transaction ' +
987 transactionId
.toString()
989 return Constants
.OCPP_RESPONSE_REJECTED
;
992 private async handleRequestGetDiagnostics(
993 chargingStation
: ChargingStation
,
994 commandPayload
: GetDiagnosticsRequest
995 ): Promise
<GetDiagnosticsResponse
> {
997 OCPP16ServiceUtils
.checkFeatureProfile(
999 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1000 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1003 return Constants
.OCPP_RESPONSE_EMPTY
;
1006 chargingStation
.logPrefix() +
1008 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
+
1009 ' request received: %j',
1012 const uri
= new URL(commandPayload
.location
);
1013 if (uri
.protocol
.startsWith('ftp:')) {
1014 let ftpClient
: Client
;
1017 .readdirSync(path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'))
1018 .filter((file
) => file
.endsWith('.log'))
1019 .map((file
) => path
.join('./', file
));
1020 const diagnosticsArchive
= chargingStation
.stationInfo
.chargingStationId
+ '_logs.tar.gz';
1021 tar
.create({ gzip
: true }, logFiles
).pipe(fs
.createWriteStream(diagnosticsArchive
));
1022 ftpClient
= new Client();
1023 const accessResponse
= await ftpClient
.access({
1025 ...(!Utils
.isEmptyString(uri
.port
) && { port
: Utils
.convertToInt(uri
.port
) }),
1026 ...(!Utils
.isEmptyString(uri
.username
) && { user
: uri
.username
}),
1027 ...(!Utils
.isEmptyString(uri
.password
) && { password
: uri
.password
}),
1029 let uploadResponse
: FTPResponse
;
1030 if (accessResponse
.code
=== 220) {
1031 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1032 ftpClient
.trackProgress(async (info
) => {
1034 `${chargingStation.logPrefix()} ${
1036 } bytes transferred from diagnostics archive ${info.name}`
1038 await chargingStation
.ocppRequestService
.requestHandler
<
1039 DiagnosticsStatusNotificationRequest
,
1040 DiagnosticsStatusNotificationResponse
1041 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1042 status: OCPP16DiagnosticsStatus
.Uploading
,
1045 uploadResponse
= await ftpClient
.uploadFrom(
1047 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'),
1050 uri
.pathname
+ diagnosticsArchive
1052 if (uploadResponse
.code
=== 226) {
1053 await chargingStation
.ocppRequestService
.requestHandler
<
1054 DiagnosticsStatusNotificationRequest
,
1055 DiagnosticsStatusNotificationResponse
1056 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1057 status: OCPP16DiagnosticsStatus
.Uploaded
,
1062 return { fileName
: diagnosticsArchive
};
1064 throw new OCPPError(
1065 ErrorType
.GENERIC_ERROR
,
1066 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1067 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1069 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1072 throw new OCPPError(
1073 ErrorType
.GENERIC_ERROR
,
1074 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1075 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1077 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1080 await chargingStation
.ocppRequestService
.requestHandler
<
1081 DiagnosticsStatusNotificationRequest
,
1082 DiagnosticsStatusNotificationResponse
1083 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1084 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1089 return this.handleIncomingRequestError(
1091 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1093 { errorResponse
: Constants
.OCPP_RESPONSE_EMPTY
}
1098 `${chargingStation.logPrefix()} Unsupported protocol ${
1100 } to transfer the diagnostic logs archive`
1102 await chargingStation
.ocppRequestService
.requestHandler
<
1103 DiagnosticsStatusNotificationRequest
,
1104 DiagnosticsStatusNotificationResponse
1105 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1106 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1108 return Constants
.OCPP_RESPONSE_EMPTY
;
1112 private handleRequestTriggerMessage(
1113 chargingStation
: ChargingStation
,
1114 commandPayload
: OCPP16TriggerMessageRequest
1115 ): OCPP16TriggerMessageResponse
{
1117 !OCPP16ServiceUtils
.checkFeatureProfile(
1119 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1120 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1122 !OCPP16ServiceUtils
.isMessageTriggerSupported(
1124 commandPayload
.requestedMessage
1127 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1130 !OCPP16ServiceUtils
.isConnectorIdValid(
1132 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1133 commandPayload
.connectorId
1136 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1139 switch (commandPayload
.requestedMessage
) {
1140 case OCPP16MessageTrigger
.BootNotification
:
1142 chargingStation
.ocppRequestService
1143 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1145 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1146 chargingStation
.bootNotificationRequest
,
1147 { skipBufferingOnError
: true, triggerMessage
: true }
1149 .then((response
) => {
1150 chargingStation
.bootNotificationResponse
= response
;
1153 /* This is intentional */
1155 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1156 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1157 case OCPP16MessageTrigger
.Heartbeat
:
1159 chargingStation
.ocppRequestService
1160 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1162 OCPP16RequestCommand
.HEARTBEAT
,
1165 triggerMessage
: true,
1169 /* This is intentional */
1171 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1172 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1173 case OCPP16MessageTrigger
.StatusNotification
:
1175 if (commandPayload
?.connectorId
) {
1176 chargingStation
.ocppRequestService
1177 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1179 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1181 connectorId
: commandPayload
.connectorId
,
1182 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1183 status: chargingStation
.getConnectorStatus(commandPayload
.connectorId
).status,
1186 triggerMessage
: true,
1190 /* This is intentional */
1193 for (const connectorId
of chargingStation
.connectors
.keys()) {
1194 chargingStation
.ocppRequestService
1196 OCPP16StatusNotificationRequest
,
1197 OCPP16StatusNotificationResponse
1200 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1203 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1204 status: chargingStation
.getConnectorStatus(connectorId
).status,
1207 triggerMessage
: true,
1211 /* This is intentional */
1215 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1216 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1218 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1221 return this.handleIncomingRequestError(
1223 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1225 { errorResponse
: Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
}