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() === 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 (connectorId
=== 0) {
418 chargingStation
.logPrefix() + ' Trying to unlock connector ' + connectorId
.toString()
420 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
422 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
423 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
425 OCPP16StopTransactionReason
.UNLOCK_COMMAND
427 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
428 return Constants
.OCPP_RESPONSE_UNLOCKED
;
430 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
432 await chargingStation
.ocppRequestService
.requestHandler
<
433 OCPP16StatusNotificationRequest
,
434 OCPP16StatusNotificationResponse
435 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
437 status: OCPP16ChargePointStatus
.AVAILABLE
,
438 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
440 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
441 return Constants
.OCPP_RESPONSE_UNLOCKED
;
444 private handleRequestGetConfiguration(
445 chargingStation
: ChargingStation
,
446 commandPayload
: GetConfigurationRequest
447 ): GetConfigurationResponse
{
448 const configurationKey
: OCPPConfigurationKey
[] = [];
449 const unknownKey
: string[] = [];
450 if (Utils
.isEmptyArray(commandPayload
.key
) === true) {
451 for (const configuration
of chargingStation
.ocppConfiguration
.configurationKey
) {
452 if (Utils
.isUndefined(configuration
.visible
) === true) {
453 configuration
.visible
= true;
455 if (configuration
.visible
=== false) {
458 configurationKey
.push({
459 key
: configuration
.key
,
460 readonly: configuration
.readonly,
461 value
: configuration
.value
,
465 for (const key
of commandPayload
.key
) {
466 const keyFound
= ChargingStationConfigurationUtils
.getConfigurationKey(
471 if (Utils
.isUndefined(keyFound
.visible
) === true) {
472 keyFound
.visible
= true;
474 if (keyFound
.visible
=== false) {
477 configurationKey
.push({
479 readonly: keyFound
.readonly,
480 value
: keyFound
.value
,
483 unknownKey
.push(key
);
493 private handleRequestChangeConfiguration(
494 chargingStation
: ChargingStation
,
495 commandPayload
: ChangeConfigurationRequest
496 ): ChangeConfigurationResponse
{
497 const keyToChange
= ChargingStationConfigurationUtils
.getConfigurationKey(
503 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
504 } else if (keyToChange
&& keyToChange
.readonly) {
505 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
506 } else if (keyToChange
&& !keyToChange
.readonly) {
507 let valueChanged
= false;
508 if (keyToChange
.value
!== commandPayload
.value
) {
509 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
512 commandPayload
.value
,
517 let triggerHeartbeatRestart
= false;
518 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
519 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
521 OCPP16StandardParametersKey
.HeartbeatInterval
,
524 triggerHeartbeatRestart
= true;
526 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
527 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
529 OCPP16StandardParametersKey
.HeartBeatInterval
,
532 triggerHeartbeatRestart
= true;
534 if (triggerHeartbeatRestart
) {
535 chargingStation
.restartHeartbeat();
537 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
538 chargingStation
.restartWebSocketPing();
540 if (keyToChange
.reboot
) {
541 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
543 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
547 private handleRequestSetChargingProfile(
548 chargingStation
: ChargingStation
,
549 commandPayload
: SetChargingProfileRequest
550 ): SetChargingProfileResponse
{
552 OCPP16ServiceUtils
.checkFeatureProfile(
554 OCPP16SupportedFeatureProfiles
.SmartCharging
,
555 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
558 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
560 if (chargingStation
.connectors
.has(commandPayload
.connectorId
) === false) {
562 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${
563 commandPayload.connectorId
566 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
569 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
570 ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
571 commandPayload
.connectorId
!== 0
573 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
576 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
577 ChargingProfilePurposeType
.TX_PROFILE
&&
578 (commandPayload
.connectorId
=== 0 ||
579 chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
===
583 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${
584 commandPayload.connectorId
585 } without a started transaction`
587 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
589 OCPP16ServiceUtils
.setChargingProfile(
591 commandPayload
.connectorId
,
592 commandPayload
.csChargingProfiles
595 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${
596 commandPayload.connectorId
597 }, dump their stack: %j`,
598 chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
600 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
603 private handleRequestClearChargingProfile(
604 chargingStation
: ChargingStation
,
605 commandPayload
: ClearChargingProfileRequest
606 ): ClearChargingProfileResponse
{
608 OCPP16ServiceUtils
.checkFeatureProfile(
610 OCPP16SupportedFeatureProfiles
.SmartCharging
,
611 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
614 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
616 if (chargingStation
.connectors
.has(commandPayload
.connectorId
) === false) {
618 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${
619 commandPayload.connectorId
622 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
624 const connectorStatus
= chargingStation
.getConnectorStatus(commandPayload
.connectorId
);
625 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(connectorStatus
.chargingProfiles
)) {
626 connectorStatus
.chargingProfiles
= [];
628 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${
629 commandPayload.connectorId
630 }, dump their stack: %j`,
631 connectorStatus
.chargingProfiles
633 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
635 if (!commandPayload
.connectorId
) {
636 let clearedCP
= false;
637 for (const connectorId
of chargingStation
.connectors
.keys()) {
638 if (!Utils
.isEmptyArray(chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
)) {
640 .getConnectorStatus(connectorId
)
641 .chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
642 let clearCurrentCP
= false;
643 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
644 clearCurrentCP
= true;
647 !commandPayload
.chargingProfilePurpose
&&
648 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
650 clearCurrentCP
= true;
653 !chargingProfile
.stackLevel
&&
654 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
656 clearCurrentCP
= true;
659 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&&
660 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
662 clearCurrentCP
= true;
664 if (clearCurrentCP
) {
665 connectorStatus
.chargingProfiles
.splice(index
, 1);
667 `${chargingStation.logPrefix()} Matching charging profile(s) cleared on connector id ${
668 commandPayload.connectorId
669 }, dump their stack: %j`,
670 connectorStatus
.chargingProfiles
678 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
681 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
684 private async handleRequestChangeAvailability(
685 chargingStation
: ChargingStation
,
686 commandPayload
: ChangeAvailabilityRequest
687 ): Promise
<ChangeAvailabilityResponse
> {
688 const connectorId
: number = commandPayload
.connectorId
;
689 if (!chargingStation
.getConnectorStatus(connectorId
)) {
691 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`
693 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
695 const chargePointStatus
: OCPP16ChargePointStatus
=
696 commandPayload
.type === OCPP16AvailabilityType
.OPERATIVE
697 ? OCPP16ChargePointStatus
.AVAILABLE
698 : OCPP16ChargePointStatus
.UNAVAILABLE
;
699 if (connectorId
=== 0) {
700 let response
: ChangeAvailabilityResponse
= Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
701 for (const id
of chargingStation
.connectors
.keys()) {
702 if (chargingStation
.getConnectorStatus(id
)?.transactionStarted
=== true) {
703 response
= Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
705 chargingStation
.getConnectorStatus(id
).availability
= commandPayload
.type;
706 if (response
=== Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
) {
707 await chargingStation
.ocppRequestService
.requestHandler
<
708 OCPP16StatusNotificationRequest
,
709 OCPP16StatusNotificationResponse
710 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
712 status: chargePointStatus
,
713 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
715 chargingStation
.getConnectorStatus(id
).status = chargePointStatus
;
721 (chargingStation
.isChargingStationAvailable() === true ||
722 (chargingStation
.isChargingStationAvailable() === false &&
723 commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))
725 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
726 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
727 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
729 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
730 await chargingStation
.ocppRequestService
.requestHandler
<
731 OCPP16StatusNotificationRequest
,
732 OCPP16StatusNotificationResponse
733 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
735 status: chargePointStatus
,
736 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
738 chargingStation
.getConnectorStatus(connectorId
).status = chargePointStatus
;
739 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
741 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
744 private async handleRequestRemoteStartTransaction(
745 chargingStation
: ChargingStation
,
746 commandPayload
: RemoteStartTransactionRequest
747 ): Promise
<DefaultResponse
> {
748 const transactionConnectorId
= commandPayload
.connectorId
;
749 if (chargingStation
.connectors
.has(transactionConnectorId
) === true) {
750 const remoteStartTransactionLogMsg
=
751 chargingStation
.logPrefix() +
752 ' Transaction remotely STARTED on ' +
753 chargingStation
.stationInfo
.chargingStationId
+
755 transactionConnectorId
.toString() +
757 commandPayload
.idTag
+
759 await chargingStation
.ocppRequestService
.requestHandler
<
760 OCPP16StatusNotificationRequest
,
761 OCPP16StatusNotificationResponse
762 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
763 connectorId
: transactionConnectorId
,
764 status: OCPP16ChargePointStatus
.PREPARING
,
765 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
767 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
);
768 connectorStatus
.status = OCPP16ChargePointStatus
.PREPARING
;
769 if (chargingStation
.isChargingStationAvailable() === true) {
770 // Check if authorized
771 if (chargingStation
.getAuthorizeRemoteTxRequests() === true) {
772 let authorized
= false;
774 chargingStation
.getLocalAuthListEnabled() === true &&
775 chargingStation
.hasAuthorizedTags() === true &&
776 chargingStation
.authorizedTagsCache
778 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
780 .find((idTag
) => idTag
=== commandPayload
.idTag
)
782 connectorStatus
.localAuthorizeIdTag
= commandPayload
.idTag
;
783 connectorStatus
.idTagLocalAuthorized
= true;
785 } else if (chargingStation
.getMustAuthorizeAtRemoteStart() === true) {
786 connectorStatus
.authorizeIdTag
= commandPayload
.idTag
;
787 const authorizeResponse
: OCPP16AuthorizeResponse
=
788 await chargingStation
.ocppRequestService
.requestHandler
<
789 OCPP16AuthorizeRequest
,
790 OCPP16AuthorizeResponse
791 >(chargingStation
, OCPP16RequestCommand
.AUTHORIZE
, {
792 idTag
: commandPayload
.idTag
,
794 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
799 `${chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`
802 if (authorized
=== true) {
803 // Authorization successful, start transaction
805 this.setRemoteStartTransactionChargingProfile(
807 transactionConnectorId
,
808 commandPayload
.chargingProfile
811 connectorStatus
.transactionRemoteStarted
= true;
814 await chargingStation
.ocppRequestService
.requestHandler
<
815 OCPP16StartTransactionRequest
,
816 OCPP16StartTransactionResponse
817 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
818 connectorId
: transactionConnectorId
,
819 idTag
: commandPayload
.idTag
,
821 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
823 logger
.debug(remoteStartTransactionLogMsg
);
824 return Constants
.OCPP_RESPONSE_ACCEPTED
;
826 return this.notifyRemoteStartTransactionRejected(
828 transactionConnectorId
,
832 return this.notifyRemoteStartTransactionRejected(
834 transactionConnectorId
,
838 return this.notifyRemoteStartTransactionRejected(
840 transactionConnectorId
,
844 // No authorization check required, start transaction
846 this.setRemoteStartTransactionChargingProfile(
848 transactionConnectorId
,
849 commandPayload
.chargingProfile
852 connectorStatus
.transactionRemoteStarted
= true;
855 await chargingStation
.ocppRequestService
.requestHandler
<
856 OCPP16StartTransactionRequest
,
857 OCPP16StartTransactionResponse
858 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
859 connectorId
: transactionConnectorId
,
860 idTag
: commandPayload
.idTag
,
862 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
864 logger
.debug(remoteStartTransactionLogMsg
);
865 return Constants
.OCPP_RESPONSE_ACCEPTED
;
867 return this.notifyRemoteStartTransactionRejected(
869 transactionConnectorId
,
873 return this.notifyRemoteStartTransactionRejected(
875 transactionConnectorId
,
879 return this.notifyRemoteStartTransactionRejected(
881 transactionConnectorId
,
885 return this.notifyRemoteStartTransactionRejected(
887 transactionConnectorId
,
892 private async notifyRemoteStartTransactionRejected(
893 chargingStation
: ChargingStation
,
896 ): Promise
<DefaultResponse
> {
898 chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
900 await chargingStation
.ocppRequestService
.requestHandler
<
901 OCPP16StatusNotificationRequest
,
902 OCPP16StatusNotificationResponse
903 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
905 status: OCPP16ChargePointStatus
.AVAILABLE
,
906 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
908 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
911 chargingStation
.logPrefix() +
912 ' Remote starting transaction REJECTED on connector Id ' +
913 connectorId
.toString() +
916 "', availability '" +
917 chargingStation
.getConnectorStatus(connectorId
).availability
+
919 chargingStation
.getConnectorStatus(connectorId
).status +
922 return Constants
.OCPP_RESPONSE_REJECTED
;
925 private setRemoteStartTransactionChargingProfile(
926 chargingStation
: ChargingStation
,
928 cp
: OCPP16ChargingProfile
930 if (cp
&& cp
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
931 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, cp
);
933 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}, dump their stack: %j`,
934 chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
937 } else if (cp
&& cp
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
939 `${chargingStation.logPrefix()} Not allowed to set ${
940 cp.chargingProfilePurpose
941 } charging profile(s) at remote start transaction`
949 private async handleRequestRemoteStopTransaction(
950 chargingStation
: ChargingStation
,
951 commandPayload
: RemoteStopTransactionRequest
952 ): Promise
<DefaultResponse
> {
953 const transactionId
= commandPayload
.transactionId
;
954 for (const connectorId
of chargingStation
.connectors
.keys()) {
957 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
959 await chargingStation
.ocppRequestService
.requestHandler
<
960 OCPP16StatusNotificationRequest
,
961 OCPP16StatusNotificationResponse
962 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
964 status: OCPP16ChargePointStatus
.FINISHING
,
965 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
967 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.FINISHING
;
968 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
970 OCPP16StopTransactionReason
.REMOTE
972 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
973 return Constants
.OCPP_RESPONSE_ACCEPTED
;
975 return Constants
.OCPP_RESPONSE_REJECTED
;
979 chargingStation
.logPrefix() +
980 ' Trying to remote stop a non existing transaction ' +
981 transactionId
.toString()
983 return Constants
.OCPP_RESPONSE_REJECTED
;
986 private async handleRequestGetDiagnostics(
987 chargingStation
: ChargingStation
,
988 commandPayload
: GetDiagnosticsRequest
989 ): Promise
<GetDiagnosticsResponse
> {
991 OCPP16ServiceUtils
.checkFeatureProfile(
993 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
994 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
997 return Constants
.OCPP_RESPONSE_EMPTY
;
1000 chargingStation
.logPrefix() +
1002 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
+
1003 ' request received: %j',
1006 const uri
= new URL(commandPayload
.location
);
1007 if (uri
.protocol
.startsWith('ftp:')) {
1008 let ftpClient
: Client
;
1011 .readdirSync(path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'))
1012 .filter((file
) => file
.endsWith('.log'))
1013 .map((file
) => path
.join('./', file
));
1014 const diagnosticsArchive
= chargingStation
.stationInfo
.chargingStationId
+ '_logs.tar.gz';
1015 tar
.create({ gzip
: true }, logFiles
).pipe(fs
.createWriteStream(diagnosticsArchive
));
1016 ftpClient
= new Client();
1017 const accessResponse
= await ftpClient
.access({
1019 ...(!Utils
.isEmptyString(uri
.port
) && { port
: Utils
.convertToInt(uri
.port
) }),
1020 ...(!Utils
.isEmptyString(uri
.username
) && { user
: uri
.username
}),
1021 ...(!Utils
.isEmptyString(uri
.password
) && { password
: uri
.password
}),
1023 let uploadResponse
: FTPResponse
;
1024 if (accessResponse
.code
=== 220) {
1025 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1026 ftpClient
.trackProgress(async (info
) => {
1028 `${chargingStation.logPrefix()} ${
1030 } bytes transferred from diagnostics archive ${info.name}`
1032 await chargingStation
.ocppRequestService
.requestHandler
<
1033 DiagnosticsStatusNotificationRequest
,
1034 DiagnosticsStatusNotificationResponse
1035 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1036 status: OCPP16DiagnosticsStatus
.Uploading
,
1039 uploadResponse
= await ftpClient
.uploadFrom(
1041 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'),
1044 uri
.pathname
+ diagnosticsArchive
1046 if (uploadResponse
.code
=== 226) {
1047 await chargingStation
.ocppRequestService
.requestHandler
<
1048 DiagnosticsStatusNotificationRequest
,
1049 DiagnosticsStatusNotificationResponse
1050 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1051 status: OCPP16DiagnosticsStatus
.Uploaded
,
1056 return { fileName
: diagnosticsArchive
};
1058 throw new OCPPError(
1059 ErrorType
.GENERIC_ERROR
,
1060 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1061 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1063 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1066 throw new OCPPError(
1067 ErrorType
.GENERIC_ERROR
,
1068 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1069 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1071 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1074 await chargingStation
.ocppRequestService
.requestHandler
<
1075 DiagnosticsStatusNotificationRequest
,
1076 DiagnosticsStatusNotificationResponse
1077 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1078 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1083 return this.handleIncomingRequestError(
1085 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1087 { errorResponse
: Constants
.OCPP_RESPONSE_EMPTY
}
1092 `${chargingStation.logPrefix()} Unsupported protocol ${
1094 } to transfer the diagnostic logs archive`
1096 await chargingStation
.ocppRequestService
.requestHandler
<
1097 DiagnosticsStatusNotificationRequest
,
1098 DiagnosticsStatusNotificationResponse
1099 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1100 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1102 return Constants
.OCPP_RESPONSE_EMPTY
;
1106 private handleRequestTriggerMessage(
1107 chargingStation
: ChargingStation
,
1108 commandPayload
: OCPP16TriggerMessageRequest
1109 ): OCPP16TriggerMessageResponse
{
1111 !OCPP16ServiceUtils
.checkFeatureProfile(
1113 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1114 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1117 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1119 // TODO: factor out the check on connector id
1120 if (commandPayload
?.connectorId
< 0) {
1122 `${chargingStation.logPrefix()} ${
1123 OCPP16IncomingRequestCommand.TRIGGER_MESSAGE
1124 } incoming request received with invalid connectorId ${commandPayload.connectorId}`
1126 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1129 switch (commandPayload
.requestedMessage
) {
1130 case MessageTrigger
.BootNotification
:
1132 chargingStation
.ocppRequestService
1133 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1135 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1136 chargingStation
.bootNotificationRequest
,
1137 { skipBufferingOnError
: true, triggerMessage
: true }
1139 .then((response
) => {
1140 chargingStation
.bootNotificationResponse
= response
;
1143 /* This is intentional */
1145 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1146 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1147 case MessageTrigger
.Heartbeat
:
1149 chargingStation
.ocppRequestService
1150 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1152 OCPP16RequestCommand
.HEARTBEAT
,
1155 triggerMessage
: true,
1159 /* This is intentional */
1161 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1162 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1163 case MessageTrigger
.StatusNotification
:
1165 if (commandPayload
?.connectorId
) {
1166 chargingStation
.ocppRequestService
1167 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1169 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1171 connectorId
: commandPayload
.connectorId
,
1172 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1173 status: chargingStation
.getConnectorStatus(commandPayload
.connectorId
).status,
1176 triggerMessage
: true,
1180 /* This is intentional */
1183 for (const connectorId
of chargingStation
.connectors
.keys()) {
1184 chargingStation
.ocppRequestService
1186 OCPP16StatusNotificationRequest
,
1187 OCPP16StatusNotificationResponse
1190 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1193 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1194 status: chargingStation
.getConnectorStatus(connectorId
).status,
1197 triggerMessage
: true,
1201 /* This is intentional */
1205 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1206 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1208 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1211 return this.handleIncomingRequestError(
1213 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1215 { errorResponse
: Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
}