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 { OCPP16ChargePointStatus
} from
'../../../types/ocpp/1.6/ChargePointStatus';
15 import { OCPP16DiagnosticsStatus
} from
'../../../types/ocpp/1.6/DiagnosticsStatus';
16 import { OCPP16StandardParametersKey
} from
'../../../types/ocpp/1.6/Configuration';
17 import { OCPPConfigurationKey
} from
'../../../types/ocpp/Configuration';
18 import OCPPError from
'../OCPPError';
19 import OCPPIncomingRequestService from
'../OCPPIncomingRequestService';
20 import { URL
} from
'url';
21 import Utils from
'../../../utils/Utils';
23 import logger from
'../../../utils/Logger';
24 import path from
'path';
25 import tar from
'tar';
27 export default class OCPP16IncomingRequestService
extends OCPPIncomingRequestService
{
28 private incomingRequestHandlers
: Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>;
30 constructor(chargingStation
: ChargingStation
) {
31 super(chargingStation
);
32 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
33 [OCPP16IncomingRequestCommand
.RESET
, this.handleRequestReset
.bind(this)],
34 [OCPP16IncomingRequestCommand
.CLEAR_CACHE
, this.handleRequestClearCache
.bind(this)],
35 [OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
, this.handleRequestUnlockConnector
.bind(this)],
36 [OCPP16IncomingRequestCommand
.GET_CONFIGURATION
, this.handleRequestGetConfiguration
.bind(this)],
37 [OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
, this.handleRequestChangeConfiguration
.bind(this)],
38 [OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
, this.handleRequestSetChargingProfile
.bind(this)],
39 [OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
, this.handleRequestClearChargingProfile
.bind(this)],
40 [OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
, this.handleRequestChangeAvailability
.bind(this)],
41 [OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
, this.handleRequestRemoteStartTransaction
.bind(this)],
42 [OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
, this.handleRequestRemoteStopTransaction
.bind(this)],
43 [OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
, this.handleRequestGetDiagnostics
.bind(this)],
44 [OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
, this.handleRequestTriggerMessage
.bind(this)]
48 public async handleRequest(messageId
: string, commandName
: OCPP16IncomingRequestCommand
, commandPayload
: Record
<string, unknown
>): Promise
<void> {
49 let result
: Record
<string, unknown
>;
50 if (this.chargingStation
.isRegistered()) {
51 if (this.incomingRequestHandlers
.has(commandName
)) {
53 // Call the method to build the result
54 result
= 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 request payload ${JSON.stringify(commandPayload, null, 2)}`, commandName
);
65 throw new OCPPError(ErrorType
.SECURITY_ERROR
, `The charging station is not registered on the central server. ${commandName} cannot be not issued to handle request payload ${JSON.stringify(commandPayload, null, 2)}`, commandName
);
67 // Send the built result
68 await this.chargingStation
.ocppRequestService
.sendResult(messageId
, result
, commandName
);
71 // Simulate charging station restart
72 private handleRequestReset(commandPayload
: ResetRequest
): DefaultResponse
{
73 // eslint-disable-next-line @typescript-eslint/no-misused-promises
74 setImmediate(async (): Promise
<void> => {
75 await this.chargingStation
.stop(commandPayload
.type + 'Reset' as OCPP16StopTransactionReason
);
76 await Utils
.sleep(this.chargingStation
.stationInfo
.resetTime
);
77 this.chargingStation
.start();
79 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)}`);
80 return Constants
.OCPP_RESPONSE_ACCEPTED
;
83 private handleRequestClearCache(): DefaultResponse
{
84 return Constants
.OCPP_RESPONSE_ACCEPTED
;
87 private async handleRequestUnlockConnector(commandPayload
: UnlockConnectorRequest
): Promise
<UnlockConnectorResponse
> {
88 const connectorId
= commandPayload
.connectorId
;
89 if (connectorId
=== 0) {
90 logger
.error(this.chargingStation
.logPrefix() + ' Trying to unlock connector ' + connectorId
.toString());
91 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
93 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
94 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
).transactionId
;
95 const stopResponse
= await this.chargingStation
.ocppRequestService
.sendStopTransaction(transactionId
,
96 this.chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
97 this.chargingStation
.getTransactionIdTag(transactionId
),
98 OCPP16StopTransactionReason
.UNLOCK_COMMAND
);
99 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
100 return Constants
.OCPP_RESPONSE_UNLOCKED
;
102 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
104 await this.chargingStation
.ocppRequestService
.sendStatusNotification(connectorId
, OCPP16ChargePointStatus
.AVAILABLE
);
105 this.chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
106 return Constants
.OCPP_RESPONSE_UNLOCKED
;
109 private handleRequestGetConfiguration(commandPayload
: GetConfigurationRequest
): GetConfigurationResponse
{
110 const configurationKey
: OCPPConfigurationKey
[] = [];
111 const unknownKey
: string[] = [];
112 if (Utils
.isEmptyArray(commandPayload
.key
)) {
113 for (const configuration
of this.chargingStation
.configuration
.configurationKey
) {
114 if (Utils
.isUndefined(configuration
.visible
)) {
115 configuration
.visible
= true;
117 if (!configuration
.visible
) {
120 configurationKey
.push({
121 key
: configuration
.key
,
122 readonly: configuration
.readonly,
123 value
: configuration
.value
,
127 for (const key
of commandPayload
.key
) {
128 const keyFound
= this.chargingStation
.getConfigurationKey(key
);
130 if (Utils
.isUndefined(keyFound
.visible
)) {
131 keyFound
.visible
= true;
133 if (!keyFound
.visible
) {
136 configurationKey
.push({
138 readonly: keyFound
.readonly,
139 value
: keyFound
.value
,
142 unknownKey
.push(key
);
152 private handleRequestChangeConfiguration(commandPayload
: ChangeConfigurationRequest
): ChangeConfigurationResponse
{
153 // JSON request fields type sanity check
154 if (!Utils
.isString(commandPayload
.key
)) {
155 logger
.error(`${this.chargingStation.logPrefix()} ${OCPP16RequestCommand.CHANGE_CONFIGURATION} request key field is not a string:`, commandPayload
);
157 if (!Utils
.isString(commandPayload
.value
)) {
158 logger
.error(`${this.chargingStation.logPrefix()} ${OCPP16RequestCommand.CHANGE_CONFIGURATION} request value field is not a string:`, commandPayload
);
160 const keyToChange
= this.chargingStation
.getConfigurationKey(commandPayload
.key
, true);
162 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
163 } else if (keyToChange
&& keyToChange
.readonly) {
164 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
165 } else if (keyToChange
&& !keyToChange
.readonly) {
166 const keyIndex
= this.chargingStation
.configuration
.configurationKey
.indexOf(keyToChange
);
167 let valueChanged
= false;
168 if (this.chargingStation
.configuration
.configurationKey
[keyIndex
].value
!== commandPayload
.value
) {
169 this.chargingStation
.configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
172 let triggerHeartbeatRestart
= false;
173 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
174 this.chargingStation
.setConfigurationKeyValue(OCPP16StandardParametersKey
.HeartbeatInterval
, commandPayload
.value
);
175 triggerHeartbeatRestart
= true;
177 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
178 this.chargingStation
.setConfigurationKeyValue(OCPP16StandardParametersKey
.HeartBeatInterval
, commandPayload
.value
);
179 triggerHeartbeatRestart
= true;
181 if (triggerHeartbeatRestart
) {
182 this.chargingStation
.restartHeartbeat();
184 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
185 this.chargingStation
.restartWebSocketPing();
187 if (keyToChange
.reboot
) {
188 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
190 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
194 private handleRequestSetChargingProfile(commandPayload
: SetChargingProfileRequest
): SetChargingProfileResponse
{
195 if (!this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
)) {
196 logger
.error(`${this.chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${commandPayload.connectorId}`);
197 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
199 if (commandPayload
.csChargingProfiles
.chargingProfilePurpose
=== ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&& commandPayload
.connectorId
!== 0) {
200 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
202 if (commandPayload
.csChargingProfiles
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
&& (commandPayload
.connectorId
=== 0 || !this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
)) {
203 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
205 this.chargingStation
.setChargingProfile(commandPayload
.connectorId
, commandPayload
.csChargingProfiles
);
206 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set, dump their stack: %j`, this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
);
207 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
210 private handleRequestClearChargingProfile(commandPayload
: ClearChargingProfileRequest
): ClearChargingProfileResponse
{
211 if (!this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
)) {
212 logger
.error(`${this.chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${commandPayload.connectorId}`);
213 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
215 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
)) {
216 this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
= [];
217 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`, this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
);
218 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
220 if (!commandPayload
.connectorId
) {
221 let clearedCP
= false;
222 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
223 if (!Utils
.isEmptyArray(this.chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
)) {
224 this.chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
225 let clearCurrentCP
= false;
226 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
227 clearCurrentCP
= true;
229 if (!commandPayload
.chargingProfilePurpose
&& chargingProfile
.stackLevel
=== commandPayload
.stackLevel
) {
230 clearCurrentCP
= true;
232 if (!chargingProfile
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
) {
233 clearCurrentCP
= true;
235 if (chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
) {
236 clearCurrentCP
= true;
238 if (clearCurrentCP
) {
239 this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
[index
] = {} as OCPP16ChargingProfile
;
240 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`, this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
);
247 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
250 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
253 private async handleRequestChangeAvailability(commandPayload
: ChangeAvailabilityRequest
): Promise
<ChangeAvailabilityResponse
> {
254 const connectorId
: number = commandPayload
.connectorId
;
255 if (!this.chargingStation
.getConnectorStatus(connectorId
)) {
256 logger
.error(`${this.chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`);
257 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
259 const chargePointStatus
: OCPP16ChargePointStatus
= commandPayload
.type === OCPP16AvailabilityType
.OPERATIVE
260 ? OCPP16ChargePointStatus
.AVAILABLE
261 : OCPP16ChargePointStatus
.UNAVAILABLE
;
262 if (connectorId
=== 0) {
263 let response
: ChangeAvailabilityResponse
= Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
264 for (const id
of this.chargingStation
.connectors
.keys()) {
265 if (this.chargingStation
.getConnectorStatus(id
)?.transactionStarted
) {
266 response
= Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
268 this.chargingStation
.getConnectorStatus(id
).availability
= commandPayload
.type;
269 if (response
=== Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
) {
270 await this.chargingStation
.ocppRequestService
.sendStatusNotification(id
, chargePointStatus
);
271 this.chargingStation
.getConnectorStatus(id
).status = chargePointStatus
;
275 } else if (connectorId
> 0 && (this.chargingStation
.getConnectorStatus(0).availability
=== OCPP16AvailabilityType
.OPERATIVE
|| (this.chargingStation
.getConnectorStatus(0).availability
=== OCPP16AvailabilityType
.INOPERATIVE
&& commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))) {
276 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
277 this.chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
278 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
280 this.chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
281 await this.chargingStation
.ocppRequestService
.sendStatusNotification(connectorId
, chargePointStatus
);
282 this.chargingStation
.getConnectorStatus(connectorId
).status = chargePointStatus
;
283 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
285 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
288 private async handleRequestRemoteStartTransaction(commandPayload
: RemoteStartTransactionRequest
): Promise
<DefaultResponse
> {
289 const transactionConnectorId
: number = commandPayload
.connectorId
;
290 if (transactionConnectorId
) {
291 await this.chargingStation
.ocppRequestService
.sendStatusNotification(transactionConnectorId
, OCPP16ChargePointStatus
.PREPARING
);
292 this.chargingStation
.getConnectorStatus(transactionConnectorId
).status = OCPP16ChargePointStatus
.PREPARING
;
293 if (this.chargingStation
.isChargingStationAvailable() && this.chargingStation
.isConnectorAvailable(transactionConnectorId
)) {
294 // Check if authorized
295 if (this.chargingStation
.getAuthorizeRemoteTxRequests()) {
296 let authorized
= false;
297 if (this.chargingStation
.getLocalAuthListEnabled() && this.chargingStation
.hasAuthorizedTags()
298 && this.chargingStation
.authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
299 this.chargingStation
.getConnectorStatus(transactionConnectorId
).localAuthorizeIdTag
= commandPayload
.idTag
;
300 this.chargingStation
.getConnectorStatus(transactionConnectorId
).idTagLocalAuthorized
= true;
302 } else if (this.chargingStation
.getMayAuthorizeAtRemoteStart()) {
303 const authorizeResponse
= await this.chargingStation
.ocppRequestService
.sendAuthorize(transactionConnectorId
, commandPayload
.idTag
);
304 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
308 logger
.warn(`${this.chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`);
311 // Authorization successful, start transaction
312 if (this.setRemoteStartTransactionChargingProfile(transactionConnectorId
, commandPayload
.chargingProfile
)) {
313 this.chargingStation
.getConnectorStatus(transactionConnectorId
).transactionRemoteStarted
= true;
314 if ((await this.chargingStation
.ocppRequestService
.sendStartTransaction(transactionConnectorId
, commandPayload
.idTag
)).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
315 logger
.debug(this.chargingStation
.logPrefix() + ' Transaction remotely STARTED on ' + this.chargingStation
.stationInfo
.chargingStationId
+ '#' + transactionConnectorId
.toString() + ' for idTag ' + commandPayload
.idTag
);
316 return Constants
.OCPP_RESPONSE_ACCEPTED
;
318 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
320 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
322 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
324 // No authorization check required, start transaction
325 if (this.setRemoteStartTransactionChargingProfile(transactionConnectorId
, commandPayload
.chargingProfile
)) {
326 this.chargingStation
.getConnectorStatus(transactionConnectorId
).transactionRemoteStarted
= true;
327 if ((await this.chargingStation
.ocppRequestService
.sendStartTransaction(transactionConnectorId
, commandPayload
.idTag
)).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
328 logger
.debug(this.chargingStation
.logPrefix() + ' Transaction remotely STARTED on ' + this.chargingStation
.stationInfo
.chargingStationId
+ '#' + transactionConnectorId
.toString() + ' for idTag ' + commandPayload
.idTag
);
329 return Constants
.OCPP_RESPONSE_ACCEPTED
;
331 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
333 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
335 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
337 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
340 private async notifyRemoteStartTransactionRejected(connectorId
: number, idTag
: string): Promise
<DefaultResponse
> {
341 if (this.chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
) {
342 await this.chargingStation
.ocppRequestService
.sendStatusNotification(connectorId
, OCPP16ChargePointStatus
.AVAILABLE
);
343 this.chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
345 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);
346 return Constants
.OCPP_RESPONSE_REJECTED
;
349 private setRemoteStartTransactionChargingProfile(connectorId
: number, cp
: OCPP16ChargingProfile
): boolean {
350 if (cp
&& cp
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
351 this.chargingStation
.setChargingProfile(connectorId
, cp
);
352 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set at remote start transaction, dump their stack: %j`, this.chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
);
354 } else if (cp
&& cp
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
355 logger
.warn(`${this.chargingStation.logPrefix()} Not allowed to set ${cp.chargingProfilePurpose} charging profile(s) at remote start transaction`);
362 private async handleRequestRemoteStopTransaction(commandPayload
: RemoteStopTransactionRequest
): Promise
<DefaultResponse
> {
363 const transactionId
= commandPayload
.transactionId
;
364 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
365 if (connectorId
> 0 && this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
366 await this.chargingStation
.ocppRequestService
.sendStatusNotification(connectorId
, OCPP16ChargePointStatus
.FINISHING
);
367 this.chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.FINISHING
;
368 await this.chargingStation
.ocppRequestService
.sendStopTransaction(transactionId
, this.chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
369 this.chargingStation
.getTransactionIdTag(transactionId
));
370 return Constants
.OCPP_RESPONSE_ACCEPTED
;
373 logger
.info(this.chargingStation
.logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId
.toString());
374 return Constants
.OCPP_RESPONSE_REJECTED
;
377 private async handleRequestGetDiagnostics(commandPayload
: GetDiagnosticsRequest
): Promise
<GetDiagnosticsResponse
> {
378 logger
.debug(this.chargingStation
.logPrefix() + ' ' + OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
+ ' request received: %j', commandPayload
);
379 const uri
= new URL(commandPayload
.location
);
380 if (uri
.protocol
.startsWith('ftp:')) {
381 let ftpClient
: Client
;
383 const logFiles
= fs
.readdirSync(path
.resolve(__dirname
, '../../../../')).filter((file
) => file
.endsWith('.log')).map((file
) => path
.join('./', file
));
384 const diagnosticsArchive
= this.chargingStation
.stationInfo
.chargingStationId
+ '_logs.tar.gz';
385 tar
.create({ gzip
: true }, logFiles
).pipe(fs
.createWriteStream(diagnosticsArchive
));
386 ftpClient
= new Client();
387 const accessResponse
= await ftpClient
.access({
389 ...(uri
.port
!== '') && { port
: Utils
.convertToInt(uri
.port
) },
390 ...(uri
.username
!== '') && { user
: uri
.username
},
391 ...(uri
.password
!== '') && { password
: uri
.password
},
393 let uploadResponse
: FTPResponse
;
394 if (accessResponse
.code
=== 220) {
395 // eslint-disable-next-line @typescript-eslint/no-misused-promises
396 ftpClient
.trackProgress(async (info
) => {
397 logger
.info(`${this.chargingStation.logPrefix()} ${info.bytes / 1024} bytes transferred from diagnostics archive ${info.name}`);
398 await this.chargingStation
.ocppRequestService
.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus
.Uploading
);
400 uploadResponse
= await ftpClient
.uploadFrom(path
.join(path
.resolve(__dirname
, '../../../../'), diagnosticsArchive
), uri
.pathname
+ diagnosticsArchive
);
401 if (uploadResponse
.code
=== 226) {
402 await this.chargingStation
.ocppRequestService
.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus
.Uploaded
);
406 return { fileName
: diagnosticsArchive
};
408 throw new OCPPError(ErrorType
.GENERIC_ERROR
, `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${uploadResponse?.code && '|' + uploadResponse?.code.toString()}`, OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
);
410 throw new OCPPError(ErrorType
.GENERIC_ERROR
, `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${uploadResponse?.code && '|' + uploadResponse?.code.toString()}`, OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
);
412 await this.chargingStation
.ocppRequestService
.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus
.UploadFailed
);
416 return this.handleIncomingRequestError(OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
, error
as Error, Constants
.OCPP_RESPONSE_EMPTY
);
419 logger
.error(`${this.chargingStation.logPrefix()} Unsupported protocol ${uri.protocol} to transfer the diagnostic logs archive`);
420 await this.chargingStation
.ocppRequestService
.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus
.UploadFailed
);
421 return Constants
.OCPP_RESPONSE_EMPTY
;
425 private handleRequestTriggerMessage(commandPayload
: OCPP16TriggerMessageRequest
): OCPP16TriggerMessageResponse
{
427 switch (commandPayload
.requestedMessage
) {
428 case MessageTrigger
.BootNotification
:
430 this.chargingStation
.ocppRequestService
.sendBootNotification(this.chargingStation
.getBootNotificationRequest().chargePointModel
,
431 this.chargingStation
.getBootNotificationRequest().chargePointVendor
, this.chargingStation
.getBootNotificationRequest().chargeBoxSerialNumber
,
432 this.chargingStation
.getBootNotificationRequest().firmwareVersion
).catch(() => { /* This is intentional */ });
433 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
434 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
435 case MessageTrigger
.Heartbeat
:
437 this.chargingStation
.ocppRequestService
.sendHeartbeat().catch(() => { /* This is intentional */ });
438 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
439 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
441 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
444 return this.handleIncomingRequestError(OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
, error
as Error, Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
);