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
,
39 OCPP16AuthorizationStatus
,
40 OCPP16AvailabilityType
,
41 type OCPP16BootNotificationRequest
,
42 type OCPP16BootNotificationResponse
,
43 type OCPP16CancelReservationRequest
,
44 type OCPP16ChangeAvailabilityRequest
,
45 type OCPP16ChangeAvailabilityResponse
,
46 OCPP16ChargePointErrorCode
,
47 OCPP16ChargePointStatus
,
48 type OCPP16ChargingProfile
,
49 OCPP16ChargingProfilePurposeType
,
50 type OCPP16ChargingSchedule
,
51 type OCPP16ClearCacheRequest
,
52 type OCPP16DataTransferRequest
,
53 type OCPP16DataTransferResponse
,
54 OCPP16DataTransferVendorId
,
55 OCPP16DiagnosticsStatus
,
56 type OCPP16DiagnosticsStatusNotificationRequest
,
57 type OCPP16DiagnosticsStatusNotificationResponse
,
59 type OCPP16FirmwareStatusNotificationRequest
,
60 type OCPP16FirmwareStatusNotificationResponse
,
61 type OCPP16GetCompositeScheduleRequest
,
62 type OCPP16GetCompositeScheduleResponse
,
63 type OCPP16HeartbeatRequest
,
64 type OCPP16HeartbeatResponse
,
65 OCPP16IncomingRequestCommand
,
68 type OCPP16ReserveNowRequest
,
69 type OCPP16ReserveNowResponse
,
70 OCPP16StandardParametersKey
,
71 type OCPP16StartTransactionRequest
,
72 type OCPP16StartTransactionResponse
,
73 type OCPP16StatusNotificationRequest
,
74 type OCPP16StatusNotificationResponse
,
75 OCPP16StopTransactionReason
,
76 OCPP16SupportedFeatureProfiles
,
77 type OCPP16TriggerMessageRequest
,
78 type OCPP16TriggerMessageResponse
,
79 type OCPP16UpdateFirmwareRequest
,
80 type OCPP16UpdateFirmwareResponse
,
81 type OCPPConfigurationKey
,
83 type RemoteStartTransactionRequest
,
84 type RemoteStopTransactionRequest
,
85 ReservationTerminationReason
,
87 type SetChargingProfileRequest
,
88 type SetChargingProfileResponse
,
89 type UnlockConnectorRequest
,
90 type UnlockConnectorResponse
,
91 } from
'../../../types';
96 formatDurationMilliSeconds
,
105 } from
'../../../utils';
106 import { OCPPIncomingRequestService
} from
'../OCPPIncomingRequestService';
108 const moduleName
= 'OCPP16IncomingRequestService';
110 export class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
111 protected jsonSchemas
: Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonType
>>;
112 private incomingRequestHandlers
: Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>;
114 public constructor() {
115 // if (new.target?.name === moduleName) {
116 // throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
118 super(OCPPVersion
.VERSION_16
);
119 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
121 OCPP16IncomingRequestCommand
.RESET
,
122 this.handleRequestReset
.bind(this) as unknown
as IncomingRequestHandler
,
125 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
126 this.handleRequestClearCache
.bind(this) as IncomingRequestHandler
,
129 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
130 this.handleRequestUnlockConnector
.bind(this) as unknown
as IncomingRequestHandler
,
133 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
134 this.handleRequestGetConfiguration
.bind(this) as IncomingRequestHandler
,
137 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
138 this.handleRequestChangeConfiguration
.bind(this) as unknown
as IncomingRequestHandler
,
141 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
142 this.handleRequestGetCompositeSchedule
.bind(this) as unknown
as IncomingRequestHandler
,
145 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
146 this.handleRequestSetChargingProfile
.bind(this) as unknown
as IncomingRequestHandler
,
149 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
150 this.handleRequestClearChargingProfile
.bind(this) as IncomingRequestHandler
,
153 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
154 this.handleRequestChangeAvailability
.bind(this) as unknown
as IncomingRequestHandler
,
157 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
158 this.handleRequestRemoteStartTransaction
.bind(this) as unknown
as IncomingRequestHandler
,
161 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
162 this.handleRequestRemoteStopTransaction
.bind(this) as unknown
as IncomingRequestHandler
,
165 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
166 this.handleRequestGetDiagnostics
.bind(this) as IncomingRequestHandler
,
169 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
170 this.handleRequestTriggerMessage
.bind(this) as unknown
as IncomingRequestHandler
,
173 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
174 this.handleRequestDataTransfer
.bind(this) as unknown
as IncomingRequestHandler
,
177 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
178 this.handleRequestUpdateFirmware
.bind(this) as unknown
as IncomingRequestHandler
,
181 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
182 this.handleRequestReserveNow
.bind(this) as unknown
as IncomingRequestHandler
,
185 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
186 this.handleRequestCancelReservation
.bind(this) as unknown
as IncomingRequestHandler
,
189 this.jsonSchemas
= new Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonType
>>([
191 OCPP16IncomingRequestCommand
.RESET
,
192 OCPP16ServiceUtils
.parseJsonSchemaFile
<ResetRequest
>(
193 'assets/json-schemas/ocpp/1.6/Reset.json',
199 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
200 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ClearCacheRequest
>(
201 'assets/json-schemas/ocpp/1.6/ClearCache.json',
207 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
208 OCPP16ServiceUtils
.parseJsonSchemaFile
<UnlockConnectorRequest
>(
209 'assets/json-schemas/ocpp/1.6/UnlockConnector.json',
215 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
216 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetConfigurationRequest
>(
217 'assets/json-schemas/ocpp/1.6/GetConfiguration.json',
223 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
224 OCPP16ServiceUtils
.parseJsonSchemaFile
<ChangeConfigurationRequest
>(
225 'assets/json-schemas/ocpp/1.6/ChangeConfiguration.json',
231 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
232 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetDiagnosticsRequest
>(
233 'assets/json-schemas/ocpp/1.6/GetDiagnostics.json',
239 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
240 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16GetCompositeScheduleRequest
>(
241 'assets/json-schemas/ocpp/1.6/GetCompositeSchedule.json',
247 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
248 OCPP16ServiceUtils
.parseJsonSchemaFile
<SetChargingProfileRequest
>(
249 'assets/json-schemas/ocpp/1.6/SetChargingProfile.json',
255 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
256 OCPP16ServiceUtils
.parseJsonSchemaFile
<ClearChargingProfileRequest
>(
257 'assets/json-schemas/ocpp/1.6/ClearChargingProfile.json',
263 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
264 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ChangeAvailabilityRequest
>(
265 'assets/json-schemas/ocpp/1.6/ChangeAvailability.json',
271 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
272 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStartTransactionRequest
>(
273 'assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json',
279 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
280 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStopTransactionRequest
>(
281 'assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json',
287 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
288 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16TriggerMessageRequest
>(
289 'assets/json-schemas/ocpp/1.6/TriggerMessage.json',
295 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
296 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16DataTransferRequest
>(
297 'assets/json-schemas/ocpp/1.6/DataTransfer.json',
303 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
304 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16UpdateFirmwareRequest
>(
305 'assets/json-schemas/ocpp/1.6/UpdateFirmware.json',
311 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
312 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ReserveNowRequest
>(
313 'assets/json-schemas/ocpp/1.6/ReserveNow.json',
319 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
320 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16CancelReservationRequest
>(
321 'assets/json-schemas/ocpp/1.6/CancelReservation.json',
327 this.validatePayload
= this.validatePayload
.bind(this) as (
328 chargingStation
: ChargingStation
,
329 commandName
: OCPP16IncomingRequestCommand
,
330 commandPayload
: JsonType
,
334 public async incomingRequestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
335 chargingStation
: ChargingStation
,
337 commandName
: OCPP16IncomingRequestCommand
,
338 commandPayload
: ReqType
,
340 let response
: ResType
;
342 chargingStation
.stationInfo
?.ocppStrictCompliance
=== true &&
343 chargingStation
.inPendingState() === true &&
344 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
345 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
348 ErrorType
.SECURITY_ERROR
,
349 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
353 )} while the charging station is in pending state on the central server`,
359 chargingStation
.isRegistered() === true ||
360 (chargingStation
.stationInfo
?.ocppStrictCompliance
=== false &&
361 chargingStation
.inUnknownState() === true)
364 this.incomingRequestHandlers
.has(commandName
) === true &&
365 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
) === true
368 this.validatePayload(chargingStation
, commandName
, commandPayload
);
369 // Call the method to build the response
370 response
= (await this.incomingRequestHandlers
.get(commandName
)!(
377 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
385 ErrorType
.NOT_IMPLEMENTED
,
386 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
397 ErrorType
.SECURITY_ERROR
,
398 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
402 )} while the charging station is not registered on the central server.`,
407 // Send the built response
408 await chargingStation
.ocppRequestService
.sendResponse(
416 private validatePayload(
417 chargingStation
: ChargingStation
,
418 commandName
: OCPP16IncomingRequestCommand
,
419 commandPayload
: JsonType
,
421 if (this.jsonSchemas
.has(commandName
) === true) {
422 return this.validateIncomingRequestPayload(
425 this.jsonSchemas
.get(commandName
)!,
430 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command '${commandName}' PDU validation`,
435 // Simulate charging station restart
436 private handleRequestReset(
437 chargingStation
: ChargingStation
,
438 commandPayload
: ResetRequest
,
440 const { type } = commandPayload
;
441 this.runInAsyncScope(
442 chargingStation
.reset
.bind(chargingStation
) as (
443 this: ChargingStation
,
447 `${type}Reset` as OCPP16StopTransactionReason
,
448 ).catch(Constants
.EMPTY_FUNCTION
);
450 `${chargingStation.logPrefix()} ${type} reset command received, simulating it. The station will be back online in ${formatDurationMilliSeconds(
451 chargingStation.stationInfo.resetTime!,
454 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
457 private async handleRequestUnlockConnector(
458 chargingStation
: ChargingStation
,
459 commandPayload
: UnlockConnectorRequest
,
460 ): Promise
<UnlockConnectorResponse
> {
461 const { connectorId
} = commandPayload
;
462 if (chargingStation
.hasConnector(connectorId
) === false) {
464 `${chargingStation.logPrefix()} Trying to unlock a non existing connector id ${connectorId}`,
466 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
468 if (connectorId
=== 0) {
469 logger
.error(`${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId}`);
470 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
472 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
473 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
475 OCPP16StopTransactionReason
.UNLOCK_COMMAND
,
477 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
478 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
;
480 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
482 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
485 OCPP16ChargePointStatus
.Available
,
487 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
;
490 private handleRequestGetConfiguration(
491 chargingStation
: ChargingStation
,
492 commandPayload
: GetConfigurationRequest
,
493 ): GetConfigurationResponse
{
494 const { key
} = commandPayload
;
495 const configurationKey
: OCPPConfigurationKey
[] = [];
496 const unknownKey
: string[] = [];
497 if (isUndefined(key
) === true) {
498 for (const configuration
of chargingStation
.ocppConfiguration
!.configurationKey
!) {
499 if (isUndefined(configuration
.visible
) === true) {
500 configuration
.visible
= true;
502 if (configuration
.visible
=== false) {
505 configurationKey
.push({
506 key
: configuration
.key
,
507 readonly: configuration
.readonly,
508 value
: configuration
.value
,
511 } else if (isNotEmptyArray(key
) === true) {
512 for (const k
of key
!) {
513 const keyFound
= getConfigurationKey(chargingStation
, k
, true);
514 if (keyFound
!== undefined) {
515 if (isUndefined(keyFound
.visible
) === true) {
516 keyFound
.visible
= true;
518 if (keyFound
.visible
=== false) {
521 configurationKey
.push({
523 readonly: keyFound
.readonly,
524 value
: keyFound
.value
,
537 private handleRequestChangeConfiguration(
538 chargingStation
: ChargingStation
,
539 commandPayload
: ChangeConfigurationRequest
,
540 ): ChangeConfigurationResponse
{
541 const { key
, value
} = commandPayload
;
542 const keyToChange
= getConfigurationKey(chargingStation
, key
, true);
543 if (keyToChange
?.readonly === true) {
544 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
545 } else if (keyToChange
?.readonly === false) {
546 let valueChanged
= false;
547 if (keyToChange
.value
!== value
) {
548 setConfigurationKeyValue(chargingStation
, key
, value
, true);
551 let triggerHeartbeatRestart
= false;
553 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
554 OCPP16StandardParametersKey
.HeartBeatInterval
&&
557 setConfigurationKeyValue(
559 OCPP16StandardParametersKey
.HeartbeatInterval
,
562 triggerHeartbeatRestart
= true;
565 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
566 OCPP16StandardParametersKey
.HeartbeatInterval
&&
569 setConfigurationKeyValue(
571 OCPP16StandardParametersKey
.HeartBeatInterval
,
574 triggerHeartbeatRestart
= true;
576 if (triggerHeartbeatRestart
) {
577 chargingStation
.restartHeartbeat();
580 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
581 OCPP16StandardParametersKey
.WebSocketPingInterval
&&
584 chargingStation
.restartWebSocketPing();
586 if (keyToChange
.reboot
) {
587 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
589 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
591 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
594 private handleRequestSetChargingProfile(
595 chargingStation
: ChargingStation
,
596 commandPayload
: SetChargingProfileRequest
,
597 ): SetChargingProfileResponse
{
599 OCPP16ServiceUtils
.checkFeatureProfile(
601 OCPP16SupportedFeatureProfiles
.SmartCharging
,
602 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
605 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
607 const { connectorId
, csChargingProfiles
} = commandPayload
;
608 if (chargingStation
.hasConnector(connectorId
) === false) {
610 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector id ${connectorId}`,
612 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
615 csChargingProfiles
.chargingProfilePurpose
===
616 OCPP16ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
619 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
622 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
626 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId}`,
628 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
630 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
);
632 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
634 connectorStatus
?.transactionStarted
=== false
637 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} without a started transaction`,
639 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
642 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
644 connectorStatus
?.transactionStarted
=== true &&
645 csChargingProfiles
.transactionId
!== connectorStatus
?.transactionId
648 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} with a different transaction id ${
649 csChargingProfiles.transactionId
650 } than the started transaction id ${connectorStatus?.transactionId}`,
652 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
654 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, csChargingProfiles
);
656 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${connectorId}: %j`,
659 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
662 private handleRequestGetCompositeSchedule(
663 chargingStation
: ChargingStation
,
664 commandPayload
: OCPP16GetCompositeScheduleRequest
,
665 ): OCPP16GetCompositeScheduleResponse
{
667 OCPP16ServiceUtils
.checkFeatureProfile(
669 OCPP16SupportedFeatureProfiles
.SmartCharging
,
670 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
673 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
675 const { connectorId
, duration
, chargingRateUnit
} = commandPayload
;
676 if (chargingStation
.hasConnector(connectorId
) === false) {
678 `${chargingStation.logPrefix()} Trying to get composite schedule to a non existing connector id ${connectorId}`,
680 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
682 if (connectorId
=== 0) {
684 `${chargingStation.logPrefix()} Get composite schedule on connector id ${connectorId} is not yet supported`,
686 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
688 if (chargingRateUnit
) {
690 `${chargingStation.logPrefix()} Get composite schedule with a specified rate unit is not yet supported, no conversion will be done`,
693 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)!;
696 connectorStatus
?.chargingProfiles
&&
697 isEmptyArray(chargingStation
.getConnectorStatus(0)?.chargingProfiles
),
700 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
702 const currentDate
= new Date();
703 const compositeScheduleInterval
: Interval
= {
705 end
: addSeconds(currentDate
, duration
),
707 // Get charging profiles sorted by connector id then stack level
708 const chargingProfiles
: OCPP16ChargingProfile
[] = getConnectorChargingProfiles(
712 let previousCompositeSchedule
: OCPP16ChargingSchedule
| undefined;
713 let compositeSchedule
: OCPP16ChargingSchedule
| undefined;
714 for (const chargingProfile
of chargingProfiles
) {
716 isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
) &&
717 connectorStatus
?.transactionStarted
720 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
721 chargingProfile.chargingProfileId
722 } has no startSchedule defined. Trying to set it to the connector current transaction start date`,
724 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
725 chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
;
728 !isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
) &&
729 !isDate(chargingProfile
.chargingSchedule
?.startSchedule
)
732 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
733 chargingProfile.chargingProfileId
734 } startSchedule property is not a Date instance. Trying to convert it to a Date instance`,
736 chargingProfile
.chargingSchedule
.startSchedule
= convertToDate(
737 chargingProfile
.chargingSchedule
?.startSchedule
,
741 !isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
) &&
742 isNullOrUndefined(chargingProfile
.chargingSchedule
?.duration
)
745 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
746 chargingProfile.chargingProfileId
747 } has no duration defined and will be set to the maximum time allowed`,
749 // OCPP specifies that if duration is not defined, it should be infinite
750 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(
752 chargingProfile
.chargingSchedule
.startSchedule
!,
756 !prepareChargingProfileKind(
759 compositeScheduleInterval
.start
as Date,
760 chargingStation
.logPrefix(),
766 !canProceedChargingProfile(
768 compositeScheduleInterval
.start
as Date,
769 chargingStation
.logPrefix(),
774 compositeSchedule
= OCPP16ServiceUtils
.composeChargingSchedules(
775 previousCompositeSchedule
,
776 chargingProfile
.chargingSchedule
,
777 compositeScheduleInterval
,
779 previousCompositeSchedule
= compositeSchedule
;
781 if (compositeSchedule
) {
783 status: GenericStatus
.Accepted
,
784 scheduleStart
: compositeSchedule
.startSchedule
!,
786 chargingSchedule
: compositeSchedule
,
789 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
792 private handleRequestClearChargingProfile(
793 chargingStation
: ChargingStation
,
794 commandPayload
: ClearChargingProfileRequest
,
795 ): ClearChargingProfileResponse
{
797 OCPP16ServiceUtils
.checkFeatureProfile(
799 OCPP16SupportedFeatureProfiles
.SmartCharging
,
800 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
803 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
805 const { connectorId
} = commandPayload
;
806 if (chargingStation
.hasConnector(connectorId
!) === false) {
808 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector id ${connectorId}`,
810 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
812 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
!);
813 if (!isNullOrUndefined(connectorId
) && isNotEmptyArray(connectorStatus
?.chargingProfiles
)) {
814 connectorStatus
!.chargingProfiles
= [];
816 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}`,
818 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
820 if (isNullOrUndefined(connectorId
)) {
821 let clearedCP
= false;
822 if (chargingStation
.hasEvses
) {
823 for (const evseStatus
of chargingStation
.evses
.values()) {
824 for (const status of evseStatus
.connectors
.values()) {
825 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
828 status.chargingProfiles
,
833 for (const id
of chargingStation
.connectors
.keys()) {
834 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
837 chargingStation
.getConnectorStatus(id
)?.chargingProfiles
,
842 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
845 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
848 private async handleRequestChangeAvailability(
849 chargingStation
: ChargingStation
,
850 commandPayload
: OCPP16ChangeAvailabilityRequest
,
851 ): Promise
<OCPP16ChangeAvailabilityResponse
> {
852 const { connectorId
, type } = commandPayload
;
853 if (chargingStation
.hasConnector(connectorId
) === false) {
855 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector id ${connectorId}`,
857 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
859 const chargePointStatus
: OCPP16ChargePointStatus
=
860 type === OCPP16AvailabilityType
.Operative
861 ? OCPP16ChargePointStatus
.Available
862 : OCPP16ChargePointStatus
.Unavailable
;
863 if (connectorId
=== 0) {
864 let response
: OCPP16ChangeAvailabilityResponse
;
865 if (chargingStation
.hasEvses
) {
866 for (const evseStatus
of chargingStation
.evses
.values()) {
867 response
= await OCPP16ServiceUtils
.changeAvailability(
869 [...evseStatus
.connectors
.keys()],
875 response
= await OCPP16ServiceUtils
.changeAvailability(
877 [...chargingStation
.connectors
.keys()],
885 (chargingStation
.isChargingStationAvailable() === true ||
886 (chargingStation
.isChargingStationAvailable() === false &&
887 type === OCPP16AvailabilityType
.Inoperative
))
889 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
890 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type;
891 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
893 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type;
894 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
899 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
901 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
904 private async handleRequestRemoteStartTransaction(
905 chargingStation
: ChargingStation
,
906 commandPayload
: RemoteStartTransactionRequest
,
907 ): Promise
<GenericResponse
> {
908 const { connectorId
: transactionConnectorId
, idTag
, chargingProfile
} = commandPayload
;
909 if (chargingStation
.hasConnector(transactionConnectorId
) === false) {
910 return this.notifyRemoteStartTransactionRejected(
912 transactionConnectorId
,
917 !chargingStation
.isChargingStationAvailable() ||
918 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
920 return this.notifyRemoteStartTransactionRejected(
922 transactionConnectorId
,
926 const remoteStartTransactionLogMsg
= `
927 ${chargingStation.logPrefix()} Transaction remotely STARTED on ${
928 chargingStation.stationInfo.chargingStationId
929 }#${transactionConnectorId} for idTag '${idTag}'`;
930 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
932 transactionConnectorId
,
933 OCPP16ChargePointStatus
.Preparing
,
935 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
)!;
936 // Authorization check required
938 chargingStation
.getAuthorizeRemoteTxRequests() === true &&
939 (await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
941 // Authorization successful, start transaction
944 this.setRemoteStartTransactionChargingProfile(
946 transactionConnectorId
,
948 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
952 connectorStatus
.transactionRemoteStarted
= true;
955 await chargingStation
.ocppRequestService
.requestHandler
<
956 OCPP16StartTransactionRequest
,
957 OCPP16StartTransactionResponse
958 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
959 connectorId
: transactionConnectorId
,
962 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
964 logger
.debug(remoteStartTransactionLogMsg
);
965 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
967 return this.notifyRemoteStartTransactionRejected(
969 transactionConnectorId
,
973 return this.notifyRemoteStartTransactionRejected(
975 transactionConnectorId
,
979 // No authorization check required, start transaction
982 this.setRemoteStartTransactionChargingProfile(
984 transactionConnectorId
,
986 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
990 connectorStatus
.transactionRemoteStarted
= true;
993 await chargingStation
.ocppRequestService
.requestHandler
<
994 OCPP16StartTransactionRequest
,
995 OCPP16StartTransactionResponse
996 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
997 connectorId
: transactionConnectorId
,
1000 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
1002 logger
.debug(remoteStartTransactionLogMsg
);
1003 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
1005 return this.notifyRemoteStartTransactionRejected(
1007 transactionConnectorId
,
1011 return this.notifyRemoteStartTransactionRejected(
1013 transactionConnectorId
,
1018 private async notifyRemoteStartTransactionRejected(
1019 chargingStation
: ChargingStation
,
1020 connectorId
: number,
1022 ): Promise
<GenericResponse
> {
1023 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
);
1024 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Available
) {
1025 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1028 OCPP16ChargePointStatus
.Available
,
1032 `${chargingStation.logPrefix()} Remote starting transaction REJECTED on connector id ${connectorId}, idTag '${idTag}', availability '${connectorStatus?.availability}', status '${connectorStatus?.status}'`,
1034 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
1037 private setRemoteStartTransactionChargingProfile(
1038 chargingStation
: ChargingStation
,
1039 connectorId
: number,
1040 chargingProfile
: OCPP16ChargingProfile
,
1042 if (chargingProfile
?.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
) {
1043 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
);
1045 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}: %j`,
1051 `${chargingStation.logPrefix()} Not allowed to set ${
1052 chargingProfile.chargingProfilePurpose
1053 } charging profile(s) at remote start transaction`,
1058 private async handleRequestRemoteStopTransaction(
1059 chargingStation
: ChargingStation
,
1060 commandPayload
: RemoteStopTransactionRequest
,
1061 ): Promise
<GenericResponse
> {
1062 const { transactionId
} = commandPayload
;
1063 if (chargingStation
.hasEvses
) {
1064 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1066 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1067 if (connectorStatus
.transactionId
=== transactionId
) {
1068 return OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
);
1074 for (const connectorId
of chargingStation
.connectors
.keys()) {
1077 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
1079 return OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
);
1084 `${chargingStation.logPrefix()} Trying to remote stop a non existing transaction with id ${transactionId}`,
1086 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
1089 private handleRequestUpdateFirmware(
1090 chargingStation
: ChargingStation
,
1091 commandPayload
: OCPP16UpdateFirmwareRequest
,
1092 ): OCPP16UpdateFirmwareResponse
{
1094 OCPP16ServiceUtils
.checkFeatureProfile(
1096 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1097 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
1101 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: feature profile not supported`,
1103 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1105 let { retrieveDate
} = commandPayload
;
1106 if (chargingStation
.stationInfo
.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
) {
1108 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: firmware update is already in progress`,
1110 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1112 retrieveDate
= convertToDate(retrieveDate
)!;
1113 const now
= Date.now();
1114 if (retrieveDate
?.getTime() <= now
) {
1115 this.runInAsyncScope(
1116 this.updateFirmwareSimulation
.bind(this) as (
1117 this: OCPP16IncomingRequestService
,
1122 ).catch(Constants
.EMPTY_FUNCTION
);
1126 this.runInAsyncScope(
1127 this.updateFirmwareSimulation
.bind(this) as (
1128 this: OCPP16IncomingRequestService
,
1133 ).catch(Constants
.EMPTY_FUNCTION
);
1135 retrieveDate
?.getTime() - now
,
1138 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1141 private async updateFirmwareSimulation(
1142 chargingStation
: ChargingStation
,
1146 if (checkChargingStation(chargingStation
, chargingStation
.logPrefix()) === false) {
1149 if (chargingStation
.hasEvses
) {
1150 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1152 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1153 if (connectorStatus
?.transactionStarted
=== false) {
1154 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1157 OCPP16ChargePointStatus
.Unavailable
,
1164 for (const connectorId
of chargingStation
.connectors
.keys()) {
1167 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1169 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1172 OCPP16ChargePointStatus
.Unavailable
,
1177 await chargingStation
.ocppRequestService
.requestHandler
<
1178 OCPP16FirmwareStatusNotificationRequest
,
1179 OCPP16FirmwareStatusNotificationResponse
1180 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1181 status: OCPP16FirmwareStatus
.Downloading
,
1183 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
;
1185 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1186 OCPP16FirmwareStatus
.DownloadFailed
1188 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1189 await chargingStation
.ocppRequestService
.requestHandler
<
1190 OCPP16FirmwareStatusNotificationRequest
,
1191 OCPP16FirmwareStatusNotificationResponse
1192 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1193 status: chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
,
1195 chargingStation
.stationInfo
.firmwareStatus
=
1196 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
;
1199 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1200 await chargingStation
.ocppRequestService
.requestHandler
<
1201 OCPP16FirmwareStatusNotificationRequest
,
1202 OCPP16FirmwareStatusNotificationResponse
1203 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1204 status: OCPP16FirmwareStatus
.Downloaded
,
1206 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
;
1207 let wasTransactionsStarted
= false;
1208 let transactionsStarted
: boolean;
1210 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions();
1211 if (runningTransactions
> 0) {
1212 const waitTime
= secondsToMilliseconds(15);
1214 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation: ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1216 )} before continuing firmware update simulation`,
1218 await sleep(waitTime
);
1219 transactionsStarted
= true;
1220 wasTransactionsStarted
= true;
1222 if (chargingStation
.hasEvses
) {
1223 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1225 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1226 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Unavailable
) {
1227 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1230 OCPP16ChargePointStatus
.Unavailable
,
1237 for (const connectorId
of chargingStation
.connectors
.keys()) {
1240 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1241 OCPP16ChargePointStatus
.Unavailable
1243 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1246 OCPP16ChargePointStatus
.Unavailable
,
1251 transactionsStarted
= false;
1253 } while (transactionsStarted
);
1254 !wasTransactionsStarted
&&
1255 (await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
))));
1256 if (checkChargingStation(chargingStation
, chargingStation
.logPrefix()) === false) {
1259 await chargingStation
.ocppRequestService
.requestHandler
<
1260 OCPP16FirmwareStatusNotificationRequest
,
1261 OCPP16FirmwareStatusNotificationResponse
1262 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1263 status: OCPP16FirmwareStatus
.Installing
,
1265 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Installing
;
1267 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1268 OCPP16FirmwareStatus
.InstallationFailed
1270 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1271 await chargingStation
.ocppRequestService
.requestHandler
<
1272 OCPP16FirmwareStatusNotificationRequest
,
1273 OCPP16FirmwareStatusNotificationResponse
1274 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1275 status: chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
,
1277 chargingStation
.stationInfo
.firmwareStatus
=
1278 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
;
1281 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1282 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1283 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
);
1287 private async handleRequestGetDiagnostics(
1288 chargingStation
: ChargingStation
,
1289 commandPayload
: GetDiagnosticsRequest
,
1290 ): Promise
<GetDiagnosticsResponse
> {
1292 OCPP16ServiceUtils
.checkFeatureProfile(
1294 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1295 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1299 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Cannot get diagnostics: feature profile not supported`,
1301 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1303 const { location
} = commandPayload
;
1304 const uri
= new URL(location
);
1305 if (uri
.protocol
.startsWith('ftp:')) {
1306 let ftpClient
: Client
| undefined;
1308 const logFiles
= readdirSync(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'))
1309 .filter((file
) => file
.endsWith('.log'))
1310 .map((file
) => join('./', file
));
1311 const diagnosticsArchive
= `${chargingStation.stationInfo.chargingStationId}_logs.tar.gz`;
1312 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
));
1313 ftpClient
= new Client();
1314 const accessResponse
= await ftpClient
.access({
1316 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1317 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1318 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
}),
1320 let uploadResponse
: FTPResponse
| undefined;
1321 if (accessResponse
.code
=== 220) {
1322 ftpClient
.trackProgress((info
) => {
1324 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1326 } bytes transferred from diagnostics archive ${info.name}`,
1328 chargingStation
.ocppRequestService
1330 OCPP16DiagnosticsStatusNotificationRequest
,
1331 OCPP16DiagnosticsStatusNotificationResponse
1332 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1333 status: OCPP16DiagnosticsStatus
.Uploading
,
1337 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Error while sending '${
1338 OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION
1344 uploadResponse
= await ftpClient
.uploadFrom(
1345 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1346 `${uri.pathname}${diagnosticsArchive}`,
1348 if (uploadResponse
.code
=== 226) {
1349 await chargingStation
.ocppRequestService
.requestHandler
<
1350 OCPP16DiagnosticsStatusNotificationRequest
,
1351 OCPP16DiagnosticsStatusNotificationResponse
1352 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1353 status: OCPP16DiagnosticsStatus
.Uploaded
,
1358 return { fileName
: diagnosticsArchive
};
1360 throw new OCPPError(
1361 ErrorType
.GENERIC_ERROR
,
1362 `Diagnostics transfer failed with error code ${accessResponse.code}${
1363 uploadResponse?.code && `|${uploadResponse?.code}
`
1365 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1368 throw new OCPPError(
1369 ErrorType
.GENERIC_ERROR
,
1370 `Diagnostics transfer failed with error code ${accessResponse.code}${
1371 uploadResponse?.code && `|${uploadResponse?.code}
`
1373 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1376 await chargingStation
.ocppRequestService
.requestHandler
<
1377 OCPP16DiagnosticsStatusNotificationRequest
,
1378 OCPP16DiagnosticsStatusNotificationResponse
1379 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1380 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1385 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1387 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1389 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
},
1394 `${chargingStation.logPrefix()} Unsupported protocol ${
1396 } to transfer the diagnostic logs archive`,
1398 await chargingStation
.ocppRequestService
.requestHandler
<
1399 OCPP16DiagnosticsStatusNotificationRequest
,
1400 OCPP16DiagnosticsStatusNotificationResponse
1401 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1402 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1404 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1408 private handleRequestTriggerMessage(
1409 chargingStation
: ChargingStation
,
1410 commandPayload
: OCPP16TriggerMessageRequest
,
1411 ): OCPP16TriggerMessageResponse
{
1412 const { requestedMessage
, connectorId
} = commandPayload
;
1414 !OCPP16ServiceUtils
.checkFeatureProfile(
1416 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1417 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1419 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1421 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1424 !OCPP16ServiceUtils
.isConnectorIdValid(
1426 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1430 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1433 switch (requestedMessage
) {
1434 case OCPP16MessageTrigger
.BootNotification
:
1436 chargingStation
.ocppRequestService
1437 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1439 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1440 chargingStation
.bootNotificationRequest
,
1441 { skipBufferingOnError
: true, triggerMessage
: true },
1443 .then((response
) => {
1444 chargingStation
.bootNotificationResponse
= response
;
1446 .catch(Constants
.EMPTY_FUNCTION
);
1447 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1448 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1449 case OCPP16MessageTrigger
.Heartbeat
:
1451 chargingStation
.ocppRequestService
1452 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1454 OCPP16RequestCommand
.HEARTBEAT
,
1457 triggerMessage
: true,
1460 .catch(Constants
.EMPTY_FUNCTION
);
1461 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1462 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1463 case OCPP16MessageTrigger
.StatusNotification
:
1465 if (!isNullOrUndefined(connectorId
)) {
1466 chargingStation
.ocppRequestService
1467 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1469 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1472 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1473 status: chargingStation
.getConnectorStatus(connectorId
!)?.status,
1476 triggerMessage
: true,
1479 .catch(Constants
.EMPTY_FUNCTION
);
1481 // eslint-disable-next-line no-lonely-if
1482 if (chargingStation
.hasEvses
) {
1483 for (const evseStatus
of chargingStation
.evses
.values()) {
1484 for (const [id
, connectorStatus
] of evseStatus
.connectors
) {
1485 chargingStation
.ocppRequestService
1487 OCPP16StatusNotificationRequest
,
1488 OCPP16StatusNotificationResponse
1491 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1494 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1495 status: connectorStatus
.status,
1498 triggerMessage
: true,
1501 .catch(Constants
.EMPTY_FUNCTION
);
1505 for (const id
of chargingStation
.connectors
.keys()) {
1506 chargingStation
.ocppRequestService
1508 OCPP16StatusNotificationRequest
,
1509 OCPP16StatusNotificationResponse
1512 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1515 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1516 status: chargingStation
.getConnectorStatus(id
)?.status,
1519 triggerMessage
: true,
1522 .catch(Constants
.EMPTY_FUNCTION
);
1526 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1527 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1529 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1532 return this.handleIncomingRequestError
<OCPP16TriggerMessageResponse
>(
1534 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1536 { errorResponse
: OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
},
1541 private handleRequestDataTransfer(
1542 chargingStation
: ChargingStation
,
1543 commandPayload
: OCPP16DataTransferRequest
,
1544 ): OCPP16DataTransferResponse
{
1545 const { vendorId
} = commandPayload
;
1547 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1548 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
;
1550 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
;
1552 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1554 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1556 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
},
1561 private async handleRequestReserveNow(
1562 chargingStation
: ChargingStation
,
1563 commandPayload
: OCPP16ReserveNowRequest
,
1564 ): Promise
<OCPP16ReserveNowResponse
> {
1566 !OCPP16ServiceUtils
.checkFeatureProfile(
1568 OCPP16SupportedFeatureProfiles
.Reservation
,
1569 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1572 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1574 const { reservationId
, idTag
, connectorId
} = commandPayload
;
1575 let response
: OCPP16ReserveNowResponse
;
1577 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1578 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1580 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1581 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1583 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1584 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1586 await removeExpiredReservations(chargingStation
);
1587 switch (chargingStation
.getConnectorStatus(connectorId
)!.status) {
1588 case OCPP16ChargePointStatus
.Faulted
:
1589 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
;
1591 case OCPP16ChargePointStatus
.Preparing
:
1592 case OCPP16ChargePointStatus
.Charging
:
1593 case OCPP16ChargePointStatus
.SuspendedEV
:
1594 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1595 case OCPP16ChargePointStatus
.Finishing
:
1596 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1598 case OCPP16ChargePointStatus
.Unavailable
:
1599 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
;
1601 case OCPP16ChargePointStatus
.Reserved
:
1602 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1603 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1606 // eslint-disable-next-line no-fallthrough
1608 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1609 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1612 await chargingStation
.addReservation({
1613 id
: commandPayload
.reservationId
,
1616 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
;
1621 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
;
1622 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1624 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1626 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
},
1631 private async handleRequestCancelReservation(
1632 chargingStation
: ChargingStation
,
1633 commandPayload
: OCPP16CancelReservationRequest
,
1634 ): Promise
<GenericResponse
> {
1636 !OCPP16ServiceUtils
.checkFeatureProfile(
1638 OCPP16SupportedFeatureProfiles
.Reservation
,
1639 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1642 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
;
1645 const { reservationId
} = commandPayload
;
1646 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
);
1647 if (isUndefined(reservation
)) {
1649 `${chargingStation.logPrefix()} Reservation with id ${reservationId} does not exist on charging station`,
1651 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
;
1653 await chargingStation
.removeReservation(
1655 ReservationTerminationReason
.RESERVATION_CANCELED
,
1657 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
;
1659 return this.handleIncomingRequestError
<GenericResponse
>(
1661 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1663 { errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
},