1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
4 import path from
'path';
5 import { URL
, fileURLToPath
} from
'url';
7 import { JSONSchemaType
} from
'ajv';
8 import { Client
, FTPResponse
} from
'basic-ftp';
11 import OCPPError from
'../../../exception/OCPPError';
12 import { JsonType
} from
'../../../types/JsonType';
13 import { OCPP16ChargePointErrorCode
} from
'../../../types/ocpp/1.6/ChargePointErrorCode';
14 import { OCPP16ChargePointStatus
} from
'../../../types/ocpp/1.6/ChargePointStatus';
16 ChargingProfilePurposeType
,
17 OCPP16ChargingProfile
,
18 } from
'../../../types/ocpp/1.6/ChargingProfile';
20 OCPP16StandardParametersKey
,
21 OCPP16SupportedFeatureProfiles
,
22 } from
'../../../types/ocpp/1.6/Configuration';
23 import { OCPP16DiagnosticsStatus
} from
'../../../types/ocpp/1.6/DiagnosticsStatus';
25 OCPP16MeterValuesRequest
,
26 OCPP16MeterValuesResponse
,
27 } from
'../../../types/ocpp/1.6/MeterValues';
29 ChangeAvailabilityRequest
,
30 ChangeConfigurationRequest
,
31 ClearChargingProfileRequest
,
32 DiagnosticsStatusNotificationRequest
,
33 GetConfigurationRequest
,
34 GetDiagnosticsRequest
,
36 OCPP16AvailabilityType
,
37 OCPP16BootNotificationRequest
,
38 OCPP16ClearCacheRequest
,
39 OCPP16HeartbeatRequest
,
40 OCPP16IncomingRequestCommand
,
42 OCPP16StatusNotificationRequest
,
43 OCPP16TriggerMessageRequest
,
44 RemoteStartTransactionRequest
,
45 RemoteStopTransactionRequest
,
47 SetChargingProfileRequest
,
48 UnlockConnectorRequest
,
49 } from
'../../../types/ocpp/1.6/Requests';
51 ChangeAvailabilityResponse
,
52 ChangeConfigurationResponse
,
53 ClearChargingProfileResponse
,
54 DiagnosticsStatusNotificationResponse
,
55 GetConfigurationResponse
,
56 GetDiagnosticsResponse
,
57 OCPP16BootNotificationResponse
,
58 OCPP16HeartbeatResponse
,
59 OCPP16StatusNotificationResponse
,
60 OCPP16TriggerMessageResponse
,
61 SetChargingProfileResponse
,
62 UnlockConnectorResponse
,
63 } from
'../../../types/ocpp/1.6/Responses';
65 OCPP16AuthorizationStatus
,
66 OCPP16AuthorizeRequest
,
67 OCPP16AuthorizeResponse
,
68 OCPP16StartTransactionRequest
,
69 OCPP16StartTransactionResponse
,
70 OCPP16StopTransactionReason
,
71 OCPP16StopTransactionRequest
,
72 OCPP16StopTransactionResponse
,
73 } from
'../../../types/ocpp/1.6/Transaction';
74 import { OCPPConfigurationKey
} from
'../../../types/ocpp/Configuration';
75 import { ErrorType
} from
'../../../types/ocpp/ErrorType';
76 import { IncomingRequestHandler
} from
'../../../types/ocpp/Requests';
77 import { DefaultResponse
} from
'../../../types/ocpp/Responses';
78 import Constants from
'../../../utils/Constants';
79 import logger from
'../../../utils/Logger';
80 import Utils from
'../../../utils/Utils';
81 import type ChargingStation from
'../../ChargingStation';
82 import { ChargingStationConfigurationUtils
} from
'../../ChargingStationConfigurationUtils';
83 import { ChargingStationUtils
} from
'../../ChargingStationUtils';
84 import OCPPIncomingRequestService from
'../OCPPIncomingRequestService';
85 import { OCPP16ServiceUtils
} from
'./OCPP16ServiceUtils';
87 const moduleName
= 'OCPP16IncomingRequestService';
89 export default class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
90 private incomingRequestHandlers
: Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>;
91 private resetJsonSchema
: JSONSchemaType
<ResetRequest
>;
92 private clearCacheJsonSchema
: JSONSchemaType
<OCPP16ClearCacheRequest
>;
93 private getConfigurationJsonSchema
: JSONSchemaType
<GetConfigurationRequest
>;
94 private changeConfigurationJsonSchema
: JSONSchemaType
<ChangeConfigurationRequest
>;
95 private unlockConnectorJsonSchema
: JSONSchemaType
<UnlockConnectorRequest
>;
96 private getDiagnosticsJsonSchema
: JSONSchemaType
<GetDiagnosticsRequest
>;
97 private setChargingProfileJsonSchema
: JSONSchemaType
<SetChargingProfileRequest
>;
98 private clearChargingProfileJsonSchema
: JSONSchemaType
<ClearChargingProfileRequest
>;
99 private changeAvailabilityJsonSchema
: JSONSchemaType
<ChangeAvailabilityRequest
>;
100 private remoteStartTransactionJsonSchema
: JSONSchemaType
<RemoteStartTransactionRequest
>;
101 private remoteStopTransactionJsonSchema
: JSONSchemaType
<RemoteStopTransactionRequest
>;
102 private triggerMessageJsonSchema
: JSONSchemaType
<OCPP16TriggerMessageRequest
>;
104 public constructor() {
105 if (new.target
?.name
=== moduleName
) {
106 throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
109 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
110 [OCPP16IncomingRequestCommand
.RESET
, this.handleRequestReset
.bind(this)],
111 [OCPP16IncomingRequestCommand
.CLEAR_CACHE
, this.handleRequestClearCache
.bind(this)],
112 [OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
, this.handleRequestUnlockConnector
.bind(this)],
114 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
115 this.handleRequestGetConfiguration
.bind(this),
118 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
119 this.handleRequestChangeConfiguration
.bind(this),
122 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
123 this.handleRequestSetChargingProfile
.bind(this),
126 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
127 this.handleRequestClearChargingProfile
.bind(this),
130 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
131 this.handleRequestChangeAvailability
.bind(this),
134 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
135 this.handleRequestRemoteStartTransaction
.bind(this),
138 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
139 this.handleRequestRemoteStopTransaction
.bind(this),
141 [OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
, this.handleRequestGetDiagnostics
.bind(this)],
142 [OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
, this.handleRequestTriggerMessage
.bind(this)],
144 this.resetJsonSchema
= JSON
.parse(
147 path
.dirname(fileURLToPath(import.meta
.url
)),
148 '../../../assets/json-schemas/ocpp/1.6/Reset.json'
152 ) as JSONSchemaType
<ResetRequest
>;
153 this.clearCacheJsonSchema
= JSON
.parse(
156 path
.dirname(fileURLToPath(import.meta
.url
)),
157 '../../../assets/json-schemas/ocpp/1.6/ClearCache.json'
161 ) as JSONSchemaType
<OCPP16ClearCacheRequest
>;
162 this.getConfigurationJsonSchema
= JSON
.parse(
165 path
.dirname(fileURLToPath(import.meta
.url
)),
166 '../../../assets/json-schemas/ocpp/1.6/GetConfiguration.json'
170 ) as JSONSchemaType
<GetConfigurationRequest
>;
171 this.changeConfigurationJsonSchema
= JSON
.parse(
174 path
.dirname(fileURLToPath(import.meta
.url
)),
175 '../../../assets/json-schemas/ocpp/1.6/ChangeConfiguration.json'
179 ) as JSONSchemaType
<ChangeConfigurationRequest
>;
180 this.unlockConnectorJsonSchema
= JSON
.parse(
183 path
.dirname(fileURLToPath(import.meta
.url
)),
184 '../../../assets/json-schemas/ocpp/1.6/UnlockConnector.json'
188 ) as JSONSchemaType
<UnlockConnectorRequest
>;
189 this.getDiagnosticsJsonSchema
= JSON
.parse(
192 path
.dirname(fileURLToPath(import.meta
.url
)),
193 '../../../assets/json-schemas/ocpp/1.6/GetDiagnostics.json'
197 ) as JSONSchemaType
<GetDiagnosticsRequest
>;
198 this.setChargingProfileJsonSchema
= JSON
.parse(
201 path
.dirname(fileURLToPath(import.meta
.url
)),
202 '../../../assets/json-schemas/ocpp/1.6/SetChargingProfile.json'
206 ) as JSONSchemaType
<SetChargingProfileRequest
>;
207 this.clearChargingProfileJsonSchema
= JSON
.parse(
210 path
.dirname(fileURLToPath(import.meta
.url
)),
211 '../../../assets/json-schemas/ocpp/1.6/ClearChargingProfile.json'
215 ) as JSONSchemaType
<ClearChargingProfileRequest
>;
216 this.changeAvailabilityJsonSchema
= JSON
.parse(
219 path
.dirname(fileURLToPath(import.meta
.url
)),
220 '../../../assets/json-schemas/ocpp/1.6/ChangeAvailability.json'
224 ) as JSONSchemaType
<ChangeAvailabilityRequest
>;
225 this.remoteStartTransactionJsonSchema
= JSON
.parse(
228 path
.dirname(fileURLToPath(import.meta
.url
)),
229 '../../../assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json'
233 ) as JSONSchemaType
<RemoteStartTransactionRequest
>;
234 this.remoteStopTransactionJsonSchema
= JSON
.parse(
237 path
.dirname(fileURLToPath(import.meta
.url
)),
238 '../../../assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json'
242 ) as JSONSchemaType
<RemoteStopTransactionRequest
>;
243 this.triggerMessageJsonSchema
= JSON
.parse(
246 path
.dirname(fileURLToPath(import.meta
.url
)),
247 '../../../assets/json-schemas/ocpp/1.6/TriggerMessage.json'
251 ) as JSONSchemaType
<OCPP16TriggerMessageRequest
>;
254 public async incomingRequestHandler(
255 chargingStation
: ChargingStation
,
257 commandName
: OCPP16IncomingRequestCommand
,
258 commandPayload
: JsonType
260 let response
: JsonType
;
262 chargingStation
.getOcppStrictCompliance() &&
263 chargingStation
.isInPendingState() &&
264 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
265 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
268 ErrorType
.SECURITY_ERROR
,
269 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
273 )} while the charging station is in pending state on the central server`,
279 chargingStation
.isRegistered() ||
280 (!chargingStation
.getOcppStrictCompliance() && chargingStation
.isInUnknownState())
283 this.incomingRequestHandlers
.has(commandName
) &&
284 ChargingStationUtils
.isIncomingRequestCommandSupported(commandName
, chargingStation
)
287 // Call the method to build the response
288 response
= await this.incomingRequestHandlers
.get(commandName
)(
294 logger
.error(chargingStation
.logPrefix() + ' Handle request error: %j', error
);
300 ErrorType
.NOT_IMPLEMENTED
,
301 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
312 ErrorType
.SECURITY_ERROR
,
313 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
317 )} while the charging station is not registered on the central server.`,
322 // Send the built response
323 await chargingStation
.ocppRequestService
.sendResponse(
331 // Simulate charging station restart
332 private handleRequestReset(
333 chargingStation
: ChargingStation
,
334 commandPayload
: ResetRequest
336 this.validateIncomingRequestPayload(
338 OCPP16IncomingRequestCommand
.RESET
,
339 this.resetJsonSchema
,
342 // eslint-disable-next-line @typescript-eslint/no-misused-promises
343 setImmediate(async (): Promise
<void> => {
344 await chargingStation
.reset((commandPayload
.type + 'Reset') as OCPP16StopTransactionReason
);
347 `${chargingStation.logPrefix()} ${
349 } reset command received, simulating it. The station will be back online in ${Utils.formatDurationMilliSeconds(
350 chargingStation.stationInfo.resetTime
353 return Constants
.OCPP_RESPONSE_ACCEPTED
;
356 private handleRequestClearCache(
357 chargingStation
: ChargingStation
,
358 commandPayload
: OCPP16ClearCacheRequest
360 this.validateIncomingRequestPayload(
362 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
363 this.clearCacheJsonSchema
,
366 return Constants
.OCPP_RESPONSE_ACCEPTED
;
369 private async handleRequestUnlockConnector(
370 chargingStation
: ChargingStation
,
371 commandPayload
: UnlockConnectorRequest
372 ): Promise
<UnlockConnectorResponse
> {
373 this.validateIncomingRequestPayload(
375 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
376 this.unlockConnectorJsonSchema
,
379 const connectorId
= commandPayload
.connectorId
;
380 if (connectorId
=== 0) {
382 chargingStation
.logPrefix() + ' Trying to unlock connector ' + connectorId
.toString()
384 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
386 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
387 const transactionId
= chargingStation
.getConnectorStatus(connectorId
).transactionId
;
389 chargingStation
.getBeginEndMeterValues() &&
390 chargingStation
.getOcppStrictCompliance() &&
391 !chargingStation
.getOutOfOrderEndMeterValues()
393 // FIXME: Implement OCPP version agnostic helpers
394 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
397 chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
)
399 await chargingStation
.ocppRequestService
.requestHandler
<
400 OCPP16MeterValuesRequest
,
401 OCPP16MeterValuesResponse
402 >(chargingStation
, OCPP16RequestCommand
.METER_VALUES
, {
405 meterValue
: [transactionEndMeterValue
],
408 const stopResponse
= await chargingStation
.ocppRequestService
.requestHandler
<
409 OCPP16StopTransactionRequest
,
410 OCPP16StopTransactionResponse
411 >(chargingStation
, OCPP16RequestCommand
.STOP_TRANSACTION
, {
413 meterStop
: chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
414 idTag
: chargingStation
.getTransactionIdTag(transactionId
),
415 reason
: OCPP16StopTransactionReason
.UNLOCK_COMMAND
,
417 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
418 return Constants
.OCPP_RESPONSE_UNLOCKED
;
420 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
422 await chargingStation
.ocppRequestService
.requestHandler
<
423 OCPP16StatusNotificationRequest
,
424 OCPP16StatusNotificationResponse
425 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
427 status: OCPP16ChargePointStatus
.AVAILABLE
,
428 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
430 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
431 return Constants
.OCPP_RESPONSE_UNLOCKED
;
434 private handleRequestGetConfiguration(
435 chargingStation
: ChargingStation
,
436 commandPayload
: GetConfigurationRequest
437 ): GetConfigurationResponse
{
438 this.validateIncomingRequestPayload(
440 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
441 this.getConfigurationJsonSchema
,
444 const configurationKey
: OCPPConfigurationKey
[] = [];
445 const unknownKey
: string[] = [];
446 if (Utils
.isEmptyArray(commandPayload
.key
)) {
447 for (const configuration
of chargingStation
.ocppConfiguration
.configurationKey
) {
448 if (Utils
.isUndefined(configuration
.visible
)) {
449 configuration
.visible
= true;
451 if (!configuration
.visible
) {
454 configurationKey
.push({
455 key
: configuration
.key
,
456 readonly: configuration
.readonly,
457 value
: configuration
.value
,
461 for (const key
of commandPayload
.key
) {
462 const keyFound
= ChargingStationConfigurationUtils
.getConfigurationKey(
467 if (Utils
.isUndefined(keyFound
.visible
)) {
468 keyFound
.visible
= true;
470 if (!keyFound
.visible
) {
473 configurationKey
.push({
475 readonly: keyFound
.readonly,
476 value
: keyFound
.value
,
479 unknownKey
.push(key
);
489 private handleRequestChangeConfiguration(
490 chargingStation
: ChargingStation
,
491 commandPayload
: ChangeConfigurationRequest
492 ): ChangeConfigurationResponse
{
493 this.validateIncomingRequestPayload(
495 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
496 this.changeConfigurationJsonSchema
,
499 const keyToChange
= ChargingStationConfigurationUtils
.getConfigurationKey(
505 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
506 } else if (keyToChange
&& keyToChange
.readonly) {
507 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
508 } else if (keyToChange
&& !keyToChange
.readonly) {
509 let valueChanged
= false;
510 if (keyToChange
.value
!== commandPayload
.value
) {
511 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
514 commandPayload
.value
,
519 let triggerHeartbeatRestart
= false;
520 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
521 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
523 OCPP16StandardParametersKey
.HeartbeatInterval
,
526 triggerHeartbeatRestart
= true;
528 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
529 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
531 OCPP16StandardParametersKey
.HeartBeatInterval
,
534 triggerHeartbeatRestart
= true;
536 if (triggerHeartbeatRestart
) {
537 chargingStation
.restartHeartbeat();
539 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
540 chargingStation
.restartWebSocketPing();
542 if (keyToChange
.reboot
) {
543 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
545 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
549 private handleRequestSetChargingProfile(
550 chargingStation
: ChargingStation
,
551 commandPayload
: SetChargingProfileRequest
552 ): SetChargingProfileResponse
{
553 this.validateIncomingRequestPayload(
555 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
556 this.setChargingProfileJsonSchema
,
560 !OCPP16ServiceUtils
.checkFeatureProfile(
562 OCPP16SupportedFeatureProfiles
.SmartCharging
,
563 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
566 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
568 if (!chargingStation
.getConnectorStatus(commandPayload
.connectorId
)) {
570 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${
571 commandPayload.connectorId
574 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
577 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
578 ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
579 commandPayload
.connectorId
!== 0
581 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
584 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
585 ChargingProfilePurposeType
.TX_PROFILE
&&
586 (commandPayload
.connectorId
=== 0 ||
587 !chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
)
589 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
591 chargingStation
.setChargingProfile(
592 commandPayload
.connectorId
,
593 commandPayload
.csChargingProfiles
596 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${
597 commandPayload.connectorId
598 }, dump their stack: %j`,
599 chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
601 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
604 private handleRequestClearChargingProfile(
605 chargingStation
: ChargingStation
,
606 commandPayload
: ClearChargingProfileRequest
607 ): ClearChargingProfileResponse
{
608 this.validateIncomingRequestPayload(
610 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
611 this.clearChargingProfileJsonSchema
,
615 !OCPP16ServiceUtils
.checkFeatureProfile(
617 OCPP16SupportedFeatureProfiles
.SmartCharging
,
618 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
621 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
623 const connectorStatus
= chargingStation
.getConnectorStatus(commandPayload
.connectorId
);
624 if (!connectorStatus
) {
626 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${
627 commandPayload.connectorId
630 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
632 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(connectorStatus
.chargingProfiles
)) {
633 connectorStatus
.chargingProfiles
= [];
635 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${
636 commandPayload.connectorId
637 }, dump their stack: %j`,
638 connectorStatus
.chargingProfiles
640 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
642 if (!commandPayload
.connectorId
) {
643 let clearedCP
= false;
644 for (const connectorId
of chargingStation
.connectors
.keys()) {
645 if (!Utils
.isEmptyArray(chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
)) {
647 .getConnectorStatus(connectorId
)
648 .chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
649 let clearCurrentCP
= false;
650 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
651 clearCurrentCP
= true;
654 !commandPayload
.chargingProfilePurpose
&&
655 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
657 clearCurrentCP
= true;
660 !chargingProfile
.stackLevel
&&
661 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
663 clearCurrentCP
= true;
666 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&&
667 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
669 clearCurrentCP
= true;
671 if (clearCurrentCP
) {
672 connectorStatus
.chargingProfiles
.splice(index
, 1);
674 `${chargingStation.logPrefix()} Matching charging profile(s) cleared on connector id ${
675 commandPayload.connectorId
676 }, dump their stack: %j`,
677 connectorStatus
.chargingProfiles
685 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
688 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
691 private async handleRequestChangeAvailability(
692 chargingStation
: ChargingStation
,
693 commandPayload
: ChangeAvailabilityRequest
694 ): Promise
<ChangeAvailabilityResponse
> {
695 this.validateIncomingRequestPayload(
697 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
698 this.changeAvailabilityJsonSchema
,
701 const connectorId
: number = commandPayload
.connectorId
;
702 if (!chargingStation
.getConnectorStatus(connectorId
)) {
704 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`
706 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
708 const chargePointStatus
: OCPP16ChargePointStatus
=
709 commandPayload
.type === OCPP16AvailabilityType
.OPERATIVE
710 ? OCPP16ChargePointStatus
.AVAILABLE
711 : OCPP16ChargePointStatus
.UNAVAILABLE
;
712 if (connectorId
=== 0) {
713 let response
: ChangeAvailabilityResponse
= Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
714 for (const id
of chargingStation
.connectors
.keys()) {
715 if (chargingStation
.getConnectorStatus(id
)?.transactionStarted
) {
716 response
= Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
718 chargingStation
.getConnectorStatus(id
).availability
= commandPayload
.type;
719 if (response
=== Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
) {
720 await chargingStation
.ocppRequestService
.requestHandler
<
721 OCPP16StatusNotificationRequest
,
722 OCPP16StatusNotificationResponse
723 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
725 status: chargePointStatus
,
726 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
728 chargingStation
.getConnectorStatus(id
).status = chargePointStatus
;
734 (chargingStation
.getConnectorStatus(0).availability
=== OCPP16AvailabilityType
.OPERATIVE
||
735 (chargingStation
.getConnectorStatus(0).availability
===
736 OCPP16AvailabilityType
.INOPERATIVE
&&
737 commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))
739 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
740 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
741 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
743 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
744 await chargingStation
.ocppRequestService
.requestHandler
<
745 OCPP16StatusNotificationRequest
,
746 OCPP16StatusNotificationResponse
747 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
749 status: chargePointStatus
,
750 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
752 chargingStation
.getConnectorStatus(connectorId
).status = chargePointStatus
;
753 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
755 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
758 private async handleRequestRemoteStartTransaction(
759 chargingStation
: ChargingStation
,
760 commandPayload
: RemoteStartTransactionRequest
761 ): Promise
<DefaultResponse
> {
762 this.validateIncomingRequestPayload(
764 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
765 this.remoteStartTransactionJsonSchema
,
768 const transactionConnectorId
= commandPayload
.connectorId
;
769 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
);
770 if (transactionConnectorId
) {
771 await chargingStation
.ocppRequestService
.requestHandler
<
772 OCPP16StatusNotificationRequest
,
773 OCPP16StatusNotificationResponse
774 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
775 connectorId
: transactionConnectorId
,
776 status: OCPP16ChargePointStatus
.PREPARING
,
777 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
779 connectorStatus
.status = OCPP16ChargePointStatus
.PREPARING
;
780 if (chargingStation
.isChargingStationAvailable() && connectorStatus
) {
781 // Check if authorized
782 if (chargingStation
.getAuthorizeRemoteTxRequests()) {
783 let authorized
= false;
785 chargingStation
.getLocalAuthListEnabled() &&
786 chargingStation
.hasAuthorizedTags() &&
787 chargingStation
.authorizedTagsCache
789 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
791 .find((value
) => value
=== commandPayload
.idTag
)
793 connectorStatus
.localAuthorizeIdTag
= commandPayload
.idTag
;
794 connectorStatus
.idTagLocalAuthorized
= true;
796 } else if (chargingStation
.getMayAuthorizeAtRemoteStart()) {
797 connectorStatus
.authorizeIdTag
= commandPayload
.idTag
;
798 const authorizeResponse
: OCPP16AuthorizeResponse
=
799 await chargingStation
.ocppRequestService
.requestHandler
<
800 OCPP16AuthorizeRequest
,
801 OCPP16AuthorizeResponse
802 >(chargingStation
, OCPP16RequestCommand
.AUTHORIZE
, {
803 idTag
: commandPayload
.idTag
,
805 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
810 `${chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`
814 // Authorization successful, start transaction
816 this.setRemoteStartTransactionChargingProfile(
818 transactionConnectorId
,
819 commandPayload
.chargingProfile
822 connectorStatus
.transactionRemoteStarted
= true;
825 await chargingStation
.ocppRequestService
.requestHandler
<
826 OCPP16StartTransactionRequest
,
827 OCPP16StartTransactionResponse
828 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
829 connectorId
: transactionConnectorId
,
830 idTag
: commandPayload
.idTag
,
832 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
835 chargingStation
.logPrefix() +
836 ' Transaction remotely STARTED on ' +
837 chargingStation
.stationInfo
.chargingStationId
+
839 transactionConnectorId
.toString() +
843 return Constants
.OCPP_RESPONSE_ACCEPTED
;
845 return this.notifyRemoteStartTransactionRejected(
847 transactionConnectorId
,
851 return this.notifyRemoteStartTransactionRejected(
853 transactionConnectorId
,
857 return this.notifyRemoteStartTransactionRejected(
859 transactionConnectorId
,
863 // No authorization check required, start transaction
865 this.setRemoteStartTransactionChargingProfile(
867 transactionConnectorId
,
868 commandPayload
.chargingProfile
871 connectorStatus
.transactionRemoteStarted
= true;
874 await chargingStation
.ocppRequestService
.requestHandler
<
875 OCPP16StartTransactionRequest
,
876 OCPP16StartTransactionResponse
877 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
878 connectorId
: transactionConnectorId
,
879 idTag
: commandPayload
.idTag
,
881 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
884 chargingStation
.logPrefix() +
885 ' Transaction remotely STARTED on ' +
886 chargingStation
.stationInfo
.chargingStationId
+
888 transactionConnectorId
.toString() +
892 return Constants
.OCPP_RESPONSE_ACCEPTED
;
894 return this.notifyRemoteStartTransactionRejected(
896 transactionConnectorId
,
900 return this.notifyRemoteStartTransactionRejected(
902 transactionConnectorId
,
906 return this.notifyRemoteStartTransactionRejected(
908 transactionConnectorId
,
912 return this.notifyRemoteStartTransactionRejected(
914 transactionConnectorId
,
919 private async notifyRemoteStartTransactionRejected(
920 chargingStation
: ChargingStation
,
923 ): Promise
<DefaultResponse
> {
925 chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
927 await chargingStation
.ocppRequestService
.requestHandler
<
928 OCPP16StatusNotificationRequest
,
929 OCPP16StatusNotificationResponse
930 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
932 status: OCPP16ChargePointStatus
.AVAILABLE
,
933 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
935 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
938 chargingStation
.logPrefix() +
939 ' Remote starting transaction REJECTED on connector Id ' +
940 connectorId
.toString() +
944 chargingStation
.getConnectorStatus(connectorId
).availability
+
946 chargingStation
.getConnectorStatus(connectorId
).status
948 return Constants
.OCPP_RESPONSE_REJECTED
;
951 private setRemoteStartTransactionChargingProfile(
952 chargingStation
: ChargingStation
,
954 cp
: OCPP16ChargingProfile
956 if (cp
&& cp
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
957 chargingStation
.setChargingProfile(connectorId
, cp
);
959 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}, dump their stack: %j`,
960 chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
963 } else if (cp
&& cp
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
965 `${chargingStation.logPrefix()} Not allowed to set ${
966 cp.chargingProfilePurpose
967 } charging profile(s) at remote start transaction`
975 private async handleRequestRemoteStopTransaction(
976 chargingStation
: ChargingStation
,
977 commandPayload
: RemoteStopTransactionRequest
978 ): Promise
<DefaultResponse
> {
979 this.validateIncomingRequestPayload(
981 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
982 this.remoteStopTransactionJsonSchema
,
985 const transactionId
= commandPayload
.transactionId
;
986 for (const connectorId
of chargingStation
.connectors
.keys()) {
989 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
991 await chargingStation
.ocppRequestService
.requestHandler
<
992 OCPP16StatusNotificationRequest
,
993 OCPP16StatusNotificationResponse
994 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
996 status: OCPP16ChargePointStatus
.FINISHING
,
997 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
999 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.FINISHING
;
1001 chargingStation
.getBeginEndMeterValues() &&
1002 chargingStation
.getOcppStrictCompliance() &&
1003 !chargingStation
.getOutOfOrderEndMeterValues()
1005 // FIXME: Implement OCPP version agnostic helpers
1006 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
1009 chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
)
1011 await chargingStation
.ocppRequestService
.requestHandler
<
1012 OCPP16MeterValuesRequest
,
1013 OCPP16MeterValuesResponse
1014 >(chargingStation
, OCPP16RequestCommand
.METER_VALUES
, {
1017 meterValue
: [transactionEndMeterValue
],
1020 await chargingStation
.ocppRequestService
.requestHandler
<
1021 OCPP16StopTransactionRequest
,
1022 OCPP16StopTransactionResponse
1023 >(chargingStation
, OCPP16RequestCommand
.STOP_TRANSACTION
, {
1025 meterStop
: chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1026 idTag
: chargingStation
.getTransactionIdTag(transactionId
),
1028 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1032 chargingStation
.logPrefix() +
1033 ' Trying to remote stop a non existing transaction ' +
1034 transactionId
.toString()
1036 return Constants
.OCPP_RESPONSE_REJECTED
;
1039 private async handleRequestGetDiagnostics(
1040 chargingStation
: ChargingStation
,
1041 commandPayload
: GetDiagnosticsRequest
1042 ): Promise
<GetDiagnosticsResponse
> {
1043 this.validateIncomingRequestPayload(
1045 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1046 this.getDiagnosticsJsonSchema
,
1050 !OCPP16ServiceUtils
.checkFeatureProfile(
1052 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1053 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1056 return Constants
.OCPP_RESPONSE_EMPTY
;
1059 chargingStation
.logPrefix() +
1061 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
+
1062 ' request received: %j',
1065 const uri
= new URL(commandPayload
.location
);
1066 if (uri
.protocol
.startsWith('ftp:')) {
1067 let ftpClient
: Client
;
1070 .readdirSync(path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'))
1071 .filter((file
) => file
.endsWith('.log'))
1072 .map((file
) => path
.join('./', file
));
1073 const diagnosticsArchive
= chargingStation
.stationInfo
.chargingStationId
+ '_logs.tar.gz';
1074 tar
.create({ gzip
: true }, logFiles
).pipe(fs
.createWriteStream(diagnosticsArchive
));
1075 ftpClient
= new Client();
1076 const accessResponse
= await ftpClient
.access({
1078 ...(!Utils
.isEmptyString(uri
.port
) && { port
: Utils
.convertToInt(uri
.port
) }),
1079 ...(!Utils
.isEmptyString(uri
.username
) && { user
: uri
.username
}),
1080 ...(!Utils
.isEmptyString(uri
.password
) && { password
: uri
.password
}),
1082 let uploadResponse
: FTPResponse
;
1083 if (accessResponse
.code
=== 220) {
1084 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1085 ftpClient
.trackProgress(async (info
) => {
1087 `${chargingStation.logPrefix()} ${
1089 } bytes transferred from diagnostics archive ${info.name}`
1091 await chargingStation
.ocppRequestService
.requestHandler
<
1092 DiagnosticsStatusNotificationRequest
,
1093 DiagnosticsStatusNotificationResponse
1094 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1095 status: OCPP16DiagnosticsStatus
.Uploading
,
1098 uploadResponse
= await ftpClient
.uploadFrom(
1100 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'),
1103 uri
.pathname
+ diagnosticsArchive
1105 if (uploadResponse
.code
=== 226) {
1106 await chargingStation
.ocppRequestService
.requestHandler
<
1107 DiagnosticsStatusNotificationRequest
,
1108 DiagnosticsStatusNotificationResponse
1109 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1110 status: OCPP16DiagnosticsStatus
.Uploaded
,
1115 return { fileName
: diagnosticsArchive
};
1117 throw new OCPPError(
1118 ErrorType
.GENERIC_ERROR
,
1119 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1120 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1122 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1125 throw new OCPPError(
1126 ErrorType
.GENERIC_ERROR
,
1127 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1128 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1130 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1133 await chargingStation
.ocppRequestService
.requestHandler
<
1134 DiagnosticsStatusNotificationRequest
,
1135 DiagnosticsStatusNotificationResponse
1136 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1137 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1142 return this.handleIncomingRequestError(
1144 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1146 { errorResponse
: Constants
.OCPP_RESPONSE_EMPTY
}
1151 `${chargingStation.logPrefix()} Unsupported protocol ${
1153 } to transfer the diagnostic logs archive`
1155 await chargingStation
.ocppRequestService
.requestHandler
<
1156 DiagnosticsStatusNotificationRequest
,
1157 DiagnosticsStatusNotificationResponse
1158 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1159 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1161 return Constants
.OCPP_RESPONSE_EMPTY
;
1165 private handleRequestTriggerMessage(
1166 chargingStation
: ChargingStation
,
1167 commandPayload
: OCPP16TriggerMessageRequest
1168 ): OCPP16TriggerMessageResponse
{
1169 this.validateIncomingRequestPayload(
1171 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1172 this.triggerMessageJsonSchema
,
1176 !OCPP16ServiceUtils
.checkFeatureProfile(
1178 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1179 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1182 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1184 // TODO: factor out the check on connector id
1185 if (commandPayload
?.connectorId
< 0) {
1187 `${chargingStation.logPrefix()} ${
1188 OCPP16IncomingRequestCommand.TRIGGER_MESSAGE
1189 } incoming request received with invalid connectorId ${commandPayload.connectorId}`
1191 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1194 switch (commandPayload
.requestedMessage
) {
1195 case MessageTrigger
.BootNotification
:
1197 chargingStation
.ocppRequestService
1198 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1200 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1202 chargePointModel
: chargingStation
.getBootNotificationRequest().chargePointModel
,
1203 chargePointVendor
: chargingStation
.getBootNotificationRequest().chargePointVendor
,
1204 chargeBoxSerialNumber
:
1205 chargingStation
.getBootNotificationRequest().chargeBoxSerialNumber
,
1206 firmwareVersion
: chargingStation
.getBootNotificationRequest().firmwareVersion
,
1207 chargePointSerialNumber
:
1208 chargingStation
.getBootNotificationRequest().chargePointSerialNumber
,
1209 iccid
: chargingStation
.getBootNotificationRequest().iccid
,
1210 imsi
: chargingStation
.getBootNotificationRequest().imsi
,
1211 meterSerialNumber
: chargingStation
.getBootNotificationRequest().meterSerialNumber
,
1212 meterType
: chargingStation
.getBootNotificationRequest().meterType
,
1214 { skipBufferingOnError
: true, triggerMessage
: true }
1217 chargingStation
.bootNotificationResponse
= value
;
1220 /* This is intentional */
1222 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1223 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1224 case MessageTrigger
.Heartbeat
:
1226 chargingStation
.ocppRequestService
1227 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1229 OCPP16RequestCommand
.HEARTBEAT
,
1232 triggerMessage
: true,
1236 /* This is intentional */
1238 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1239 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1240 case MessageTrigger
.StatusNotification
:
1242 if (commandPayload
?.connectorId
) {
1243 chargingStation
.ocppRequestService
1244 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1246 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1248 connectorId
: commandPayload
.connectorId
,
1249 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1250 status: chargingStation
.getConnectorStatus(commandPayload
.connectorId
).status,
1253 triggerMessage
: true,
1257 /* This is intentional */
1260 for (const connectorId
of chargingStation
.connectors
.keys()) {
1261 chargingStation
.ocppRequestService
1263 OCPP16StatusNotificationRequest
,
1264 OCPP16StatusNotificationResponse
1267 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1270 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1271 status: chargingStation
.getConnectorStatus(connectorId
).status,
1274 triggerMessage
: true,
1278 /* This is intentional */
1282 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1283 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1285 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1288 return this.handleIncomingRequestError(
1290 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1292 { errorResponse
: Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
}