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
>,
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
)(
323 logger
.error(chargingStation
.logPrefix() + ' Handle request error:', error
);
329 ErrorType
.NOT_IMPLEMENTED
,
330 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
341 ErrorType
.SECURITY_ERROR
,
342 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
346 )} while the charging station is not registered on the central server.`,
351 // Send the built response
352 await chargingStation
.ocppRequestService
.sendResponse(
360 private validatePayload(
361 chargingStation
: ChargingStation
,
362 commandName
: OCPP16IncomingRequestCommand
,
363 commandPayload
: JsonType
365 if (this.jsonSchemas
.has(commandName
)) {
366 return this.validateIncomingRequestPayload(
369 this.jsonSchemas
.get(commandName
),
374 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command ${commandName} PDU validation`
379 // Simulate charging station restart
380 private handleRequestReset(
381 chargingStation
: ChargingStation
,
382 commandPayload
: ResetRequest
384 // eslint-disable-next-line @typescript-eslint/no-misused-promises
385 setImmediate(async (): Promise
<void> => {
386 await chargingStation
.reset((commandPayload
.type + 'Reset') as OCPP16StopTransactionReason
);
389 `${chargingStation.logPrefix()} ${
391 } reset command received, simulating it. The station will be back online in ${Utils.formatDurationMilliSeconds(
392 chargingStation.stationInfo.resetTime
395 return Constants
.OCPP_RESPONSE_ACCEPTED
;
398 private handleRequestClearCache(): DefaultResponse
{
399 return Constants
.OCPP_RESPONSE_ACCEPTED
;
402 private async handleRequestUnlockConnector(
403 chargingStation
: ChargingStation
,
404 commandPayload
: UnlockConnectorRequest
405 ): Promise
<UnlockConnectorResponse
> {
406 const connectorId
= commandPayload
.connectorId
;
407 if (connectorId
=== 0) {
409 chargingStation
.logPrefix() + ' Trying to unlock connector ' + connectorId
.toString()
411 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
413 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
414 const transactionId
= chargingStation
.getConnectorStatus(connectorId
).transactionId
;
416 chargingStation
.getBeginEndMeterValues() &&
417 chargingStation
.getOcppStrictCompliance() &&
418 !chargingStation
.getOutOfOrderEndMeterValues()
420 // FIXME: Implement OCPP version agnostic helpers
421 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
424 chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
)
426 await chargingStation
.ocppRequestService
.requestHandler
<
427 OCPP16MeterValuesRequest
,
428 OCPP16MeterValuesResponse
429 >(chargingStation
, OCPP16RequestCommand
.METER_VALUES
, {
432 meterValue
: [transactionEndMeterValue
],
435 const stopResponse
= await chargingStation
.ocppRequestService
.requestHandler
<
436 OCPP16StopTransactionRequest
,
437 OCPP16StopTransactionResponse
438 >(chargingStation
, OCPP16RequestCommand
.STOP_TRANSACTION
, {
440 meterStop
: chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
441 idTag
: chargingStation
.getTransactionIdTag(transactionId
),
442 reason
: OCPP16StopTransactionReason
.UNLOCK_COMMAND
,
444 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
445 return Constants
.OCPP_RESPONSE_UNLOCKED
;
447 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
449 await chargingStation
.ocppRequestService
.requestHandler
<
450 OCPP16StatusNotificationRequest
,
451 OCPP16StatusNotificationResponse
452 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
454 status: OCPP16ChargePointStatus
.AVAILABLE
,
455 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
457 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
458 return Constants
.OCPP_RESPONSE_UNLOCKED
;
461 private handleRequestGetConfiguration(
462 chargingStation
: ChargingStation
,
463 commandPayload
: GetConfigurationRequest
464 ): GetConfigurationResponse
{
465 const configurationKey
: OCPPConfigurationKey
[] = [];
466 const unknownKey
: string[] = [];
467 if (Utils
.isEmptyArray(commandPayload
.key
)) {
468 for (const configuration
of chargingStation
.ocppConfiguration
.configurationKey
) {
469 if (Utils
.isUndefined(configuration
.visible
)) {
470 configuration
.visible
= true;
472 if (!configuration
.visible
) {
475 configurationKey
.push({
476 key
: configuration
.key
,
477 readonly: configuration
.readonly,
478 value
: configuration
.value
,
482 for (const key
of commandPayload
.key
) {
483 const keyFound
= ChargingStationConfigurationUtils
.getConfigurationKey(
488 if (Utils
.isUndefined(keyFound
.visible
)) {
489 keyFound
.visible
= true;
491 if (!keyFound
.visible
) {
494 configurationKey
.push({
496 readonly: keyFound
.readonly,
497 value
: keyFound
.value
,
500 unknownKey
.push(key
);
510 private handleRequestChangeConfiguration(
511 chargingStation
: ChargingStation
,
512 commandPayload
: ChangeConfigurationRequest
513 ): ChangeConfigurationResponse
{
514 const keyToChange
= ChargingStationConfigurationUtils
.getConfigurationKey(
520 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
521 } else if (keyToChange
&& keyToChange
.readonly) {
522 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
523 } else if (keyToChange
&& !keyToChange
.readonly) {
524 let valueChanged
= false;
525 if (keyToChange
.value
!== commandPayload
.value
) {
526 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
529 commandPayload
.value
,
534 let triggerHeartbeatRestart
= false;
535 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
536 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
538 OCPP16StandardParametersKey
.HeartbeatInterval
,
541 triggerHeartbeatRestart
= true;
543 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
544 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
546 OCPP16StandardParametersKey
.HeartBeatInterval
,
549 triggerHeartbeatRestart
= true;
551 if (triggerHeartbeatRestart
) {
552 chargingStation
.restartHeartbeat();
554 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
555 chargingStation
.restartWebSocketPing();
557 if (keyToChange
.reboot
) {
558 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
560 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
564 private handleRequestSetChargingProfile(
565 chargingStation
: ChargingStation
,
566 commandPayload
: SetChargingProfileRequest
567 ): SetChargingProfileResponse
{
569 !OCPP16ServiceUtils
.checkFeatureProfile(
571 OCPP16SupportedFeatureProfiles
.SmartCharging
,
572 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
575 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
577 if (!chargingStation
.getConnectorStatus(commandPayload
.connectorId
)) {
579 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${
580 commandPayload.connectorId
583 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
586 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
587 ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
588 commandPayload
.connectorId
!== 0
590 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
593 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
594 ChargingProfilePurposeType
.TX_PROFILE
&&
595 (commandPayload
.connectorId
=== 0 ||
596 !chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
)
598 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
600 chargingStation
.setChargingProfile(
601 commandPayload
.connectorId
,
602 commandPayload
.csChargingProfiles
605 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${
606 commandPayload.connectorId
607 }, dump their stack: %j`,
608 chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
610 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
613 private handleRequestClearChargingProfile(
614 chargingStation
: ChargingStation
,
615 commandPayload
: ClearChargingProfileRequest
616 ): ClearChargingProfileResponse
{
618 !OCPP16ServiceUtils
.checkFeatureProfile(
620 OCPP16SupportedFeatureProfiles
.SmartCharging
,
621 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
624 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
626 const connectorStatus
= chargingStation
.getConnectorStatus(commandPayload
.connectorId
);
627 if (!connectorStatus
) {
629 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${
630 commandPayload.connectorId
633 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
635 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(connectorStatus
.chargingProfiles
)) {
636 connectorStatus
.chargingProfiles
= [];
638 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${
639 commandPayload.connectorId
640 }, dump their stack: %j`,
641 connectorStatus
.chargingProfiles
643 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
645 if (!commandPayload
.connectorId
) {
646 let clearedCP
= false;
647 for (const connectorId
of chargingStation
.connectors
.keys()) {
648 if (!Utils
.isEmptyArray(chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
)) {
650 .getConnectorStatus(connectorId
)
651 .chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
652 let clearCurrentCP
= false;
653 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
654 clearCurrentCP
= true;
657 !commandPayload
.chargingProfilePurpose
&&
658 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
660 clearCurrentCP
= true;
663 !chargingProfile
.stackLevel
&&
664 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
666 clearCurrentCP
= true;
669 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&&
670 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
672 clearCurrentCP
= true;
674 if (clearCurrentCP
) {
675 connectorStatus
.chargingProfiles
.splice(index
, 1);
677 `${chargingStation.logPrefix()} Matching charging profile(s) cleared on connector id ${
678 commandPayload.connectorId
679 }, dump their stack: %j`,
680 connectorStatus
.chargingProfiles
688 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
691 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
694 private async handleRequestChangeAvailability(
695 chargingStation
: ChargingStation
,
696 commandPayload
: ChangeAvailabilityRequest
697 ): Promise
<ChangeAvailabilityResponse
> {
698 const connectorId
: number = commandPayload
.connectorId
;
699 if (!chargingStation
.getConnectorStatus(connectorId
)) {
701 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`
703 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
705 const chargePointStatus
: OCPP16ChargePointStatus
=
706 commandPayload
.type === OCPP16AvailabilityType
.OPERATIVE
707 ? OCPP16ChargePointStatus
.AVAILABLE
708 : OCPP16ChargePointStatus
.UNAVAILABLE
;
709 if (connectorId
=== 0) {
710 let response
: ChangeAvailabilityResponse
= Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
711 for (const id
of chargingStation
.connectors
.keys()) {
712 if (chargingStation
.getConnectorStatus(id
)?.transactionStarted
) {
713 response
= Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
715 chargingStation
.getConnectorStatus(id
).availability
= commandPayload
.type;
716 if (response
=== Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
) {
717 await chargingStation
.ocppRequestService
.requestHandler
<
718 OCPP16StatusNotificationRequest
,
719 OCPP16StatusNotificationResponse
720 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
722 status: chargePointStatus
,
723 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
725 chargingStation
.getConnectorStatus(id
).status = chargePointStatus
;
731 (chargingStation
.getConnectorStatus(0).availability
=== OCPP16AvailabilityType
.OPERATIVE
||
732 (chargingStation
.getConnectorStatus(0).availability
===
733 OCPP16AvailabilityType
.INOPERATIVE
&&
734 commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))
736 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
737 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
738 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
740 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
741 await chargingStation
.ocppRequestService
.requestHandler
<
742 OCPP16StatusNotificationRequest
,
743 OCPP16StatusNotificationResponse
744 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
746 status: chargePointStatus
,
747 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
749 chargingStation
.getConnectorStatus(connectorId
).status = chargePointStatus
;
750 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
752 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
755 private async handleRequestRemoteStartTransaction(
756 chargingStation
: ChargingStation
,
757 commandPayload
: RemoteStartTransactionRequest
758 ): Promise
<DefaultResponse
> {
759 const transactionConnectorId
= commandPayload
.connectorId
;
760 const connectorStatus
= chargingStation
.getConnectorStatus(transactionConnectorId
);
761 if (transactionConnectorId
) {
762 await chargingStation
.ocppRequestService
.requestHandler
<
763 OCPP16StatusNotificationRequest
,
764 OCPP16StatusNotificationResponse
765 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
766 connectorId
: transactionConnectorId
,
767 status: OCPP16ChargePointStatus
.PREPARING
,
768 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
770 connectorStatus
.status = OCPP16ChargePointStatus
.PREPARING
;
771 if (chargingStation
.isChargingStationAvailable() && connectorStatus
) {
772 // Check if authorized
773 if (chargingStation
.getAuthorizeRemoteTxRequests()) {
774 let authorized
= false;
776 chargingStation
.getLocalAuthListEnabled() &&
777 chargingStation
.hasAuthorizedTags() &&
778 chargingStation
.authorizedTagsCache
780 ChargingStationUtils
.getAuthorizationFile(chargingStation
.stationInfo
)
782 .find((value
) => value
=== commandPayload
.idTag
)
784 connectorStatus
.localAuthorizeIdTag
= commandPayload
.idTag
;
785 connectorStatus
.idTagLocalAuthorized
= true;
787 } else if (chargingStation
.getMayAuthorizeAtRemoteStart()) {
788 connectorStatus
.authorizeIdTag
= commandPayload
.idTag
;
789 const authorizeResponse
: OCPP16AuthorizeResponse
=
790 await chargingStation
.ocppRequestService
.requestHandler
<
791 OCPP16AuthorizeRequest
,
792 OCPP16AuthorizeResponse
793 >(chargingStation
, OCPP16RequestCommand
.AUTHORIZE
, {
794 idTag
: commandPayload
.idTag
,
796 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
801 `${chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`
805 // Authorization successful, start transaction
807 this.setRemoteStartTransactionChargingProfile(
809 transactionConnectorId
,
810 commandPayload
.chargingProfile
813 connectorStatus
.transactionRemoteStarted
= true;
816 await chargingStation
.ocppRequestService
.requestHandler
<
817 OCPP16StartTransactionRequest
,
818 OCPP16StartTransactionResponse
819 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
820 connectorId
: transactionConnectorId
,
821 idTag
: commandPayload
.idTag
,
823 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
826 chargingStation
.logPrefix() +
827 ' Transaction remotely STARTED on ' +
828 chargingStation
.stationInfo
.chargingStationId
+
830 transactionConnectorId
.toString() +
834 return Constants
.OCPP_RESPONSE_ACCEPTED
;
836 return this.notifyRemoteStartTransactionRejected(
838 transactionConnectorId
,
842 return this.notifyRemoteStartTransactionRejected(
844 transactionConnectorId
,
848 return this.notifyRemoteStartTransactionRejected(
850 transactionConnectorId
,
854 // No authorization check required, start transaction
856 this.setRemoteStartTransactionChargingProfile(
858 transactionConnectorId
,
859 commandPayload
.chargingProfile
862 connectorStatus
.transactionRemoteStarted
= true;
865 await chargingStation
.ocppRequestService
.requestHandler
<
866 OCPP16StartTransactionRequest
,
867 OCPP16StartTransactionResponse
868 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
869 connectorId
: transactionConnectorId
,
870 idTag
: commandPayload
.idTag
,
872 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
875 chargingStation
.logPrefix() +
876 ' Transaction remotely STARTED on ' +
877 chargingStation
.stationInfo
.chargingStationId
+
879 transactionConnectorId
.toString() +
883 return Constants
.OCPP_RESPONSE_ACCEPTED
;
885 return this.notifyRemoteStartTransactionRejected(
887 transactionConnectorId
,
891 return this.notifyRemoteStartTransactionRejected(
893 transactionConnectorId
,
897 return this.notifyRemoteStartTransactionRejected(
899 transactionConnectorId
,
903 return this.notifyRemoteStartTransactionRejected(
905 transactionConnectorId
,
910 private async notifyRemoteStartTransactionRejected(
911 chargingStation
: ChargingStation
,
914 ): Promise
<DefaultResponse
> {
916 chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
918 await chargingStation
.ocppRequestService
.requestHandler
<
919 OCPP16StatusNotificationRequest
,
920 OCPP16StatusNotificationResponse
921 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
923 status: OCPP16ChargePointStatus
.AVAILABLE
,
924 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
926 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
929 chargingStation
.logPrefix() +
930 ' Remote starting transaction REJECTED on connector Id ' +
931 connectorId
.toString() +
935 chargingStation
.getConnectorStatus(connectorId
).availability
+
937 chargingStation
.getConnectorStatus(connectorId
).status
939 return Constants
.OCPP_RESPONSE_REJECTED
;
942 private setRemoteStartTransactionChargingProfile(
943 chargingStation
: ChargingStation
,
945 cp
: OCPP16ChargingProfile
947 if (cp
&& cp
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
948 chargingStation
.setChargingProfile(connectorId
, cp
);
950 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}, dump their stack: %j`,
951 chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
954 } else if (cp
&& cp
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
956 `${chargingStation.logPrefix()} Not allowed to set ${
957 cp.chargingProfilePurpose
958 } charging profile(s) at remote start transaction`
966 private async handleRequestRemoteStopTransaction(
967 chargingStation
: ChargingStation
,
968 commandPayload
: RemoteStopTransactionRequest
969 ): Promise
<DefaultResponse
> {
970 const transactionId
= commandPayload
.transactionId
;
971 for (const connectorId
of chargingStation
.connectors
.keys()) {
974 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
976 await chargingStation
.ocppRequestService
.requestHandler
<
977 OCPP16StatusNotificationRequest
,
978 OCPP16StatusNotificationResponse
979 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
981 status: OCPP16ChargePointStatus
.FINISHING
,
982 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
984 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.FINISHING
;
986 chargingStation
.getBeginEndMeterValues() &&
987 chargingStation
.getOcppStrictCompliance() &&
988 !chargingStation
.getOutOfOrderEndMeterValues()
990 // FIXME: Implement OCPP version agnostic helpers
991 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
994 chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
)
996 await chargingStation
.ocppRequestService
.requestHandler
<
997 OCPP16MeterValuesRequest
,
998 OCPP16MeterValuesResponse
999 >(chargingStation
, OCPP16RequestCommand
.METER_VALUES
, {
1002 meterValue
: [transactionEndMeterValue
],
1005 await chargingStation
.ocppRequestService
.requestHandler
<
1006 OCPP16StopTransactionRequest
,
1007 OCPP16StopTransactionResponse
1008 >(chargingStation
, OCPP16RequestCommand
.STOP_TRANSACTION
, {
1010 meterStop
: chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
1011 idTag
: chargingStation
.getTransactionIdTag(transactionId
),
1013 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1017 chargingStation
.logPrefix() +
1018 ' Trying to remote stop a non existing transaction ' +
1019 transactionId
.toString()
1021 return Constants
.OCPP_RESPONSE_REJECTED
;
1024 private async handleRequestGetDiagnostics(
1025 chargingStation
: ChargingStation
,
1026 commandPayload
: GetDiagnosticsRequest
1027 ): Promise
<GetDiagnosticsResponse
> {
1029 !OCPP16ServiceUtils
.checkFeatureProfile(
1031 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
1032 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1035 return Constants
.OCPP_RESPONSE_EMPTY
;
1038 chargingStation
.logPrefix() +
1040 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
+
1041 ' request received: %j',
1044 const uri
= new URL(commandPayload
.location
);
1045 if (uri
.protocol
.startsWith('ftp:')) {
1046 let ftpClient
: Client
;
1049 .readdirSync(path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'))
1050 .filter((file
) => file
.endsWith('.log'))
1051 .map((file
) => path
.join('./', file
));
1052 const diagnosticsArchive
= chargingStation
.stationInfo
.chargingStationId
+ '_logs.tar.gz';
1053 tar
.create({ gzip
: true }, logFiles
).pipe(fs
.createWriteStream(diagnosticsArchive
));
1054 ftpClient
= new Client();
1055 const accessResponse
= await ftpClient
.access({
1057 ...(!Utils
.isEmptyString(uri
.port
) && { port
: Utils
.convertToInt(uri
.port
) }),
1058 ...(!Utils
.isEmptyString(uri
.username
) && { user
: uri
.username
}),
1059 ...(!Utils
.isEmptyString(uri
.password
) && { password
: uri
.password
}),
1061 let uploadResponse
: FTPResponse
;
1062 if (accessResponse
.code
=== 220) {
1063 // eslint-disable-next-line @typescript-eslint/no-misused-promises
1064 ftpClient
.trackProgress(async (info
) => {
1066 `${chargingStation.logPrefix()} ${
1068 } bytes transferred from diagnostics archive ${info.name}`
1070 await chargingStation
.ocppRequestService
.requestHandler
<
1071 DiagnosticsStatusNotificationRequest
,
1072 DiagnosticsStatusNotificationResponse
1073 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1074 status: OCPP16DiagnosticsStatus
.Uploading
,
1077 uploadResponse
= await ftpClient
.uploadFrom(
1079 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'),
1082 uri
.pathname
+ diagnosticsArchive
1084 if (uploadResponse
.code
=== 226) {
1085 await chargingStation
.ocppRequestService
.requestHandler
<
1086 DiagnosticsStatusNotificationRequest
,
1087 DiagnosticsStatusNotificationResponse
1088 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1089 status: OCPP16DiagnosticsStatus
.Uploaded
,
1094 return { fileName
: diagnosticsArchive
};
1096 throw new OCPPError(
1097 ErrorType
.GENERIC_ERROR
,
1098 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1099 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1101 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1104 throw new OCPPError(
1105 ErrorType
.GENERIC_ERROR
,
1106 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
1107 uploadResponse?.code && '|' + uploadResponse?.code.toString()
1109 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
1112 await chargingStation
.ocppRequestService
.requestHandler
<
1113 DiagnosticsStatusNotificationRequest
,
1114 DiagnosticsStatusNotificationResponse
1115 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1116 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1121 return this.handleIncomingRequestError(
1123 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
1125 { errorResponse
: Constants
.OCPP_RESPONSE_EMPTY
}
1130 `${chargingStation.logPrefix()} Unsupported protocol ${
1132 } to transfer the diagnostic logs archive`
1134 await chargingStation
.ocppRequestService
.requestHandler
<
1135 DiagnosticsStatusNotificationRequest
,
1136 DiagnosticsStatusNotificationResponse
1137 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
1138 status: OCPP16DiagnosticsStatus
.UploadFailed
,
1140 return Constants
.OCPP_RESPONSE_EMPTY
;
1144 private handleRequestTriggerMessage(
1145 chargingStation
: ChargingStation
,
1146 commandPayload
: OCPP16TriggerMessageRequest
1147 ): OCPP16TriggerMessageResponse
{
1149 !OCPP16ServiceUtils
.checkFeatureProfile(
1151 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
1152 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
1155 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1157 // TODO: factor out the check on connector id
1158 if (commandPayload
?.connectorId
< 0) {
1160 `${chargingStation.logPrefix()} ${
1161 OCPP16IncomingRequestCommand.TRIGGER_MESSAGE
1162 } incoming request received with invalid connectorId ${commandPayload.connectorId}`
1164 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1167 switch (commandPayload
.requestedMessage
) {
1168 case MessageTrigger
.BootNotification
:
1170 chargingStation
.ocppRequestService
1171 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1173 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
1175 chargePointModel
: chargingStation
.getBootNotificationRequest().chargePointModel
,
1176 chargePointVendor
: chargingStation
.getBootNotificationRequest().chargePointVendor
,
1177 chargeBoxSerialNumber
:
1178 chargingStation
.getBootNotificationRequest().chargeBoxSerialNumber
,
1179 firmwareVersion
: chargingStation
.getBootNotificationRequest().firmwareVersion
,
1180 chargePointSerialNumber
:
1181 chargingStation
.getBootNotificationRequest().chargePointSerialNumber
,
1182 iccid
: chargingStation
.getBootNotificationRequest().iccid
,
1183 imsi
: chargingStation
.getBootNotificationRequest().imsi
,
1184 meterSerialNumber
: chargingStation
.getBootNotificationRequest().meterSerialNumber
,
1185 meterType
: chargingStation
.getBootNotificationRequest().meterType
,
1187 { skipBufferingOnError
: true, triggerMessage
: true }
1190 chargingStation
.bootNotificationResponse
= value
;
1193 /* This is intentional */
1195 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1196 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1197 case MessageTrigger
.Heartbeat
:
1199 chargingStation
.ocppRequestService
1200 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1202 OCPP16RequestCommand
.HEARTBEAT
,
1205 triggerMessage
: true,
1209 /* This is intentional */
1211 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1212 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1213 case MessageTrigger
.StatusNotification
:
1215 if (commandPayload
?.connectorId
) {
1216 chargingStation
.ocppRequestService
1217 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1219 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1221 connectorId
: commandPayload
.connectorId
,
1222 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1223 status: chargingStation
.getConnectorStatus(commandPayload
.connectorId
).status,
1226 triggerMessage
: true,
1230 /* This is intentional */
1233 for (const connectorId
of chargingStation
.connectors
.keys()) {
1234 chargingStation
.ocppRequestService
1236 OCPP16StatusNotificationRequest
,
1237 OCPP16StatusNotificationResponse
1240 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1243 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1244 status: chargingStation
.getConnectorStatus(connectorId
).status,
1247 triggerMessage
: true,
1251 /* This is intentional */
1255 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1256 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1258 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1261 return this.handleIncomingRequestError(
1263 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1265 { errorResponse
: Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
}