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:
379 Handle incoming request error:`,
387 ErrorType
.NOT_IMPLEMENTED
,
388 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
399 ErrorType
.SECURITY_ERROR
,
400 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
404 )} while the charging station is not registered on the central server.`,
409 // Send the built response
410 await chargingStation
.ocppRequestService
.sendResponse(
418 private validatePayload(
419 chargingStation
: ChargingStation
,
420 commandName
: OCPP16IncomingRequestCommand
,
421 commandPayload
: JsonType
,
423 if (this.jsonSchemas
.has(commandName
) === true) {
424 return this.validateIncomingRequestPayload(
427 this.jsonSchemas
.get(commandName
)!,
432 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found
433 for command '${commandName}' PDU validation`,
438 // Simulate charging station restart
439 private handleRequestReset(
440 chargingStation
: ChargingStation
,
441 commandPayload
: ResetRequest
,
443 const { type } = commandPayload
;
444 this.runInAsyncScope(
445 chargingStation
.reset
.bind(chargingStation
) as (
446 this: ChargingStation
,
450 `${type}Reset` as OCPP16StopTransactionReason
,
451 ).catch(Constants
.EMPTY_FUNCTION
);
453 `${chargingStation.logPrefix()} ${type} reset command received, simulating it. The station will be
454 back online in ${formatDurationMilliSeconds(chargingStation.stationInfo.resetTime!)}`,
456 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
459 private async handleRequestUnlockConnector(
460 chargingStation
: ChargingStation
,
461 commandPayload
: UnlockConnectorRequest
,
462 ): Promise
<UnlockConnectorResponse
> {
463 const { connectorId
} = commandPayload
;
464 if (chargingStation
.hasConnector(connectorId
) === false) {
466 `${chargingStation.logPrefix()} Trying to unlock a non existing
467 connector id ${connectorId}`,
469 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
471 if (connectorId
=== 0) {
472 logger
.error(`${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId}`);
473 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
475 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
476 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
478 OCPP16StopTransactionReason
.UNLOCK_COMMAND
,
480 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
481 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
;
483 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
485 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
488 OCPP16ChargePointStatus
.Available
,
490 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
;
493 private handleRequestGetConfiguration(
494 chargingStation
: ChargingStation
,
495 commandPayload
: GetConfigurationRequest
,
496 ): GetConfigurationResponse
{
497 const { key
} = commandPayload
;
498 const configurationKey
: OCPPConfigurationKey
[] = [];
499 const unknownKey
: string[] = [];
500 if (isUndefined(key
) === true) {
501 for (const configuration
of chargingStation
.ocppConfiguration
!.configurationKey
!) {
502 if (isUndefined(configuration
.visible
) === true) {
503 configuration
.visible
= true;
505 if (configuration
.visible
=== false) {
508 configurationKey
.push({
509 key
: configuration
.key
,
510 readonly: configuration
.readonly,
511 value
: configuration
.value
,
514 } else if (isNotEmptyArray(key
) === true) {
515 for (const k
of key
!) {
516 const keyFound
= getConfigurationKey(chargingStation
, k
, true);
518 if (isUndefined(keyFound
.visible
) === true) {
519 keyFound
.visible
= true;
521 if (keyFound
.visible
=== false) {
524 configurationKey
.push({
526 readonly: keyFound
.readonly,
527 value
: keyFound
.value
,
540 private handleRequestChangeConfiguration(
541 chargingStation
: ChargingStation
,
542 commandPayload
: ChangeConfigurationRequest
,
543 ): ChangeConfigurationResponse
{
544 const { key
, value
} = commandPayload
;
545 const keyToChange
= getConfigurationKey(chargingStation
, key
, true);
546 if (keyToChange
?.readonly === true) {
547 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
548 } else if (keyToChange
?.readonly === false) {
549 let valueChanged
= false;
550 if (keyToChange
.value
!== value
) {
551 setConfigurationKeyValue(chargingStation
, key
, value
, true);
554 let triggerHeartbeatRestart
= false;
556 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
557 OCPP16StandardParametersKey
.HeartBeatInterval
&&
560 setConfigurationKeyValue(
562 OCPP16StandardParametersKey
.HeartbeatInterval
,
565 triggerHeartbeatRestart
= true;
568 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
569 OCPP16StandardParametersKey
.HeartbeatInterval
&&
572 setConfigurationKeyValue(
574 OCPP16StandardParametersKey
.HeartBeatInterval
,
577 triggerHeartbeatRestart
= true;
579 if (triggerHeartbeatRestart
) {
580 chargingStation
.restartHeartbeat();
583 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
584 OCPP16StandardParametersKey
.WebSocketPingInterval
&&
587 chargingStation
.restartWebSocketPing();
589 if (keyToChange
.reboot
) {
590 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
592 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
594 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
597 private handleRequestSetChargingProfile(
598 chargingStation
: ChargingStation
,
599 commandPayload
: SetChargingProfileRequest
,
600 ): SetChargingProfileResponse
{
602 OCPP16ServiceUtils
.checkFeatureProfile(
604 OCPP16SupportedFeatureProfiles
.SmartCharging
,
605 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
608 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
610 const { connectorId
, csChargingProfiles
} = commandPayload
;
611 if (chargingStation
.hasConnector(connectorId
) === false) {
613 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a
614 non existing connector id ${connectorId}`,
616 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
619 csChargingProfiles
.chargingProfilePurpose
===
620 OCPP16ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
623 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
626 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
630 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s)
631 on connector ${connectorId}`,
633 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
635 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
);
637 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
639 connectorStatus
?.transactionStarted
=== false
642 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s)
643 on connector ${connectorId} without a started transaction`,
645 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
648 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
650 connectorStatus
?.transactionStarted
=== true &&
651 csChargingProfiles
.transactionId
!== connectorStatus
?.transactionId
654 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s)
655 on connector ${connectorId} with a different transaction id ${
656 csChargingProfiles.transactionId
657 } than the started transaction id ${connectorStatus?.transactionId}`,
659 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
661 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, csChargingProfiles
);
663 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${connectorId}: %j`,
666 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
669 private handleRequestGetCompositeSchedule(
670 chargingStation
: ChargingStation
,
671 commandPayload
: OCPP16GetCompositeScheduleRequest
,
672 ): OCPP16GetCompositeScheduleResponse
{
674 OCPP16ServiceUtils
.checkFeatureProfile(
676 OCPP16SupportedFeatureProfiles
.SmartCharging
,
677 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
680 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
682 const { connectorId
, duration
, chargingRateUnit
} = commandPayload
;
683 if (chargingStation
.hasConnector(connectorId
) === false) {
685 `${chargingStation.logPrefix()} Trying to get composite schedule to a
686 non existing connector id ${connectorId}`,
688 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
690 if (connectorId
=== 0) {
692 `${chargingStation.logPrefix()} Get composite schedule on connector id ${connectorId} is not yet supported`,
694 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
696 if (chargingRateUnit
) {
698 `${chargingStation.logPrefix()} Get composite schedule with a specified rate unit is not yet supported, no conversion will be done`,
701 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)!;
704 connectorStatus
?.chargingProfiles
&&
705 isEmptyArray(chargingStation
.getConnectorStatus(0)?.chargingProfiles
),
708 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
710 const currentDate
= new Date();
711 const compositeScheduleInterval
: Interval
= {
713 end
: addSeconds(currentDate
, duration
),
715 // Get charging profiles sorted by connector id then stack level
716 const chargingProfiles
: OCPP16ChargingProfile
[] = getConnectorChargingProfiles(
720 let previousCompositeSchedule
: OCPP16ChargingSchedule
| undefined;
721 let compositeSchedule
: OCPP16ChargingSchedule
| undefined;
722 for (const chargingProfile
of chargingProfiles
) {
724 isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
) &&
725 connectorStatus
?.transactionStarted
728 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
729 chargingProfile.chargingProfileId
730 } has no startSchedule defined. Trying to set it to the connector current transaction start date`,
732 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
733 chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
;
736 !isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
) &&
737 !isDate(chargingProfile
.chargingSchedule
?.startSchedule
)
740 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
741 chargingProfile.chargingProfileId
742 } startSchedule property is not a Date instance. Trying to convert it to a Date instance`,
744 chargingProfile
.chargingSchedule
.startSchedule
= convertToDate(
745 chargingProfile
.chargingSchedule
?.startSchedule
,
749 !isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
) &&
750 isNullOrUndefined(chargingProfile
.chargingSchedule
?.duration
)
753 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
754 chargingProfile.chargingProfileId
755 } has no duration defined and will be set to the maximum time allowed`,
757 // OCPP specifies that if duration is not defined, it should be infinite
758 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(
760 chargingProfile
.chargingSchedule
.startSchedule
!,
764 !prepareChargingProfileKind(
767 compositeScheduleInterval
.start
as Date,
768 chargingStation
.logPrefix(),
774 !canProceedChargingProfile(
776 compositeScheduleInterval
.start
as Date,
777 chargingStation
.logPrefix(),
782 compositeSchedule
= OCPP16ServiceUtils
.composeChargingSchedules(
783 previousCompositeSchedule
,
784 chargingProfile
.chargingSchedule
,
785 compositeScheduleInterval
,
787 previousCompositeSchedule
= compositeSchedule
;
789 if (compositeSchedule
) {
791 status: GenericStatus
.Accepted
,
792 scheduleStart
: compositeSchedule
.startSchedule
!,
794 chargingSchedule
: compositeSchedule
,
797 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
800 private handleRequestClearChargingProfile(
801 chargingStation
: ChargingStation
,
802 commandPayload
: ClearChargingProfileRequest
,
803 ): ClearChargingProfileResponse
{
805 OCPP16ServiceUtils
.checkFeatureProfile(
807 OCPP16SupportedFeatureProfiles
.SmartCharging
,
808 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
811 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
813 const { connectorId
} = commandPayload
;
814 if (chargingStation
.hasConnector(connectorId
!) === false) {
816 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to
817 a non existing connector id ${connectorId}`,
819 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
821 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
!);
822 if (!isNullOrUndefined(connectorId
) && isNotEmptyArray(connectorStatus
?.chargingProfiles
)) {
823 connectorStatus
!.chargingProfiles
= [];
825 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}`,
827 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
829 if (isNullOrUndefined(connectorId
)) {
830 let clearedCP
= false;
831 if (chargingStation
.hasEvses
) {
832 for (const evseStatus
of chargingStation
.evses
.values()) {
833 for (const status of evseStatus
.connectors
.values()) {
834 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
837 status.chargingProfiles
,
842 for (const id
of chargingStation
.connectors
.keys()) {
843 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
846 chargingStation
.getConnectorStatus(id
)?.chargingProfiles
,
851 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
854 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
857 private async handleRequestChangeAvailability(
858 chargingStation
: ChargingStation
,
859 commandPayload
: OCPP16ChangeAvailabilityRequest
,
860 ): Promise
<OCPP16ChangeAvailabilityResponse
> {
861 const { connectorId
, type } = commandPayload
;
862 if (chargingStation
.hasConnector(connectorId
) === false) {
864 `${chargingStation.logPrefix()} Trying to change the availability of a
865 non existing connector id ${connectorId}`,
867 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
869 const chargePointStatus
: OCPP16ChargePointStatus
=
870 type === OCPP16AvailabilityType
.Operative
871 ? OCPP16ChargePointStatus
.Available
872 : OCPP16ChargePointStatus
.Unavailable
;
873 if (connectorId
=== 0) {
874 let response
: OCPP16ChangeAvailabilityResponse
;
875 if (chargingStation
.hasEvses
) {
876 for (const evseStatus
of chargingStation
.evses
.values()) {
877 response
= await OCPP16ServiceUtils
.changeAvailability(
879 [...evseStatus
.connectors
.keys()],
885 response
= await OCPP16ServiceUtils
.changeAvailability(
887 [...chargingStation
.connectors
.keys()],
895 (chargingStation
.isChargingStationAvailable() === true ||
896 (chargingStation
.isChargingStationAvailable() === false &&
897 type === OCPP16AvailabilityType
.Inoperative
))
899 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
900 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type;
901 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
903 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type;
904 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
909 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
911 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
914 private async handleRequestRemoteStartTransaction(
915 chargingStation
: ChargingStation
,
916 commandPayload
: RemoteStartTransactionRequest
,
917 ): Promise
<GenericResponse
> {
918 const { connectorId
: transactionConnectorId
, idTag
, chargingProfile
} = commandPayload
;
919 if (chargingStation
.hasConnector(transactionConnectorId
) === false) {
920 return this.notifyRemoteStartTransactionRejected(
922 transactionConnectorId
,
927 !chargingStation
.isChargingStationAvailable() ||
928 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
930 return this.notifyRemoteStartTransactionRejected(
932 transactionConnectorId
,
936 const remoteStartTransactionLogMsg
= `
937 ${chargingStation.logPrefix()} Transaction remotely STARTED on ${
938 chargingStation.stationInfo.chargingStationId
939 }#${transactionConnectorId} for idTag '${idTag}'`;
940 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
942 transactionConnectorId
,
943 OCPP16ChargePointStatus
.Preparing
,
945 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
)!;
946 // Authorization check required
948 chargingStation
.getAuthorizeRemoteTxRequests() === true &&
949 (await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
951 // Authorization successful, start transaction
954 this.setRemoteStartTransactionChargingProfile(
956 transactionConnectorId
,
961 connectorStatus
.transactionRemoteStarted
= true;
964 await chargingStation
.ocppRequestService
.requestHandler
<
965 OCPP16StartTransactionRequest
,
966 OCPP16StartTransactionResponse
967 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
968 connectorId
: transactionConnectorId
,
971 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
973 logger
.debug(remoteStartTransactionLogMsg
);
974 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
976 return this.notifyRemoteStartTransactionRejected(
978 transactionConnectorId
,
982 return this.notifyRemoteStartTransactionRejected(
984 transactionConnectorId
,
988 // No authorization check required, start transaction
991 this.setRemoteStartTransactionChargingProfile(
993 transactionConnectorId
,
995 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
999 connectorStatus
.transactionRemoteStarted
= true;
1002 await chargingStation
.ocppRequestService
.requestHandler
<
1003 OCPP16StartTransactionRequest
,
1004 OCPP16StartTransactionResponse
1005 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
1006 connectorId
: transactionConnectorId
,
1009 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
1011 logger
.debug(remoteStartTransactionLogMsg
);
1012 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
1014 return this.notifyRemoteStartTransactionRejected(
1016 transactionConnectorId
,
1020 return this.notifyRemoteStartTransactionRejected(
1022 transactionConnectorId
,
1027 private async notifyRemoteStartTransactionRejected(
1028 chargingStation
: ChargingStation
,
1029 connectorId
: number,
1031 ): Promise
<GenericResponse
> {
1032 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
);
1033 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Available
) {
1034 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1037 OCPP16ChargePointStatus
.Available
,
1041 `${chargingStation.logPrefix()} Remote starting transaction REJECTED on connector id
1042 ${connectorId}, idTag '${idTag}', availability '${connectorStatus?.availability}', status '${connectorStatus?.status}'`,
1044 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
1047 private setRemoteStartTransactionChargingProfile(
1048 chargingStation
: ChargingStation
,
1049 connectorId
: number,
1050 chargingProfile
: OCPP16ChargingProfile
,
1052 if (chargingProfile
?.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
) {
1053 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
);
1055 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction
1056 on connector id ${connectorId}: %j`,
1062 `${chargingStation.logPrefix()} Not allowed to set ${
1063 chargingProfile.chargingProfilePurpose
1064 } charging profile(s) at remote start transaction`,
1069 private async handleRequestRemoteStopTransaction(
1070 chargingStation
: ChargingStation
,
1071 commandPayload
: RemoteStopTransactionRequest
,
1072 ): Promise
<GenericResponse
> {
1073 const { transactionId
} = commandPayload
;
1074 if (chargingStation
.hasEvses
) {
1075 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1077 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1078 if (connectorStatus
.transactionId
=== transactionId
) {
1079 return OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
);
1085 for (const connectorId
of chargingStation
.connectors
.keys()) {
1088 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
1090 return OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
);
1095 `${chargingStation.logPrefix()} Trying to remote stop a non existing transaction with id
1098 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
1101 private handleRequestUpdateFirmware(
1102 chargingStation
: ChargingStation
,
1103 commandPayload
: OCPP16UpdateFirmwareRequest
,
1104 ): OCPP16UpdateFirmwareResponse
{
1106 OCPP16ServiceUtils
.checkFeatureProfile(
1108 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1109 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
1113 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware:
1114 Cannot simulate firmware update: feature profile not supported`,
1116 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1118 let { retrieveDate
} = commandPayload
;
1120 !isNullOrUndefined(chargingStation
.stationInfo
.firmwareStatus
) &&
1121 chargingStation
.stationInfo
.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
1124 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware:
1125 Cannot simulate firmware update: firmware update is already in progress`,
1127 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1129 retrieveDate
= convertToDate(retrieveDate
)!;
1130 const now
= Date.now();
1131 if (retrieveDate
?.getTime() <= now
) {
1132 this.runInAsyncScope(
1133 this.updateFirmwareSimulation
.bind(this) as (
1134 this: OCPP16IncomingRequestService
,
1139 ).catch(Constants
.EMPTY_FUNCTION
);
1143 this.runInAsyncScope(
1144 this.updateFirmwareSimulation
.bind(this) as (
1145 this: OCPP16IncomingRequestService
,
1150 ).catch(Constants
.EMPTY_FUNCTION
);
1152 retrieveDate
?.getTime() - now
,
1155 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1158 private async updateFirmwareSimulation(
1159 chargingStation
: ChargingStation
,
1163 if (checkChargingStation(chargingStation
, chargingStation
.logPrefix()) === false) {
1166 if (chargingStation
.hasEvses
) {
1167 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1169 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1170 if (connectorStatus
?.transactionStarted
=== false) {
1171 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1174 OCPP16ChargePointStatus
.Unavailable
,
1181 for (const connectorId
of chargingStation
.connectors
.keys()) {
1184 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1186 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1189 OCPP16ChargePointStatus
.Unavailable
,
1194 await chargingStation
.ocppRequestService
.requestHandler
<
1195 OCPP16FirmwareStatusNotificationRequest
,
1196 OCPP16FirmwareStatusNotificationResponse
1197 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1198 status: OCPP16FirmwareStatus
.Downloading
,
1200 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
;
1202 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1203 OCPP16FirmwareStatus
.DownloadFailed
1205 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1206 await chargingStation
.ocppRequestService
.requestHandler
<
1207 OCPP16FirmwareStatusNotificationRequest
,
1208 OCPP16FirmwareStatusNotificationResponse
1209 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1210 status: chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
,
1212 chargingStation
.stationInfo
.firmwareStatus
=
1213 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
;
1216 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1217 await chargingStation
.ocppRequestService
.requestHandler
<
1218 OCPP16FirmwareStatusNotificationRequest
,
1219 OCPP16FirmwareStatusNotificationResponse
1220 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1221 status: OCPP16FirmwareStatus
.Downloaded
,
1223 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
;
1224 let wasTransactionsStarted
= false;
1225 let transactionsStarted
: boolean;
1227 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions();
1228 if (runningTransactions
> 0) {
1229 const waitTime
= secondsToMilliseconds(15);
1231 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation:
1232 ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1234 )} before continuing firmware update simulation`,
1236 await sleep(waitTime
);
1237 transactionsStarted
= true;
1238 wasTransactionsStarted
= true;
1240 if (chargingStation
.hasEvses
) {
1241 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1243 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1244 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Unavailable
) {
1245 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1248 OCPP16ChargePointStatus
.Unavailable
,
1255 for (const connectorId
of chargingStation
.connectors
.keys()) {
1258 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1259 OCPP16ChargePointStatus
.Unavailable
1261 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1264 OCPP16ChargePointStatus
.Unavailable
,
1269 transactionsStarted
= false;
1271 } while (transactionsStarted
);
1272 !wasTransactionsStarted
&&
1273 (await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
))));
1274 if (checkChargingStation(chargingStation
, chargingStation
.logPrefix()) === false) {
1277 await chargingStation
.ocppRequestService
.requestHandler
<
1278 OCPP16FirmwareStatusNotificationRequest
,
1279 OCPP16FirmwareStatusNotificationResponse
1280 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1281 status: OCPP16FirmwareStatus
.Installing
,
1283 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Installing
;
1285 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1286 OCPP16FirmwareStatus
.InstallationFailed
1288 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1289 await chargingStation
.ocppRequestService
.requestHandler
<
1290 OCPP16FirmwareStatusNotificationRequest
,
1291 OCPP16FirmwareStatusNotificationResponse
1292 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1293 status: chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
,
1295 chargingStation
.stationInfo
.firmwareStatus
=
1296 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
;
1299 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1300 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1301 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
);
1305 private async handleRequestGetDiagnostics(
1306 chargingStation
: ChargingStation
,
1307 commandPayload
: GetDiagnosticsRequest
,
1308 ): Promise
<GetDiagnosticsResponse
> {
1310 OCPP16ServiceUtils
.checkFeatureProfile(
1312 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1313 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1317 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics:
1318 Cannot get diagnostics: feature profile not supported`,
1320 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1322 const { location
} = commandPayload
;
1323 const uri
= new URL(location
);
1324 if (uri
.protocol
.startsWith('ftp:')) {
1325 let ftpClient
: Client
| undefined;
1327 const logFiles
= readdirSync(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'))
1328 .filter((file
) => file
.endsWith('.log'))
1329 .map((file
) => join('./', file
));
1330 const diagnosticsArchive
= `${chargingStation.stationInfo.chargingStationId}_logs.tar.gz`;
1331 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
));
1332 ftpClient
= new Client();
1333 const accessResponse
= await ftpClient
.access({
1335 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1336 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1337 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
}),
1339 let uploadResponse
: FTPResponse
| undefined;
1340 if (accessResponse
.code
=== 220) {
1341 ftpClient
.trackProgress((info
) => {
1343 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1345 } bytes transferred from diagnostics archive ${info.name}`,
1347 chargingStation
.ocppRequestService
1349 OCPP16DiagnosticsStatusNotificationRequest
,
1350 OCPP16DiagnosticsStatusNotificationResponse
1351 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1352 status: OCPP16DiagnosticsStatus
.Uploading
,
1356 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics:
1357 Error while sending '${OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION}'`,
1362 uploadResponse
= await ftpClient
.uploadFrom(
1363 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1364 `${uri.pathname}${diagnosticsArchive}`,
1366 if (uploadResponse
.code
=== 226) {
1367 await chargingStation
.ocppRequestService
.requestHandler
<
1368 OCPP16DiagnosticsStatusNotificationRequest
,
1369 OCPP16DiagnosticsStatusNotificationResponse
1370 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1371 status: OCPP16DiagnosticsStatus
.Uploaded
,
1376 return { fileName
: diagnosticsArchive
};
1378 throw new OCPPError(
1379 ErrorType
.GENERIC_ERROR
,
1380 `Diagnostics transfer failed with error code ${accessResponse.code}${
1381 uploadResponse?.code && `|${uploadResponse?.code}
`
1383 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1386 throw new OCPPError(
1387 ErrorType
.GENERIC_ERROR
,
1388 `Diagnostics transfer failed with error code ${accessResponse.code}${
1389 uploadResponse?.code && `|${uploadResponse?.code}
`
1391 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1394 await chargingStation
.ocppRequestService
.requestHandler
<
1395 OCPP16DiagnosticsStatusNotificationRequest
,
1396 OCPP16DiagnosticsStatusNotificationResponse
1397 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1398 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1403 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1405 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1407 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
},
1412 `${chargingStation.logPrefix()} Unsupported protocol ${
1414 } to transfer the diagnostic logs archive`,
1416 await chargingStation
.ocppRequestService
.requestHandler
<
1417 OCPP16DiagnosticsStatusNotificationRequest
,
1418 OCPP16DiagnosticsStatusNotificationResponse
1419 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1420 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1422 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1426 private handleRequestTriggerMessage(
1427 chargingStation
: ChargingStation
,
1428 commandPayload
: OCPP16TriggerMessageRequest
,
1429 ): OCPP16TriggerMessageResponse
{
1430 const { requestedMessage
, connectorId
} = commandPayload
;
1432 !OCPP16ServiceUtils
.checkFeatureProfile(
1434 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1435 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1437 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1439 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1442 !OCPP16ServiceUtils
.isConnectorIdValid(
1444 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1448 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1451 switch (requestedMessage
) {
1452 case OCPP16MessageTrigger
.BootNotification
:
1454 chargingStation
.ocppRequestService
1455 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1457 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1458 chargingStation
.bootNotificationRequest
,
1459 { skipBufferingOnError
: true, triggerMessage
: true },
1461 .then((response
) => {
1462 chargingStation
.bootNotificationResponse
= response
;
1464 .catch(Constants
.EMPTY_FUNCTION
);
1465 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1466 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1467 case OCPP16MessageTrigger
.Heartbeat
:
1469 chargingStation
.ocppRequestService
1470 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1472 OCPP16RequestCommand
.HEARTBEAT
,
1475 triggerMessage
: true,
1478 .catch(Constants
.EMPTY_FUNCTION
);
1479 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1480 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1481 case OCPP16MessageTrigger
.StatusNotification
:
1483 if (!isNullOrUndefined(connectorId
)) {
1484 chargingStation
.ocppRequestService
1485 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1487 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1490 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1491 status: chargingStation
.getConnectorStatus(connectorId
!)?.status,
1494 triggerMessage
: true,
1497 .catch(Constants
.EMPTY_FUNCTION
);
1499 // eslint-disable-next-line no-lonely-if
1500 if (chargingStation
.hasEvses
) {
1501 for (const evseStatus
of chargingStation
.evses
.values()) {
1502 for (const [id
, connectorStatus
] of evseStatus
.connectors
) {
1503 chargingStation
.ocppRequestService
1505 OCPP16StatusNotificationRequest
,
1506 OCPP16StatusNotificationResponse
1509 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1512 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1513 status: connectorStatus
.status,
1516 triggerMessage
: true,
1519 .catch(Constants
.EMPTY_FUNCTION
);
1523 for (const id
of chargingStation
.connectors
.keys()) {
1524 chargingStation
.ocppRequestService
1526 OCPP16StatusNotificationRequest
,
1527 OCPP16StatusNotificationResponse
1530 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1533 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1534 status: chargingStation
.getConnectorStatus(id
)?.status,
1537 triggerMessage
: true,
1540 .catch(Constants
.EMPTY_FUNCTION
);
1544 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1545 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1547 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1550 return this.handleIncomingRequestError
<OCPP16TriggerMessageResponse
>(
1552 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1554 { errorResponse
: OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
},
1559 private handleRequestDataTransfer(
1560 chargingStation
: ChargingStation
,
1561 commandPayload
: OCPP16DataTransferRequest
,
1562 ): OCPP16DataTransferResponse
{
1563 const { vendorId
} = commandPayload
;
1565 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1566 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
;
1568 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
;
1570 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1572 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1574 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
},
1579 private async handleRequestReserveNow(
1580 chargingStation
: ChargingStation
,
1581 commandPayload
: OCPP16ReserveNowRequest
,
1582 ): Promise
<OCPP16ReserveNowResponse
> {
1584 !OCPP16ServiceUtils
.checkFeatureProfile(
1586 OCPP16SupportedFeatureProfiles
.Reservation
,
1587 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1590 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1592 const { reservationId
, idTag
, connectorId
} = commandPayload
;
1593 let response
: OCPP16ReserveNowResponse
;
1595 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1596 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1598 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1599 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1601 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1602 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1604 await removeExpiredReservations(chargingStation
);
1605 switch (chargingStation
.getConnectorStatus(connectorId
)!.status) {
1606 case OCPP16ChargePointStatus
.Faulted
:
1607 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
;
1609 case OCPP16ChargePointStatus
.Preparing
:
1610 case OCPP16ChargePointStatus
.Charging
:
1611 case OCPP16ChargePointStatus
.SuspendedEV
:
1612 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1613 case OCPP16ChargePointStatus
.Finishing
:
1614 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1616 case OCPP16ChargePointStatus
.Unavailable
:
1617 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
;
1619 case OCPP16ChargePointStatus
.Reserved
:
1620 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1621 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1624 // eslint-disable-next-line no-fallthrough
1626 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1627 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1630 await chargingStation
.addReservation({
1631 id
: commandPayload
.reservationId
,
1634 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
;
1639 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
;
1640 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1642 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1644 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
},
1649 private async handleRequestCancelReservation(
1650 chargingStation
: ChargingStation
,
1651 commandPayload
: OCPP16CancelReservationRequest
,
1652 ): Promise
<GenericResponse
> {
1654 !OCPP16ServiceUtils
.checkFeatureProfile(
1656 OCPP16SupportedFeatureProfiles
.Reservation
,
1657 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1660 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
;
1663 const { reservationId
} = commandPayload
;
1664 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
);
1665 if (isUndefined(reservation
)) {
1667 `${chargingStation.logPrefix()} Reservation with id ${reservationId}
1668 does not exist on charging station`,
1670 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
;
1672 await chargingStation
.removeReservation(
1674 ReservationTerminationReason
.RESERVATION_CANCELED
,
1676 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
;
1678 return this.handleIncomingRequestError
<GenericResponse
>(
1680 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1682 { errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
},