e806051a449da65b5a4b989492d0050f50d760aa
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / 1.6 / OCCP16IncomingRequestService.ts
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';
5
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';
17
18 export default class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
19 public async handleRequest(messageId: string, commandName: OCPP16IncomingRequestCommand, commandPayload: Record<string, unknown>): Promise<void> {
20 let response;
21 const methodName = `handleRequest${commandName}`;
22 // Call
23 if (typeof this[methodName] === 'function') {
24 try {
25 // Call the method to build the response
26 response = await this[methodName](commandPayload);
27 } catch (error) {
28 // Log
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);
32 throw error;
33 }
34 } else {
35 // Throw exception
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)}`);
38 }
39 // Send the built response
40 await this.chargingStation.ocppRequestService.sendMessage(messageId, response, MessageType.CALL_RESULT_MESSAGE, commandName);
41 }
42
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();
50 });
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;
53 }
54
55 private handleRequestClearCache(): DefaultResponse {
56 return Constants.OCPP_RESPONSE_ACCEPTED;
57 }
58
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;
64 }
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;
73 }
74 return Constants.OCPP_RESPONSE_UNLOCK_FAILED;
75 }
76 await this.chargingStation.ocppRequestService.sendStatusNotification(connectorId, OCPP16ChargePointStatus.AVAILABLE);
77 this.chargingStation.getConnector(connectorId).status = OCPP16ChargePointStatus.AVAILABLE;
78 return Constants.OCPP_RESPONSE_UNLOCKED;
79 }
80
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;
88 }
89 if (!configuration.visible) {
90 continue;
91 }
92 configurationKey.push({
93 key: configuration.key,
94 readonly: configuration.readonly,
95 value: configuration.value,
96 });
97 }
98 } else {
99 for (const key of commandPayload.key) {
100 const keyFound = this.chargingStation.getConfigurationKey(key);
101 if (keyFound) {
102 if (Utils.isUndefined(keyFound.visible)) {
103 keyFound.visible = true;
104 }
105 if (!keyFound.visible) {
106 continue;
107 }
108 configurationKey.push({
109 key: keyFound.key,
110 readonly: keyFound.readonly,
111 value: keyFound.value,
112 });
113 } else {
114 unknownKey.push(key);
115 }
116 }
117 }
118 return {
119 configurationKey,
120 unknownKey,
121 };
122 }
123
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);
128 }
129 if (!Utils.isString(commandPayload.value)) {
130 logger.error(`${this.chargingStation.logPrefix()} ChangeConfiguration request value field is not a string:`, commandPayload);
131 }
132 const keyToChange = this.chargingStation.getConfigurationKey(commandPayload.key, true);
133 if (!keyToChange) {
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;
142 valueChanged = true;
143 }
144 let triggerHeartbeatRestart = false;
145 if (keyToChange.key === OCPP16StandardParametersKey.HeartBeatInterval && valueChanged) {
146 this.chargingStation.setConfigurationKeyValue(OCPP16StandardParametersKey.HeartbeatInterval, commandPayload.value);
147 triggerHeartbeatRestart = true;
148 }
149 if (keyToChange.key === OCPP16StandardParametersKey.HeartbeatInterval && valueChanged) {
150 this.chargingStation.setConfigurationKeyValue(OCPP16StandardParametersKey.HeartBeatInterval, commandPayload.value);
151 triggerHeartbeatRestart = true;
152 }
153 if (triggerHeartbeatRestart) {
154 this.chargingStation.restartHeartbeat();
155 }
156 if (keyToChange.key === OCPP16StandardParametersKey.WebSocketPingInterval && valueChanged) {
157 this.chargingStation.restartWebSocketPing();
158 }
159 if (keyToChange.reboot) {
160 return Constants.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED;
161 }
162 return Constants.OCPP_CONFIGURATION_RESPONSE_ACCEPTED;
163 }
164 }
165
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;
170 }
171 if (commandPayload.csChargingProfiles.chargingProfilePurpose === ChargingProfilePurposeType.CHARGE_POINT_MAX_PROFILE && commandPayload.connectorId !== 0) {
172 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED;
173 }
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;
176 }
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;
180 }
181
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;
186 }
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;
191 }
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;
200 }
201 if (!commandPayload.chargingProfilePurpose && chargingProfile.stackLevel === commandPayload.stackLevel) {
202 clearCurrentCP = true;
203 }
204 if (!chargingProfile.stackLevel && chargingProfile.chargingProfilePurpose === commandPayload.chargingProfilePurpose) {
205 clearCurrentCP = true;
206 }
207 if (chargingProfile.stackLevel === commandPayload.stackLevel && chargingProfile.chargingProfilePurpose === commandPayload.chargingProfilePurpose) {
208 clearCurrentCP = true;
209 }
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);
213 clearedCP = true;
214 }
215 });
216 }
217 }
218 if (clearedCP) {
219 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED;
220 }
221 }
222 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN;
223 }
224
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;
230 }
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;
237 }
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;
242 }
243 }
244 return response;
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;
249 }
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;
254 }
255 return Constants.OCPP_AVAILABILITY_RESPONSE_REJECTED;
256 }
257
258 private async handleRequestRemoteStartTransaction(commandPayload: RemoteStartTransactionRequest): Promise<DefaultResponse> {
259 const transactionConnectorId: number = commandPayload.connectorId;
260 if (transactionConnectorId) {
261 await this.chargingStation.ocppRequestService.sendStatusNotification(transactionConnectorId, OCPP16ChargePointStatus.PREPARING);
262 this.chargingStation.getConnector(transactionConnectorId).status = OCPP16ChargePointStatus.PREPARING;
263 if (this.chargingStation.isChargingStationAvailable() && this.chargingStation.isConnectorAvailable(transactionConnectorId)) {
264 // Check if authorized
265 if (this.chargingStation.getAuthorizeRemoteTxRequests()) {
266 let authorized = false;
267 if (this.chargingStation.getLocalAuthListEnabled() && this.chargingStation.hasAuthorizedTags()
268 && this.chargingStation.authorizedTags.find((value) => value === commandPayload.idTag)) {
269 authorized = true;
270 }
271 if (!authorized || (authorized && this.chargingStation.getMayAuthorizeAtRemoteStart())) {
272 const authorizeResponse = await this.chargingStation.ocppRequestService.sendAuthorize(transactionConnectorId, commandPayload.idTag);
273 if (authorizeResponse?.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED) {
274 authorized = true;
275 } else {
276 authorized = false;
277 }
278 }
279 if (authorized) {
280 // Authorization successful, start transaction
281 if (this.setRemoteStartTransactionChargingProfile(transactionConnectorId, commandPayload.chargingProfile)) {
282 if ((await this.chargingStation.ocppRequestService.sendStartTransaction(transactionConnectorId, commandPayload.idTag)).idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED) {
283 logger.debug(this.chargingStation.logPrefix() + ' Transaction remotely STARTED on ' + this.chargingStation.stationInfo.chargingStationId + '#' + transactionConnectorId.toString() + ' for idTag ' + commandPayload.idTag);
284 return Constants.OCPP_RESPONSE_ACCEPTED;
285 }
286 return await this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
287 }
288 return await this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
289 }
290 return await this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
291 }
292 // No authorization check required, start transaction
293 if (this.setRemoteStartTransactionChargingProfile(transactionConnectorId, commandPayload.chargingProfile)) {
294 if ((await this.chargingStation.ocppRequestService.sendStartTransaction(transactionConnectorId, commandPayload.idTag)).idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED) {
295 logger.debug(this.chargingStation.logPrefix() + ' Transaction remotely STARTED on ' + this.chargingStation.stationInfo.chargingStationId + '#' + transactionConnectorId.toString() + ' for idTag ' + commandPayload.idTag);
296 return Constants.OCPP_RESPONSE_ACCEPTED;
297 }
298 return await this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
299 }
300 return await this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
301 }
302 return await this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
303 }
304 return await this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
305 }
306
307 private async notifyRemoteStartTransactionRejected(connectorId: number, idTag: string): Promise<DefaultResponse> {
308 if (this.chargingStation.getConnector(connectorId).status !== OCPP16ChargePointStatus.AVAILABLE) {
309 await this.chargingStation.ocppRequestService.sendStatusNotification(connectorId, OCPP16ChargePointStatus.AVAILABLE);
310 this.chargingStation.getConnector(connectorId).status = OCPP16ChargePointStatus.AVAILABLE;
311 }
312 logger.warn(this.chargingStation.logPrefix() + ' Remote starting transaction REJECTED on connector Id ' + connectorId.toString() + ', idTag ' + idTag + ', availability ' + this.chargingStation.getConnector(connectorId).availability + ', status ' + this.chargingStation.getConnector(connectorId).status);
313 return Constants.OCPP_RESPONSE_REJECTED;
314 }
315
316 private setRemoteStartTransactionChargingProfile(connectorId: number, cp: OCPP16ChargingProfile): boolean {
317 if (cp && cp.chargingProfilePurpose === ChargingProfilePurposeType.TX_PROFILE) {
318 this.chargingStation.setChargingProfile(connectorId, cp);
319 logger.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set at remote start transaction, dump their stack: %j`, this.chargingStation.getConnector(connectorId).chargingProfiles);
320 return true;
321 } else if (cp && cp.chargingProfilePurpose !== ChargingProfilePurposeType.TX_PROFILE) {
322 logger.warn(`${this.chargingStation.logPrefix()} Not allowed to set ${cp.chargingProfilePurpose} charging profile(s) at remote start transaction`);
323 return false;
324 } else if (!cp) {
325 return true;
326 }
327 }
328
329 private async handleRequestRemoteStopTransaction(commandPayload: RemoteStopTransactionRequest): Promise<DefaultResponse> {
330 const transactionId = commandPayload.transactionId;
331 for (const connector in this.chargingStation.connectors) {
332 if (Utils.convertToInt(connector) > 0 && this.chargingStation.getConnector(Utils.convertToInt(connector))?.transactionId === transactionId) {
333 await this.chargingStation.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), OCPP16ChargePointStatus.FINISHING);
334 this.chargingStation.getConnector(Utils.convertToInt(connector)).status = OCPP16ChargePointStatus.FINISHING;
335 await this.chargingStation.ocppRequestService.sendStopTransaction(transactionId, this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
336 this.chargingStation.getTransactionIdTag(transactionId));
337 return Constants.OCPP_RESPONSE_ACCEPTED;
338 }
339 }
340 logger.info(this.chargingStation.logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId.toString());
341 return Constants.OCPP_RESPONSE_REJECTED;
342 }
343 }