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 { 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 { 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 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
>,
281 public async incomingRequestHandler(
282 chargingStation
: ChargingStation
,
284 commandName
: OCPP16IncomingRequestCommand
,
285 commandPayload
: JsonType
287 let response
: JsonType
;
289 chargingStation
.getOcppStrictCompliance() &&
290 chargingStation
.isInPendingState() &&
291 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
292 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
295 ErrorType
.SECURITY_ERROR
,
296 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
300 )} while the charging station is in pending state on the central server`,
306 chargingStation
.isRegistered() ||
307 (!chargingStation
.getOcppStrictCompliance() && chargingStation
.isInUnknownState())
310 this.incomingRequestHandlers
.has(commandName
) &&
311 ChargingStationUtils
.isIncomingRequestCommandSupported(commandName
, chargingStation
)
314 this.validatePayload(chargingStation
, commandName
, commandPayload
);
315 // Call the method to build the response
316 response
= await this.incomingRequestHandlers
.get(commandName
)(
322 logger
.error(chargingStation
.logPrefix() + ' Handle request error: %j', error
);
328 ErrorType
.NOT_IMPLEMENTED
,
329 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
340 ErrorType
.SECURITY_ERROR
,
341 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
345 )} while the charging station is not registered on the central server.`,
350 // Send the built response
351 await chargingStation
.ocppRequestService
.sendResponse(
359 private validatePayload(
360 chargingStation
: ChargingStation
,
361 commandName
: OCPP16IncomingRequestCommand
,
362 commandPayload
: JsonType
364 if (this.jsonSchemas
.has(commandName
)) {
365 return this.validateIncomingRequestPayload(
368 this.jsonSchemas
.get(commandName
),
373 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: No JSON schema found for command ${commandName} PDU validation`
378 // Simulate charging station restart
379 private handleRequestReset(
380 chargingStation
: ChargingStation
,
381 commandPayload
: ResetRequest
383 // eslint-disable-next-line @typescript-eslint/no-misused-promises
384 setImmediate(async (): Promise
<void> => {
385 await chargingStation
.reset((commandPayload
.type + 'Reset') as OCPP16StopTransactionReason
);
388 `${chargingStation.logPrefix()} ${
390 } reset command received, simulating it. The station will be back online in ${Utils.formatDurationMilliSeconds(
391 chargingStation.stationInfo.resetTime
394 return Constants
.OCPP_RESPONSE_ACCEPTED
;
397 private handleRequestClearCache(): DefaultResponse
{
398 return Constants
.OCPP_RESPONSE_ACCEPTED
;
401 private async handleRequestUnlockConnector(
402 chargingStation
: ChargingStation
,
403 commandPayload
: UnlockConnectorRequest
404 ): Promise
<UnlockConnectorResponse
> {
405 const connectorId
= commandPayload
.connectorId
;
406 if (connectorId
=== 0) {
408 chargingStation
.logPrefix() + ' Trying to unlock connector ' + connectorId
.toString()
410 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
412 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
413 const transactionId
= chargingStation
.getConnectorStatus(connectorId
).transactionId
;
415 chargingStation
.getBeginEndMeterValues() &&
416 chargingStation
.getOcppStrictCompliance() &&
417 !chargingStation
.getOutOfOrderEndMeterValues()
419 // FIXME: Implement OCPP version agnostic helpers
420 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
423 chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
)
425 await chargingStation
.ocppRequestService
.requestHandler
<
426 OCPP16MeterValuesRequest
,
427 OCPP16MeterValuesResponse
428 >(chargingStation
, OCPP16RequestCommand
.METER_VALUES
, {
431 meterValue
: [transactionEndMeterValue
],
434 const stopResponse
= await chargingStation
.ocppRequestService
.requestHandler
<
435 OCPP16StopTransactionRequest
,
436 OCPP16StopTransactionResponse
437 >(chargingStation
, OCPP16RequestCommand
.STOP_TRANSACTION
, {
439 meterStop
: chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
440 idTag
: chargingStation
.getTransactionIdTag(transactionId
),
441 reason
: OCPP16StopTransactionReason
.UNLOCK_COMMAND
,
443 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
444 return Constants
.OCPP_RESPONSE_UNLOCKED
;
446 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
448 await chargingStation
.ocppRequestService
.requestHandler
<
449 OCPP16StatusNotificationRequest
,
450 OCPP16StatusNotificationResponse
451 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
453 status: OCPP16ChargePointStatus
.AVAILABLE
,
454 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
456 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
457 return Constants
.OCPP_RESPONSE_UNLOCKED
;
460 private handleRequestGetConfiguration(
461 chargingStation
: ChargingStation
,
462 commandPayload
: GetConfigurationRequest
463 ): GetConfigurationResponse
{
464 const configurationKey
: OCPPConfigurationKey
[] = [];
465 const unknownKey
: string[] = [];
466 if (Utils
.isEmptyArray(commandPayload
.key
)) {
467 for (const configuration
of chargingStation
.ocppConfiguration
.configurationKey
) {
468 if (Utils
.isUndefined(configuration
.visible
)) {
469 configuration
.visible
= true;
471 if (!configuration
.visible
) {
474 configurationKey
.push({
475 key
: configuration
.key
,
476 readonly: configuration
.readonly,
477 value
: configuration
.value
,
481 for (const key
of commandPayload
.key
) {
482 const keyFound
= ChargingStationConfigurationUtils
.getConfigurationKey(
487 if (Utils
.isUndefined(keyFound
.visible
)) {
488 keyFound
.visible
= true;
490 if (!keyFound
.visible
) {
493 configurationKey
.push({
495 readonly: keyFound
.readonly,
496 value
: keyFound
.value
,
499 unknownKey
.push(key
);
509 private handleRequestChangeConfiguration(
510 chargingStation
: ChargingStation
,
511 commandPayload
: ChangeConfigurationRequest
512 ): ChangeConfigurationResponse
{
513 const keyToChange
= ChargingStationConfigurationUtils
.getConfigurationKey(
519 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
520 } else if (keyToChange
&& keyToChange
.readonly) {
521 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
522 } else if (keyToChange
&& !keyToChange
.readonly) {
523 let valueChanged
= false;
524 if (keyToChange
.value
!== commandPayload
.value
) {
525 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
528 commandPayload
.value
,
533 let triggerHeartbeatRestart
= false;
534 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
535 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
537 OCPP16StandardParametersKey
.HeartbeatInterval
,
540 triggerHeartbeatRestart
= true;
542 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
543 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
545 OCPP16StandardParametersKey
.HeartBeatInterval
,
548 triggerHeartbeatRestart
= true;
550 if (triggerHeartbeatRestart
) {
551 chargingStation
.restartHeartbeat();
553 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
554 chargingStation
.restartWebSocketPing();
556 if (keyToChange
.reboot
) {
557 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
559 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
563 private handleRequestSetChargingProfile(
564 chargingStation
: ChargingStation
,
565 commandPayload
: SetChargingProfileRequest
566 ): SetChargingProfileResponse
{
568 !OCPP16ServiceUtils
.checkFeatureProfile(
570 OCPP16SupportedFeatureProfiles
.SmartCharging
,
571 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
574 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
576 if (!chargingStation
.getConnectorStatus(commandPayload
.connectorId
)) {
578 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${
579 commandPayload.connectorId
582 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
585 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
586 ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
587 commandPayload
.connectorId
!== 0
589 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
592 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
593 ChargingProfilePurposeType
.TX_PROFILE
&&
594 (commandPayload
.connectorId
=== 0 ||
595 !chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
)
597 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
599 chargingStation
.setChargingProfile(
600 commandPayload
.connectorId
,
601 commandPayload
.csChargingProfiles
604 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${
605 commandPayload.connectorId
606 }, dump their stack: %j`,
607 chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
609 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
612 private handleRequestClearChargingProfile(
613 chargingStation
: ChargingStation
,
614 commandPayload
: ClearChargingProfileRequest
615 ): ClearChargingProfileResponse
{
617 !OCPP16ServiceUtils
.checkFeatureProfile(
619 OCPP16SupportedFeatureProfiles
.SmartCharging
,
620 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
623 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
625 const connectorStatus
= chargingStation
.getConnectorStatus(commandPayload
.connectorId
);
626 if (!connectorStatus
) {
628 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${
629 commandPayload.connectorId
632 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
634 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(connectorStatus
.chargingProfiles
)) {
635 connectorStatus
.chargingProfiles
= [];
637 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${
638 commandPayload.connectorId
639 }, dump their stack: %j`,
640 connectorStatus
.chargingProfiles
642 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
644 if (!commandPayload
.connectorId
) {
645 let clearedCP
= false;
646 for (const connectorId
of chargingStation
.connectors
.keys()) {
647 if (!Utils
.isEmptyArray(chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
)) {
649 .getConnectorStatus(connectorId
)
650 .chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
651 let clearCurrentCP
= false;
652 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
653 clearCurrentCP
= true;
656 !commandPayload
.chargingProfilePurpose
&&
657 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
659 clearCurrentCP
= true;
662 !chargingProfile
.stackLevel
&&
663 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
665 clearCurrentCP
= true;
668 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&&
669 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
671 clearCurrentCP
= true;
673 if (clearCurrentCP
) {
674 connectorStatus
.chargingProfiles
.splice(index
, 1);
676 `${chargingStation.logPrefix()} Matching charging profile(s) cleared on connector id ${
677 commandPayload.connectorId
678 }, dump their stack: %j`,
679 connectorStatus
.chargingProfiles
687 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
690 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
693 private async handleRequestChangeAvailability(
694 chargingStation
: ChargingStation
,
695 commandPayload
: ChangeAvailabilityRequest
696 ): Promise
<ChangeAvailabilityResponse
> {
697 const connectorId
: number = commandPayload
.connectorId
;
698 if (!chargingStation
.getConnectorStatus(connectorId
)) {
700 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`
702 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
704 const chargePointStatus
: OCPP16ChargePointStatus
=
705 commandPayload
.type === OCPP16AvailabilityType
.OPERATIVE
706 ? OCPP16ChargePointStatus
.AVAILABLE
707 : OCPP16ChargePointStatus
.UNAVAILABLE
;
708 if (connectorId
=== 0) {
709 let response
: ChangeAvailabilityResponse
= Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
710 for (const id
of chargingStation
.connectors
.keys()) {
711 if (chargingStation
.getConnectorStatus(id
)?.transactionStarted
) {
712 response
= Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
714 chargingStation
.getConnectorStatus(id
).availability
= commandPayload
.type;
715 if (response
=== Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
) {
716 await chargingStation
.ocppRequestService
.requestHandler
<
717 OCPP16StatusNotificationRequest
,
718 OCPP16StatusNotificationResponse
719 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
721 status: chargePointStatus
,
722 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
724 chargingStation
.getConnectorStatus(id
).status = chargePointStatus
;
730 (chargingStation
.getConnectorStatus(0).availability
=== OCPP16AvailabilityType
.OPERATIVE
||
731 (chargingStation
.getConnectorStatus(0).availability
===
732 OCPP16AvailabilityType
.INOPERATIVE
&&
733 commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))
735 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
736 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
737 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
739 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
740 await chargingStation
.ocppRequestService
.requestHandler
<
741 OCPP16StatusNotificationRequest
,
742 OCPP16StatusNotificationResponse
743 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
745 status: chargePointStatus
,
746 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
748 chargingStation
.getConnectorStatus(connectorId
).status = chargePointStatus
;
749 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
751 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
754 private async handleRequestRemoteStartTransaction(
755 chargingStation
: ChargingStation
,
756 commandPayload
: RemoteStartTransactionRequest
757 ): Promise
<DefaultResponse
> {
758 const transactionConnectorId
= commandPayload
.connectorId
;
759 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
);
760 if (transactionConnectorId
) {
761 await chargingStation
.ocppRequestService
.requestHandler
<
762 OCPP16StatusNotificationRequest
,
763 OCPP16StatusNotificationResponse
764 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
765 connectorId
: transactionConnectorId
,
766 status: OCPP16ChargePointStatus
.PREPARING
,
767 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
769 connectorStatus
.status = OCPP16ChargePointStatus
.PREPARING
;
770 if (chargingStation
.isChargingStationAvailable() && connectorStatus
) {
771 // Check if authorized
772 if (chargingStation
.getAuthorizeRemoteTxRequests()) {
773 let authorized
= false;
775 chargingStation
.getLocalAuthListEnabled() &&
776 chargingStation
.hasAuthorizedTags() &&
777 chargingStation
.authorizedTagsCache
779 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
781 .find((value
) => value
=== commandPayload
.idTag
)
783 connectorStatus
.localAuthorizeIdTag
= commandPayload
.idTag
;
784 connectorStatus
.idTagLocalAuthorized
= true;
786 } else if (chargingStation
.getMayAuthorizeAtRemoteStart()) {
787 connectorStatus
.authorizeIdTag
= commandPayload
.idTag
;
788 const authorizeResponse
: OCPP16AuthorizeResponse
=
789 await chargingStation
.ocppRequestService
.requestHandler
<
790 OCPP16AuthorizeRequest
,
791 OCPP16AuthorizeResponse
792 >(chargingStation
, OCPP16RequestCommand
.AUTHORIZE
, {
793 idTag
: commandPayload
.idTag
,
795 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
800 `${chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`
804 // Authorization successful, start transaction
806 this.setRemoteStartTransactionChargingProfile(
808 transactionConnectorId
,
809 commandPayload
.chargingProfile
812 connectorStatus
.transactionRemoteStarted
= true;
815 await chargingStation
.ocppRequestService
.requestHandler
<
816 OCPP16StartTransactionRequest
,
817 OCPP16StartTransactionResponse
818 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
819 connectorId
: transactionConnectorId
,
820 idTag
: commandPayload
.idTag
,
822 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
825 chargingStation
.logPrefix() +
826 ' Transaction remotely STARTED on ' +
827 chargingStation
.stationInfo
.chargingStationId
+
829 transactionConnectorId
.toString() +
833 return Constants
.OCPP_RESPONSE_ACCEPTED
;
835 return this.notifyRemoteStartTransactionRejected(
837 transactionConnectorId
,
841 return this.notifyRemoteStartTransactionRejected(
843 transactionConnectorId
,
847 return this.notifyRemoteStartTransactionRejected(
849 transactionConnectorId
,
853 // No authorization check required, start transaction
855 this.setRemoteStartTransactionChargingProfile(
857 transactionConnectorId
,
858 commandPayload
.chargingProfile
861 connectorStatus
.transactionRemoteStarted
= true;
864 await chargingStation
.ocppRequestService
.requestHandler
<
865 OCPP16StartTransactionRequest
,
866 OCPP16StartTransactionResponse
867 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
868 connectorId
: transactionConnectorId
,
869 idTag
: commandPayload
.idTag
,
871 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
874 chargingStation
.logPrefix() +
875 ' Transaction remotely STARTED on ' +
876 chargingStation
.stationInfo
.chargingStationId
+
878 transactionConnectorId
.toString() +
882 return Constants
.OCPP_RESPONSE_ACCEPTED
;
884 return this.notifyRemoteStartTransactionRejected(
886 transactionConnectorId
,
890 return this.notifyRemoteStartTransactionRejected(
892 transactionConnectorId
,
896 return this.notifyRemoteStartTransactionRejected(
898 transactionConnectorId
,
902 return this.notifyRemoteStartTransactionRejected(
904 transactionConnectorId
,
909 private async notifyRemoteStartTransactionRejected(
910 chargingStation
: ChargingStation
,
913 ): Promise
<DefaultResponse
> {
915 chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
917 await chargingStation
.ocppRequestService
.requestHandler
<
918 OCPP16StatusNotificationRequest
,
919 OCPP16StatusNotificationResponse
920 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
922 status: OCPP16ChargePointStatus
.AVAILABLE
,
923 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
925 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
928 chargingStation
.logPrefix() +
929 ' Remote starting transaction REJECTED on connector Id ' +
930 connectorId
.toString() +
934 chargingStation
.getConnectorStatus(connectorId
).availability
+
936 chargingStation
.getConnectorStatus(connectorId
).status
938 return Constants
.OCPP_RESPONSE_REJECTED
;
941 private setRemoteStartTransactionChargingProfile(
942 chargingStation
: ChargingStation
,
944 cp
: OCPP16ChargingProfile
946 if (cp
&& cp
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
947 chargingStation
.setChargingProfile(connectorId
, cp
);
949 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}, dump their stack: %j`,
950 chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
953 } else if (cp
&& cp
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
955 `${chargingStation.logPrefix()} Not allowed to set ${
956 cp.chargingProfilePurpose
957 } charging profile(s) at remote start transaction`
965 private async handleRequestRemoteStopTransaction(
966 chargingStation
: ChargingStation
,
967 commandPayload
: RemoteStopTransactionRequest
968 ): Promise
<DefaultResponse
> {
969 const transactionId
= commandPayload
.transactionId
;
970 for (const connectorId
of chargingStation
.connectors
.keys()) {
973 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
975 await chargingStation
.ocppRequestService
.requestHandler
<
976 OCPP16StatusNotificationRequest
,
977 OCPP16StatusNotificationResponse
978 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
980 status: OCPP16ChargePointStatus
.FINISHING
,
981 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
983 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.FINISHING
;
985 chargingStation
.getBeginEndMeterValues() &&
986 chargingStation
.getOcppStrictCompliance() &&
987 !chargingStation
.getOutOfOrderEndMeterValues()
989 // FIXME: Implement OCPP version agnostic helpers
990 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
993 chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
)
995 await chargingStation
.ocppRequestService
.requestHandler
<
996 OCPP16MeterValuesRequest
,
997 OCPP16MeterValuesResponse
998 >(chargingStation
, OCPP16RequestCommand
.METER_VALUES
, {
1001 meterValue
: [transactionEndMeterValue
],
1004 await chargingStation
.ocppRequestService
.requestHandler
<
1005 OCPP16StopTransactionRequest
,
1006 OCPP16StopTransactionResponse
1007 >(chargingStation
, OCPP16RequestCommand
.STOP_TRANSACTION
, {
1009 meterStop
: chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1010 idTag
: chargingStation
.getTransactionIdTag(transactionId
),
1012 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1016 chargingStation
.logPrefix() +
1017 ' Trying to remote stop a non existing transaction ' +
1018 transactionId
.toString()
1020 return Constants
.OCPP_RESPONSE_REJECTED
;
1023 private async handleRequestGetDiagnostics(
1024 chargingStation
: ChargingStation
,
1025 commandPayload
: GetDiagnosticsRequest
1026 ): Promise
<GetDiagnosticsResponse
> {
1028 !OCPP16ServiceUtils
.checkFeatureProfile(
1030 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1031 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1034 return Constants
.OCPP_RESPONSE_EMPTY
;
1037 chargingStation
.logPrefix() +
1039 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
+
1040 ' request received: %j',
1043 const uri
= new URL(commandPayload
.location
);
1044 if (uri
.protocol
.startsWith('ftp:')) {
1045 let ftpClient
: Client
;
1048 .readdirSync(path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'))
1049 .filter((file
) => file
.endsWith('.log'))
1050 .map((file
) => path
.join('./', file
));
1051 const diagnosticsArchive
= chargingStation
.stationInfo
.chargingStationId
+ '_logs.tar.gz';
1052 tar
.create({ gzip
: true }, logFiles
).pipe(fs
.createWriteStream(diagnosticsArchive
));
1053 ftpClient
= new Client();
1054 const accessResponse
= await ftpClient
.access({
1056 ...(!Utils
.isEmptyString(uri
.port
) && { port
: Utils
.convertToInt(uri
.port
) }),
1057 ...(!Utils
.isEmptyString(uri
.username
) && { user
: uri
.username
}),
1058 ...(!Utils
.isEmptyString(uri
.password
) && { password
: uri
.password
}),
1060 let uploadResponse
: FTPResponse
;
1061 if (accessResponse
.code
=== 220) {
1062 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1063 ftpClient
.trackProgress(async (info
) => {
1065 `${chargingStation.logPrefix()} ${
1067 } bytes transferred from diagnostics archive ${info.name}`
1069 await chargingStation
.ocppRequestService
.requestHandler
<
1070 DiagnosticsStatusNotificationRequest
,
1071 DiagnosticsStatusNotificationResponse
1072 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1073 status: OCPP16DiagnosticsStatus
.Uploading
,
1076 uploadResponse
= await ftpClient
.uploadFrom(
1078 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'),
1081 uri
.pathname
+ diagnosticsArchive
1083 if (uploadResponse
.code
=== 226) {
1084 await chargingStation
.ocppRequestService
.requestHandler
<
1085 DiagnosticsStatusNotificationRequest
,
1086 DiagnosticsStatusNotificationResponse
1087 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1088 status: OCPP16DiagnosticsStatus
.Uploaded
,
1093 return { fileName
: diagnosticsArchive
};
1095 throw new OCPPError(
1096 ErrorType
.GENERIC_ERROR
,
1097 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1098 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1100 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1103 throw new OCPPError(
1104 ErrorType
.GENERIC_ERROR
,
1105 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1106 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1108 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1111 await chargingStation
.ocppRequestService
.requestHandler
<
1112 DiagnosticsStatusNotificationRequest
,
1113 DiagnosticsStatusNotificationResponse
1114 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1115 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1120 return this.handleIncomingRequestError(
1122 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1124 { errorResponse
: Constants
.OCPP_RESPONSE_EMPTY
}
1129 `${chargingStation.logPrefix()} Unsupported protocol ${
1131 } to transfer the diagnostic logs archive`
1133 await chargingStation
.ocppRequestService
.requestHandler
<
1134 DiagnosticsStatusNotificationRequest
,
1135 DiagnosticsStatusNotificationResponse
1136 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1137 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1139 return Constants
.OCPP_RESPONSE_EMPTY
;
1143 private handleRequestTriggerMessage(
1144 chargingStation
: ChargingStation
,
1145 commandPayload
: OCPP16TriggerMessageRequest
1146 ): OCPP16TriggerMessageResponse
{
1148 !OCPP16ServiceUtils
.checkFeatureProfile(
1150 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1151 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1154 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1156 // TODO: factor out the check on connector id
1157 if (commandPayload
?.connectorId
< 0) {
1159 `${chargingStation.logPrefix()} ${
1160 OCPP16IncomingRequestCommand.TRIGGER_MESSAGE
1161 } incoming request received with invalid connectorId ${commandPayload.connectorId}`
1163 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1166 switch (commandPayload
.requestedMessage
) {
1167 case MessageTrigger
.BootNotification
:
1169 chargingStation
.ocppRequestService
1170 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1172 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1174 chargePointModel
: chargingStation
.getBootNotificationRequest().chargePointModel
,
1175 chargePointVendor
: chargingStation
.getBootNotificationRequest().chargePointVendor
,
1176 chargeBoxSerialNumber
:
1177 chargingStation
.getBootNotificationRequest().chargeBoxSerialNumber
,
1178 firmwareVersion
: chargingStation
.getBootNotificationRequest().firmwareVersion
,
1179 chargePointSerialNumber
:
1180 chargingStation
.getBootNotificationRequest().chargePointSerialNumber
,
1181 iccid
: chargingStation
.getBootNotificationRequest().iccid
,
1182 imsi
: chargingStation
.getBootNotificationRequest().imsi
,
1183 meterSerialNumber
: chargingStation
.getBootNotificationRequest().meterSerialNumber
,
1184 meterType
: chargingStation
.getBootNotificationRequest().meterType
,
1186 { skipBufferingOnError
: true, triggerMessage
: true }
1189 chargingStation
.bootNotificationResponse
= value
;
1192 /* This is intentional */
1194 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1195 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1196 case MessageTrigger
.Heartbeat
:
1198 chargingStation
.ocppRequestService
1199 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1201 OCPP16RequestCommand
.HEARTBEAT
,
1204 triggerMessage
: true,
1208 /* This is intentional */
1210 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1211 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1212 case MessageTrigger
.StatusNotification
:
1214 if (commandPayload
?.connectorId
) {
1215 chargingStation
.ocppRequestService
1216 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1218 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1220 connectorId
: commandPayload
.connectorId
,
1221 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1222 status: chargingStation
.getConnectorStatus(commandPayload
.connectorId
).status,
1225 triggerMessage
: true,
1229 /* This is intentional */
1232 for (const connectorId
of chargingStation
.connectors
.keys()) {
1233 chargingStation
.ocppRequestService
1235 OCPP16StatusNotificationRequest
,
1236 OCPP16StatusNotificationResponse
1239 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1242 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1243 status: chargingStation
.getConnectorStatus(connectorId
).status,
1246 triggerMessage
: true,
1250 /* This is intentional */
1254 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1255 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1257 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1260 return this.handleIncomingRequestError(
1262 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1264 { errorResponse
: Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
}