1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { createWriteStream
, readdirSync
} from
'node:fs';
4 import { dirname
, join
, resolve
} from
'node:path';
5 import { URL
, fileURLToPath
} from
'node:url';
7 import type { JSONSchemaType
} from
'ajv';
8 import { Client
, type FTPResponse
} from
'basic-ftp';
9 import { addSeconds
, differenceInSeconds
, isDate
, maxTime
, secondsToMilliseconds
} from
'date-fns';
10 import { create
} from
'tar';
12 import { OCPP16Constants
} from
'./OCPP16Constants';
13 import { OCPP16ServiceUtils
} from
'./OCPP16ServiceUtils';
16 canProceedChargingProfile
,
19 getConnectorChargingProfiles
,
20 prepareChargingProfileKind
,
21 removeExpiredReservations
,
22 setConfigurationKeyValue
,
23 } from
'../../../charging-station';
24 import { OCPPError
} from
'../../../exception';
26 type ChangeConfigurationRequest
,
27 type ChangeConfigurationResponse
,
28 type ClearChargingProfileRequest
,
29 type ClearChargingProfileResponse
,
33 type GetConfigurationRequest
,
34 type GetConfigurationResponse
,
35 type GetDiagnosticsRequest
,
36 type GetDiagnosticsResponse
,
37 type IncomingRequestHandler
,
40 OCPP16AuthorizationStatus
,
41 OCPP16AvailabilityType
,
42 type OCPP16BootNotificationRequest
,
43 type OCPP16BootNotificationResponse
,
44 type OCPP16CancelReservationRequest
,
45 type OCPP16ChangeAvailabilityRequest
,
46 type OCPP16ChangeAvailabilityResponse
,
47 OCPP16ChargePointErrorCode
,
48 OCPP16ChargePointStatus
,
49 type OCPP16ChargingProfile
,
50 OCPP16ChargingProfilePurposeType
,
51 type OCPP16ChargingSchedule
,
52 type OCPP16ClearCacheRequest
,
53 type OCPP16DataTransferRequest
,
54 type OCPP16DataTransferResponse
,
55 OCPP16DataTransferVendorId
,
56 OCPP16DiagnosticsStatus
,
57 type OCPP16DiagnosticsStatusNotificationRequest
,
58 type OCPP16DiagnosticsStatusNotificationResponse
,
60 type OCPP16FirmwareStatusNotificationRequest
,
61 type OCPP16FirmwareStatusNotificationResponse
,
62 type OCPP16GetCompositeScheduleRequest
,
63 type OCPP16GetCompositeScheduleResponse
,
64 type OCPP16HeartbeatRequest
,
65 type OCPP16HeartbeatResponse
,
66 OCPP16IncomingRequestCommand
,
69 type OCPP16ReserveNowRequest
,
70 type OCPP16ReserveNowResponse
,
71 OCPP16StandardParametersKey
,
72 type OCPP16StartTransactionRequest
,
73 type OCPP16StartTransactionResponse
,
74 type OCPP16StatusNotificationRequest
,
75 type OCPP16StatusNotificationResponse
,
76 OCPP16StopTransactionReason
,
77 OCPP16SupportedFeatureProfiles
,
78 type OCPP16TriggerMessageRequest
,
79 type OCPP16TriggerMessageResponse
,
80 type OCPP16UpdateFirmwareRequest
,
81 type OCPP16UpdateFirmwareResponse
,
82 type OCPPConfigurationKey
,
84 type RemoteStartTransactionRequest
,
85 type RemoteStopTransactionRequest
,
86 ReservationTerminationReason
,
88 type SetChargingProfileRequest
,
89 type SetChargingProfileResponse
,
90 type UnlockConnectorRequest
,
91 type UnlockConnectorResponse
,
92 } from
'../../../types';
97 formatDurationMilliSeconds
,
106 } from
'../../../utils';
107 import { OCPPIncomingRequestService
} from
'../OCPPIncomingRequestService';
109 const moduleName
= 'OCPP16IncomingRequestService';
111 export class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
112 protected jsonSchemas
: Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>;
113 private incomingRequestHandlers
: Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>;
115 public constructor() {
116 // if (new.target?.name === moduleName) {
117 // throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
119 super(OCPPVersion
.VERSION_16
);
120 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
122 OCPP16IncomingRequestCommand
.RESET
,
123 this.handleRequestReset
.bind(this) as unknown
as IncomingRequestHandler
,
126 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
127 this.handleRequestClearCache
.bind(this) as IncomingRequestHandler
,
130 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
131 this.handleRequestUnlockConnector
.bind(this) as unknown
as IncomingRequestHandler
,
134 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
135 this.handleRequestGetConfiguration
.bind(this) as IncomingRequestHandler
,
138 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
139 this.handleRequestChangeConfiguration
.bind(this) as unknown
as IncomingRequestHandler
,
142 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
143 this.handleRequestGetCompositeSchedule
.bind(this) as unknown
as IncomingRequestHandler
,
146 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
147 this.handleRequestSetChargingProfile
.bind(this) as unknown
as IncomingRequestHandler
,
150 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
151 this.handleRequestClearChargingProfile
.bind(this) as IncomingRequestHandler
,
154 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
155 this.handleRequestChangeAvailability
.bind(this) as unknown
as IncomingRequestHandler
,
158 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
159 this.handleRequestRemoteStartTransaction
.bind(this) as unknown
as IncomingRequestHandler
,
162 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
163 this.handleRequestRemoteStopTransaction
.bind(this) as unknown
as IncomingRequestHandler
,
166 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
167 this.handleRequestGetDiagnostics
.bind(this) as IncomingRequestHandler
,
170 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
171 this.handleRequestTriggerMessage
.bind(this) as unknown
as IncomingRequestHandler
,
174 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
175 this.handleRequestDataTransfer
.bind(this) as unknown
as IncomingRequestHandler
,
178 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
179 this.handleRequestUpdateFirmware
.bind(this) as unknown
as IncomingRequestHandler
,
182 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
183 this.handleRequestReserveNow
.bind(this) as unknown
as IncomingRequestHandler
,
186 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
187 this.handleRequestCancelReservation
.bind(this) as unknown
as IncomingRequestHandler
,
190 this.jsonSchemas
= new Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>([
192 OCPP16IncomingRequestCommand
.RESET
,
193 OCPP16ServiceUtils
.parseJsonSchemaFile
<ResetRequest
>(
194 'assets/json-schemas/ocpp/1.6/Reset.json',
200 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
201 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ClearCacheRequest
>(
202 'assets/json-schemas/ocpp/1.6/ClearCache.json',
208 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
209 OCPP16ServiceUtils
.parseJsonSchemaFile
<UnlockConnectorRequest
>(
210 'assets/json-schemas/ocpp/1.6/UnlockConnector.json',
216 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
217 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetConfigurationRequest
>(
218 'assets/json-schemas/ocpp/1.6/GetConfiguration.json',
224 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
225 OCPP16ServiceUtils
.parseJsonSchemaFile
<ChangeConfigurationRequest
>(
226 'assets/json-schemas/ocpp/1.6/ChangeConfiguration.json',
232 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
233 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetDiagnosticsRequest
>(
234 'assets/json-schemas/ocpp/1.6/GetDiagnostics.json',
240 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
241 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16GetCompositeScheduleRequest
>(
242 'assets/json-schemas/ocpp/1.6/GetCompositeSchedule.json',
248 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
249 OCPP16ServiceUtils
.parseJsonSchemaFile
<SetChargingProfileRequest
>(
250 'assets/json-schemas/ocpp/1.6/SetChargingProfile.json',
256 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
257 OCPP16ServiceUtils
.parseJsonSchemaFile
<ClearChargingProfileRequest
>(
258 'assets/json-schemas/ocpp/1.6/ClearChargingProfile.json',
264 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
265 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ChangeAvailabilityRequest
>(
266 'assets/json-schemas/ocpp/1.6/ChangeAvailability.json',
272 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
273 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStartTransactionRequest
>(
274 'assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json',
280 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
281 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStopTransactionRequest
>(
282 'assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json',
288 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
289 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16TriggerMessageRequest
>(
290 'assets/json-schemas/ocpp/1.6/TriggerMessage.json',
296 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
297 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16DataTransferRequest
>(
298 'assets/json-schemas/ocpp/1.6/DataTransfer.json',
304 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
305 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16UpdateFirmwareRequest
>(
306 'assets/json-schemas/ocpp/1.6/UpdateFirmware.json',
312 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
313 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ReserveNowRequest
>(
314 'assets/json-schemas/ocpp/1.6/ReserveNow.json',
320 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
321 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16CancelReservationRequest
>(
322 'assets/json-schemas/ocpp/1.6/CancelReservation.json',
328 this.validatePayload
= this.validatePayload
.bind(this) as (
329 chargingStation
: ChargingStation
,
330 commandName
: OCPP16IncomingRequestCommand
,
331 commandPayload
: JsonType
,
335 public async incomingRequestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
336 chargingStation
: ChargingStation
,
338 commandName
: OCPP16IncomingRequestCommand
,
339 commandPayload
: ReqType
,
341 let response
: ResType
;
343 chargingStation
.getOcppStrictCompliance() === true &&
344 chargingStation
.inPendingState() === true &&
345 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
346 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
349 ErrorType
.SECURITY_ERROR
,
350 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
354 )} while the charging station is in pending state on the central server`,
360 chargingStation
.isRegistered() === true ||
361 (chargingStation
.getOcppStrictCompliance() === false &&
362 chargingStation
.inUnknownState() === true)
365 this.incomingRequestHandlers
.has(commandName
) === true &&
366 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
) === true
369 this.validatePayload(chargingStation
, commandName
, commandPayload
);
370 // Call the method to build the response
371 response
= (await this.incomingRequestHandlers
.get(commandName
)!(
378 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
386 ErrorType
.NOT_IMPLEMENTED
,
387 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
398 ErrorType
.SECURITY_ERROR
,
399 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
403 )} while the charging station is not registered on the central server.`,
408 // Send the built response
409 await chargingStation
.ocppRequestService
.sendResponse(
417 private validatePayload(
418 chargingStation
: ChargingStation
,
419 commandName
: OCPP16IncomingRequestCommand
,
420 commandPayload
: JsonType
,
422 if (this.jsonSchemas
.has(commandName
) === true) {
423 return this.validateIncomingRequestPayload(
426 this.jsonSchemas
.get(commandName
)!,
431 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command '${commandName}' PDU validation`,
436 // Simulate charging station restart
437 private handleRequestReset(
438 chargingStation
: ChargingStation
,
439 commandPayload
: ResetRequest
,
441 const { type } = commandPayload
;
442 this.runInAsyncScope(
443 chargingStation
.reset
.bind(chargingStation
) as (
444 this: ChargingStation
,
448 `${type}Reset` as OCPP16StopTransactionReason
,
449 ).catch(Constants
.EMPTY_FUNCTION
);
451 `${chargingStation.logPrefix()} ${type} reset command received, simulating it. The station will be back online in ${formatDurationMilliSeconds(
452 chargingStation.stationInfo.resetTime!,
455 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
458 private async handleRequestUnlockConnector(
459 chargingStation
: ChargingStation
,
460 commandPayload
: UnlockConnectorRequest
,
461 ): Promise
<UnlockConnectorResponse
> {
462 const { connectorId
} = commandPayload
;
463 if (chargingStation
.hasConnector(connectorId
) === false) {
465 `${chargingStation.logPrefix()} Trying to unlock a non existing connector id ${connectorId}`,
467 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
469 if (connectorId
=== 0) {
470 logger
.error(`${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId}`);
471 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
473 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
474 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
476 OCPP16StopTransactionReason
.UNLOCK_COMMAND
,
478 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
479 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
;
481 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
483 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
486 OCPP16ChargePointStatus
.Available
,
488 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
;
491 private handleRequestGetConfiguration(
492 chargingStation
: ChargingStation
,
493 commandPayload
: GetConfigurationRequest
,
494 ): GetConfigurationResponse
{
495 const { key
} = commandPayload
;
496 const configurationKey
: OCPPConfigurationKey
[] = [];
497 const unknownKey
: string[] = [];
498 if (isUndefined(key
) === true) {
499 for (const configuration
of chargingStation
.ocppConfiguration
!.configurationKey
!) {
500 if (isUndefined(configuration
.visible
) === true) {
501 configuration
.visible
= true;
503 if (configuration
.visible
=== false) {
506 configurationKey
.push({
507 key
: configuration
.key
,
508 readonly: configuration
.readonly,
509 value
: configuration
.value
,
512 } else if (isNotEmptyArray(key
) === true) {
513 for (const k
of key
!) {
514 const keyFound
= getConfigurationKey(chargingStation
, k
, true);
516 if (isUndefined(keyFound
.visible
) === true) {
517 keyFound
.visible
= true;
519 if (keyFound
.visible
=== false) {
522 configurationKey
.push({
524 readonly: keyFound
.readonly,
525 value
: keyFound
.value
,
538 private handleRequestChangeConfiguration(
539 chargingStation
: ChargingStation
,
540 commandPayload
: ChangeConfigurationRequest
,
541 ): ChangeConfigurationResponse
{
542 const { key
, value
} = commandPayload
;
543 const keyToChange
= getConfigurationKey(chargingStation
, key
, true);
544 if (keyToChange
?.readonly === true) {
545 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
546 } else if (keyToChange
?.readonly === false) {
547 let valueChanged
= false;
548 if (keyToChange
.value
!== value
) {
549 setConfigurationKeyValue(chargingStation
, key
, value
, true);
552 let triggerHeartbeatRestart
= false;
554 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
555 OCPP16StandardParametersKey
.HeartBeatInterval
&&
558 setConfigurationKeyValue(
560 OCPP16StandardParametersKey
.HeartbeatInterval
,
563 triggerHeartbeatRestart
= true;
566 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
567 OCPP16StandardParametersKey
.HeartbeatInterval
&&
570 setConfigurationKeyValue(
572 OCPP16StandardParametersKey
.HeartBeatInterval
,
575 triggerHeartbeatRestart
= true;
577 if (triggerHeartbeatRestart
) {
578 chargingStation
.restartHeartbeat();
581 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
582 OCPP16StandardParametersKey
.WebSocketPingInterval
&&
585 chargingStation
.restartWebSocketPing();
587 if (keyToChange
.reboot
) {
588 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
590 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
592 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
595 private handleRequestSetChargingProfile(
596 chargingStation
: ChargingStation
,
597 commandPayload
: SetChargingProfileRequest
,
598 ): SetChargingProfileResponse
{
600 OCPP16ServiceUtils
.checkFeatureProfile(
602 OCPP16SupportedFeatureProfiles
.SmartCharging
,
603 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
606 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
608 const { connectorId
, csChargingProfiles
} = commandPayload
;
609 if (chargingStation
.hasConnector(connectorId
) === false) {
611 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector id ${connectorId}`,
613 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
616 csChargingProfiles
.chargingProfilePurpose
===
617 OCPP16ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
620 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
623 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
627 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId}`,
629 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
631 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
);
633 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
635 connectorStatus
?.transactionStarted
=== false
638 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} without a started transaction`,
640 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
643 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
645 connectorStatus
?.transactionStarted
=== true &&
646 csChargingProfiles
.transactionId
!== connectorStatus
?.transactionId
649 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} with a different transaction id ${
650 csChargingProfiles.transactionId
651 } than the started transaction id ${connectorStatus?.transactionId}`,
653 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
655 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, csChargingProfiles
);
657 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${connectorId}: %j`,
660 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
663 private handleRequestGetCompositeSchedule(
664 chargingStation
: ChargingStation
,
665 commandPayload
: OCPP16GetCompositeScheduleRequest
,
666 ): OCPP16GetCompositeScheduleResponse
{
668 OCPP16ServiceUtils
.checkFeatureProfile(
670 OCPP16SupportedFeatureProfiles
.SmartCharging
,
671 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
674 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
676 const { connectorId
, duration
, chargingRateUnit
} = commandPayload
;
677 if (chargingStation
.hasConnector(connectorId
) === false) {
679 `${chargingStation.logPrefix()} Trying to get composite schedule to a non existing connector id ${connectorId}`,
681 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
683 if (connectorId
=== 0) {
685 `${chargingStation.logPrefix()} Get composite schedule on connector id ${connectorId} is not yet supported`,
687 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
689 if (chargingRateUnit
) {
691 `${chargingStation.logPrefix()} Get composite schedule with a specified rate unit is not yet supported, no conversion will be done`,
694 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)!;
697 connectorStatus
?.chargingProfiles
&&
698 isEmptyArray(chargingStation
.getConnectorStatus(0)?.chargingProfiles
),
701 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
703 const currentDate
= new Date();
704 const compositeScheduleInterval
: Interval
= {
706 end
: addSeconds(currentDate
, duration
),
708 // Get charging profiles sorted by connector id then stack level
709 const chargingProfiles
: OCPP16ChargingProfile
[] = getConnectorChargingProfiles(
713 let previousCompositeSchedule
: OCPP16ChargingSchedule
| undefined;
714 let compositeSchedule
: OCPP16ChargingSchedule
| undefined;
715 for (const chargingProfile
of chargingProfiles
) {
717 isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
) &&
718 connectorStatus
?.transactionStarted
721 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
722 chargingProfile.chargingProfileId
723 } has no startSchedule defined. Trying to set it to the connector current transaction start date`,
725 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
726 chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
;
729 !isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
) &&
730 !isDate(chargingProfile
.chargingSchedule
?.startSchedule
)
733 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
734 chargingProfile.chargingProfileId
735 } startSchedule property is not a Date instance. Trying to convert it to a Date instance`,
737 chargingProfile
.chargingSchedule
.startSchedule
= convertToDate(
738 chargingProfile
.chargingSchedule
?.startSchedule
,
742 !isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
) &&
743 isNullOrUndefined(chargingProfile
.chargingSchedule
?.duration
)
746 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
747 chargingProfile.chargingProfileId
748 } has no duration defined and will be set to the maximum time allowed`,
750 // OCPP specifies that if duration is not defined, it should be infinite
751 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(
753 chargingProfile
.chargingSchedule
.startSchedule
!,
757 !prepareChargingProfileKind(
760 compositeScheduleInterval
.start
as Date,
761 chargingStation
.logPrefix(),
767 !canProceedChargingProfile(
769 compositeScheduleInterval
.start
as Date,
770 chargingStation
.logPrefix(),
775 compositeSchedule
= OCPP16ServiceUtils
.composeChargingSchedules(
776 previousCompositeSchedule
,
777 chargingProfile
.chargingSchedule
,
778 compositeScheduleInterval
,
780 previousCompositeSchedule
= compositeSchedule
;
782 if (compositeSchedule
) {
784 status: GenericStatus
.Accepted
,
785 scheduleStart
: compositeSchedule
.startSchedule
!,
787 chargingSchedule
: compositeSchedule
,
790 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
793 private handleRequestClearChargingProfile(
794 chargingStation
: ChargingStation
,
795 commandPayload
: ClearChargingProfileRequest
,
796 ): ClearChargingProfileResponse
{
798 OCPP16ServiceUtils
.checkFeatureProfile(
800 OCPP16SupportedFeatureProfiles
.SmartCharging
,
801 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
804 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
806 const { connectorId
} = commandPayload
;
807 if (chargingStation
.hasConnector(connectorId
!) === false) {
809 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector id ${connectorId}`,
811 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
813 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
!);
814 if (!isNullOrUndefined(connectorId
) && isNotEmptyArray(connectorStatus
?.chargingProfiles
)) {
815 connectorStatus
!.chargingProfiles
= [];
817 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}`,
819 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
821 if (isNullOrUndefined(connectorId
)) {
822 let clearedCP
= false;
823 if (chargingStation
.hasEvses
) {
824 for (const evseStatus
of chargingStation
.evses
.values()) {
825 for (const status of evseStatus
.connectors
.values()) {
826 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
829 status.chargingProfiles
,
834 for (const id
of chargingStation
.connectors
.keys()) {
835 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
838 chargingStation
.getConnectorStatus(id
)?.chargingProfiles
,
843 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
846 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
849 private async handleRequestChangeAvailability(
850 chargingStation
: ChargingStation
,
851 commandPayload
: OCPP16ChangeAvailabilityRequest
,
852 ): Promise
<OCPP16ChangeAvailabilityResponse
> {
853 const { connectorId
, type } = commandPayload
;
854 if (chargingStation
.hasConnector(connectorId
) === false) {
856 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector id ${connectorId}`,
858 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
860 const chargePointStatus
: OCPP16ChargePointStatus
=
861 type === OCPP16AvailabilityType
.Operative
862 ? OCPP16ChargePointStatus
.Available
863 : OCPP16ChargePointStatus
.Unavailable
;
864 if (connectorId
=== 0) {
865 let response
: OCPP16ChangeAvailabilityResponse
;
866 if (chargingStation
.hasEvses
) {
867 for (const evseStatus
of chargingStation
.evses
.values()) {
868 response
= await OCPP16ServiceUtils
.changeAvailability(
870 [...evseStatus
.connectors
.keys()],
876 response
= await OCPP16ServiceUtils
.changeAvailability(
878 [...chargingStation
.connectors
.keys()],
886 (chargingStation
.isChargingStationAvailable() === true ||
887 (chargingStation
.isChargingStationAvailable() === false &&
888 type === OCPP16AvailabilityType
.Inoperative
))
890 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
891 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type;
892 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
894 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type;
895 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
900 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
902 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
905 private async handleRequestRemoteStartTransaction(
906 chargingStation
: ChargingStation
,
907 commandPayload
: RemoteStartTransactionRequest
,
908 ): Promise
<GenericResponse
> {
909 const { connectorId
: transactionConnectorId
, idTag
, chargingProfile
} = commandPayload
;
910 if (chargingStation
.hasConnector(transactionConnectorId
) === false) {
911 return this.notifyRemoteStartTransactionRejected(
913 transactionConnectorId
,
918 !chargingStation
.isChargingStationAvailable() ||
919 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
921 return this.notifyRemoteStartTransactionRejected(
923 transactionConnectorId
,
927 const remoteStartTransactionLogMsg
= `
928 ${chargingStation.logPrefix()} Transaction remotely STARTED on ${
929 chargingStation.stationInfo.chargingStationId
930 }#${transactionConnectorId} for idTag '${idTag}'`;
931 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
933 transactionConnectorId
,
934 OCPP16ChargePointStatus
.Preparing
,
936 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
)!;
937 // Authorization check required
939 chargingStation
.getAuthorizeRemoteTxRequests() === true &&
940 (await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
942 // Authorization successful, start transaction
945 this.setRemoteStartTransactionChargingProfile(
947 transactionConnectorId
,
949 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
953 connectorStatus
.transactionRemoteStarted
= true;
956 await chargingStation
.ocppRequestService
.requestHandler
<
957 OCPP16StartTransactionRequest
,
958 OCPP16StartTransactionResponse
959 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
960 connectorId
: transactionConnectorId
,
963 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
965 logger
.debug(remoteStartTransactionLogMsg
);
966 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
968 return this.notifyRemoteStartTransactionRejected(
970 transactionConnectorId
,
974 return this.notifyRemoteStartTransactionRejected(
976 transactionConnectorId
,
980 // No authorization check required, start transaction
983 this.setRemoteStartTransactionChargingProfile(
985 transactionConnectorId
,
987 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
991 connectorStatus
.transactionRemoteStarted
= true;
994 await chargingStation
.ocppRequestService
.requestHandler
<
995 OCPP16StartTransactionRequest
,
996 OCPP16StartTransactionResponse
997 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
998 connectorId
: transactionConnectorId
,
1001 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
1003 logger
.debug(remoteStartTransactionLogMsg
);
1004 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
1006 return this.notifyRemoteStartTransactionRejected(
1008 transactionConnectorId
,
1012 return this.notifyRemoteStartTransactionRejected(
1014 transactionConnectorId
,
1019 private async notifyRemoteStartTransactionRejected(
1020 chargingStation
: ChargingStation
,
1021 connectorId
: number,
1023 ): Promise
<GenericResponse
> {
1024 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
);
1025 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Available
) {
1026 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1029 OCPP16ChargePointStatus
.Available
,
1033 `${chargingStation.logPrefix()} Remote starting transaction REJECTED on connector id ${connectorId}, idTag '${idTag}', availability '${connectorStatus?.availability}', status '${connectorStatus?.status}'`,
1035 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
1038 private setRemoteStartTransactionChargingProfile(
1039 chargingStation
: ChargingStation
,
1040 connectorId
: number,
1041 chargingProfile
: OCPP16ChargingProfile
,
1043 if (chargingProfile
?.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
) {
1044 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
);
1046 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}: %j`,
1052 `${chargingStation.logPrefix()} Not allowed to set ${
1053 chargingProfile.chargingProfilePurpose
1054 } charging profile(s) at remote start transaction`,
1059 private async handleRequestRemoteStopTransaction(
1060 chargingStation
: ChargingStation
,
1061 commandPayload
: RemoteStopTransactionRequest
,
1062 ): Promise
<GenericResponse
> {
1063 const { transactionId
} = commandPayload
;
1064 if (chargingStation
.hasEvses
) {
1065 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1067 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1068 if (connectorStatus
.transactionId
=== transactionId
) {
1069 return OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
);
1075 for (const connectorId
of chargingStation
.connectors
.keys()) {
1078 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
1080 return OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
);
1085 `${chargingStation.logPrefix()} Trying to remote stop a non existing transaction with id ${transactionId}`,
1087 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
1090 private handleRequestUpdateFirmware(
1091 chargingStation
: ChargingStation
,
1092 commandPayload
: OCPP16UpdateFirmwareRequest
,
1093 ): OCPP16UpdateFirmwareResponse
{
1095 OCPP16ServiceUtils
.checkFeatureProfile(
1097 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1098 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
1102 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: feature profile not supported`,
1104 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1106 let { retrieveDate
} = commandPayload
;
1108 !isNullOrUndefined(chargingStation
.stationInfo
.firmwareStatus
) &&
1109 chargingStation
.stationInfo
.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
1112 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: firmware update is already in progress`,
1114 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1116 retrieveDate
= convertToDate(retrieveDate
)!;
1117 const now
= Date.now();
1118 if (retrieveDate
?.getTime() <= now
) {
1119 this.runInAsyncScope(
1120 this.updateFirmwareSimulation
.bind(this) as (
1121 this: OCPP16IncomingRequestService
,
1126 ).catch(Constants
.EMPTY_FUNCTION
);
1130 this.runInAsyncScope(
1131 this.updateFirmwareSimulation
.bind(this) as (
1132 this: OCPP16IncomingRequestService
,
1137 ).catch(Constants
.EMPTY_FUNCTION
);
1139 retrieveDate
?.getTime() - now
,
1142 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1145 private async updateFirmwareSimulation(
1146 chargingStation
: ChargingStation
,
1150 if (checkChargingStation(chargingStation
, chargingStation
.logPrefix()) === false) {
1153 if (chargingStation
.hasEvses
) {
1154 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1156 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1157 if (connectorStatus
?.transactionStarted
=== false) {
1158 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1161 OCPP16ChargePointStatus
.Unavailable
,
1168 for (const connectorId
of chargingStation
.connectors
.keys()) {
1171 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1173 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1176 OCPP16ChargePointStatus
.Unavailable
,
1181 await chargingStation
.ocppRequestService
.requestHandler
<
1182 OCPP16FirmwareStatusNotificationRequest
,
1183 OCPP16FirmwareStatusNotificationResponse
1184 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1185 status: OCPP16FirmwareStatus
.Downloading
,
1187 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
;
1189 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1190 OCPP16FirmwareStatus
.DownloadFailed
1192 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1193 await chargingStation
.ocppRequestService
.requestHandler
<
1194 OCPP16FirmwareStatusNotificationRequest
,
1195 OCPP16FirmwareStatusNotificationResponse
1196 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1197 status: chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
,
1199 chargingStation
.stationInfo
.firmwareStatus
=
1200 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
;
1203 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1204 await chargingStation
.ocppRequestService
.requestHandler
<
1205 OCPP16FirmwareStatusNotificationRequest
,
1206 OCPP16FirmwareStatusNotificationResponse
1207 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1208 status: OCPP16FirmwareStatus
.Downloaded
,
1210 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
;
1211 let wasTransactionsStarted
= false;
1212 let transactionsStarted
: boolean;
1214 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions();
1215 if (runningTransactions
> 0) {
1216 const waitTime
= secondsToMilliseconds(15);
1218 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation: ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1220 )} before continuing firmware update simulation`,
1222 await sleep(waitTime
);
1223 transactionsStarted
= true;
1224 wasTransactionsStarted
= true;
1226 if (chargingStation
.hasEvses
) {
1227 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1229 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1230 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Unavailable
) {
1231 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1234 OCPP16ChargePointStatus
.Unavailable
,
1241 for (const connectorId
of chargingStation
.connectors
.keys()) {
1244 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1245 OCPP16ChargePointStatus
.Unavailable
1247 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1250 OCPP16ChargePointStatus
.Unavailable
,
1255 transactionsStarted
= false;
1257 } while (transactionsStarted
);
1258 !wasTransactionsStarted
&&
1259 (await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
))));
1260 if (checkChargingStation(chargingStation
, chargingStation
.logPrefix()) === false) {
1263 await chargingStation
.ocppRequestService
.requestHandler
<
1264 OCPP16FirmwareStatusNotificationRequest
,
1265 OCPP16FirmwareStatusNotificationResponse
1266 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1267 status: OCPP16FirmwareStatus
.Installing
,
1269 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Installing
;
1271 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1272 OCPP16FirmwareStatus
.InstallationFailed
1274 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1275 await chargingStation
.ocppRequestService
.requestHandler
<
1276 OCPP16FirmwareStatusNotificationRequest
,
1277 OCPP16FirmwareStatusNotificationResponse
1278 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1279 status: chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
,
1281 chargingStation
.stationInfo
.firmwareStatus
=
1282 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
;
1285 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1286 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1287 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
);
1291 private async handleRequestGetDiagnostics(
1292 chargingStation
: ChargingStation
,
1293 commandPayload
: GetDiagnosticsRequest
,
1294 ): Promise
<GetDiagnosticsResponse
> {
1296 OCPP16ServiceUtils
.checkFeatureProfile(
1298 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1299 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1303 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Cannot get diagnostics: feature profile not supported`,
1305 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1307 const { location
} = commandPayload
;
1308 const uri
= new URL(location
);
1309 if (uri
.protocol
.startsWith('ftp:')) {
1310 let ftpClient
: Client
| undefined;
1312 const logFiles
= readdirSync(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'))
1313 .filter((file
) => file
.endsWith('.log'))
1314 .map((file
) => join('./', file
));
1315 const diagnosticsArchive
= `${chargingStation.stationInfo.chargingStationId}_logs.tar.gz`;
1316 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
));
1317 ftpClient
= new Client();
1318 const accessResponse
= await ftpClient
.access({
1320 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1321 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1322 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
}),
1324 let uploadResponse
: FTPResponse
| undefined;
1325 if (accessResponse
.code
=== 220) {
1326 ftpClient
.trackProgress((info
) => {
1328 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1330 } bytes transferred from diagnostics archive ${info.name}`,
1332 chargingStation
.ocppRequestService
1334 OCPP16DiagnosticsStatusNotificationRequest
,
1335 OCPP16DiagnosticsStatusNotificationResponse
1336 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1337 status: OCPP16DiagnosticsStatus
.Uploading
,
1341 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Error while sending '${
1342 OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION
1348 uploadResponse
= await ftpClient
.uploadFrom(
1349 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1350 `${uri.pathname}${diagnosticsArchive}`,
1352 if (uploadResponse
.code
=== 226) {
1353 await chargingStation
.ocppRequestService
.requestHandler
<
1354 OCPP16DiagnosticsStatusNotificationRequest
,
1355 OCPP16DiagnosticsStatusNotificationResponse
1356 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1357 status: OCPP16DiagnosticsStatus
.Uploaded
,
1362 return { fileName
: diagnosticsArchive
};
1364 throw new OCPPError(
1365 ErrorType
.GENERIC_ERROR
,
1366 `Diagnostics transfer failed with error code ${accessResponse.code}${
1367 uploadResponse?.code && `|${uploadResponse?.code}
`
1369 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1372 throw new OCPPError(
1373 ErrorType
.GENERIC_ERROR
,
1374 `Diagnostics transfer failed with error code ${accessResponse.code}${
1375 uploadResponse?.code && `|${uploadResponse?.code}
`
1377 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1380 await chargingStation
.ocppRequestService
.requestHandler
<
1381 OCPP16DiagnosticsStatusNotificationRequest
,
1382 OCPP16DiagnosticsStatusNotificationResponse
1383 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1384 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1389 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1391 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1393 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
},
1398 `${chargingStation.logPrefix()} Unsupported protocol ${
1400 } to transfer the diagnostic logs archive`,
1402 await chargingStation
.ocppRequestService
.requestHandler
<
1403 OCPP16DiagnosticsStatusNotificationRequest
,
1404 OCPP16DiagnosticsStatusNotificationResponse
1405 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1406 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1408 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1412 private handleRequestTriggerMessage(
1413 chargingStation
: ChargingStation
,
1414 commandPayload
: OCPP16TriggerMessageRequest
,
1415 ): OCPP16TriggerMessageResponse
{
1416 const { requestedMessage
, connectorId
} = commandPayload
;
1418 !OCPP16ServiceUtils
.checkFeatureProfile(
1420 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1421 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1423 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1425 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1428 !OCPP16ServiceUtils
.isConnectorIdValid(
1430 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1434 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1437 switch (requestedMessage
) {
1438 case OCPP16MessageTrigger
.BootNotification
:
1440 chargingStation
.ocppRequestService
1441 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1443 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1444 chargingStation
.bootNotificationRequest
,
1445 { skipBufferingOnError
: true, triggerMessage
: true },
1447 .then((response
) => {
1448 chargingStation
.bootNotificationResponse
= response
;
1450 .catch(Constants
.EMPTY_FUNCTION
);
1451 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1452 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1453 case OCPP16MessageTrigger
.Heartbeat
:
1455 chargingStation
.ocppRequestService
1456 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1458 OCPP16RequestCommand
.HEARTBEAT
,
1461 triggerMessage
: true,
1464 .catch(Constants
.EMPTY_FUNCTION
);
1465 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1466 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1467 case OCPP16MessageTrigger
.StatusNotification
:
1469 if (!isNullOrUndefined(connectorId
)) {
1470 chargingStation
.ocppRequestService
1471 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1473 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1476 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1477 status: chargingStation
.getConnectorStatus(connectorId
!)?.status,
1480 triggerMessage
: true,
1483 .catch(Constants
.EMPTY_FUNCTION
);
1485 // eslint-disable-next-line no-lonely-if
1486 if (chargingStation
.hasEvses
) {
1487 for (const evseStatus
of chargingStation
.evses
.values()) {
1488 for (const [id
, connectorStatus
] of evseStatus
.connectors
) {
1489 chargingStation
.ocppRequestService
1491 OCPP16StatusNotificationRequest
,
1492 OCPP16StatusNotificationResponse
1495 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1498 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1499 status: connectorStatus
.status,
1502 triggerMessage
: true,
1505 .catch(Constants
.EMPTY_FUNCTION
);
1509 for (const id
of chargingStation
.connectors
.keys()) {
1510 chargingStation
.ocppRequestService
1512 OCPP16StatusNotificationRequest
,
1513 OCPP16StatusNotificationResponse
1516 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1519 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1520 status: chargingStation
.getConnectorStatus(id
)?.status,
1523 triggerMessage
: true,
1526 .catch(Constants
.EMPTY_FUNCTION
);
1530 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1531 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1533 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1536 return this.handleIncomingRequestError
<OCPP16TriggerMessageResponse
>(
1538 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1540 { errorResponse
: OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
},
1545 private handleRequestDataTransfer(
1546 chargingStation
: ChargingStation
,
1547 commandPayload
: OCPP16DataTransferRequest
,
1548 ): OCPP16DataTransferResponse
{
1549 const { vendorId
} = commandPayload
;
1551 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1552 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
;
1554 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
;
1556 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1558 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1560 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
},
1565 private async handleRequestReserveNow(
1566 chargingStation
: ChargingStation
,
1567 commandPayload
: OCPP16ReserveNowRequest
,
1568 ): Promise
<OCPP16ReserveNowResponse
> {
1570 !OCPP16ServiceUtils
.checkFeatureProfile(
1572 OCPP16SupportedFeatureProfiles
.Reservation
,
1573 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1576 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1578 const { reservationId
, idTag
, connectorId
} = commandPayload
;
1579 let response
: OCPP16ReserveNowResponse
;
1581 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1582 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1584 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1585 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1587 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1588 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1590 await removeExpiredReservations(chargingStation
);
1591 switch (chargingStation
.getConnectorStatus(connectorId
)!.status) {
1592 case OCPP16ChargePointStatus
.Faulted
:
1593 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
;
1595 case OCPP16ChargePointStatus
.Preparing
:
1596 case OCPP16ChargePointStatus
.Charging
:
1597 case OCPP16ChargePointStatus
.SuspendedEV
:
1598 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1599 case OCPP16ChargePointStatus
.Finishing
:
1600 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1602 case OCPP16ChargePointStatus
.Unavailable
:
1603 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
;
1605 case OCPP16ChargePointStatus
.Reserved
:
1606 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1607 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1610 // eslint-disable-next-line no-fallthrough
1612 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1613 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1616 await chargingStation
.addReservation({
1617 id
: commandPayload
.reservationId
,
1620 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
;
1625 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
;
1626 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1628 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1630 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
},
1635 private async handleRequestCancelReservation(
1636 chargingStation
: ChargingStation
,
1637 commandPayload
: OCPP16CancelReservationRequest
,
1638 ): Promise
<GenericResponse
> {
1640 !OCPP16ServiceUtils
.checkFeatureProfile(
1642 OCPP16SupportedFeatureProfiles
.Reservation
,
1643 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1646 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
;
1649 const { reservationId
} = commandPayload
;
1650 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
);
1651 if (isUndefined(reservation
)) {
1653 `${chargingStation.logPrefix()} Reservation with id ${reservationId} does not exist on charging station`,
1655 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
;
1657 await chargingStation
.removeReservation(
1659 ReservationTerminationReason
.RESERVATION_CANCELED
,
1661 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
;
1663 return this.handleIncomingRequestError
<GenericResponse
>(
1665 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1667 { errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
},