1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { AuthorizeRequest
, OCPP16AuthorizationStatus
, OCPP16AuthorizeResponse
, OCPP16StartTransactionResponse
, OCPP16StopTransactionResponse
, StartTransactionRequest
, StopTransactionRequest
} from
'../../../types/ocpp/1.6/Transaction';
4 import { HeartbeatRequest
, OCPP16RequestCommand
, StatusNotificationRequest
} from
'../../../types/ocpp/1.6/Requests';
5 import { HeartbeatResponse
, OCPP16BootNotificationResponse
, OCPP16RegistrationStatus
, StatusNotificationResponse
} from
'../../../types/ocpp/1.6/Responses';
6 import { MeterValuesRequest
, MeterValuesResponse
} from
'../../../types/ocpp/1.6/MeterValues';
8 import type ChargingStation from
'../../ChargingStation';
9 import { ErrorType
} from
'../../../types/ocpp/ErrorType';
10 import { JsonType
} from
'../../../types/JsonType';
11 import { OCPP16ChargePointStatus
} from
'../../../types/ocpp/1.6/ChargePointStatus';
12 import { OCPP16ServiceUtils
} from
'./OCPP16ServiceUtils';
13 import { OCPP16StandardParametersKey
} from
'../../../types/ocpp/1.6/Configuration';
14 import OCPPError from
'../../../exception/OCPPError';
15 import OCPPResponseService from
'../OCPPResponseService';
16 import { ResponseHandler
} from
'../../../types/ocpp/Responses';
17 import Utils from
'../../../utils/Utils';
18 import logger from
'../../../utils/Logger';
20 export default class OCPP16ResponseService
extends OCPPResponseService
{
21 private responseHandlers
: Map
<OCPP16RequestCommand
, ResponseHandler
>;
23 public constructor(chargingStation
: ChargingStation
) {
24 if (new.target
?.name
=== 'OCPP16ResponseService') {
25 throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
27 super(chargingStation
);
28 this.responseHandlers
= new Map
<OCPP16RequestCommand
, ResponseHandler
>([
29 [OCPP16RequestCommand
.BOOT_NOTIFICATION
, this.handleResponseBootNotification
.bind(this)],
30 [OCPP16RequestCommand
.HEARTBEAT
, this.handleResponseHeartbeat
.bind(this)],
31 [OCPP16RequestCommand
.AUTHORIZE
, this.handleResponseAuthorize
.bind(this)],
32 [OCPP16RequestCommand
.START_TRANSACTION
, this.handleResponseStartTransaction
.bind(this)],
33 [OCPP16RequestCommand
.STOP_TRANSACTION
, this.handleResponseStopTransaction
.bind(this)],
34 [OCPP16RequestCommand
.STATUS_NOTIFICATION
, this.handleResponseStatusNotification
.bind(this)],
35 [OCPP16RequestCommand
.METER_VALUES
, this.handleResponseMeterValues
.bind(this)]
39 public async handleResponse(commandName
: OCPP16RequestCommand
, payload
: JsonType
| string, requestPayload
: JsonType
): Promise
<void> {
40 if (this.chargingStation
.isRegistered() || commandName
=== OCPP16RequestCommand
.BOOT_NOTIFICATION
) {
41 if (this.responseHandlers
.has(commandName
)) {
43 await this.responseHandlers
.get(commandName
)(payload
, requestPayload
);
45 logger
.error(this.chargingStation
.logPrefix() + ' Handle request response error: %j', error
);
50 throw new OCPPError(ErrorType
.NOT_IMPLEMENTED
, `${commandName} is not implemented to handle request response payload ${JSON.stringify(payload, null, 2)}`, commandName
);
53 throw new OCPPError(ErrorType
.SECURITY_ERROR
, `${commandName} cannot be issued to handle request response payload ${JSON.stringify(payload, null, 2)} while the charging station is not registered on the central server. `, commandName
);
57 private handleResponseBootNotification(payload
: OCPP16BootNotificationResponse
): void {
58 if (payload
.status === OCPP16RegistrationStatus
.ACCEPTED
) {
59 this.chargingStation
.addConfigurationKey(OCPP16StandardParametersKey
.HeartBeatInterval
, payload
.interval
.toString());
60 this.chargingStation
.addConfigurationKey(OCPP16StandardParametersKey
.HeartbeatInterval
, payload
.interval
.toString(), { visible
: false });
61 this.chargingStation
.heartbeatSetInterval
? this.chargingStation
.restartHeartbeat() : this.chargingStation
.startHeartbeat();
63 if (Object.values(OCPP16RegistrationStatus
).includes(payload
.status)) {
64 const logMsg
= `${this.chargingStation.logPrefix()} Charging station in '${payload.status}' state on the central server`;
65 payload
.status === OCPP16RegistrationStatus
.REJECTED
? logger
.warn(logMsg
) : logger
.info(logMsg
);
67 logger
.error(this.chargingStation
.logPrefix() + ' Charging station boot notification response received: %j with undefined registration status', payload
);
71 private handleResponseHeartbeat(payload
: HeartbeatResponse
, requestPayload
: HeartbeatRequest
): void {
72 logger
.debug(this.chargingStation
.logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
75 private handleResponseAuthorize(payload
: OCPP16AuthorizeResponse
, requestPayload
: AuthorizeRequest
): void {
76 let authorizeConnectorId
: number;
77 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
78 if (connectorId
> 0 && this.chargingStation
.getConnectorStatus(connectorId
)?.authorizeIdTag
=== requestPayload
.idTag
) {
79 authorizeConnectorId
= connectorId
;
83 if (payload
.idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
84 this.chargingStation
.getConnectorStatus(authorizeConnectorId
).idTagAuthorized
= true;
85 logger
.debug(`${this.chargingStation.logPrefix()} IdTag ${requestPayload.idTag} authorized on connector ${authorizeConnectorId}`);
87 this.chargingStation
.getConnectorStatus(authorizeConnectorId
).idTagAuthorized
= false;
88 delete this.chargingStation
.getConnectorStatus(authorizeConnectorId
).authorizeIdTag
;
89 logger
.debug(`${this.chargingStation.logPrefix()} IdTag ${requestPayload.idTag} refused with status ${payload.idTagInfo.status} on connector ${authorizeConnectorId}`);
93 private async handleResponseStartTransaction(payload
: OCPP16StartTransactionResponse
, requestPayload
: StartTransactionRequest
): Promise
<void> {
94 const connectorId
= requestPayload
.connectorId
;
96 let transactionConnectorId
: number;
97 for (const id
of this.chargingStation
.connectors
.keys()) {
98 if (id
> 0 && id
=== connectorId
) {
99 transactionConnectorId
= id
;
103 if (!transactionConnectorId
) {
104 logger
.error(this.chargingStation
.logPrefix() + ' Trying to start a transaction on a non existing connector Id ' + connectorId
.toString());
107 if (this.chargingStation
.getConnectorStatus(connectorId
).transactionRemoteStarted
&& this.chargingStation
.getAuthorizeRemoteTxRequests()
108 && this.chargingStation
.getLocalAuthListEnabled() && this.chargingStation
.hasAuthorizedTags() && !this.chargingStation
.getConnectorStatus(connectorId
).idTagLocalAuthorized
) {
109 logger
.error(this.chargingStation
.logPrefix() + ' Trying to start a transaction with a not local authorized idTag ' + this.chargingStation
.getConnectorStatus(connectorId
).localAuthorizeIdTag
+ ' on connector Id ' + connectorId
.toString());
110 await this.resetConnectorOnStartTransactionError(connectorId
);
113 if (this.chargingStation
.getConnectorStatus(connectorId
).transactionRemoteStarted
&& this.chargingStation
.getAuthorizeRemoteTxRequests()
114 && this.chargingStation
.getMayAuthorizeAtRemoteStart() && !this.chargingStation
.getConnectorStatus(connectorId
).idTagLocalAuthorized
115 && !this.chargingStation
.getConnectorStatus(connectorId
).idTagAuthorized
) {
116 logger
.error(this.chargingStation
.logPrefix() + ' Trying to start a transaction with a not authorized idTag ' + this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
+ ' on connector Id ' + connectorId
.toString());
117 await this.resetConnectorOnStartTransactionError(connectorId
);
120 if (this.chargingStation
.getConnectorStatus(connectorId
).idTagAuthorized
&& this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
!== requestPayload
.idTag
) {
121 logger
.error(this.chargingStation
.logPrefix() + ' Trying to start a transaction with an idTag ' + requestPayload
.idTag
+ ' different from the authorize request one ' + this.chargingStation
.getConnectorStatus(connectorId
).authorizeIdTag
+ ' on connector Id ' + connectorId
.toString());
122 await this.resetConnectorOnStartTransactionError(connectorId
);
125 if (this.chargingStation
.getConnectorStatus(connectorId
).idTagLocalAuthorized
126 && this.chargingStation
.getConnectorStatus(connectorId
).localAuthorizeIdTag
!== requestPayload
.idTag
) {
127 logger
.error(this.chargingStation
.logPrefix() + ' Trying to start a transaction with an idTag ' + requestPayload
.idTag
+ ' different from the local authorized one ' + this.chargingStation
.getConnectorStatus(connectorId
).localAuthorizeIdTag
+ ' on connector Id ' + connectorId
.toString());
128 await this.resetConnectorOnStartTransactionError(connectorId
);
131 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
132 logger
.debug(this.chargingStation
.logPrefix() + ' Trying to start a transaction on an already used connector ' + connectorId
.toString() + ': %j', this.chargingStation
.getConnectorStatus(connectorId
));
135 if (this.chargingStation
.getConnectorStatus(connectorId
)?.status !== OCPP16ChargePointStatus
.AVAILABLE
136 && this.chargingStation
.getConnectorStatus(connectorId
)?.status !== OCPP16ChargePointStatus
.PREPARING
) {
137 logger
.error(`${this.chargingStation.logPrefix()} Trying to start a transaction on connector ${connectorId.toString()} with status ${this.chargingStation.getConnectorStatus(connectorId)?.status}`);
140 if (!Number.isInteger(payload
.transactionId
)) {
141 logger
.warn(`${this.chargingStation.logPrefix()} Trying to start a transaction on connector ${connectorId.toString()} with a non integer transaction Id ${payload.transactionId}, converting to integer`);
142 payload
.transactionId
= Utils
.convertToInt(payload
.transactionId
);
145 if (payload
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
146 this.chargingStation
.getConnectorStatus(connectorId
).transactionStarted
= true;
147 this.chargingStation
.getConnectorStatus(connectorId
).transactionId
= payload
.transactionId
;
148 this.chargingStation
.getConnectorStatus(connectorId
).transactionIdTag
= requestPayload
.idTag
;
149 this.chargingStation
.getConnectorStatus(connectorId
).transactionEnergyActiveImportRegisterValue
= 0;
150 this.chargingStation
.getConnectorStatus(connectorId
).transactionBeginMeterValue
= OCPP16ServiceUtils
.buildTransactionBeginMeterValue(this.chargingStation
, connectorId
,
151 requestPayload
.meterStart
);
152 this.chargingStation
.getBeginEndMeterValues() && await this.chargingStation
.ocppRequestService
.sendTransactionBeginMeterValues(connectorId
, payload
.transactionId
,
153 this.chargingStation
.getConnectorStatus(connectorId
).transactionBeginMeterValue
);
154 await this.chargingStation
.ocppRequestService
.sendStatusNotification(connectorId
, OCPP16ChargePointStatus
.CHARGING
);
155 this.chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.CHARGING
;
156 logger
.info(this.chargingStation
.logPrefix() + ' Transaction ' + payload
.transactionId
.toString() + ' STARTED on ' + this.chargingStation
.stationInfo
.chargingStationId
+ '#' + connectorId
.toString() + ' for idTag ' + requestPayload
.idTag
);
157 if (this.chargingStation
.stationInfo
.powerSharedByConnectors
) {
158 this.chargingStation
.stationInfo
.powerDivider
++;
160 const configuredMeterValueSampleInterval
= this.chargingStation
.getConfigurationKey(OCPP16StandardParametersKey
.MeterValueSampleInterval
);
161 this.chargingStation
.startMeterValues(connectorId
, configuredMeterValueSampleInterval
? Utils
.convertToInt(configuredMeterValueSampleInterval
.value
) * 1000 : 60000);
163 logger
.warn(this.chargingStation
.logPrefix() + ' Starting transaction id ' + payload
.transactionId
.toString() + ' REJECTED with status ' + payload
?.idTagInfo
?.status + ', idTag ' + requestPayload
.idTag
);
164 await this.resetConnectorOnStartTransactionError(connectorId
);
168 private async resetConnectorOnStartTransactionError(connectorId
: number): Promise
<void> {
169 this.chargingStation
.resetConnectorStatus(connectorId
);
170 if (this.chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
) {
171 await this.chargingStation
.ocppRequestService
.sendStatusNotification(connectorId
, OCPP16ChargePointStatus
.AVAILABLE
);
172 this.chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
176 private async handleResponseStopTransaction(payload
: OCPP16StopTransactionResponse
, requestPayload
: StopTransactionRequest
): Promise
<void> {
177 let transactionConnectorId
: number;
178 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
179 if (connectorId
> 0 && this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== requestPayload
.transactionId
) {
180 transactionConnectorId
= connectorId
;
184 if (!transactionConnectorId
) {
185 logger
.error(this.chargingStation
.logPrefix() + ' Trying to stop a non existing transaction ' + requestPayload
.transactionId
.toString());
188 if (payload
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
189 (this.chargingStation
.getBeginEndMeterValues() && !this.chargingStation
.getOcppStrictCompliance() && this.chargingStation
.getOutOfOrderEndMeterValues())
190 && await this.chargingStation
.ocppRequestService
.sendTransactionEndMeterValues(transactionConnectorId
, requestPayload
.transactionId
,
191 OCPP16ServiceUtils
.buildTransactionEndMeterValue(this.chargingStation
, transactionConnectorId
, requestPayload
.meterStop
));
192 if (!this.chargingStation
.isChargingStationAvailable() || !this.chargingStation
.isConnectorAvailable(transactionConnectorId
)) {
193 await this.chargingStation
.ocppRequestService
.sendStatusNotification(transactionConnectorId
, OCPP16ChargePointStatus
.UNAVAILABLE
);
194 this.chargingStation
.getConnectorStatus(transactionConnectorId
).status = OCPP16ChargePointStatus
.UNAVAILABLE
;
196 await this.chargingStation
.ocppRequestService
.sendStatusNotification(transactionConnectorId
, OCPP16ChargePointStatus
.AVAILABLE
);
197 this.chargingStation
.getConnectorStatus(transactionConnectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
199 if (this.chargingStation
.stationInfo
.powerSharedByConnectors
) {
200 this.chargingStation
.stationInfo
.powerDivider
--;
202 logger
.info(this.chargingStation
.logPrefix() + ' Transaction ' + requestPayload
.transactionId
.toString() + ' STOPPED on ' + this.chargingStation
.stationInfo
.chargingStationId
+ '#' + transactionConnectorId
.toString());
203 this.chargingStation
.resetConnectorStatus(transactionConnectorId
);
205 logger
.warn(this.chargingStation
.logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
.toString() + ' REJECTED with status ' + payload
.idTagInfo
?.status);
209 private handleResponseStatusNotification(payload
: StatusNotificationRequest
, requestPayload
: StatusNotificationResponse
): void {
210 logger
.debug(this.chargingStation
.logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
213 private handleResponseMeterValues(payload
: MeterValuesRequest
, requestPayload
: MeterValuesResponse
): void {
214 logger
.debug(this.chargingStation
.logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);