fix: fix reservation removal at transaction start
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / 1.6 / OCPP16IncomingRequestService.ts
CommitLineData
edd13439 1// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
c8eeb62b 2
d972af76
JB
3import { createWriteStream, readdirSync } from 'node:fs';
4import { dirname, join, resolve } from 'node:path';
130783a7 5import { URL, fileURLToPath } from 'node:url';
8114d10e 6
6c1761d4 7import type { JSONSchemaType } from 'ajv';
27782dbc 8import { Client, type FTPResponse } from 'basic-ftp';
be4c6702 9import { secondsToMilliseconds } from 'date-fns';
d972af76 10import { create } from 'tar';
8114d10e 11
4c3c0d59
JB
12import { OCPP16Constants } from './OCPP16Constants';
13import { OCPP16ServiceUtils } from './OCPP16ServiceUtils';
2896e06d
JB
14import {
15 type ChargingStation,
fba11dc6 16 checkChargingStation,
f2d5e3d9
JB
17 getConfigurationKey,
18 setConfigurationKeyValue,
2896e06d 19} from '../../../charging-station';
268a74bb 20import { OCPPError } from '../../../exception';
e7aeea18 21import {
27782dbc 22 type ChangeAvailabilityRequest,
268a74bb 23 type ChangeAvailabilityResponse,
27782dbc 24 type ChangeConfigurationRequest,
268a74bb 25 type ChangeConfigurationResponse,
27782dbc 26 type ClearChargingProfileRequest,
268a74bb 27 type ClearChargingProfileResponse,
4334db72 28 type ConnectorStatus,
268a74bb
JB
29 ErrorType,
30 type GenericResponse,
41189456 31 GenericStatus,
27782dbc 32 type GetConfigurationRequest,
268a74bb 33 type GetConfigurationResponse,
27782dbc 34 type GetDiagnosticsRequest,
268a74bb
JB
35 type GetDiagnosticsResponse,
36 type IncomingRequestHandler,
37 type JsonObject,
38 type JsonType,
39 OCPP16AuthorizationStatus,
e7aeea18 40 OCPP16AvailabilityType,
27782dbc 41 type OCPP16BootNotificationRequest,
268a74bb 42 type OCPP16BootNotificationResponse,
66dd3447 43 type OCPP16CancelReservationRequest,
268a74bb
JB
44 OCPP16ChargePointErrorCode,
45 OCPP16ChargePointStatus,
46 type OCPP16ChargingProfile,
0ac97927 47 OCPP16ChargingProfilePurposeType,
41189456 48 type OCPP16ChargingSchedule,
27782dbc
JB
49 type OCPP16ClearCacheRequest,
50 type OCPP16DataTransferRequest,
268a74bb 51 type OCPP16DataTransferResponse,
77b95a89 52 OCPP16DataTransferVendorId,
268a74bb 53 OCPP16DiagnosticsStatus,
c9a4f9ea 54 type OCPP16DiagnosticsStatusNotificationRequest,
268a74bb 55 type OCPP16DiagnosticsStatusNotificationResponse,
c9a4f9ea
JB
56 OCPP16FirmwareStatus,
57 type OCPP16FirmwareStatusNotificationRequest,
268a74bb 58 type OCPP16FirmwareStatusNotificationResponse,
41189456
JB
59 type OCPP16GetCompositeScheduleRequest,
60 type OCPP16GetCompositeScheduleResponse,
27782dbc 61 type OCPP16HeartbeatRequest,
268a74bb 62 type OCPP16HeartbeatResponse,
e7aeea18 63 OCPP16IncomingRequestCommand,
c60ed4b8 64 OCPP16MessageTrigger,
94a464f9 65 OCPP16RequestCommand,
66dd3447
JB
66 type OCPP16ReserveNowRequest,
67 type OCPP16ReserveNowResponse,
268a74bb
JB
68 OCPP16StandardParametersKey,
69 type OCPP16StartTransactionRequest,
70 type OCPP16StartTransactionResponse,
27782dbc 71 type OCPP16StatusNotificationRequest,
268a74bb
JB
72 type OCPP16StatusNotificationResponse,
73 OCPP16StopTransactionReason,
74 OCPP16SupportedFeatureProfiles,
27782dbc 75 type OCPP16TriggerMessageRequest,
268a74bb 76 type OCPP16TriggerMessageResponse,
27782dbc 77 type OCPP16UpdateFirmwareRequest,
268a74bb
JB
78 type OCPP16UpdateFirmwareResponse,
79 type OCPPConfigurationKey,
80 OCPPVersion,
27782dbc
JB
81 type RemoteStartTransactionRequest,
82 type RemoteStopTransactionRequest,
66dd3447 83 ReservationTerminationReason,
27782dbc
JB
84 type ResetRequest,
85 type SetChargingProfileRequest,
27782dbc 86 type SetChargingProfileResponse,
268a74bb 87 type UnlockConnectorRequest,
27782dbc 88 type UnlockConnectorResponse,
268a74bb 89} from '../../../types';
9bf0ef23
JB
90import {
91 Constants,
92 convertToDate,
93 convertToInt,
94 formatDurationMilliSeconds,
95 getRandomInteger,
96 isEmptyArray,
97 isNotEmptyArray,
98 isNotEmptyString,
99 isNullOrUndefined,
100 isUndefined,
101 logger,
102 sleep,
103} from '../../../utils';
4c3c0d59 104import { OCPPIncomingRequestService } from '../OCPPIncomingRequestService';
c0560973 105
2a115f87 106const moduleName = 'OCPP16IncomingRequestService';
909dcf2d 107
268a74bb 108export class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
b3fc3ff5 109 protected jsonSchemas: Map<OCPP16IncomingRequestCommand, JSONSchemaType<JsonObject>>;
58144adb
JB
110 private incomingRequestHandlers: Map<OCPP16IncomingRequestCommand, IncomingRequestHandler>;
111
08f130a0 112 public constructor() {
b768993d
JB
113 // if (new.target?.name === moduleName) {
114 // throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
115 // }
d270cc87 116 super(OCPPVersion.VERSION_16);
58144adb 117 this.incomingRequestHandlers = new Map<OCPP16IncomingRequestCommand, IncomingRequestHandler>([
a37fc6dc
JB
118 [
119 OCPP16IncomingRequestCommand.RESET,
120 this.handleRequestReset.bind(this) as unknown as IncomingRequestHandler,
121 ],
122 [
123 OCPP16IncomingRequestCommand.CLEAR_CACHE,
124 this.handleRequestClearCache.bind(this) as IncomingRequestHandler,
125 ],
126 [
127 OCPP16IncomingRequestCommand.UNLOCK_CONNECTOR,
128 this.handleRequestUnlockConnector.bind(this) as unknown as IncomingRequestHandler,
129 ],
e7aeea18
JB
130 [
131 OCPP16IncomingRequestCommand.GET_CONFIGURATION,
a37fc6dc 132 this.handleRequestGetConfiguration.bind(this) as IncomingRequestHandler,
e7aeea18
JB
133 ],
134 [
135 OCPP16IncomingRequestCommand.CHANGE_CONFIGURATION,
a37fc6dc 136 this.handleRequestChangeConfiguration.bind(this) as unknown as IncomingRequestHandler,
e7aeea18 137 ],
41189456
JB
138 [
139 OCPP16IncomingRequestCommand.GET_COMPOSITE_SCHEDULE,
a37fc6dc 140 this.handleRequestGetCompositeSchedule.bind(this) as unknown as IncomingRequestHandler,
41189456 141 ],
e7aeea18
JB
142 [
143 OCPP16IncomingRequestCommand.SET_CHARGING_PROFILE,
a37fc6dc 144 this.handleRequestSetChargingProfile.bind(this) as unknown as IncomingRequestHandler,
e7aeea18
JB
145 ],
146 [
147 OCPP16IncomingRequestCommand.CLEAR_CHARGING_PROFILE,
a37fc6dc 148 this.handleRequestClearChargingProfile.bind(this) as IncomingRequestHandler,
e7aeea18
JB
149 ],
150 [
151 OCPP16IncomingRequestCommand.CHANGE_AVAILABILITY,
a37fc6dc 152 this.handleRequestChangeAvailability.bind(this) as unknown as IncomingRequestHandler,
e7aeea18
JB
153 ],
154 [
155 OCPP16IncomingRequestCommand.REMOTE_START_TRANSACTION,
a37fc6dc 156 this.handleRequestRemoteStartTransaction.bind(this) as unknown as IncomingRequestHandler,
e7aeea18
JB
157 ],
158 [
159 OCPP16IncomingRequestCommand.REMOTE_STOP_TRANSACTION,
a37fc6dc
JB
160 this.handleRequestRemoteStopTransaction.bind(this) as unknown as IncomingRequestHandler,
161 ],
162 [
163 OCPP16IncomingRequestCommand.GET_DIAGNOSTICS,
164 this.handleRequestGetDiagnostics.bind(this) as IncomingRequestHandler,
165 ],
166 [
167 OCPP16IncomingRequestCommand.TRIGGER_MESSAGE,
168 this.handleRequestTriggerMessage.bind(this) as unknown as IncomingRequestHandler,
169 ],
170 [
171 OCPP16IncomingRequestCommand.DATA_TRANSFER,
172 this.handleRequestDataTransfer.bind(this) as unknown as IncomingRequestHandler,
173 ],
174 [
175 OCPP16IncomingRequestCommand.UPDATE_FIRMWARE,
176 this.handleRequestUpdateFirmware.bind(this) as unknown as IncomingRequestHandler,
177 ],
178 [
179 OCPP16IncomingRequestCommand.RESERVE_NOW,
180 this.handleRequestReserveNow.bind(this) as unknown as IncomingRequestHandler,
e7aeea18 181 ],
d193a949
JB
182 [
183 OCPP16IncomingRequestCommand.CANCEL_RESERVATION,
a37fc6dc 184 this.handleRequestCancelReservation.bind(this) as unknown as IncomingRequestHandler,
d193a949 185 ],
58144adb 186 ]);
b52c969d
JB
187 this.jsonSchemas = new Map<OCPP16IncomingRequestCommand, JSONSchemaType<JsonObject>>([
188 [
189 OCPP16IncomingRequestCommand.RESET,
130783a7 190 OCPP16ServiceUtils.parseJsonSchemaFile<ResetRequest>(
51022aa0 191 'assets/json-schemas/ocpp/1.6/Reset.json',
1b271a54 192 moduleName,
5edd8ba0 193 'constructor',
130783a7 194 ),
b52c969d
JB
195 ],
196 [
197 OCPP16IncomingRequestCommand.CLEAR_CACHE,
130783a7 198 OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16ClearCacheRequest>(
51022aa0 199 'assets/json-schemas/ocpp/1.6/ClearCache.json',
1b271a54 200 moduleName,
5edd8ba0 201 'constructor',
e9a4164c 202 ),
b52c969d
JB
203 ],
204 [
205 OCPP16IncomingRequestCommand.UNLOCK_CONNECTOR,
130783a7 206 OCPP16ServiceUtils.parseJsonSchemaFile<UnlockConnectorRequest>(
51022aa0 207 'assets/json-schemas/ocpp/1.6/UnlockConnector.json',
1b271a54 208 moduleName,
5edd8ba0 209 'constructor',
e9a4164c 210 ),
b52c969d
JB
211 ],
212 [
213 OCPP16IncomingRequestCommand.GET_CONFIGURATION,
130783a7 214 OCPP16ServiceUtils.parseJsonSchemaFile<GetConfigurationRequest>(
51022aa0 215 'assets/json-schemas/ocpp/1.6/GetConfiguration.json',
1b271a54 216 moduleName,
5edd8ba0 217 'constructor',
e9a4164c 218 ),
b52c969d
JB
219 ],
220 [
221 OCPP16IncomingRequestCommand.CHANGE_CONFIGURATION,
130783a7 222 OCPP16ServiceUtils.parseJsonSchemaFile<ChangeConfigurationRequest>(
51022aa0 223 'assets/json-schemas/ocpp/1.6/ChangeConfiguration.json',
1b271a54 224 moduleName,
5edd8ba0 225 'constructor',
e9a4164c 226 ),
b52c969d
JB
227 ],
228 [
229 OCPP16IncomingRequestCommand.GET_DIAGNOSTICS,
130783a7 230 OCPP16ServiceUtils.parseJsonSchemaFile<GetDiagnosticsRequest>(
51022aa0 231 'assets/json-schemas/ocpp/1.6/GetDiagnostics.json',
1b271a54 232 moduleName,
5edd8ba0 233 'constructor',
e9a4164c 234 ),
b52c969d 235 ],
41189456
JB
236 [
237 OCPP16IncomingRequestCommand.GET_COMPOSITE_SCHEDULE,
238 OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16GetCompositeScheduleRequest>(
51022aa0 239 'assets/json-schemas/ocpp/1.6/GetCompositeSchedule.json',
41189456 240 moduleName,
5edd8ba0 241 'constructor',
41189456
JB
242 ),
243 ],
b52c969d
JB
244 [
245 OCPP16IncomingRequestCommand.SET_CHARGING_PROFILE,
130783a7 246 OCPP16ServiceUtils.parseJsonSchemaFile<SetChargingProfileRequest>(
51022aa0 247 'assets/json-schemas/ocpp/1.6/SetChargingProfile.json',
1b271a54 248 moduleName,
5edd8ba0 249 'constructor',
e9a4164c 250 ),
b52c969d
JB
251 ],
252 [
253 OCPP16IncomingRequestCommand.CLEAR_CHARGING_PROFILE,
130783a7 254 OCPP16ServiceUtils.parseJsonSchemaFile<ClearChargingProfileRequest>(
51022aa0 255 'assets/json-schemas/ocpp/1.6/ClearChargingProfile.json',
1b271a54 256 moduleName,
5edd8ba0 257 'constructor',
e9a4164c 258 ),
b52c969d
JB
259 ],
260 [
261 OCPP16IncomingRequestCommand.CHANGE_AVAILABILITY,
130783a7 262 OCPP16ServiceUtils.parseJsonSchemaFile<ChangeAvailabilityRequest>(
51022aa0 263 'assets/json-schemas/ocpp/1.6/ChangeAvailability.json',
1b271a54 264 moduleName,
5edd8ba0 265 'constructor',
e9a4164c 266 ),
b52c969d
JB
267 ],
268 [
269 OCPP16IncomingRequestCommand.REMOTE_START_TRANSACTION,
130783a7 270 OCPP16ServiceUtils.parseJsonSchemaFile<RemoteStartTransactionRequest>(
51022aa0 271 'assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json',
1b271a54 272 moduleName,
5edd8ba0 273 'constructor',
e9a4164c 274 ),
b52c969d
JB
275 ],
276 [
277 OCPP16IncomingRequestCommand.REMOTE_STOP_TRANSACTION,
130783a7 278 OCPP16ServiceUtils.parseJsonSchemaFile<RemoteStopTransactionRequest>(
51022aa0 279 'assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json',
1b271a54 280 moduleName,
5edd8ba0 281 'constructor',
e9a4164c 282 ),
b52c969d
JB
283 ],
284 [
285 OCPP16IncomingRequestCommand.TRIGGER_MESSAGE,
130783a7 286 OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16TriggerMessageRequest>(
51022aa0 287 'assets/json-schemas/ocpp/1.6/TriggerMessage.json',
1b271a54 288 moduleName,
5edd8ba0 289 'constructor',
e9a4164c 290 ),
b52c969d 291 ],
77b95a89
JB
292 [
293 OCPP16IncomingRequestCommand.DATA_TRANSFER,
130783a7 294 OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16DataTransferRequest>(
51022aa0 295 'assets/json-schemas/ocpp/1.6/DataTransfer.json',
1b271a54 296 moduleName,
5edd8ba0 297 'constructor',
e9a4164c 298 ),
77b95a89 299 ],
bfbda738
JB
300 [
301 OCPP16IncomingRequestCommand.UPDATE_FIRMWARE,
130783a7 302 OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16UpdateFirmwareRequest>(
51022aa0 303 'assets/json-schemas/ocpp/1.6/UpdateFirmware.json',
1b271a54 304 moduleName,
5edd8ba0 305 'constructor',
e9a4164c 306 ),
bfbda738 307 ],
d193a949
JB
308 [
309 OCPP16IncomingRequestCommand.RESERVE_NOW,
310 OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16ReserveNowRequest>(
311 'assets/json-schemas/ocpp/1.6/ReserveNow.json',
312 moduleName,
5edd8ba0 313 'constructor',
d193a949
JB
314 ),
315 ],
316 [
317 OCPP16IncomingRequestCommand.CANCEL_RESERVATION,
318 OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16CancelReservationRequest>(
319 'assets/json-schemas/ocpp/1.6/CancelReservation.json',
320 moduleName,
5edd8ba0 321 'constructor',
d193a949
JB
322 ),
323 ],
b52c969d 324 ]);
31f59c6d
JB
325 this.validatePayload = this.validatePayload.bind(this) as (
326 chargingStation: ChargingStation,
327 commandName: OCPP16IncomingRequestCommand,
5edd8ba0 328 commandPayload: JsonType,
31f59c6d 329 ) => boolean;
58144adb
JB
330 }
331
9429aa42 332 public async incomingRequestHandler<ReqType extends JsonType, ResType extends JsonType>(
08f130a0 333 chargingStation: ChargingStation,
e7aeea18
JB
334 messageId: string,
335 commandName: OCPP16IncomingRequestCommand,
9429aa42 336 commandPayload: ReqType,
e7aeea18 337 ): Promise<void> {
9429aa42 338 let response: ResType;
e7aeea18 339 if (
3a13fc92 340 chargingStation.getOcppStrictCompliance() === true &&
f7c2994d 341 chargingStation.inPendingState() === true &&
e7aeea18
JB
342 (commandName === OCPP16IncomingRequestCommand.REMOTE_START_TRANSACTION ||
343 commandName === OCPP16IncomingRequestCommand.REMOTE_STOP_TRANSACTION)
344 ) {
345 throw new OCPPError(
346 ErrorType.SECURITY_ERROR,
e3018bc4 347 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
e7aeea18
JB
348 commandPayload,
349 null,
5edd8ba0 350 2,
e7aeea18 351 )} while the charging station is in pending state on the central server`,
7369e417 352 commandName,
5edd8ba0 353 commandPayload,
e7aeea18 354 );
caad9d6b 355 }
e7aeea18 356 if (
ed6cfcff
JB
357 chargingStation.isRegistered() === true ||
358 (chargingStation.getOcppStrictCompliance() === false &&
f7c2994d 359 chargingStation.inUnknownState() === true)
e7aeea18 360 ) {
65554cc3 361 if (
ed6cfcff
JB
362 this.incomingRequestHandlers.has(commandName) === true &&
363 OCPP16ServiceUtils.isIncomingRequestCommandSupported(chargingStation, commandName) === true
65554cc3 364 ) {
124f3553 365 try {
9c5c4195 366 this.validatePayload(chargingStation, commandName, commandPayload);
c75a6675 367 // Call the method to build the response
9429aa42 368 response = (await this.incomingRequestHandlers.get(commandName)!(
08f130a0 369 chargingStation,
5edd8ba0 370 commandPayload,
9429aa42 371 )) as ResType;
124f3553
JB
372 } catch (error) {
373 // Log
6c8f5d90 374 logger.error(
66dd3447
JB
375 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler:
376 Handle incoming request error:`,
5edd8ba0 377 error,
6c8f5d90 378 );
124f3553
JB
379 throw error;
380 }
381 } else {
382 // Throw exception
e7aeea18
JB
383 throw new OCPPError(
384 ErrorType.NOT_IMPLEMENTED,
e3018bc4 385 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
e7aeea18
JB
386 commandPayload,
387 null,
5edd8ba0 388 2,
e7aeea18 389 )}`,
7369e417 390 commandName,
5edd8ba0 391 commandPayload,
e7aeea18 392 );
c0560973
JB
393 }
394 } else {
e7aeea18
JB
395 throw new OCPPError(
396 ErrorType.SECURITY_ERROR,
e3018bc4 397 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
e7aeea18
JB
398 commandPayload,
399 null,
5edd8ba0 400 2,
e7aeea18 401 )} while the charging station is not registered on the central server.`,
7369e417 402 commandName,
5edd8ba0 403 commandPayload,
e7aeea18 404 );
c0560973 405 }
c75a6675 406 // Send the built response
08f130a0
JB
407 await chargingStation.ocppRequestService.sendResponse(
408 chargingStation,
409 messageId,
410 response,
5edd8ba0 411 commandName,
08f130a0 412 );
c0560973
JB
413 }
414
9c5c4195
JB
415 private validatePayload(
416 chargingStation: ChargingStation,
417 commandName: OCPP16IncomingRequestCommand,
5edd8ba0 418 commandPayload: JsonType,
9c5c4195 419 ): boolean {
45988780 420 if (this.jsonSchemas.has(commandName) === true) {
9c5c4195
JB
421 return this.validateIncomingRequestPayload(
422 chargingStation,
423 commandName,
e1d9a0f4 424 this.jsonSchemas.get(commandName)!,
5edd8ba0 425 commandPayload,
9c5c4195
JB
426 );
427 }
428 logger.warn(
66dd3447 429 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found
5edd8ba0 430 for command '${commandName}' PDU validation`,
9c5c4195
JB
431 );
432 return false;
433 }
434
c0560973 435 // Simulate charging station restart
08f130a0
JB
436 private handleRequestReset(
437 chargingStation: ChargingStation,
5edd8ba0 438 commandPayload: ResetRequest,
f03e1042 439 ): GenericResponse {
27f08ad3
JB
440 this.runInAsyncScope(
441 chargingStation.reset.bind(chargingStation) as (
442 this: ChargingStation,
e843aa40 443 ...args: unknown[]
27f08ad3
JB
444 ) => Promise<void>,
445 chargingStation,
5edd8ba0 446 `${commandPayload.type}Reset` as OCPP16StopTransactionReason,
59b6ed8d 447 ).catch(Constants.EMPTY_FUNCTION);
e7aeea18 448 logger.info(
08f130a0 449 `${chargingStation.logPrefix()} ${
e7aeea18 450 commandPayload.type
66dd3447 451 } reset command received, simulating it. The station will be
e1d9a0f4 452 back online in ${formatDurationMilliSeconds(chargingStation.stationInfo.resetTime!)}`,
e7aeea18 453 );
d8b1fab1 454 return OCPP16Constants.OCPP_RESPONSE_ACCEPTED;
c0560973
JB
455 }
456
e7aeea18 457 private async handleRequestUnlockConnector(
08f130a0 458 chargingStation: ChargingStation,
5edd8ba0 459 commandPayload: UnlockConnectorRequest,
e7aeea18 460 ): Promise<UnlockConnectorResponse> {
c0560973 461 const connectorId = commandPayload.connectorId;
a14022a2 462 if (chargingStation.hasConnector(connectorId) === false) {
c60ed4b8 463 logger.error(
66dd3447 464 `${chargingStation.logPrefix()} Trying to unlock a non existing
5edd8ba0 465 connector id ${connectorId.toString()}`,
c60ed4b8 466 );
d8b1fab1 467 return OCPP16Constants.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED;
c60ed4b8 468 }
c0560973 469 if (connectorId === 0) {
e7aeea18 470 logger.error(
5edd8ba0 471 `${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId.toString()}`,
e7aeea18 472 );
d8b1fab1 473 return OCPP16Constants.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED;
c0560973 474 }
5e3cb728
JB
475 if (chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) {
476 const stopResponse = await chargingStation.stopTransactionOnConnector(
477 connectorId,
5edd8ba0 478 OCPP16StopTransactionReason.UNLOCK_COMMAND,
5e3cb728 479 );
c0560973 480 if (stopResponse.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED) {
d8b1fab1 481 return OCPP16Constants.OCPP_RESPONSE_UNLOCKED;
c0560973 482 }
d8b1fab1 483 return OCPP16Constants.OCPP_RESPONSE_UNLOCK_FAILED;
c0560973 484 }
4ecff7ce
JB
485 await OCPP16ServiceUtils.sendAndSetConnectorStatus(
486 chargingStation,
ef6fa3fb 487 connectorId,
5edd8ba0 488 OCPP16ChargePointStatus.Available,
4ecff7ce 489 );
d8b1fab1 490 return OCPP16Constants.OCPP_RESPONSE_UNLOCKED;
c0560973
JB
491 }
492
e7aeea18 493 private handleRequestGetConfiguration(
08f130a0 494 chargingStation: ChargingStation,
5edd8ba0 495 commandPayload: GetConfigurationRequest,
e7aeea18 496 ): GetConfigurationResponse {
c0560973
JB
497 const configurationKey: OCPPConfigurationKey[] = [];
498 const unknownKey: string[] = [];
f568f368
JB
499 if (isUndefined(commandPayload.key) === true) {
500 for (const configuration of chargingStation.ocppConfiguration!.configurationKey!) {
9bf0ef23 501 if (isUndefined(configuration.visible) === true) {
7f7b65ca 502 configuration.visible = true;
c0560973 503 }
da8629bb 504 if (configuration.visible === false) {
c0560973
JB
505 continue;
506 }
507 configurationKey.push({
7f7b65ca
JB
508 key: configuration.key,
509 readonly: configuration.readonly,
510 value: configuration.value,
c0560973
JB
511 });
512 }
f568f368
JB
513 } else if (isNotEmptyArray(commandPayload.key) === true) {
514 for (const key of commandPayload.key!) {
f2d5e3d9 515 const keyFound = getConfigurationKey(chargingStation, key, true);
c0560973 516 if (keyFound) {
9bf0ef23 517 if (isUndefined(keyFound.visible) === true) {
c0560973
JB
518 keyFound.visible = true;
519 }
a723e7e9 520 if (keyFound.visible === false) {
c0560973
JB
521 continue;
522 }
523 configurationKey.push({
524 key: keyFound.key,
525 readonly: keyFound.readonly,
526 value: keyFound.value,
527 });
528 } else {
529 unknownKey.push(key);
530 }
531 }
532 }
533 return {
534 configurationKey,
535 unknownKey,
536 };
537 }
538
e7aeea18 539 private handleRequestChangeConfiguration(
08f130a0 540 chargingStation: ChargingStation,
5edd8ba0 541 commandPayload: ChangeConfigurationRequest,
e7aeea18 542 ): ChangeConfigurationResponse {
f2d5e3d9 543 const keyToChange = getConfigurationKey(chargingStation, commandPayload.key, true);
e1d9a0f4 544 if (keyToChange?.readonly === true) {
d8b1fab1 545 return OCPP16Constants.OCPP_CONFIGURATION_RESPONSE_REJECTED;
bd5d98e0 546 } else if (keyToChange?.readonly === false) {
c0560973 547 let valueChanged = false;
a95873d8 548 if (keyToChange.value !== commandPayload.value) {
f2d5e3d9 549 setConfigurationKeyValue(chargingStation, commandPayload.key, commandPayload.value, true);
c0560973
JB
550 valueChanged = true;
551 }
552 let triggerHeartbeatRestart = false;
e1d9a0f4
JB
553 if (
554 (keyToChange.key as OCPP16StandardParametersKey) ===
555 OCPP16StandardParametersKey.HeartBeatInterval &&
556 valueChanged
557 ) {
f2d5e3d9 558 setConfigurationKeyValue(
17ac262c 559 chargingStation,
e7aeea18 560 OCPP16StandardParametersKey.HeartbeatInterval,
5edd8ba0 561 commandPayload.value,
e7aeea18 562 );
c0560973
JB
563 triggerHeartbeatRestart = true;
564 }
e1d9a0f4
JB
565 if (
566 (keyToChange.key as OCPP16StandardParametersKey) ===
567 OCPP16StandardParametersKey.HeartbeatInterval &&
568 valueChanged
569 ) {
f2d5e3d9 570 setConfigurationKeyValue(
17ac262c 571 chargingStation,
e7aeea18 572 OCPP16StandardParametersKey.HeartBeatInterval,
5edd8ba0 573 commandPayload.value,
e7aeea18 574 );
c0560973
JB
575 triggerHeartbeatRestart = true;
576 }
577 if (triggerHeartbeatRestart) {
08f130a0 578 chargingStation.restartHeartbeat();
c0560973 579 }
e1d9a0f4
JB
580 if (
581 (keyToChange.key as OCPP16StandardParametersKey) ===
582 OCPP16StandardParametersKey.WebSocketPingInterval &&
583 valueChanged
584 ) {
08f130a0 585 chargingStation.restartWebSocketPing();
c0560973
JB
586 }
587 if (keyToChange.reboot) {
d8b1fab1 588 return OCPP16Constants.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED;
c0560973 589 }
d8b1fab1 590 return OCPP16Constants.OCPP_CONFIGURATION_RESPONSE_ACCEPTED;
c0560973 591 }
e1d9a0f4 592 return OCPP16Constants.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED;
c0560973
JB
593 }
594
e7aeea18 595 private handleRequestSetChargingProfile(
08f130a0 596 chargingStation: ChargingStation,
5edd8ba0 597 commandPayload: SetChargingProfileRequest,
e7aeea18 598 ): SetChargingProfileResponse {
370ae4ee 599 if (
1789ba2c 600 OCPP16ServiceUtils.checkFeatureProfile(
08f130a0 601 chargingStation,
370ae4ee 602 OCPP16SupportedFeatureProfiles.SmartCharging,
5edd8ba0 603 OCPP16IncomingRequestCommand.SET_CHARGING_PROFILE,
1789ba2c 604 ) === false
370ae4ee 605 ) {
d8b1fab1 606 return OCPP16Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED;
68cb8b91 607 }
a14022a2 608 if (chargingStation.hasConnector(commandPayload.connectorId) === false) {
e7aeea18 609 logger.error(
66dd3447 610 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a
5edd8ba0 611 non existing connector id ${commandPayload.connectorId}`,
e7aeea18 612 );
d8b1fab1 613 return OCPP16Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED;
c0560973 614 }
e7aeea18
JB
615 if (
616 commandPayload.csChargingProfiles.chargingProfilePurpose ===
0ac97927 617 OCPP16ChargingProfilePurposeType.CHARGE_POINT_MAX_PROFILE &&
e7aeea18
JB
618 commandPayload.connectorId !== 0
619 ) {
d8b1fab1 620 return OCPP16Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED;
c0560973 621 }
e7aeea18
JB
622 if (
623 commandPayload.csChargingProfiles.chargingProfilePurpose ===
0ac97927 624 OCPP16ChargingProfilePurposeType.TX_PROFILE &&
e7aeea18 625 (commandPayload.connectorId === 0 ||
5e3cb728
JB
626 chargingStation.getConnectorStatus(commandPayload.connectorId)?.transactionStarted ===
627 false)
e7aeea18 628 ) {
db0af086 629 logger.error(
66dd3447 630 `${chargingStation.logPrefix()} Trying to set transaction charging profile(s)
5edd8ba0 631 on connector ${commandPayload.connectorId} without a started transaction`,
db0af086 632 );
d8b1fab1 633 return OCPP16Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED;
c0560973 634 }
ed3d2808 635 OCPP16ServiceUtils.setChargingProfile(
7cb5b17f 636 chargingStation,
e7aeea18 637 commandPayload.connectorId,
5edd8ba0 638 commandPayload.csChargingProfiles,
e7aeea18
JB
639 );
640 logger.debug(
08f130a0 641 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${
ad8537a7 642 commandPayload.connectorId
ad67a158 643 }: %j`,
5edd8ba0 644 commandPayload.csChargingProfiles,
e7aeea18 645 );
d8b1fab1 646 return OCPP16Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED;
c0560973
JB
647 }
648
41189456
JB
649 private handleRequestGetCompositeSchedule(
650 chargingStation: ChargingStation,
5edd8ba0 651 commandPayload: OCPP16GetCompositeScheduleRequest,
41189456
JB
652 ): OCPP16GetCompositeScheduleResponse {
653 if (
654 OCPP16ServiceUtils.checkFeatureProfile(
655 chargingStation,
656 OCPP16SupportedFeatureProfiles.SmartCharging,
e1d9a0f4 657 OCPP16IncomingRequestCommand.GET_COMPOSITE_SCHEDULE,
41189456
JB
658 ) === false
659 ) {
d8b1fab1 660 return OCPP16Constants.OCPP_RESPONSE_REJECTED;
41189456 661 }
a14022a2 662 if (chargingStation.hasConnector(commandPayload.connectorId) === false) {
41189456 663 logger.error(
66dd3447 664 `${chargingStation.logPrefix()} Trying to get composite schedule to a
5edd8ba0 665 non existing connector id ${commandPayload.connectorId}`,
41189456 666 );
d8b1fab1 667 return OCPP16Constants.OCPP_RESPONSE_REJECTED;
41189456
JB
668 }
669 if (
9bf0ef23 670 isEmptyArray(chargingStation.getConnectorStatus(commandPayload.connectorId)?.chargingProfiles)
41189456 671 ) {
d8b1fab1 672 return OCPP16Constants.OCPP_RESPONSE_REJECTED;
41189456
JB
673 }
674 const startDate = new Date();
be4c6702 675 const endDate = new Date(startDate.getTime() + secondsToMilliseconds(commandPayload.duration));
e1d9a0f4
JB
676 let compositeSchedule: OCPP16ChargingSchedule | undefined;
677 for (const chargingProfile of chargingStation.getConnectorStatus(commandPayload.connectorId)!
678 .chargingProfiles!) {
41189456
JB
679 // FIXME: build the composite schedule including the local power limit, the stack level, the charging rate unit, etc.
680 if (
e1d9a0f4
JB
681 chargingProfile.chargingSchedule.startSchedule! >= startDate &&
682 chargingProfile.chargingSchedule.startSchedule! <= endDate
41189456
JB
683 ) {
684 compositeSchedule = chargingProfile.chargingSchedule;
685 break;
686 }
687 }
688 return {
689 status: GenericStatus.Accepted,
690 scheduleStart: compositeSchedule?.startSchedule,
691 connectorId: commandPayload.connectorId,
692 chargingSchedule: compositeSchedule,
693 };
694 }
695
e7aeea18 696 private handleRequestClearChargingProfile(
08f130a0 697 chargingStation: ChargingStation,
5edd8ba0 698 commandPayload: ClearChargingProfileRequest,
e7aeea18 699 ): ClearChargingProfileResponse {
370ae4ee 700 if (
a36bad10 701 OCPP16ServiceUtils.checkFeatureProfile(
08f130a0 702 chargingStation,
370ae4ee 703 OCPP16SupportedFeatureProfiles.SmartCharging,
5edd8ba0 704 OCPP16IncomingRequestCommand.CLEAR_CHARGING_PROFILE,
a36bad10 705 ) === false
370ae4ee 706 ) {
d8b1fab1 707 return OCPP16Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN;
68cb8b91 708 }
e1d9a0f4 709 if (chargingStation.hasConnector(commandPayload.connectorId!) === false) {
e7aeea18 710 logger.error(
66dd3447 711 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to
5edd8ba0 712 a non existing connector id ${commandPayload.connectorId}`,
e7aeea18 713 );
d8b1fab1 714 return OCPP16Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN;
c0560973 715 }
d812bdcb 716 if (
9bf0ef23
JB
717 !isNullOrUndefined(commandPayload.connectorId) &&
718 isNotEmptyArray(
e1d9a0f4 719 chargingStation.getConnectorStatus(commandPayload.connectorId!)?.chargingProfiles,
4334db72 720 )
d812bdcb 721 ) {
e1d9a0f4 722 chargingStation.getConnectorStatus(commandPayload.connectorId!)!.chargingProfiles = [];
e7aeea18 723 logger.debug(
08f130a0 724 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${
ad8537a7 725 commandPayload.connectorId
5edd8ba0 726 }`,
e7aeea18 727 );
d8b1fab1 728 return OCPP16Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED;
c0560973 729 }
9bf0ef23 730 if (isNullOrUndefined(commandPayload.connectorId)) {
c0560973 731 let clearedCP = false;
4334db72
JB
732 if (chargingStation.hasEvses) {
733 for (const evseStatus of chargingStation.evses.values()) {
734 for (const connectorStatus of evseStatus.connectors.values()) {
73d87be1
JB
735 clearedCP = OCPP16ServiceUtils.clearChargingProfiles(
736 chargingStation,
737 commandPayload,
738 connectorStatus.chargingProfiles,
739 );
4334db72
JB
740 }
741 }
742 } else {
743 for (const connectorId of chargingStation.connectors.keys()) {
73d87be1
JB
744 clearedCP = OCPP16ServiceUtils.clearChargingProfiles(
745 chargingStation,
746 commandPayload,
747 chargingStation.getConnectorStatus(connectorId)?.chargingProfiles,
748 );
c0560973
JB
749 }
750 }
751 if (clearedCP) {
d8b1fab1 752 return OCPP16Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED;
c0560973
JB
753 }
754 }
d8b1fab1 755 return OCPP16Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN;
c0560973
JB
756 }
757
e7aeea18 758 private async handleRequestChangeAvailability(
08f130a0 759 chargingStation: ChargingStation,
5edd8ba0 760 commandPayload: ChangeAvailabilityRequest,
e7aeea18 761 ): Promise<ChangeAvailabilityResponse> {
c0560973 762 const connectorId: number = commandPayload.connectorId;
a14022a2 763 if (chargingStation.hasConnector(connectorId) === false) {
e7aeea18 764 logger.error(
66dd3447 765 `${chargingStation.logPrefix()} Trying to change the availability of a
5edd8ba0 766 non existing connector id ${connectorId.toString()}`,
e7aeea18 767 );
d8b1fab1 768 return OCPP16Constants.OCPP_AVAILABILITY_RESPONSE_REJECTED;
c0560973 769 }
e7aeea18 770 const chargePointStatus: OCPP16ChargePointStatus =
0d6f335f 771 commandPayload.type === OCPP16AvailabilityType.Operative
721646e9
JB
772 ? OCPP16ChargePointStatus.Available
773 : OCPP16ChargePointStatus.Unavailable;
c0560973 774 if (connectorId === 0) {
d8b1fab1
JB
775 let response: ChangeAvailabilityResponse =
776 OCPP16Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED;
ded57f02
JB
777 const changeAvailability = async (id: number, connectorStatus: ConnectorStatus) => {
778 if (connectorStatus?.transactionStarted === true) {
d8b1fab1 779 response = OCPP16Constants.OCPP_AVAILABILITY_RESPONSE_SCHEDULED;
c0560973 780 }
ded57f02 781 connectorStatus.availability = commandPayload.type;
d8b1fab1 782 if (response === OCPP16Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED) {
4ecff7ce
JB
783 await OCPP16ServiceUtils.sendAndSetConnectorStatus(
784 chargingStation,
785 id,
5edd8ba0 786 chargePointStatus,
4ecff7ce 787 );
c0560973 788 }
ded57f02
JB
789 };
790 if (chargingStation.hasEvses) {
791 for (const evseStatus of chargingStation.evses.values()) {
792 for (const [id, connectorStatus] of evseStatus.connectors) {
793 await changeAvailability(id, connectorStatus);
794 }
795 }
796 } else {
797 for (const id of chargingStation.connectors.keys()) {
e1d9a0f4 798 await changeAvailability(id, chargingStation.getConnectorStatus(id)!);
ded57f02 799 }
c0560973
JB
800 }
801 return response;
e7aeea18
JB
802 } else if (
803 connectorId > 0 &&
56eb297e
JB
804 (chargingStation.isChargingStationAvailable() === true ||
805 (chargingStation.isChargingStationAvailable() === false &&
0d6f335f 806 commandPayload.type === OCPP16AvailabilityType.Inoperative))
e7aeea18 807 ) {
5e3cb728 808 if (chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) {
e1d9a0f4 809 chargingStation.getConnectorStatus(connectorId)!.availability = commandPayload.type;
d8b1fab1 810 return OCPP16Constants.OCPP_AVAILABILITY_RESPONSE_SCHEDULED;
c0560973 811 }
e1d9a0f4 812 chargingStation.getConnectorStatus(connectorId)!.availability = commandPayload.type;
4ecff7ce
JB
813 await OCPP16ServiceUtils.sendAndSetConnectorStatus(
814 chargingStation,
ef6fa3fb 815 connectorId,
5edd8ba0 816 chargePointStatus,
4ecff7ce 817 );
d8b1fab1 818 return OCPP16Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED;
c0560973 819 }
d8b1fab1 820 return OCPP16Constants.OCPP_AVAILABILITY_RESPONSE_REJECTED;
c0560973
JB
821 }
822
e7aeea18 823 private async handleRequestRemoteStartTransaction(
08f130a0 824 chargingStation: ChargingStation,
5edd8ba0 825 commandPayload: RemoteStartTransactionRequest,
f03e1042 826 ): Promise<GenericResponse> {
66dd3447 827 const { connectorId: transactionConnectorId, idTag, chargingProfile } = commandPayload;
d193a949 828 if (
d984c13f
JB
829 (chargingStation.getConnectorStatus(transactionConnectorId)!.status ===
830 OCPP16ChargePointStatus.Reserved &&
0557254b 831 chargingStation.getReservationBy('connectorId', transactionConnectorId)?.idTag !== idTag) ||
d984c13f 832 (chargingStation.getConnectorStatus(0)!.status === OCPP16ChargePointStatus.Reserved &&
0557254b 833 chargingStation.getReservationBy('connectorId', 0)?.idTag !== idTag)
d193a949
JB
834 ) {
835 return OCPP16Constants.OCPP_RESPONSE_REJECTED;
836 }
649287f8
JB
837 if (chargingStation.hasConnector(transactionConnectorId) === false) {
838 return this.notifyRemoteStartTransactionRejected(
4ecff7ce
JB
839 chargingStation,
840 transactionConnectorId,
5edd8ba0 841 idTag,
4ecff7ce 842 );
649287f8
JB
843 }
844 if (
d193a949
JB
845 !chargingStation.isChargingStationAvailable() ||
846 !chargingStation.isConnectorAvailable(transactionConnectorId)
649287f8
JB
847 ) {
848 return this.notifyRemoteStartTransactionRejected(
849 chargingStation,
850 transactionConnectorId,
5edd8ba0 851 idTag,
649287f8
JB
852 );
853 }
66dd3447
JB
854 const remoteStartTransactionLogMsg = `
855 ${chargingStation.logPrefix()} Transaction remotely STARTED on ${
5edd8ba0
JB
856 chargingStation.stationInfo.chargingStationId
857 }#${transactionConnectorId.toString()} for idTag '${idTag}'`;
649287f8
JB
858 await OCPP16ServiceUtils.sendAndSetConnectorStatus(
859 chargingStation,
860 transactionConnectorId,
5edd8ba0 861 OCPP16ChargePointStatus.Preparing,
649287f8 862 );
e1d9a0f4 863 const connectorStatus = chargingStation.getConnectorStatus(transactionConnectorId)!;
66dd3447
JB
864 if (
865 chargingStation.getAuthorizeRemoteTxRequests() &&
d984c13f
JB
866 !chargingStation.getLocalAuthListEnabled() &&
867 !chargingStation.getMustAuthorizeAtRemoteStart()
868 ) {
869 logger.warn(
870 `${chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction
871 but local authorization or must authorize at remote start isn't enabled`,
872 );
873 }
874 // Authorization check required
875 if (
876 chargingStation.getAuthorizeRemoteTxRequests() === true &&
877 chargingStation.getMustAuthorizeAtRemoteStart() === true &&
66dd3447
JB
878 (await OCPP16ServiceUtils.isIdTagAuthorized(chargingStation, transactionConnectorId, idTag))
879 ) {
880 // Authorization successful, start transaction
881 if (
882 this.setRemoteStartTransactionChargingProfile(
883 chargingStation,
884 transactionConnectorId,
e1d9a0f4 885 chargingProfile!,
66dd3447
JB
886 ) === true
887 ) {
888 connectorStatus.transactionRemoteStarted = true;
e7aeea18 889 if (
66dd3447
JB
890 (
891 await chargingStation.ocppRequestService.requestHandler<
892 OCPP16StartTransactionRequest,
893 OCPP16StartTransactionResponse
d984c13f
JB
894 >(chargingStation, OCPP16RequestCommand.START_TRANSACTION, {
895 connectorId: transactionConnectorId,
896 idTag,
897 })
66dd3447 898 ).idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED
e7aeea18 899 ) {
eb79c525 900 logger.debug(remoteStartTransactionLogMsg);
66dd3447 901 return OCPP16Constants.OCPP_RESPONSE_ACCEPTED;
e060fe58 902 }
e7aeea18 903 return this.notifyRemoteStartTransactionRejected(
08f130a0 904 chargingStation,
e7aeea18 905 transactionConnectorId,
5edd8ba0 906 idTag,
e7aeea18 907 );
c0560973 908 }
e7aeea18 909 return this.notifyRemoteStartTransactionRejected(
08f130a0 910 chargingStation,
e7aeea18 911 transactionConnectorId,
5edd8ba0 912 idTag,
e7aeea18 913 );
c0560973 914 }
649287f8
JB
915 // No authorization check required, start transaction
916 if (
917 this.setRemoteStartTransactionChargingProfile(
918 chargingStation,
919 transactionConnectorId,
e1d9a0f4 920 chargingProfile!,
649287f8
JB
921 ) === true
922 ) {
923 connectorStatus.transactionRemoteStarted = true;
924 if (
925 (
926 await chargingStation.ocppRequestService.requestHandler<
927 OCPP16StartTransactionRequest,
928 OCPP16StartTransactionResponse
929 >(chargingStation, OCPP16RequestCommand.START_TRANSACTION, {
930 connectorId: transactionConnectorId,
66dd3447 931 idTag,
649287f8
JB
932 })
933 ).idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED
934 ) {
eb79c525 935 logger.debug(remoteStartTransactionLogMsg);
649287f8
JB
936 return OCPP16Constants.OCPP_RESPONSE_ACCEPTED;
937 }
938 return this.notifyRemoteStartTransactionRejected(
939 chargingStation,
940 transactionConnectorId,
5edd8ba0 941 idTag,
649287f8
JB
942 );
943 }
08f130a0
JB
944 return this.notifyRemoteStartTransactionRejected(
945 chargingStation,
946 transactionConnectorId,
5edd8ba0 947 idTag,
08f130a0 948 );
a7fc8211
JB
949 }
950
e7aeea18 951 private async notifyRemoteStartTransactionRejected(
08f130a0 952 chargingStation: ChargingStation,
e7aeea18 953 connectorId: number,
5edd8ba0 954 idTag: string,
f03e1042 955 ): Promise<GenericResponse> {
e7aeea18 956 if (
721646e9 957 chargingStation.getConnectorStatus(connectorId)?.status !== OCPP16ChargePointStatus.Available
e7aeea18 958 ) {
4ecff7ce
JB
959 await OCPP16ServiceUtils.sendAndSetConnectorStatus(
960 chargingStation,
ef6fa3fb 961 connectorId,
5edd8ba0 962 OCPP16ChargePointStatus.Available,
4ecff7ce 963 );
e060fe58 964 }
e7aeea18 965 logger.warn(
66dd3447 966 `${chargingStation.logPrefix()} Remote starting transaction REJECTED on connector id
5edd8ba0
JB
967 ${connectorId.toString()}, idTag '${idTag}', availability '${chargingStation.getConnectorStatus(
968 connectorId,
969 )?.availability}', status '${chargingStation.getConnectorStatus(connectorId)?.status}'`,
e7aeea18 970 );
d8b1fab1 971 return OCPP16Constants.OCPP_RESPONSE_REJECTED;
c0560973
JB
972 }
973
e7aeea18 974 private setRemoteStartTransactionChargingProfile(
08f130a0 975 chargingStation: ChargingStation,
e7aeea18 976 connectorId: number,
55f2ab60 977 chargingProfile: OCPP16ChargingProfile,
e7aeea18 978 ): boolean {
55f2ab60
JB
979 if (
980 chargingProfile &&
981 chargingProfile.chargingProfilePurpose === OCPP16ChargingProfilePurposeType.TX_PROFILE
982 ) {
983 OCPP16ServiceUtils.setChargingProfile(chargingStation, connectorId, chargingProfile);
e7aeea18 984 logger.debug(
66dd3447
JB
985 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction
986 on connector id ${connectorId}: %j`,
55f2ab60 987 chargingProfile,
e7aeea18 988 );
a7fc8211 989 return true;
55f2ab60
JB
990 } else if (
991 chargingProfile &&
992 chargingProfile.chargingProfilePurpose !== OCPP16ChargingProfilePurposeType.TX_PROFILE
993 ) {
e7aeea18 994 logger.warn(
08f130a0 995 `${chargingStation.logPrefix()} Not allowed to set ${
55f2ab60 996 chargingProfile.chargingProfilePurpose
5edd8ba0 997 } charging profile(s) at remote start transaction`,
e7aeea18 998 );
a7fc8211
JB
999 return false;
1000 }
e1d9a0f4 1001 return true;
a7fc8211
JB
1002 }
1003
e7aeea18 1004 private async handleRequestRemoteStopTransaction(
08f130a0 1005 chargingStation: ChargingStation,
5edd8ba0 1006 commandPayload: RemoteStopTransactionRequest,
f03e1042 1007 ): Promise<GenericResponse> {
c0560973 1008 const transactionId = commandPayload.transactionId;
ded57f02
JB
1009 const remoteStopTransaction = async (connectorId: number): Promise<GenericResponse> => {
1010 await OCPP16ServiceUtils.sendAndSetConnectorStatus(
1011 chargingStation,
1012 connectorId,
5edd8ba0 1013 OCPP16ChargePointStatus.Finishing,
ded57f02
JB
1014 );
1015 const stopResponse = await chargingStation.stopTransactionOnConnector(
1016 connectorId,
5edd8ba0 1017 OCPP16StopTransactionReason.REMOTE,
ded57f02
JB
1018 );
1019 if (stopResponse.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED) {
1020 return OCPP16Constants.OCPP_RESPONSE_ACCEPTED;
1021 }
1022 return OCPP16Constants.OCPP_RESPONSE_REJECTED;
1023 };
1024 if (chargingStation.hasEvses) {
1025 for (const [evseId, evseStatus] of chargingStation.evses) {
1026 if (evseId > 0) {
1027 for (const [connectorId, connectorStatus] of evseStatus.connectors) {
1028 if (connectorStatus.transactionId === transactionId) {
1029 return remoteStopTransaction(connectorId);
1030 }
1031 }
1032 }
1033 }
1034 } else {
1035 for (const connectorId of chargingStation.connectors.keys()) {
1036 if (
1037 connectorId > 0 &&
1038 chargingStation.getConnectorStatus(connectorId)?.transactionId === transactionId
1039 ) {
1040 return remoteStopTransaction(connectorId);
ef6fa3fb 1041 }
c0560973
JB
1042 }
1043 }
44b9b577 1044 logger.warn(
66dd3447 1045 `${chargingStation.logPrefix()} Trying to remote stop a non existing transaction with id:
5edd8ba0 1046 ${transactionId.toString()}`,
e7aeea18 1047 );
d8b1fab1 1048 return OCPP16Constants.OCPP_RESPONSE_REJECTED;
c0560973 1049 }
47e22477 1050
b03df580
JB
1051 private handleRequestUpdateFirmware(
1052 chargingStation: ChargingStation,
5edd8ba0 1053 commandPayload: OCPP16UpdateFirmwareRequest,
b03df580
JB
1054 ): OCPP16UpdateFirmwareResponse {
1055 if (
1056 OCPP16ServiceUtils.checkFeatureProfile(
1057 chargingStation,
1058 OCPP16SupportedFeatureProfiles.FirmwareManagement,
5edd8ba0 1059 OCPP16IncomingRequestCommand.UPDATE_FIRMWARE,
b03df580
JB
1060 ) === false
1061 ) {
5d280aae 1062 logger.warn(
66dd3447 1063 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware:
5edd8ba0 1064 Cannot simulate firmware update: feature profile not supported`,
5d280aae 1065 );
d8b1fab1 1066 return OCPP16Constants.OCPP_RESPONSE_EMPTY;
5d280aae
JB
1067 }
1068 if (
9bf0ef23 1069 !isNullOrUndefined(chargingStation.stationInfo.firmwareStatus) &&
5d280aae
JB
1070 chargingStation.stationInfo.firmwareStatus !== OCPP16FirmwareStatus.Installed
1071 ) {
1072 logger.warn(
66dd3447 1073 `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware:
5edd8ba0 1074 Cannot simulate firmware update: firmware update is already in progress`,
5d280aae 1075 );
d8b1fab1 1076 return OCPP16Constants.OCPP_RESPONSE_EMPTY;
b03df580 1077 }
e1d9a0f4 1078 const retrieveDate = convertToDate(commandPayload.retrieveDate)!;
2c7bdc61 1079 const now = Date.now();
72092cfc 1080 if (retrieveDate?.getTime() <= now) {
27f08ad3 1081 this.runInAsyncScope(
62340a29 1082 this.updateFirmwareSimulation.bind(this) as (
27f08ad3 1083 this: OCPP16IncomingRequestService,
e843aa40 1084 ...args: unknown[]
27f08ad3
JB
1085 ) => Promise<void>,
1086 this,
5edd8ba0 1087 chargingStation,
59b6ed8d 1088 ).catch(Constants.EMPTY_FUNCTION);
c9a4f9ea 1089 } else {
5edd8ba0
JB
1090 setTimeout(
1091 () => {
1092 this.runInAsyncScope(
1093 this.updateFirmwareSimulation.bind(this) as (
1094 this: OCPP16IncomingRequestService,
e843aa40 1095 ...args: unknown[]
5edd8ba0
JB
1096 ) => Promise<void>,
1097 this,
1098 chargingStation,
1099 ).catch(Constants.EMPTY_FUNCTION);
1100 },
1101 retrieveDate?.getTime() - now,
1102 );
c9a4f9ea 1103 }
d8b1fab1 1104 return OCPP16Constants.OCPP_RESPONSE_EMPTY;
c9a4f9ea
JB
1105 }
1106
62340a29 1107 private async updateFirmwareSimulation(
c9a4f9ea 1108 chargingStation: ChargingStation,
90293abb 1109 maxDelay = 30,
5edd8ba0 1110 minDelay = 15,
c9a4f9ea 1111 ): Promise<void> {
fba11dc6 1112 if (checkChargingStation(chargingStation, chargingStation.logPrefix()) === false) {
1bf29f5b
JB
1113 return;
1114 }
ded57f02
JB
1115 if (chargingStation.hasEvses) {
1116 for (const [evseId, evseStatus] of chargingStation.evses) {
1117 if (evseId > 0) {
1118 for (const [connectorId, connectorStatus] of evseStatus.connectors) {
1119 if (connectorStatus?.transactionStarted === false) {
1120 await OCPP16ServiceUtils.sendAndSetConnectorStatus(
1121 chargingStation,
1122 connectorId,
5edd8ba0 1123 OCPP16ChargePointStatus.Unavailable,
ded57f02
JB
1124 );
1125 }
1126 }
1127 }
1128 }
1129 } else {
1130 for (const connectorId of chargingStation.connectors.keys()) {
1131 if (
1132 connectorId > 0 &&
1133 chargingStation.getConnectorStatus(connectorId)?.transactionStarted === false
1134 ) {
1135 await OCPP16ServiceUtils.sendAndSetConnectorStatus(
1136 chargingStation,
1137 connectorId,
5edd8ba0 1138 OCPP16ChargePointStatus.Unavailable,
ded57f02
JB
1139 );
1140 }
c9a4f9ea
JB
1141 }
1142 }
93f0c2c8
JB
1143 await chargingStation.ocppRequestService.requestHandler<
1144 OCPP16FirmwareStatusNotificationRequest,
1145 OCPP16FirmwareStatusNotificationResponse
1146 >(chargingStation, OCPP16RequestCommand.FIRMWARE_STATUS_NOTIFICATION, {
1147 status: OCPP16FirmwareStatus.Downloading,
1148 });
1149 chargingStation.stationInfo.firmwareStatus = OCPP16FirmwareStatus.Downloading;
5d280aae 1150 if (
93f0c2c8
JB
1151 chargingStation.stationInfo?.firmwareUpgrade?.failureStatus ===
1152 OCPP16FirmwareStatus.DownloadFailed
5d280aae 1153 ) {
be4c6702 1154 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay, minDelay)));
5d280aae
JB
1155 await chargingStation.ocppRequestService.requestHandler<
1156 OCPP16FirmwareStatusNotificationRequest,
1157 OCPP16FirmwareStatusNotificationResponse
1158 >(chargingStation, OCPP16RequestCommand.FIRMWARE_STATUS_NOTIFICATION, {
15748260 1159 status: chargingStation.stationInfo?.firmwareUpgrade?.failureStatus,
5d280aae 1160 });
93f0c2c8
JB
1161 chargingStation.stationInfo.firmwareStatus =
1162 chargingStation.stationInfo?.firmwareUpgrade?.failureStatus;
5d280aae
JB
1163 return;
1164 }
be4c6702 1165 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay, minDelay)));
c9a4f9ea
JB
1166 await chargingStation.ocppRequestService.requestHandler<
1167 OCPP16FirmwareStatusNotificationRequest,
1168 OCPP16FirmwareStatusNotificationResponse
1169 >(chargingStation, OCPP16RequestCommand.FIRMWARE_STATUS_NOTIFICATION, {
1170 status: OCPP16FirmwareStatus.Downloaded,
1171 });
1172 chargingStation.stationInfo.firmwareStatus = OCPP16FirmwareStatus.Downloaded;
380ccc42 1173 let wasTransactionsStarted = false;
62340a29
JB
1174 let transactionsStarted: boolean;
1175 do {
ded57f02
JB
1176 const runningTransactions = chargingStation.getNumberOfRunningTransactions();
1177 if (runningTransactions > 0) {
be4c6702 1178 const waitTime = secondsToMilliseconds(15);
62340a29 1179 logger.debug(
66dd3447 1180 `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation:
be4c6702
JB
1181 ${runningTransactions} transaction(s) in progress, waiting ${formatDurationMilliSeconds(
1182 waitTime,
1183 )} before continuing firmware update simulation`,
62340a29 1184 );
9bf0ef23 1185 await sleep(waitTime);
62340a29 1186 transactionsStarted = true;
380ccc42 1187 wasTransactionsStarted = true;
62340a29 1188 } else {
ded57f02
JB
1189 if (chargingStation.hasEvses) {
1190 for (const [evseId, evseStatus] of chargingStation.evses) {
1191 if (evseId > 0) {
1192 for (const [connectorId, connectorStatus] of evseStatus.connectors) {
1193 if (connectorStatus?.status !== OCPP16ChargePointStatus.Unavailable) {
1194 await OCPP16ServiceUtils.sendAndSetConnectorStatus(
1195 chargingStation,
1196 connectorId,
5edd8ba0 1197 OCPP16ChargePointStatus.Unavailable,
ded57f02
JB
1198 );
1199 }
1200 }
1201 }
1202 }
1203 } else {
1204 for (const connectorId of chargingStation.connectors.keys()) {
1205 if (
1206 connectorId > 0 &&
1207 chargingStation.getConnectorStatus(connectorId)?.status !==
1208 OCPP16ChargePointStatus.Unavailable
1209 ) {
1210 await OCPP16ServiceUtils.sendAndSetConnectorStatus(
1211 chargingStation,
1212 connectorId,
5edd8ba0 1213 OCPP16ChargePointStatus.Unavailable,
ded57f02
JB
1214 );
1215 }
62340a29
JB
1216 }
1217 }
1218 transactionsStarted = false;
1219 }
1220 } while (transactionsStarted);
be4c6702
JB
1221 !wasTransactionsStarted &&
1222 (await sleep(secondsToMilliseconds(getRandomInteger(maxDelay, minDelay))));
fba11dc6 1223 if (checkChargingStation(chargingStation, chargingStation.logPrefix()) === false) {
1bf29f5b
JB
1224 return;
1225 }
c9a4f9ea
JB
1226 await chargingStation.ocppRequestService.requestHandler<
1227 OCPP16FirmwareStatusNotificationRequest,
1228 OCPP16FirmwareStatusNotificationResponse
1229 >(chargingStation, OCPP16RequestCommand.FIRMWARE_STATUS_NOTIFICATION, {
1230 status: OCPP16FirmwareStatus.Installing,
1231 });
1232 chargingStation.stationInfo.firmwareStatus = OCPP16FirmwareStatus.Installing;
93f0c2c8
JB
1233 if (
1234 chargingStation.stationInfo?.firmwareUpgrade?.failureStatus ===
1235 OCPP16FirmwareStatus.InstallationFailed
1236 ) {
be4c6702 1237 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay, minDelay)));
93f0c2c8
JB
1238 await chargingStation.ocppRequestService.requestHandler<
1239 OCPP16FirmwareStatusNotificationRequest,
1240 OCPP16FirmwareStatusNotificationResponse
1241 >(chargingStation, OCPP16RequestCommand.FIRMWARE_STATUS_NOTIFICATION, {
1242 status: chargingStation.stationInfo?.firmwareUpgrade?.failureStatus,
1243 });
1244 chargingStation.stationInfo.firmwareStatus =
1245 chargingStation.stationInfo?.firmwareUpgrade?.failureStatus;
1246 return;
1247 }
15748260 1248 if (chargingStation.stationInfo?.firmwareUpgrade?.reset === true) {
be4c6702 1249 await sleep(secondsToMilliseconds(getRandomInteger(maxDelay, minDelay)));
5d280aae
JB
1250 await chargingStation.reset(OCPP16StopTransactionReason.REBOOT);
1251 }
b03df580
JB
1252 }
1253
e7aeea18 1254 private async handleRequestGetDiagnostics(
08f130a0 1255 chargingStation: ChargingStation,
5edd8ba0 1256 commandPayload: GetDiagnosticsRequest,
e7aeea18 1257 ): Promise<GetDiagnosticsResponse> {
68cb8b91 1258 if (
1789ba2c 1259 OCPP16ServiceUtils.checkFeatureProfile(
08f130a0 1260 chargingStation,
370ae4ee 1261 OCPP16SupportedFeatureProfiles.FirmwareManagement,
5edd8ba0 1262 OCPP16IncomingRequestCommand.GET_DIAGNOSTICS,
1789ba2c 1263 ) === false
68cb8b91 1264 ) {
90293abb 1265 logger.warn(
66dd3447 1266 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics:
5edd8ba0 1267 Cannot get diagnostics: feature profile not supported`,
90293abb 1268 );
d8b1fab1 1269 return OCPP16Constants.OCPP_RESPONSE_EMPTY;
68cb8b91 1270 }
a3868ec4 1271 const uri = new URL(commandPayload.location);
47e22477 1272 if (uri.protocol.startsWith('ftp:')) {
e1d9a0f4 1273 let ftpClient: Client | undefined;
47e22477 1274 try {
d972af76 1275 const logFiles = readdirSync(resolve(dirname(fileURLToPath(import.meta.url)), '../'))
72092cfc 1276 .filter((file) => file.endsWith('.log'))
d972af76 1277 .map((file) => join('./', file));
44eb6026 1278 const diagnosticsArchive = `${chargingStation.stationInfo.chargingStationId}_logs.tar.gz`;
d972af76 1279 create({ gzip: true }, logFiles).pipe(createWriteStream(diagnosticsArchive));
47e22477
JB
1280 ftpClient = new Client();
1281 const accessResponse = await ftpClient.access({
1282 host: uri.host,
9bf0ef23
JB
1283 ...(isNotEmptyString(uri.port) && { port: convertToInt(uri.port) }),
1284 ...(isNotEmptyString(uri.username) && { user: uri.username }),
1285 ...(isNotEmptyString(uri.password) && { password: uri.password }),
47e22477 1286 });
e1d9a0f4 1287 let uploadResponse: FTPResponse | undefined;
47e22477 1288 if (accessResponse.code === 220) {
72092cfc 1289 ftpClient.trackProgress((info) => {
e7aeea18 1290 logger.info(
08f130a0 1291 `${chargingStation.logPrefix()} ${
e7aeea18 1292 info.bytes / 1024
5edd8ba0 1293 } bytes transferred from diagnostics archive ${info.name}`,
e7aeea18 1294 );
6a8329b4
JB
1295 chargingStation.ocppRequestService
1296 .requestHandler<
1297 OCPP16DiagnosticsStatusNotificationRequest,
1298 OCPP16DiagnosticsStatusNotificationResponse
1299 >(chargingStation, OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION, {
1300 status: OCPP16DiagnosticsStatus.Uploading,
1301 })
72092cfc 1302 .catch((error) => {
6a8329b4 1303 logger.error(
66dd3447
JB
1304 `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics:
1305 Error while sending '${OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION}'`,
5edd8ba0 1306 error,
6a8329b4
JB
1307 );
1308 });
47e22477 1309 });
e7aeea18 1310 uploadResponse = await ftpClient.uploadFrom(
d972af76 1311 join(resolve(dirname(fileURLToPath(import.meta.url)), '../'), diagnosticsArchive),
5edd8ba0 1312 `${uri.pathname}${diagnosticsArchive}`,
e7aeea18 1313 );
47e22477 1314 if (uploadResponse.code === 226) {
08f130a0 1315 await chargingStation.ocppRequestService.requestHandler<
c9a4f9ea
JB
1316 OCPP16DiagnosticsStatusNotificationRequest,
1317 OCPP16DiagnosticsStatusNotificationResponse
08f130a0 1318 >(chargingStation, OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION, {
ef6fa3fb
JB
1319 status: OCPP16DiagnosticsStatus.Uploaded,
1320 });
47e22477
JB
1321 if (ftpClient) {
1322 ftpClient.close();
1323 }
1324 return { fileName: diagnosticsArchive };
1325 }
e7aeea18
JB
1326 throw new OCPPError(
1327 ErrorType.GENERIC_ERROR,
1328 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
44eb6026 1329 uploadResponse?.code && `|${uploadResponse?.code.toString()}`
e7aeea18 1330 }`,
5edd8ba0 1331 OCPP16IncomingRequestCommand.GET_DIAGNOSTICS,
e7aeea18 1332 );
47e22477 1333 }
e7aeea18
JB
1334 throw new OCPPError(
1335 ErrorType.GENERIC_ERROR,
1336 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
44eb6026 1337 uploadResponse?.code && `|${uploadResponse?.code.toString()}`
e7aeea18 1338 }`,
5edd8ba0 1339 OCPP16IncomingRequestCommand.GET_DIAGNOSTICS,
e7aeea18 1340 );
47e22477 1341 } catch (error) {
08f130a0 1342 await chargingStation.ocppRequestService.requestHandler<
c9a4f9ea
JB
1343 OCPP16DiagnosticsStatusNotificationRequest,
1344 OCPP16DiagnosticsStatusNotificationResponse
08f130a0 1345 >(chargingStation, OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION, {
ef6fa3fb
JB
1346 status: OCPP16DiagnosticsStatus.UploadFailed,
1347 });
47e22477
JB
1348 if (ftpClient) {
1349 ftpClient.close();
1350 }
e1d9a0f4 1351 return this.handleIncomingRequestError<GetDiagnosticsResponse>(
08f130a0 1352 chargingStation,
e7aeea18
JB
1353 OCPP16IncomingRequestCommand.GET_DIAGNOSTICS,
1354 error as Error,
5edd8ba0 1355 { errorResponse: OCPP16Constants.OCPP_RESPONSE_EMPTY },
e1d9a0f4 1356 )!;
47e22477
JB
1357 }
1358 } else {
e7aeea18 1359 logger.error(
08f130a0 1360 `${chargingStation.logPrefix()} Unsupported protocol ${
e7aeea18 1361 uri.protocol
5edd8ba0 1362 } to transfer the diagnostic logs archive`,
e7aeea18 1363 );
08f130a0 1364 await chargingStation.ocppRequestService.requestHandler<
c9a4f9ea
JB
1365 OCPP16DiagnosticsStatusNotificationRequest,
1366 OCPP16DiagnosticsStatusNotificationResponse
08f130a0 1367 >(chargingStation, OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION, {
ef6fa3fb
JB
1368 status: OCPP16DiagnosticsStatus.UploadFailed,
1369 });
d8b1fab1 1370 return OCPP16Constants.OCPP_RESPONSE_EMPTY;
47e22477
JB
1371 }
1372 }
802cfa13 1373
e7aeea18 1374 private handleRequestTriggerMessage(
08f130a0 1375 chargingStation: ChargingStation,
5edd8ba0 1376 commandPayload: OCPP16TriggerMessageRequest,
e7aeea18 1377 ): OCPP16TriggerMessageResponse {
370ae4ee
JB
1378 if (
1379 !OCPP16ServiceUtils.checkFeatureProfile(
08f130a0 1380 chargingStation,
370ae4ee 1381 OCPP16SupportedFeatureProfiles.RemoteTrigger,
5edd8ba0 1382 OCPP16IncomingRequestCommand.TRIGGER_MESSAGE,
c60ed4b8
JB
1383 ) ||
1384 !OCPP16ServiceUtils.isMessageTriggerSupported(
1385 chargingStation,
5edd8ba0 1386 commandPayload.requestedMessage,
370ae4ee
JB
1387 )
1388 ) {
d8b1fab1 1389 return OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED;
68cb8b91 1390 }
c60ed4b8 1391 if (
4caa7e67 1392 !OCPP16ServiceUtils.isConnectorIdValid(
c60ed4b8
JB
1393 chargingStation,
1394 OCPP16IncomingRequestCommand.TRIGGER_MESSAGE,
e1d9a0f4 1395 commandPayload.connectorId!,
c60ed4b8
JB
1396 )
1397 ) {
d8b1fab1 1398 return OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED;
dc661702 1399 }
802cfa13
JB
1400 try {
1401 switch (commandPayload.requestedMessage) {
c60ed4b8 1402 case OCPP16MessageTrigger.BootNotification:
802cfa13 1403 setTimeout(() => {
08f130a0 1404 chargingStation.ocppRequestService
f7f98c68 1405 .requestHandler<OCPP16BootNotificationRequest, OCPP16BootNotificationResponse>(
08f130a0 1406 chargingStation,
6a8b180d 1407 OCPP16RequestCommand.BOOT_NOTIFICATION,
8bfbc743 1408 chargingStation.bootNotificationRequest,
5edd8ba0 1409 { skipBufferingOnError: true, triggerMessage: true },
e7aeea18 1410 )
72092cfc 1411 .then((response) => {
8bfbc743 1412 chargingStation.bootNotificationResponse = response;
ae711c83 1413 })
59b6ed8d 1414 .catch(Constants.EMPTY_FUNCTION);
d8b1fab1
JB
1415 }, OCPP16Constants.OCPP_TRIGGER_MESSAGE_DELAY);
1416 return OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED;
c60ed4b8 1417 case OCPP16MessageTrigger.Heartbeat:
802cfa13 1418 setTimeout(() => {
08f130a0 1419 chargingStation.ocppRequestService
f7f98c68 1420 .requestHandler<OCPP16HeartbeatRequest, OCPP16HeartbeatResponse>(
08f130a0 1421 chargingStation,
ef6fa3fb
JB
1422 OCPP16RequestCommand.HEARTBEAT,
1423 null,
1424 {
1425 triggerMessage: true,
5edd8ba0 1426 },
ef6fa3fb 1427 )
59b6ed8d 1428 .catch(Constants.EMPTY_FUNCTION);
d8b1fab1
JB
1429 }, OCPP16Constants.OCPP_TRIGGER_MESSAGE_DELAY);
1430 return OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED;
c60ed4b8 1431 case OCPP16MessageTrigger.StatusNotification:
dc661702 1432 setTimeout(() => {
9bf0ef23 1433 if (!isNullOrUndefined(commandPayload?.connectorId)) {
08f130a0 1434 chargingStation.ocppRequestService
dc661702 1435 .requestHandler<OCPP16StatusNotificationRequest, OCPP16StatusNotificationResponse>(
08f130a0 1436 chargingStation,
dc661702
JB
1437 OCPP16RequestCommand.STATUS_NOTIFICATION,
1438 {
1439 connectorId: commandPayload.connectorId,
1440 errorCode: OCPP16ChargePointErrorCode.NO_ERROR,
e1d9a0f4 1441 status: chargingStation.getConnectorStatus(commandPayload.connectorId!)?.status,
dc661702
JB
1442 },
1443 {
1444 triggerMessage: true,
5edd8ba0 1445 },
dc661702 1446 )
59b6ed8d 1447 .catch(Constants.EMPTY_FUNCTION);
dc661702 1448 } else {
ded57f02
JB
1449 // eslint-disable-next-line no-lonely-if
1450 if (chargingStation.hasEvses) {
1451 for (const evseStatus of chargingStation.evses.values()) {
1452 for (const [connectorId, connectorStatus] of evseStatus.connectors) {
1453 chargingStation.ocppRequestService
1454 .requestHandler<
1455 OCPP16StatusNotificationRequest,
1456 OCPP16StatusNotificationResponse
1457 >(
1458 chargingStation,
1459 OCPP16RequestCommand.STATUS_NOTIFICATION,
1460 {
1461 connectorId,
1462 errorCode: OCPP16ChargePointErrorCode.NO_ERROR,
1463 status: connectorStatus.status,
1464 },
1465 {
1466 triggerMessage: true,
5edd8ba0 1467 },
ded57f02
JB
1468 )
1469 .catch(Constants.EMPTY_FUNCTION);
1470 }
1471 }
1472 } else {
1473 for (const connectorId of chargingStation.connectors.keys()) {
1474 chargingStation.ocppRequestService
1475 .requestHandler<
1476 OCPP16StatusNotificationRequest,
1477 OCPP16StatusNotificationResponse
1478 >(
1479 chargingStation,
1480 OCPP16RequestCommand.STATUS_NOTIFICATION,
1481 {
1482 connectorId,
1483 errorCode: OCPP16ChargePointErrorCode.NO_ERROR,
1484 status: chargingStation.getConnectorStatus(connectorId)?.status,
1485 },
1486 {
1487 triggerMessage: true,
5edd8ba0 1488 },
ded57f02
JB
1489 )
1490 .catch(Constants.EMPTY_FUNCTION);
1491 }
dc661702
JB
1492 }
1493 }
d8b1fab1
JB
1494 }, OCPP16Constants.OCPP_TRIGGER_MESSAGE_DELAY);
1495 return OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED;
802cfa13 1496 default:
d8b1fab1 1497 return OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED;
802cfa13
JB
1498 }
1499 } catch (error) {
e1d9a0f4 1500 return this.handleIncomingRequestError<OCPP16TriggerMessageResponse>(
08f130a0 1501 chargingStation,
e7aeea18
JB
1502 OCPP16IncomingRequestCommand.TRIGGER_MESSAGE,
1503 error as Error,
5edd8ba0 1504 { errorResponse: OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED },
e1d9a0f4 1505 )!;
802cfa13
JB
1506 }
1507 }
77b95a89
JB
1508
1509 private handleRequestDataTransfer(
1510 chargingStation: ChargingStation,
5edd8ba0 1511 commandPayload: OCPP16DataTransferRequest,
77b95a89
JB
1512 ): OCPP16DataTransferResponse {
1513 try {
1514 if (Object.values(OCPP16DataTransferVendorId).includes(commandPayload.vendorId)) {
b63b4a73 1515 return OCPP16Constants.OCPP_DATA_TRANSFER_RESPONSE_ACCEPTED;
77b95a89 1516 }
b63b4a73 1517 return OCPP16Constants.OCPP_DATA_TRANSFER_RESPONSE_UNKNOWN_VENDOR_ID;
77b95a89 1518 } catch (error) {
e1d9a0f4 1519 return this.handleIncomingRequestError<OCPP16DataTransferResponse>(
77b95a89
JB
1520 chargingStation,
1521 OCPP16IncomingRequestCommand.DATA_TRANSFER,
1522 error as Error,
5edd8ba0 1523 { errorResponse: OCPP16Constants.OCPP_DATA_TRANSFER_RESPONSE_REJECTED },
e1d9a0f4 1524 )!;
77b95a89
JB
1525 }
1526 }
24578c31
JB
1527
1528 private async handleRequestReserveNow(
1529 chargingStation: ChargingStation,
5edd8ba0 1530 commandPayload: OCPP16ReserveNowRequest,
24578c31 1531 ): Promise<OCPP16ReserveNowResponse> {
66dd3447
JB
1532 if (
1533 !OCPP16ServiceUtils.checkFeatureProfile(
1534 chargingStation,
1535 OCPP16SupportedFeatureProfiles.Reservation,
5edd8ba0 1536 OCPP16IncomingRequestCommand.RESERVE_NOW,
66dd3447
JB
1537 )
1538 ) {
178956d8 1539 return OCPP16Constants.OCPP_RESERVATION_RESPONSE_REJECTED;
66dd3447 1540 }
24578c31 1541 const { reservationId, idTag, connectorId } = commandPayload;
24578c31
JB
1542 let response: OCPP16ReserveNowResponse;
1543 try {
d984c13f 1544 if (connectorId > 0 && !chargingStation.isConnectorAvailable(connectorId)) {
178956d8 1545 return OCPP16Constants.OCPP_RESERVATION_RESPONSE_REJECTED;
24578c31 1546 }
10e8c3e1 1547 if (connectorId === 0 && !chargingStation.getReserveConnectorZeroSupported()) {
178956d8 1548 return OCPP16Constants.OCPP_RESERVATION_RESPONSE_REJECTED;
24578c31 1549 }
66dd3447 1550 if (!(await OCPP16ServiceUtils.isIdTagAuthorized(chargingStation, connectorId, idTag))) {
178956d8 1551 return OCPP16Constants.OCPP_RESERVATION_RESPONSE_REJECTED;
24578c31 1552 }
e1d9a0f4 1553 switch (chargingStation.getConnectorStatus(connectorId)!.status) {
178956d8
JB
1554 case OCPP16ChargePointStatus.Faulted:
1555 response = OCPP16Constants.OCPP_RESERVATION_RESPONSE_FAULTED;
24578c31 1556 break;
178956d8
JB
1557 case OCPP16ChargePointStatus.Preparing:
1558 case OCPP16ChargePointStatus.Charging:
1559 case OCPP16ChargePointStatus.SuspendedEV:
1560 case OCPP16ChargePointStatus.SuspendedEVSE:
1561 case OCPP16ChargePointStatus.Finishing:
1562 response = OCPP16Constants.OCPP_RESERVATION_RESPONSE_OCCUPIED;
24578c31 1563 break;
178956d8
JB
1564 case OCPP16ChargePointStatus.Unavailable:
1565 response = OCPP16Constants.OCPP_RESERVATION_RESPONSE_UNAVAILABLE;
24578c31 1566 break;
178956d8 1567 case OCPP16ChargePointStatus.Reserved:
66dd3447 1568 if (!chargingStation.isConnectorReservable(reservationId, idTag, connectorId)) {
178956d8 1569 response = OCPP16Constants.OCPP_RESERVATION_RESPONSE_OCCUPIED;
24578c31
JB
1570 break;
1571 }
1572 // eslint-disable-next-line no-fallthrough
1573 default:
66dd3447 1574 if (!chargingStation.isConnectorReservable(reservationId, idTag)) {
178956d8 1575 response = OCPP16Constants.OCPP_RESERVATION_RESPONSE_OCCUPIED;
d193a949
JB
1576 break;
1577 }
1578 await chargingStation.addReservation({
1579 id: commandPayload.reservationId,
1580 ...commandPayload,
1581 });
178956d8 1582 response = OCPP16Constants.OCPP_RESERVATION_RESPONSE_ACCEPTED;
24578c31
JB
1583 break;
1584 }
1585 return response;
1586 } catch (error) {
e1d9a0f4
JB
1587 chargingStation.getConnectorStatus(connectorId)!.status = OCPP16ChargePointStatus.Available;
1588 return this.handleIncomingRequestError<OCPP16ReserveNowResponse>(
24578c31
JB
1589 chargingStation,
1590 OCPP16IncomingRequestCommand.RESERVE_NOW,
1591 error as Error,
5edd8ba0 1592 { errorResponse: OCPP16Constants.OCPP_RESERVATION_RESPONSE_FAULTED },
e1d9a0f4 1593 )!;
24578c31
JB
1594 }
1595 }
1596
1597 private async handleRequestCancelReservation(
1598 chargingStation: ChargingStation,
5edd8ba0 1599 commandPayload: OCPP16CancelReservationRequest,
b1f1b0f6 1600 ): Promise<GenericResponse> {
66dd3447
JB
1601 if (
1602 !OCPP16ServiceUtils.checkFeatureProfile(
1603 chargingStation,
1604 OCPP16SupportedFeatureProfiles.Reservation,
5edd8ba0 1605 OCPP16IncomingRequestCommand.CANCEL_RESERVATION,
66dd3447
JB
1606 )
1607 ) {
178956d8 1608 return OCPP16Constants.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED;
66dd3447 1609 }
24578c31 1610 try {
d193a949 1611 const { reservationId } = commandPayload;
2ca0ea90 1612 const reservation = chargingStation.getReservationBy('reservationId', reservationId);
af4339e1 1613 if (isUndefined(reservation)) {
24578c31 1614 logger.error(
66dd3447 1615 `${chargingStation.logPrefix()} Reservation with ID ${reservationId}
5edd8ba0 1616 does not exist on charging station`,
24578c31 1617 );
178956d8 1618 return OCPP16Constants.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED;
24578c31 1619 }
ec9f36cc 1620 await chargingStation.removeReservation(
e1d9a0f4 1621 reservation!,
5edd8ba0 1622 ReservationTerminationReason.RESERVATION_CANCELED,
ec9f36cc 1623 );
178956d8 1624 return OCPP16Constants.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED;
24578c31 1625 } catch (error) {
e1d9a0f4 1626 return this.handleIncomingRequestError<GenericResponse>(
24578c31
JB
1627 chargingStation,
1628 OCPP16IncomingRequestCommand.CANCEL_RESERVATION,
1629 error as Error,
5edd8ba0 1630 { errorResponse: OCPP16Constants.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED },
e1d9a0f4 1631 )!;
24578c31
JB
1632 }
1633 }
c0560973 1634}