1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { ChangeAvailabilityRequest
, ChangeConfigurationRequest
, ClearChargingProfileRequest
, GetConfigurationRequest
, GetDiagnosticsRequest
, MessageTrigger
, OCPP16AvailabilityType
, OCPP16IncomingRequestCommand
, OCPP16RequestCommand
, OCPP16TriggerMessageRequest
, RemoteStartTransactionRequest
, RemoteStopTransactionRequest
, ResetRequest
, SetChargingProfileRequest
, UnlockConnectorRequest
} from
'../../../types/ocpp/1.6/Requests';
4 import { ChangeAvailabilityResponse
, ChangeConfigurationResponse
, ClearChargingProfileResponse
, GetConfigurationResponse
, GetDiagnosticsResponse
, OCPP16TriggerMessageResponse
, SetChargingProfileResponse
, UnlockConnectorResponse
} from
'../../../types/ocpp/1.6/Responses';
5 import { ChargingProfilePurposeType
, OCPP16ChargingProfile
} from
'../../../types/ocpp/1.6/ChargingProfile';
6 import { Client
, FTPResponse
} from
'basic-ftp';
7 import { OCPP16AuthorizationStatus
, OCPP16StopTransactionReason
} from
'../../../types/ocpp/1.6/Transaction';
9 import ChargingStation from
'../../ChargingStation';
10 import Constants from
'../../../utils/Constants';
11 import { DefaultResponse
} from
'../../../types/ocpp/Responses';
12 import { ErrorType
} from
'../../../types/ocpp/ErrorType';
13 import { IncomingRequestHandler
} from
'../../../types/ocpp/Requests';
14 import { MessageType
} from
'../../../types/ocpp/MessageType';
15 import { OCPP16ChargePointStatus
} from
'../../../types/ocpp/1.6/ChargePointStatus';
16 import { OCPP16DiagnosticsStatus
} from
'../../../types/ocpp/1.6/DiagnosticsStatus';
17 import { OCPP16StandardParametersKey
} from
'../../../types/ocpp/1.6/Configuration';
18 import { OCPPConfigurationKey
} from
'../../../types/ocpp/Configuration';
19 import OCPPError from
'../OCPPError';
20 import OCPPIncomingRequestService from
'../OCPPIncomingRequestService';
21 import { URL
} from
'url';
22 import Utils from
'../../../utils/Utils';
24 import logger from
'../../../utils/Logger';
25 import path from
'path';
26 import tar from
'tar';
28 export default class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
29 private incomingRequestHandlers
: Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>;
31 constructor(chargingStation
: ChargingStation
) {
32 super(chargingStation
);
33 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
34 [OCPP16IncomingRequestCommand
.RESET
, this.handleRequestReset
.bind(this)],
35 [OCPP16IncomingRequestCommand
.CLEAR_CACHE
, this.handleRequestClearCache
.bind(this)],
36 [OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
, this.handleRequestUnlockConnector
.bind(this)],
37 [OCPP16IncomingRequestCommand
.GET_CONFIGURATION
, this.handleRequestGetConfiguration
.bind(this)],
38 [OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
, this.handleRequestChangeConfiguration
.bind(this)],
39 [OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
, this.handleRequestSetChargingProfile
.bind(this)],
40 [OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
, this.handleRequestClearChargingProfile
.bind(this)],
41 [OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
, this.handleRequestChangeAvailability
.bind(this)],
42 [OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
, this.handleRequestRemoteStartTransaction
.bind(this)],
43 [OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
, this.handleRequestRemoteStopTransaction
.bind(this)],
44 [OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
, this.handleRequestGetDiagnostics
.bind(this)],
45 [OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
, this.handleRequestTriggerMessage
.bind(this)]
49 public async handleRequest(messageId
: string, commandName
: OCPP16IncomingRequestCommand
, commandPayload
: Record
<string, unknown
>): Promise
<void> {
50 let response
: Record
<string, unknown
>;
51 if (this.incomingRequestHandlers
.has(commandName
)) {
53 // Call the method to build the response
54 response
= await this.incomingRequestHandlers
.get(commandName
)(commandPayload
);
57 logger
.error(this.chargingStation
.logPrefix() + ' Handle request error: %j', error
);
62 throw new OCPPError(ErrorType
.NOT_IMPLEMENTED
, `${commandName} is not implemented to handle payload ${JSON.stringify(commandPayload, null, 2)}`, commandName
);
64 // Send the built response
65 await this.chargingStation
.ocppRequestService
.sendMessage(messageId
, response
, MessageType
.CALL_RESULT_MESSAGE
, commandName
);
68 // Simulate charging station restart
69 private handleRequestReset(commandPayload
: ResetRequest
): DefaultResponse
{
70 // eslint-disable-next-line @typescript-eslint/no-misused-promises
71 setImmediate(async (): Promise
<void> => {
72 await this.chargingStation
.stop(commandPayload
.type + 'Reset' as OCPP16StopTransactionReason
);
73 await Utils
.sleep(this.chargingStation
.stationInfo
.resetTime
);
74 this.chargingStation
.start();
76 logger
.info(`${this.chargingStation.logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${Utils.formatDurationMilliSeconds(this.chargingStation.stationInfo.resetTime)}`);
77 return Constants
.OCPP_RESPONSE_ACCEPTED
;
80 private handleRequestClearCache(): DefaultResponse
{
81 return Constants
.OCPP_RESPONSE_ACCEPTED
;
84 private async handleRequestUnlockConnector(commandPayload
: UnlockConnectorRequest
): Promise
<UnlockConnectorResponse
> {
85 const connectorId
= commandPayload
.connectorId
;
86 if (connectorId
=== 0) {
87 logger
.error(this.chargingStation
.logPrefix() + ' Trying to unlock connector ' + connectorId
.toString());
88 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
90 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
91 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
).transactionId
;
92 const stopResponse
= await this.chargingStation
.ocppRequestService
.sendStopTransaction(transactionId
,
93 this.chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
94 this.chargingStation
.getTransactionIdTag(transactionId
),
95 OCPP16StopTransactionReason
.UNLOCK_COMMAND
);
96 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
97 return Constants
.OCPP_RESPONSE_UNLOCKED
;
99 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
101 await this.chargingStation
.ocppRequestService
.sendStatusNotification(connectorId
, OCPP16ChargePointStatus
.AVAILABLE
);
102 this.chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
103 return Constants
.OCPP_RESPONSE_UNLOCKED
;
106 private handleRequestGetConfiguration(commandPayload
: GetConfigurationRequest
): GetConfigurationResponse
{
107 const configurationKey
: OCPPConfigurationKey
[] = [];
108 const unknownKey
: string[] = [];
109 if (Utils
.isEmptyArray(commandPayload
.key
)) {
110 for (const configuration
of this.chargingStation
.configuration
.configurationKey
) {
111 if (Utils
.isUndefined(configuration
.visible
)) {
112 configuration
.visible
= true;
114 if (!configuration
.visible
) {
117 configurationKey
.push({
118 key
: configuration
.key
,
119 readonly: configuration
.readonly,
120 value
: configuration
.value
,
124 for (const key
of commandPayload
.key
) {
125 const keyFound
= this.chargingStation
.getConfigurationKey(key
);
127 if (Utils
.isUndefined(keyFound
.visible
)) {
128 keyFound
.visible
= true;
130 if (!keyFound
.visible
) {
133 configurationKey
.push({
135 readonly: keyFound
.readonly,
136 value
: keyFound
.value
,
139 unknownKey
.push(key
);
149 private handleRequestChangeConfiguration(commandPayload
: ChangeConfigurationRequest
): ChangeConfigurationResponse
{
150 // JSON request fields type sanity check
151 if (!Utils
.isString(commandPayload
.key
)) {
152 logger
.error(`${this.chargingStation.logPrefix()} ${OCPP16RequestCommand.CHANGE_CONFIGURATION} request key field is not a string:`, commandPayload
);
154 if (!Utils
.isString(commandPayload
.value
)) {
155 logger
.error(`${this.chargingStation.logPrefix()} ${OCPP16RequestCommand.CHANGE_CONFIGURATION} request value field is not a string:`, commandPayload
);
157 const keyToChange
= this.chargingStation
.getConfigurationKey(commandPayload
.key
, true);
159 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
160 } else if (keyToChange
&& keyToChange
.readonly) {
161 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
162 } else if (keyToChange
&& !keyToChange
.readonly) {
163 const keyIndex
= this.chargingStation
.configuration
.configurationKey
.indexOf(keyToChange
);
164 let valueChanged
= false;
165 if (this.chargingStation
.configuration
.configurationKey
[keyIndex
].value
!== commandPayload
.value
) {
166 this.chargingStation
.configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
169 let triggerHeartbeatRestart
= false;
170 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
171 this.chargingStation
.setConfigurationKeyValue(OCPP16StandardParametersKey
.HeartbeatInterval
, commandPayload
.value
);
172 triggerHeartbeatRestart
= true;
174 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
175 this.chargingStation
.setConfigurationKeyValue(OCPP16StandardParametersKey
.HeartBeatInterval
, commandPayload
.value
);
176 triggerHeartbeatRestart
= true;
178 if (triggerHeartbeatRestart
) {
179 this.chargingStation
.restartHeartbeat();
181 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
182 this.chargingStation
.restartWebSocketPing();
184 if (keyToChange
.reboot
) {
185 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
187 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
191 private handleRequestSetChargingProfile(commandPayload
: SetChargingProfileRequest
): SetChargingProfileResponse
{
192 if (!this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
)) {
193 logger
.error(`${this.chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${commandPayload.connectorId}`);
194 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
196 if (commandPayload
.csChargingProfiles
.chargingProfilePurpose
=== ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&& commandPayload
.connectorId
!== 0) {
197 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
199 if (commandPayload
.csChargingProfiles
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
&& (commandPayload
.connectorId
=== 0 || !this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
)) {
200 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
202 this.chargingStation
.setChargingProfile(commandPayload
.connectorId
, commandPayload
.csChargingProfiles
);
203 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set, dump their stack: %j`, this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
);
204 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
207 private handleRequestClearChargingProfile(commandPayload
: ClearChargingProfileRequest
): ClearChargingProfileResponse
{
208 if (!this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
)) {
209 logger
.error(`${this.chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${commandPayload.connectorId}`);
210 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
212 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
)) {
213 this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
= [];
214 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`, this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
);
215 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
217 if (!commandPayload
.connectorId
) {
218 let clearedCP
= false;
219 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
220 if (!Utils
.isEmptyArray(this.chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
)) {
221 this.chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
222 let clearCurrentCP
= false;
223 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
224 clearCurrentCP
= true;
226 if (!commandPayload
.chargingProfilePurpose
&& chargingProfile
.stackLevel
=== commandPayload
.stackLevel
) {
227 clearCurrentCP
= true;
229 if (!chargingProfile
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
) {
230 clearCurrentCP
= true;
232 if (chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
) {
233 clearCurrentCP
= true;
235 if (clearCurrentCP
) {
236 this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
[index
] = {} as OCPP16ChargingProfile
;
237 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`, this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
);
244 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
247 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
250 private async handleRequestChangeAvailability(commandPayload
: ChangeAvailabilityRequest
): Promise
<ChangeAvailabilityResponse
> {
251 const connectorId
: number = commandPayload
.connectorId
;
252 if (!this.chargingStation
.getConnectorStatus(connectorId
)) {
253 logger
.error(`${this.chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`);
254 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
256 const chargePointStatus
: OCPP16ChargePointStatus
= commandPayload
.type === OCPP16AvailabilityType
.OPERATIVE
257 ? OCPP16ChargePointStatus
.AVAILABLE
258 : OCPP16ChargePointStatus
.UNAVAILABLE
;
259 if (connectorId
=== 0) {
260 let response
: ChangeAvailabilityResponse
= Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
261 for (const id
of this.chargingStation
.connectors
.keys()) {
262 if (this.chargingStation
.getConnectorStatus(id
)?.transactionStarted
) {
263 response
= Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
265 this.chargingStation
.getConnectorStatus(id
).availability
= commandPayload
.type;
266 if (response
=== Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
) {
267 await this.chargingStation
.ocppRequestService
.sendStatusNotification(id
, chargePointStatus
);
268 this.chargingStation
.getConnectorStatus(id
).status = chargePointStatus
;
272 } else if (connectorId
> 0 && (this.chargingStation
.getConnectorStatus(0).availability
=== OCPP16AvailabilityType
.OPERATIVE
|| (this.chargingStation
.getConnectorStatus(0).availability
=== OCPP16AvailabilityType
.INOPERATIVE
&& commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))) {
273 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
274 this.chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
275 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
277 this.chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
278 await this.chargingStation
.ocppRequestService
.sendStatusNotification(connectorId
, chargePointStatus
);
279 this.chargingStation
.getConnectorStatus(connectorId
).status = chargePointStatus
;
280 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
282 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
285 private async handleRequestRemoteStartTransaction(commandPayload
: RemoteStartTransactionRequest
): Promise
<DefaultResponse
> {
286 const transactionConnectorId
: number = commandPayload
.connectorId
;
287 if (transactionConnectorId
) {
288 await this.chargingStation
.ocppRequestService
.sendStatusNotification(transactionConnectorId
, OCPP16ChargePointStatus
.PREPARING
);
289 this.chargingStation
.getConnectorStatus(transactionConnectorId
).status = OCPP16ChargePointStatus
.PREPARING
;
290 if (this.chargingStation
.isChargingStationAvailable() && this.chargingStation
.isConnectorAvailable(transactionConnectorId
)) {
291 // Check if authorized
292 if (this.chargingStation
.getAuthorizeRemoteTxRequests()) {
293 let authorized
= false;
294 if (this.chargingStation
.getLocalAuthListEnabled() && this.chargingStation
.hasAuthorizedTags()
295 && this.chargingStation
.authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
298 if (!authorized
|| (authorized
&& this.chargingStation
.getMayAuthorizeAtRemoteStart())) {
299 const authorizeResponse
= await this.chargingStation
.ocppRequestService
.sendAuthorize(transactionConnectorId
, commandPayload
.idTag
);
300 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
307 // Authorization successful, start transaction
308 if (this.setRemoteStartTransactionChargingProfile(transactionConnectorId
, commandPayload
.chargingProfile
)) {
309 if ((await this.chargingStation
.ocppRequestService
.sendStartTransaction(transactionConnectorId
, commandPayload
.idTag
)).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
310 logger
.debug(this.chargingStation
.logPrefix() + ' Transaction remotely STARTED on ' + this.chargingStation
.stationInfo
.chargingStationId
+ '#' + transactionConnectorId
.toString() + ' for idTag ' + commandPayload
.idTag
);
311 return Constants
.OCPP_RESPONSE_ACCEPTED
;
313 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
315 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
317 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
319 // No authorization check required, start transaction
320 if (this.setRemoteStartTransactionChargingProfile(transactionConnectorId
, commandPayload
.chargingProfile
)) {
321 if ((await this.chargingStation
.ocppRequestService
.sendStartTransaction(transactionConnectorId
, commandPayload
.idTag
)).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
322 logger
.debug(this.chargingStation
.logPrefix() + ' Transaction remotely STARTED on ' + this.chargingStation
.stationInfo
.chargingStationId
+ '#' + transactionConnectorId
.toString() + ' for idTag ' + commandPayload
.idTag
);
323 return Constants
.OCPP_RESPONSE_ACCEPTED
;
325 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
327 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
329 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
331 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
334 private async notifyRemoteStartTransactionRejected(connectorId
: number, idTag
: string): Promise
<DefaultResponse
> {
335 if (this.chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
) {
336 await this.chargingStation
.ocppRequestService
.sendStatusNotification(connectorId
, OCPP16ChargePointStatus
.AVAILABLE
);
337 this.chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
339 logger
.warn(this.chargingStation
.logPrefix() + ' Remote starting transaction REJECTED on connector Id ' + connectorId
.toString() + ', idTag ' + idTag
+ ', availability ' + this.chargingStation
.getConnectorStatus(connectorId
).availability
+ ', status ' + this.chargingStation
.getConnectorStatus(connectorId
).status);
340 return Constants
.OCPP_RESPONSE_REJECTED
;
343 private setRemoteStartTransactionChargingProfile(connectorId
: number, cp
: OCPP16ChargingProfile
): boolean {
344 if (cp
&& cp
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
345 this.chargingStation
.setChargingProfile(connectorId
, cp
);
346 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set at remote start transaction, dump their stack: %j`, this.chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
);
348 } else if (cp
&& cp
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
349 logger
.warn(`${this.chargingStation.logPrefix()} Not allowed to set ${cp.chargingProfilePurpose} charging profile(s) at remote start transaction`);
356 private async handleRequestRemoteStopTransaction(commandPayload
: RemoteStopTransactionRequest
): Promise
<DefaultResponse
> {
357 const transactionId
= commandPayload
.transactionId
;
358 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
359 if (connectorId
> 0 && this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
360 await this.chargingStation
.ocppRequestService
.sendStatusNotification(connectorId
, OCPP16ChargePointStatus
.FINISHING
);
361 this.chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.FINISHING
;
362 await this.chargingStation
.ocppRequestService
.sendStopTransaction(transactionId
, this.chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
363 this.chargingStation
.getTransactionIdTag(transactionId
));
364 return Constants
.OCPP_RESPONSE_ACCEPTED
;
367 logger
.info(this.chargingStation
.logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId
.toString());
368 return Constants
.OCPP_RESPONSE_REJECTED
;
371 private async handleRequestGetDiagnostics(commandPayload
: GetDiagnosticsRequest
): Promise
<GetDiagnosticsResponse
> {
372 logger
.debug(this.chargingStation
.logPrefix() + ' ' + OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
+ ' request received: %j', commandPayload
);
373 const uri
= new URL(commandPayload
.location
);
374 if (uri
.protocol
.startsWith('ftp:')) {
375 let ftpClient
: Client
;
377 const logFiles
= fs
.readdirSync(path
.resolve(__dirname
, '../../../../')).filter((file
) => file
.endsWith('.log')).map((file
) => path
.join('./', file
));
378 const diagnosticsArchive
= this.chargingStation
.stationInfo
.chargingStationId
+ '_logs.tar.gz';
379 tar
.create({ gzip
: true }, logFiles
).pipe(fs
.createWriteStream(diagnosticsArchive
));
380 ftpClient
= new Client();
381 const accessResponse
= await ftpClient
.access({
383 ...(uri
.port
!== '') && { port
: Utils
.convertToInt(uri
.port
) },
384 ...(uri
.username
!== '') && { user
: uri
.username
},
385 ...(uri
.password
!== '') && { password
: uri
.password
},
387 let uploadResponse
: FTPResponse
;
388 if (accessResponse
.code
=== 220) {
389 // eslint-disable-next-line @typescript-eslint/no-misused-promises
390 ftpClient
.trackProgress(async (info
) => {
391 logger
.info(`${this.chargingStation.logPrefix()} ${info.bytes / 1024} bytes transferred from diagnostics archive ${info.name}`);
392 await this.chargingStation
.ocppRequestService
.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus
.Uploading
);
394 uploadResponse
= await ftpClient
.uploadFrom(path
.join(path
.resolve(__dirname
, '../../../../'), diagnosticsArchive
), uri
.pathname
+ diagnosticsArchive
);
395 if (uploadResponse
.code
=== 226) {
396 await this.chargingStation
.ocppRequestService
.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus
.Uploaded
);
400 return { fileName
: diagnosticsArchive
};
402 throw new OCPPError(ErrorType
.GENERIC_ERROR
, `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${uploadResponse?.code && '|' + uploadResponse?.code.toString()}`, OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
);
404 throw new OCPPError(ErrorType
.GENERIC_ERROR
, `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${uploadResponse?.code && '|' + uploadResponse?.code.toString()}`, OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
);
406 await this.chargingStation
.ocppRequestService
.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus
.UploadFailed
);
410 return this.handleIncomingRequestError(OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
, error
, Constants
.OCPP_RESPONSE_EMPTY
);
413 logger
.error(`${this.chargingStation.logPrefix()} Unsupported protocol ${uri.protocol} to transfer the diagnostic logs archive`);
414 await this.chargingStation
.ocppRequestService
.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus
.UploadFailed
);
415 return Constants
.OCPP_RESPONSE_EMPTY
;
419 private handleRequestTriggerMessage(commandPayload
: OCPP16TriggerMessageRequest
): OCPP16TriggerMessageResponse
{
421 switch (commandPayload
.requestedMessage
) {
422 case MessageTrigger
.BootNotification
:
424 this.chargingStation
.ocppRequestService
.sendBootNotification(this.chargingStation
.getBootNotificationRequest().chargePointModel
,
425 this.chargingStation
.getBootNotificationRequest().chargePointVendor
, this.chargingStation
.getBootNotificationRequest().chargeBoxSerialNumber
,
426 this.chargingStation
.getBootNotificationRequest().firmwareVersion
).catch(() => { /* This is intentional */ });
427 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
428 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
429 case MessageTrigger
.Heartbeat
:
431 this.chargingStation
.ocppRequestService
.sendHeartbeat().catch(() => { /* This is intentional */ });
432 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
433 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
435 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
438 return this.handleIncomingRequestError(OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
, error
, Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
);