1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
4 import path from
'path';
5 import { URL
, fileURLToPath
} from
'url';
7 import type { JSONSchemaType
} from
'ajv';
8 import { Client
, FTPResponse
} from
'basic-ftp';
11 import OCPPError from
'../../../exception/OCPPError';
12 import type { JsonObject
, 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 type { OCPPConfigurationKey
} from
'../../../types/ocpp/Configuration';
75 import { ErrorType
} from
'../../../types/ocpp/ErrorType';
76 import type { IncomingRequestHandler
} from
'../../../types/ocpp/Requests';
77 import type { 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 jsonSchemas
: Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>;
93 public constructor() {
94 if (new.target
?.name
=== moduleName
) {
95 throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
98 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
99 [OCPP16IncomingRequestCommand
.RESET
, this.handleRequestReset
.bind(this)],
100 [OCPP16IncomingRequestCommand
.CLEAR_CACHE
, this.handleRequestClearCache
.bind(this)],
101 [OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
, this.handleRequestUnlockConnector
.bind(this)],
103 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
104 this.handleRequestGetConfiguration
.bind(this),
107 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
108 this.handleRequestChangeConfiguration
.bind(this),
111 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
112 this.handleRequestSetChargingProfile
.bind(this),
115 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
116 this.handleRequestClearChargingProfile
.bind(this),
119 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
120 this.handleRequestChangeAvailability
.bind(this),
123 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
124 this.handleRequestRemoteStartTransaction
.bind(this),
127 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
128 this.handleRequestRemoteStopTransaction
.bind(this),
130 [OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
, this.handleRequestGetDiagnostics
.bind(this)],
131 [OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
, this.handleRequestTriggerMessage
.bind(this)],
133 this.jsonSchemas
= new Map
<OCPP16IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>([
135 OCPP16IncomingRequestCommand
.RESET
,
139 path
.dirname(fileURLToPath(import.meta
.url
)),
140 '../../../assets/json-schemas/ocpp/1.6/Reset.json'
144 ) as JSONSchemaType
<ResetRequest
>,
147 OCPP16IncomingRequestCommand
.CLEAR_CACHE
,
151 path
.dirname(fileURLToPath(import.meta
.url
)),
152 '../../../assets/json-schemas/ocpp/1.6/ClearCache.json'
156 ) as JSONSchemaType
<OCPP16ClearCacheRequest
>,
159 OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
,
163 path
.dirname(fileURLToPath(import.meta
.url
)),
164 '../../../assets/json-schemas/ocpp/1.6/UnlockConnector.json'
168 ) as JSONSchemaType
<UnlockConnectorRequest
>,
171 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
175 path
.dirname(fileURLToPath(import.meta
.url
)),
176 '../../../assets/json-schemas/ocpp/1.6/GetConfiguration.json'
180 ) as JSONSchemaType
<GetConfigurationRequest
>,
183 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
187 path
.dirname(fileURLToPath(import.meta
.url
)),
188 '../../../assets/json-schemas/ocpp/1.6/ChangeConfiguration.json'
192 ) as JSONSchemaType
<ChangeConfigurationRequest
>,
195 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
199 path
.dirname(fileURLToPath(import.meta
.url
)),
200 '../../../assets/json-schemas/ocpp/1.6/GetDiagnostics.json'
204 ) as JSONSchemaType
<GetDiagnosticsRequest
>,
207 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
211 path
.dirname(fileURLToPath(import.meta
.url
)),
212 '../../../assets/json-schemas/ocpp/1.6/SetChargingProfile.json'
216 ) as JSONSchemaType
<SetChargingProfileRequest
>,
219 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
223 path
.dirname(fileURLToPath(import.meta
.url
)),
224 '../../../assets/json-schemas/ocpp/1.6/ClearChargingProfile.json'
228 ) as JSONSchemaType
<ClearChargingProfileRequest
>,
231 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
235 path
.dirname(fileURLToPath(import.meta
.url
)),
236 '../../../assets/json-schemas/ocpp/1.6/ChangeAvailability.json'
240 ) as JSONSchemaType
<ChangeAvailabilityRequest
>,
243 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
247 path
.dirname(fileURLToPath(import.meta
.url
)),
248 '../../../assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json'
252 ) as JSONSchemaType
<RemoteStartTransactionRequest
>,
255 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
259 path
.dirname(fileURLToPath(import.meta
.url
)),
260 '../../../assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json'
264 ) as JSONSchemaType
<RemoteStopTransactionRequest
>,
267 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
271 path
.dirname(fileURLToPath(import.meta
.url
)),
272 '../../../assets/json-schemas/ocpp/1.6/TriggerMessage.json'
276 ) as JSONSchemaType
<OCPP16TriggerMessageRequest
>,
279 this.validatePayload
.bind(this);
282 public async incomingRequestHandler(
283 chargingStation
: ChargingStation
,
285 commandName
: OCPP16IncomingRequestCommand
,
286 commandPayload
: JsonType
288 let response
: JsonType
;
290 chargingStation
.getOcppStrictCompliance() &&
291 chargingStation
.isInPendingState() &&
292 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
293 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
296 ErrorType
.SECURITY_ERROR
,
297 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
301 )} while the charging station is in pending state on the central server`,
307 chargingStation
.isRegistered() ||
308 (!chargingStation
.getOcppStrictCompliance() && chargingStation
.isInUnknownState())
311 this.incomingRequestHandlers
.has(commandName
) &&
312 ChargingStationUtils
.isIncomingRequestCommandSupported(commandName
, chargingStation
)
315 this.validatePayload(chargingStation
, commandName
, commandPayload
);
316 // Call the method to build the response
317 response
= await this.incomingRequestHandlers
.get(commandName
)(
324 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
332 ErrorType
.NOT_IMPLEMENTED
,
333 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
344 ErrorType
.SECURITY_ERROR
,
345 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
349 )} while the charging station is not registered on the central server.`,
354 // Send the built response
355 await chargingStation
.ocppRequestService
.sendResponse(
363 private validatePayload(
364 chargingStation
: ChargingStation
,
365 commandName
: OCPP16IncomingRequestCommand
,
366 commandPayload
: JsonType
368 if (this.jsonSchemas
.has(commandName
)) {
369 return this.validateIncomingRequestPayload(
372 this.jsonSchemas
.get(commandName
),
377 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command ${commandName} PDU validation`
382 // Simulate charging station restart
383 private handleRequestReset(
384 chargingStation
: ChargingStation
,
385 commandPayload
: ResetRequest
387 // eslint-disable-next-line @typescript-eslint/no-misused-promises
388 setImmediate(async (): Promise
<void> => {
389 await chargingStation
.reset((commandPayload
.type + 'Reset') as OCPP16StopTransactionReason
);
392 `${chargingStation.logPrefix()} ${
394 } reset command received, simulating it. The station will be back online in ${Utils.formatDurationMilliSeconds(
395 chargingStation.stationInfo.resetTime
398 return Constants
.OCPP_RESPONSE_ACCEPTED
;
401 private handleRequestClearCache(): DefaultResponse
{
402 return Constants
.OCPP_RESPONSE_ACCEPTED
;
405 private async handleRequestUnlockConnector(
406 chargingStation
: ChargingStation
,
407 commandPayload
: UnlockConnectorRequest
408 ): Promise
<UnlockConnectorResponse
> {
409 const connectorId
= commandPayload
.connectorId
;
410 if (connectorId
=== 0) {
412 chargingStation
.logPrefix() + ' Trying to unlock connector ' + connectorId
.toString()
414 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
416 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
417 const transactionId
= chargingStation
.getConnectorStatus(connectorId
).transactionId
;
419 chargingStation
.getBeginEndMeterValues() &&
420 chargingStation
.getOcppStrictCompliance() &&
421 !chargingStation
.getOutOfOrderEndMeterValues()
423 // FIXME: Implement OCPP version agnostic helpers
424 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
427 chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
)
429 await chargingStation
.ocppRequestService
.requestHandler
<
430 OCPP16MeterValuesRequest
,
431 OCPP16MeterValuesResponse
432 >(chargingStation
, OCPP16RequestCommand
.METER_VALUES
, {
435 meterValue
: [transactionEndMeterValue
],
438 const stopResponse
= await chargingStation
.ocppRequestService
.requestHandler
<
439 OCPP16StopTransactionRequest
,
440 OCPP16StopTransactionResponse
441 >(chargingStation
, OCPP16RequestCommand
.STOP_TRANSACTION
, {
443 meterStop
: chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
444 idTag
: chargingStation
.getTransactionIdTag(transactionId
),
445 reason
: OCPP16StopTransactionReason
.UNLOCK_COMMAND
,
447 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
448 return Constants
.OCPP_RESPONSE_UNLOCKED
;
450 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
452 await chargingStation
.ocppRequestService
.requestHandler
<
453 OCPP16StatusNotificationRequest
,
454 OCPP16StatusNotificationResponse
455 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
457 status: OCPP16ChargePointStatus
.AVAILABLE
,
458 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
460 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
461 return Constants
.OCPP_RESPONSE_UNLOCKED
;
464 private handleRequestGetConfiguration(
465 chargingStation
: ChargingStation
,
466 commandPayload
: GetConfigurationRequest
467 ): GetConfigurationResponse
{
468 const configurationKey
: OCPPConfigurationKey
[] = [];
469 const unknownKey
: string[] = [];
470 if (Utils
.isEmptyArray(commandPayload
.key
)) {
471 for (const configuration
of chargingStation
.ocppConfiguration
.configurationKey
) {
472 if (Utils
.isUndefined(configuration
.visible
)) {
473 configuration
.visible
= true;
475 if (!configuration
.visible
) {
478 configurationKey
.push({
479 key
: configuration
.key
,
480 readonly: configuration
.readonly,
481 value
: configuration
.value
,
485 for (const key
of commandPayload
.key
) {
486 const keyFound
= ChargingStationConfigurationUtils
.getConfigurationKey(
491 if (Utils
.isUndefined(keyFound
.visible
)) {
492 keyFound
.visible
= true;
494 if (!keyFound
.visible
) {
497 configurationKey
.push({
499 readonly: keyFound
.readonly,
500 value
: keyFound
.value
,
503 unknownKey
.push(key
);
513 private handleRequestChangeConfiguration(
514 chargingStation
: ChargingStation
,
515 commandPayload
: ChangeConfigurationRequest
516 ): ChangeConfigurationResponse
{
517 const keyToChange
= ChargingStationConfigurationUtils
.getConfigurationKey(
523 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
524 } else if (keyToChange
&& keyToChange
.readonly) {
525 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
526 } else if (keyToChange
&& !keyToChange
.readonly) {
527 let valueChanged
= false;
528 if (keyToChange
.value
!== commandPayload
.value
) {
529 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
532 commandPayload
.value
,
537 let triggerHeartbeatRestart
= false;
538 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
539 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
541 OCPP16StandardParametersKey
.HeartbeatInterval
,
544 triggerHeartbeatRestart
= true;
546 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
547 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
549 OCPP16StandardParametersKey
.HeartBeatInterval
,
552 triggerHeartbeatRestart
= true;
554 if (triggerHeartbeatRestart
) {
555 chargingStation
.restartHeartbeat();
557 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
558 chargingStation
.restartWebSocketPing();
560 if (keyToChange
.reboot
) {
561 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
563 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
567 private handleRequestSetChargingProfile(
568 chargingStation
: ChargingStation
,
569 commandPayload
: SetChargingProfileRequest
570 ): SetChargingProfileResponse
{
572 !OCPP16ServiceUtils
.checkFeatureProfile(
574 OCPP16SupportedFeatureProfiles
.SmartCharging
,
575 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
578 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
580 if (!chargingStation
.getConnectorStatus(commandPayload
.connectorId
)) {
582 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${
583 commandPayload.connectorId
586 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
589 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
590 ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
591 commandPayload
.connectorId
!== 0
593 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
596 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
597 ChargingProfilePurposeType
.TX_PROFILE
&&
598 (commandPayload
.connectorId
=== 0 ||
599 !chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
)
601 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
603 chargingStation
.setChargingProfile(
604 commandPayload
.connectorId
,
605 commandPayload
.csChargingProfiles
608 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${
609 commandPayload.connectorId
610 }, dump their stack: %j`,
611 chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
613 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
616 private handleRequestClearChargingProfile(
617 chargingStation
: ChargingStation
,
618 commandPayload
: ClearChargingProfileRequest
619 ): ClearChargingProfileResponse
{
621 !OCPP16ServiceUtils
.checkFeatureProfile(
623 OCPP16SupportedFeatureProfiles
.SmartCharging
,
624 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
627 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
629 const connectorStatus
= chargingStation
.getConnectorStatus(commandPayload
.connectorId
);
630 if (!connectorStatus
) {
632 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${
633 commandPayload.connectorId
636 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
638 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(connectorStatus
.chargingProfiles
)) {
639 connectorStatus
.chargingProfiles
= [];
641 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${
642 commandPayload.connectorId
643 }, dump their stack: %j`,
644 connectorStatus
.chargingProfiles
646 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
648 if (!commandPayload
.connectorId
) {
649 let clearedCP
= false;
650 for (const connectorId
of chargingStation
.connectors
.keys()) {
651 if (!Utils
.isEmptyArray(chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
)) {
653 .getConnectorStatus(connectorId
)
654 .chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
655 let clearCurrentCP
= false;
656 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
657 clearCurrentCP
= true;
660 !commandPayload
.chargingProfilePurpose
&&
661 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
663 clearCurrentCP
= true;
666 !chargingProfile
.stackLevel
&&
667 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
669 clearCurrentCP
= true;
672 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&&
673 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
675 clearCurrentCP
= true;
677 if (clearCurrentCP
) {
678 connectorStatus
.chargingProfiles
.splice(index
, 1);
680 `${chargingStation.logPrefix()} Matching charging profile(s) cleared on connector id ${
681 commandPayload.connectorId
682 }, dump their stack: %j`,
683 connectorStatus
.chargingProfiles
691 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
694 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
697 private async handleRequestChangeAvailability(
698 chargingStation
: ChargingStation
,
699 commandPayload
: ChangeAvailabilityRequest
700 ): Promise
<ChangeAvailabilityResponse
> {
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 const transactionConnectorId
= commandPayload
.connectorId
;
763 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
);
764 if (transactionConnectorId
) {
765 const remoteStartTransactionLogMsg
=
766 chargingStation
.logPrefix() +
767 ' Transaction remotely STARTED on ' +
768 chargingStation
.stationInfo
.chargingStationId
+
770 transactionConnectorId
.toString() +
772 commandPayload
.idTag
+
774 await chargingStation
.ocppRequestService
.requestHandler
<
775 OCPP16StatusNotificationRequest
,
776 OCPP16StatusNotificationResponse
777 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
778 connectorId
: transactionConnectorId
,
779 status: OCPP16ChargePointStatus
.PREPARING
,
780 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
782 connectorStatus
.status = OCPP16ChargePointStatus
.PREPARING
;
783 if (chargingStation
.isChargingStationAvailable() && connectorStatus
) {
784 // Check if authorized
785 if (chargingStation
.getAuthorizeRemoteTxRequests()) {
786 let authorized
= false;
788 chargingStation
.getLocalAuthListEnabled() &&
789 chargingStation
.hasAuthorizedTags() &&
790 chargingStation
.authorizedTagsCache
792 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
794 .find((value
) => value
=== commandPayload
.idTag
)
796 connectorStatus
.localAuthorizeIdTag
= commandPayload
.idTag
;
797 connectorStatus
.idTagLocalAuthorized
= true;
799 } else if (chargingStation
.getMustAuthorizeAtRemoteStart()) {
800 connectorStatus
.authorizeIdTag
= commandPayload
.idTag
;
801 const authorizeResponse
: OCPP16AuthorizeResponse
=
802 await chargingStation
.ocppRequestService
.requestHandler
<
803 OCPP16AuthorizeRequest
,
804 OCPP16AuthorizeResponse
805 >(chargingStation
, OCPP16RequestCommand
.AUTHORIZE
, {
806 idTag
: commandPayload
.idTag
,
808 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
813 `${chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`
817 // Authorization successful, start transaction
819 this.setRemoteStartTransactionChargingProfile(
821 transactionConnectorId
,
822 commandPayload
.chargingProfile
825 connectorStatus
.transactionRemoteStarted
= true;
828 await chargingStation
.ocppRequestService
.requestHandler
<
829 OCPP16StartTransactionRequest
,
830 OCPP16StartTransactionResponse
831 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
832 connectorId
: transactionConnectorId
,
833 idTag
: commandPayload
.idTag
,
835 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
837 logger
.debug(remoteStartTransactionLogMsg
);
838 return Constants
.OCPP_RESPONSE_ACCEPTED
;
840 return this.notifyRemoteStartTransactionRejected(
842 transactionConnectorId
,
846 return this.notifyRemoteStartTransactionRejected(
848 transactionConnectorId
,
852 return this.notifyRemoteStartTransactionRejected(
854 transactionConnectorId
,
858 // No authorization check required, start transaction
860 this.setRemoteStartTransactionChargingProfile(
862 transactionConnectorId
,
863 commandPayload
.chargingProfile
866 connectorStatus
.transactionRemoteStarted
= true;
869 await chargingStation
.ocppRequestService
.requestHandler
<
870 OCPP16StartTransactionRequest
,
871 OCPP16StartTransactionResponse
872 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
873 connectorId
: transactionConnectorId
,
874 idTag
: commandPayload
.idTag
,
876 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
878 logger
.debug(remoteStartTransactionLogMsg
);
879 return Constants
.OCPP_RESPONSE_ACCEPTED
;
881 return this.notifyRemoteStartTransactionRejected(
883 transactionConnectorId
,
887 return this.notifyRemoteStartTransactionRejected(
889 transactionConnectorId
,
893 return this.notifyRemoteStartTransactionRejected(
895 transactionConnectorId
,
899 return this.notifyRemoteStartTransactionRejected(
901 transactionConnectorId
,
906 private async notifyRemoteStartTransactionRejected(
907 chargingStation
: ChargingStation
,
910 ): Promise
<DefaultResponse
> {
912 chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
914 await chargingStation
.ocppRequestService
.requestHandler
<
915 OCPP16StatusNotificationRequest
,
916 OCPP16StatusNotificationResponse
917 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
919 status: OCPP16ChargePointStatus
.AVAILABLE
,
920 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
922 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
925 chargingStation
.logPrefix() +
926 ' Remote starting transaction REJECTED on connector Id ' +
927 connectorId
.toString() +
930 "', availability '" +
931 chargingStation
.getConnectorStatus(connectorId
).availability
+
933 chargingStation
.getConnectorStatus(connectorId
).status +
936 return Constants
.OCPP_RESPONSE_REJECTED
;
939 private setRemoteStartTransactionChargingProfile(
940 chargingStation
: ChargingStation
,
942 cp
: OCPP16ChargingProfile
944 if (cp
&& cp
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
945 chargingStation
.setChargingProfile(connectorId
, cp
);
947 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}, dump their stack: %j`,
948 chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
951 } else if (cp
&& cp
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
953 `${chargingStation.logPrefix()} Not allowed to set ${
954 cp.chargingProfilePurpose
955 } charging profile(s) at remote start transaction`
963 private async handleRequestRemoteStopTransaction(
964 chargingStation
: ChargingStation
,
965 commandPayload
: RemoteStopTransactionRequest
966 ): Promise
<DefaultResponse
> {
967 const transactionId
= commandPayload
.transactionId
;
968 for (const connectorId
of chargingStation
.connectors
.keys()) {
971 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
973 await chargingStation
.ocppRequestService
.requestHandler
<
974 OCPP16StatusNotificationRequest
,
975 OCPP16StatusNotificationResponse
976 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
978 status: OCPP16ChargePointStatus
.FINISHING
,
979 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
981 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.FINISHING
;
983 chargingStation
.getBeginEndMeterValues() &&
984 chargingStation
.getOcppStrictCompliance() &&
985 !chargingStation
.getOutOfOrderEndMeterValues()
987 // FIXME: Implement OCPP version agnostic helpers
988 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
991 chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
)
993 await chargingStation
.ocppRequestService
.requestHandler
<
994 OCPP16MeterValuesRequest
,
995 OCPP16MeterValuesResponse
996 >(chargingStation
, OCPP16RequestCommand
.METER_VALUES
, {
999 meterValue
: [transactionEndMeterValue
],
1002 await chargingStation
.ocppRequestService
.requestHandler
<
1003 OCPP16StopTransactionRequest
,
1004 OCPP16StopTransactionResponse
1005 >(chargingStation
, OCPP16RequestCommand
.STOP_TRANSACTION
, {
1007 meterStop
: chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1008 idTag
: chargingStation
.getTransactionIdTag(transactionId
),
1010 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1014 chargingStation
.logPrefix() +
1015 ' Trying to remote stop a non existing transaction ' +
1016 transactionId
.toString()
1018 return Constants
.OCPP_RESPONSE_REJECTED
;
1021 private async handleRequestGetDiagnostics(
1022 chargingStation
: ChargingStation
,
1023 commandPayload
: GetDiagnosticsRequest
1024 ): Promise
<GetDiagnosticsResponse
> {
1026 !OCPP16ServiceUtils
.checkFeatureProfile(
1028 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1029 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1032 return Constants
.OCPP_RESPONSE_EMPTY
;
1035 chargingStation
.logPrefix() +
1037 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
+
1038 ' request received: %j',
1041 const uri
= new URL(commandPayload
.location
);
1042 if (uri
.protocol
.startsWith('ftp:')) {
1043 let ftpClient
: Client
;
1046 .readdirSync(path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'))
1047 .filter((file
) => file
.endsWith('.log'))
1048 .map((file
) => path
.join('./', file
));
1049 const diagnosticsArchive
= chargingStation
.stationInfo
.chargingStationId
+ '_logs.tar.gz';
1050 tar
.create({ gzip
: true }, logFiles
).pipe(fs
.createWriteStream(diagnosticsArchive
));
1051 ftpClient
= new Client();
1052 const accessResponse
= await ftpClient
.access({
1054 ...(!Utils
.isEmptyString(uri
.port
) && { port
: Utils
.convertToInt(uri
.port
) }),
1055 ...(!Utils
.isEmptyString(uri
.username
) && { user
: uri
.username
}),
1056 ...(!Utils
.isEmptyString(uri
.password
) && { password
: uri
.password
}),
1058 let uploadResponse
: FTPResponse
;
1059 if (accessResponse
.code
=== 220) {
1060 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1061 ftpClient
.trackProgress(async (info
) => {
1063 `${chargingStation.logPrefix()} ${
1065 } bytes transferred from diagnostics archive ${info.name}`
1067 await chargingStation
.ocppRequestService
.requestHandler
<
1068 DiagnosticsStatusNotificationRequest
,
1069 DiagnosticsStatusNotificationResponse
1070 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1071 status: OCPP16DiagnosticsStatus
.Uploading
,
1074 uploadResponse
= await ftpClient
.uploadFrom(
1076 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'),
1079 uri
.pathname
+ diagnosticsArchive
1081 if (uploadResponse
.code
=== 226) {
1082 await chargingStation
.ocppRequestService
.requestHandler
<
1083 DiagnosticsStatusNotificationRequest
,
1084 DiagnosticsStatusNotificationResponse
1085 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1086 status: OCPP16DiagnosticsStatus
.Uploaded
,
1091 return { fileName
: diagnosticsArchive
};
1093 throw new OCPPError(
1094 ErrorType
.GENERIC_ERROR
,
1095 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1096 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1098 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1101 throw new OCPPError(
1102 ErrorType
.GENERIC_ERROR
,
1103 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1104 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1106 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1109 await chargingStation
.ocppRequestService
.requestHandler
<
1110 DiagnosticsStatusNotificationRequest
,
1111 DiagnosticsStatusNotificationResponse
1112 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1113 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1118 return this.handleIncomingRequestError(
1120 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1122 { errorResponse
: Constants
.OCPP_RESPONSE_EMPTY
}
1127 `${chargingStation.logPrefix()} Unsupported protocol ${
1129 } to transfer the diagnostic logs archive`
1131 await chargingStation
.ocppRequestService
.requestHandler
<
1132 DiagnosticsStatusNotificationRequest
,
1133 DiagnosticsStatusNotificationResponse
1134 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1135 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1137 return Constants
.OCPP_RESPONSE_EMPTY
;
1141 private handleRequestTriggerMessage(
1142 chargingStation
: ChargingStation
,
1143 commandPayload
: OCPP16TriggerMessageRequest
1144 ): OCPP16TriggerMessageResponse
{
1146 !OCPP16ServiceUtils
.checkFeatureProfile(
1148 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1149 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1152 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1154 // TODO: factor out the check on connector id
1155 if (commandPayload
?.connectorId
< 0) {
1157 `${chargingStation.logPrefix()} ${
1158 OCPP16IncomingRequestCommand.TRIGGER_MESSAGE
1159 } incoming request received with invalid connectorId ${commandPayload.connectorId}`
1161 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1164 switch (commandPayload
.requestedMessage
) {
1165 case MessageTrigger
.BootNotification
:
1167 chargingStation
.ocppRequestService
1168 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1170 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1172 chargePointModel
: chargingStation
.getBootNotificationRequest().chargePointModel
,
1173 chargePointVendor
: chargingStation
.getBootNotificationRequest().chargePointVendor
,
1174 chargeBoxSerialNumber
:
1175 chargingStation
.getBootNotificationRequest().chargeBoxSerialNumber
,
1176 firmwareVersion
: chargingStation
.getBootNotificationRequest().firmwareVersion
,
1177 chargePointSerialNumber
:
1178 chargingStation
.getBootNotificationRequest().chargePointSerialNumber
,
1179 iccid
: chargingStation
.getBootNotificationRequest().iccid
,
1180 imsi
: chargingStation
.getBootNotificationRequest().imsi
,
1181 meterSerialNumber
: chargingStation
.getBootNotificationRequest().meterSerialNumber
,
1182 meterType
: chargingStation
.getBootNotificationRequest().meterType
,
1184 { skipBufferingOnError
: true, triggerMessage
: true }
1187 chargingStation
.bootNotificationResponse
= value
;
1190 /* This is intentional */
1192 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1193 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1194 case MessageTrigger
.Heartbeat
:
1196 chargingStation
.ocppRequestService
1197 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1199 OCPP16RequestCommand
.HEARTBEAT
,
1202 triggerMessage
: true,
1206 /* This is intentional */
1208 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1209 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1210 case MessageTrigger
.StatusNotification
:
1212 if (commandPayload
?.connectorId
) {
1213 chargingStation
.ocppRequestService
1214 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1216 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1218 connectorId
: commandPayload
.connectorId
,
1219 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1220 status: chargingStation
.getConnectorStatus(commandPayload
.connectorId
).status,
1223 triggerMessage
: true,
1227 /* This is intentional */
1230 for (const connectorId
of chargingStation
.connectors
.keys()) {
1231 chargingStation
.ocppRequestService
1233 OCPP16StatusNotificationRequest
,
1234 OCPP16StatusNotificationResponse
1237 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1240 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1241 status: chargingStation
.getConnectorStatus(connectorId
).status,
1244 triggerMessage
: true,
1248 /* This is intentional */
1252 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1253 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1255 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1258 return this.handleIncomingRequestError(
1260 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1262 { errorResponse
: Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
}