1 import { ChangeAvailabilityRequest
, ChangeConfigurationRequest
, ClearChargingProfileRequest
, GetConfigurationRequest
, OCPP16AvailabilityType
, OCPP16IncomingRequestCommand
, RemoteStartTransactionRequest
, RemoteStopTransactionRequest
, ResetRequest
, SetChargingProfileRequest
, UnlockConnectorRequest
} from
'../../../types/ocpp/1.6/Requests';
2 import { ChangeAvailabilityResponse
, ChangeConfigurationResponse
, ClearChargingProfileResponse
, DefaultResponse
, GetConfigurationResponse
, SetChargingProfileResponse
, UnlockConnectorResponse
} from
'../../../types/ocpp/1.6/Responses';
3 import { ChargingProfilePurposeType
, OCPP16ChargingProfile
} from
'../../../types/ocpp/1.6/ChargingProfile';
4 import { OCPP16AuthorizationStatus
, OCPP16StopTransactionReason
} from
'../../../types/ocpp/1.6/Transaction';
6 import Constants from
'../../../utils/Constants';
7 import { ErrorType
} from
'../../../types/ocpp/ErrorType';
8 import { MessageType
} from
'../../../types/ocpp/MessageType';
9 import { OCPP16ChargePointStatus
} from
'../../../types/ocpp/1.6/ChargePointStatus';
10 import { OCPP16StandardParametersKey
} from
'../../../types/ocpp/1.6/Configuration';
11 import { OCPPConfigurationKey
} from
'../../../types/ocpp/Configuration';
12 import OCPPError from
'../../OcppError';
13 import OCPPIncomingRequestService from
'../OCPPIncomingRequestService';
14 import Utils from
'../../../utils/Utils';
15 import logger from
'../../../utils/Logger';
17 export default class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
18 public async handleRequest(messageId
: string, commandName
: OCPP16IncomingRequestCommand
, commandPayload
: Record
<string, unknown
>): Promise
<void> {
21 if (typeof this['handleRequest' + commandName
] === 'function') {
23 // Call the method to build the response
24 response
= await this['handleRequest' + commandName
](commandPayload
);
27 logger
.error(this.chargingStation
.logPrefix() + ' Handle request error: %j', error
);
28 // Send back an error response to inform backend
29 await this.chargingStation
.ocppRequestService
.sendError(messageId
, error
, commandName
);
34 await this.chargingStation
.ocppRequestService
.sendError(messageId
, new OCPPError(ErrorType
.NOT_IMPLEMENTED
, `${commandName} is not implemented`, {}), commandName
);
35 throw new Error(`${commandName} is not implemented to handle payload ${JSON.stringify(commandPayload)}`);
37 // Send the built response
38 await this.chargingStation
.ocppRequestService
.sendMessage(messageId
, response
, MessageType
.CALL_RESULT_MESSAGE
, commandName
);
41 // Simulate charging station restart
42 private handleRequestReset(commandPayload
: ResetRequest
): DefaultResponse
{
43 // eslint-disable-next-line @typescript-eslint/no-misused-promises
44 setImmediate(async (): Promise
<void> => {
45 await this.chargingStation
.stop(commandPayload
.type + 'Reset' as OCPP16StopTransactionReason
);
46 await Utils
.sleep(this.chargingStation
.stationInfo
.resetTime
);
47 this.chargingStation
.start();
49 logger
.info(`${this.chargingStation.logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${Utils.milliSecondsToHHMMSS(this.chargingStation.stationInfo.resetTime)}`);
50 return Constants
.OCPP_RESPONSE_ACCEPTED
;
53 private handleRequestClearCache(): DefaultResponse
{
54 return Constants
.OCPP_RESPONSE_ACCEPTED
;
57 private async handleRequestUnlockConnector(commandPayload
: UnlockConnectorRequest
): Promise
<UnlockConnectorResponse
> {
58 const connectorId
= commandPayload
.connectorId
;
59 if (connectorId
=== 0) {
60 logger
.error(this.chargingStation
.logPrefix() + ' Trying to unlock connector ' + connectorId
.toString());
61 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
63 if (this.chargingStation
.getConnector(connectorId
)?.transactionStarted
) {
64 const transactionId
= this.chargingStation
.getConnector(connectorId
).transactionId
;
65 const stopResponse
= await this.chargingStation
.ocppRequestService
.sendStopTransaction(transactionId
, this.chargingStation
.getTransactionMeterStop(transactionId
), this.chargingStation
.getTransactionIdTag(transactionId
), OCPP16StopTransactionReason
.UNLOCK_COMMAND
);
66 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
67 return Constants
.OCPP_RESPONSE_UNLOCKED
;
69 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
71 await this.chargingStation
.ocppRequestService
.sendStatusNotification(connectorId
, OCPP16ChargePointStatus
.AVAILABLE
);
72 this.chargingStation
.getConnector(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
73 return Constants
.OCPP_RESPONSE_UNLOCKED
;
76 private handleRequestGetConfiguration(commandPayload
: GetConfigurationRequest
): GetConfigurationResponse
{
77 const configurationKey
: OCPPConfigurationKey
[] = [];
78 const unknownKey
: string[] = [];
79 if (Utils
.isEmptyArray(commandPayload
.key
)) {
80 for (const configuration
of this.chargingStation
.configuration
.configurationKey
) {
81 if (Utils
.isUndefined(configuration
.visible
)) {
82 configuration
.visible
= true;
84 if (!configuration
.visible
) {
87 configurationKey
.push({
88 key
: configuration
.key
,
89 readonly: configuration
.readonly,
90 value
: configuration
.value
,
94 for (const key
of commandPayload
.key
) {
95 const keyFound
= this.chargingStation
.getConfigurationKey(key
);
97 if (Utils
.isUndefined(keyFound
.visible
)) {
98 keyFound
.visible
= true;
100 if (!keyFound
.visible
) {
103 configurationKey
.push({
105 readonly: keyFound
.readonly,
106 value
: keyFound
.value
,
109 unknownKey
.push(key
);
119 private handleRequestChangeConfiguration(commandPayload
: ChangeConfigurationRequest
): ChangeConfigurationResponse
{
120 // JSON request fields type sanity check
121 if (!Utils
.isString(commandPayload
.key
)) {
122 logger
.error(`${this.chargingStation.logPrefix()} ChangeConfiguration request key field is not a string:`, commandPayload
);
124 if (!Utils
.isString(commandPayload
.value
)) {
125 logger
.error(`${this.chargingStation.logPrefix()} ChangeConfiguration request value field is not a string:`, commandPayload
);
127 const keyToChange
= this.chargingStation
.getConfigurationKey(commandPayload
.key
, true);
129 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
130 } else if (keyToChange
&& keyToChange
.readonly) {
131 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
132 } else if (keyToChange
&& !keyToChange
.readonly) {
133 const keyIndex
= this.chargingStation
.configuration
.configurationKey
.indexOf(keyToChange
);
134 let valueChanged
= false;
135 if (this.chargingStation
.configuration
.configurationKey
[keyIndex
].value
!== commandPayload
.value
) {
136 this.chargingStation
.configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
139 let triggerHeartbeatRestart
= false;
140 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
141 this.chargingStation
.setConfigurationKeyValue(OCPP16StandardParametersKey
.HeartbeatInterval
, commandPayload
.value
);
142 triggerHeartbeatRestart
= true;
144 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
145 this.chargingStation
.setConfigurationKeyValue(OCPP16StandardParametersKey
.HeartBeatInterval
, commandPayload
.value
);
146 triggerHeartbeatRestart
= true;
148 if (triggerHeartbeatRestart
) {
149 this.chargingStation
.restartHeartbeat();
151 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
152 this.chargingStation
.restartWebSocketPing();
154 if (keyToChange
.reboot
) {
155 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
157 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
161 private handleRequestSetChargingProfile(commandPayload
: SetChargingProfileRequest
): SetChargingProfileResponse
{
162 if (!this.chargingStation
.getConnector(commandPayload
.connectorId
)) {
163 logger
.error(`${this.chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${commandPayload.connectorId}`);
164 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
166 if (commandPayload
.csChargingProfiles
.chargingProfilePurpose
=== ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&& commandPayload
.connectorId
!== 0) {
167 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
169 if (commandPayload
.csChargingProfiles
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
&& (commandPayload
.connectorId
=== 0 || !this.chargingStation
.getConnector(commandPayload
.connectorId
)?.transactionStarted
)) {
170 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
172 this.chargingStation
.setChargingProfile(commandPayload
.connectorId
, commandPayload
.csChargingProfiles
);
173 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set, dump their stack: %j`, this.chargingStation
.getConnector(commandPayload
.connectorId
).chargingProfiles
);
174 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
177 private handleRequestClearChargingProfile(commandPayload
: ClearChargingProfileRequest
): ClearChargingProfileResponse
{
178 if (!this.chargingStation
.getConnector(commandPayload
.connectorId
)) {
179 logger
.error(`${this.chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${commandPayload.connectorId}`);
180 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
182 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(this.chargingStation
.getConnector(commandPayload
.connectorId
).chargingProfiles
)) {
183 this.chargingStation
.getConnector(commandPayload
.connectorId
).chargingProfiles
= [];
184 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`, this.chargingStation
.getConnector(commandPayload
.connectorId
).chargingProfiles
);
185 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
187 if (!commandPayload
.connectorId
) {
188 let clearedCP
= false;
189 for (const connector
in this.chargingStation
.connectors
) {
190 if (!Utils
.isEmptyArray(this.chargingStation
.getConnector(Utils
.convertToInt(connector
)).chargingProfiles
)) {
191 this.chargingStation
.getConnector(Utils
.convertToInt(connector
)).chargingProfiles
.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
192 let clearCurrentCP
= false;
193 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
194 clearCurrentCP
= true;
196 if (!commandPayload
.chargingProfilePurpose
&& chargingProfile
.stackLevel
=== commandPayload
.stackLevel
) {
197 clearCurrentCP
= true;
199 if (!chargingProfile
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
) {
200 clearCurrentCP
= true;
202 if (chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
) {
203 clearCurrentCP
= true;
205 if (clearCurrentCP
) {
206 this.chargingStation
.getConnector(commandPayload
.connectorId
).chargingProfiles
[index
] = {} as OCPP16ChargingProfile
;
207 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`, this.chargingStation
.getConnector(commandPayload
.connectorId
).chargingProfiles
);
214 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
217 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
220 private async handleRequestChangeAvailability(commandPayload
: ChangeAvailabilityRequest
): Promise
<ChangeAvailabilityResponse
> {
221 const connectorId
: number = commandPayload
.connectorId
;
222 if (!this.chargingStation
.getConnector(connectorId
)) {
223 logger
.error(`${this.chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`);
224 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
226 const chargePointStatus
: OCPP16ChargePointStatus
= commandPayload
.type === OCPP16AvailabilityType
.OPERATIVE
? OCPP16ChargePointStatus
.AVAILABLE
: OCPP16ChargePointStatus
.UNAVAILABLE
;
227 if (connectorId
=== 0) {
228 let response
: ChangeAvailabilityResponse
= Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
229 for (const connector
in this.chargingStation
.connectors
) {
230 if (this.chargingStation
.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
231 response
= Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
233 this.chargingStation
.getConnector(Utils
.convertToInt(connector
)).availability
= commandPayload
.type;
234 if (response
=== Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
) {
235 await this.chargingStation
.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), chargePointStatus
);
236 this.chargingStation
.getConnector(Utils
.convertToInt(connector
)).status = chargePointStatus
;
240 } else if (connectorId
> 0 && (this.chargingStation
.getConnector(0).availability
=== OCPP16AvailabilityType
.OPERATIVE
|| (this.chargingStation
.getConnector(0).availability
=== OCPP16AvailabilityType
.INOPERATIVE
&& commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))) {
241 if (this.chargingStation
.getConnector(connectorId
)?.transactionStarted
) {
242 this.chargingStation
.getConnector(connectorId
).availability
= commandPayload
.type;
243 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
245 this.chargingStation
.getConnector(connectorId
).availability
= commandPayload
.type;
246 await this.chargingStation
.ocppRequestService
.sendStatusNotification(connectorId
, chargePointStatus
);
247 this.chargingStation
.getConnector(connectorId
).status = chargePointStatus
;
248 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
250 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
253 private async handleRequestRemoteStartTransaction(commandPayload
: RemoteStartTransactionRequest
): Promise
<DefaultResponse
> {
254 const transactionConnectorID
: number = commandPayload
.connectorId
? commandPayload
.connectorId
: 1;
255 if (this.chargingStation
.isChargingStationAvailable() && this.chargingStation
.isConnectorAvailable(transactionConnectorID
)) {
256 if (this.chargingStation
.getAuthorizeRemoteTxRequests() && this.chargingStation
.getLocalAuthListEnabled() && this.chargingStation
.hasAuthorizedTags()) {
257 // Check if authorized
258 if (this.chargingStation
.authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
259 await this.chargingStation
.ocppRequestService
.sendStatusNotification(transactionConnectorID
, OCPP16ChargePointStatus
.PREPARING
);
260 this.chargingStation
.getConnector(transactionConnectorID
).status = OCPP16ChargePointStatus
.PREPARING
;
261 if (commandPayload
.chargingProfile
&& commandPayload
.chargingProfile
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
262 this.chargingStation
.setChargingProfile(transactionConnectorID
, commandPayload
.chargingProfile
);
263 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set at start transaction, dump their stack: %j`, this.chargingStation
.getConnector(transactionConnectorID
).chargingProfiles
);
264 } else if (commandPayload
.chargingProfile
&& commandPayload
.chargingProfile
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
265 return Constants
.OCPP_RESPONSE_REJECTED
;
267 // Authorization successful start transaction
268 await this.chargingStation
.ocppRequestService
.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
);
269 logger
.debug(this.chargingStation
.logPrefix() + ' Transaction remotely STARTED on ' + this.chargingStation
.stationInfo
.chargingStationId
+ '#' + transactionConnectorID
.toString() + ' for idTag ' + commandPayload
.idTag
);
270 return Constants
.OCPP_RESPONSE_ACCEPTED
;
272 logger
.error(this.chargingStation
.logPrefix() + ' Remote starting transaction REJECTED on connector Id ' + transactionConnectorID
.toString() + ', idTag ' + commandPayload
.idTag
);
273 return Constants
.OCPP_RESPONSE_REJECTED
;
275 await this.chargingStation
.ocppRequestService
.sendStatusNotification(transactionConnectorID
, OCPP16ChargePointStatus
.PREPARING
);
276 this.chargingStation
.getConnector(transactionConnectorID
).status = OCPP16ChargePointStatus
.PREPARING
;
277 if (commandPayload
.chargingProfile
&& commandPayload
.chargingProfile
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
278 this.chargingStation
.setChargingProfile(transactionConnectorID
, commandPayload
.chargingProfile
);
279 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set at start transaction, dump their stack: %j`, this.chargingStation
.getConnector(commandPayload
.connectorId
).chargingProfiles
);
280 } else if (commandPayload
.chargingProfile
&& commandPayload
.chargingProfile
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
281 return Constants
.OCPP_RESPONSE_REJECTED
;
283 // No local authorization check required => start transaction
284 await this.chargingStation
.ocppRequestService
.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
);
285 logger
.debug(this.chargingStation
.logPrefix() + ' Transaction remotely STARTED on ' + this.chargingStation
.stationInfo
.chargingStationId
+ '#' + transactionConnectorID
.toString() + ' for idTag ' + commandPayload
.idTag
);
286 return Constants
.OCPP_RESPONSE_ACCEPTED
;
288 logger
.error(this.chargingStation
.logPrefix() + ' Remote starting transaction REJECTED on unavailable connector Id ' + transactionConnectorID
.toString() + ', idTag ' + commandPayload
.idTag
);
289 return Constants
.OCPP_RESPONSE_REJECTED
;
292 private async handleRequestRemoteStopTransaction(commandPayload
: RemoteStopTransactionRequest
): Promise
<DefaultResponse
> {
293 const transactionId
= commandPayload
.transactionId
;
294 for (const connector
in this.chargingStation
.connectors
) {
295 if (Utils
.convertToInt(connector
) > 0 && this.chargingStation
.getConnector(Utils
.convertToInt(connector
))?.transactionId
=== transactionId
) {
296 await this.chargingStation
.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), OCPP16ChargePointStatus
.FINISHING
);
297 this.chargingStation
.getConnector(Utils
.convertToInt(connector
)).status = OCPP16ChargePointStatus
.FINISHING
;
298 await this.chargingStation
.ocppRequestService
.sendStopTransaction(transactionId
, this.chargingStation
.getTransactionMeterStop(transactionId
), this.chargingStation
.getTransactionIdTag(transactionId
));
299 return Constants
.OCPP_RESPONSE_ACCEPTED
;
302 logger
.info(this.chargingStation
.logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId
.toString());
303 return Constants
.OCPP_RESPONSE_REJECTED
;