Add JSDoc.
[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, 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';
5
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';
16
17 export default class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
18 public async handleRequest(messageId: string, commandName: OCPP16IncomingRequestCommand, commandPayload: Record<string, unknown>): Promise<void> {
19 let response;
20 // Call
21 if (typeof this['handleRequest' + commandName] === 'function') {
22 try {
23 // Call the method to build the response
24 response = await this['handleRequest' + commandName](commandPayload);
25 } catch (error) {
26 // Log
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);
30 throw error;
31 }
32 } else {
33 // Throw exception
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)}`);
36 }
37 // Send the built response
38 await this.chargingStation.ocppRequestService.sendMessage(messageId, response, MessageType.CALL_RESULT_MESSAGE, commandName);
39 }
40
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();
48 });
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;
51 }
52
53 private handleRequestClearCache(): DefaultResponse {
54 return Constants.OCPP_RESPONSE_ACCEPTED;
55 }
56
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;
62 }
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;
68 }
69 return Constants.OCPP_RESPONSE_UNLOCK_FAILED;
70 }
71 await this.chargingStation.ocppRequestService.sendStatusNotification(connectorId, OCPP16ChargePointStatus.AVAILABLE);
72 this.chargingStation.getConnector(connectorId).status = OCPP16ChargePointStatus.AVAILABLE;
73 return Constants.OCPP_RESPONSE_UNLOCKED;
74 }
75
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;
83 }
84 if (!configuration.visible) {
85 continue;
86 }
87 configurationKey.push({
88 key: configuration.key,
89 readonly: configuration.readonly,
90 value: configuration.value,
91 });
92 }
93 } else {
94 for (const key of commandPayload.key) {
95 const keyFound = this.chargingStation.getConfigurationKey(key);
96 if (keyFound) {
97 if (Utils.isUndefined(keyFound.visible)) {
98 keyFound.visible = true;
99 }
100 if (!keyFound.visible) {
101 continue;
102 }
103 configurationKey.push({
104 key: keyFound.key,
105 readonly: keyFound.readonly,
106 value: keyFound.value,
107 });
108 } else {
109 unknownKey.push(key);
110 }
111 }
112 }
113 return {
114 configurationKey,
115 unknownKey,
116 };
117 }
118
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);
123 }
124 if (!Utils.isString(commandPayload.value)) {
125 logger.error(`${this.chargingStation.logPrefix()} ChangeConfiguration request value field is not a string:`, commandPayload);
126 }
127 const keyToChange = this.chargingStation.getConfigurationKey(commandPayload.key, true);
128 if (!keyToChange) {
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;
137 valueChanged = true;
138 }
139 let triggerHeartbeatRestart = false;
140 if (keyToChange.key === OCPP16StandardParametersKey.HeartBeatInterval && valueChanged) {
141 this.chargingStation.setConfigurationKeyValue(OCPP16StandardParametersKey.HeartbeatInterval, commandPayload.value);
142 triggerHeartbeatRestart = true;
143 }
144 if (keyToChange.key === OCPP16StandardParametersKey.HeartbeatInterval && valueChanged) {
145 this.chargingStation.setConfigurationKeyValue(OCPP16StandardParametersKey.HeartBeatInterval, commandPayload.value);
146 triggerHeartbeatRestart = true;
147 }
148 if (triggerHeartbeatRestart) {
149 this.chargingStation.restartHeartbeat();
150 }
151 if (keyToChange.key === OCPP16StandardParametersKey.WebSocketPingInterval && valueChanged) {
152 this.chargingStation.restartWebSocketPing();
153 }
154 if (keyToChange.reboot) {
155 return Constants.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED;
156 }
157 return Constants.OCPP_CONFIGURATION_RESPONSE_ACCEPTED;
158 }
159 }
160
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;
165 }
166 if (commandPayload.csChargingProfiles.chargingProfilePurpose === ChargingProfilePurposeType.CHARGE_POINT_MAX_PROFILE && commandPayload.connectorId !== 0) {
167 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED;
168 }
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;
171 }
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;
175 }
176
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;
181 }
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;
186 }
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;
195 }
196 if (!commandPayload.chargingProfilePurpose && chargingProfile.stackLevel === commandPayload.stackLevel) {
197 clearCurrentCP = true;
198 }
199 if (!chargingProfile.stackLevel && chargingProfile.chargingProfilePurpose === commandPayload.chargingProfilePurpose) {
200 clearCurrentCP = true;
201 }
202 if (chargingProfile.stackLevel === commandPayload.stackLevel && chargingProfile.chargingProfilePurpose === commandPayload.chargingProfilePurpose) {
203 clearCurrentCP = true;
204 }
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);
208 clearedCP = true;
209 }
210 });
211 }
212 }
213 if (clearedCP) {
214 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED;
215 }
216 }
217 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN;
218 }
219
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;
225 }
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;
232 }
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;
237 }
238 }
239 return response;
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;
244 }
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;
249 }
250 return Constants.OCPP_AVAILABILITY_RESPONSE_REJECTED;
251 }
252
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;
266 }
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;
271 }
272 logger.error(this.chargingStation.logPrefix() + ' Remote starting transaction REJECTED on connector Id ' + transactionConnectorID.toString() + ', idTag ' + commandPayload.idTag);
273 return Constants.OCPP_RESPONSE_REJECTED;
274 }
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;
282 }
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;
287 }
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;
290 }
291
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;
300 }
301 }
302 logger.info(this.chargingStation.logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId.toString());
303 return Constants.OCPP_RESPONSE_REJECTED;
304 }
305 }