1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { createWriteStream
, readdirSync
} from
'node:fs';
4 import { dirname
, join
, resolve
} from
'node:path';
5 import { URL
, fileURLToPath
} from
'node:url';
7 import type { JSONSchemaType
} from
'ajv';
8 import { Client
, type FTPResponse
} from
'basic-ftp';
9 import { addSeconds
, differenceInSeconds
, isDate
, maxTime
, secondsToMilliseconds
} from
'date-fns';
10 import { create
} from
'tar';
12 import { OCPP16Constants
} from
'./OCPP16Constants';
13 import { OCPP16ServiceUtils
} from
'./OCPP16ServiceUtils';
16 canProceedChargingProfile
,
19 getConnectorChargingProfiles
,
20 prepareChargingProfileKind
,
21 removeExpiredReservations
,
22 setConfigurationKeyValue
,
23 } from
'../../../charging-station';
24 import { OCPPError
} from
'../../../exception';
26 type ChangeConfigurationRequest
,
27 type ChangeConfigurationResponse
,
28 type ClearChargingProfileRequest
,
29 type ClearChargingProfileResponse
,
33 type GetConfigurationRequest
,
34 type GetConfigurationResponse
,
35 type GetDiagnosticsRequest
,
36 type GetDiagnosticsResponse
,
37 type IncomingRequestHandler
,
40 OCPP16AuthorizationStatus
,
41 OCPP16AvailabilityType
,
42 type OCPP16BootNotificationRequest
,
43 type OCPP16BootNotificationResponse
,
44 type OCPP16CancelReservationRequest
,
45 type OCPP16ChangeAvailabilityRequest
,
46 type OCPP16ChangeAvailabilityResponse
,
47 OCPP16ChargePointErrorCode
,
48 OCPP16ChargePointStatus
,
49 type OCPP16ChargingProfile
,
50 OCPP16ChargingProfilePurposeType
,
51 type OCPP16ChargingSchedule
,
52 type OCPP16ClearCacheRequest
,
53 type OCPP16DataTransferRequest
,
54 type OCPP16DataTransferResponse
,
55 OCPP16DataTransferVendorId
,
56 OCPP16DiagnosticsStatus
,
57 type OCPP16DiagnosticsStatusNotificationRequest
,
58 type OCPP16DiagnosticsStatusNotificationResponse
,
60 type OCPP16FirmwareStatusNotificationRequest
,
61 type OCPP16FirmwareStatusNotificationResponse
,
62 type OCPP16GetCompositeScheduleRequest
,
63 type OCPP16GetCompositeScheduleResponse
,
64 type OCPP16HeartbeatRequest
,
65 type OCPP16HeartbeatResponse
,
66 OCPP16IncomingRequestCommand
,
69 type OCPP16ReserveNowRequest
,
70 type OCPP16ReserveNowResponse
,
71 OCPP16StandardParametersKey
,
72 type OCPP16StartTransactionRequest
,
73 type OCPP16StartTransactionResponse
,
74 type OCPP16StatusNotificationRequest
,
75 type OCPP16StatusNotificationResponse
,
76 OCPP16StopTransactionReason
,
77 OCPP16SupportedFeatureProfiles
,
78 type OCPP16TriggerMessageRequest
,
79 type OCPP16TriggerMessageResponse
,
80 type OCPP16UpdateFirmwareRequest
,
81 type OCPP16UpdateFirmwareResponse
,
82 type OCPPConfigurationKey
,
84 type RemoteStartTransactionRequest
,
85 type RemoteStopTransactionRequest
,
86 ReservationTerminationReason
,
88 type SetChargingProfileRequest
,
89 type SetChargingProfileResponse
,
90 type UnlockConnectorRequest
,
91 type UnlockConnectorResponse
,
92 } from
'../../../types';
97 formatDurationMilliSeconds
,
106 } from
'../../../utils';
107 import { OCPPIncomingRequestService
} from
'../OCPPIncomingRequestService';
109 const moduleName
= 'OCPP16IncomingRequestService';
111 export class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
112 protected jsonSchemas
: Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>;
113 private incomingRequestHandlers
: Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>;
115 public constructor() {
116 // if (new.target?.name === moduleName) {
117 // throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
119 super(OCPPVersion
.VERSION_16
);
120 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
122 OCPP16IncomingRequestCommand
.RESET
,
123 this.handleRequestReset
.bind(this) as unknown
as IncomingRequestHandler
,
126 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
127 this.handleRequestClearCache
.bind(this) as IncomingRequestHandler
,
130 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
131 this.handleRequestUnlockConnector
.bind(this) as unknown
as IncomingRequestHandler
,
134 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
135 this.handleRequestGetConfiguration
.bind(this) as IncomingRequestHandler
,
138 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
139 this.handleRequestChangeConfiguration
.bind(this) as unknown
as IncomingRequestHandler
,
142 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
143 this.handleRequestGetCompositeSchedule
.bind(this) as unknown
as IncomingRequestHandler
,
146 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
147 this.handleRequestSetChargingProfile
.bind(this) as unknown
as IncomingRequestHandler
,
150 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
151 this.handleRequestClearChargingProfile
.bind(this) as IncomingRequestHandler
,
154 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
155 this.handleRequestChangeAvailability
.bind(this) as unknown
as IncomingRequestHandler
,
158 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
159 this.handleRequestRemoteStartTransaction
.bind(this) as unknown
as IncomingRequestHandler
,
162 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
163 this.handleRequestRemoteStopTransaction
.bind(this) as unknown
as IncomingRequestHandler
,
166 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
167 this.handleRequestGetDiagnostics
.bind(this) as IncomingRequestHandler
,
170 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
171 this.handleRequestTriggerMessage
.bind(this) as unknown
as IncomingRequestHandler
,
174 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
175 this.handleRequestDataTransfer
.bind(this) as unknown
as IncomingRequestHandler
,
178 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
179 this.handleRequestUpdateFirmware
.bind(this) as unknown
as IncomingRequestHandler
,
182 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
183 this.handleRequestReserveNow
.bind(this) as unknown
as IncomingRequestHandler
,
186 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
187 this.handleRequestCancelReservation
.bind(this) as unknown
as IncomingRequestHandler
,
190 this.jsonSchemas
= new Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>([
192 OCPP16IncomingRequestCommand
.RESET
,
193 OCPP16ServiceUtils
.parseJsonSchemaFile
<ResetRequest
>(
194 'assets/json-schemas/ocpp/1.6/Reset.json',
200 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
201 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ClearCacheRequest
>(
202 'assets/json-schemas/ocpp/1.6/ClearCache.json',
208 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
209 OCPP16ServiceUtils
.parseJsonSchemaFile
<UnlockConnectorRequest
>(
210 'assets/json-schemas/ocpp/1.6/UnlockConnector.json',
216 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
217 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetConfigurationRequest
>(
218 'assets/json-schemas/ocpp/1.6/GetConfiguration.json',
224 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
225 OCPP16ServiceUtils
.parseJsonSchemaFile
<ChangeConfigurationRequest
>(
226 'assets/json-schemas/ocpp/1.6/ChangeConfiguration.json',
232 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
233 OCPP16ServiceUtils
.parseJsonSchemaFile
<GetDiagnosticsRequest
>(
234 'assets/json-schemas/ocpp/1.6/GetDiagnostics.json',
240 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
241 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16GetCompositeScheduleRequest
>(
242 'assets/json-schemas/ocpp/1.6/GetCompositeSchedule.json',
248 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
249 OCPP16ServiceUtils
.parseJsonSchemaFile
<SetChargingProfileRequest
>(
250 'assets/json-schemas/ocpp/1.6/SetChargingProfile.json',
256 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
257 OCPP16ServiceUtils
.parseJsonSchemaFile
<ClearChargingProfileRequest
>(
258 'assets/json-schemas/ocpp/1.6/ClearChargingProfile.json',
264 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
265 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ChangeAvailabilityRequest
>(
266 'assets/json-schemas/ocpp/1.6/ChangeAvailability.json',
272 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
273 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStartTransactionRequest
>(
274 'assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json',
280 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
281 OCPP16ServiceUtils
.parseJsonSchemaFile
<RemoteStopTransactionRequest
>(
282 'assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json',
288 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
289 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16TriggerMessageRequest
>(
290 'assets/json-schemas/ocpp/1.6/TriggerMessage.json',
296 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
297 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16DataTransferRequest
>(
298 'assets/json-schemas/ocpp/1.6/DataTransfer.json',
304 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
305 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16UpdateFirmwareRequest
>(
306 'assets/json-schemas/ocpp/1.6/UpdateFirmware.json',
312 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
313 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16ReserveNowRequest
>(
314 'assets/json-schemas/ocpp/1.6/ReserveNow.json',
320 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
321 OCPP16ServiceUtils
.parseJsonSchemaFile
<OCPP16CancelReservationRequest
>(
322 'assets/json-schemas/ocpp/1.6/CancelReservation.json',
328 this.validatePayload
= this.validatePayload
.bind(this) as (
329 chargingStation
: ChargingStation
,
330 commandName
: OCPP16IncomingRequestCommand
,
331 commandPayload
: JsonType
,
335 public async incomingRequestHandler
<ReqType
extends JsonType
, ResType
extends JsonType
>(
336 chargingStation
: ChargingStation
,
338 commandName
: OCPP16IncomingRequestCommand
,
339 commandPayload
: ReqType
,
341 let response
: ResType
;
343 chargingStation
.getOcppStrictCompliance() === true &&
344 chargingStation
.inPendingState() === true &&
345 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
346 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
349 ErrorType
.SECURITY_ERROR
,
350 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
354 )} while the charging station is in pending state on the central server`,
360 chargingStation
.isRegistered() === true ||
361 (chargingStation
.getOcppStrictCompliance() === false &&
362 chargingStation
.inUnknownState() === true)
365 this.incomingRequestHandlers
.has(commandName
) === true &&
366 OCPP16ServiceUtils
.isIncomingRequestCommandSupported(chargingStation
, commandName
) === true
369 this.validatePayload(chargingStation
, commandName
, commandPayload
);
370 // Call the method to build the response
371 response
= (await this.incomingRequestHandlers
.get(commandName
)!(
378 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler:
379 Handle incoming request error:`,
387 ErrorType
.NOT_IMPLEMENTED
,
388 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
399 ErrorType
.SECURITY_ERROR
,
400 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
404 )} while the charging station is not registered on the central server.`,
409 // Send the built response
410 await chargingStation
.ocppRequestService
.sendResponse(
418 private validatePayload(
419 chargingStation
: ChargingStation
,
420 commandName
: OCPP16IncomingRequestCommand
,
421 commandPayload
: JsonType
,
423 if (this.jsonSchemas
.has(commandName
) === true) {
424 return this.validateIncomingRequestPayload(
427 this.jsonSchemas
.get(commandName
)!,
432 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found
433 for command '${commandName}' PDU validation`,
438 // Simulate charging station restart
439 private handleRequestReset(
440 chargingStation
: ChargingStation
,
441 commandPayload
: ResetRequest
,
443 const { type } = commandPayload
;
444 this.runInAsyncScope(
445 chargingStation
.reset
.bind(chargingStation
) as (
446 this: ChargingStation
,
450 `${type}Reset` as OCPP16StopTransactionReason
,
451 ).catch(Constants
.EMPTY_FUNCTION
);
453 `${chargingStation.logPrefix()} ${type} reset command received, simulating it. The station will be
454 back online in ${formatDurationMilliSeconds(chargingStation.stationInfo.resetTime!)}`,
456 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
459 private async handleRequestUnlockConnector(
460 chargingStation
: ChargingStation
,
461 commandPayload
: UnlockConnectorRequest
,
462 ): Promise
<UnlockConnectorResponse
> {
463 const { connectorId
} = commandPayload
;
464 if (chargingStation
.hasConnector(connectorId
) === false) {
466 `${chargingStation.logPrefix()} Trying to unlock a non existing
467 connector id ${connectorId.toString()}`,
469 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
471 if (connectorId
=== 0) {
473 `${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId.toString()}`,
475 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
477 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
478 const stopResponse
= await chargingStation
.stopTransactionOnConnector(
480 OCPP16StopTransactionReason
.UNLOCK_COMMAND
,
482 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
483 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
;
485 return OCPP16Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
487 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
490 OCPP16ChargePointStatus
.Available
,
492 return OCPP16Constants
.OCPP_RESPONSE_UNLOCKED
;
495 private handleRequestGetConfiguration(
496 chargingStation
: ChargingStation
,
497 commandPayload
: GetConfigurationRequest
,
498 ): GetConfigurationResponse
{
499 const { key
} = commandPayload
;
500 const configurationKey
: OCPPConfigurationKey
[] = [];
501 const unknownKey
: string[] = [];
502 if (isUndefined(key
) === true) {
503 for (const configuration
of chargingStation
.ocppConfiguration
!.configurationKey
!) {
504 if (isUndefined(configuration
.visible
) === true) {
505 configuration
.visible
= true;
507 if (configuration
.visible
=== false) {
510 configurationKey
.push({
511 key
: configuration
.key
,
512 readonly: configuration
.readonly,
513 value
: configuration
.value
,
516 } else if (isNotEmptyArray(key
) === true) {
517 for (const k
of key
!) {
518 const keyFound
= getConfigurationKey(chargingStation
, k
, true);
520 if (isUndefined(keyFound
.visible
) === true) {
521 keyFound
.visible
= true;
523 if (keyFound
.visible
=== false) {
526 configurationKey
.push({
528 readonly: keyFound
.readonly,
529 value
: keyFound
.value
,
542 private handleRequestChangeConfiguration(
543 chargingStation
: ChargingStation
,
544 commandPayload
: ChangeConfigurationRequest
,
545 ): ChangeConfigurationResponse
{
546 const { key
, value
} = commandPayload
;
547 const keyToChange
= getConfigurationKey(chargingStation
, key
, true);
548 if (keyToChange
?.readonly === true) {
549 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
550 } else if (keyToChange
?.readonly === false) {
551 let valueChanged
= false;
552 if (keyToChange
.value
!== value
) {
553 setConfigurationKeyValue(chargingStation
, key
, value
, true);
556 let triggerHeartbeatRestart
= false;
558 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
559 OCPP16StandardParametersKey
.HeartBeatInterval
&&
562 setConfigurationKeyValue(
564 OCPP16StandardParametersKey
.HeartbeatInterval
,
567 triggerHeartbeatRestart
= true;
570 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
571 OCPP16StandardParametersKey
.HeartbeatInterval
&&
574 setConfigurationKeyValue(
576 OCPP16StandardParametersKey
.HeartBeatInterval
,
579 triggerHeartbeatRestart
= true;
581 if (triggerHeartbeatRestart
) {
582 chargingStation
.restartHeartbeat();
585 (keyToChange
.key
as OCPP16StandardParametersKey
) ===
586 OCPP16StandardParametersKey
.WebSocketPingInterval
&&
589 chargingStation
.restartWebSocketPing();
591 if (keyToChange
.reboot
) {
592 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
594 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
596 return OCPP16Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
599 private handleRequestSetChargingProfile(
600 chargingStation
: ChargingStation
,
601 commandPayload
: SetChargingProfileRequest
,
602 ): SetChargingProfileResponse
{
604 OCPP16ServiceUtils
.checkFeatureProfile(
606 OCPP16SupportedFeatureProfiles
.SmartCharging
,
607 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
610 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
612 const { connectorId
, csChargingProfiles
} = commandPayload
;
613 if (chargingStation
.hasConnector(connectorId
) === false) {
615 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a
616 non existing connector id ${connectorId}`,
618 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
621 csChargingProfiles
.chargingProfilePurpose
===
622 OCPP16ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
625 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
628 csChargingProfiles
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
&&
629 (connectorId
=== 0 ||
630 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false)
633 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s)
634 on connector ${connectorId} without a started transaction`,
636 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
638 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, csChargingProfiles
);
640 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${connectorId}: %j`,
643 return OCPP16Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
646 private handleRequestGetCompositeSchedule(
647 chargingStation
: ChargingStation
,
648 commandPayload
: OCPP16GetCompositeScheduleRequest
,
649 ): OCPP16GetCompositeScheduleResponse
{
651 OCPP16ServiceUtils
.checkFeatureProfile(
653 OCPP16SupportedFeatureProfiles
.SmartCharging
,
654 OCPP16IncomingRequestCommand
.GET_COMPOSITE_SCHEDULE
,
657 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
659 const { connectorId
, duration
, chargingRateUnit
} = commandPayload
;
660 if (chargingStation
.hasConnector(connectorId
) === false) {
662 `${chargingStation.logPrefix()} Trying to get composite schedule to a
663 non existing connector id ${connectorId}`,
665 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
667 if (connectorId
=== 0) {
669 `${chargingStation.logPrefix()} Get composite schedule on connector id ${connectorId} is not yet supported`,
671 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
673 if (chargingRateUnit
) {
675 `${chargingStation.logPrefix()} Get composite schedule with a specified rate unit is not yet supported, no conversion will be done`,
678 const connectorStatus
= chargingStation
.getConnectorStatus(connectorId
)!;
681 connectorStatus
?.chargingProfiles
&&
682 isEmptyArray(chargingStation
.getConnectorStatus(0)?.chargingProfiles
),
685 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
687 const currentDate
= new Date();
688 const compositeScheduleInterval
: Interval
= {
690 end
: addSeconds(currentDate
, duration
),
692 // Get charging profiles sorted by connector id then stack level
693 const chargingProfiles
: OCPP16ChargingProfile
[] = getConnectorChargingProfiles(
697 let previousCompositeSchedule
: OCPP16ChargingSchedule
| undefined;
698 let compositeSchedule
: OCPP16ChargingSchedule
| undefined;
699 for (const chargingProfile
of chargingProfiles
) {
701 isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
) &&
702 connectorStatus
?.transactionStarted
705 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
706 chargingProfile.chargingProfileId
707 } has no startSchedule defined. Trying to set it to the connector current transaction start date`,
709 // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
710 chargingProfile
.chargingSchedule
.startSchedule
= connectorStatus
?.transactionStart
;
713 !isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
) &&
714 !isDate(chargingProfile
.chargingSchedule
?.startSchedule
)
717 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
718 chargingProfile.chargingProfileId
719 } startSchedule property is not a Date instance. Trying to convert it to a Date instance`,
721 chargingProfile
.chargingSchedule
.startSchedule
= convertToDate(
722 chargingProfile
.chargingSchedule
?.startSchedule
,
726 !isNullOrUndefined(chargingProfile
.chargingSchedule
?.startSchedule
) &&
727 isNullOrUndefined(chargingProfile
.chargingSchedule
?.duration
)
730 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
731 chargingProfile.chargingProfileId
732 } has no duration defined and will be set to the maximum time allowed`,
734 // OCPP specifies that if duration is not defined, it should be infinite
735 chargingProfile
.chargingSchedule
.duration
= differenceInSeconds(
737 chargingProfile
.chargingSchedule
.startSchedule
!,
741 !prepareChargingProfileKind(
744 compositeScheduleInterval
.start
as Date,
745 chargingStation
.logPrefix(),
751 !canProceedChargingProfile(
753 compositeScheduleInterval
.start
as Date,
754 chargingStation
.logPrefix(),
759 compositeSchedule
= OCPP16ServiceUtils
.composeChargingSchedules(
760 previousCompositeSchedule
,
761 chargingProfile
.chargingSchedule
,
762 compositeScheduleInterval
,
764 previousCompositeSchedule
= compositeSchedule
;
766 if (compositeSchedule
) {
768 status: GenericStatus
.Accepted
,
769 scheduleStart
: compositeSchedule
.startSchedule
!,
771 chargingSchedule
: compositeSchedule
,
774 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
777 private handleRequestClearChargingProfile(
778 chargingStation
: ChargingStation
,
779 commandPayload
: ClearChargingProfileRequest
,
780 ): ClearChargingProfileResponse
{
782 OCPP16ServiceUtils
.checkFeatureProfile(
784 OCPP16SupportedFeatureProfiles
.SmartCharging
,
785 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
788 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
790 const { connectorId
} = commandPayload
;
791 if (chargingStation
.hasConnector(connectorId
!) === false) {
793 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to
794 a non existing connector id ${connectorId}`,
796 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
799 !isNullOrUndefined(connectorId
) &&
800 isNotEmptyArray(chargingStation
.getConnectorStatus(connectorId
!)?.chargingProfiles
)
802 chargingStation
.getConnectorStatus(connectorId
!)!.chargingProfiles
= [];
804 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${connectorId}`,
806 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
808 if (isNullOrUndefined(connectorId
)) {
809 let clearedCP
= false;
810 if (chargingStation
.hasEvses
) {
811 for (const evseStatus
of chargingStation
.evses
.values()) {
812 for (const connectorStatus
of evseStatus
.connectors
.values()) {
813 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
816 connectorStatus
.chargingProfiles
,
821 for (const id
of chargingStation
.connectors
.keys()) {
822 clearedCP
= OCPP16ServiceUtils
.clearChargingProfiles(
825 chargingStation
.getConnectorStatus(id
)?.chargingProfiles
,
830 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
833 return OCPP16Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
836 private async handleRequestChangeAvailability(
837 chargingStation
: ChargingStation
,
838 commandPayload
: OCPP16ChangeAvailabilityRequest
,
839 ): Promise
<OCPP16ChangeAvailabilityResponse
> {
840 const { connectorId
, type } = commandPayload
;
841 if (chargingStation
.hasConnector(connectorId
) === false) {
843 `${chargingStation.logPrefix()} Trying to change the availability of a
844 non existing connector id ${connectorId.toString()}`,
846 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
848 const chargePointStatus
: OCPP16ChargePointStatus
=
849 type === OCPP16AvailabilityType
.Operative
850 ? OCPP16ChargePointStatus
.Available
851 : OCPP16ChargePointStatus
.Unavailable
;
852 if (connectorId
=== 0) {
853 let response
: OCPP16ChangeAvailabilityResponse
;
854 if (chargingStation
.hasEvses
) {
855 for (const evseStatus
of chargingStation
.evses
.values()) {
856 response
= await OCPP16ServiceUtils
.changeAvailability(
858 [...evseStatus
.connectors
.keys()],
864 response
= await OCPP16ServiceUtils
.changeAvailability(
866 [...chargingStation
.connectors
.keys()],
874 (chargingStation
.isChargingStationAvailable() === true ||
875 (chargingStation
.isChargingStationAvailable() === false &&
876 type === OCPP16AvailabilityType
.Inoperative
))
878 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== true) {
879 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type;
880 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
882 chargingStation
.getConnectorStatus(connectorId
)!.availability
= type;
883 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
888 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
890 return OCPP16Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
893 private async handleRequestRemoteStartTransaction(
894 chargingStation
: ChargingStation
,
895 commandPayload
: RemoteStartTransactionRequest
,
896 ): Promise
<GenericResponse
> {
897 const { connectorId
: transactionConnectorId
, idTag
, chargingProfile
} = commandPayload
;
898 if (chargingStation
.hasConnector(transactionConnectorId
) === false) {
899 return this.notifyRemoteStartTransactionRejected(
901 transactionConnectorId
,
906 !chargingStation
.isChargingStationAvailable() ||
907 !chargingStation
.isConnectorAvailable(transactionConnectorId
)
909 return this.notifyRemoteStartTransactionRejected(
911 transactionConnectorId
,
915 const remoteStartTransactionLogMsg
= `
916 ${chargingStation.logPrefix()} Transaction remotely STARTED on ${
917 chargingStation.stationInfo.chargingStationId
918 }#${transactionConnectorId.toString()} for idTag '${idTag}'`;
919 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
921 transactionConnectorId
,
922 OCPP16ChargePointStatus
.Preparing
,
924 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
)!;
925 // Authorization check required
927 chargingStation
.getAuthorizeRemoteTxRequests() === true &&
928 (await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, transactionConnectorId
, idTag
))
930 // Authorization successful, start transaction
932 this.setRemoteStartTransactionChargingProfile(
934 transactionConnectorId
,
938 connectorStatus
.transactionRemoteStarted
= true;
941 await chargingStation
.ocppRequestService
.requestHandler
<
942 OCPP16StartTransactionRequest
,
943 OCPP16StartTransactionResponse
944 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
945 connectorId
: transactionConnectorId
,
948 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
950 logger
.debug(remoteStartTransactionLogMsg
);
951 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
953 return this.notifyRemoteStartTransactionRejected(
955 transactionConnectorId
,
959 return this.notifyRemoteStartTransactionRejected(
961 transactionConnectorId
,
965 // No authorization check required, start transaction
967 this.setRemoteStartTransactionChargingProfile(
969 transactionConnectorId
,
973 connectorStatus
.transactionRemoteStarted
= true;
976 await chargingStation
.ocppRequestService
.requestHandler
<
977 OCPP16StartTransactionRequest
,
978 OCPP16StartTransactionResponse
979 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
980 connectorId
: transactionConnectorId
,
983 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
985 logger
.debug(remoteStartTransactionLogMsg
);
986 return OCPP16Constants
.OCPP_RESPONSE_ACCEPTED
;
988 return this.notifyRemoteStartTransactionRejected(
990 transactionConnectorId
,
994 return this.notifyRemoteStartTransactionRejected(
996 transactionConnectorId
,
1001 private async notifyRemoteStartTransactionRejected(
1002 chargingStation
: ChargingStation
,
1003 connectorId
: number,
1005 ): Promise
<GenericResponse
> {
1007 chargingStation
.getConnectorStatus(connectorId
)?.status !== OCPP16ChargePointStatus
.Available
1009 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1012 OCPP16ChargePointStatus
.Available
,
1016 `${chargingStation.logPrefix()} Remote starting transaction REJECTED on connector id
1017 ${connectorId.toString()}, idTag '${idTag}', availability '${chargingStation.getConnectorStatus(
1019 )?.availability}', status '${chargingStation.getConnectorStatus(connectorId)?.status}'`,
1021 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
1024 private setRemoteStartTransactionChargingProfile(
1025 chargingStation
: ChargingStation
,
1026 connectorId
: number,
1027 chargingProfile
: OCPP16ChargingProfile
,
1031 chargingProfile
.chargingProfilePurpose
=== OCPP16ChargingProfilePurposeType
.TX_PROFILE
1033 OCPP16ServiceUtils
.setChargingProfile(chargingStation
, connectorId
, chargingProfile
);
1035 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction
1036 on connector id ${connectorId}: %j`,
1042 chargingProfile
.chargingProfilePurpose
!== OCPP16ChargingProfilePurposeType
.TX_PROFILE
1045 `${chargingStation.logPrefix()} Not allowed to set ${
1046 chargingProfile.chargingProfilePurpose
1047 } charging profile(s) at remote start transaction`,
1054 private async handleRequestRemoteStopTransaction(
1055 chargingStation
: ChargingStation
,
1056 commandPayload
: RemoteStopTransactionRequest
,
1057 ): Promise
<GenericResponse
> {
1058 const { transactionId
} = commandPayload
;
1059 if (chargingStation
.hasEvses
) {
1060 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1062 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1063 if (connectorStatus
.transactionId
=== transactionId
) {
1064 return OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
);
1070 for (const connectorId
of chargingStation
.connectors
.keys()) {
1073 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
1075 return OCPP16ServiceUtils
.remoteStopTransaction(chargingStation
, connectorId
);
1080 `${chargingStation.logPrefix()} Trying to remote stop a non existing transaction with id
1081 ${transactionId.toString()}`,
1083 return OCPP16Constants
.OCPP_RESPONSE_REJECTED
;
1086 private handleRequestUpdateFirmware(
1087 chargingStation
: ChargingStation
,
1088 commandPayload
: OCPP16UpdateFirmwareRequest
,
1089 ): OCPP16UpdateFirmwareResponse
{
1091 OCPP16ServiceUtils
.checkFeatureProfile(
1093 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1094 OCPP16IncomingRequestCommand
.UPDATE_FIRMWARE
,
1098 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware:
1099 Cannot simulate firmware update: feature profile not supported`,
1101 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1103 let { retrieveDate
} = commandPayload
;
1105 !isNullOrUndefined(chargingStation
.stationInfo
.firmwareStatus
) &&
1106 chargingStation
.stationInfo
.firmwareStatus
!== OCPP16FirmwareStatus
.Installed
1109 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware:
1110 Cannot simulate firmware update: firmware update is already in progress`,
1112 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1114 retrieveDate
= convertToDate(retrieveDate
)!;
1115 const now
= Date.now();
1116 if (retrieveDate
?.getTime() <= now
) {
1117 this.runInAsyncScope(
1118 this.updateFirmwareSimulation
.bind(this) as (
1119 this: OCPP16IncomingRequestService
,
1124 ).catch(Constants
.EMPTY_FUNCTION
);
1128 this.runInAsyncScope(
1129 this.updateFirmwareSimulation
.bind(this) as (
1130 this: OCPP16IncomingRequestService
,
1135 ).catch(Constants
.EMPTY_FUNCTION
);
1137 retrieveDate
?.getTime() - now
,
1140 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1143 private async updateFirmwareSimulation(
1144 chargingStation
: ChargingStation
,
1148 if (checkChargingStation(chargingStation
, chargingStation
.logPrefix()) === false) {
1151 if (chargingStation
.hasEvses
) {
1152 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1154 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1155 if (connectorStatus
?.transactionStarted
=== false) {
1156 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1159 OCPP16ChargePointStatus
.Unavailable
,
1166 for (const connectorId
of chargingStation
.connectors
.keys()) {
1169 chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
=== false
1171 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1174 OCPP16ChargePointStatus
.Unavailable
,
1179 await chargingStation
.ocppRequestService
.requestHandler
<
1180 OCPP16FirmwareStatusNotificationRequest
,
1181 OCPP16FirmwareStatusNotificationResponse
1182 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1183 status: OCPP16FirmwareStatus
.Downloading
,
1185 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Downloading
;
1187 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1188 OCPP16FirmwareStatus
.DownloadFailed
1190 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1191 await chargingStation
.ocppRequestService
.requestHandler
<
1192 OCPP16FirmwareStatusNotificationRequest
,
1193 OCPP16FirmwareStatusNotificationResponse
1194 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1195 status: chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
,
1197 chargingStation
.stationInfo
.firmwareStatus
=
1198 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
;
1201 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1202 await chargingStation
.ocppRequestService
.requestHandler
<
1203 OCPP16FirmwareStatusNotificationRequest
,
1204 OCPP16FirmwareStatusNotificationResponse
1205 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1206 status: OCPP16FirmwareStatus
.Downloaded
,
1208 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Downloaded
;
1209 let wasTransactionsStarted
= false;
1210 let transactionsStarted
: boolean;
1212 const runningTransactions
= chargingStation
.getNumberOfRunningTransactions();
1213 if (runningTransactions
> 0) {
1214 const waitTime
= secondsToMilliseconds(15);
1216 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation:
1217 ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1219 )} before continuing firmware update simulation`,
1221 await sleep(waitTime
);
1222 transactionsStarted
= true;
1223 wasTransactionsStarted
= true;
1225 if (chargingStation
.hasEvses
) {
1226 for (const [evseId
, evseStatus
] of chargingStation
.evses
) {
1228 for (const [connectorId
, connectorStatus
] of evseStatus
.connectors
) {
1229 if (connectorStatus
?.status !== OCPP16ChargePointStatus
.Unavailable
) {
1230 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1233 OCPP16ChargePointStatus
.Unavailable
,
1240 for (const connectorId
of chargingStation
.connectors
.keys()) {
1243 chargingStation
.getConnectorStatus(connectorId
)?.status !==
1244 OCPP16ChargePointStatus
.Unavailable
1246 await OCPP16ServiceUtils
.sendAndSetConnectorStatus(
1249 OCPP16ChargePointStatus
.Unavailable
,
1254 transactionsStarted
= false;
1256 } while (transactionsStarted
);
1257 !wasTransactionsStarted
&&
1258 (await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
))));
1259 if (checkChargingStation(chargingStation
, chargingStation
.logPrefix()) === false) {
1262 await chargingStation
.ocppRequestService
.requestHandler
<
1263 OCPP16FirmwareStatusNotificationRequest
,
1264 OCPP16FirmwareStatusNotificationResponse
1265 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1266 status: OCPP16FirmwareStatus
.Installing
,
1268 chargingStation
.stationInfo
.firmwareStatus
= OCPP16FirmwareStatus
.Installing
;
1270 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
===
1271 OCPP16FirmwareStatus
.InstallationFailed
1273 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1274 await chargingStation
.ocppRequestService
.requestHandler
<
1275 OCPP16FirmwareStatusNotificationRequest
,
1276 OCPP16FirmwareStatusNotificationResponse
1277 >(chargingStation
, OCPP16RequestCommand
.FIRMWARE_STATUS_NOTIFICATION
, {
1278 status: chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
,
1280 chargingStation
.stationInfo
.firmwareStatus
=
1281 chargingStation
.stationInfo
?.firmwareUpgrade
?.failureStatus
;
1284 if (chargingStation
.stationInfo
?.firmwareUpgrade
?.reset
=== true) {
1285 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay
, minDelay
)));
1286 await chargingStation
.reset(OCPP16StopTransactionReason
.REBOOT
);
1290 private async handleRequestGetDiagnostics(
1291 chargingStation
: ChargingStation
,
1292 commandPayload
: GetDiagnosticsRequest
,
1293 ): Promise
<GetDiagnosticsResponse
> {
1295 OCPP16ServiceUtils
.checkFeatureProfile(
1297 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1298 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1302 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics:
1303 Cannot get diagnostics: feature profile not supported`,
1305 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1307 const { location
} = commandPayload
;
1308 const uri
= new URL(location
);
1309 if (uri
.protocol
.startsWith('ftp:')) {
1310 let ftpClient
: Client
| undefined;
1312 const logFiles
= readdirSync(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'))
1313 .filter((file
) => file
.endsWith('.log'))
1314 .map((file
) => join('./', file
));
1315 const diagnosticsArchive
= `${chargingStation.stationInfo.chargingStationId}_logs.tar.gz`;
1316 create({ gzip
: true }, logFiles
).pipe(createWriteStream(diagnosticsArchive
));
1317 ftpClient
= new Client();
1318 const accessResponse
= await ftpClient
.access({
1320 ...(isNotEmptyString(uri
.port
) && { port
: convertToInt(uri
.port
) }),
1321 ...(isNotEmptyString(uri
.username
) && { user
: uri
.username
}),
1322 ...(isNotEmptyString(uri
.password
) && { password
: uri
.password
}),
1324 let uploadResponse
: FTPResponse
| undefined;
1325 if (accessResponse
.code
=== 220) {
1326 ftpClient
.trackProgress((info
) => {
1328 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: ${
1330 } bytes transferred from diagnostics archive ${info.name}`,
1332 chargingStation
.ocppRequestService
1334 OCPP16DiagnosticsStatusNotificationRequest
,
1335 OCPP16DiagnosticsStatusNotificationResponse
1336 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1337 status: OCPP16DiagnosticsStatus
.Uploading
,
1341 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics:
1342 Error while sending '${OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION}'`,
1347 uploadResponse
= await ftpClient
.uploadFrom(
1348 join(resolve(dirname(fileURLToPath(import.meta
.url
)), '../'), diagnosticsArchive
),
1349 `${uri.pathname}${diagnosticsArchive}`,
1351 if (uploadResponse
.code
=== 226) {
1352 await chargingStation
.ocppRequestService
.requestHandler
<
1353 OCPP16DiagnosticsStatusNotificationRequest
,
1354 OCPP16DiagnosticsStatusNotificationResponse
1355 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1356 status: OCPP16DiagnosticsStatus
.Uploaded
,
1361 return { fileName
: diagnosticsArchive
};
1363 throw new OCPPError(
1364 ErrorType
.GENERIC_ERROR
,
1365 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1366 uploadResponse?.code && `|${uploadResponse?.code.toString()}
`
1368 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1371 throw new OCPPError(
1372 ErrorType
.GENERIC_ERROR
,
1373 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1374 uploadResponse?.code && `|${uploadResponse?.code.toString()}
`
1376 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1379 await chargingStation
.ocppRequestService
.requestHandler
<
1380 OCPP16DiagnosticsStatusNotificationRequest
,
1381 OCPP16DiagnosticsStatusNotificationResponse
1382 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1383 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1388 return this.handleIncomingRequestError
<GetDiagnosticsResponse
>(
1390 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1392 { errorResponse
: OCPP16Constants
.OCPP_RESPONSE_EMPTY
},
1397 `${chargingStation.logPrefix()} Unsupported protocol ${
1399 } to transfer the diagnostic logs archive`,
1401 await chargingStation
.ocppRequestService
.requestHandler
<
1402 OCPP16DiagnosticsStatusNotificationRequest
,
1403 OCPP16DiagnosticsStatusNotificationResponse
1404 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1405 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1407 return OCPP16Constants
.OCPP_RESPONSE_EMPTY
;
1411 private handleRequestTriggerMessage(
1412 chargingStation
: ChargingStation
,
1413 commandPayload
: OCPP16TriggerMessageRequest
,
1414 ): OCPP16TriggerMessageResponse
{
1415 const { requestedMessage
, connectorId
} = commandPayload
;
1417 !OCPP16ServiceUtils
.checkFeatureProfile(
1419 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1420 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1422 !OCPP16ServiceUtils
.isMessageTriggerSupported(chargingStation
, requestedMessage
)
1424 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1427 !OCPP16ServiceUtils
.isConnectorIdValid(
1429 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1433 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1436 switch (requestedMessage
) {
1437 case OCPP16MessageTrigger
.BootNotification
:
1439 chargingStation
.ocppRequestService
1440 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1442 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1443 chargingStation
.bootNotificationRequest
,
1444 { skipBufferingOnError
: true, triggerMessage
: true },
1446 .then((response
) => {
1447 chargingStation
.bootNotificationResponse
= response
;
1449 .catch(Constants
.EMPTY_FUNCTION
);
1450 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1451 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1452 case OCPP16MessageTrigger
.Heartbeat
:
1454 chargingStation
.ocppRequestService
1455 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1457 OCPP16RequestCommand
.HEARTBEAT
,
1460 triggerMessage
: true,
1463 .catch(Constants
.EMPTY_FUNCTION
);
1464 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1465 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1466 case OCPP16MessageTrigger
.StatusNotification
:
1468 if (!isNullOrUndefined(connectorId
)) {
1469 chargingStation
.ocppRequestService
1470 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1472 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1475 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1476 status: chargingStation
.getConnectorStatus(connectorId
!)?.status,
1479 triggerMessage
: true,
1482 .catch(Constants
.EMPTY_FUNCTION
);
1484 // eslint-disable-next-line no-lonely-if
1485 if (chargingStation
.hasEvses
) {
1486 for (const evseStatus
of chargingStation
.evses
.values()) {
1487 for (const [id
, connectorStatus
] of evseStatus
.connectors
) {
1488 chargingStation
.ocppRequestService
1490 OCPP16StatusNotificationRequest
,
1491 OCPP16StatusNotificationResponse
1494 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1497 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1498 status: connectorStatus
.status,
1501 triggerMessage
: true,
1504 .catch(Constants
.EMPTY_FUNCTION
);
1508 for (const id
of chargingStation
.connectors
.keys()) {
1509 chargingStation
.ocppRequestService
1511 OCPP16StatusNotificationRequest
,
1512 OCPP16StatusNotificationResponse
1515 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1518 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1519 status: chargingStation
.getConnectorStatus(id
)?.status,
1522 triggerMessage
: true,
1525 .catch(Constants
.EMPTY_FUNCTION
);
1529 }, OCPP16Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1530 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1532 return OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1535 return this.handleIncomingRequestError
<OCPP16TriggerMessageResponse
>(
1537 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1539 { errorResponse
: OCPP16Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
},
1544 private handleRequestDataTransfer(
1545 chargingStation
: ChargingStation
,
1546 commandPayload
: OCPP16DataTransferRequest
,
1547 ): OCPP16DataTransferResponse
{
1548 const { vendorId
} = commandPayload
;
1550 if (Object.values(OCPP16DataTransferVendorId
).includes(vendorId
)) {
1551 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED
;
1553 return OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID
;
1555 return this.handleIncomingRequestError
<OCPP16DataTransferResponse
>(
1557 OCPP16IncomingRequestCommand
.DATA_TRANSFER
,
1559 { errorResponse
: OCPP16Constants
.OCPP_DATA_TRANSFER_RESPONSE_REJECTED
},
1564 private async handleRequestReserveNow(
1565 chargingStation
: ChargingStation
,
1566 commandPayload
: OCPP16ReserveNowRequest
,
1567 ): Promise
<OCPP16ReserveNowResponse
> {
1569 !OCPP16ServiceUtils
.checkFeatureProfile(
1571 OCPP16SupportedFeatureProfiles
.Reservation
,
1572 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1575 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1577 const { reservationId
, idTag
, connectorId
} = commandPayload
;
1578 let response
: OCPP16ReserveNowResponse
;
1580 if (connectorId
> 0 && !chargingStation
.isConnectorAvailable(connectorId
)) {
1581 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1583 if (connectorId
=== 0 && !chargingStation
.getReserveConnectorZeroSupported()) {
1584 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1586 if (!(await OCPP16ServiceUtils
.isIdTagAuthorized(chargingStation
, connectorId
, idTag
))) {
1587 return OCPP16Constants
.OCPP_RESERVATION_RESPONSE_REJECTED
;
1589 await removeExpiredReservations(chargingStation
);
1590 switch (chargingStation
.getConnectorStatus(connectorId
)!.status) {
1591 case OCPP16ChargePointStatus
.Faulted
:
1592 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
;
1594 case OCPP16ChargePointStatus
.Preparing
:
1595 case OCPP16ChargePointStatus
.Charging
:
1596 case OCPP16ChargePointStatus
.SuspendedEV
:
1597 case OCPP16ChargePointStatus
.SuspendedEVSE
:
1598 case OCPP16ChargePointStatus
.Finishing
:
1599 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1601 case OCPP16ChargePointStatus
.Unavailable
:
1602 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_UNAVAILABLE
;
1604 case OCPP16ChargePointStatus
.Reserved
:
1605 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
, connectorId
)) {
1606 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1609 // eslint-disable-next-line no-fallthrough
1611 if (!chargingStation
.isConnectorReservable(reservationId
, idTag
)) {
1612 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_OCCUPIED
;
1615 await chargingStation
.addReservation({
1616 id
: commandPayload
.reservationId
,
1619 response
= OCPP16Constants
.OCPP_RESERVATION_RESPONSE_ACCEPTED
;
1624 chargingStation
.getConnectorStatus(connectorId
)!.status = OCPP16ChargePointStatus
.Available
;
1625 return this.handleIncomingRequestError
<OCPP16ReserveNowResponse
>(
1627 OCPP16IncomingRequestCommand
.RESERVE_NOW
,
1629 { errorResponse
: OCPP16Constants
.OCPP_RESERVATION_RESPONSE_FAULTED
},
1634 private async handleRequestCancelReservation(
1635 chargingStation
: ChargingStation
,
1636 commandPayload
: OCPP16CancelReservationRequest
,
1637 ): Promise
<GenericResponse
> {
1639 !OCPP16ServiceUtils
.checkFeatureProfile(
1641 OCPP16SupportedFeatureProfiles
.Reservation
,
1642 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1645 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
;
1648 const { reservationId
} = commandPayload
;
1649 const reservation
= chargingStation
.getReservationBy('reservationId', reservationId
);
1650 if (isUndefined(reservation
)) {
1652 `${chargingStation.logPrefix()} Reservation with id ${reservationId}
1653 does not exist on charging station`,
1655 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
;
1657 await chargingStation
.removeReservation(
1659 ReservationTerminationReason
.RESERVATION_CANCELED
,
1661 return OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED
;
1663 return this.handleIncomingRequestError
<GenericResponse
>(
1665 OCPP16IncomingRequestCommand
.CANCEL_RESERVATION
,
1667 { errorResponse
: OCPP16Constants
.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED
},