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() === 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
382 this.asyncResource
.runInAsyncScope(
383 chargingStation
.reset
.bind(chargingStation
) as (
384 this: ChargingStation
,
388 (commandPayload
.type + 'Reset') as OCPP16StopTransactionReason
391 `${chargingStation.logPrefix()} ${
393 } reset command received, simulating it. The station will be back online in ${Utils.formatDurationMilliSeconds(
394 chargingStation.stationInfo.resetTime
397 return Constants
.OCPP_RESPONSE_ACCEPTED
;
400 private handleRequestClearCache(chargingStation
: ChargingStation
): DefaultResponse
{
401 chargingStation
.authorizedTagsCache
.deleteAuthorizedTags(
402 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
404 return Constants
.OCPP_RESPONSE_ACCEPTED
;
407 private async handleRequestUnlockConnector(
408 chargingStation
: ChargingStation
,
409 commandPayload
: UnlockConnectorRequest
410 ): Promise
<UnlockConnectorResponse
> {
411 const connectorId
= commandPayload
.connectorId
;
412 if (connectorId
=== 0) {
414 chargingStation
.logPrefix() + ' Trying to unlock connector ' + connectorId
.toString()
416 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
418 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
419 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
421 OCPP16StopTransactionReason
.UNLOCK_COMMAND
423 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
424 return Constants
.OCPP_RESPONSE_UNLOCKED
;
426 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
428 await chargingStation
.ocppRequestService
.requestHandler
<
429 OCPP16StatusNotificationRequest
,
430 OCPP16StatusNotificationResponse
431 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
433 status: OCPP16ChargePointStatus
.AVAILABLE
,
434 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
436 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
437 return Constants
.OCPP_RESPONSE_UNLOCKED
;
440 private handleRequestGetConfiguration(
441 chargingStation
: ChargingStation
,
442 commandPayload
: GetConfigurationRequest
443 ): GetConfigurationResponse
{
444 const configurationKey
: OCPPConfigurationKey
[] = [];
445 const unknownKey
: string[] = [];
446 if (Utils
.isEmptyArray(commandPayload
.key
) === true) {
447 for (const configuration
of chargingStation
.ocppConfiguration
.configurationKey
) {
448 if (Utils
.isUndefined(configuration
.visible
) === true) {
449 configuration
.visible
= true;
451 if (configuration
.visible
=== false) {
454 configurationKey
.push({
455 key
: configuration
.key
,
456 readonly: configuration
.readonly,
457 value
: configuration
.value
,
461 for (const key
of commandPayload
.key
) {
462 const keyFound
= ChargingStationConfigurationUtils
.getConfigurationKey(
467 if (Utils
.isUndefined(keyFound
.visible
) === true) {
468 keyFound
.visible
= true;
470 if (keyFound
.visible
=== false) {
473 configurationKey
.push({
475 readonly: keyFound
.readonly,
476 value
: keyFound
.value
,
479 unknownKey
.push(key
);
489 private handleRequestChangeConfiguration(
490 chargingStation
: ChargingStation
,
491 commandPayload
: ChangeConfigurationRequest
492 ): ChangeConfigurationResponse
{
493 const keyToChange
= ChargingStationConfigurationUtils
.getConfigurationKey(
499 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
500 } else if (keyToChange
&& keyToChange
.readonly) {
501 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
502 } else if (keyToChange
&& !keyToChange
.readonly) {
503 let valueChanged
= false;
504 if (keyToChange
.value
!== commandPayload
.value
) {
505 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
508 commandPayload
.value
,
513 let triggerHeartbeatRestart
= false;
514 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
515 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
517 OCPP16StandardParametersKey
.HeartbeatInterval
,
520 triggerHeartbeatRestart
= true;
522 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
523 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
525 OCPP16StandardParametersKey
.HeartBeatInterval
,
528 triggerHeartbeatRestart
= true;
530 if (triggerHeartbeatRestart
) {
531 chargingStation
.restartHeartbeat();
533 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
534 chargingStation
.restartWebSocketPing();
536 if (keyToChange
.reboot
) {
537 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
539 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
543 private handleRequestSetChargingProfile(
544 chargingStation
: ChargingStation
,
545 commandPayload
: SetChargingProfileRequest
546 ): SetChargingProfileResponse
{
548 OCPP16ServiceUtils
.checkFeatureProfile(
550 OCPP16SupportedFeatureProfiles
.SmartCharging
,
551 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
554 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
556 if (chargingStation
.connectors
.has(commandPayload
.connectorId
) === false) {
558 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${
559 commandPayload.connectorId
562 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
565 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
566 ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
567 commandPayload
.connectorId
!== 0
569 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
572 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
573 ChargingProfilePurposeType
.TX_PROFILE
&&
574 (commandPayload
.connectorId
=== 0 ||
575 chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
===
579 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${
580 commandPayload.connectorId
581 } without a started transaction`
583 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
585 OCPP16ServiceUtils
.setChargingProfile(
587 commandPayload
.connectorId
,
588 commandPayload
.csChargingProfiles
591 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${
592 commandPayload.connectorId
593 }, dump their stack: %j`,
594 chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
596 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
599 private handleRequestClearChargingProfile(
600 chargingStation
: ChargingStation
,
601 commandPayload
: ClearChargingProfileRequest
602 ): ClearChargingProfileResponse
{
604 OCPP16ServiceUtils
.checkFeatureProfile(
606 OCPP16SupportedFeatureProfiles
.SmartCharging
,
607 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
610 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
612 if (chargingStation
.connectors
.has(commandPayload
.connectorId
) === false) {
614 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${
615 commandPayload.connectorId
618 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
620 const connectorStatus
= chargingStation
.getConnectorStatus(commandPayload
.connectorId
);
621 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(connectorStatus
.chargingProfiles
)) {
622 connectorStatus
.chargingProfiles
= [];
624 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${
625 commandPayload.connectorId
626 }, dump their stack: %j`,
627 connectorStatus
.chargingProfiles
629 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
631 if (!commandPayload
.connectorId
) {
632 let clearedCP
= false;
633 for (const connectorId
of chargingStation
.connectors
.keys()) {
634 if (!Utils
.isEmptyArray(chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
)) {
636 .getConnectorStatus(connectorId
)
637 .chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
638 let clearCurrentCP
= false;
639 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
640 clearCurrentCP
= true;
643 !commandPayload
.chargingProfilePurpose
&&
644 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
646 clearCurrentCP
= true;
649 !chargingProfile
.stackLevel
&&
650 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
652 clearCurrentCP
= true;
655 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&&
656 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
658 clearCurrentCP
= true;
660 if (clearCurrentCP
) {
661 connectorStatus
.chargingProfiles
.splice(index
, 1);
663 `${chargingStation.logPrefix()} Matching charging profile(s) cleared on connector id ${
664 commandPayload.connectorId
665 }, dump their stack: %j`,
666 connectorStatus
.chargingProfiles
674 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
677 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
680 private async handleRequestChangeAvailability(
681 chargingStation
: ChargingStation
,
682 commandPayload
: ChangeAvailabilityRequest
683 ): Promise
<ChangeAvailabilityResponse
> {
684 const connectorId
: number = commandPayload
.connectorId
;
685 if (!chargingStation
.getConnectorStatus(connectorId
)) {
687 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`
689 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
691 const chargePointStatus
: OCPP16ChargePointStatus
=
692 commandPayload
.type === OCPP16AvailabilityType
.OPERATIVE
693 ? OCPP16ChargePointStatus
.AVAILABLE
694 : OCPP16ChargePointStatus
.UNAVAILABLE
;
695 if (connectorId
=== 0) {
696 let response
: ChangeAvailabilityResponse
= Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
697 for (const id
of chargingStation
.connectors
.keys()) {
698 if (chargingStation
.getConnectorStatus(id
)?.transactionStarted
=== true) {
699 response
= Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
701 chargingStation
.getConnectorStatus(id
).availability
= commandPayload
.type;
702 if (response
=== Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
) {
703 await chargingStation
.ocppRequestService
.requestHandler
<
704 OCPP16StatusNotificationRequest
,
705 OCPP16StatusNotificationResponse
706 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
708 status: chargePointStatus
,
709 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
711 chargingStation
.getConnectorStatus(id
).status = chargePointStatus
;
717 (chargingStation
.isChargingStationAvailable() === true ||
718 (chargingStation
.isChargingStationAvailable() === false &&
719 commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))
721 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
722 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
723 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
725 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
726 await chargingStation
.ocppRequestService
.requestHandler
<
727 OCPP16StatusNotificationRequest
,
728 OCPP16StatusNotificationResponse
729 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
731 status: chargePointStatus
,
732 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
734 chargingStation
.getConnectorStatus(connectorId
).status = chargePointStatus
;
735 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
737 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
740 private async handleRequestRemoteStartTransaction(
741 chargingStation
: ChargingStation
,
742 commandPayload
: RemoteStartTransactionRequest
743 ): Promise
<DefaultResponse
> {
744 const transactionConnectorId
= commandPayload
.connectorId
;
745 if (chargingStation
.connectors
.has(transactionConnectorId
) === true) {
746 const remoteStartTransactionLogMsg
=
747 chargingStation
.logPrefix() +
748 ' Transaction remotely STARTED on ' +
749 chargingStation
.stationInfo
.chargingStationId
+
751 transactionConnectorId
.toString() +
753 commandPayload
.idTag
+
755 await chargingStation
.ocppRequestService
.requestHandler
<
756 OCPP16StatusNotificationRequest
,
757 OCPP16StatusNotificationResponse
758 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
759 connectorId
: transactionConnectorId
,
760 status: OCPP16ChargePointStatus
.PREPARING
,
761 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
763 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
);
764 connectorStatus
.status = OCPP16ChargePointStatus
.PREPARING
;
765 if (chargingStation
.isChargingStationAvailable() === true) {
766 // Check if authorized
767 if (chargingStation
.getAuthorizeRemoteTxRequests() === true) {
768 let authorized
= false;
770 chargingStation
.getLocalAuthListEnabled() === true &&
771 chargingStation
.hasAuthorizedTags() === true &&
772 chargingStation
.authorizedTagsCache
774 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
776 .find((idTag
) => idTag
=== commandPayload
.idTag
)
778 connectorStatus
.localAuthorizeIdTag
= commandPayload
.idTag
;
779 connectorStatus
.idTagLocalAuthorized
= true;
781 } else if (chargingStation
.getMustAuthorizeAtRemoteStart() === true) {
782 connectorStatus
.authorizeIdTag
= commandPayload
.idTag
;
783 const authorizeResponse
: OCPP16AuthorizeResponse
=
784 await chargingStation
.ocppRequestService
.requestHandler
<
785 OCPP16AuthorizeRequest
,
786 OCPP16AuthorizeResponse
787 >(chargingStation
, OCPP16RequestCommand
.AUTHORIZE
, {
788 idTag
: commandPayload
.idTag
,
790 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
795 `${chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`
798 if (authorized
=== true) {
799 // Authorization successful, start transaction
801 this.setRemoteStartTransactionChargingProfile(
803 transactionConnectorId
,
804 commandPayload
.chargingProfile
807 connectorStatus
.transactionRemoteStarted
= true;
810 await chargingStation
.ocppRequestService
.requestHandler
<
811 OCPP16StartTransactionRequest
,
812 OCPP16StartTransactionResponse
813 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
814 connectorId
: transactionConnectorId
,
815 idTag
: commandPayload
.idTag
,
817 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
819 logger
.debug(remoteStartTransactionLogMsg
);
820 return Constants
.OCPP_RESPONSE_ACCEPTED
;
822 return this.notifyRemoteStartTransactionRejected(
824 transactionConnectorId
,
828 return this.notifyRemoteStartTransactionRejected(
830 transactionConnectorId
,
834 return this.notifyRemoteStartTransactionRejected(
836 transactionConnectorId
,
840 // No authorization check required, start transaction
842 this.setRemoteStartTransactionChargingProfile(
844 transactionConnectorId
,
845 commandPayload
.chargingProfile
848 connectorStatus
.transactionRemoteStarted
= true;
851 await chargingStation
.ocppRequestService
.requestHandler
<
852 OCPP16StartTransactionRequest
,
853 OCPP16StartTransactionResponse
854 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
855 connectorId
: transactionConnectorId
,
856 idTag
: commandPayload
.idTag
,
858 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
860 logger
.debug(remoteStartTransactionLogMsg
);
861 return Constants
.OCPP_RESPONSE_ACCEPTED
;
863 return this.notifyRemoteStartTransactionRejected(
865 transactionConnectorId
,
869 return this.notifyRemoteStartTransactionRejected(
871 transactionConnectorId
,
875 return this.notifyRemoteStartTransactionRejected(
877 transactionConnectorId
,
881 return this.notifyRemoteStartTransactionRejected(
883 transactionConnectorId
,
888 private async notifyRemoteStartTransactionRejected(
889 chargingStation
: ChargingStation
,
892 ): Promise
<DefaultResponse
> {
894 chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
896 await chargingStation
.ocppRequestService
.requestHandler
<
897 OCPP16StatusNotificationRequest
,
898 OCPP16StatusNotificationResponse
899 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
901 status: OCPP16ChargePointStatus
.AVAILABLE
,
902 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
904 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
907 chargingStation
.logPrefix() +
908 ' Remote starting transaction REJECTED on connector Id ' +
909 connectorId
.toString() +
912 "', availability '" +
913 chargingStation
.getConnectorStatus(connectorId
).availability
+
915 chargingStation
.getConnectorStatus(connectorId
).status +
918 return Constants
.OCPP_RESPONSE_REJECTED
;
921 private setRemoteStartTransactionChargingProfile(
922 chargingStation
: ChargingStation
,
924 cp
: OCPP16ChargingProfile
926 if (cp
&& cp
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
927 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, cp
);
929 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}, dump their stack: %j`,
930 chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
933 } else if (cp
&& cp
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
935 `${chargingStation.logPrefix()} Not allowed to set ${
936 cp.chargingProfilePurpose
937 } charging profile(s) at remote start transaction`
945 private async handleRequestRemoteStopTransaction(
946 chargingStation
: ChargingStation
,
947 commandPayload
: RemoteStopTransactionRequest
948 ): Promise
<DefaultResponse
> {
949 const transactionId
= commandPayload
.transactionId
;
950 for (const connectorId
of chargingStation
.connectors
.keys()) {
953 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
955 await chargingStation
.ocppRequestService
.requestHandler
<
956 OCPP16StatusNotificationRequest
,
957 OCPP16StatusNotificationResponse
958 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
960 status: OCPP16ChargePointStatus
.FINISHING
,
961 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
963 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.FINISHING
;
964 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
966 OCPP16StopTransactionReason
.REMOTE
968 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
969 return Constants
.OCPP_RESPONSE_ACCEPTED
;
971 return Constants
.OCPP_RESPONSE_REJECTED
;
975 chargingStation
.logPrefix() +
976 ' Trying to remote stop a non existing transaction ' +
977 transactionId
.toString()
979 return Constants
.OCPP_RESPONSE_REJECTED
;
982 private async handleRequestGetDiagnostics(
983 chargingStation
: ChargingStation
,
984 commandPayload
: GetDiagnosticsRequest
985 ): Promise
<GetDiagnosticsResponse
> {
987 OCPP16ServiceUtils
.checkFeatureProfile(
989 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
990 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
993 return Constants
.OCPP_RESPONSE_EMPTY
;
996 chargingStation
.logPrefix() +
998 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
+
999 ' request received: %j',
1002 const uri
= new URL(commandPayload
.location
);
1003 if (uri
.protocol
.startsWith('ftp:')) {
1004 let ftpClient
: Client
;
1007 .readdirSync(path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'))
1008 .filter((file
) => file
.endsWith('.log'))
1009 .map((file
) => path
.join('./', file
));
1010 const diagnosticsArchive
= chargingStation
.stationInfo
.chargingStationId
+ '_logs.tar.gz';
1011 tar
.create({ gzip
: true }, logFiles
).pipe(fs
.createWriteStream(diagnosticsArchive
));
1012 ftpClient
= new Client();
1013 const accessResponse
= await ftpClient
.access({
1015 ...(!Utils
.isEmptyString(uri
.port
) && { port
: Utils
.convertToInt(uri
.port
) }),
1016 ...(!Utils
.isEmptyString(uri
.username
) && { user
: uri
.username
}),
1017 ...(!Utils
.isEmptyString(uri
.password
) && { password
: uri
.password
}),
1019 let uploadResponse
: FTPResponse
;
1020 if (accessResponse
.code
=== 220) {
1021 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1022 ftpClient
.trackProgress(async (info
) => {
1024 `${chargingStation.logPrefix()} ${
1026 } bytes transferred from diagnostics archive ${info.name}`
1028 await chargingStation
.ocppRequestService
.requestHandler
<
1029 DiagnosticsStatusNotificationRequest
,
1030 DiagnosticsStatusNotificationResponse
1031 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1032 status: OCPP16DiagnosticsStatus
.Uploading
,
1035 uploadResponse
= await ftpClient
.uploadFrom(
1037 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'),
1040 uri
.pathname
+ diagnosticsArchive
1042 if (uploadResponse
.code
=== 226) {
1043 await chargingStation
.ocppRequestService
.requestHandler
<
1044 DiagnosticsStatusNotificationRequest
,
1045 DiagnosticsStatusNotificationResponse
1046 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1047 status: OCPP16DiagnosticsStatus
.Uploaded
,
1052 return { fileName
: diagnosticsArchive
};
1054 throw new OCPPError(
1055 ErrorType
.GENERIC_ERROR
,
1056 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1057 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1059 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1062 throw new OCPPError(
1063 ErrorType
.GENERIC_ERROR
,
1064 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1065 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1067 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1070 await chargingStation
.ocppRequestService
.requestHandler
<
1071 DiagnosticsStatusNotificationRequest
,
1072 DiagnosticsStatusNotificationResponse
1073 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1074 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1079 return this.handleIncomingRequestError(
1081 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1083 { errorResponse
: Constants
.OCPP_RESPONSE_EMPTY
}
1088 `${chargingStation.logPrefix()} Unsupported protocol ${
1090 } to transfer the diagnostic logs archive`
1092 await chargingStation
.ocppRequestService
.requestHandler
<
1093 DiagnosticsStatusNotificationRequest
,
1094 DiagnosticsStatusNotificationResponse
1095 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1096 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1098 return Constants
.OCPP_RESPONSE_EMPTY
;
1102 private handleRequestTriggerMessage(
1103 chargingStation
: ChargingStation
,
1104 commandPayload
: OCPP16TriggerMessageRequest
1105 ): OCPP16TriggerMessageResponse
{
1107 !OCPP16ServiceUtils
.checkFeatureProfile(
1109 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1110 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1113 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1115 // TODO: factor out the check on connector id
1116 if (commandPayload
?.connectorId
< 0) {
1118 `${chargingStation.logPrefix()} ${
1119 OCPP16IncomingRequestCommand.TRIGGER_MESSAGE
1120 } incoming request received with invalid connectorId ${commandPayload.connectorId}`
1122 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1125 switch (commandPayload
.requestedMessage
) {
1126 case MessageTrigger
.BootNotification
:
1128 chargingStation
.ocppRequestService
1129 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1131 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1132 chargingStation
.bootNotificationRequest
,
1133 { skipBufferingOnError
: true, triggerMessage
: true }
1135 .then((response
) => {
1136 chargingStation
.bootNotificationResponse
= response
;
1139 /* This is intentional */
1141 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1142 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1143 case MessageTrigger
.Heartbeat
:
1145 chargingStation
.ocppRequestService
1146 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1148 OCPP16RequestCommand
.HEARTBEAT
,
1151 triggerMessage
: true,
1155 /* This is intentional */
1157 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1158 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1159 case MessageTrigger
.StatusNotification
:
1161 if (commandPayload
?.connectorId
) {
1162 chargingStation
.ocppRequestService
1163 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1165 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1167 connectorId
: commandPayload
.connectorId
,
1168 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1169 status: chargingStation
.getConnectorStatus(commandPayload
.connectorId
).status,
1172 triggerMessage
: true,
1176 /* This is intentional */
1179 for (const connectorId
of chargingStation
.connectors
.keys()) {
1180 chargingStation
.ocppRequestService
1182 OCPP16StatusNotificationRequest
,
1183 OCPP16StatusNotificationResponse
1186 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1189 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1190 status: chargingStation
.getConnectorStatus(connectorId
).status,
1193 triggerMessage
: true,
1197 /* This is intentional */
1201 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1202 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1204 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1207 return this.handleIncomingRequestError(
1209 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1211 { errorResponse
: Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
}