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
,
26 getConnectorChargingProfiles
,
27 prepareChargingProfileKind
,
28 removeExpiredReservations
,
29 setConfigurationKeyValue
,
30 } from
'../../../charging-station';
31 import { OCPPError
} from
'../../../exception';
33 type ChangeConfigurationRequest
,
34 type ChangeConfigurationResponse
,
35 type ClearChargingProfileRequest
,
36 type ClearChargingProfileResponse
,
40 type GetConfigurationRequest
,
41 type GetConfigurationResponse
,
42 type GetDiagnosticsRequest
,
43 type GetDiagnosticsResponse
,
44 type IncomingRequestHandler
,
46 OCPP16AuthorizationStatus
,
47 OCPP16AvailabilityType
,
48 type OCPP16BootNotificationRequest
,
49 type OCPP16BootNotificationResponse
,
50 type OCPP16CancelReservationRequest
,
51 type OCPP16ChangeAvailabilityRequest
,
52 type OCPP16ChangeAvailabilityResponse
,
53 OCPP16ChargePointErrorCode
,
54 OCPP16ChargePointStatus
,
55 type OCPP16ChargingProfile
,
56 OCPP16ChargingProfilePurposeType
,
57 type OCPP16ChargingSchedule
,
58 type OCPP16ClearCacheRequest
,
59 type OCPP16DataTransferRequest
,
60 type OCPP16DataTransferResponse
,
61 OCPP16DataTransferVendorId
,
62 OCPP16DiagnosticsStatus
,
63 type OCPP16DiagnosticsStatusNotificationRequest
,
64 type OCPP16DiagnosticsStatusNotificationResponse
,
66 type OCPP16FirmwareStatusNotificationRequest
,
67 type OCPP16FirmwareStatusNotificationResponse
,
68 type OCPP16GetCompositeScheduleRequest
,
69 type OCPP16GetCompositeScheduleResponse
,
70 type OCPP16HeartbeatRequest
,
71 type OCPP16HeartbeatResponse
,
72 OCPP16IncomingRequestCommand
,
75 type OCPP16ReserveNowRequest
,
76 type OCPP16ReserveNowResponse
,
77 OCPP16StandardParametersKey
,
78 type OCPP16StartTransactionRequest
,
79 type OCPP16StartTransactionResponse
,
80 type OCPP16StatusNotificationRequest
,
81 type OCPP16StatusNotificationResponse
,
82 OCPP16StopTransactionReason
,
83 OCPP16SupportedFeatureProfiles
,
84 type OCPP16TriggerMessageRequest
,
85 type OCPP16TriggerMessageResponse
,
86 type OCPP16UpdateFirmwareRequest
,
87 type OCPP16UpdateFirmwareResponse
,
88 type OCPPConfigurationKey
,
90 type RemoteStartTransactionRequest
,
91 type RemoteStopTransactionRequest
,
92 ReservationTerminationReason
,
94 type SetChargingProfileRequest
,
95 type SetChargingProfileResponse
,
96 type UnlockConnectorRequest
,
97 type UnlockConnectorResponse
,
98 } from
'../../../types';
103 formatDurationMilliSeconds
,
112 } from
'../../../utils';
113 import { OCPPIncomingRequestService
} from
'../OCPPIncomingRequestService';
115 const moduleName
= 'OCPP16IncomingRequestService';
117 export class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
118 protected jsonSchemas
: Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonType
>>;
119 private incomingRequestHandlers
: Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>;
121 public constructor() {
122 // if (new.target?.name === moduleName) {
123 // throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
125 super(OCPPVersion
.VERSION_16
);
126 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
128 OCPP16IncomingRequestCommand
.RESET
,
129 this.handleRequestReset
.bind(this) as unknown
as IncomingRequestHandler
,
132 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
133 this.handleRequestClearCache
.bind(this) as IncomingRequestHandler
,
136 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
137 this.handleRequestUnlockConnector
.bind(this) as unknown
as IncomingRequestHandler
,
140 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
141 this.handleRequestGetConfiguration
.bind(this) as IncomingRequestHandler
,
144 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
145 this.handleRequestChangeConfiguration
.bind(this) as unknown
as IncomingRequestHandler
,
148 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
149 this.handleRequestGetCompositeSchedule
.bind(this) as unknown
as IncomingRequestHandler
,
152 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
153 this.handleRequestSetChargingProfile
.bind(this) as unknown
as IncomingRequestHandler
,
156 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
157 this.handleRequestClearChargingProfile
.bind(this) as IncomingRequestHandler
,
160 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
161 this.handleRequestChangeAvailability
.bind(this) as unknown
as IncomingRequestHandler
,
164 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
165 this.handleRequestRemoteStartTransaction
.bind(this) as unknown
as IncomingRequestHandler
,
168 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
169 this.handleRequestRemoteStopTransaction
.bind(this) as unknown
as IncomingRequestHandler
,
172 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
173 this.handleRequestGetDiagnostics
.bind(this) as IncomingRequestHandler
,
176 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
177 this.handleRequestTriggerMessage
.bind(this) as unknown
as IncomingRequestHandler
,
180 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
181 this.handleRequestDataTransfer
.bind(this) as unknown
as IncomingRequestHandler
,
184 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
185 this.handleRequestUpdateFirmware
.bind(this) as unknown
as IncomingRequestHandler
,
188 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
189 this.handleRequestReserveNow
.bind(this) as unknown
as IncomingRequestHandler
,
192 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
193 this.handleRequestCancelReservation
.bind(this) as unknown
as IncomingRequestHandler
,
196 this.jsonSchemas
= new Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonType
>>([
198 OCPP16IncomingRequestCommand
.RESET
,
199 OCPP16ServiceUtils
.parseJsonSchemaFile
<ResetRequest
>(
200 'assets/json-schemas/ocpp/1.6/Reset.json',
206 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
207 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ClearCacheRequest
>(
208 'assets/json-schemas/ocpp/1.6/ClearCache.json',
214 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
215 OCPP16ServiceUtils
.parseJsonSchemaFile
<UnlockConnectorRequest
>(
216 'assets/json-schemas/ocpp/1.6/UnlockConnector.json',
222 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
223 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetConfigurationRequest
>(
224 'assets/json-schemas/ocpp/1.6/GetConfiguration.json',
230 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
231 OCPP16ServiceUtils
.parseJsonSchemaFile
<ChangeConfigurationRequest
>(
232 'assets/json-schemas/ocpp/1.6/ChangeConfiguration.json',
238 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
239 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetDiagnosticsRequest
>(
240 'assets/json-schemas/ocpp/1.6/GetDiagnostics.json',
246 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
247 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16GetCompositeScheduleRequest
>(
248 'assets/json-schemas/ocpp/1.6/GetCompositeSchedule.json',
254 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
255 OCPP16ServiceUtils
.parseJsonSchemaFile
<SetChargingProfileRequest
>(
256 'assets/json-schemas/ocpp/1.6/SetChargingProfile.json',
262 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
263 OCPP16ServiceUtils
.parseJsonSchemaFile
<ClearChargingProfileRequest
>(
264 'assets/json-schemas/ocpp/1.6/ClearChargingProfile.json',
270 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
271 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ChangeAvailabilityRequest
>(
272 'assets/json-schemas/ocpp/1.6/ChangeAvailability.json',
278 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
279 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStartTransactionRequest
>(
280 'assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json',
286 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
287 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStopTransactionRequest
>(
288 'assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json',
294 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
295 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16TriggerMessageRequest
>(
296 'assets/json-schemas/ocpp/1.6/TriggerMessage.json',
302 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
303 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16DataTransferRequest
>(
304 'assets/json-schemas/ocpp/1.6/DataTransfer.json',
310 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
311 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16UpdateFirmwareRequest
>(
312 'assets/json-schemas/ocpp/1.6/UpdateFirmware.json',
318 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
319 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ReserveNowRequest
>(
320 'assets/json-schemas/ocpp/1.6/ReserveNow.json',
326 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
327 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16CancelReservationRequest
>(
328 'assets/json-schemas/ocpp/1.6/CancelReservation.json',
334 this.validatePayload
= this.validatePayload
.bind(this) as (
335 chargingStation
: ChargingStation
,
336 commandName
: OCPP16IncomingRequestCommand
,
337 commandPayload
: JsonType
,
341 public async incomingRequestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
342 chargingStation
: ChargingStation
,
344 commandName
: OCPP16IncomingRequestCommand
,
345 commandPayload
: ReqType
,
347 let response
: ResType
;
349 chargingStation
.stationInfo
?.ocppStrictCompliance
=== true &&
350 chargingStation
.inPendingState() === true &&
351 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
352 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
355 ErrorType
.SECURITY_ERROR
,
356 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
360 )} while the charging station is in pending state on the central server`,
366 chargingStation
.isRegistered() === true ||
367 (chargingStation
.stationInfo
?.ocppStrictCompliance
=== false &&
368 chargingStation
.inUnknownState() === true)
371 this.incomingRequestHandlers
.has(commandName
) === true &&
372 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
) === true
375 this.validatePayload(chargingStation
, commandName
, commandPayload
);
376 // Call the method to build the response
377 response
= (await this.incomingRequestHandlers
.get(commandName
)!(
384 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
392 ErrorType
.NOT_IMPLEMENTED
,
393 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
404 ErrorType
.SECURITY_ERROR
,
405 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
409 )} while the charging station is not registered on the central server.`,
414 // Send the built response
415 await chargingStation
.ocppRequestService
.sendResponse(
423 private validatePayload(
424 chargingStation
: ChargingStation
,
425 commandName
: OCPP16IncomingRequestCommand
,
426 commandPayload
: JsonType
,
428 if (this.jsonSchemas
.has(commandName
) === true) {
429 return this.validateIncomingRequestPayload(
432 this.jsonSchemas
.get(commandName
)!,
437 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command '${commandName}' PDU validation`,
442 // Simulate charging station restart
443 private handleRequestReset(
444 chargingStation
: ChargingStation
,
445 commandPayload
: ResetRequest
,
447 const { type } = commandPayload
;
448 this.runInAsyncScope(
449 chargingStation
.reset
.bind(chargingStation
) as (
450 this: ChargingStation
,
454 `${type}Reset` as OCPP16StopTransactionReason
,
455 ).catch(Constants
.EMPTY_FUNCTION
);
457 `${chargingStation.logPrefix()} ${type} reset command received, simulating it. The station will be back online in ${formatDurationMilliSeconds(
458 chargingStation.stationInfo.resetTime!,
461 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
464 private async handleRequestUnlockConnector(
465 chargingStation
: ChargingStation
,
466 commandPayload
: UnlockConnectorRequest
,
467 ): Promise
<UnlockConnectorResponse
> {
468 const { connectorId
} = commandPayload
;
469 if (chargingStation
.hasConnector(connectorId
) === false) {
471 `${chargingStation.logPrefix()} Trying to unlock a non existing connector id ${connectorId}`,
473 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
475 if (connectorId
=== 0) {
476 logger
.error(`${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId}`);
477 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
479 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
480 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
482 OCPP16StopTransactionReason
.UNLOCK_COMMAND
,
484 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
485 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
;
487 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
489 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
492 OCPP16ChargePointStatus
.Available
,
494 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
;
497 private handleRequestGetConfiguration(
498 chargingStation
: ChargingStation
,
499 commandPayload
: GetConfigurationRequest
,
500 ): GetConfigurationResponse
{
501 const { key
} = commandPayload
;
502 const configurationKey
: OCPPConfigurationKey
[] = [];
503 const unknownKey
: string[] = [];
504 if (isUndefined(key
) === true) {
505 for (const configuration
of chargingStation
.ocppConfiguration
!.configurationKey
!) {
506 if (isUndefined(configuration
.visible
) === true) {
507 configuration
.visible
= true;
509 if (configuration
.visible
=== false) {
512 configurationKey
.push({
513 key
: configuration
.key
,
514 readonly: configuration
.readonly,
515 value
: configuration
.value
,
518 } else if (isNotEmptyArray(key
) === true) {
519 for (const k
of key
!) {
520 const keyFound
= getConfigurationKey(chargingStation
, k
, true);
521 if (keyFound
!== undefined) {
522 if (isUndefined(keyFound
.visible
) === true) {
523 keyFound
.visible
= true;
525 if (keyFound
.visible
=== false) {
528 configurationKey
.push({
530 readonly: keyFound
.readonly,
531 value
: keyFound
.value
,
544 private handleRequestChangeConfiguration(
545 chargingStation
: ChargingStation
,
546 commandPayload
: ChangeConfigurationRequest
,
547 ): ChangeConfigurationResponse
{
548 const { key
, value
} = commandPayload
;
549 const keyToChange
= getConfigurationKey(chargingStation
, key
, true);
550 if (keyToChange
?.readonly === true) {
551 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
552 } else if (keyToChange
?.readonly === false) {
553 let valueChanged
= false;
554 if (keyToChange
.value
!== value
) {
555 setConfigurationKeyValue(chargingStation
, key
, value
, true);
558 let triggerHeartbeatRestart
= false;
560 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
561 OCPP16StandardParametersKey
.HeartBeatInterval
&&
564 setConfigurationKeyValue(
566 OCPP16StandardParametersKey
.HeartbeatInterval
,
569 triggerHeartbeatRestart
= true;
572 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
573 OCPP16StandardParametersKey
.HeartbeatInterval
&&
576 setConfigurationKeyValue(
578 OCPP16StandardParametersKey
.HeartBeatInterval
,
581 triggerHeartbeatRestart
= true;
583 if (triggerHeartbeatRestart
) {
584 chargingStation
.restartHeartbeat();
587 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
588 OCPP16StandardParametersKey
.WebSocketPingInterval
&&
591 chargingStation
.restartWebSocketPing();
593 if (keyToChange
.reboot
) {
594 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
596 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
598 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
601 private handleRequestSetChargingProfile(
602 chargingStation
: ChargingStation
,
603 commandPayload
: SetChargingProfileRequest
,
604 ): SetChargingProfileResponse
{
606 OCPP16ServiceUtils
.checkFeatureProfile(
608 OCPP16SupportedFeatureProfiles
.SmartCharging
,
609 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
612 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
614 const { connectorId
, csChargingProfiles
} = commandPayload
;
615 if (chargingStation
.hasConnector(connectorId
) === false) {
617 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector id ${connectorId}`,
619 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
622 csChargingProfiles
.chargingProfilePurpose
===
623 OCPP16ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
626 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
629 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
633 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId}`,
635 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
637 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
);
639 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
641 connectorStatus
?.transactionStarted
=== false
644 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} without a started transaction`,
646 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
649 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
651 connectorStatus
?.transactionStarted
=== true &&
652 csChargingProfiles
.transactionId
!== connectorStatus
?.transactionId
655 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) on connector ${connectorId} with a different transaction id ${
656 csChargingProfiles.transactionId
657 } than the started transaction id ${connectorStatus?.transactionId}`,
659 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
661 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, csChargingProfiles
);
663 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${connectorId}: %j`,
666 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
669 private handleRequestGetCompositeSchedule(
670 chargingStation
: ChargingStation
,
671 commandPayload
: OCPP16GetCompositeScheduleRequest
,
672 ): OCPP16GetCompositeScheduleResponse
{
674 OCPP16ServiceUtils
.checkFeatureProfile(
676 OCPP16SupportedFeatureProfiles
.SmartCharging
,
677 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
680 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
682 const { connectorId
, duration
, chargingRateUnit
} = commandPayload
;
683 if (chargingStation
.hasConnector(connectorId
) === false) {
685 `${chargingStation.logPrefix()} Trying to get composite schedule to a non existing connector id ${connectorId}`,
687 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
689 if (connectorId
=== 0) {
691 `${chargingStation.logPrefix()} Get composite schedule on connector id ${connectorId} is not yet supported`,
693 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
695 if (chargingRateUnit
) {
697 `${chargingStation.logPrefix()} Get composite schedule with a specified rate unit is not yet supported, no conversion will be done`,
700 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)!;
703 connectorStatus
?.chargingProfiles
&&
704 isEmptyArray(chargingStation
.getConnectorStatus(0)?.chargingProfiles
),
707 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
709 const currentDate
= new Date();
710 const compositeScheduleInterval
: Interval
= {
712 end
: addSeconds(currentDate
, duration
),
714 // Get charging profiles sorted by connector id then stack level
715 const chargingProfiles
: OCPP16ChargingProfile
[] = getConnectorChargingProfiles(
719 let previousCompositeSchedule
: OCPP16ChargingSchedule
| undefined;
720 let compositeSchedule
: OCPP16ChargingSchedule
| undefined;
721 for (const chargingProfile
of chargingProfiles
) {
723 isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
) &&
724 connectorStatus
?.transactionStarted
727 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
728 chargingProfile.chargingProfileId
729 } has no startSchedule defined. Trying to set it to the connector current transaction start date`,
731 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
732 chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
;
735 !isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
) &&
736 !isDate(chargingProfile
.chargingSchedule
?.startSchedule
)
739 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
740 chargingProfile.chargingProfileId
741 } startSchedule property is not a Date instance. Trying to convert it to a Date instance`,
743 chargingProfile
.chargingSchedule
.startSchedule
= convertToDate(
744 chargingProfile
.chargingSchedule
?.startSchedule
,
748 !isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
) &&
749 isNullOrUndefined(chargingProfile
.chargingSchedule
?.duration
)
752 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
753 chargingProfile.chargingProfileId
754 } has no duration defined and will be set to the maximum time allowed`,
756 // OCPP specifies that if duration is not defined, it should be infinite
757 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(
759 chargingProfile
.chargingSchedule
.startSchedule
!,
763 !prepareChargingProfileKind(
766 compositeScheduleInterval
.start
as Date,
767 chargingStation
.logPrefix(),
773 !canProceedChargingProfile(
775 compositeScheduleInterval
.start
as Date,
776 chargingStation
.logPrefix(),
781 compositeSchedule
= OCPP16ServiceUtils
.composeChargingSchedules(
782 previousCompositeSchedule
,
783 chargingProfile
.chargingSchedule
,
784 compositeScheduleInterval
,
786 previousCompositeSchedule
= compositeSchedule
;
788 if (compositeSchedule
) {
790 status: GenericStatus
.Accepted
,
791 scheduleStart
: compositeSchedule
.startSchedule
!,
793 chargingSchedule
: compositeSchedule
,
796 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
799 private handleRequestClearChargingProfile(
800 chargingStation
: ChargingStation
,
801 commandPayload
: ClearChargingProfileRequest
,
802 ): ClearChargingProfileResponse
{
804 OCPP16ServiceUtils
.checkFeatureProfile(
806 OCPP16SupportedFeatureProfiles
.SmartCharging
,
807 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
810 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
812 const { connectorId
} = commandPayload
;
813 if (chargingStation
.hasConnector(connectorId
!) === false) {
815 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector id ${connectorId}`,
817 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
819 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
!);
820 if (!isNullOrUndefined(connectorId
) && isNotEmptyArray(connectorStatus
?.chargingProfiles
)) {
821 connectorStatus
!.chargingProfiles
= [];
823 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}`,
825 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
827 if (isNullOrUndefined(connectorId
)) {
828 let clearedCP
= false;
829 if (chargingStation
.hasEvses
) {
830 for (const evseStatus
of chargingStation
.evses
.values()) {
831 for (const status of evseStatus
.connectors
.values()) {
832 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
835 status.chargingProfiles
,
840 for (const id
of chargingStation
.connectors
.keys()) {
841 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
844 chargingStation
.getConnectorStatus(id
)?.chargingProfiles
,
849 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
852 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
855 private async handleRequestChangeAvailability(
856 chargingStation
: ChargingStation
,
857 commandPayload
: OCPP16ChangeAvailabilityRequest
,
858 ): Promise
<OCPP16ChangeAvailabilityResponse
> {
859 const { connectorId
, type } = commandPayload
;
860 if (chargingStation
.hasConnector(connectorId
) === false) {
862 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector id ${connectorId}`,
864 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
866 const chargePointStatus
: OCPP16ChargePointStatus
=
867 type === OCPP16AvailabilityType
.Operative
868 ? OCPP16ChargePointStatus
.Available
869 : OCPP16ChargePointStatus
.Unavailable
;
870 if (connectorId
=== 0) {
871 let response
: OCPP16ChangeAvailabilityResponse
;
872 if (chargingStation
.hasEvses
) {
873 for (const evseStatus
of chargingStation
.evses
.values()) {
874 response
= await OCPP16ServiceUtils
.changeAvailability(
876 [...evseStatus
.connectors
.keys()],
882 response
= await OCPP16ServiceUtils
.changeAvailability(
884 [...chargingStation
.connectors
.keys()],
892 (chargingStation
.isChargingStationAvailable() === true ||
893 (chargingStation
.isChargingStationAvailable() === false &&
894 type === OCPP16AvailabilityType
.Inoperative
))
896 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
897 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type;
898 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
900 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type;
901 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
906 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
908 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
911 private async handleRequestRemoteStartTransaction(
912 chargingStation
: ChargingStation
,
913 commandPayload
: RemoteStartTransactionRequest
,
914 ): Promise
<GenericResponse
> {
915 const { connectorId
: transactionConnectorId
, idTag
, chargingProfile
} = commandPayload
;
916 if (chargingStation
.hasConnector(transactionConnectorId
) === false) {
917 return this.notifyRemoteStartTransactionRejected(
919 transactionConnectorId
,
924 !chargingStation
.isChargingStationAvailable() ||
925 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
927 return this.notifyRemoteStartTransactionRejected(
929 transactionConnectorId
,
933 const remoteStartTransactionLogMsg
= `
934 ${chargingStation.logPrefix()} Transaction remotely STARTED on ${
935 chargingStation.stationInfo.chargingStationId
936 }#${transactionConnectorId} for idTag '${idTag}'`;
937 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
939 transactionConnectorId
,
940 OCPP16ChargePointStatus
.Preparing
,
942 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
)!;
943 // Authorization check required
945 chargingStation
.getAuthorizeRemoteTxRequests() === true &&
946 (await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
948 // Authorization successful, start transaction
951 this.setRemoteStartTransactionChargingProfile(
953 transactionConnectorId
,
955 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
959 connectorStatus
.transactionRemoteStarted
= true;
962 await chargingStation
.ocppRequestService
.requestHandler
<
963 OCPP16StartTransactionRequest
,
964 OCPP16StartTransactionResponse
965 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
966 connectorId
: transactionConnectorId
,
969 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
971 logger
.debug(remoteStartTransactionLogMsg
);
972 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
974 return this.notifyRemoteStartTransactionRejected(
976 transactionConnectorId
,
980 return this.notifyRemoteStartTransactionRejected(
982 transactionConnectorId
,
986 // No authorization check required, start transaction
989 this.setRemoteStartTransactionChargingProfile(
991 transactionConnectorId
,
993 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
997 connectorStatus
.transactionRemoteStarted
= true;
1000 await chargingStation
.ocppRequestService
.requestHandler
<
1001 OCPP16StartTransactionRequest
,
1002 OCPP16StartTransactionResponse
1003 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
1004 connectorId
: transactionConnectorId
,
1007 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
1009 logger
.debug(remoteStartTransactionLogMsg
);
1010 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
1012 return this.notifyRemoteStartTransactionRejected(
1014 transactionConnectorId
,
1018 return this.notifyRemoteStartTransactionRejected(
1020 transactionConnectorId
,
1025 private async notifyRemoteStartTransactionRejected(
1026 chargingStation
: ChargingStation
,
1027 connectorId
: number,
1029 ): Promise
<GenericResponse
> {
1030 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
);
1031 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Available
) {
1032 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1035 OCPP16ChargePointStatus
.Available
,
1039 `${chargingStation.logPrefix()} Remote starting transaction REJECTED on connector id ${connectorId}, idTag '${idTag}', availability '${connectorStatus?.availability}', status '${connectorStatus?.status}'`,
1041 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
1044 private setRemoteStartTransactionChargingProfile(
1045 chargingStation
: ChargingStation
,
1046 connectorId
: number,
1047 chargingProfile
: OCPP16ChargingProfile
,
1049 if (chargingProfile
?.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
) {
1050 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
);
1052 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}: %j`,
1058 `${chargingStation.logPrefix()} Not allowed to set ${
1059 chargingProfile.chargingProfilePurpose
1060 } charging profile(s) at remote start transaction`,
1065 private async handleRequestRemoteStopTransaction(
1066 chargingStation
: ChargingStation
,
1067 commandPayload
: RemoteStopTransactionRequest
,
1068 ): Promise
<GenericResponse
> {
1069 const { transactionId
} = commandPayload
;
1070 if (chargingStation
.hasEvses
) {
1071 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1073 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1074 if (connectorStatus
.transactionId
=== transactionId
) {
1075 return OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
);
1081 for (const connectorId
of chargingStation
.connectors
.keys()) {
1084 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
1086 return OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
);
1091 `${chargingStation.logPrefix()} Trying to remote stop a non existing transaction with id ${transactionId}`,
1093 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
1096 private handleRequestUpdateFirmware(
1097 chargingStation
: ChargingStation
,
1098 commandPayload
: OCPP16UpdateFirmwareRequest
,
1099 ): OCPP16UpdateFirmwareResponse
{
1101 OCPP16ServiceUtils
.checkFeatureProfile(
1103 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1104 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
1108 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: feature profile not supported`,
1110 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1112 let { retrieveDate
} = commandPayload
;
1114 !isNullOrUndefined(chargingStation
.stationInfo
.firmwareStatus
) &&
1115 chargingStation
.stationInfo
.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
1118 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: Cannot simulate firmware update: firmware update is already in progress`,
1120 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1122 retrieveDate
= convertToDate(retrieveDate
)!;
1123 const now
= Date.now();
1124 if (retrieveDate
?.getTime() <= now
) {
1125 this.runInAsyncScope(
1126 this.updateFirmwareSimulation
.bind(this) as (
1127 this: OCPP16IncomingRequestService
,
1132 ).catch(Constants
.EMPTY_FUNCTION
);
1136 this.runInAsyncScope(
1137 this.updateFirmwareSimulation
.bind(this) as (
1138 this: OCPP16IncomingRequestService
,
1143 ).catch(Constants
.EMPTY_FUNCTION
);
1145 retrieveDate
?.getTime() - now
,
1148 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1151 private async updateFirmwareSimulation(
1152 chargingStation
: ChargingStation
,
1156 if (checkChargingStation(chargingStation
, chargingStation
.logPrefix()) === false) {
1159 if (chargingStation
.hasEvses
) {
1160 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1162 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1163 if (connectorStatus
?.transactionStarted
=== false) {
1164 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1167 OCPP16ChargePointStatus
.Unavailable
,
1174 for (const connectorId
of chargingStation
.connectors
.keys()) {
1177 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1179 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1182 OCPP16ChargePointStatus
.Unavailable
,
1187 await chargingStation
.ocppRequestService
.requestHandler
<
1188 OCPP16FirmwareStatusNotificationRequest
,
1189 OCPP16FirmwareStatusNotificationResponse
1190 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1191 status: OCPP16FirmwareStatus
.Downloading
,
1193 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
;
1195 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1196 OCPP16FirmwareStatus
.DownloadFailed
1198 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1199 await chargingStation
.ocppRequestService
.requestHandler
<
1200 OCPP16FirmwareStatusNotificationRequest
,
1201 OCPP16FirmwareStatusNotificationResponse
1202 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1203 status: chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
,
1205 chargingStation
.stationInfo
.firmwareStatus
=
1206 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
;
1209 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1210 await chargingStation
.ocppRequestService
.requestHandler
<
1211 OCPP16FirmwareStatusNotificationRequest
,
1212 OCPP16FirmwareStatusNotificationResponse
1213 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1214 status: OCPP16FirmwareStatus
.Downloaded
,
1216 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
;
1217 let wasTransactionsStarted
= false;
1218 let transactionsStarted
: boolean;
1220 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions();
1221 if (runningTransactions
> 0) {
1222 const waitTime
= secondsToMilliseconds(15);
1224 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation: ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1226 )} before continuing firmware update simulation`,
1228 await sleep(waitTime
);
1229 transactionsStarted
= true;
1230 wasTransactionsStarted
= true;
1232 if (chargingStation
.hasEvses
) {
1233 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1235 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1236 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Unavailable
) {
1237 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1240 OCPP16ChargePointStatus
.Unavailable
,
1247 for (const connectorId
of chargingStation
.connectors
.keys()) {
1250 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1251 OCPP16ChargePointStatus
.Unavailable
1253 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1256 OCPP16ChargePointStatus
.Unavailable
,
1261 transactionsStarted
= false;
1263 } while (transactionsStarted
);
1264 !wasTransactionsStarted
&&
1265 (await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
))));
1266 if (checkChargingStation(chargingStation
, chargingStation
.logPrefix()) === false) {
1269 await chargingStation
.ocppRequestService
.requestHandler
<
1270 OCPP16FirmwareStatusNotificationRequest
,
1271 OCPP16FirmwareStatusNotificationResponse
1272 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1273 status: OCPP16FirmwareStatus
.Installing
,
1275 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Installing
;
1277 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1278 OCPP16FirmwareStatus
.InstallationFailed
1280 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1281 await chargingStation
.ocppRequestService
.requestHandler
<
1282 OCPP16FirmwareStatusNotificationRequest
,
1283 OCPP16FirmwareStatusNotificationResponse
1284 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1285 status: chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
,
1287 chargingStation
.stationInfo
.firmwareStatus
=
1288 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
;
1291 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1292 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1293 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
);
1297 private async handleRequestGetDiagnostics(
1298 chargingStation
: ChargingStation
,
1299 commandPayload
: GetDiagnosticsRequest
,
1300 ): Promise
<GetDiagnosticsResponse
> {
1302 OCPP16ServiceUtils
.checkFeatureProfile(
1304 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1305 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1309 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Cannot get diagnostics: feature profile not supported`,
1311 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1313 const { location
} = commandPayload
;
1314 const uri
= new URL(location
);
1315 if (uri
.protocol
.startsWith('ftp:')) {
1316 let ftpClient
: Client
| undefined;
1318 const logFiles
= readdirSync(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'))
1319 .filter((file
) => file
.endsWith('.log'))
1320 .map((file
) => join('./', file
));
1321 const diagnosticsArchive
= `${chargingStation.stationInfo.chargingStationId}_logs.tar.gz`;
1322 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
));
1323 ftpClient
= new Client();
1324 const accessResponse
= await ftpClient
.access({
1326 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1327 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1328 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
}),
1330 let uploadResponse
: FTPResponse
| undefined;
1331 if (accessResponse
.code
=== 220) {
1332 ftpClient
.trackProgress((info
) => {
1334 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1336 } bytes transferred from diagnostics archive ${info.name}`,
1338 chargingStation
.ocppRequestService
1340 OCPP16DiagnosticsStatusNotificationRequest
,
1341 OCPP16DiagnosticsStatusNotificationResponse
1342 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1343 status: OCPP16DiagnosticsStatus
.Uploading
,
1347 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Error while sending '${
1348 OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION
1354 uploadResponse
= await ftpClient
.uploadFrom(
1355 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1356 `${uri.pathname}${diagnosticsArchive}`,
1358 if (uploadResponse
.code
=== 226) {
1359 await chargingStation
.ocppRequestService
.requestHandler
<
1360 OCPP16DiagnosticsStatusNotificationRequest
,
1361 OCPP16DiagnosticsStatusNotificationResponse
1362 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1363 status: OCPP16DiagnosticsStatus
.Uploaded
,
1368 return { fileName
: diagnosticsArchive
};
1370 throw new OCPPError(
1371 ErrorType
.GENERIC_ERROR
,
1372 `Diagnostics transfer failed with error code ${accessResponse.code}${
1373 uploadResponse?.code && `|${uploadResponse?.code}
`
1375 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1378 throw new OCPPError(
1379 ErrorType
.GENERIC_ERROR
,
1380 `Diagnostics transfer failed with error code ${accessResponse.code}${
1381 uploadResponse?.code && `|${uploadResponse?.code}
`
1383 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1386 await chargingStation
.ocppRequestService
.requestHandler
<
1387 OCPP16DiagnosticsStatusNotificationRequest
,
1388 OCPP16DiagnosticsStatusNotificationResponse
1389 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1390 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1395 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1397 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1399 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
},
1404 `${chargingStation.logPrefix()} Unsupported protocol ${
1406 } to transfer the diagnostic logs archive`,
1408 await chargingStation
.ocppRequestService
.requestHandler
<
1409 OCPP16DiagnosticsStatusNotificationRequest
,
1410 OCPP16DiagnosticsStatusNotificationResponse
1411 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1412 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1414 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1418 private handleRequestTriggerMessage(
1419 chargingStation
: ChargingStation
,
1420 commandPayload
: OCPP16TriggerMessageRequest
,
1421 ): OCPP16TriggerMessageResponse
{
1422 const { requestedMessage
, connectorId
} = commandPayload
;
1424 !OCPP16ServiceUtils
.checkFeatureProfile(
1426 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1427 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1429 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1431 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1434 !OCPP16ServiceUtils
.isConnectorIdValid(
1436 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1440 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1443 switch (requestedMessage
) {
1444 case OCPP16MessageTrigger
.BootNotification
:
1446 chargingStation
.ocppRequestService
1447 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1449 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1450 chargingStation
.bootNotificationRequest
,
1451 { skipBufferingOnError
: true, triggerMessage
: true },
1453 .then((response
) => {
1454 chargingStation
.bootNotificationResponse
= response
;
1456 .catch(Constants
.EMPTY_FUNCTION
);
1457 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1458 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1459 case OCPP16MessageTrigger
.Heartbeat
:
1461 chargingStation
.ocppRequestService
1462 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1464 OCPP16RequestCommand
.HEARTBEAT
,
1467 triggerMessage
: true,
1470 .catch(Constants
.EMPTY_FUNCTION
);
1471 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1472 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1473 case OCPP16MessageTrigger
.StatusNotification
:
1475 if (!isNullOrUndefined(connectorId
)) {
1476 chargingStation
.ocppRequestService
1477 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1479 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1482 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1483 status: chargingStation
.getConnectorStatus(connectorId
!)?.status,
1486 triggerMessage
: true,
1489 .catch(Constants
.EMPTY_FUNCTION
);
1491 // eslint-disable-next-line no-lonely-if
1492 if (chargingStation
.hasEvses
) {
1493 for (const evseStatus
of chargingStation
.evses
.values()) {
1494 for (const [id
, connectorStatus
] of evseStatus
.connectors
) {
1495 chargingStation
.ocppRequestService
1497 OCPP16StatusNotificationRequest
,
1498 OCPP16StatusNotificationResponse
1501 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1504 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1505 status: connectorStatus
.status,
1508 triggerMessage
: true,
1511 .catch(Constants
.EMPTY_FUNCTION
);
1515 for (const id
of chargingStation
.connectors
.keys()) {
1516 chargingStation
.ocppRequestService
1518 OCPP16StatusNotificationRequest
,
1519 OCPP16StatusNotificationResponse
1522 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1525 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1526 status: chargingStation
.getConnectorStatus(id
)?.status,
1529 triggerMessage
: true,
1532 .catch(Constants
.EMPTY_FUNCTION
);
1536 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1537 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1539 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1542 return this.handleIncomingRequestError
<OCPP16TriggerMessageResponse
>(
1544 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1546 { errorResponse
: OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
},
1551 private handleRequestDataTransfer(
1552 chargingStation
: ChargingStation
,
1553 commandPayload
: OCPP16DataTransferRequest
,
1554 ): OCPP16DataTransferResponse
{
1555 const { vendorId
} = commandPayload
;
1557 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1558 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
;
1560 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
;
1562 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1564 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1566 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
},
1571 private async handleRequestReserveNow(
1572 chargingStation
: ChargingStation
,
1573 commandPayload
: OCPP16ReserveNowRequest
,
1574 ): Promise
<OCPP16ReserveNowResponse
> {
1576 !OCPP16ServiceUtils
.checkFeatureProfile(
1578 OCPP16SupportedFeatureProfiles
.Reservation
,
1579 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1582 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1584 const { reservationId
, idTag
, connectorId
} = commandPayload
;
1585 let response
: OCPP16ReserveNowResponse
;
1587 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1588 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1590 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1591 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1593 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1594 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1596 await removeExpiredReservations(chargingStation
);
1597 switch (chargingStation
.getConnectorStatus(connectorId
)!.status) {
1598 case OCPP16ChargePointStatus
.Faulted
:
1599 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
;
1601 case OCPP16ChargePointStatus
.Preparing
:
1602 case OCPP16ChargePointStatus
.Charging
:
1603 case OCPP16ChargePointStatus
.SuspendedEV
:
1604 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1605 case OCPP16ChargePointStatus
.Finishing
:
1606 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1608 case OCPP16ChargePointStatus
.Unavailable
:
1609 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
;
1611 case OCPP16ChargePointStatus
.Reserved
:
1612 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1613 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1616 // eslint-disable-next-line no-fallthrough
1618 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1619 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1622 await chargingStation
.addReservation({
1623 id
: commandPayload
.reservationId
,
1626 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
;
1631 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
;
1632 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1634 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1636 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
},
1641 private async handleRequestCancelReservation(
1642 chargingStation
: ChargingStation
,
1643 commandPayload
: OCPP16CancelReservationRequest
,
1644 ): Promise
<GenericResponse
> {
1646 !OCPP16ServiceUtils
.checkFeatureProfile(
1648 OCPP16SupportedFeatureProfiles
.Reservation
,
1649 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1652 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
;
1655 const { reservationId
} = commandPayload
;
1656 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
);
1657 if (isUndefined(reservation
)) {
1659 `${chargingStation.logPrefix()} Reservation with id ${reservationId} does not exist on charging station`,
1661 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
;
1663 await chargingStation
.removeReservation(
1665 ReservationTerminationReason
.RESERVATION_CANCELED
,
1667 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
;
1669 return this.handleIncomingRequestError
<GenericResponse
>(
1671 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1673 { errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
},