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';
15 secondsToMilliseconds
,
17 import { create
} from
'tar';
19 import { OCPP16Constants
} from
'./OCPP16Constants';
20 import { OCPP16ServiceUtils
} from
'./OCPP16ServiceUtils';
23 canProceedChargingProfile
,
24 canProceedRecurringChargingProfile
,
27 prepareRecurringChargingProfile
,
28 removeExpiredReservations
,
29 setConfigurationKeyValue
,
30 } from
'../../../charging-station';
31 import { OCPPError
} from
'../../../exception';
33 type ChangeConfigurationRequest
,
34 type ChangeConfigurationResponse
,
35 ChargingProfileKindType
,
37 type ClearChargingProfileRequest
,
38 type ClearChargingProfileResponse
,
42 type GetConfigurationRequest
,
43 type GetConfigurationResponse
,
44 type GetDiagnosticsRequest
,
45 type GetDiagnosticsResponse
,
46 type IncomingRequestHandler
,
49 OCPP16AuthorizationStatus
,
50 OCPP16AvailabilityType
,
51 type OCPP16BootNotificationRequest
,
52 type OCPP16BootNotificationResponse
,
53 type OCPP16CancelReservationRequest
,
54 type OCPP16ChangeAvailabilityRequest
,
55 type OCPP16ChangeAvailabilityResponse
,
56 OCPP16ChargePointErrorCode
,
57 OCPP16ChargePointStatus
,
58 type OCPP16ChargingProfile
,
59 OCPP16ChargingProfilePurposeType
,
60 type OCPP16ChargingSchedule
,
61 type OCPP16ClearCacheRequest
,
62 type OCPP16DataTransferRequest
,
63 type OCPP16DataTransferResponse
,
64 OCPP16DataTransferVendorId
,
65 OCPP16DiagnosticsStatus
,
66 type OCPP16DiagnosticsStatusNotificationRequest
,
67 type OCPP16DiagnosticsStatusNotificationResponse
,
69 type OCPP16FirmwareStatusNotificationRequest
,
70 type OCPP16FirmwareStatusNotificationResponse
,
71 type OCPP16GetCompositeScheduleRequest
,
72 type OCPP16GetCompositeScheduleResponse
,
73 type OCPP16HeartbeatRequest
,
74 type OCPP16HeartbeatResponse
,
75 OCPP16IncomingRequestCommand
,
78 type OCPP16ReserveNowRequest
,
79 type OCPP16ReserveNowResponse
,
80 OCPP16StandardParametersKey
,
81 type OCPP16StartTransactionRequest
,
82 type OCPP16StartTransactionResponse
,
83 type OCPP16StatusNotificationRequest
,
84 type OCPP16StatusNotificationResponse
,
85 OCPP16StopTransactionReason
,
86 OCPP16SupportedFeatureProfiles
,
87 type OCPP16TriggerMessageRequest
,
88 type OCPP16TriggerMessageResponse
,
89 type OCPP16UpdateFirmwareRequest
,
90 type OCPP16UpdateFirmwareResponse
,
91 type OCPPConfigurationKey
,
93 type RemoteStartTransactionRequest
,
94 type RemoteStopTransactionRequest
,
95 ReservationTerminationReason
,
97 type SetChargingProfileRequest
,
98 type SetChargingProfileResponse
,
99 type UnlockConnectorRequest
,
100 type UnlockConnectorResponse
,
101 } from
'../../../types';
107 formatDurationMilliSeconds
,
117 } from
'../../../utils';
118 import { OCPPIncomingRequestService
} from
'../OCPPIncomingRequestService';
120 const moduleName
= 'OCPP16IncomingRequestService';
122 export class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
123 protected jsonSchemas
: Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>;
124 private incomingRequestHandlers
: Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>;
126 public constructor() {
127 // if (new.target?.name === moduleName) {
128 // throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
130 super(OCPPVersion
.VERSION_16
);
131 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
133 OCPP16IncomingRequestCommand
.RESET
,
134 this.handleRequestReset
.bind(this) as unknown
as IncomingRequestHandler
,
137 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
138 this.handleRequestClearCache
.bind(this) as IncomingRequestHandler
,
141 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
142 this.handleRequestUnlockConnector
.bind(this) as unknown
as IncomingRequestHandler
,
145 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
146 this.handleRequestGetConfiguration
.bind(this) as IncomingRequestHandler
,
149 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
150 this.handleRequestChangeConfiguration
.bind(this) as unknown
as IncomingRequestHandler
,
153 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
154 this.handleRequestGetCompositeSchedule
.bind(this) as unknown
as IncomingRequestHandler
,
157 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
158 this.handleRequestSetChargingProfile
.bind(this) as unknown
as IncomingRequestHandler
,
161 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
162 this.handleRequestClearChargingProfile
.bind(this) as IncomingRequestHandler
,
165 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
166 this.handleRequestChangeAvailability
.bind(this) as unknown
as IncomingRequestHandler
,
169 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
170 this.handleRequestRemoteStartTransaction
.bind(this) as unknown
as IncomingRequestHandler
,
173 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
174 this.handleRequestRemoteStopTransaction
.bind(this) as unknown
as IncomingRequestHandler
,
177 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
178 this.handleRequestGetDiagnostics
.bind(this) as IncomingRequestHandler
,
181 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
182 this.handleRequestTriggerMessage
.bind(this) as unknown
as IncomingRequestHandler
,
185 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
186 this.handleRequestDataTransfer
.bind(this) as unknown
as IncomingRequestHandler
,
189 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
190 this.handleRequestUpdateFirmware
.bind(this) as unknown
as IncomingRequestHandler
,
193 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
194 this.handleRequestReserveNow
.bind(this) as unknown
as IncomingRequestHandler
,
197 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
198 this.handleRequestCancelReservation
.bind(this) as unknown
as IncomingRequestHandler
,
201 this.jsonSchemas
= new Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>([
203 OCPP16IncomingRequestCommand
.RESET
,
204 OCPP16ServiceUtils
.parseJsonSchemaFile
<ResetRequest
>(
205 'assets/json-schemas/ocpp/1.6/Reset.json',
211 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
212 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ClearCacheRequest
>(
213 'assets/json-schemas/ocpp/1.6/ClearCache.json',
219 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
220 OCPP16ServiceUtils
.parseJsonSchemaFile
<UnlockConnectorRequest
>(
221 'assets/json-schemas/ocpp/1.6/UnlockConnector.json',
227 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
228 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetConfigurationRequest
>(
229 'assets/json-schemas/ocpp/1.6/GetConfiguration.json',
235 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
236 OCPP16ServiceUtils
.parseJsonSchemaFile
<ChangeConfigurationRequest
>(
237 'assets/json-schemas/ocpp/1.6/ChangeConfiguration.json',
243 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
244 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetDiagnosticsRequest
>(
245 'assets/json-schemas/ocpp/1.6/GetDiagnostics.json',
251 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
252 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16GetCompositeScheduleRequest
>(
253 'assets/json-schemas/ocpp/1.6/GetCompositeSchedule.json',
259 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
260 OCPP16ServiceUtils
.parseJsonSchemaFile
<SetChargingProfileRequest
>(
261 'assets/json-schemas/ocpp/1.6/SetChargingProfile.json',
267 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
268 OCPP16ServiceUtils
.parseJsonSchemaFile
<ClearChargingProfileRequest
>(
269 'assets/json-schemas/ocpp/1.6/ClearChargingProfile.json',
275 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
276 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ChangeAvailabilityRequest
>(
277 'assets/json-schemas/ocpp/1.6/ChangeAvailability.json',
283 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
284 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStartTransactionRequest
>(
285 'assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json',
291 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
292 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStopTransactionRequest
>(
293 'assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json',
299 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
300 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16TriggerMessageRequest
>(
301 'assets/json-schemas/ocpp/1.6/TriggerMessage.json',
307 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
308 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16DataTransferRequest
>(
309 'assets/json-schemas/ocpp/1.6/DataTransfer.json',
315 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
316 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16UpdateFirmwareRequest
>(
317 'assets/json-schemas/ocpp/1.6/UpdateFirmware.json',
323 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
324 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ReserveNowRequest
>(
325 'assets/json-schemas/ocpp/1.6/ReserveNow.json',
331 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
332 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16CancelReservationRequest
>(
333 'assets/json-schemas/ocpp/1.6/CancelReservation.json',
339 this.validatePayload
= this.validatePayload
.bind(this) as (
340 chargingStation
: ChargingStation
,
341 commandName
: OCPP16IncomingRequestCommand
,
342 commandPayload
: JsonType
,
346 public async incomingRequestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
347 chargingStation
: ChargingStation
,
349 commandName
: OCPP16IncomingRequestCommand
,
350 commandPayload
: ReqType
,
352 let response
: ResType
;
354 chargingStation
.getOcppStrictCompliance() === true &&
355 chargingStation
.inPendingState() === true &&
356 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
357 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
360 ErrorType
.SECURITY_ERROR
,
361 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
365 )} while the charging station is in pending state on the central server`,
371 chargingStation
.isRegistered() === true ||
372 (chargingStation
.getOcppStrictCompliance() === false &&
373 chargingStation
.inUnknownState() === true)
376 this.incomingRequestHandlers
.has(commandName
) === true &&
377 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
) === true
380 this.validatePayload(chargingStation
, commandName
, commandPayload
);
381 // Call the method to build the response
382 response
= (await this.incomingRequestHandlers
.get(commandName
)!(
389 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler:
390 Handle incoming request error:`,
398 ErrorType
.NOT_IMPLEMENTED
,
399 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
410 ErrorType
.SECURITY_ERROR
,
411 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
415 )} while the charging station is not registered on the central server.`,
420 // Send the built response
421 await chargingStation
.ocppRequestService
.sendResponse(
429 private validatePayload(
430 chargingStation
: ChargingStation
,
431 commandName
: OCPP16IncomingRequestCommand
,
432 commandPayload
: JsonType
,
434 if (this.jsonSchemas
.has(commandName
) === true) {
435 return this.validateIncomingRequestPayload(
438 this.jsonSchemas
.get(commandName
)!,
443 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found
444 for command '${commandName}' PDU validation`,
449 // Simulate charging station restart
450 private handleRequestReset(
451 chargingStation
: ChargingStation
,
452 commandPayload
: ResetRequest
,
454 const { type } = commandPayload
;
455 this.runInAsyncScope(
456 chargingStation
.reset
.bind(chargingStation
) as (
457 this: ChargingStation
,
461 `${type}Reset` as OCPP16StopTransactionReason
,
462 ).catch(Constants
.EMPTY_FUNCTION
);
464 `${chargingStation.logPrefix()} ${type} reset command received, simulating it. The station will be
465 back online in ${formatDurationMilliSeconds(chargingStation.stationInfo.resetTime!)}`,
467 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
470 private async handleRequestUnlockConnector(
471 chargingStation
: ChargingStation
,
472 commandPayload
: UnlockConnectorRequest
,
473 ): Promise
<UnlockConnectorResponse
> {
474 const { connectorId
} = commandPayload
;
475 if (chargingStation
.hasConnector(connectorId
) === false) {
477 `${chargingStation.logPrefix()} Trying to unlock a non existing
478 connector id ${connectorId.toString()}`,
480 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
482 if (connectorId
=== 0) {
484 `${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId.toString()}`,
486 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
488 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
489 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
491 OCPP16StopTransactionReason
.UNLOCK_COMMAND
,
493 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
494 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
;
496 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
498 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
501 OCPP16ChargePointStatus
.Available
,
503 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
;
506 private handleRequestGetConfiguration(
507 chargingStation
: ChargingStation
,
508 commandPayload
: GetConfigurationRequest
,
509 ): GetConfigurationResponse
{
510 const { key
} = commandPayload
;
511 const configurationKey
: OCPPConfigurationKey
[] = [];
512 const unknownKey
: string[] = [];
513 if (isUndefined(key
) === true) {
514 for (const configuration
of chargingStation
.ocppConfiguration
!.configurationKey
!) {
515 if (isUndefined(configuration
.visible
) === true) {
516 configuration
.visible
= true;
518 if (configuration
.visible
=== false) {
521 configurationKey
.push({
522 key
: configuration
.key
,
523 readonly: configuration
.readonly,
524 value
: configuration
.value
,
527 } else if (isNotEmptyArray(key
) === true) {
528 for (const k
of key
!) {
529 const keyFound
= getConfigurationKey(chargingStation
, k
, true);
531 if (isUndefined(keyFound
.visible
) === true) {
532 keyFound
.visible
= true;
534 if (keyFound
.visible
=== false) {
537 configurationKey
.push({
539 readonly: keyFound
.readonly,
540 value
: keyFound
.value
,
553 private handleRequestChangeConfiguration(
554 chargingStation
: ChargingStation
,
555 commandPayload
: ChangeConfigurationRequest
,
556 ): ChangeConfigurationResponse
{
557 const { key
, value
} = commandPayload
;
558 const keyToChange
= getConfigurationKey(chargingStation
, key
, true);
559 if (keyToChange
?.readonly === true) {
560 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
561 } else if (keyToChange
?.readonly === false) {
562 let valueChanged
= false;
563 if (keyToChange
.value
!== value
) {
564 setConfigurationKeyValue(chargingStation
, key
, value
, true);
567 let triggerHeartbeatRestart
= false;
569 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
570 OCPP16StandardParametersKey
.HeartBeatInterval
&&
573 setConfigurationKeyValue(
575 OCPP16StandardParametersKey
.HeartbeatInterval
,
578 triggerHeartbeatRestart
= true;
581 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
582 OCPP16StandardParametersKey
.HeartbeatInterval
&&
585 setConfigurationKeyValue(
587 OCPP16StandardParametersKey
.HeartBeatInterval
,
590 triggerHeartbeatRestart
= true;
592 if (triggerHeartbeatRestart
) {
593 chargingStation
.restartHeartbeat();
596 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
597 OCPP16StandardParametersKey
.WebSocketPingInterval
&&
600 chargingStation
.restartWebSocketPing();
602 if (keyToChange
.reboot
) {
603 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
605 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
607 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
610 private handleRequestSetChargingProfile(
611 chargingStation
: ChargingStation
,
612 commandPayload
: SetChargingProfileRequest
,
613 ): SetChargingProfileResponse
{
615 OCPP16ServiceUtils
.checkFeatureProfile(
617 OCPP16SupportedFeatureProfiles
.SmartCharging
,
618 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
621 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
623 const { connectorId
, csChargingProfiles
} = commandPayload
;
624 if (chargingStation
.hasConnector(connectorId
) === false) {
626 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a
627 non existing connector id ${connectorId}`,
629 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
632 csChargingProfiles
.chargingProfilePurpose
===
633 OCPP16ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
636 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
639 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
640 (connectorId
=== 0 ||
641 chargingStation
.getConnectorStatus(connectorId
)?.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
;
649 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, csChargingProfiles
);
651 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${connectorId}: %j`,
654 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
657 private handleRequestGetCompositeSchedule(
658 chargingStation
: ChargingStation
,
659 commandPayload
: OCPP16GetCompositeScheduleRequest
,
660 ): OCPP16GetCompositeScheduleResponse
{
662 OCPP16ServiceUtils
.checkFeatureProfile(
664 OCPP16SupportedFeatureProfiles
.SmartCharging
,
665 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
668 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
670 const { connectorId
, duration
, chargingRateUnit
} = commandPayload
;
671 if (chargingStation
.hasConnector(connectorId
) === false) {
673 `${chargingStation.logPrefix()} Trying to get composite schedule to a
674 non existing connector id ${connectorId}`,
676 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
678 if (connectorId
=== 0) {
680 `${chargingStation.logPrefix()} Get composite schedule on connector id ${connectorId} is not yet supported`,
682 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
684 if (chargingRateUnit
) {
686 `${chargingStation.logPrefix()} Get composite schedule with a specified rate unit is not yet supported`,
688 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
690 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
);
693 connectorStatus
?.chargingProfiles
&&
694 isEmptyArray(chargingStation
.getConnectorStatus(0)?.chargingProfiles
),
697 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
699 const currentDate
= new Date();
700 const interval
: Interval
= {
702 end
: addSeconds(currentDate
, duration
),
704 const chargingProfiles
: OCPP16ChargingProfile
[] = [];
705 for (const chargingProfile
of cloneObject
<OCPP16ChargingProfile
[]>(
706 (connectorStatus
?.chargingProfiles
?? []).concat(
707 chargingStation
.getConnectorStatus(0)?.chargingProfiles
?? [],
709 ).sort((a
, b
) => b
.stackLevel
- a
.stackLevel
)) {
711 connectorStatus
?.transactionStarted
&&
712 isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
)
715 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
716 chargingProfile.chargingProfileId
717 } has no startSchedule defined. Trying to set it to the connector current transaction start date`,
719 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
720 chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
;
722 if (!isDate(chargingProfile
.chargingSchedule
?.startSchedule
)) {
724 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
725 chargingProfile.chargingProfileId
726 } startSchedule property is not a Date object. Trying to convert it to a Date object`,
728 chargingProfile
.chargingSchedule
.startSchedule
= convertToDate(
729 chargingProfile
.chargingSchedule
?.startSchedule
,
732 switch (chargingProfile
.chargingProfileKind
) {
733 case ChargingProfileKindType
.RECURRING
:
734 if (!canProceedRecurringChargingProfile(chargingProfile
, chargingStation
.logPrefix())) {
737 prepareRecurringChargingProfile(
739 interval
.start
as Date,
740 chargingStation
.logPrefix(),
743 case ChargingProfileKindType
.RELATIVE
:
744 connectorStatus
?.transactionStarted
&&
745 (chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
);
749 !canProceedChargingProfile(
751 interval
.start
as Date,
752 chargingStation
.logPrefix(),
757 // Add active charging profiles into chargingProfiles array
759 isValidTime(chargingProfile
.chargingSchedule
?.startSchedule
) &&
760 isWithinInterval(chargingProfile
.chargingSchedule
.startSchedule
!, interval
)
762 chargingProfiles
.push(chargingProfile
);
765 const compositeSchedule
: OCPP16ChargingSchedule
= {
767 chargingProfiles
.map(
768 (chargingProfile
) => chargingProfile
.chargingSchedule
.startSchedule
?? maxTime
,
772 ...chargingProfiles
.map(
773 (chargingProfile
) => chargingProfile
.chargingSchedule
.duration
?? -Infinity,
776 chargingRateUnit
: chargingProfiles
.every(
778 chargingProfile
.chargingSchedule
.chargingRateUnit
=== ChargingRateUnitType
.AMPERE
,
780 ? ChargingRateUnitType
.AMPERE
781 : chargingProfiles
.every(
783 chargingProfile
.chargingSchedule
.chargingRateUnit
=== ChargingRateUnitType
.WATT
,
785 ? ChargingRateUnitType
.WATT
786 : ChargingRateUnitType
.AMPERE
,
787 // FIXME: remove overlapping charging schedule periods
788 chargingSchedulePeriod
: chargingProfiles
789 .map((chargingProfile
) => chargingProfile
.chargingSchedule
.chargingSchedulePeriod
)
791 (accumulator
, value
) =>
792 accumulator
.concat(value
).sort((a
, b
) => a
.startPeriod
- b
.startPeriod
),
795 minChargeRate
: Math.min(
796 ...chargingProfiles
.map(
797 (chargingProfile
) => chargingProfile
.chargingSchedule
.minChargeRate
?? Infinity,
802 status: GenericStatus
.Accepted
,
803 scheduleStart
: compositeSchedule
.startSchedule
!,
805 chargingSchedule
: compositeSchedule
,
809 private handleRequestClearChargingProfile(
810 chargingStation
: ChargingStation
,
811 commandPayload
: ClearChargingProfileRequest
,
812 ): ClearChargingProfileResponse
{
814 OCPP16ServiceUtils
.checkFeatureProfile(
816 OCPP16SupportedFeatureProfiles
.SmartCharging
,
817 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
820 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
822 const { connectorId
} = commandPayload
;
823 if (chargingStation
.hasConnector(connectorId
!) === false) {
825 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to
826 a non existing connector id ${connectorId}`,
828 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
831 !isNullOrUndefined(connectorId
) &&
832 isNotEmptyArray(chargingStation
.getConnectorStatus(connectorId
!)?.chargingProfiles
)
834 chargingStation
.getConnectorStatus(connectorId
!)!.chargingProfiles
= [];
836 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}`,
838 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
840 if (isNullOrUndefined(connectorId
)) {
841 let clearedCP
= false;
842 if (chargingStation
.hasEvses
) {
843 for (const evseStatus
of chargingStation
.evses
.values()) {
844 for (const connectorStatus
of evseStatus
.connectors
.values()) {
845 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
848 connectorStatus
.chargingProfiles
,
853 for (const id
of chargingStation
.connectors
.keys()) {
854 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
857 chargingStation
.getConnectorStatus(id
)?.chargingProfiles
,
862 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
865 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
868 private async handleRequestChangeAvailability(
869 chargingStation
: ChargingStation
,
870 commandPayload
: OCPP16ChangeAvailabilityRequest
,
871 ): Promise
<OCPP16ChangeAvailabilityResponse
> {
872 const { connectorId
, type } = commandPayload
;
873 if (chargingStation
.hasConnector(connectorId
) === false) {
875 `${chargingStation.logPrefix()} Trying to change the availability of a
876 non existing connector id ${connectorId.toString()}`,
878 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
880 const chargePointStatus
: OCPP16ChargePointStatus
=
881 type === OCPP16AvailabilityType
.Operative
882 ? OCPP16ChargePointStatus
.Available
883 : OCPP16ChargePointStatus
.Unavailable
;
884 if (connectorId
=== 0) {
885 let response
: OCPP16ChangeAvailabilityResponse
;
886 if (chargingStation
.hasEvses
) {
887 for (const evseStatus
of chargingStation
.evses
.values()) {
888 response
= await OCPP16ServiceUtils
.changeAvailability(
890 [...evseStatus
.connectors
.keys()],
896 response
= await OCPP16ServiceUtils
.changeAvailability(
898 [...chargingStation
.connectors
.keys()],
906 (chargingStation
.isChargingStationAvailable() === true ||
907 (chargingStation
.isChargingStationAvailable() === false &&
908 type === OCPP16AvailabilityType
.Inoperative
))
910 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
911 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type;
912 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
914 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type;
915 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
920 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
922 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
925 private async handleRequestRemoteStartTransaction(
926 chargingStation
: ChargingStation
,
927 commandPayload
: RemoteStartTransactionRequest
,
928 ): Promise
<GenericResponse
> {
929 const { connectorId
: transactionConnectorId
, idTag
, chargingProfile
} = commandPayload
;
930 if (chargingStation
.hasConnector(transactionConnectorId
) === false) {
931 return this.notifyRemoteStartTransactionRejected(
933 transactionConnectorId
,
938 !chargingStation
.isChargingStationAvailable() ||
939 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
941 return this.notifyRemoteStartTransactionRejected(
943 transactionConnectorId
,
947 const remoteStartTransactionLogMsg
= `
948 ${chargingStation.logPrefix()} Transaction remotely STARTED on ${
949 chargingStation.stationInfo.chargingStationId
950 }#${transactionConnectorId.toString()} for idTag '${idTag}'`;
951 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
953 transactionConnectorId
,
954 OCPP16ChargePointStatus
.Preparing
,
956 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
)!;
957 // Authorization check required
959 chargingStation
.getAuthorizeRemoteTxRequests() === true &&
960 (await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
962 // Authorization successful, start transaction
964 this.setRemoteStartTransactionChargingProfile(
966 transactionConnectorId
,
970 connectorStatus
.transactionRemoteStarted
= true;
973 await chargingStation
.ocppRequestService
.requestHandler
<
974 OCPP16StartTransactionRequest
,
975 OCPP16StartTransactionResponse
976 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
977 connectorId
: transactionConnectorId
,
980 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
982 logger
.debug(remoteStartTransactionLogMsg
);
983 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
985 return this.notifyRemoteStartTransactionRejected(
987 transactionConnectorId
,
991 return this.notifyRemoteStartTransactionRejected(
993 transactionConnectorId
,
997 // No authorization check required, start transaction
999 this.setRemoteStartTransactionChargingProfile(
1001 transactionConnectorId
,
1005 connectorStatus
.transactionRemoteStarted
= true;
1008 await chargingStation
.ocppRequestService
.requestHandler
<
1009 OCPP16StartTransactionRequest
,
1010 OCPP16StartTransactionResponse
1011 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
1012 connectorId
: transactionConnectorId
,
1015 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
1017 logger
.debug(remoteStartTransactionLogMsg
);
1018 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
1020 return this.notifyRemoteStartTransactionRejected(
1022 transactionConnectorId
,
1026 return this.notifyRemoteStartTransactionRejected(
1028 transactionConnectorId
,
1033 private async notifyRemoteStartTransactionRejected(
1034 chargingStation
: ChargingStation
,
1035 connectorId
: number,
1037 ): Promise
<GenericResponse
> {
1039 chargingStation
.getConnectorStatus(connectorId
)?.status !== OCPP16ChargePointStatus
.Available
1041 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1044 OCPP16ChargePointStatus
.Available
,
1048 `${chargingStation.logPrefix()} Remote starting transaction REJECTED on connector id
1049 ${connectorId.toString()}, idTag '${idTag}', availability '${chargingStation.getConnectorStatus(
1051 )?.availability}', status '${chargingStation.getConnectorStatus(connectorId)?.status}'`,
1053 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
1056 private setRemoteStartTransactionChargingProfile(
1057 chargingStation
: ChargingStation
,
1058 connectorId
: number,
1059 chargingProfile
: OCPP16ChargingProfile
,
1063 chargingProfile
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
1065 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
);
1067 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction
1068 on connector id ${connectorId}: %j`,
1074 chargingProfile
.chargingProfilePurpose
!== OCPP16ChargingProfilePurposeType
.TX_PROFILE
1077 `${chargingStation.logPrefix()} Not allowed to set ${
1078 chargingProfile.chargingProfilePurpose
1079 } charging profile(s) at remote start transaction`,
1086 private async handleRequestRemoteStopTransaction(
1087 chargingStation
: ChargingStation
,
1088 commandPayload
: RemoteStopTransactionRequest
,
1089 ): Promise
<GenericResponse
> {
1090 const { transactionId
} = commandPayload
;
1091 if (chargingStation
.hasEvses
) {
1092 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1094 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1095 if (connectorStatus
.transactionId
=== transactionId
) {
1096 return OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
);
1102 for (const connectorId
of chargingStation
.connectors
.keys()) {
1105 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
1107 return OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
);
1112 `${chargingStation.logPrefix()} Trying to remote stop a non existing transaction with id
1113 ${transactionId.toString()}`,
1115 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
1118 private handleRequestUpdateFirmware(
1119 chargingStation
: ChargingStation
,
1120 commandPayload
: OCPP16UpdateFirmwareRequest
,
1121 ): OCPP16UpdateFirmwareResponse
{
1123 OCPP16ServiceUtils
.checkFeatureProfile(
1125 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1126 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
1130 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware:
1131 Cannot simulate firmware update: feature profile not supported`,
1133 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1135 let { retrieveDate
} = commandPayload
;
1137 !isNullOrUndefined(chargingStation
.stationInfo
.firmwareStatus
) &&
1138 chargingStation
.stationInfo
.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
1141 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware:
1142 Cannot simulate firmware update: firmware update is already in progress`,
1144 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1146 retrieveDate
= convertToDate(retrieveDate
)!;
1147 const now
= Date.now();
1148 if (retrieveDate
?.getTime() <= now
) {
1149 this.runInAsyncScope(
1150 this.updateFirmwareSimulation
.bind(this) as (
1151 this: OCPP16IncomingRequestService
,
1156 ).catch(Constants
.EMPTY_FUNCTION
);
1160 this.runInAsyncScope(
1161 this.updateFirmwareSimulation
.bind(this) as (
1162 this: OCPP16IncomingRequestService
,
1167 ).catch(Constants
.EMPTY_FUNCTION
);
1169 retrieveDate
?.getTime() - now
,
1172 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1175 private async updateFirmwareSimulation(
1176 chargingStation
: ChargingStation
,
1180 if (checkChargingStation(chargingStation
, chargingStation
.logPrefix()) === false) {
1183 if (chargingStation
.hasEvses
) {
1184 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1186 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1187 if (connectorStatus
?.transactionStarted
=== false) {
1188 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1191 OCPP16ChargePointStatus
.Unavailable
,
1198 for (const connectorId
of chargingStation
.connectors
.keys()) {
1201 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1203 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1206 OCPP16ChargePointStatus
.Unavailable
,
1211 await chargingStation
.ocppRequestService
.requestHandler
<
1212 OCPP16FirmwareStatusNotificationRequest
,
1213 OCPP16FirmwareStatusNotificationResponse
1214 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1215 status: OCPP16FirmwareStatus
.Downloading
,
1217 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
;
1219 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1220 OCPP16FirmwareStatus
.DownloadFailed
1222 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1223 await chargingStation
.ocppRequestService
.requestHandler
<
1224 OCPP16FirmwareStatusNotificationRequest
,
1225 OCPP16FirmwareStatusNotificationResponse
1226 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1227 status: chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
,
1229 chargingStation
.stationInfo
.firmwareStatus
=
1230 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
;
1233 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1234 await chargingStation
.ocppRequestService
.requestHandler
<
1235 OCPP16FirmwareStatusNotificationRequest
,
1236 OCPP16FirmwareStatusNotificationResponse
1237 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1238 status: OCPP16FirmwareStatus
.Downloaded
,
1240 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
;
1241 let wasTransactionsStarted
= false;
1242 let transactionsStarted
: boolean;
1244 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions();
1245 if (runningTransactions
> 0) {
1246 const waitTime
= secondsToMilliseconds(15);
1248 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation:
1249 ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1251 )} before continuing firmware update simulation`,
1253 await sleep(waitTime
);
1254 transactionsStarted
= true;
1255 wasTransactionsStarted
= true;
1257 if (chargingStation
.hasEvses
) {
1258 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1260 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1261 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Unavailable
) {
1262 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1265 OCPP16ChargePointStatus
.Unavailable
,
1272 for (const connectorId
of chargingStation
.connectors
.keys()) {
1275 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1276 OCPP16ChargePointStatus
.Unavailable
1278 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1281 OCPP16ChargePointStatus
.Unavailable
,
1286 transactionsStarted
= false;
1288 } while (transactionsStarted
);
1289 !wasTransactionsStarted
&&
1290 (await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
))));
1291 if (checkChargingStation(chargingStation
, chargingStation
.logPrefix()) === false) {
1294 await chargingStation
.ocppRequestService
.requestHandler
<
1295 OCPP16FirmwareStatusNotificationRequest
,
1296 OCPP16FirmwareStatusNotificationResponse
1297 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1298 status: OCPP16FirmwareStatus
.Installing
,
1300 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Installing
;
1302 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1303 OCPP16FirmwareStatus
.InstallationFailed
1305 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1306 await chargingStation
.ocppRequestService
.requestHandler
<
1307 OCPP16FirmwareStatusNotificationRequest
,
1308 OCPP16FirmwareStatusNotificationResponse
1309 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1310 status: chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
,
1312 chargingStation
.stationInfo
.firmwareStatus
=
1313 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
;
1316 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1317 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1318 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
);
1322 private async handleRequestGetDiagnostics(
1323 chargingStation
: ChargingStation
,
1324 commandPayload
: GetDiagnosticsRequest
,
1325 ): Promise
<GetDiagnosticsResponse
> {
1327 OCPP16ServiceUtils
.checkFeatureProfile(
1329 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1330 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1334 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics:
1335 Cannot get diagnostics: feature profile not supported`,
1337 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1339 const { location
} = commandPayload
;
1340 const uri
= new URL(location
);
1341 if (uri
.protocol
.startsWith('ftp:')) {
1342 let ftpClient
: Client
| undefined;
1344 const logFiles
= readdirSync(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'))
1345 .filter((file
) => file
.endsWith('.log'))
1346 .map((file
) => join('./', file
));
1347 const diagnosticsArchive
= `${chargingStation.stationInfo.chargingStationId}_logs.tar.gz`;
1348 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
));
1349 ftpClient
= new Client();
1350 const accessResponse
= await ftpClient
.access({
1352 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1353 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1354 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
}),
1356 let uploadResponse
: FTPResponse
| undefined;
1357 if (accessResponse
.code
=== 220) {
1358 ftpClient
.trackProgress((info
) => {
1360 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1362 } bytes transferred from diagnostics archive ${info.name}`,
1364 chargingStation
.ocppRequestService
1366 OCPP16DiagnosticsStatusNotificationRequest
,
1367 OCPP16DiagnosticsStatusNotificationResponse
1368 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1369 status: OCPP16DiagnosticsStatus
.Uploading
,
1373 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics:
1374 Error while sending '${OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION}'`,
1379 uploadResponse
= await ftpClient
.uploadFrom(
1380 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1381 `${uri.pathname}${diagnosticsArchive}`,
1383 if (uploadResponse
.code
=== 226) {
1384 await chargingStation
.ocppRequestService
.requestHandler
<
1385 OCPP16DiagnosticsStatusNotificationRequest
,
1386 OCPP16DiagnosticsStatusNotificationResponse
1387 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1388 status: OCPP16DiagnosticsStatus
.Uploaded
,
1393 return { fileName
: diagnosticsArchive
};
1395 throw new OCPPError(
1396 ErrorType
.GENERIC_ERROR
,
1397 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1398 uploadResponse?.code && `|${uploadResponse?.code.toString()}
`
1400 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1403 throw new OCPPError(
1404 ErrorType
.GENERIC_ERROR
,
1405 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1406 uploadResponse?.code && `|${uploadResponse?.code.toString()}
`
1408 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1411 await chargingStation
.ocppRequestService
.requestHandler
<
1412 OCPP16DiagnosticsStatusNotificationRequest
,
1413 OCPP16DiagnosticsStatusNotificationResponse
1414 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1415 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1420 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1422 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1424 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
},
1429 `${chargingStation.logPrefix()} Unsupported protocol ${
1431 } to transfer the diagnostic logs archive`,
1433 await chargingStation
.ocppRequestService
.requestHandler
<
1434 OCPP16DiagnosticsStatusNotificationRequest
,
1435 OCPP16DiagnosticsStatusNotificationResponse
1436 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1437 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1439 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1443 private handleRequestTriggerMessage(
1444 chargingStation
: ChargingStation
,
1445 commandPayload
: OCPP16TriggerMessageRequest
,
1446 ): OCPP16TriggerMessageResponse
{
1447 const { requestedMessage
, connectorId
} = commandPayload
;
1449 !OCPP16ServiceUtils
.checkFeatureProfile(
1451 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1452 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1454 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1456 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1459 !OCPP16ServiceUtils
.isConnectorIdValid(
1461 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1465 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1468 switch (requestedMessage
) {
1469 case OCPP16MessageTrigger
.BootNotification
:
1471 chargingStation
.ocppRequestService
1472 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1474 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1475 chargingStation
.bootNotificationRequest
,
1476 { skipBufferingOnError
: true, triggerMessage
: true },
1478 .then((response
) => {
1479 chargingStation
.bootNotificationResponse
= response
;
1481 .catch(Constants
.EMPTY_FUNCTION
);
1482 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1483 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1484 case OCPP16MessageTrigger
.Heartbeat
:
1486 chargingStation
.ocppRequestService
1487 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1489 OCPP16RequestCommand
.HEARTBEAT
,
1492 triggerMessage
: true,
1495 .catch(Constants
.EMPTY_FUNCTION
);
1496 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1497 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1498 case OCPP16MessageTrigger
.StatusNotification
:
1500 if (!isNullOrUndefined(connectorId
)) {
1501 chargingStation
.ocppRequestService
1502 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1504 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1507 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1508 status: chargingStation
.getConnectorStatus(connectorId
!)?.status,
1511 triggerMessage
: true,
1514 .catch(Constants
.EMPTY_FUNCTION
);
1516 // eslint-disable-next-line no-lonely-if
1517 if (chargingStation
.hasEvses
) {
1518 for (const evseStatus
of chargingStation
.evses
.values()) {
1519 for (const [id
, connectorStatus
] of evseStatus
.connectors
) {
1520 chargingStation
.ocppRequestService
1522 OCPP16StatusNotificationRequest
,
1523 OCPP16StatusNotificationResponse
1526 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1529 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1530 status: connectorStatus
.status,
1533 triggerMessage
: true,
1536 .catch(Constants
.EMPTY_FUNCTION
);
1540 for (const id
of chargingStation
.connectors
.keys()) {
1541 chargingStation
.ocppRequestService
1543 OCPP16StatusNotificationRequest
,
1544 OCPP16StatusNotificationResponse
1547 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1550 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1551 status: chargingStation
.getConnectorStatus(id
)?.status,
1554 triggerMessage
: true,
1557 .catch(Constants
.EMPTY_FUNCTION
);
1561 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1562 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1564 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1567 return this.handleIncomingRequestError
<OCPP16TriggerMessageResponse
>(
1569 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1571 { errorResponse
: OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
},
1576 private handleRequestDataTransfer(
1577 chargingStation
: ChargingStation
,
1578 commandPayload
: OCPP16DataTransferRequest
,
1579 ): OCPP16DataTransferResponse
{
1580 const { vendorId
} = commandPayload
;
1582 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1583 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
;
1585 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
;
1587 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1589 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1591 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
},
1596 private async handleRequestReserveNow(
1597 chargingStation
: ChargingStation
,
1598 commandPayload
: OCPP16ReserveNowRequest
,
1599 ): Promise
<OCPP16ReserveNowResponse
> {
1601 !OCPP16ServiceUtils
.checkFeatureProfile(
1603 OCPP16SupportedFeatureProfiles
.Reservation
,
1604 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1607 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1609 const { reservationId
, idTag
, connectorId
} = commandPayload
;
1610 let response
: OCPP16ReserveNowResponse
;
1612 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1613 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1615 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1616 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1618 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1619 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1621 await removeExpiredReservations(chargingStation
);
1622 switch (chargingStation
.getConnectorStatus(connectorId
)!.status) {
1623 case OCPP16ChargePointStatus
.Faulted
:
1624 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
;
1626 case OCPP16ChargePointStatus
.Preparing
:
1627 case OCPP16ChargePointStatus
.Charging
:
1628 case OCPP16ChargePointStatus
.SuspendedEV
:
1629 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1630 case OCPP16ChargePointStatus
.Finishing
:
1631 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1633 case OCPP16ChargePointStatus
.Unavailable
:
1634 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
;
1636 case OCPP16ChargePointStatus
.Reserved
:
1637 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1638 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1641 // eslint-disable-next-line no-fallthrough
1643 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1644 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1647 await chargingStation
.addReservation({
1648 id
: commandPayload
.reservationId
,
1651 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
;
1656 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
;
1657 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1659 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1661 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
},
1666 private async handleRequestCancelReservation(
1667 chargingStation
: ChargingStation
,
1668 commandPayload
: OCPP16CancelReservationRequest
,
1669 ): Promise
<GenericResponse
> {
1671 !OCPP16ServiceUtils
.checkFeatureProfile(
1673 OCPP16SupportedFeatureProfiles
.Reservation
,
1674 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1677 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
;
1680 const { reservationId
} = commandPayload
;
1681 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
);
1682 if (isUndefined(reservation
)) {
1684 `${chargingStation.logPrefix()} Reservation with id ${reservationId}
1685 does not exist on charging station`,
1687 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
;
1689 await chargingStation
.removeReservation(
1691 ReservationTerminationReason
.RESERVATION_CANCELED
,
1693 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
;
1695 return this.handleIncomingRequestError
<GenericResponse
>(
1697 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1699 { errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
},