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.toString()}`,
469 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
471 if (connectorId
=== 0) {
473 `${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId.toString()}`,
475 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
477 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
478 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
480 OCPP16StopTransactionReason
.UNLOCK_COMMAND
,
482 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
483 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
;
485 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
487 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
490 OCPP16ChargePointStatus
.Available
,
492 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
;
495 private handleRequestGetConfiguration(
496 chargingStation
: ChargingStation
,
497 commandPayload
: GetConfigurationRequest
,
498 ): GetConfigurationResponse
{
499 const { key
} = commandPayload
;
500 const configurationKey
: OCPPConfigurationKey
[] = [];
501 const unknownKey
: string[] = [];
502 if (isUndefined(key
) === true) {
503 for (const configuration
of chargingStation
.ocppConfiguration
!.configurationKey
!) {
504 if (isUndefined(configuration
.visible
) === true) {
505 configuration
.visible
= true;
507 if (configuration
.visible
=== false) {
510 configurationKey
.push({
511 key
: configuration
.key
,
512 readonly: configuration
.readonly,
513 value
: configuration
.value
,
516 } else if (isNotEmptyArray(key
) === true) {
517 for (const k
of key
!) {
518 const keyFound
= getConfigurationKey(chargingStation
, k
, true);
520 if (isUndefined(keyFound
.visible
) === true) {
521 keyFound
.visible
= true;
523 if (keyFound
.visible
=== false) {
526 configurationKey
.push({
528 readonly: keyFound
.readonly,
529 value
: keyFound
.value
,
542 private handleRequestChangeConfiguration(
543 chargingStation
: ChargingStation
,
544 commandPayload
: ChangeConfigurationRequest
,
545 ): ChangeConfigurationResponse
{
546 const { key
, value
} = commandPayload
;
547 const keyToChange
= getConfigurationKey(chargingStation
, key
, true);
548 if (keyToChange
?.readonly === true) {
549 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
550 } else if (keyToChange
?.readonly === false) {
551 let valueChanged
= false;
552 if (keyToChange
.value
!== value
) {
553 setConfigurationKeyValue(chargingStation
, key
, value
, true);
556 let triggerHeartbeatRestart
= false;
558 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
559 OCPP16StandardParametersKey
.HeartBeatInterval
&&
562 setConfigurationKeyValue(
564 OCPP16StandardParametersKey
.HeartbeatInterval
,
567 triggerHeartbeatRestart
= true;
570 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
571 OCPP16StandardParametersKey
.HeartbeatInterval
&&
574 setConfigurationKeyValue(
576 OCPP16StandardParametersKey
.HeartBeatInterval
,
579 triggerHeartbeatRestart
= true;
581 if (triggerHeartbeatRestart
) {
582 chargingStation
.restartHeartbeat();
585 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
586 OCPP16StandardParametersKey
.WebSocketPingInterval
&&
589 chargingStation
.restartWebSocketPing();
591 if (keyToChange
.reboot
) {
592 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
594 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
596 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
599 private handleRequestSetChargingProfile(
600 chargingStation
: ChargingStation
,
601 commandPayload
: SetChargingProfileRequest
,
602 ): SetChargingProfileResponse
{
604 OCPP16ServiceUtils
.checkFeatureProfile(
606 OCPP16SupportedFeatureProfiles
.SmartCharging
,
607 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
610 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
612 const { connectorId
, csChargingProfiles
} = commandPayload
;
613 if (chargingStation
.hasConnector(connectorId
) === false) {
615 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a
616 non existing connector id ${connectorId}`,
618 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
621 csChargingProfiles
.chargingProfilePurpose
===
622 OCPP16ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
625 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
628 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
632 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s)
633 on connector ${connectorId}`,
635 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
637 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
);
639 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
641 connectorStatus
?.transactionStarted
=== false
644 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s)
645 on connector ${connectorId} without a started transaction`,
647 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
650 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
652 connectorStatus
?.transactionStarted
=== true &&
653 csChargingProfiles
.transactionId
!== connectorStatus
?.transactionId
656 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s)
657 on connector ${connectorId} with a different transaction id ${
658 csChargingProfiles.transactionId
659 } than the started transaction id ${connectorStatus?.transactionId}`,
661 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
663 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, csChargingProfiles
);
665 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${connectorId}: %j`,
668 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
671 private handleRequestGetCompositeSchedule(
672 chargingStation
: ChargingStation
,
673 commandPayload
: OCPP16GetCompositeScheduleRequest
,
674 ): OCPP16GetCompositeScheduleResponse
{
676 OCPP16ServiceUtils
.checkFeatureProfile(
678 OCPP16SupportedFeatureProfiles
.SmartCharging
,
679 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
682 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
684 const { connectorId
, duration
, chargingRateUnit
} = commandPayload
;
685 if (chargingStation
.hasConnector(connectorId
) === false) {
687 `${chargingStation.logPrefix()} Trying to get composite schedule to a
688 non existing connector id ${connectorId}`,
690 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
692 if (connectorId
=== 0) {
694 `${chargingStation.logPrefix()} Get composite schedule on connector id ${connectorId} is not yet supported`,
696 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
698 if (chargingRateUnit
) {
700 `${chargingStation.logPrefix()} Get composite schedule with a specified rate unit is not yet supported, no conversion will be done`,
703 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)!;
706 connectorStatus
?.chargingProfiles
&&
707 isEmptyArray(chargingStation
.getConnectorStatus(0)?.chargingProfiles
),
710 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
712 const currentDate
= new Date();
713 const compositeScheduleInterval
: Interval
= {
715 end
: addSeconds(currentDate
, duration
),
717 // Get charging profiles sorted by connector id then stack level
718 const chargingProfiles
: OCPP16ChargingProfile
[] = getConnectorChargingProfiles(
722 let previousCompositeSchedule
: OCPP16ChargingSchedule
| undefined;
723 let compositeSchedule
: OCPP16ChargingSchedule
| undefined;
724 for (const chargingProfile
of chargingProfiles
) {
726 isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
) &&
727 connectorStatus
?.transactionStarted
730 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
731 chargingProfile.chargingProfileId
732 } has no startSchedule defined. Trying to set it to the connector current transaction start date`,
734 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
735 chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
;
738 !isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
) &&
739 !isDate(chargingProfile
.chargingSchedule
?.startSchedule
)
742 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
743 chargingProfile.chargingProfileId
744 } startSchedule property is not a Date instance. Trying to convert it to a Date instance`,
746 chargingProfile
.chargingSchedule
.startSchedule
= convertToDate(
747 chargingProfile
.chargingSchedule
?.startSchedule
,
751 !isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
) &&
752 isNullOrUndefined(chargingProfile
.chargingSchedule
?.duration
)
755 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
756 chargingProfile.chargingProfileId
757 } has no duration defined and will be set to the maximum time allowed`,
759 // OCPP specifies that if duration is not defined, it should be infinite
760 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(
762 chargingProfile
.chargingSchedule
.startSchedule
!,
766 !prepareChargingProfileKind(
769 compositeScheduleInterval
.start
as Date,
770 chargingStation
.logPrefix(),
776 !canProceedChargingProfile(
778 compositeScheduleInterval
.start
as Date,
779 chargingStation
.logPrefix(),
784 compositeSchedule
= OCPP16ServiceUtils
.composeChargingSchedules(
785 previousCompositeSchedule
,
786 chargingProfile
.chargingSchedule
,
787 compositeScheduleInterval
,
789 previousCompositeSchedule
= compositeSchedule
;
791 if (compositeSchedule
) {
793 status: GenericStatus
.Accepted
,
794 scheduleStart
: compositeSchedule
.startSchedule
!,
796 chargingSchedule
: compositeSchedule
,
799 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
802 private handleRequestClearChargingProfile(
803 chargingStation
: ChargingStation
,
804 commandPayload
: ClearChargingProfileRequest
,
805 ): ClearChargingProfileResponse
{
807 OCPP16ServiceUtils
.checkFeatureProfile(
809 OCPP16SupportedFeatureProfiles
.SmartCharging
,
810 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
813 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
815 const { connectorId
} = commandPayload
;
816 if (chargingStation
.hasConnector(connectorId
!) === false) {
818 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to
819 a non existing connector id ${connectorId}`,
821 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
824 !isNullOrUndefined(connectorId
) &&
825 isNotEmptyArray(chargingStation
.getConnectorStatus(connectorId
!)?.chargingProfiles
)
827 chargingStation
.getConnectorStatus(connectorId
!)!.chargingProfiles
= [];
829 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}`,
831 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
833 if (isNullOrUndefined(connectorId
)) {
834 let clearedCP
= false;
835 if (chargingStation
.hasEvses
) {
836 for (const evseStatus
of chargingStation
.evses
.values()) {
837 for (const connectorStatus
of evseStatus
.connectors
.values()) {
838 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
841 connectorStatus
.chargingProfiles
,
846 for (const id
of chargingStation
.connectors
.keys()) {
847 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
850 chargingStation
.getConnectorStatus(id
)?.chargingProfiles
,
855 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
858 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
861 private async handleRequestChangeAvailability(
862 chargingStation
: ChargingStation
,
863 commandPayload
: OCPP16ChangeAvailabilityRequest
,
864 ): Promise
<OCPP16ChangeAvailabilityResponse
> {
865 const { connectorId
, type } = commandPayload
;
866 if (chargingStation
.hasConnector(connectorId
) === false) {
868 `${chargingStation.logPrefix()} Trying to change the availability of a
869 non existing connector id ${connectorId.toString()}`,
871 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
873 const chargePointStatus
: OCPP16ChargePointStatus
=
874 type === OCPP16AvailabilityType
.Operative
875 ? OCPP16ChargePointStatus
.Available
876 : OCPP16ChargePointStatus
.Unavailable
;
877 if (connectorId
=== 0) {
878 let response
: OCPP16ChangeAvailabilityResponse
;
879 if (chargingStation
.hasEvses
) {
880 for (const evseStatus
of chargingStation
.evses
.values()) {
881 response
= await OCPP16ServiceUtils
.changeAvailability(
883 [...evseStatus
.connectors
.keys()],
889 response
= await OCPP16ServiceUtils
.changeAvailability(
891 [...chargingStation
.connectors
.keys()],
899 (chargingStation
.isChargingStationAvailable() === true ||
900 (chargingStation
.isChargingStationAvailable() === false &&
901 type === OCPP16AvailabilityType
.Inoperative
))
903 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
904 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type;
905 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
907 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type;
908 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
913 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
915 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
918 private async handleRequestRemoteStartTransaction(
919 chargingStation
: ChargingStation
,
920 commandPayload
: RemoteStartTransactionRequest
,
921 ): Promise
<GenericResponse
> {
922 const { connectorId
: transactionConnectorId
, idTag
, chargingProfile
} = commandPayload
;
923 if (chargingStation
.hasConnector(transactionConnectorId
) === false) {
924 return this.notifyRemoteStartTransactionRejected(
926 transactionConnectorId
,
931 !chargingStation
.isChargingStationAvailable() ||
932 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
934 return this.notifyRemoteStartTransactionRejected(
936 transactionConnectorId
,
940 const remoteStartTransactionLogMsg
= `
941 ${chargingStation.logPrefix()} Transaction remotely STARTED on ${
942 chargingStation.stationInfo.chargingStationId
943 }#${transactionConnectorId.toString()} for idTag '${idTag}'`;
944 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
946 transactionConnectorId
,
947 OCPP16ChargePointStatus
.Preparing
,
949 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
)!;
950 // Authorization check required
952 chargingStation
.getAuthorizeRemoteTxRequests() === true &&
953 (await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
955 // Authorization successful, start transaction
957 this.setRemoteStartTransactionChargingProfile(
959 transactionConnectorId
,
963 connectorStatus
.transactionRemoteStarted
= true;
966 await chargingStation
.ocppRequestService
.requestHandler
<
967 OCPP16StartTransactionRequest
,
968 OCPP16StartTransactionResponse
969 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
970 connectorId
: transactionConnectorId
,
973 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
975 logger
.debug(remoteStartTransactionLogMsg
);
976 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
978 return this.notifyRemoteStartTransactionRejected(
980 transactionConnectorId
,
984 return this.notifyRemoteStartTransactionRejected(
986 transactionConnectorId
,
990 // No authorization check required, start transaction
992 this.setRemoteStartTransactionChargingProfile(
994 transactionConnectorId
,
998 connectorStatus
.transactionRemoteStarted
= true;
1001 await chargingStation
.ocppRequestService
.requestHandler
<
1002 OCPP16StartTransactionRequest
,
1003 OCPP16StartTransactionResponse
1004 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
1005 connectorId
: transactionConnectorId
,
1008 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
1010 logger
.debug(remoteStartTransactionLogMsg
);
1011 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
1013 return this.notifyRemoteStartTransactionRejected(
1015 transactionConnectorId
,
1019 return this.notifyRemoteStartTransactionRejected(
1021 transactionConnectorId
,
1026 private async notifyRemoteStartTransactionRejected(
1027 chargingStation
: ChargingStation
,
1028 connectorId
: number,
1030 ): Promise
<GenericResponse
> {
1032 chargingStation
.getConnectorStatus(connectorId
)?.status !== OCPP16ChargePointStatus
.Available
1034 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1037 OCPP16ChargePointStatus
.Available
,
1041 `${chargingStation.logPrefix()} Remote starting transaction REJECTED on connector id
1042 ${connectorId.toString()}, idTag '${idTag}', availability '${chargingStation.getConnectorStatus(
1044 )?.availability}', status '${chargingStation.getConnectorStatus(connectorId)?.status}'`,
1046 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
1049 private setRemoteStartTransactionChargingProfile(
1050 chargingStation
: ChargingStation
,
1051 connectorId
: number,
1052 chargingProfile
: OCPP16ChargingProfile
,
1056 chargingProfile
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
1058 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
);
1060 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction
1061 on connector id ${connectorId}: %j`,
1067 chargingProfile
.chargingProfilePurpose
!== OCPP16ChargingProfilePurposeType
.TX_PROFILE
1070 `${chargingStation.logPrefix()} Not allowed to set ${
1071 chargingProfile.chargingProfilePurpose
1072 } charging profile(s) at remote start transaction`,
1079 private async handleRequestRemoteStopTransaction(
1080 chargingStation
: ChargingStation
,
1081 commandPayload
: RemoteStopTransactionRequest
,
1082 ): Promise
<GenericResponse
> {
1083 const { transactionId
} = commandPayload
;
1084 if (chargingStation
.hasEvses
) {
1085 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1087 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1088 if (connectorStatus
.transactionId
=== transactionId
) {
1089 return OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
);
1095 for (const connectorId
of chargingStation
.connectors
.keys()) {
1098 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
1100 return OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
);
1105 `${chargingStation.logPrefix()} Trying to remote stop a non existing transaction with id
1106 ${transactionId.toString()}`,
1108 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
1111 private handleRequestUpdateFirmware(
1112 chargingStation
: ChargingStation
,
1113 commandPayload
: OCPP16UpdateFirmwareRequest
,
1114 ): OCPP16UpdateFirmwareResponse
{
1116 OCPP16ServiceUtils
.checkFeatureProfile(
1118 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1119 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
1123 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware:
1124 Cannot simulate firmware update: feature profile not supported`,
1126 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1128 let { retrieveDate
} = commandPayload
;
1130 !isNullOrUndefined(chargingStation
.stationInfo
.firmwareStatus
) &&
1131 chargingStation
.stationInfo
.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
1134 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware:
1135 Cannot simulate firmware update: firmware update is already in progress`,
1137 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1139 retrieveDate
= convertToDate(retrieveDate
)!;
1140 const now
= Date.now();
1141 if (retrieveDate
?.getTime() <= now
) {
1142 this.runInAsyncScope(
1143 this.updateFirmwareSimulation
.bind(this) as (
1144 this: OCPP16IncomingRequestService
,
1149 ).catch(Constants
.EMPTY_FUNCTION
);
1153 this.runInAsyncScope(
1154 this.updateFirmwareSimulation
.bind(this) as (
1155 this: OCPP16IncomingRequestService
,
1160 ).catch(Constants
.EMPTY_FUNCTION
);
1162 retrieveDate
?.getTime() - now
,
1165 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1168 private async updateFirmwareSimulation(
1169 chargingStation
: ChargingStation
,
1173 if (checkChargingStation(chargingStation
, chargingStation
.logPrefix()) === false) {
1176 if (chargingStation
.hasEvses
) {
1177 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1179 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1180 if (connectorStatus
?.transactionStarted
=== false) {
1181 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1184 OCPP16ChargePointStatus
.Unavailable
,
1191 for (const connectorId
of chargingStation
.connectors
.keys()) {
1194 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1196 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1199 OCPP16ChargePointStatus
.Unavailable
,
1204 await chargingStation
.ocppRequestService
.requestHandler
<
1205 OCPP16FirmwareStatusNotificationRequest
,
1206 OCPP16FirmwareStatusNotificationResponse
1207 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1208 status: OCPP16FirmwareStatus
.Downloading
,
1210 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
;
1212 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1213 OCPP16FirmwareStatus
.DownloadFailed
1215 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1216 await chargingStation
.ocppRequestService
.requestHandler
<
1217 OCPP16FirmwareStatusNotificationRequest
,
1218 OCPP16FirmwareStatusNotificationResponse
1219 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1220 status: chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
,
1222 chargingStation
.stationInfo
.firmwareStatus
=
1223 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
;
1226 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1227 await chargingStation
.ocppRequestService
.requestHandler
<
1228 OCPP16FirmwareStatusNotificationRequest
,
1229 OCPP16FirmwareStatusNotificationResponse
1230 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1231 status: OCPP16FirmwareStatus
.Downloaded
,
1233 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
;
1234 let wasTransactionsStarted
= false;
1235 let transactionsStarted
: boolean;
1237 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions();
1238 if (runningTransactions
> 0) {
1239 const waitTime
= secondsToMilliseconds(15);
1241 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation:
1242 ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1244 )} before continuing firmware update simulation`,
1246 await sleep(waitTime
);
1247 transactionsStarted
= true;
1248 wasTransactionsStarted
= true;
1250 if (chargingStation
.hasEvses
) {
1251 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1253 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1254 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Unavailable
) {
1255 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1258 OCPP16ChargePointStatus
.Unavailable
,
1265 for (const connectorId
of chargingStation
.connectors
.keys()) {
1268 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1269 OCPP16ChargePointStatus
.Unavailable
1271 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1274 OCPP16ChargePointStatus
.Unavailable
,
1279 transactionsStarted
= false;
1281 } while (transactionsStarted
);
1282 !wasTransactionsStarted
&&
1283 (await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
))));
1284 if (checkChargingStation(chargingStation
, chargingStation
.logPrefix()) === false) {
1287 await chargingStation
.ocppRequestService
.requestHandler
<
1288 OCPP16FirmwareStatusNotificationRequest
,
1289 OCPP16FirmwareStatusNotificationResponse
1290 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1291 status: OCPP16FirmwareStatus
.Installing
,
1293 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Installing
;
1295 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1296 OCPP16FirmwareStatus
.InstallationFailed
1298 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1299 await chargingStation
.ocppRequestService
.requestHandler
<
1300 OCPP16FirmwareStatusNotificationRequest
,
1301 OCPP16FirmwareStatusNotificationResponse
1302 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1303 status: chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
,
1305 chargingStation
.stationInfo
.firmwareStatus
=
1306 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
;
1309 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1310 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1311 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
);
1315 private async handleRequestGetDiagnostics(
1316 chargingStation
: ChargingStation
,
1317 commandPayload
: GetDiagnosticsRequest
,
1318 ): Promise
<GetDiagnosticsResponse
> {
1320 OCPP16ServiceUtils
.checkFeatureProfile(
1322 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1323 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1327 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics:
1328 Cannot get diagnostics: feature profile not supported`,
1330 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1332 const { location
} = commandPayload
;
1333 const uri
= new URL(location
);
1334 if (uri
.protocol
.startsWith('ftp:')) {
1335 let ftpClient
: Client
| undefined;
1337 const logFiles
= readdirSync(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'))
1338 .filter((file
) => file
.endsWith('.log'))
1339 .map((file
) => join('./', file
));
1340 const diagnosticsArchive
= `${chargingStation.stationInfo.chargingStationId}_logs.tar.gz`;
1341 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
));
1342 ftpClient
= new Client();
1343 const accessResponse
= await ftpClient
.access({
1345 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1346 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1347 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
}),
1349 let uploadResponse
: FTPResponse
| undefined;
1350 if (accessResponse
.code
=== 220) {
1351 ftpClient
.trackProgress((info
) => {
1353 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1355 } bytes transferred from diagnostics archive ${info.name}`,
1357 chargingStation
.ocppRequestService
1359 OCPP16DiagnosticsStatusNotificationRequest
,
1360 OCPP16DiagnosticsStatusNotificationResponse
1361 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1362 status: OCPP16DiagnosticsStatus
.Uploading
,
1366 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics:
1367 Error while sending '${OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION}'`,
1372 uploadResponse
= await ftpClient
.uploadFrom(
1373 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1374 `${uri.pathname}${diagnosticsArchive}`,
1376 if (uploadResponse
.code
=== 226) {
1377 await chargingStation
.ocppRequestService
.requestHandler
<
1378 OCPP16DiagnosticsStatusNotificationRequest
,
1379 OCPP16DiagnosticsStatusNotificationResponse
1380 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1381 status: OCPP16DiagnosticsStatus
.Uploaded
,
1386 return { fileName
: diagnosticsArchive
};
1388 throw new OCPPError(
1389 ErrorType
.GENERIC_ERROR
,
1390 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1391 uploadResponse?.code && `|${uploadResponse?.code.toString()}
`
1393 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1396 throw new OCPPError(
1397 ErrorType
.GENERIC_ERROR
,
1398 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1399 uploadResponse?.code && `|${uploadResponse?.code.toString()}
`
1401 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1404 await chargingStation
.ocppRequestService
.requestHandler
<
1405 OCPP16DiagnosticsStatusNotificationRequest
,
1406 OCPP16DiagnosticsStatusNotificationResponse
1407 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1408 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1413 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1415 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1417 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
},
1422 `${chargingStation.logPrefix()} Unsupported protocol ${
1424 } to transfer the diagnostic logs archive`,
1426 await chargingStation
.ocppRequestService
.requestHandler
<
1427 OCPP16DiagnosticsStatusNotificationRequest
,
1428 OCPP16DiagnosticsStatusNotificationResponse
1429 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1430 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1432 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1436 private handleRequestTriggerMessage(
1437 chargingStation
: ChargingStation
,
1438 commandPayload
: OCPP16TriggerMessageRequest
,
1439 ): OCPP16TriggerMessageResponse
{
1440 const { requestedMessage
, connectorId
} = commandPayload
;
1442 !OCPP16ServiceUtils
.checkFeatureProfile(
1444 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1445 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1447 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1449 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1452 !OCPP16ServiceUtils
.isConnectorIdValid(
1454 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1458 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1461 switch (requestedMessage
) {
1462 case OCPP16MessageTrigger
.BootNotification
:
1464 chargingStation
.ocppRequestService
1465 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1467 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1468 chargingStation
.bootNotificationRequest
,
1469 { skipBufferingOnError
: true, triggerMessage
: true },
1471 .then((response
) => {
1472 chargingStation
.bootNotificationResponse
= response
;
1474 .catch(Constants
.EMPTY_FUNCTION
);
1475 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1476 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1477 case OCPP16MessageTrigger
.Heartbeat
:
1479 chargingStation
.ocppRequestService
1480 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1482 OCPP16RequestCommand
.HEARTBEAT
,
1485 triggerMessage
: true,
1488 .catch(Constants
.EMPTY_FUNCTION
);
1489 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1490 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1491 case OCPP16MessageTrigger
.StatusNotification
:
1493 if (!isNullOrUndefined(connectorId
)) {
1494 chargingStation
.ocppRequestService
1495 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1497 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1500 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1501 status: chargingStation
.getConnectorStatus(connectorId
!)?.status,
1504 triggerMessage
: true,
1507 .catch(Constants
.EMPTY_FUNCTION
);
1509 // eslint-disable-next-line no-lonely-if
1510 if (chargingStation
.hasEvses
) {
1511 for (const evseStatus
of chargingStation
.evses
.values()) {
1512 for (const [id
, connectorStatus
] of evseStatus
.connectors
) {
1513 chargingStation
.ocppRequestService
1515 OCPP16StatusNotificationRequest
,
1516 OCPP16StatusNotificationResponse
1519 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1522 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1523 status: connectorStatus
.status,
1526 triggerMessage
: true,
1529 .catch(Constants
.EMPTY_FUNCTION
);
1533 for (const id
of chargingStation
.connectors
.keys()) {
1534 chargingStation
.ocppRequestService
1536 OCPP16StatusNotificationRequest
,
1537 OCPP16StatusNotificationResponse
1540 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1543 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1544 status: chargingStation
.getConnectorStatus(id
)?.status,
1547 triggerMessage
: true,
1550 .catch(Constants
.EMPTY_FUNCTION
);
1554 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1555 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1557 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1560 return this.handleIncomingRequestError
<OCPP16TriggerMessageResponse
>(
1562 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1564 { errorResponse
: OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
},
1569 private handleRequestDataTransfer(
1570 chargingStation
: ChargingStation
,
1571 commandPayload
: OCPP16DataTransferRequest
,
1572 ): OCPP16DataTransferResponse
{
1573 const { vendorId
} = commandPayload
;
1575 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1576 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
;
1578 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
;
1580 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1582 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1584 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
},
1589 private async handleRequestReserveNow(
1590 chargingStation
: ChargingStation
,
1591 commandPayload
: OCPP16ReserveNowRequest
,
1592 ): Promise
<OCPP16ReserveNowResponse
> {
1594 !OCPP16ServiceUtils
.checkFeatureProfile(
1596 OCPP16SupportedFeatureProfiles
.Reservation
,
1597 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1600 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1602 const { reservationId
, idTag
, connectorId
} = commandPayload
;
1603 let response
: OCPP16ReserveNowResponse
;
1605 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1606 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1608 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1609 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1611 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1612 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1614 await removeExpiredReservations(chargingStation
);
1615 switch (chargingStation
.getConnectorStatus(connectorId
)!.status) {
1616 case OCPP16ChargePointStatus
.Faulted
:
1617 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
;
1619 case OCPP16ChargePointStatus
.Preparing
:
1620 case OCPP16ChargePointStatus
.Charging
:
1621 case OCPP16ChargePointStatus
.SuspendedEV
:
1622 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1623 case OCPP16ChargePointStatus
.Finishing
:
1624 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1626 case OCPP16ChargePointStatus
.Unavailable
:
1627 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
;
1629 case OCPP16ChargePointStatus
.Reserved
:
1630 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1631 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1634 // eslint-disable-next-line no-fallthrough
1636 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1637 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1640 await chargingStation
.addReservation({
1641 id
: commandPayload
.reservationId
,
1644 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
;
1649 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
;
1650 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1652 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1654 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
},
1659 private async handleRequestCancelReservation(
1660 chargingStation
: ChargingStation
,
1661 commandPayload
: OCPP16CancelReservationRequest
,
1662 ): Promise
<GenericResponse
> {
1664 !OCPP16ServiceUtils
.checkFeatureProfile(
1666 OCPP16SupportedFeatureProfiles
.Reservation
,
1667 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1670 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
;
1673 const { reservationId
} = commandPayload
;
1674 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
);
1675 if (isUndefined(reservation
)) {
1677 `${chargingStation.logPrefix()} Reservation with id ${reservationId}
1678 does not exist on charging station`,
1680 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
;
1682 await chargingStation
.removeReservation(
1684 ReservationTerminationReason
.RESERVATION_CANCELED
,
1686 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
;
1688 return this.handleIncomingRequestError
<GenericResponse
>(
1690 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1692 { errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
},