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
,
32 OCPP16AvailabilityType
,
33 OCPP16BootNotificationRequest
,
34 OCPP16ClearCacheRequest
,
35 OCPP16HeartbeatRequest
,
36 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() &&
285 chargingStation
.isInPendingState() &&
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() ||
302 (!chargingStation
.getOcppStrictCompliance() && chargingStation
.isInUnknownState())
305 this.incomingRequestHandlers
.has(commandName
) &&
306 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
)
309 this.validatePayload(chargingStation
, commandName
, commandPayload
);
310 // Call the method to build the response
311 response
= await this.incomingRequestHandlers
.get(commandName
)(
318 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
326 ErrorType
.NOT_IMPLEMENTED
,
327 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
338 ErrorType
.SECURITY_ERROR
,
339 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
343 )} while the charging station is not registered on the central server.`,
348 // Send the built response
349 await chargingStation
.ocppRequestService
.sendResponse(
357 private validatePayload(
358 chargingStation
: ChargingStation
,
359 commandName
: OCPP16IncomingRequestCommand
,
360 commandPayload
: JsonType
362 if (this.jsonSchemas
.has(commandName
)) {
363 return this.validateIncomingRequestPayload(
366 this.jsonSchemas
.get(commandName
),
371 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command ${commandName} PDU validation`
376 // Simulate charging station restart
377 private handleRequestReset(
378 chargingStation
: ChargingStation
,
379 commandPayload
: ResetRequest
381 this.asyncResource
.runInAsyncScope(
382 chargingStation
.reset
.bind(chargingStation
) as (
383 this: ChargingStation
,
387 (commandPayload
.type + 'Reset') as OCPP16StopTransactionReason
390 `${chargingStation.logPrefix()} ${
392 } reset command received, simulating it. The station will be back online in ${Utils.formatDurationMilliSeconds(
393 chargingStation.stationInfo.resetTime
396 return Constants
.OCPP_RESPONSE_ACCEPTED
;
399 private handleRequestClearCache(chargingStation
: ChargingStation
): DefaultResponse
{
400 chargingStation
.authorizedTagsCache
.deleteAuthorizedTags(
401 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
403 return Constants
.OCPP_RESPONSE_ACCEPTED
;
406 private async handleRequestUnlockConnector(
407 chargingStation
: ChargingStation
,
408 commandPayload
: UnlockConnectorRequest
409 ): Promise
<UnlockConnectorResponse
> {
410 const connectorId
= commandPayload
.connectorId
;
411 if (connectorId
=== 0) {
413 chargingStation
.logPrefix() + ' Trying to unlock connector ' + connectorId
.toString()
415 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
417 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
418 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
420 OCPP16StopTransactionReason
.UNLOCK_COMMAND
422 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
423 return Constants
.OCPP_RESPONSE_UNLOCKED
;
425 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
427 await chargingStation
.ocppRequestService
.requestHandler
<
428 OCPP16StatusNotificationRequest
,
429 OCPP16StatusNotificationResponse
430 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
432 status: OCPP16ChargePointStatus
.AVAILABLE
,
433 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
435 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
436 return Constants
.OCPP_RESPONSE_UNLOCKED
;
439 private handleRequestGetConfiguration(
440 chargingStation
: ChargingStation
,
441 commandPayload
: GetConfigurationRequest
442 ): GetConfigurationResponse
{
443 const configurationKey
: OCPPConfigurationKey
[] = [];
444 const unknownKey
: string[] = [];
445 if (Utils
.isEmptyArray(commandPayload
.key
) === true) {
446 for (const configuration
of chargingStation
.ocppConfiguration
.configurationKey
) {
447 if (Utils
.isUndefined(configuration
.visible
) === true) {
448 configuration
.visible
= true;
450 if (configuration
.visible
=== false) {
453 configurationKey
.push({
454 key
: configuration
.key
,
455 readonly: configuration
.readonly,
456 value
: configuration
.value
,
460 for (const key
of commandPayload
.key
) {
461 const keyFound
= ChargingStationConfigurationUtils
.getConfigurationKey(
466 if (Utils
.isUndefined(keyFound
.visible
) === true) {
467 keyFound
.visible
= true;
469 if (keyFound
.visible
=== false) {
472 configurationKey
.push({
474 readonly: keyFound
.readonly,
475 value
: keyFound
.value
,
478 unknownKey
.push(key
);
488 private handleRequestChangeConfiguration(
489 chargingStation
: ChargingStation
,
490 commandPayload
: ChangeConfigurationRequest
491 ): ChangeConfigurationResponse
{
492 const keyToChange
= ChargingStationConfigurationUtils
.getConfigurationKey(
498 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
499 } else if (keyToChange
&& keyToChange
.readonly) {
500 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
501 } else if (keyToChange
&& !keyToChange
.readonly) {
502 let valueChanged
= false;
503 if (keyToChange
.value
!== commandPayload
.value
) {
504 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
507 commandPayload
.value
,
512 let triggerHeartbeatRestart
= false;
513 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
514 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
516 OCPP16StandardParametersKey
.HeartbeatInterval
,
519 triggerHeartbeatRestart
= true;
521 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
522 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
524 OCPP16StandardParametersKey
.HeartBeatInterval
,
527 triggerHeartbeatRestart
= true;
529 if (triggerHeartbeatRestart
) {
530 chargingStation
.restartHeartbeat();
532 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
533 chargingStation
.restartWebSocketPing();
535 if (keyToChange
.reboot
) {
536 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
538 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
542 private handleRequestSetChargingProfile(
543 chargingStation
: ChargingStation
,
544 commandPayload
: SetChargingProfileRequest
545 ): SetChargingProfileResponse
{
547 OCPP16ServiceUtils
.checkFeatureProfile(
549 OCPP16SupportedFeatureProfiles
.SmartCharging
,
550 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
553 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
555 if (chargingStation
.connectors
.has(commandPayload
.connectorId
) === false) {
557 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${
558 commandPayload.connectorId
561 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
564 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
565 ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
566 commandPayload
.connectorId
!== 0
568 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
571 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
572 ChargingProfilePurposeType
.TX_PROFILE
&&
573 (commandPayload
.connectorId
=== 0 ||
574 chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
===
577 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
579 OCPP16ServiceUtils
.setChargingProfile(
581 commandPayload
.connectorId
,
582 commandPayload
.csChargingProfiles
585 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${
586 commandPayload.connectorId
587 }, dump their stack: %j`,
588 chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
590 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
593 private handleRequestClearChargingProfile(
594 chargingStation
: ChargingStation
,
595 commandPayload
: ClearChargingProfileRequest
596 ): ClearChargingProfileResponse
{
598 OCPP16ServiceUtils
.checkFeatureProfile(
600 OCPP16SupportedFeatureProfiles
.SmartCharging
,
601 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
604 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
606 if (chargingStation
.connectors
.has(commandPayload
.connectorId
) === false) {
608 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${
609 commandPayload.connectorId
612 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
614 const connectorStatus
= chargingStation
.getConnectorStatus(commandPayload
.connectorId
);
615 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(connectorStatus
.chargingProfiles
)) {
616 connectorStatus
.chargingProfiles
= [];
618 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${
619 commandPayload.connectorId
620 }, dump their stack: %j`,
621 connectorStatus
.chargingProfiles
623 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
625 if (!commandPayload
.connectorId
) {
626 let clearedCP
= false;
627 for (const connectorId
of chargingStation
.connectors
.keys()) {
628 if (!Utils
.isEmptyArray(chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
)) {
630 .getConnectorStatus(connectorId
)
631 .chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
632 let clearCurrentCP
= false;
633 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
634 clearCurrentCP
= true;
637 !commandPayload
.chargingProfilePurpose
&&
638 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
640 clearCurrentCP
= true;
643 !chargingProfile
.stackLevel
&&
644 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
646 clearCurrentCP
= true;
649 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&&
650 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
652 clearCurrentCP
= true;
654 if (clearCurrentCP
) {
655 connectorStatus
.chargingProfiles
.splice(index
, 1);
657 `${chargingStation.logPrefix()} Matching charging profile(s) cleared on connector id ${
658 commandPayload.connectorId
659 }, dump their stack: %j`,
660 connectorStatus
.chargingProfiles
668 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
671 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
674 private async handleRequestChangeAvailability(
675 chargingStation
: ChargingStation
,
676 commandPayload
: ChangeAvailabilityRequest
677 ): Promise
<ChangeAvailabilityResponse
> {
678 const connectorId
: number = commandPayload
.connectorId
;
679 if (!chargingStation
.getConnectorStatus(connectorId
)) {
681 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`
683 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
685 const chargePointStatus
: OCPP16ChargePointStatus
=
686 commandPayload
.type === OCPP16AvailabilityType
.OPERATIVE
687 ? OCPP16ChargePointStatus
.AVAILABLE
688 : OCPP16ChargePointStatus
.UNAVAILABLE
;
689 if (connectorId
=== 0) {
690 let response
: ChangeAvailabilityResponse
= Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
691 for (const id
of chargingStation
.connectors
.keys()) {
692 if (chargingStation
.getConnectorStatus(id
)?.transactionStarted
=== true) {
693 response
= Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
695 chargingStation
.getConnectorStatus(id
).availability
= commandPayload
.type;
696 if (response
=== Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
) {
697 await chargingStation
.ocppRequestService
.requestHandler
<
698 OCPP16StatusNotificationRequest
,
699 OCPP16StatusNotificationResponse
700 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
702 status: chargePointStatus
,
703 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
705 chargingStation
.getConnectorStatus(id
).status = chargePointStatus
;
711 (chargingStation
.isChargingStationAvailable() === true ||
712 (chargingStation
.isChargingStationAvailable() === false &&
713 commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))
715 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
716 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
717 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
719 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
720 await chargingStation
.ocppRequestService
.requestHandler
<
721 OCPP16StatusNotificationRequest
,
722 OCPP16StatusNotificationResponse
723 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
725 status: chargePointStatus
,
726 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
728 chargingStation
.getConnectorStatus(connectorId
).status = chargePointStatus
;
729 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
731 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
734 private async handleRequestRemoteStartTransaction(
735 chargingStation
: ChargingStation
,
736 commandPayload
: RemoteStartTransactionRequest
737 ): Promise
<DefaultResponse
> {
738 const transactionConnectorId
= commandPayload
.connectorId
;
739 if (chargingStation
.connectors
.has(transactionConnectorId
) === true) {
740 const remoteStartTransactionLogMsg
=
741 chargingStation
.logPrefix() +
742 ' Transaction remotely STARTED on ' +
743 chargingStation
.stationInfo
.chargingStationId
+
745 transactionConnectorId
.toString() +
747 commandPayload
.idTag
+
749 await chargingStation
.ocppRequestService
.requestHandler
<
750 OCPP16StatusNotificationRequest
,
751 OCPP16StatusNotificationResponse
752 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
753 connectorId
: transactionConnectorId
,
754 status: OCPP16ChargePointStatus
.PREPARING
,
755 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
757 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
);
758 connectorStatus
.status = OCPP16ChargePointStatus
.PREPARING
;
759 if (chargingStation
.isChargingStationAvailable() === true) {
760 // Check if authorized
761 if (chargingStation
.getAuthorizeRemoteTxRequests() === true) {
762 let authorized
= false;
764 chargingStation
.getLocalAuthListEnabled() === true &&
765 chargingStation
.hasAuthorizedTags() === true &&
766 chargingStation
.authorizedTagsCache
768 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
770 .find((idTag
) => idTag
=== commandPayload
.idTag
)
772 connectorStatus
.localAuthorizeIdTag
= commandPayload
.idTag
;
773 connectorStatus
.idTagLocalAuthorized
= true;
775 } else if (chargingStation
.getMustAuthorizeAtRemoteStart() === true) {
776 connectorStatus
.authorizeIdTag
= commandPayload
.idTag
;
777 const authorizeResponse
: OCPP16AuthorizeResponse
=
778 await chargingStation
.ocppRequestService
.requestHandler
<
779 OCPP16AuthorizeRequest
,
780 OCPP16AuthorizeResponse
781 >(chargingStation
, OCPP16RequestCommand
.AUTHORIZE
, {
782 idTag
: commandPayload
.idTag
,
784 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
789 `${chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`
792 if (authorized
=== true) {
793 // Authorization successful, start transaction
795 this.setRemoteStartTransactionChargingProfile(
797 transactionConnectorId
,
798 commandPayload
.chargingProfile
801 connectorStatus
.transactionRemoteStarted
= true;
804 await chargingStation
.ocppRequestService
.requestHandler
<
805 OCPP16StartTransactionRequest
,
806 OCPP16StartTransactionResponse
807 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
808 connectorId
: transactionConnectorId
,
809 idTag
: commandPayload
.idTag
,
811 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
813 logger
.debug(remoteStartTransactionLogMsg
);
814 return Constants
.OCPP_RESPONSE_ACCEPTED
;
816 return this.notifyRemoteStartTransactionRejected(
818 transactionConnectorId
,
822 return this.notifyRemoteStartTransactionRejected(
824 transactionConnectorId
,
828 return this.notifyRemoteStartTransactionRejected(
830 transactionConnectorId
,
834 // No authorization check required, start transaction
836 this.setRemoteStartTransactionChargingProfile(
838 transactionConnectorId
,
839 commandPayload
.chargingProfile
842 connectorStatus
.transactionRemoteStarted
= true;
845 await chargingStation
.ocppRequestService
.requestHandler
<
846 OCPP16StartTransactionRequest
,
847 OCPP16StartTransactionResponse
848 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
849 connectorId
: transactionConnectorId
,
850 idTag
: commandPayload
.idTag
,
852 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
854 logger
.debug(remoteStartTransactionLogMsg
);
855 return Constants
.OCPP_RESPONSE_ACCEPTED
;
857 return this.notifyRemoteStartTransactionRejected(
859 transactionConnectorId
,
863 return this.notifyRemoteStartTransactionRejected(
865 transactionConnectorId
,
869 return this.notifyRemoteStartTransactionRejected(
871 transactionConnectorId
,
875 return this.notifyRemoteStartTransactionRejected(
877 transactionConnectorId
,
882 private async notifyRemoteStartTransactionRejected(
883 chargingStation
: ChargingStation
,
886 ): Promise
<DefaultResponse
> {
888 chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
890 await chargingStation
.ocppRequestService
.requestHandler
<
891 OCPP16StatusNotificationRequest
,
892 OCPP16StatusNotificationResponse
893 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
895 status: OCPP16ChargePointStatus
.AVAILABLE
,
896 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
898 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
901 chargingStation
.logPrefix() +
902 ' Remote starting transaction REJECTED on connector Id ' +
903 connectorId
.toString() +
906 "', availability '" +
907 chargingStation
.getConnectorStatus(connectorId
).availability
+
909 chargingStation
.getConnectorStatus(connectorId
).status +
912 return Constants
.OCPP_RESPONSE_REJECTED
;
915 private setRemoteStartTransactionChargingProfile(
916 chargingStation
: ChargingStation
,
918 cp
: OCPP16ChargingProfile
920 if (cp
&& cp
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
921 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, cp
);
923 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}, dump their stack: %j`,
924 chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
927 } else if (cp
&& cp
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
929 `${chargingStation.logPrefix()} Not allowed to set ${
930 cp.chargingProfilePurpose
931 } charging profile(s) at remote start transaction`
939 private async handleRequestRemoteStopTransaction(
940 chargingStation
: ChargingStation
,
941 commandPayload
: RemoteStopTransactionRequest
942 ): Promise
<DefaultResponse
> {
943 const transactionId
= commandPayload
.transactionId
;
944 for (const connectorId
of chargingStation
.connectors
.keys()) {
947 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
949 await chargingStation
.ocppRequestService
.requestHandler
<
950 OCPP16StatusNotificationRequest
,
951 OCPP16StatusNotificationResponse
952 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
954 status: OCPP16ChargePointStatus
.FINISHING
,
955 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
957 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.FINISHING
;
958 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
960 OCPP16StopTransactionReason
.REMOTE
962 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
963 return Constants
.OCPP_RESPONSE_ACCEPTED
;
965 return Constants
.OCPP_RESPONSE_REJECTED
;
969 chargingStation
.logPrefix() +
970 ' Trying to remote stop a non existing transaction ' +
971 transactionId
.toString()
973 return Constants
.OCPP_RESPONSE_REJECTED
;
976 private async handleRequestGetDiagnostics(
977 chargingStation
: ChargingStation
,
978 commandPayload
: GetDiagnosticsRequest
979 ): Promise
<GetDiagnosticsResponse
> {
981 OCPP16ServiceUtils
.checkFeatureProfile(
983 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
984 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
987 return Constants
.OCPP_RESPONSE_EMPTY
;
990 chargingStation
.logPrefix() +
992 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
+
993 ' request received: %j',
996 const uri
= new URL(commandPayload
.location
);
997 if (uri
.protocol
.startsWith('ftp:')) {
998 let ftpClient
: Client
;
1001 .readdirSync(path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'))
1002 .filter((file
) => file
.endsWith('.log'))
1003 .map((file
) => path
.join('./', file
));
1004 const diagnosticsArchive
= chargingStation
.stationInfo
.chargingStationId
+ '_logs.tar.gz';
1005 tar
.create({ gzip
: true }, logFiles
).pipe(fs
.createWriteStream(diagnosticsArchive
));
1006 ftpClient
= new Client();
1007 const accessResponse
= await ftpClient
.access({
1009 ...(!Utils
.isEmptyString(uri
.port
) && { port
: Utils
.convertToInt(uri
.port
) }),
1010 ...(!Utils
.isEmptyString(uri
.username
) && { user
: uri
.username
}),
1011 ...(!Utils
.isEmptyString(uri
.password
) && { password
: uri
.password
}),
1013 let uploadResponse
: FTPResponse
;
1014 if (accessResponse
.code
=== 220) {
1015 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1016 ftpClient
.trackProgress(async (info
) => {
1018 `${chargingStation.logPrefix()} ${
1020 } bytes transferred from diagnostics archive ${info.name}`
1022 await chargingStation
.ocppRequestService
.requestHandler
<
1023 DiagnosticsStatusNotificationRequest
,
1024 DiagnosticsStatusNotificationResponse
1025 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1026 status: OCPP16DiagnosticsStatus
.Uploading
,
1029 uploadResponse
= await ftpClient
.uploadFrom(
1031 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'),
1034 uri
.pathname
+ diagnosticsArchive
1036 if (uploadResponse
.code
=== 226) {
1037 await chargingStation
.ocppRequestService
.requestHandler
<
1038 DiagnosticsStatusNotificationRequest
,
1039 DiagnosticsStatusNotificationResponse
1040 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1041 status: OCPP16DiagnosticsStatus
.Uploaded
,
1046 return { fileName
: diagnosticsArchive
};
1048 throw new OCPPError(
1049 ErrorType
.GENERIC_ERROR
,
1050 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1051 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1053 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1056 throw new OCPPError(
1057 ErrorType
.GENERIC_ERROR
,
1058 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1059 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1061 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1064 await chargingStation
.ocppRequestService
.requestHandler
<
1065 DiagnosticsStatusNotificationRequest
,
1066 DiagnosticsStatusNotificationResponse
1067 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1068 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1073 return this.handleIncomingRequestError(
1075 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1077 { errorResponse
: Constants
.OCPP_RESPONSE_EMPTY
}
1082 `${chargingStation.logPrefix()} Unsupported protocol ${
1084 } to transfer the diagnostic logs archive`
1086 await chargingStation
.ocppRequestService
.requestHandler
<
1087 DiagnosticsStatusNotificationRequest
,
1088 DiagnosticsStatusNotificationResponse
1089 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1090 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1092 return Constants
.OCPP_RESPONSE_EMPTY
;
1096 private handleRequestTriggerMessage(
1097 chargingStation
: ChargingStation
,
1098 commandPayload
: OCPP16TriggerMessageRequest
1099 ): OCPP16TriggerMessageResponse
{
1101 !OCPP16ServiceUtils
.checkFeatureProfile(
1103 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1104 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1107 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1109 // TODO: factor out the check on connector id
1110 if (commandPayload
?.connectorId
< 0) {
1112 `${chargingStation.logPrefix()} ${
1113 OCPP16IncomingRequestCommand.TRIGGER_MESSAGE
1114 } incoming request received with invalid connectorId ${commandPayload.connectorId}`
1116 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1119 switch (commandPayload
.requestedMessage
) {
1120 case MessageTrigger
.BootNotification
:
1122 chargingStation
.ocppRequestService
1123 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1125 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1126 chargingStation
.bootNotificationRequest
,
1127 { skipBufferingOnError
: true, triggerMessage
: true }
1129 .then((response
) => {
1130 chargingStation
.bootNotificationResponse
= response
;
1133 /* This is intentional */
1135 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1136 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1137 case MessageTrigger
.Heartbeat
:
1139 chargingStation
.ocppRequestService
1140 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1142 OCPP16RequestCommand
.HEARTBEAT
,
1145 triggerMessage
: true,
1149 /* This is intentional */
1151 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1152 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1153 case MessageTrigger
.StatusNotification
:
1155 if (commandPayload
?.connectorId
) {
1156 chargingStation
.ocppRequestService
1157 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1159 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1161 connectorId
: commandPayload
.connectorId
,
1162 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1163 status: chargingStation
.getConnectorStatus(commandPayload
.connectorId
).status,
1166 triggerMessage
: true,
1170 /* This is intentional */
1173 for (const connectorId
of chargingStation
.connectors
.keys()) {
1174 chargingStation
.ocppRequestService
1176 OCPP16StatusNotificationRequest
,
1177 OCPP16StatusNotificationResponse
1180 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1183 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1184 status: chargingStation
.getConnectorStatus(connectorId
).status,
1187 triggerMessage
: true,
1191 /* This is intentional */
1195 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1196 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1198 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1201 return this.handleIncomingRequestError(
1203 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1205 { errorResponse
: Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
}