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 { JsonType
} from
'../../../types/JsonType';
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
'../../../exception/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 public constructor(chargingStation
: ChargingStation
) {
32 if (new.target
?.name
=== 'OCPP16IncomingRequestService') {
33 throw new TypeError('Cannot construct OCPP16IncomingRequestService instances directly');
35 super(chargingStation
);
36 this.incomingRequestHandlers
= new Map
<OCPP16IncomingRequestCommand
, IncomingRequestHandler
>([
37 [OCPP16IncomingRequestCommand
.RESET
, this.handleRequestReset
.bind(this)],
38 [OCPP16IncomingRequestCommand
.CLEAR_CACHE
, this.handleRequestClearCache
.bind(this)],
39 [OCPP16IncomingRequestCommand
.UNLOCK_CONNECTOR
, this.handleRequestUnlockConnector
.bind(this)],
40 [OCPP16IncomingRequestCommand
.GET_CONFIGURATION
, this.handleRequestGetConfiguration
.bind(this)],
41 [OCPP16IncomingRequestCommand
.CHANGE_CONFIGURATION
, this.handleRequestChangeConfiguration
.bind(this)],
42 [OCPP16IncomingRequestCommand
.SET_CHARGING_PROFILE
, this.handleRequestSetChargingProfile
.bind(this)],
43 [OCPP16IncomingRequestCommand
.CLEAR_CHARGING_PROFILE
, this.handleRequestClearChargingProfile
.bind(this)],
44 [OCPP16IncomingRequestCommand
.CHANGE_AVAILABILITY
, this.handleRequestChangeAvailability
.bind(this)],
45 [OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
, this.handleRequestRemoteStartTransaction
.bind(this)],
46 [OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
, this.handleRequestRemoteStopTransaction
.bind(this)],
47 [OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
, this.handleRequestGetDiagnostics
.bind(this)],
48 [OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
, this.handleRequestTriggerMessage
.bind(this)]
52 public async handleRequest(messageId
: string, commandName
: OCPP16IncomingRequestCommand
, commandPayload
: JsonType
): Promise
<void> {
54 if (this.chargingStation
.getOcppStrictCompliance() && (this.chargingStation
.isInPendingState()
55 && (commandName
=== OCPP16IncomingRequestCommand
.REMOTE_START_TRANSACTION
|| commandName
=== OCPP16IncomingRequestCommand
.REMOTE_STOP_TRANSACTION
))) {
56 throw new OCPPError(ErrorType
.SECURITY_ERROR
, `${commandName} cannot be issued to handle request payload ${JSON.stringify(commandPayload, null, 2)} while the charging station is in pending state on the central server`, commandName
);
58 if (this.chargingStation
.isRegistered() || (!this.chargingStation
.getOcppStrictCompliance() && this.chargingStation
.isInUnknownState())) {
59 if (this.incomingRequestHandlers
.has(commandName
)) {
61 // Call the method to build the result
62 result
= await this.incomingRequestHandlers
.get(commandName
)(commandPayload
);
65 logger
.error(this.chargingStation
.logPrefix() + ' Handle request error: %j', error
);
70 throw new OCPPError(ErrorType
.NOT_IMPLEMENTED
, `${commandName} is not implemented to handle request payload ${JSON.stringify(commandPayload, null, 2)}`, commandName
);
73 throw new OCPPError(ErrorType
.SECURITY_ERROR
, `${commandName} cannot be issued to handle request payload ${JSON.stringify(commandPayload, null, 2)} while the charging station is not registered on the central server.`, commandName
);
75 // Send the built result
76 await this.chargingStation
.ocppRequestService
.sendResult(messageId
, result
, commandName
);
79 // Simulate charging station restart
80 private handleRequestReset(commandPayload
: ResetRequest
): DefaultResponse
{
81 // eslint-disable-next-line @typescript-eslint/no-misused-promises
82 setImmediate(async (): Promise
<void> => {
83 await this.chargingStation
.stop(commandPayload
.type + 'Reset' as OCPP16StopTransactionReason
);
84 await Utils
.sleep(this.chargingStation
.stationInfo
.resetTime
);
85 this.chargingStation
.start();
87 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)}`);
88 return Constants
.OCPP_RESPONSE_ACCEPTED
;
91 private handleRequestClearCache(): DefaultResponse
{
92 return Constants
.OCPP_RESPONSE_ACCEPTED
;
95 private async handleRequestUnlockConnector(commandPayload
: UnlockConnectorRequest
): Promise
<UnlockConnectorResponse
> {
96 const connectorId
= commandPayload
.connectorId
;
97 if (connectorId
=== 0) {
98 logger
.error(this.chargingStation
.logPrefix() + ' Trying to unlock connector ' + connectorId
.toString());
99 return Constants
.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED
;
101 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
102 const transactionId
= this.chargingStation
.getConnectorStatus(connectorId
).transactionId
;
103 const stopResponse
= await this.chargingStation
.ocppRequestService
.sendStopTransaction(transactionId
,
104 this.chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
105 this.chargingStation
.getTransactionIdTag(transactionId
),
106 OCPP16StopTransactionReason
.UNLOCK_COMMAND
);
107 if (stopResponse
.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
108 return Constants
.OCPP_RESPONSE_UNLOCKED
;
110 return Constants
.OCPP_RESPONSE_UNLOCK_FAILED
;
112 await this.chargingStation
.ocppRequestService
.sendStatusNotification(connectorId
, OCPP16ChargePointStatus
.AVAILABLE
);
113 this.chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
114 return Constants
.OCPP_RESPONSE_UNLOCKED
;
117 private handleRequestGetConfiguration(commandPayload
: GetConfigurationRequest
): GetConfigurationResponse
{
118 const configurationKey
: OCPPConfigurationKey
[] = [];
119 const unknownKey
: string[] = [];
120 if (Utils
.isEmptyArray(commandPayload
.key
)) {
121 for (const configuration
of this.chargingStation
.configuration
.configurationKey
) {
122 if (Utils
.isUndefined(configuration
.visible
)) {
123 configuration
.visible
= true;
125 if (!configuration
.visible
) {
128 configurationKey
.push({
129 key
: configuration
.key
,
130 readonly: configuration
.readonly,
131 value
: configuration
.value
,
135 for (const key
of commandPayload
.key
) {
136 const keyFound
= this.chargingStation
.getConfigurationKey(key
);
138 if (Utils
.isUndefined(keyFound
.visible
)) {
139 keyFound
.visible
= true;
141 if (!keyFound
.visible
) {
144 configurationKey
.push({
146 readonly: keyFound
.readonly,
147 value
: keyFound
.value
,
150 unknownKey
.push(key
);
160 private handleRequestChangeConfiguration(commandPayload
: ChangeConfigurationRequest
): ChangeConfigurationResponse
{
161 // JSON request fields type sanity check
162 if (!Utils
.isString(commandPayload
.key
)) {
163 logger
.error(`${this.chargingStation.logPrefix()} ${OCPP16RequestCommand.CHANGE_CONFIGURATION} request key field is not a string:`, commandPayload
);
165 if (!Utils
.isString(commandPayload
.value
)) {
166 logger
.error(`${this.chargingStation.logPrefix()} ${OCPP16RequestCommand.CHANGE_CONFIGURATION} request value field is not a string:`, commandPayload
);
168 const keyToChange
= this.chargingStation
.getConfigurationKey(commandPayload
.key
, true);
170 return Constants
.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED
;
171 } else if (keyToChange
&& keyToChange
.readonly) {
172 return Constants
.OCPP_CONFIGURATION_RESPONSE_REJECTED
;
173 } else if (keyToChange
&& !keyToChange
.readonly) {
174 const keyIndex
= this.chargingStation
.configuration
.configurationKey
.indexOf(keyToChange
);
175 let valueChanged
= false;
176 if (this.chargingStation
.configuration
.configurationKey
[keyIndex
].value
!== commandPayload
.value
) {
177 this.chargingStation
.configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
180 let triggerHeartbeatRestart
= false;
181 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartBeatInterval
&& valueChanged
) {
182 this.chargingStation
.setConfigurationKeyValue(OCPP16StandardParametersKey
.HeartbeatInterval
, commandPayload
.value
);
183 triggerHeartbeatRestart
= true;
185 if (keyToChange
.key
=== OCPP16StandardParametersKey
.HeartbeatInterval
&& valueChanged
) {
186 this.chargingStation
.setConfigurationKeyValue(OCPP16StandardParametersKey
.HeartBeatInterval
, commandPayload
.value
);
187 triggerHeartbeatRestart
= true;
189 if (triggerHeartbeatRestart
) {
190 this.chargingStation
.restartHeartbeat();
192 if (keyToChange
.key
=== OCPP16StandardParametersKey
.WebSocketPingInterval
&& valueChanged
) {
193 this.chargingStation
.restartWebSocketPing();
195 if (keyToChange
.reboot
) {
196 return Constants
.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED
;
198 return Constants
.OCPP_CONFIGURATION_RESPONSE_ACCEPTED
;
202 private handleRequestSetChargingProfile(commandPayload
: SetChargingProfileRequest
): SetChargingProfileResponse
{
203 if (!this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
)) {
204 logger
.error(`${this.chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${commandPayload.connectorId}`);
205 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
207 if (commandPayload
.csChargingProfiles
.chargingProfilePurpose
=== ChargingProfilePurposeType
.CHARGE_POINT_MAX_PROFILE
&& commandPayload
.connectorId
!== 0) {
208 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
210 if (commandPayload
.csChargingProfiles
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
&& (commandPayload
.connectorId
=== 0 || !this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
)?.transactionStarted
)) {
211 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED
;
213 this.chargingStation
.setChargingProfile(commandPayload
.connectorId
, commandPayload
.csChargingProfiles
);
214 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set, dump their stack: %j`, this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
);
215 return Constants
.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
218 private handleRequestClearChargingProfile(commandPayload
: ClearChargingProfileRequest
): ClearChargingProfileResponse
{
219 if (!this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
)) {
220 logger
.error(`${this.chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${commandPayload.connectorId}`);
221 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
223 if (commandPayload
.connectorId
&& !Utils
.isEmptyArray(this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
)) {
224 this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
= [];
225 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`, this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
);
226 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
228 if (!commandPayload
.connectorId
) {
229 let clearedCP
= false;
230 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
231 if (!Utils
.isEmptyArray(this.chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
)) {
232 this.chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
?.forEach((chargingProfile
: OCPP16ChargingProfile
, index
: number) => {
233 let clearCurrentCP
= false;
234 if (chargingProfile
.chargingProfileId
=== commandPayload
.id
) {
235 clearCurrentCP
= true;
237 if (!commandPayload
.chargingProfilePurpose
&& chargingProfile
.stackLevel
=== commandPayload
.stackLevel
) {
238 clearCurrentCP
= true;
240 if (!chargingProfile
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
) {
241 clearCurrentCP
= true;
243 if (chargingProfile
.stackLevel
=== commandPayload
.stackLevel
&& chargingProfile
.chargingProfilePurpose
=== commandPayload
.chargingProfilePurpose
) {
244 clearCurrentCP
= true;
246 if (clearCurrentCP
) {
247 this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
[index
] = {} as OCPP16ChargingProfile
;
248 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`, this.chargingStation
.getConnectorStatus(commandPayload
.connectorId
).chargingProfiles
);
255 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
;
258 return Constants
.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN
;
261 private async handleRequestChangeAvailability(commandPayload
: ChangeAvailabilityRequest
): Promise
<ChangeAvailabilityResponse
> {
262 const connectorId
: number = commandPayload
.connectorId
;
263 if (!this.chargingStation
.getConnectorStatus(connectorId
)) {
264 logger
.error(`${this.chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`);
265 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
267 const chargePointStatus
: OCPP16ChargePointStatus
= commandPayload
.type === OCPP16AvailabilityType
.OPERATIVE
268 ? OCPP16ChargePointStatus
.AVAILABLE
269 : OCPP16ChargePointStatus
.UNAVAILABLE
;
270 if (connectorId
=== 0) {
271 let response
: ChangeAvailabilityResponse
= Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
272 for (const id
of this.chargingStation
.connectors
.keys()) {
273 if (this.chargingStation
.getConnectorStatus(id
)?.transactionStarted
) {
274 response
= Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
276 this.chargingStation
.getConnectorStatus(id
).availability
= commandPayload
.type;
277 if (response
=== Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
) {
278 await this.chargingStation
.ocppRequestService
.sendStatusNotification(id
, chargePointStatus
);
279 this.chargingStation
.getConnectorStatus(id
).status = chargePointStatus
;
283 } else if (connectorId
> 0 && (this.chargingStation
.getConnectorStatus(0).availability
=== OCPP16AvailabilityType
.OPERATIVE
|| (this.chargingStation
.getConnectorStatus(0).availability
=== OCPP16AvailabilityType
.INOPERATIVE
&& commandPayload
.type === OCPP16AvailabilityType
.INOPERATIVE
))) {
284 if (this.chargingStation
.getConnectorStatus(connectorId
)?.transactionStarted
) {
285 this.chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
286 return Constants
.OCPP_AVAILABILITY_RESPONSE_SCHEDULED
;
288 this.chargingStation
.getConnectorStatus(connectorId
).availability
= commandPayload
.type;
289 await this.chargingStation
.ocppRequestService
.sendStatusNotification(connectorId
, chargePointStatus
);
290 this.chargingStation
.getConnectorStatus(connectorId
).status = chargePointStatus
;
291 return Constants
.OCPP_AVAILABILITY_RESPONSE_ACCEPTED
;
293 return Constants
.OCPP_AVAILABILITY_RESPONSE_REJECTED
;
296 private async handleRequestRemoteStartTransaction(commandPayload
: RemoteStartTransactionRequest
): Promise
<DefaultResponse
> {
297 const transactionConnectorId
: number = commandPayload
.connectorId
;
298 if (transactionConnectorId
) {
299 await this.chargingStation
.ocppRequestService
.sendStatusNotification(transactionConnectorId
, OCPP16ChargePointStatus
.PREPARING
);
300 this.chargingStation
.getConnectorStatus(transactionConnectorId
).status = OCPP16ChargePointStatus
.PREPARING
;
301 if (this.chargingStation
.isChargingStationAvailable() && this.chargingStation
.isConnectorAvailable(transactionConnectorId
)) {
302 // Check if authorized
303 if (this.chargingStation
.getAuthorizeRemoteTxRequests()) {
304 let authorized
= false;
305 if (this.chargingStation
.getLocalAuthListEnabled() && this.chargingStation
.hasAuthorizedTags()
306 && this.chargingStation
.authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
307 this.chargingStation
.getConnectorStatus(transactionConnectorId
).localAuthorizeIdTag
= commandPayload
.idTag
;
308 this.chargingStation
.getConnectorStatus(transactionConnectorId
).idTagLocalAuthorized
= true;
310 } else if (this.chargingStation
.getMayAuthorizeAtRemoteStart()) {
311 const authorizeResponse
= await this.chargingStation
.ocppRequestService
.sendAuthorize(transactionConnectorId
, commandPayload
.idTag
);
312 if (authorizeResponse
?.idTagInfo
?.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
316 logger
.warn(`${this.chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`);
319 // Authorization successful, start transaction
320 if (this.setRemoteStartTransactionChargingProfile(transactionConnectorId
, commandPayload
.chargingProfile
)) {
321 this.chargingStation
.getConnectorStatus(transactionConnectorId
).transactionRemoteStarted
= true;
322 if ((await this.chargingStation
.ocppRequestService
.sendStartTransaction(transactionConnectorId
, commandPayload
.idTag
)).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
323 logger
.debug(this.chargingStation
.logPrefix() + ' Transaction remotely STARTED on ' + this.chargingStation
.stationInfo
.chargingStationId
+ '#' + transactionConnectorId
.toString() + ' for idTag ' + commandPayload
.idTag
);
324 return Constants
.OCPP_RESPONSE_ACCEPTED
;
326 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
328 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
330 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
332 // No authorization check required, start transaction
333 if (this.setRemoteStartTransactionChargingProfile(transactionConnectorId
, commandPayload
.chargingProfile
)) {
334 this.chargingStation
.getConnectorStatus(transactionConnectorId
).transactionRemoteStarted
= true;
335 if ((await this.chargingStation
.ocppRequestService
.sendStartTransaction(transactionConnectorId
, commandPayload
.idTag
)).idTagInfo
.status === OCPP16AuthorizationStatus
.ACCEPTED
) {
336 logger
.debug(this.chargingStation
.logPrefix() + ' Transaction remotely STARTED on ' + this.chargingStation
.stationInfo
.chargingStationId
+ '#' + transactionConnectorId
.toString() + ' for idTag ' + commandPayload
.idTag
);
337 return Constants
.OCPP_RESPONSE_ACCEPTED
;
339 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
341 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
343 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
345 return this.notifyRemoteStartTransactionRejected(transactionConnectorId
, commandPayload
.idTag
);
348 private async notifyRemoteStartTransactionRejected(connectorId
: number, idTag
: string): Promise
<DefaultResponse
> {
349 if (this.chargingStation
.getConnectorStatus(connectorId
).status !== OCPP16ChargePointStatus
.AVAILABLE
) {
350 await this.chargingStation
.ocppRequestService
.sendStatusNotification(connectorId
, OCPP16ChargePointStatus
.AVAILABLE
);
351 this.chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.AVAILABLE
;
353 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);
354 return Constants
.OCPP_RESPONSE_REJECTED
;
357 private setRemoteStartTransactionChargingProfile(connectorId
: number, cp
: OCPP16ChargingProfile
): boolean {
358 if (cp
&& cp
.chargingProfilePurpose
=== ChargingProfilePurposeType
.TX_PROFILE
) {
359 this.chargingStation
.setChargingProfile(connectorId
, cp
);
360 logger
.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set at remote start transaction, dump their stack: %j`, this.chargingStation
.getConnectorStatus(connectorId
).chargingProfiles
);
362 } else if (cp
&& cp
.chargingProfilePurpose
!== ChargingProfilePurposeType
.TX_PROFILE
) {
363 logger
.warn(`${this.chargingStation.logPrefix()} Not allowed to set ${cp.chargingProfilePurpose} charging profile(s) at remote start transaction`);
370 private async handleRequestRemoteStopTransaction(commandPayload
: RemoteStopTransactionRequest
): Promise
<DefaultResponse
> {
371 const transactionId
= commandPayload
.transactionId
;
372 for (const connectorId
of this.chargingStation
.connectors
.keys()) {
373 if (connectorId
> 0 && this.chargingStation
.getConnectorStatus(connectorId
)?.transactionId
=== transactionId
) {
374 await this.chargingStation
.ocppRequestService
.sendStatusNotification(connectorId
, OCPP16ChargePointStatus
.FINISHING
);
375 this.chargingStation
.getConnectorStatus(connectorId
).status = OCPP16ChargePointStatus
.FINISHING
;
376 await this.chargingStation
.ocppRequestService
.sendStopTransaction(transactionId
, this.chargingStation
.getEnergyActiveImportRegisterByTransactionId(transactionId
),
377 this.chargingStation
.getTransactionIdTag(transactionId
));
378 return Constants
.OCPP_RESPONSE_ACCEPTED
;
381 logger
.info(this.chargingStation
.logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId
.toString());
382 return Constants
.OCPP_RESPONSE_REJECTED
;
385 private async handleRequestGetDiagnostics(commandPayload
: GetDiagnosticsRequest
): Promise
<GetDiagnosticsResponse
> {
386 logger
.debug(this.chargingStation
.logPrefix() + ' ' + OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
+ ' request received: %j', commandPayload
);
387 const uri
= new URL(commandPayload
.location
);
388 if (uri
.protocol
.startsWith('ftp:')) {
389 let ftpClient
: Client
;
391 const logFiles
= fs
.readdirSync(path
.resolve(__dirname
, '../../../../')).filter((file
) => file
.endsWith('.log')).map((file
) => path
.join('./', file
));
392 const diagnosticsArchive
= this.chargingStation
.stationInfo
.chargingStationId
+ '_logs.tar.gz';
393 tar
.create({ gzip
: true }, logFiles
).pipe(fs
.createWriteStream(diagnosticsArchive
));
394 ftpClient
= new Client();
395 const accessResponse
= await ftpClient
.access({
397 ...(uri
.port
!== '') && { port
: Utils
.convertToInt(uri
.port
) },
398 ...(uri
.username
!== '') && { user
: uri
.username
},
399 ...(uri
.password
!== '') && { password
: uri
.password
},
401 let uploadResponse
: FTPResponse
;
402 if (accessResponse
.code
=== 220) {
403 // eslint-disable-next-line @typescript-eslint/no-misused-promises
404 ftpClient
.trackProgress(async (info
) => {
405 logger
.info(`${this.chargingStation.logPrefix()} ${info.bytes / 1024} bytes transferred from diagnostics archive ${info.name}`);
406 await this.chargingStation
.ocppRequestService
.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus
.Uploading
);
408 uploadResponse
= await ftpClient
.uploadFrom(path
.join(path
.resolve(__dirname
, '../../../../'), diagnosticsArchive
), uri
.pathname
+ diagnosticsArchive
);
409 if (uploadResponse
.code
=== 226) {
410 await this.chargingStation
.ocppRequestService
.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus
.Uploaded
);
414 return { fileName
: diagnosticsArchive
};
416 throw new OCPPError(ErrorType
.GENERIC_ERROR
, `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${uploadResponse?.code && '|' + uploadResponse?.code.toString()}`, OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
);
418 throw new OCPPError(ErrorType
.GENERIC_ERROR
, `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${uploadResponse?.code && '|' + uploadResponse?.code.toString()}`, OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
);
420 await this.chargingStation
.ocppRequestService
.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus
.UploadFailed
);
424 return this.handleIncomingRequestError(OCPP16IncomingRequestCommand
.GET_DIAGNOSTICS
, error
as Error, Constants
.OCPP_RESPONSE_EMPTY
);
427 logger
.error(`${this.chargingStation.logPrefix()} Unsupported protocol ${uri.protocol} to transfer the diagnostic logs archive`);
428 await this.chargingStation
.ocppRequestService
.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus
.UploadFailed
);
429 return Constants
.OCPP_RESPONSE_EMPTY
;
433 private handleRequestTriggerMessage(commandPayload
: OCPP16TriggerMessageRequest
): OCPP16TriggerMessageResponse
{
435 switch (commandPayload
.requestedMessage
) {
436 case MessageTrigger
.BootNotification
:
438 this.chargingStation
.ocppRequestService
.sendBootNotification(this.chargingStation
.getBootNotificationRequest().chargePointModel
,
439 this.chargingStation
.getBootNotificationRequest().chargePointVendor
, this.chargingStation
.getBootNotificationRequest().chargeBoxSerialNumber
,
440 this.chargingStation
.getBootNotificationRequest().firmwareVersion
, this.chargingStation
.getBootNotificationRequest().chargePointSerialNumber
,
441 this.chargingStation
.getBootNotificationRequest().iccid
, this.chargingStation
.getBootNotificationRequest().imsi
,
442 this.chargingStation
.getBootNotificationRequest().meterSerialNumber
, this.chargingStation
.getBootNotificationRequest().meterType
,
443 { triggerMessage
: true }).catch(() => { /* This is intentional */ });
444 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
445 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
446 case MessageTrigger
.Heartbeat
:
448 this.chargingStation
.ocppRequestService
.sendHeartbeat({ triggerMessage
: true }).catch(() => { /* This is intentional */ });
449 }, Constants
.OCPP_TRIGGER_MESSAGE_DELAY
);
450 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
;
452 return Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED
;
455 return this.handleIncomingRequestError(OCPP16IncomingRequestCommand
.TRIGGER_MESSAGE
, error
as Error, Constants
.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED
);