Add JSDoc.
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / 1.6 / OCCP16IncomingRequestService.ts
CommitLineData
c0560973 1import { ChangeAvailabilityRequest, ChangeConfigurationRequest, ClearChargingProfileRequest, GetConfigurationRequest, OCPP16AvailabilityType, OCPP16IncomingRequestCommand, RemoteStartTransactionRequest, RemoteStopTransactionRequest, ResetRequest, SetChargingProfileRequest, UnlockConnectorRequest } from '../../../types/ocpp/1.6/Requests';
efa43e52 2import { ChangeAvailabilityResponse, ChangeConfigurationResponse, ClearChargingProfileResponse, DefaultResponse, GetConfigurationResponse, SetChargingProfileResponse, UnlockConnectorResponse } from '../../../types/ocpp/1.6/Responses';
c0560973
JB
3import { ChargingProfilePurposeType, OCPP16ChargingProfile } from '../../../types/ocpp/1.6/ChargingProfile';
4import { OCPP16AuthorizationStatus, OCPP16StopTransactionReason } from '../../../types/ocpp/1.6/Transaction';
5
6import Constants from '../../../utils/Constants';
7import { ErrorType } from '../../../types/ocpp/ErrorType';
8import { MessageType } from '../../../types/ocpp/MessageType';
9import { OCPP16ChargePointStatus } from '../../../types/ocpp/1.6/ChargePointStatus';
10import { OCPP16StandardParametersKey } from '../../../types/ocpp/1.6/Configuration';
11import { OCPPConfigurationKey } from '../../../types/ocpp/Configuration';
12import OCPPError from '../../OcppError';
13import OCPPIncomingRequestService from '../OCPPIncomingRequestService';
14import Utils from '../../../utils/Utils';
15import logger from '../../../utils/Logger';
16
17export 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);
a4cc42ea 28 // Send back an error response to inform backend
c0560973
JB
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 {
71623267
JB
43 // eslint-disable-next-line @typescript-eslint/no-misused-promises
44 setImmediate(async (): Promise<void> => {
c0560973
JB
45 await this.chargingStation.stop(commandPayload.type + 'Reset' as OCPP16StopTransactionReason);
46 await Utils.sleep(this.chargingStation.stationInfo.resetTime);
71623267 47 this.chargingStation.start();
c0560973
JB
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)) {
a4cc42ea 163 logger.error(`${this.chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${commandPayload.connectorId}`);
c0560973
JB
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);
a4cc42ea 173 logger.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set, dump their stack: %j`, this.chargingStation.getConnector(commandPayload.connectorId).chargingProfiles);
c0560973
JB
174 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED;
175 }
176
177 private handleRequestClearChargingProfile(commandPayload: ClearChargingProfileRequest): ClearChargingProfileResponse {
178 if (!this.chargingStation.getConnector(commandPayload.connectorId)) {
a4cc42ea 179 logger.error(`${this.chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${commandPayload.connectorId}`);
c0560973
JB
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 = [];
a4cc42ea 184 logger.debug(`${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`, this.chargingStation.getConnector(commandPayload.connectorId).chargingProfiles);
c0560973
JB
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;
a4cc42ea 207 logger.debug(`${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`, this.chargingStation.getConnector(commandPayload.connectorId).chargingProfiles);
c0560973
JB
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
e268356b 220 private async handleRequestChangeAvailability(commandPayload: ChangeAvailabilityRequest): Promise<ChangeAvailabilityResponse> {
c0560973
JB
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) {
e268356b 235 await this.chargingStation.ocppRequestService.sendStatusNotification(Utils.convertToInt(connector), chargePointStatus);
c0560973
JB
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;
e268356b 246 await this.chargingStation.ocppRequestService.sendStatusNotification(connectorId, chargePointStatus);
c0560973
JB
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);
a4cc42ea 263 logger.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set at start transaction, dump their stack: %j`, this.chargingStation.getConnector(transactionConnectorID).chargingProfiles);
c0560973
JB
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);
a4cc42ea 279 logger.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set at start transaction, dump their stack: %j`, this.chargingStation.getConnector(commandPayload.connectorId).chargingProfiles);
c0560973
JB
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}