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