1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
4 ChangeAvailabilityRequest
,
5 ChangeConfigurationRequest
,
6 ClearChargingProfileRequest
,
7 DiagnosticsStatusNotificationRequest
,
8 GetConfigurationRequest
,
11 OCPP16AvailabilityType
,
12 OCPP16BootNotificationRequest
,
13 OCPP16HeartbeatRequest
,
14 OCPP16IncomingRequestCommand
,
16 OCPP16StatusNotificationRequest
,
17 OCPP16TriggerMessageRequest
,
18 RemoteStartTransactionRequest
,
19 RemoteStopTransactionRequest
,
21 SetChargingProfileRequest
,
22 UnlockConnectorRequest
,
23 } from
'../../../types/ocpp/1.6/Requests';
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';
39 ChargingProfilePurposeType
,
40 OCPP16ChargingProfile
,
41 } from
'../../../types/ocpp/1.6/ChargingProfile';
42 import { Client
, FTPResponse
} from
'basic-ftp';
44 OCPP16AuthorizationStatus
,
45 OCPP16AuthorizeRequest
,
46 OCPP16AuthorizeResponse
,
47 OCPP16StartTransactionRequest
,
48 OCPP16StartTransactionResponse
,
49 OCPP16StopTransactionReason
,
50 OCPP16StopTransactionRequest
,
51 OCPP16StopTransactionResponse
,
52 } from
'../../../types/ocpp/1.6/Transaction';
54 OCPP16MeterValuesRequest
,
55 OCPP16MeterValuesResponse
,
56 } from
'../../../types/ocpp/1.6/MeterValues';
58 OCPP16StandardParametersKey
,
59 OCPP16SupportedFeatureProfiles
,
60 } from
'../../../types/ocpp/1.6/Configuration';
61 import { URL
, fileURLToPath
} from
'url';
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';
79 import logger from
'../../../utils/Logger';
80 import path from
'path';
81 import tar from
'tar';
83 const moduleName
= 'OCPP16IncomingRequestService';
85 export default class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
86 private incomingRequestHandlers
: Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>;
88 public constructor() {
89 if (new.target
?.name
=== moduleName
) {
90 throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
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)],
98 OCPP16IncomingRequestCommand
.GET_CONFIGURATION
,
99 this.handleRequestGetConfiguration
.bind(this),
102 OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
,
103 this.handleRequestChangeConfiguration
.bind(this),
106 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
,
107 this.handleRequestSetChargingProfile
.bind(this),
110 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
,
111 this.handleRequestClearChargingProfile
.bind(this),
114 OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
,
115 this.handleRequestChangeAvailability
.bind(this),
118 OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
,
119 this.handleRequestRemoteStartTransaction
.bind(this),
122 OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
,
123 this.handleRequestRemoteStopTransaction
.bind(this),
125 [OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
, this.handleRequestGetDiagnostics
.bind(this)],
126 [OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
, this.handleRequestTriggerMessage
.bind(this)],
130 public async incomingRequestHandler(
131 chargingStation
: ChargingStation
,
133 commandName
: OCPP16IncomingRequestCommand
,
134 commandPayload
: JsonType
136 let response
: JsonType
;
138 chargingStation
.getOcppStrictCompliance() &&
139 chargingStation
.isInPendingState() &&
140 (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
||
141 commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
)
144 ErrorType
.SECURITY_ERROR
,
145 `${commandName} cannot be issued to handle request payload ${JSON.stringify(
149 )} while the charging station is in pending state on the central server`,
154 chargingStation
.isRegistered() ||
155 (!chargingStation
.getOcppStrictCompliance() && chargingStation
.isInUnknownState())
157 if (this.incomingRequestHandlers
.has(commandName
)) {
159 // Call the method to build the response
160 response
= await this.incomingRequestHandlers
.get(commandName
)(
166 logger
.error(chargingStation
.logPrefix() + ' Handle request error: %j', error
);
172 ErrorType
.NOT_IMPLEMENTED
,
173 `${commandName} is not implemented to handle request payload ${JSON.stringify(
183 ErrorType
.SECURITY_ERROR
,
184 `${commandName} cannot be issued to handle request payload ${JSON.stringify(
188 )} while the charging station is not registered on the central server.`,
192 // Send the built response
193 await chargingStation
.ocppRequestService
.sendResponse(
201 // Simulate charging station restart
202 private handleRequestReset(
203 chargingStation
: ChargingStation
,
204 commandPayload
: ResetRequest
206 // eslint-disable-next-line @typescript-eslint/no-misused-promises
207 setImmediate(async (): Promise
<void> => {
208 await chargingStation
.reset((commandPayload
.type + 'Reset') as OCPP16StopTransactionReason
);
211 `${chargingStation.logPrefix()} ${
213 } reset command received, simulating it. The station will be back online in ${Utils.formatDurationMilliSeconds(
214 chargingStation.stationInfo.resetTime
217 return Constants
.OCPP_RESPONSE_ACCEPTED
;
220 private handleRequestClearCache(): DefaultResponse
{
221 return Constants
.OCPP_RESPONSE_ACCEPTED
;
224 private async handleRequestUnlockConnector(
225 chargingStation
: ChargingStation
,
226 commandPayload
: UnlockConnectorRequest
227 ): Promise
<UnlockConnectorResponse
> {
228 const connectorId
= commandPayload
.connectorId
;
229 if (connectorId
=== 0) {
231 chargingStation
.logPrefix() + ' Trying to unlock connector ' + connectorId
.toString()
233 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
235 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
236 const transactionId
= chargingStation
.getConnectorStatus(connectorId
).transactionId
;
238 chargingStation
.getBeginEndMeterValues() &&
239 chargingStation
.getOcppStrictCompliance() &&
240 !chargingStation
.getOutOfOrderEndMeterValues()
242 // FIXME: Implement OCPP version agnostic helpers
243 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
246 chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
)
248 await chargingStation
.ocppRequestService
.requestHandler
<
249 OCPP16MeterValuesRequest
,
250 OCPP16MeterValuesResponse
251 >(chargingStation
, OCPP16RequestCommand
.METER_VALUES
, {
254 meterValue
: transactionEndMeterValue
,
257 const stopResponse
= await chargingStation
.ocppRequestService
.requestHandler
<
258 OCPP16StopTransactionRequest
,
259 OCPP16StopTransactionResponse
260 >(chargingStation
, OCPP16RequestCommand
.STOP_TRANSACTION
, {
262 meterStop
: chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
263 idTag
: chargingStation
.getTransactionIdTag(transactionId
),
264 reason
: OCPP16StopTransactionReason
.UNLOCK_COMMAND
,
266 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
267 return Constants
.OCPP_RESPONSE_UNLOCKED
;
269 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
271 await chargingStation
.ocppRequestService
.requestHandler
<
272 OCPP16StatusNotificationRequest
,
273 OCPP16StatusNotificationResponse
274 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
276 status: OCPP16ChargePointStatus
.AVAILABLE
,
277 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
279 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
280 return Constants
.OCPP_RESPONSE_UNLOCKED
;
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;
294 if (!configuration
.visible
) {
297 configurationKey
.push({
298 key
: configuration
.key
,
299 readonly: configuration
.readonly,
300 value
: configuration
.value
,
304 for (const key
of commandPayload
.key
) {
305 const keyFound
= ChargingStationConfigurationUtils
.getConfigurationKey(
310 if (Utils
.isUndefined(keyFound
.visible
)) {
311 keyFound
.visible
= true;
313 if (!keyFound
.visible
) {
316 configurationKey
.push({
318 readonly: keyFound
.readonly,
319 value
: keyFound
.value
,
322 unknownKey
.push(key
);
332 private handleRequestChangeConfiguration(
333 chargingStation
: ChargingStation
,
334 commandPayload
: ChangeConfigurationRequest
335 ): ChangeConfigurationResponse
{
336 // JSON request fields type sanity check
337 if (!Utils
.isString(commandPayload
.key
)) {
339 `${chargingStation.logPrefix()} ${
340 OCPP16IncomingRequestCommand.CHANGE_CONFIGURATION
341 } request key field is not a string:`,
345 if (!Utils
.isString(commandPayload
.value
)) {
347 `${chargingStation.logPrefix()} ${
348 OCPP16IncomingRequestCommand.CHANGE_CONFIGURATION
349 } request value field is not a string:`,
353 const keyToChange
= ChargingStationConfigurationUtils
.getConfigurationKey(
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(
368 commandPayload
.value
,
373 let triggerHeartbeatRestart
= false;
374 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
375 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
377 OCPP16StandardParametersKey
.HeartbeatInterval
,
380 triggerHeartbeatRestart
= true;
382 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
383 ChargingStationConfigurationUtils
.setConfigurationKeyValue(
385 OCPP16StandardParametersKey
.HeartBeatInterval
,
388 triggerHeartbeatRestart
= true;
390 if (triggerHeartbeatRestart
) {
391 chargingStation
.restartHeartbeat();
393 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
394 chargingStation
.restartWebSocketPing();
396 if (keyToChange
.reboot
) {
397 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
399 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
403 private handleRequestSetChargingProfile(
404 chargingStation
: ChargingStation
,
405 commandPayload
: SetChargingProfileRequest
406 ): SetChargingProfileResponse
{
408 !OCPP16ServiceUtils
.checkFeatureProfile(
410 OCPP16SupportedFeatureProfiles
.SmartCharging
,
411 OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
414 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED
;
416 if (!chargingStation
.getConnectorStatus(commandPayload
.connectorId
)) {
418 `${chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${
419 commandPayload.connectorId
422 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
425 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
426 ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&&
427 commandPayload
.connectorId
!== 0
429 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
432 commandPayload
.csChargingProfiles
.chargingProfilePurpose
===
433 ChargingProfilePurposeType
.TX_PROFILE
&&
434 (commandPayload
.connectorId
=== 0 ||
435 !chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
)
437 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
439 chargingStation
.setChargingProfile(
440 commandPayload
.connectorId
,
441 commandPayload
.csChargingProfiles
444 `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${
445 commandPayload.connectorId
446 }, dump their stack: %j`,
447 chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
449 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
452 private handleRequestClearChargingProfile(
453 chargingStation
: ChargingStation
,
454 commandPayload
: ClearChargingProfileRequest
455 ): ClearChargingProfileResponse
{
457 !OCPP16ServiceUtils
.checkFeatureProfile(
459 OCPP16SupportedFeatureProfiles
.SmartCharging
,
460 OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
463 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
465 const connectorStatus
= chargingStation
.getConnectorStatus(commandPayload
.connectorId
);
466 if (!connectorStatus
) {
468 `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${
469 commandPayload.connectorId
472 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
474 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(connectorStatus
.chargingProfiles
)) {
475 connectorStatus
.chargingProfiles
= [];
477 `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${
478 commandPayload.connectorId
479 }, dump their stack: %j`,
480 connectorStatus
.chargingProfiles
482 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
484 if (!commandPayload
.connectorId
) {
485 let clearedCP
= false;
486 for (const connectorId
of chargingStation
.connectors
.keys()) {
487 if (!Utils
.isEmptyArray(chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
)) {
489 .getConnectorStatus(connectorId
)
490 .chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
491 let clearCurrentCP
= false;
492 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
493 clearCurrentCP
= true;
496 !commandPayload
.chargingProfilePurpose
&&
497 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
499 clearCurrentCP
= true;
502 !chargingProfile
.stackLevel
&&
503 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
505 clearCurrentCP
= true;
508 chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&&
509 chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
511 clearCurrentCP
= true;
513 if (clearCurrentCP
) {
514 connectorStatus
.chargingProfiles
.splice(index
, 1);
516 `${chargingStation.logPrefix()} Matching charging profile(s) cleared on connector id ${
517 commandPayload.connectorId
518 }, dump their stack: %j`,
519 connectorStatus
.chargingProfiles
527 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
530 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
533 private async handleRequestChangeAvailability(
534 chargingStation
: ChargingStation
,
535 commandPayload
: ChangeAvailabilityRequest
536 ): Promise
<ChangeAvailabilityResponse
> {
537 const connectorId
: number = commandPayload
.connectorId
;
538 if (!chargingStation
.getConnectorStatus(connectorId
)) {
540 `${chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`
542 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
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
;
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
, {
561 status: chargePointStatus
,
562 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
564 chargingStation
.getConnectorStatus(id
).status = chargePointStatus
;
570 (chargingStation
.getConnectorStatus(0).availability
=== OCPP16AvailabilityType
.OPERATIVE
||
571 (chargingStation
.getConnectorStatus(0).availability
===
572 OCPP16AvailabilityType
.INOPERATIVE
&&
573 commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))
575 if (chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
576 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
577 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
579 chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
580 await chargingStation
.ocppRequestService
.requestHandler
<
581 OCPP16StatusNotificationRequest
,
582 OCPP16StatusNotificationResponse
583 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
585 status: chargePointStatus
,
586 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
588 chargingStation
.getConnectorStatus(connectorId
).status = chargePointStatus
;
589 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
591 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
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
,
609 connectorStatus
.status = OCPP16ChargePointStatus
.PREPARING
;
610 if (chargingStation
.isChargingStationAvailable() && connectorStatus
) {
611 // Check if authorized
612 if (chargingStation
.getAuthorizeRemoteTxRequests()) {
613 let authorized
= false;
615 chargingStation
.getLocalAuthListEnabled() &&
616 chargingStation
.hasAuthorizedTags() &&
617 chargingStation
.authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)
619 connectorStatus
.localAuthorizeIdTag
= commandPayload
.idTag
;
620 connectorStatus
.idTagLocalAuthorized
= 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
,
631 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
636 `${chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`
640 // Authorization successful, start transaction
642 this.setRemoteStartTransactionChargingProfile(
644 transactionConnectorId
,
645 commandPayload
.chargingProfile
648 connectorStatus
.transactionRemoteStarted
= true;
651 await chargingStation
.ocppRequestService
.requestHandler
<
652 OCPP16StartTransactionRequest
,
653 OCPP16StartTransactionResponse
654 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
655 connectorId
: transactionConnectorId
,
656 idTag
: commandPayload
.idTag
,
658 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
661 chargingStation
.logPrefix() +
662 ' Transaction remotely STARTED on ' +
663 chargingStation
.stationInfo
.chargingStationId
+
665 transactionConnectorId
.toString() +
669 return Constants
.OCPP_RESPONSE_ACCEPTED
;
671 return this.notifyRemoteStartTransactionRejected(
673 transactionConnectorId
,
677 return this.notifyRemoteStartTransactionRejected(
679 transactionConnectorId
,
683 return this.notifyRemoteStartTransactionRejected(
685 transactionConnectorId
,
689 // No authorization check required, start transaction
691 this.setRemoteStartTransactionChargingProfile(
693 transactionConnectorId
,
694 commandPayload
.chargingProfile
697 connectorStatus
.transactionRemoteStarted
= true;
700 await chargingStation
.ocppRequestService
.requestHandler
<
701 OCPP16StartTransactionRequest
,
702 OCPP16StartTransactionResponse
703 >(chargingStation
, OCPP16RequestCommand
.START_TRANSACTION
, {
704 connectorId
: transactionConnectorId
,
705 idTag
: commandPayload
.idTag
,
707 ).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
710 chargingStation
.logPrefix() +
711 ' Transaction remotely STARTED on ' +
712 chargingStation
.stationInfo
.chargingStationId
+
714 transactionConnectorId
.toString() +
718 return Constants
.OCPP_RESPONSE_ACCEPTED
;
720 return this.notifyRemoteStartTransactionRejected(
722 transactionConnectorId
,
726 return this.notifyRemoteStartTransactionRejected(
728 transactionConnectorId
,
732 return this.notifyRemoteStartTransactionRejected(
734 transactionConnectorId
,
738 return this.notifyRemoteStartTransactionRejected(
740 transactionConnectorId
,
745 private async notifyRemoteStartTransactionRejected(
746 chargingStation
: ChargingStation
,
749 ): Promise
<DefaultResponse
> {
751 chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
753 await chargingStation
.ocppRequestService
.requestHandler
<
754 OCPP16StatusNotificationRequest
,
755 OCPP16StatusNotificationResponse
756 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
758 status: OCPP16ChargePointStatus
.AVAILABLE
,
759 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
761 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
764 chargingStation
.logPrefix() +
765 ' Remote starting transaction REJECTED on connector Id ' +
766 connectorId
.toString() +
770 chargingStation
.getConnectorStatus(connectorId
).availability
+
772 chargingStation
.getConnectorStatus(connectorId
).status
774 return Constants
.OCPP_RESPONSE_REJECTED
;
777 private setRemoteStartTransactionChargingProfile(
778 chargingStation
: ChargingStation
,
780 cp
: OCPP16ChargingProfile
782 if (cp
&& cp
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
783 chargingStation
.setChargingProfile(connectorId
, cp
);
785 `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}, dump their stack: %j`,
786 chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
789 } else if (cp
&& cp
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
791 `${chargingStation.logPrefix()} Not allowed to set ${
792 cp.chargingProfilePurpose
793 } charging profile(s) at remote start transaction`
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()) {
809 chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
811 await chargingStation
.ocppRequestService
.requestHandler
<
812 OCPP16StatusNotificationRequest
,
813 OCPP16StatusNotificationResponse
814 >(chargingStation
, OCPP16RequestCommand
.STATUS_NOTIFICATION
, {
816 status: OCPP16ChargePointStatus
.FINISHING
,
817 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
819 chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.FINISHING
;
821 chargingStation
.getBeginEndMeterValues() &&
822 chargingStation
.getOcppStrictCompliance() &&
823 !chargingStation
.getOutOfOrderEndMeterValues()
825 // FIXME: Implement OCPP version agnostic helpers
826 const transactionEndMeterValue
= OCPP16ServiceUtils
.buildTransactionEndMeterValue(
829 chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
)
831 await chargingStation
.ocppRequestService
.requestHandler
<
832 OCPP16MeterValuesRequest
,
833 OCPP16MeterValuesResponse
834 >(chargingStation
, OCPP16RequestCommand
.METER_VALUES
, {
837 meterValue
: transactionEndMeterValue
,
840 await chargingStation
.ocppRequestService
.requestHandler
<
841 OCPP16StopTransactionRequest
,
842 OCPP16StopTransactionResponse
843 >(chargingStation
, OCPP16RequestCommand
.STOP_TRANSACTION
, {
845 meterStop
: chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
846 idTag
: chargingStation
.getTransactionIdTag(transactionId
),
848 return Constants
.OCPP_RESPONSE_ACCEPTED
;
852 chargingStation
.logPrefix() +
853 ' Trying to remote stop a non existing transaction ' +
854 transactionId
.toString()
856 return Constants
.OCPP_RESPONSE_REJECTED
;
859 private async handleRequestGetDiagnostics(
860 chargingStation
: ChargingStation
,
861 commandPayload
: GetDiagnosticsRequest
862 ): Promise
<GetDiagnosticsResponse
> {
864 !OCPP16ServiceUtils
.checkFeatureProfile(
866 OCPP16SupportedFeatureProfiles
.FirmwareManagement
,
867 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
870 return Constants
.OCPP_RESPONSE_EMPTY
;
873 chargingStation
.logPrefix() +
875 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
+
876 ' request received: %j',
879 const uri
= new URL(commandPayload
.location
);
880 if (uri
.protocol
.startsWith('ftp:')) {
881 let ftpClient
: Client
;
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({
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
}),
896 let uploadResponse
: FTPResponse
;
897 if (accessResponse
.code
=== 220) {
898 // eslint-disable-next-line @typescript-eslint/no-misused-promises
899 ftpClient
.trackProgress(async (info
) => {
901 `${chargingStation.logPrefix()} ${
903 } bytes transferred from diagnostics archive ${info.name}`
905 await chargingStation
.ocppRequestService
.requestHandler
<
906 DiagnosticsStatusNotificationRequest
,
907 DiagnosticsStatusNotificationResponse
908 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
909 status: OCPP16DiagnosticsStatus
.Uploading
,
912 uploadResponse
= await ftpClient
.uploadFrom(
914 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../../../../'),
917 uri
.pathname
+ diagnosticsArchive
919 if (uploadResponse
.code
=== 226) {
920 await chargingStation
.ocppRequestService
.requestHandler
<
921 DiagnosticsStatusNotificationRequest
,
922 DiagnosticsStatusNotificationResponse
923 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
924 status: OCPP16DiagnosticsStatus
.Uploaded
,
929 return { fileName
: diagnosticsArchive
};
932 ErrorType
.GENERIC_ERROR
,
933 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
934 uploadResponse?.code && '|' + uploadResponse?.code.toString()
936 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
940 ErrorType
.GENERIC_ERROR
,
941 `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
942 uploadResponse?.code && '|' + uploadResponse?.code.toString()
944 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
947 await chargingStation
.ocppRequestService
.requestHandler
<
948 DiagnosticsStatusNotificationRequest
,
949 DiagnosticsStatusNotificationResponse
950 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
951 status: OCPP16DiagnosticsStatus
.UploadFailed
,
956 return this.handleIncomingRequestError(
958 OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
,
960 { errorResponse
: Constants
.OCPP_RESPONSE_EMPTY
}
965 `${chargingStation.logPrefix()} Unsupported protocol ${
967 } to transfer the diagnostic logs archive`
969 await chargingStation
.ocppRequestService
.requestHandler
<
970 DiagnosticsStatusNotificationRequest
,
971 DiagnosticsStatusNotificationResponse
972 >(chargingStation
, OCPP16RequestCommand
.DIAGNOSTICS_STATUS_NOTIFICATION
, {
973 status: OCPP16DiagnosticsStatus
.UploadFailed
,
975 return Constants
.OCPP_RESPONSE_EMPTY
;
979 private handleRequestTriggerMessage(
980 chargingStation
: ChargingStation
,
981 commandPayload
: OCPP16TriggerMessageRequest
982 ): OCPP16TriggerMessageResponse
{
984 !OCPP16ServiceUtils
.checkFeatureProfile(
986 OCPP16SupportedFeatureProfiles
.RemoteTrigger
,
987 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
990 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
992 // TODO: factor out the check on connector id
993 if (commandPayload
?.connectorId
< 0) {
995 `${chargingStation.logPrefix()} ${
996 OCPP16IncomingRequestCommand.TRIGGER_MESSAGE
997 } incoming request received with invalid connectorId ${commandPayload.connectorId}`
999 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
;
1002 switch (commandPayload
.requestedMessage
) {
1003 case MessageTrigger
.BootNotification
:
1005 chargingStation
.ocppRequestService
1006 .requestHandler
<OCPP16BootNotificationRequest
, OCPP16BootNotificationResponse
>(
1008 OCPP16RequestCommand
.BOOT_NOTIFICATION
,
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
,
1022 { skipBufferingOnError
: true, triggerMessage
: true }
1025 chargingStation
.bootNotificationResponse
= value
;
1028 /* This is intentional */
1030 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1031 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1032 case MessageTrigger
.Heartbeat
:
1034 chargingStation
.ocppRequestService
1035 .requestHandler
<OCPP16HeartbeatRequest
, OCPP16HeartbeatResponse
>(
1037 OCPP16RequestCommand
.HEARTBEAT
,
1040 triggerMessage
: true,
1044 /* This is intentional */
1046 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1047 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1048 case MessageTrigger
.StatusNotification
:
1050 if (commandPayload
?.connectorId
) {
1051 chargingStation
.ocppRequestService
1052 .requestHandler
<OCPP16StatusNotificationRequest
, OCPP16StatusNotificationResponse
>(
1054 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1056 connectorId
: commandPayload
.connectorId
,
1057 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1058 status: chargingStation
.getConnectorStatus(commandPayload
.connectorId
).status,
1061 triggerMessage
: true,
1065 /* This is intentional */
1068 for (const connectorId
of chargingStation
.connectors
.keys()) {
1069 chargingStation
.ocppRequestService
1071 OCPP16StatusNotificationRequest
,
1072 OCPP16StatusNotificationResponse
1075 OCPP16RequestCommand
.STATUS_NOTIFICATION
,
1078 errorCode
: OCPP16ChargePointErrorCode
.NO_ERROR
,
1079 status: chargingStation
.getConnectorStatus(connectorId
).status,
1082 triggerMessage
: true,
1086 /* This is intentional */
1090 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
1091 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
1093 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
1096 return this.handleIncomingRequestError(
1098 OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
,
1100 { errorResponse
: Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
}