Prepare the code for ESM support
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / 1.6 / OCPP16IncomingRequestService.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import {
4 ChangeAvailabilityRequest,
5 ChangeConfigurationRequest,
6 ClearChargingProfileRequest,
7 DiagnosticsStatusNotificationRequest,
8 GetConfigurationRequest,
9 GetDiagnosticsRequest,
10 MessageTrigger,
11 OCPP16AvailabilityType,
12 OCPP16BootNotificationRequest,
13 OCPP16HeartbeatRequest,
14 OCPP16IncomingRequestCommand,
15 OCPP16RequestCommand,
16 OCPP16StatusNotificationRequest,
17 OCPP16TriggerMessageRequest,
18 RemoteStartTransactionRequest,
19 RemoteStopTransactionRequest,
20 ResetRequest,
21 SetChargingProfileRequest,
22 UnlockConnectorRequest,
23 } from '../../../types/ocpp/1.6/Requests';
24 import {
25 ChangeAvailabilityResponse,
26 ChangeConfigurationResponse,
27 ClearChargingProfileResponse,
28 DiagnosticsStatusNotificationResponse,
29 GetConfigurationResponse,
30 GetDiagnosticsResponse,
31 OCPP16BootNotificationResponse,
32 OCPP16HeartbeatResponse,
33 OCPP16StatusNotificationResponse,
34 OCPP16TriggerMessageResponse,
35 SetChargingProfileResponse,
36 UnlockConnectorResponse,
37 } from '../../../types/ocpp/1.6/Responses';
38 import {
39 ChargingProfilePurposeType,
40 OCPP16ChargingProfile,
41 } from '../../../types/ocpp/1.6/ChargingProfile';
42 import { Client, FTPResponse } from 'basic-ftp';
43 import {
44 OCPP16AuthorizationStatus,
45 OCPP16AuthorizeRequest,
46 OCPP16AuthorizeResponse,
47 OCPP16StartTransactionRequest,
48 OCPP16StartTransactionResponse,
49 OCPP16StopTransactionReason,
50 OCPP16StopTransactionRequest,
51 OCPP16StopTransactionResponse,
52 } from '../../../types/ocpp/1.6/Transaction';
53 import {
54 OCPP16MeterValuesRequest,
55 OCPP16MeterValuesResponse,
56 } from '../../../types/ocpp/1.6/MeterValues';
57 import {
58 OCPP16StandardParametersKey,
59 OCPP16SupportedFeatureProfiles,
60 } from '../../../types/ocpp/1.6/Configuration';
61 import { URL, fileURLToPath } from 'url';
62
63 import type ChargingStation from '../../ChargingStation';
64 import { ChargingStationConfigurationUtils } from '../../ChargingStationConfigurationUtils';
65 import Constants from '../../../utils/Constants';
66 import { DefaultResponse } from '../../../types/ocpp/Responses';
67 import { ErrorType } from '../../../types/ocpp/ErrorType';
68 import { IncomingRequestHandler } from '../../../types/ocpp/Requests';
69 import { JsonType } from '../../../types/JsonType';
70 import { OCPP16ChargePointErrorCode } from '../../../types/ocpp/1.6/ChargePointErrorCode';
71 import { OCPP16ChargePointStatus } from '../../../types/ocpp/1.6/ChargePointStatus';
72 import { OCPP16DiagnosticsStatus } from '../../../types/ocpp/1.6/DiagnosticsStatus';
73 import { OCPP16ServiceUtils } from './OCPP16ServiceUtils';
74 import { OCPPConfigurationKey } from '../../../types/ocpp/Configuration';
75 import OCPPError from '../../../exception/OCPPError';
76 import OCPPIncomingRequestService from '../OCPPIncomingRequestService';
77 import Utils from '../../../utils/Utils';
78 import fs from 'fs';
79 import logger from '../../../utils/Logger';
80 import path from 'path';
81 import tar from 'tar';
82
83 const moduleName = 'OCPP16IncomingRequestService';
84
85 export default class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
86 private incomingRequestHandlers: Map<OCPP16IncomingRequestCommand, IncomingRequestHandler>;
87
88 public constructor() {
89 if (new.target?.name === moduleName) {
90 throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
91 }
92 super();
93 this.incomingRequestHandlers = new Map<OCPP16IncomingRequestCommand, IncomingRequestHandler>([
94 [OCPP16IncomingRequestCommand.RESET, this.handleRequestReset.bind(this)],
95 [OCPP16IncomingRequestCommand.CLEAR_CACHE, this.handleRequestClearCache.bind(this)],
96 [OCPP16IncomingRequestCommand.UNLOCK_CONNECTOR, this.handleRequestUnlockConnector.bind(this)],
97 [
98 OCPP16IncomingRequestCommand.GET_CONFIGURATION,
99 this.handleRequestGetConfiguration.bind(this),
100 ],
101 [
102 OCPP16IncomingRequestCommand.CHANGE_CONFIGURATION,
103 this.handleRequestChangeConfiguration.bind(this),
104 ],
105 [
106 OCPP16IncomingRequestCommand.SET_CHARGING_PROFILE,
107 this.handleRequestSetChargingProfile.bind(this),
108 ],
109 [
110 OCPP16IncomingRequestCommand.CLEAR_CHARGING_PROFILE,
111 this.handleRequestClearChargingProfile.bind(this),
112 ],
113 [
114 OCPP16IncomingRequestCommand.CHANGE_AVAILABILITY,
115 this.handleRequestChangeAvailability.bind(this),
116 ],
117 [
118 OCPP16IncomingRequestCommand.REMOTE_START_TRANSACTION,
119 this.handleRequestRemoteStartTransaction.bind(this),
120 ],
121 [
122 OCPP16IncomingRequestCommand.REMOTE_STOP_TRANSACTION,
123 this.handleRequestRemoteStopTransaction.bind(this),
124 ],
125 [OCPP16IncomingRequestCommand.GET_DIAGNOSTICS, this.handleRequestGetDiagnostics.bind(this)],
126 [OCPP16IncomingRequestCommand.TRIGGER_MESSAGE, this.handleRequestTriggerMessage.bind(this)],
127 ]);
128 }
129
130 public async incomingRequestHandler(
131 chargingStation: ChargingStation,
132 messageId: string,
133 commandName: OCPP16IncomingRequestCommand,
134 commandPayload: JsonType
135 ): Promise<void> {
136 let response: JsonType;
137 if (
138 chargingStation.getOcppStrictCompliance() &&
139 chargingStation.isInPendingState() &&
140 (commandName === OCPP16IncomingRequestCommand.REMOTE_START_TRANSACTION ||
141 commandName === OCPP16IncomingRequestCommand.REMOTE_STOP_TRANSACTION)
142 ) {
143 throw new OCPPError(
144 ErrorType.SECURITY_ERROR,
145 `${commandName} cannot be issued to handle request payload ${JSON.stringify(
146 commandPayload,
147 null,
148 2
149 )} while the charging station is in pending state on the central server`,
150 commandName
151 );
152 }
153 if (
154 chargingStation.isRegistered() ||
155 (!chargingStation.getOcppStrictCompliance() && chargingStation.isInUnknownState())
156 ) {
157 if (this.incomingRequestHandlers.has(commandName)) {
158 try {
159 // Call the method to build the response
160 response = await this.incomingRequestHandlers.get(commandName)(
161 chargingStation,
162 commandPayload
163 );
164 } catch (error) {
165 // Log
166 logger.error(chargingStation.logPrefix() + ' Handle request error: %j', error);
167 throw error;
168 }
169 } else {
170 // Throw exception
171 throw new OCPPError(
172 ErrorType.NOT_IMPLEMENTED,
173 `${commandName} is not implemented to handle request payload ${JSON.stringify(
174 commandPayload,
175 null,
176 2
177 )}`,
178 commandName
179 );
180 }
181 } else {
182 throw new OCPPError(
183 ErrorType.SECURITY_ERROR,
184 `${commandName} cannot be issued to handle request payload ${JSON.stringify(
185 commandPayload,
186 null,
187 2
188 )} while the charging station is not registered on the central server.`,
189 commandName
190 );
191 }
192 // Send the built response
193 await chargingStation.ocppRequestService.sendResponse(
194 chargingStation,
195 messageId,
196 response,
197 commandName
198 );
199 }
200
201 // Simulate charging station restart
202 private handleRequestReset(
203 chargingStation: ChargingStation,
204 commandPayload: ResetRequest
205 ): DefaultResponse {
206 // eslint-disable-next-line @typescript-eslint/no-misused-promises
207 setImmediate(async (): Promise<void> => {
208 await chargingStation.reset((commandPayload.type + 'Reset') as OCPP16StopTransactionReason);
209 });
210 logger.info(
211 `${chargingStation.logPrefix()} ${
212 commandPayload.type
213 } reset command received, simulating it. The station will be back online in ${Utils.formatDurationMilliSeconds(
214 chargingStation.stationInfo.resetTime
215 )}`
216 );
217 return Constants.OCPP_RESPONSE_ACCEPTED;
218 }
219
220 private handleRequestClearCache(): DefaultResponse {
221 return Constants.OCPP_RESPONSE_ACCEPTED;
222 }
223
224 private async handleRequestUnlockConnector(
225 chargingStation: ChargingStation,
226 commandPayload: UnlockConnectorRequest
227 ): Promise<UnlockConnectorResponse> {
228 const connectorId = commandPayload.connectorId;
229 if (connectorId === 0) {
230 logger.error(
231 chargingStation.logPrefix() + ' Trying to unlock connector ' + connectorId.toString()
232 );
233 return Constants.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED;
234 }
235 if (chargingStation.getConnectorStatus(connectorId)?.transactionStarted) {
236 const transactionId = chargingStation.getConnectorStatus(connectorId).transactionId;
237 if (
238 chargingStation.getBeginEndMeterValues() &&
239 chargingStation.getOcppStrictCompliance() &&
240 !chargingStation.getOutOfOrderEndMeterValues()
241 ) {
242 // FIXME: Implement OCPP version agnostic helpers
243 const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
244 chargingStation,
245 connectorId,
246 chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId)
247 );
248 await chargingStation.ocppRequestService.requestHandler<
249 OCPP16MeterValuesRequest,
250 OCPP16MeterValuesResponse
251 >(chargingStation, OCPP16RequestCommand.METER_VALUES, {
252 connectorId,
253 transactionId,
254 meterValue: transactionEndMeterValue,
255 });
256 }
257 const stopResponse = await chargingStation.ocppRequestService.requestHandler<
258 OCPP16StopTransactionRequest,
259 OCPP16StopTransactionResponse
260 >(chargingStation, OCPP16RequestCommand.STOP_TRANSACTION, {
261 transactionId,
262 meterStop: chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
263 idTag: chargingStation.getTransactionIdTag(transactionId),
264 reason: OCPP16StopTransactionReason.UNLOCK_COMMAND,
265 });
266 if (stopResponse.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED) {
267 return Constants.OCPP_RESPONSE_UNLOCKED;
268 }
269 return Constants.OCPP_RESPONSE_UNLOCK_FAILED;
270 }
271 await chargingStation.ocppRequestService.requestHandler<
272 OCPP16StatusNotificationRequest,
273 OCPP16StatusNotificationResponse
274 >(chargingStation, OCPP16RequestCommand.STATUS_NOTIFICATION, {
275 connectorId,
276 status: OCPP16ChargePointStatus.AVAILABLE,
277 errorCode: OCPP16ChargePointErrorCode.NO_ERROR,
278 });
279 chargingStation.getConnectorStatus(connectorId).status = OCPP16ChargePointStatus.AVAILABLE;
280 return Constants.OCPP_RESPONSE_UNLOCKED;
281 }
282
283 private handleRequestGetConfiguration(
284 chargingStation: ChargingStation,
285 commandPayload: GetConfigurationRequest
286 ): GetConfigurationResponse {
287 const configurationKey: OCPPConfigurationKey[] = [];
288 const unknownKey: string[] = [];
289 if (Utils.isEmptyArray(commandPayload.key)) {
290 for (const configuration of chargingStation.ocppConfiguration.configurationKey) {
291 if (Utils.isUndefined(configuration.visible)) {
292 configuration.visible = true;
293 }
294 if (!configuration.visible) {
295 continue;
296 }
297 configurationKey.push({
298 key: configuration.key,
299 readonly: configuration.readonly,
300 value: configuration.value,
301 });
302 }
303 } else {
304 for (const key of commandPayload.key) {
305 const keyFound = ChargingStationConfigurationUtils.getConfigurationKey(
306 chargingStation,
307 key
308 );
309 if (keyFound) {
310 if (Utils.isUndefined(keyFound.visible)) {
311 keyFound.visible = true;
312 }
313 if (!keyFound.visible) {
314 continue;
315 }
316 configurationKey.push({
317 key: keyFound.key,
318 readonly: keyFound.readonly,
319 value: keyFound.value,
320 });
321 } else {
322 unknownKey.push(key);
323 }
324 }
325 }
326 return {
327 configurationKey,
328 unknownKey,
329 };
330 }
331
332 private handleRequestChangeConfiguration(
333 chargingStation: ChargingStation,
334 commandPayload: ChangeConfigurationRequest
335 ): ChangeConfigurationResponse {
336 // JSON request fields type sanity check
337 if (!Utils.isString(commandPayload.key)) {
338 logger.error(
339 `${chargingStation.logPrefix()} ${
340 OCPP16IncomingRequestCommand.CHANGE_CONFIGURATION
341 } request key field is not a string:`,
342 commandPayload
343 );
344 }
345 if (!Utils.isString(commandPayload.value)) {
346 logger.error(
347 `${chargingStation.logPrefix()} ${
348 OCPP16IncomingRequestCommand.CHANGE_CONFIGURATION
349 } request value field is not a string:`,
350 commandPayload
351 );
352 }
353 const keyToChange = ChargingStationConfigurationUtils.getConfigurationKey(
354 chargingStation,
355 commandPayload.key,
356 true
357 );
358 if (!keyToChange) {
359 return Constants.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED;
360 } else if (keyToChange && keyToChange.readonly) {
361 return Constants.OCPP_CONFIGURATION_RESPONSE_REJECTED;
362 } else if (keyToChange && !keyToChange.readonly) {
363 let valueChanged = false;
364 if (keyToChange.value !== commandPayload.value) {
365 ChargingStationConfigurationUtils.setConfigurationKeyValue(
366 chargingStation,
367 commandPayload.key,
368 commandPayload.value,
369 true
370 );
371 valueChanged = true;
372 }
373 let triggerHeartbeatRestart = false;
374 if (keyToChange.key === OCPP16StandardParametersKey.HeartBeatInterval && valueChanged) {
375 ChargingStationConfigurationUtils.setConfigurationKeyValue(
376 chargingStation,
377 OCPP16StandardParametersKey.HeartbeatInterval,
378 commandPayload.value
379 );
380 triggerHeartbeatRestart = true;
381 }
382 if (keyToChange.key === OCPP16StandardParametersKey.HeartbeatInterval && valueChanged) {
383 ChargingStationConfigurationUtils.setConfigurationKeyValue(
384 chargingStation,
385 OCPP16StandardParametersKey.HeartBeatInterval,
386 commandPayload.value
387 );
388 triggerHeartbeatRestart = true;
389 }
390 if (triggerHeartbeatRestart) {
391 chargingStation.restartHeartbeat();
392 }
393 if (keyToChange.key === OCPP16StandardParametersKey.WebSocketPingInterval && valueChanged) {
394 chargingStation.restartWebSocketPing();
395 }
396 if (keyToChange.reboot) {
397 return Constants.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED;
398 }
399 return Constants.OCPP_CONFIGURATION_RESPONSE_ACCEPTED;
400 }
401 }
402
403 private handleRequestSetChargingProfile(
404 chargingStation: ChargingStation,
405 commandPayload: SetChargingProfileRequest
406 ): SetChargingProfileResponse {
407 if (
408 !OCPP16ServiceUtils.checkFeatureProfile(
409 chargingStation,
410 OCPP16SupportedFeatureProfiles.SmartCharging,
411 OCPP16IncomingRequestCommand.SET_CHARGING_PROFILE
412 )
413 ) {
414 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED;
415 }
416 if (!chargingStation.getConnectorStatus(commandPayload.connectorId)) {
417 logger.error(
418 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${
419 commandPayload.connectorId
420 }`
421 );
422 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED;
423 }
424 if (
425 commandPayload.csChargingProfiles.chargingProfilePurpose ===
426 ChargingProfilePurposeType.CHARGE_POINT_MAX_PROFILE &&
427 commandPayload.connectorId !== 0
428 ) {
429 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED;
430 }
431 if (
432 commandPayload.csChargingProfiles.chargingProfilePurpose ===
433 ChargingProfilePurposeType.TX_PROFILE &&
434 (commandPayload.connectorId === 0 ||
435 !chargingStation.getConnectorStatus(commandPayload.connectorId)?.transactionStarted)
436 ) {
437 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED;
438 }
439 chargingStation.setChargingProfile(
440 commandPayload.connectorId,
441 commandPayload.csChargingProfiles
442 );
443 logger.debug(
444 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${
445 commandPayload.connectorId
446 }, dump their stack: %j`,
447 chargingStation.getConnectorStatus(commandPayload.connectorId).chargingProfiles
448 );
449 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED;
450 }
451
452 private handleRequestClearChargingProfile(
453 chargingStation: ChargingStation,
454 commandPayload: ClearChargingProfileRequest
455 ): ClearChargingProfileResponse {
456 if (
457 !OCPP16ServiceUtils.checkFeatureProfile(
458 chargingStation,
459 OCPP16SupportedFeatureProfiles.SmartCharging,
460 OCPP16IncomingRequestCommand.CLEAR_CHARGING_PROFILE
461 )
462 ) {
463 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN;
464 }
465 const connectorStatus = chargingStation.getConnectorStatus(commandPayload.connectorId);
466 if (!connectorStatus) {
467 logger.error(
468 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${
469 commandPayload.connectorId
470 }`
471 );
472 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN;
473 }
474 if (commandPayload.connectorId && !Utils.isEmptyArray(connectorStatus.chargingProfiles)) {
475 connectorStatus.chargingProfiles = [];
476 logger.debug(
477 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${
478 commandPayload.connectorId
479 }, dump their stack: %j`,
480 connectorStatus.chargingProfiles
481 );
482 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED;
483 }
484 if (!commandPayload.connectorId) {
485 let clearedCP = false;
486 for (const connectorId of chargingStation.connectors.keys()) {
487 if (!Utils.isEmptyArray(chargingStation.getConnectorStatus(connectorId).chargingProfiles)) {
488 chargingStation
489 .getConnectorStatus(connectorId)
490 .chargingProfiles?.forEach((chargingProfile: OCPP16ChargingProfile, index: number) => {
491 let clearCurrentCP = false;
492 if (chargingProfile.chargingProfileId === commandPayload.id) {
493 clearCurrentCP = true;
494 }
495 if (
496 !commandPayload.chargingProfilePurpose &&
497 chargingProfile.stackLevel === commandPayload.stackLevel
498 ) {
499 clearCurrentCP = true;
500 }
501 if (
502 !chargingProfile.stackLevel &&
503 chargingProfile.chargingProfilePurpose === commandPayload.chargingProfilePurpose
504 ) {
505 clearCurrentCP = true;
506 }
507 if (
508 chargingProfile.stackLevel === commandPayload.stackLevel &&
509 chargingProfile.chargingProfilePurpose === commandPayload.chargingProfilePurpose
510 ) {
511 clearCurrentCP = true;
512 }
513 if (clearCurrentCP) {
514 connectorStatus.chargingProfiles.splice(index, 1);
515 logger.debug(
516 `${chargingStation.logPrefix()} Matching charging profile(s) cleared on connector id ${
517 commandPayload.connectorId
518 }, dump their stack: %j`,
519 connectorStatus.chargingProfiles
520 );
521 clearedCP = true;
522 }
523 });
524 }
525 }
526 if (clearedCP) {
527 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED;
528 }
529 }
530 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN;
531 }
532
533 private async handleRequestChangeAvailability(
534 chargingStation: ChargingStation,
535 commandPayload: ChangeAvailabilityRequest
536 ): Promise<ChangeAvailabilityResponse> {
537 const connectorId: number = commandPayload.connectorId;
538 if (!chargingStation.getConnectorStatus(connectorId)) {
539 logger.error(
540 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`
541 );
542 return Constants.OCPP_AVAILABILITY_RESPONSE_REJECTED;
543 }
544 const chargePointStatus: OCPP16ChargePointStatus =
545 commandPayload.type === OCPP16AvailabilityType.OPERATIVE
546 ? OCPP16ChargePointStatus.AVAILABLE
547 : OCPP16ChargePointStatus.UNAVAILABLE;
548 if (connectorId === 0) {
549 let response: ChangeAvailabilityResponse = Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED;
550 for (const id of chargingStation.connectors.keys()) {
551 if (chargingStation.getConnectorStatus(id)?.transactionStarted) {
552 response = Constants.OCPP_AVAILABILITY_RESPONSE_SCHEDULED;
553 }
554 chargingStation.getConnectorStatus(id).availability = commandPayload.type;
555 if (response === Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED) {
556 await chargingStation.ocppRequestService.requestHandler<
557 OCPP16StatusNotificationRequest,
558 OCPP16StatusNotificationResponse
559 >(chargingStation, OCPP16RequestCommand.STATUS_NOTIFICATION, {
560 connectorId: id,
561 status: chargePointStatus,
562 errorCode: OCPP16ChargePointErrorCode.NO_ERROR,
563 });
564 chargingStation.getConnectorStatus(id).status = chargePointStatus;
565 }
566 }
567 return response;
568 } else if (
569 connectorId > 0 &&
570 (chargingStation.getConnectorStatus(0).availability === OCPP16AvailabilityType.OPERATIVE ||
571 (chargingStation.getConnectorStatus(0).availability ===
572 OCPP16AvailabilityType.INOPERATIVE &&
573 commandPayload.type === OCPP16AvailabilityType.INOPERATIVE))
574 ) {
575 if (chargingStation.getConnectorStatus(connectorId)?.transactionStarted) {
576 chargingStation.getConnectorStatus(connectorId).availability = commandPayload.type;
577 return Constants.OCPP_AVAILABILITY_RESPONSE_SCHEDULED;
578 }
579 chargingStation.getConnectorStatus(connectorId).availability = commandPayload.type;
580 await chargingStation.ocppRequestService.requestHandler<
581 OCPP16StatusNotificationRequest,
582 OCPP16StatusNotificationResponse
583 >(chargingStation, OCPP16RequestCommand.STATUS_NOTIFICATION, {
584 connectorId,
585 status: chargePointStatus,
586 errorCode: OCPP16ChargePointErrorCode.NO_ERROR,
587 });
588 chargingStation.getConnectorStatus(connectorId).status = chargePointStatus;
589 return Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED;
590 }
591 return Constants.OCPP_AVAILABILITY_RESPONSE_REJECTED;
592 }
593
594 private async handleRequestRemoteStartTransaction(
595 chargingStation: ChargingStation,
596 commandPayload: RemoteStartTransactionRequest
597 ): Promise<DefaultResponse> {
598 const transactionConnectorId = commandPayload.connectorId;
599 const connectorStatus = chargingStation.getConnectorStatus(transactionConnectorId);
600 if (transactionConnectorId) {
601 await chargingStation.ocppRequestService.requestHandler<
602 OCPP16StatusNotificationRequest,
603 OCPP16StatusNotificationResponse
604 >(chargingStation, OCPP16RequestCommand.STATUS_NOTIFICATION, {
605 connectorId: transactionConnectorId,
606 status: OCPP16ChargePointStatus.PREPARING,
607 errorCode: OCPP16ChargePointErrorCode.NO_ERROR,
608 });
609 connectorStatus.status = OCPP16ChargePointStatus.PREPARING;
610 if (chargingStation.isChargingStationAvailable() && connectorStatus) {
611 // Check if authorized
612 if (chargingStation.getAuthorizeRemoteTxRequests()) {
613 let authorized = false;
614 if (
615 chargingStation.getLocalAuthListEnabled() &&
616 chargingStation.hasAuthorizedTags() &&
617 chargingStation.authorizedTags.find((value) => value === commandPayload.idTag)
618 ) {
619 connectorStatus.localAuthorizeIdTag = commandPayload.idTag;
620 connectorStatus.idTagLocalAuthorized = true;
621 authorized = true;
622 } else if (chargingStation.getMayAuthorizeAtRemoteStart()) {
623 connectorStatus.authorizeIdTag = commandPayload.idTag;
624 const authorizeResponse: OCPP16AuthorizeResponse =
625 await chargingStation.ocppRequestService.requestHandler<
626 OCPP16AuthorizeRequest,
627 OCPP16AuthorizeResponse
628 >(chargingStation, OCPP16RequestCommand.AUTHORIZE, {
629 idTag: commandPayload.idTag,
630 });
631 if (authorizeResponse?.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED) {
632 authorized = true;
633 }
634 } else {
635 logger.warn(
636 `${chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`
637 );
638 }
639 if (authorized) {
640 // Authorization successful, start transaction
641 if (
642 this.setRemoteStartTransactionChargingProfile(
643 chargingStation,
644 transactionConnectorId,
645 commandPayload.chargingProfile
646 )
647 ) {
648 connectorStatus.transactionRemoteStarted = true;
649 if (
650 (
651 await chargingStation.ocppRequestService.requestHandler<
652 OCPP16StartTransactionRequest,
653 OCPP16StartTransactionResponse
654 >(chargingStation, OCPP16RequestCommand.START_TRANSACTION, {
655 connectorId: transactionConnectorId,
656 idTag: commandPayload.idTag,
657 })
658 ).idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED
659 ) {
660 logger.debug(
661 chargingStation.logPrefix() +
662 ' Transaction remotely STARTED on ' +
663 chargingStation.stationInfo.chargingStationId +
664 '#' +
665 transactionConnectorId.toString() +
666 ' for idTag ' +
667 commandPayload.idTag
668 );
669 return Constants.OCPP_RESPONSE_ACCEPTED;
670 }
671 return this.notifyRemoteStartTransactionRejected(
672 chargingStation,
673 transactionConnectorId,
674 commandPayload.idTag
675 );
676 }
677 return this.notifyRemoteStartTransactionRejected(
678 chargingStation,
679 transactionConnectorId,
680 commandPayload.idTag
681 );
682 }
683 return this.notifyRemoteStartTransactionRejected(
684 chargingStation,
685 transactionConnectorId,
686 commandPayload.idTag
687 );
688 }
689 // No authorization check required, start transaction
690 if (
691 this.setRemoteStartTransactionChargingProfile(
692 chargingStation,
693 transactionConnectorId,
694 commandPayload.chargingProfile
695 )
696 ) {
697 connectorStatus.transactionRemoteStarted = true;
698 if (
699 (
700 await chargingStation.ocppRequestService.requestHandler<
701 OCPP16StartTransactionRequest,
702 OCPP16StartTransactionResponse
703 >(chargingStation, OCPP16RequestCommand.START_TRANSACTION, {
704 connectorId: transactionConnectorId,
705 idTag: commandPayload.idTag,
706 })
707 ).idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED
708 ) {
709 logger.debug(
710 chargingStation.logPrefix() +
711 ' Transaction remotely STARTED on ' +
712 chargingStation.stationInfo.chargingStationId +
713 '#' +
714 transactionConnectorId.toString() +
715 ' for idTag ' +
716 commandPayload.idTag
717 );
718 return Constants.OCPP_RESPONSE_ACCEPTED;
719 }
720 return this.notifyRemoteStartTransactionRejected(
721 chargingStation,
722 transactionConnectorId,
723 commandPayload.idTag
724 );
725 }
726 return this.notifyRemoteStartTransactionRejected(
727 chargingStation,
728 transactionConnectorId,
729 commandPayload.idTag
730 );
731 }
732 return this.notifyRemoteStartTransactionRejected(
733 chargingStation,
734 transactionConnectorId,
735 commandPayload.idTag
736 );
737 }
738 return this.notifyRemoteStartTransactionRejected(
739 chargingStation,
740 transactionConnectorId,
741 commandPayload.idTag
742 );
743 }
744
745 private async notifyRemoteStartTransactionRejected(
746 chargingStation: ChargingStation,
747 connectorId: number,
748 idTag: string
749 ): Promise<DefaultResponse> {
750 if (
751 chargingStation.getConnectorStatus(connectorId).status !== OCPP16ChargePointStatus.AVAILABLE
752 ) {
753 await chargingStation.ocppRequestService.requestHandler<
754 OCPP16StatusNotificationRequest,
755 OCPP16StatusNotificationResponse
756 >(chargingStation, OCPP16RequestCommand.STATUS_NOTIFICATION, {
757 connectorId,
758 status: OCPP16ChargePointStatus.AVAILABLE,
759 errorCode: OCPP16ChargePointErrorCode.NO_ERROR,
760 });
761 chargingStation.getConnectorStatus(connectorId).status = OCPP16ChargePointStatus.AVAILABLE;
762 }
763 logger.warn(
764 chargingStation.logPrefix() +
765 ' Remote starting transaction REJECTED on connector Id ' +
766 connectorId.toString() +
767 ', idTag ' +
768 idTag +
769 ', availability ' +
770 chargingStation.getConnectorStatus(connectorId).availability +
771 ', status ' +
772 chargingStation.getConnectorStatus(connectorId).status
773 );
774 return Constants.OCPP_RESPONSE_REJECTED;
775 }
776
777 private setRemoteStartTransactionChargingProfile(
778 chargingStation: ChargingStation,
779 connectorId: number,
780 cp: OCPP16ChargingProfile
781 ): boolean {
782 if (cp && cp.chargingProfilePurpose === ChargingProfilePurposeType.TX_PROFILE) {
783 chargingStation.setChargingProfile(connectorId, cp);
784 logger.debug(
785 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}, dump their stack: %j`,
786 chargingStation.getConnectorStatus(connectorId).chargingProfiles
787 );
788 return true;
789 } else if (cp && cp.chargingProfilePurpose !== ChargingProfilePurposeType.TX_PROFILE) {
790 logger.warn(
791 `${chargingStation.logPrefix()} Not allowed to set ${
792 cp.chargingProfilePurpose
793 } charging profile(s) at remote start transaction`
794 );
795 return false;
796 } else if (!cp) {
797 return true;
798 }
799 }
800
801 private async handleRequestRemoteStopTransaction(
802 chargingStation: ChargingStation,
803 commandPayload: RemoteStopTransactionRequest
804 ): Promise<DefaultResponse> {
805 const transactionId = commandPayload.transactionId;
806 for (const connectorId of chargingStation.connectors.keys()) {
807 if (
808 connectorId > 0 &&
809 chargingStation.getConnectorStatus(connectorId)?.transactionId === transactionId
810 ) {
811 await chargingStation.ocppRequestService.requestHandler<
812 OCPP16StatusNotificationRequest,
813 OCPP16StatusNotificationResponse
814 >(chargingStation, OCPP16RequestCommand.STATUS_NOTIFICATION, {
815 connectorId,
816 status: OCPP16ChargePointStatus.FINISHING,
817 errorCode: OCPP16ChargePointErrorCode.NO_ERROR,
818 });
819 chargingStation.getConnectorStatus(connectorId).status = OCPP16ChargePointStatus.FINISHING;
820 if (
821 chargingStation.getBeginEndMeterValues() &&
822 chargingStation.getOcppStrictCompliance() &&
823 !chargingStation.getOutOfOrderEndMeterValues()
824 ) {
825 // FIXME: Implement OCPP version agnostic helpers
826 const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
827 chargingStation,
828 connectorId,
829 chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId)
830 );
831 await chargingStation.ocppRequestService.requestHandler<
832 OCPP16MeterValuesRequest,
833 OCPP16MeterValuesResponse
834 >(chargingStation, OCPP16RequestCommand.METER_VALUES, {
835 connectorId,
836 transactionId,
837 meterValue: transactionEndMeterValue,
838 });
839 }
840 await chargingStation.ocppRequestService.requestHandler<
841 OCPP16StopTransactionRequest,
842 OCPP16StopTransactionResponse
843 >(chargingStation, OCPP16RequestCommand.STOP_TRANSACTION, {
844 transactionId,
845 meterStop: chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
846 idTag: chargingStation.getTransactionIdTag(transactionId),
847 });
848 return Constants.OCPP_RESPONSE_ACCEPTED;
849 }
850 }
851 logger.info(
852 chargingStation.logPrefix() +
853 ' Trying to remote stop a non existing transaction ' +
854 transactionId.toString()
855 );
856 return Constants.OCPP_RESPONSE_REJECTED;
857 }
858
859 private async handleRequestGetDiagnostics(
860 chargingStation: ChargingStation,
861 commandPayload: GetDiagnosticsRequest
862 ): Promise<GetDiagnosticsResponse> {
863 if (
864 !OCPP16ServiceUtils.checkFeatureProfile(
865 chargingStation,
866 OCPP16SupportedFeatureProfiles.FirmwareManagement,
867 OCPP16IncomingRequestCommand.GET_DIAGNOSTICS
868 )
869 ) {
870 return Constants.OCPP_RESPONSE_EMPTY;
871 }
872 logger.debug(
873 chargingStation.logPrefix() +
874 ' ' +
875 OCPP16IncomingRequestCommand.GET_DIAGNOSTICS +
876 ' request received: %j',
877 commandPayload
878 );
879 const uri = new URL(commandPayload.location);
880 if (uri.protocol.startsWith('ftp:')) {
881 let ftpClient: Client;
882 try {
883 const logFiles = fs
884 .readdirSync(path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../../'))
885 .filter((file) => file.endsWith('.log'))
886 .map((file) => path.join('./', file));
887 const diagnosticsArchive = chargingStation.stationInfo.chargingStationId + '_logs.tar.gz';
888 tar.create({ gzip: true }, logFiles).pipe(fs.createWriteStream(diagnosticsArchive));
889 ftpClient = new Client();
890 const accessResponse = await ftpClient.access({
891 host: uri.host,
892 ...(!Utils.isEmptyString(uri.port) && { port: Utils.convertToInt(uri.port) }),
893 ...(!Utils.isEmptyString(uri.username) && { user: uri.username }),
894 ...(!Utils.isEmptyString(uri.password) && { password: uri.password }),
895 });
896 let uploadResponse: FTPResponse;
897 if (accessResponse.code === 220) {
898 // eslint-disable-next-line @typescript-eslint/no-misused-promises
899 ftpClient.trackProgress(async (info) => {
900 logger.info(
901 `${chargingStation.logPrefix()} ${
902 info.bytes / 1024
903 } bytes transferred from diagnostics archive ${info.name}`
904 );
905 await chargingStation.ocppRequestService.requestHandler<
906 DiagnosticsStatusNotificationRequest,
907 DiagnosticsStatusNotificationResponse
908 >(chargingStation, OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION, {
909 status: OCPP16DiagnosticsStatus.Uploading,
910 });
911 });
912 uploadResponse = await ftpClient.uploadFrom(
913 path.join(
914 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../../'),
915 diagnosticsArchive
916 ),
917 uri.pathname + diagnosticsArchive
918 );
919 if (uploadResponse.code === 226) {
920 await chargingStation.ocppRequestService.requestHandler<
921 DiagnosticsStatusNotificationRequest,
922 DiagnosticsStatusNotificationResponse
923 >(chargingStation, OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION, {
924 status: OCPP16DiagnosticsStatus.Uploaded,
925 });
926 if (ftpClient) {
927 ftpClient.close();
928 }
929 return { fileName: diagnosticsArchive };
930 }
931 throw new OCPPError(
932 ErrorType.GENERIC_ERROR,
933 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
934 uploadResponse?.code && '|' + uploadResponse?.code.toString()
935 }`,
936 OCPP16IncomingRequestCommand.GET_DIAGNOSTICS
937 );
938 }
939 throw new OCPPError(
940 ErrorType.GENERIC_ERROR,
941 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
942 uploadResponse?.code && '|' + uploadResponse?.code.toString()
943 }`,
944 OCPP16IncomingRequestCommand.GET_DIAGNOSTICS
945 );
946 } catch (error) {
947 await chargingStation.ocppRequestService.requestHandler<
948 DiagnosticsStatusNotificationRequest,
949 DiagnosticsStatusNotificationResponse
950 >(chargingStation, OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION, {
951 status: OCPP16DiagnosticsStatus.UploadFailed,
952 });
953 if (ftpClient) {
954 ftpClient.close();
955 }
956 return this.handleIncomingRequestError(
957 chargingStation,
958 OCPP16IncomingRequestCommand.GET_DIAGNOSTICS,
959 error as Error,
960 { errorResponse: Constants.OCPP_RESPONSE_EMPTY }
961 );
962 }
963 } else {
964 logger.error(
965 `${chargingStation.logPrefix()} Unsupported protocol ${
966 uri.protocol
967 } to transfer the diagnostic logs archive`
968 );
969 await chargingStation.ocppRequestService.requestHandler<
970 DiagnosticsStatusNotificationRequest,
971 DiagnosticsStatusNotificationResponse
972 >(chargingStation, OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION, {
973 status: OCPP16DiagnosticsStatus.UploadFailed,
974 });
975 return Constants.OCPP_RESPONSE_EMPTY;
976 }
977 }
978
979 private handleRequestTriggerMessage(
980 chargingStation: ChargingStation,
981 commandPayload: OCPP16TriggerMessageRequest
982 ): OCPP16TriggerMessageResponse {
983 if (
984 !OCPP16ServiceUtils.checkFeatureProfile(
985 chargingStation,
986 OCPP16SupportedFeatureProfiles.RemoteTrigger,
987 OCPP16IncomingRequestCommand.TRIGGER_MESSAGE
988 )
989 ) {
990 return Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED;
991 }
992 // TODO: factor out the check on connector id
993 if (commandPayload?.connectorId < 0) {
994 logger.warn(
995 `${chargingStation.logPrefix()} ${
996 OCPP16IncomingRequestCommand.TRIGGER_MESSAGE
997 } incoming request received with invalid connectorId ${commandPayload.connectorId}`
998 );
999 return Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED;
1000 }
1001 try {
1002 switch (commandPayload.requestedMessage) {
1003 case MessageTrigger.BootNotification:
1004 setTimeout(() => {
1005 chargingStation.ocppRequestService
1006 .requestHandler<OCPP16BootNotificationRequest, OCPP16BootNotificationResponse>(
1007 chargingStation,
1008 OCPP16RequestCommand.BOOT_NOTIFICATION,
1009 {
1010 chargePointModel: chargingStation.getBootNotificationRequest().chargePointModel,
1011 chargePointVendor: chargingStation.getBootNotificationRequest().chargePointVendor,
1012 chargeBoxSerialNumber:
1013 chargingStation.getBootNotificationRequest().chargeBoxSerialNumber,
1014 firmwareVersion: chargingStation.getBootNotificationRequest().firmwareVersion,
1015 chargePointSerialNumber:
1016 chargingStation.getBootNotificationRequest().chargePointSerialNumber,
1017 iccid: chargingStation.getBootNotificationRequest().iccid,
1018 imsi: chargingStation.getBootNotificationRequest().imsi,
1019 meterSerialNumber: chargingStation.getBootNotificationRequest().meterSerialNumber,
1020 meterType: chargingStation.getBootNotificationRequest().meterType,
1021 },
1022 { skipBufferingOnError: true, triggerMessage: true }
1023 )
1024 .then((value) => {
1025 chargingStation.bootNotificationResponse = value;
1026 })
1027 .catch(() => {
1028 /* This is intentional */
1029 });
1030 }, Constants.OCPP_TRIGGER_MESSAGE_DELAY);
1031 return Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED;
1032 case MessageTrigger.Heartbeat:
1033 setTimeout(() => {
1034 chargingStation.ocppRequestService
1035 .requestHandler<OCPP16HeartbeatRequest, OCPP16HeartbeatResponse>(
1036 chargingStation,
1037 OCPP16RequestCommand.HEARTBEAT,
1038 null,
1039 {
1040 triggerMessage: true,
1041 }
1042 )
1043 .catch(() => {
1044 /* This is intentional */
1045 });
1046 }, Constants.OCPP_TRIGGER_MESSAGE_DELAY);
1047 return Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED;
1048 case MessageTrigger.StatusNotification:
1049 setTimeout(() => {
1050 if (commandPayload?.connectorId) {
1051 chargingStation.ocppRequestService
1052 .requestHandler<OCPP16StatusNotificationRequest, OCPP16StatusNotificationResponse>(
1053 chargingStation,
1054 OCPP16RequestCommand.STATUS_NOTIFICATION,
1055 {
1056 connectorId: commandPayload.connectorId,
1057 errorCode: OCPP16ChargePointErrorCode.NO_ERROR,
1058 status: chargingStation.getConnectorStatus(commandPayload.connectorId).status,
1059 },
1060 {
1061 triggerMessage: true,
1062 }
1063 )
1064 .catch(() => {
1065 /* This is intentional */
1066 });
1067 } else {
1068 for (const connectorId of chargingStation.connectors.keys()) {
1069 chargingStation.ocppRequestService
1070 .requestHandler<
1071 OCPP16StatusNotificationRequest,
1072 OCPP16StatusNotificationResponse
1073 >(
1074 chargingStation,
1075 OCPP16RequestCommand.STATUS_NOTIFICATION,
1076 {
1077 connectorId,
1078 errorCode: OCPP16ChargePointErrorCode.NO_ERROR,
1079 status: chargingStation.getConnectorStatus(connectorId).status,
1080 },
1081 {
1082 triggerMessage: true,
1083 }
1084 )
1085 .catch(() => {
1086 /* This is intentional */
1087 });
1088 }
1089 }
1090 }, Constants.OCPP_TRIGGER_MESSAGE_DELAY);
1091 return Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED;
1092 default:
1093 return Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED;
1094 }
1095 } catch (error) {
1096 return this.handleIncomingRequestError(
1097 chargingStation,
1098 OCPP16IncomingRequestCommand.TRIGGER_MESSAGE,
1099 error as Error,
1100 { errorResponse: Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED }
1101 );
1102 }
1103 }
1104 }