1 import { ChangeAvailabilityRequest
, ChangeConfigurationRequest
, ClearChargingProfileRequest
, GetConfigurationRequest
, OCPP16AvailabilityType
, OCPP16IncomingRequestCommand
, RemoteStartTransactionRequest
, RemoteStopTransactionRequest
, ResetRequest
, SetChargingProfileRequest
, UnlockConnectorRequest
} from
'../../../types/ocpp/1.6/Requests';
2 import { ChangeAvailabilityResponse
, ChangeConfigurationResponse
, ClearChargingProfileResponse
, 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 { DefaultResponse
} from
'../../../types/ocpp/Responses';
8 import { ErrorType
} from
'../../../types/ocpp/ErrorType';
9 import { MessageType
} from
'../../../types/ocpp/MessageType';
10 import { OCPP16ChargePointStatus
} from
'../../../types/ocpp/1.6/ChargePointStatus';
11 import { OCPP16StandardParametersKey
} from
'../../../types/ocpp/1.6/Configuration';
12 import { OCPPConfigurationKey
} from
'../../../types/ocpp/Configuration';
13 import OCPPError from
'../../OcppError';
14 import OCPPIncomingRequestService from
'../OCPPIncomingRequestService';
15 import Utils from
'../../../utils/Utils';
16 import logger from
'../../../utils/Logger';
18 export default class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
19 public async handleRequest(messageId
: string, commandName
: OCPP16IncomingRequestCommand
, commandPayload
: Record
<string, unknown
>): Promise
<void> {
21 const methodName
= `handleRequest${commandName}`;
23 if (typeof this[methodName
] === 'function') {
25 // Call the method to build the response
26 response
= await this[methodName
](commandPayload
);
29 logger
.error(this.chargingStation
.logPrefix() + ' Handle request error: %j', error
);
30 // Send back an error response to inform backend
31 await this.chargingStation
.ocppRequestService
.sendError(messageId
, error
, commandName
);
36 await this.chargingStation
.ocppRequestService
.sendError(messageId
, new OCPPError(ErrorType
.NOT_IMPLEMENTED
, `${commandName} is not implemented`, {}), commandName
);
37 throw new Error(`${commandName} is not implemented to handle payload ${JSON.stringify(commandPayload)}`);
39 // Send the built response
40 await this.chargingStation
.ocppRequestService
.sendMessage(messageId
, response
, MessageType
.CALL_RESULT_MESSAGE
, commandName
);
43 // Simulate charging station restart
44 private handleRequestReset(commandPayload
: ResetRequest
): DefaultResponse
{
45 // eslint-disable-next-line @typescript-eslint/no-misused-promises
46 setImmediate(async (): Promise
<void> => {
47 await this.chargingStation
.stop(commandPayload
.type + 'Reset' as OCPP16StopTransactionReason
);
48 await Utils
.sleep(this.chargingStation
.stationInfo
.resetTime
);
49 this.chargingStation
.start();
51 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)}`);
52 return Constants
.OCPP_RESPONSE_ACCEPTED
;
55 private handleRequestClearCache(): DefaultResponse
{
56 return Constants
.OCPP_RESPONSE_ACCEPTED
;
59 private async handleRequestUnlockConnector(commandPayload
: UnlockConnectorRequest
): Promise
<UnlockConnectorResponse
> {
60 const connectorId
= commandPayload
.connectorId
;
61 if (connectorId
=== 0) {
62 logger
.error(this.chargingStation
.logPrefix() + ' Trying to unlock connector ' + connectorId
.toString());
63 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
65 if (this.chargingStation
.getConnector(connectorId
)?.transactionStarted
) {
66 const transactionId
= this.chargingStation
.getConnector(connectorId
).transactionId
;
67 const stopResponse
= await this.chargingStation
.ocppRequestService
.sendStopTransaction(transactionId
,
68 this.chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
69 this.chargingStation
.getTransactionIdTag(transactionId
),
70 OCPP16StopTransactionReason
.UNLOCK_COMMAND
);
71 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
72 return Constants
.OCPP_RESPONSE_UNLOCKED
;
74 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
76 await this.chargingStation
.ocppRequestService
.sendStatusNotification(connectorId
, OCPP16ChargePointStatus
.AVAILABLE
);
77 this.chargingStation
.getConnector(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
78 return Constants
.OCPP_RESPONSE_UNLOCKED
;
81 private handleRequestGetConfiguration(commandPayload
: GetConfigurationRequest
): GetConfigurationResponse
{
82 const configurationKey
: OCPPConfigurationKey
[] = [];
83 const unknownKey
: string[] = [];
84 if (Utils
.isEmptyArray(commandPayload
.key
)) {
85 for (const configuration
of this.chargingStation
.configuration
.configurationKey
) {
86 if (Utils
.isUndefined(configuration
.visible
)) {
87 configuration
.visible
= true;
89 if (!configuration
.visible
) {
92 configurationKey
.push({
93 key
: configuration
.key
,
94 readonly: configuration
.readonly,
95 value
: configuration
.value
,
99 for (const key
of commandPayload
.key
) {
100 const keyFound
= this.chargingStation
.getConfigurationKey(key
);
102 if (Utils
.isUndefined(keyFound
.visible
)) {
103 keyFound
.visible
= true;
105 if (!keyFound
.visible
) {
108 configurationKey
.push({
110 readonly: keyFound
.readonly,
111 value
: keyFound
.value
,
114 unknownKey
.push(key
);
124 private handleRequestChangeConfiguration(commandPayload
: ChangeConfigurationRequest
): ChangeConfigurationResponse
{
125 // JSON request fields type sanity check
126 if (!Utils
.isString(commandPayload
.key
)) {
127 logger
.error(`${this.chargingStation.logPrefix()} ChangeConfiguration request key field is not a string:`, commandPayload
);
129 if (!Utils
.isString(commandPayload
.value
)) {
130 logger
.error(`${this.chargingStation.logPrefix()} ChangeConfiguration request value field is not a string:`, commandPayload
);
132 const keyToChange
= this.chargingStation
.getConfigurationKey(commandPayload
.key
, true);
134 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
135 } else if (keyToChange
&& keyToChange
.readonly) {
136 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
137 } else if (keyToChange
&& !keyToChange
.readonly) {
138 const keyIndex
= this.chargingStation
.configuration
.configurationKey
.indexOf(keyToChange
);
139 let valueChanged
= false;
140 if (this.chargingStation
.configuration
.configurationKey
[keyIndex
].value
!== commandPayload
.value
) {
141 this.chargingStation
.configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
144 let triggerHeartbeatRestart
= false;
145 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
146 this.chargingStation
.setConfigurationKeyValue(OCPP16StandardParametersKey
.HeartbeatInterval
, commandPayload
.value
);
147 triggerHeartbeatRestart
= true;
149 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
150 this.chargingStation
.setConfigurationKeyValue(OCPP16StandardParametersKey
.HeartBeatInterval
, commandPayload
.value
);
151 triggerHeartbeatRestart
= true;
153 if (triggerHeartbeatRestart
) {
154 this.chargingStation
.restartHeartbeat();
156 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
157 this.chargingStation
.restartWebSocketPing();
159 if (keyToChange
.reboot
) {
160 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
162 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
166 private handleRequestSetChargingProfile(commandPayload
: SetChargingProfileRequest
): SetChargingProfileResponse
{
167 if (!this.chargingStation
.getConnector(commandPayload
.connectorId
)) {
168 logger
.error(`${this.chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${commandPayload.connectorId}`);
169 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
171 if (commandPayload
.csChargingProfiles
.chargingProfilePurpose
=== ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&& commandPayload
.connectorId
!== 0) {
172 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
174 if (commandPayload
.csChargingProfiles
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
&& (commandPayload
.connectorId
=== 0 || !this.chargingStation
.getConnector(commandPayload
.connectorId
)?.transactionStarted
)) {
175 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
177 this.chargingStation
.setChargingProfile(commandPayload
.connectorId
, commandPayload
.csChargingProfiles
);
178 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set, dump their stack: %j`, this.chargingStation
.getConnector(commandPayload
.connectorId
).chargingProfiles
);
179 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
182 private handleRequestClearChargingProfile(commandPayload
: ClearChargingProfileRequest
): ClearChargingProfileResponse
{
183 if (!this.chargingStation
.getConnector(commandPayload
.connectorId
)) {
184 logger
.error(`${this.chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${commandPayload.connectorId}`);
185 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
187 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(this.chargingStation
.getConnector(commandPayload
.connectorId
).chargingProfiles
)) {
188 this.chargingStation
.getConnector(commandPayload
.connectorId
).chargingProfiles
= [];
189 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`, this.chargingStation
.getConnector(commandPayload
.connectorId
).chargingProfiles
);
190 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
192 if (!commandPayload
.connectorId
) {
193 let clearedCP
= false;
194 for (const connector
in this.chargingStation
.connectors
) {
195 if (!Utils
.isEmptyArray(this.chargingStation
.getConnector(Utils
.convertToInt(connector
)).chargingProfiles
)) {
196 this.chargingStation
.getConnector(Utils
.convertToInt(connector
)).chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
197 let clearCurrentCP
= false;
198 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
199 clearCurrentCP
= true;
201 if (!commandPayload
.chargingProfilePurpose
&& chargingProfile
.stackLevel
=== commandPayload
.stackLevel
) {
202 clearCurrentCP
= true;
204 if (!chargingProfile
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
) {
205 clearCurrentCP
= true;
207 if (chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
) {
208 clearCurrentCP
= true;
210 if (clearCurrentCP
) {
211 this.chargingStation
.getConnector(commandPayload
.connectorId
).chargingProfiles
[index
] = {} as OCPP16ChargingProfile
;
212 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`, this.chargingStation
.getConnector(commandPayload
.connectorId
).chargingProfiles
);
219 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
222 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
225 private async handleRequestChangeAvailability(commandPayload
: ChangeAvailabilityRequest
): Promise
<ChangeAvailabilityResponse
> {
226 const connectorId
: number = commandPayload
.connectorId
;
227 if (!this.chargingStation
.getConnector(connectorId
)) {
228 logger
.error(`${this.chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`);
229 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
231 const chargePointStatus
: OCPP16ChargePointStatus
= commandPayload
.type === OCPP16AvailabilityType
.OPERATIVE
? OCPP16ChargePointStatus
.AVAILABLE
: OCPP16ChargePointStatus
.UNAVAILABLE
;
232 if (connectorId
=== 0) {
233 let response
: ChangeAvailabilityResponse
= Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
234 for (const connector
in this.chargingStation
.connectors
) {
235 if (this.chargingStation
.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
236 response
= Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
238 this.chargingStation
.getConnector(Utils
.convertToInt(connector
)).availability
= commandPayload
.type;
239 if (response
=== Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
) {
240 await this.chargingStation
.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), chargePointStatus
);
241 this.chargingStation
.getConnector(Utils
.convertToInt(connector
)).status = chargePointStatus
;
245 } else if (connectorId
> 0 && (this.chargingStation
.getConnector(0).availability
=== OCPP16AvailabilityType
.OPERATIVE
|| (this.chargingStation
.getConnector(0).availability
=== OCPP16AvailabilityType
.INOPERATIVE
&& commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))) {
246 if (this.chargingStation
.getConnector(connectorId
)?.transactionStarted
) {
247 this.chargingStation
.getConnector(connectorId
).availability
= commandPayload
.type;
248 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
250 this.chargingStation
.getConnector(connectorId
).availability
= commandPayload
.type;
251 await this.chargingStation
.ocppRequestService
.sendStatusNotification(connectorId
, chargePointStatus
);
252 this.chargingStation
.getConnector(connectorId
).status = chargePointStatus
;
253 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
255 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
258 private async handleRequestRemoteStartTransaction(commandPayload
: RemoteStartTransactionRequest
): Promise
<DefaultResponse
> {
259 const transactionConnectorID
: number = commandPayload
.connectorId
?? 1;
260 await this.chargingStation
.ocppRequestService
.sendStatusNotification(transactionConnectorID
, OCPP16ChargePointStatus
.PREPARING
);
261 this.chargingStation
.getConnector(transactionConnectorID
).status = OCPP16ChargePointStatus
.PREPARING
;
262 if (this.chargingStation
.isChargingStationAvailable() && this.chargingStation
.isConnectorAvailable(transactionConnectorID
)) {
263 if (this.chargingStation
.getAuthorizeRemoteTxRequests()) {
264 let authorized
= false;
265 // Check if authorized
266 if (this.chargingStation
.getLocalAuthListEnabled() && this.chargingStation
.hasAuthorizedTags()
267 && this.chargingStation
.authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
269 if (commandPayload
.chargingProfile
&& commandPayload
.chargingProfile
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
270 this.chargingStation
.setChargingProfile(transactionConnectorID
, commandPayload
.chargingProfile
);
271 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set at remote start transaction, dump their stack: %j`, this.chargingStation
.getConnector(transactionConnectorID
).chargingProfiles
);
272 } else if (commandPayload
.chargingProfile
&& commandPayload
.chargingProfile
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
273 await this.chargingStation
.ocppRequestService
.sendStatusNotification(transactionConnectorID
, OCPP16ChargePointStatus
.AVAILABLE
);
274 this.chargingStation
.getConnector(transactionConnectorID
).status = OCPP16ChargePointStatus
.AVAILABLE
;
275 logger
.warn(`${this.chargingStation.logPrefix()} Not allowed to set ${commandPayload.chargingProfile.chargingProfilePurpose} charging profile(s) at remote start transaction`);
276 return Constants
.OCPP_RESPONSE_REJECTED
;
280 const authorizeResponse
= await this.chargingStation
.ocppRequestService
.sendAuthorize(commandPayload
.idTag
);
281 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
286 // Authorization successful, start transaction
287 await this.chargingStation
.ocppRequestService
.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
);
288 logger
.debug(this.chargingStation
.logPrefix() + ' Transaction remotely STARTED on ' + this.chargingStation
.stationInfo
.chargingStationId
+ '#' + transactionConnectorID
.toString() + ' for idTag ' + commandPayload
.idTag
);
289 return Constants
.OCPP_RESPONSE_ACCEPTED
;
291 await this.chargingStation
.ocppRequestService
.sendStatusNotification(transactionConnectorID
, OCPP16ChargePointStatus
.AVAILABLE
);
292 this.chargingStation
.getConnector(transactionConnectorID
).status = OCPP16ChargePointStatus
.AVAILABLE
;
293 logger
.warn(this.chargingStation
.logPrefix() + ' Remote starting transaction REJECTED on connector Id ' + transactionConnectorID
.toString() + ', idTag ' + commandPayload
.idTag
);
294 return Constants
.OCPP_RESPONSE_REJECTED
;
296 if (commandPayload
.chargingProfile
&& commandPayload
.chargingProfile
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
297 this.chargingStation
.setChargingProfile(transactionConnectorID
, commandPayload
.chargingProfile
);
298 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set at remote start transaction, dump their stack: %j`, this.chargingStation
.getConnector(commandPayload
.connectorId
).chargingProfiles
);
299 } else if (commandPayload
.chargingProfile
&& commandPayload
.chargingProfile
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
300 await this.chargingStation
.ocppRequestService
.sendStatusNotification(transactionConnectorID
, OCPP16ChargePointStatus
.AVAILABLE
);
301 this.chargingStation
.getConnector(transactionConnectorID
).status = OCPP16ChargePointStatus
.AVAILABLE
;
302 logger
.warn(`${this.chargingStation.logPrefix()} Not allowed to set ${commandPayload.chargingProfile.chargingProfilePurpose} charging profile(s) at remote start transaction`);
303 return Constants
.OCPP_RESPONSE_REJECTED
;
305 // No authorization check required, start transaction
306 await this.chargingStation
.ocppRequestService
.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
);
307 logger
.debug(this.chargingStation
.logPrefix() + ' Transaction remotely STARTED on ' + this.chargingStation
.stationInfo
.chargingStationId
+ '#' + transactionConnectorID
.toString() + ' for idTag ' + commandPayload
.idTag
);
308 return Constants
.OCPP_RESPONSE_ACCEPTED
;
310 await this.chargingStation
.ocppRequestService
.sendStatusNotification(transactionConnectorID
, OCPP16ChargePointStatus
.AVAILABLE
);
311 this.chargingStation
.getConnector(transactionConnectorID
).status = OCPP16ChargePointStatus
.AVAILABLE
;
312 logger
.warn(this.chargingStation
.logPrefix() + ' Remote starting transaction REJECTED on unavailable connector Id ' + transactionConnectorID
.toString() + ', idTag ' + commandPayload
.idTag
);
313 return Constants
.OCPP_RESPONSE_REJECTED
;
316 private async handleRequestRemoteStopTransaction(commandPayload
: RemoteStopTransactionRequest
): Promise
<DefaultResponse
> {
317 const transactionId
= commandPayload
.transactionId
;
318 for (const connector
in this.chargingStation
.connectors
) {
319 if (Utils
.convertToInt(connector
) > 0 && this.chargingStation
.getConnector(Utils
.convertToInt(connector
))?.transactionId
=== transactionId
) {
320 await this.chargingStation
.ocppRequestService
.sendStatusNotification(Utils
.convertToInt(connector
), OCPP16ChargePointStatus
.FINISHING
);
321 this.chargingStation
.getConnector(Utils
.convertToInt(connector
)).status = OCPP16ChargePointStatus
.FINISHING
;
322 await this.chargingStation
.ocppRequestService
.sendStopTransaction(transactionId
, this.chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
323 this.chargingStation
.getTransactionIdTag(transactionId
));
324 return Constants
.OCPP_RESPONSE_ACCEPTED
;
327 logger
.info(this.chargingStation
.logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId
.toString());
328 return Constants
.OCPP_RESPONSE_REJECTED
;