Fix PENDING state boot notification handling
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / 1.6 / OCPP16IncomingRequestService.ts
CommitLineData
c8eeb62b
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
58144adb 3import { ChangeAvailabilityRequest, ChangeConfigurationRequest, ClearChargingProfileRequest, GetConfigurationRequest, GetDiagnosticsRequest, MessageTrigger, OCPP16AvailabilityType, OCPP16IncomingRequestCommand, OCPP16RequestCommand, OCPP16TriggerMessageRequest, RemoteStartTransactionRequest, RemoteStopTransactionRequest, ResetRequest, SetChargingProfileRequest, UnlockConnectorRequest } from '../../../types/ocpp/1.6/Requests';
802cfa13 4import { ChangeAvailabilityResponse, ChangeConfigurationResponse, ClearChargingProfileResponse, GetConfigurationResponse, GetDiagnosticsResponse, OCPP16TriggerMessageResponse, SetChargingProfileResponse, UnlockConnectorResponse } from '../../../types/ocpp/1.6/Responses';
c0560973 5import { ChargingProfilePurposeType, OCPP16ChargingProfile } from '../../../types/ocpp/1.6/ChargingProfile';
47e22477 6import { Client, FTPResponse } from 'basic-ftp';
c0560973
JB
7import { OCPP16AuthorizationStatus, OCPP16StopTransactionReason } from '../../../types/ocpp/1.6/Transaction';
8
58144adb 9import ChargingStation from '../../ChargingStation';
c0560973 10import Constants from '../../../utils/Constants';
9ccca265 11import { DefaultResponse } from '../../../types/ocpp/Responses';
c0560973 12import { ErrorType } from '../../../types/ocpp/ErrorType';
58144adb 13import { IncomingRequestHandler } from '../../../types/ocpp/Requests';
c0560973 14import { OCPP16ChargePointStatus } from '../../../types/ocpp/1.6/ChargePointStatus';
47e22477 15import { OCPP16DiagnosticsStatus } from '../../../types/ocpp/1.6/DiagnosticsStatus';
c0560973
JB
16import { OCPP16StandardParametersKey } from '../../../types/ocpp/1.6/Configuration';
17import { OCPPConfigurationKey } from '../../../types/ocpp/Configuration';
e58068fd 18import OCPPError from '../../../exception/OCPPError';
c0560973 19import OCPPIncomingRequestService from '../OCPPIncomingRequestService';
a3868ec4 20import { URL } from 'url';
c0560973 21import Utils from '../../../utils/Utils';
47e22477 22import fs from 'fs';
c0560973 23import logger from '../../../utils/Logger';
47e22477
JB
24import path from 'path';
25import tar from 'tar';
c0560973
JB
26
27export default class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
58144adb
JB
28 private incomingRequestHandlers: Map<OCPP16IncomingRequestCommand, IncomingRequestHandler>;
29
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)],
734d790d 43 [OCPP16IncomingRequestCommand.GET_DIAGNOSTICS, this.handleRequestGetDiagnostics.bind(this)],
58144adb
JB
44 [OCPP16IncomingRequestCommand.TRIGGER_MESSAGE, this.handleRequestTriggerMessage.bind(this)]
45 ]);
46 }
47
c0560973 48 public async handleRequest(messageId: string, commandName: OCPP16IncomingRequestCommand, commandPayload: Record<string, unknown>): Promise<void> {
de3dbcf5 49 let result: Record<string, unknown>;
16cd35ad
JB
50 if (this.chargingStation.isRegistered() &&
51 !(this.chargingStation.isInPendingState
52 && (commandName === OCPP16IncomingRequestCommand.REMOTE_START_TRANSACTION || commandName === OCPP16IncomingRequestCommand.REMOTE_STOP_TRANSACTION))) {
124f3553
JB
53 if (this.incomingRequestHandlers.has(commandName)) {
54 try {
55 // Call the method to build the result
56 result = await this.incomingRequestHandlers.get(commandName)(commandPayload);
57 } catch (error) {
58 // Log
59 logger.error(this.chargingStation.logPrefix() + ' Handle request error: %j', error);
60 throw error;
61 }
62 } else {
63 // Throw exception
64 throw new OCPPError(ErrorType.NOT_IMPLEMENTED, `${commandName} is not implemented to handle request payload ${JSON.stringify(commandPayload, null, 2)}`, commandName);
c0560973
JB
65 }
66 } else {
124f3553 67 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);
c0560973 68 }
de3dbcf5
JB
69 // Send the built result
70 await this.chargingStation.ocppRequestService.sendResult(messageId, result, commandName);
c0560973
JB
71 }
72
73 // Simulate charging station restart
74 private handleRequestReset(commandPayload: ResetRequest): DefaultResponse {
71623267
JB
75 // eslint-disable-next-line @typescript-eslint/no-misused-promises
76 setImmediate(async (): Promise<void> => {
c0560973
JB
77 await this.chargingStation.stop(commandPayload.type + 'Reset' as OCPP16StopTransactionReason);
78 await Utils.sleep(this.chargingStation.stationInfo.resetTime);
71623267 79 this.chargingStation.start();
c0560973 80 });
d7d1db72 81 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)}`);
c0560973
JB
82 return Constants.OCPP_RESPONSE_ACCEPTED;
83 }
84
85 private handleRequestClearCache(): DefaultResponse {
86 return Constants.OCPP_RESPONSE_ACCEPTED;
87 }
88
89 private async handleRequestUnlockConnector(commandPayload: UnlockConnectorRequest): Promise<UnlockConnectorResponse> {
90 const connectorId = commandPayload.connectorId;
91 if (connectorId === 0) {
92 logger.error(this.chargingStation.logPrefix() + ' Trying to unlock connector ' + connectorId.toString());
93 return Constants.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED;
94 }
734d790d
JB
95 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted) {
96 const transactionId = this.chargingStation.getConnectorStatus(connectorId).transactionId;
6ed92bc1
JB
97 const stopResponse = await this.chargingStation.ocppRequestService.sendStopTransaction(transactionId,
98 this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
99 this.chargingStation.getTransactionIdTag(transactionId),
100 OCPP16StopTransactionReason.UNLOCK_COMMAND);
c0560973
JB
101 if (stopResponse.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED) {
102 return Constants.OCPP_RESPONSE_UNLOCKED;
103 }
104 return Constants.OCPP_RESPONSE_UNLOCK_FAILED;
105 }
106 await this.chargingStation.ocppRequestService.sendStatusNotification(connectorId, OCPP16ChargePointStatus.AVAILABLE);
734d790d 107 this.chargingStation.getConnectorStatus(connectorId).status = OCPP16ChargePointStatus.AVAILABLE;
c0560973
JB
108 return Constants.OCPP_RESPONSE_UNLOCKED;
109 }
110
111 private handleRequestGetConfiguration(commandPayload: GetConfigurationRequest): GetConfigurationResponse {
112 const configurationKey: OCPPConfigurationKey[] = [];
113 const unknownKey: string[] = [];
114 if (Utils.isEmptyArray(commandPayload.key)) {
115 for (const configuration of this.chargingStation.configuration.configurationKey) {
116 if (Utils.isUndefined(configuration.visible)) {
117 configuration.visible = true;
118 }
119 if (!configuration.visible) {
120 continue;
121 }
122 configurationKey.push({
123 key: configuration.key,
124 readonly: configuration.readonly,
125 value: configuration.value,
126 });
127 }
128 } else {
129 for (const key of commandPayload.key) {
130 const keyFound = this.chargingStation.getConfigurationKey(key);
131 if (keyFound) {
132 if (Utils.isUndefined(keyFound.visible)) {
133 keyFound.visible = true;
134 }
135 if (!keyFound.visible) {
136 continue;
137 }
138 configurationKey.push({
139 key: keyFound.key,
140 readonly: keyFound.readonly,
141 value: keyFound.value,
142 });
143 } else {
144 unknownKey.push(key);
145 }
146 }
147 }
148 return {
149 configurationKey,
150 unknownKey,
151 };
152 }
153
154 private handleRequestChangeConfiguration(commandPayload: ChangeConfigurationRequest): ChangeConfigurationResponse {
155 // JSON request fields type sanity check
156 if (!Utils.isString(commandPayload.key)) {
58144adb 157 logger.error(`${this.chargingStation.logPrefix()} ${OCPP16RequestCommand.CHANGE_CONFIGURATION} request key field is not a string:`, commandPayload);
c0560973
JB
158 }
159 if (!Utils.isString(commandPayload.value)) {
58144adb 160 logger.error(`${this.chargingStation.logPrefix()} ${OCPP16RequestCommand.CHANGE_CONFIGURATION} request value field is not a string:`, commandPayload);
c0560973
JB
161 }
162 const keyToChange = this.chargingStation.getConfigurationKey(commandPayload.key, true);
163 if (!keyToChange) {
164 return Constants.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED;
165 } else if (keyToChange && keyToChange.readonly) {
166 return Constants.OCPP_CONFIGURATION_RESPONSE_REJECTED;
167 } else if (keyToChange && !keyToChange.readonly) {
168 const keyIndex = this.chargingStation.configuration.configurationKey.indexOf(keyToChange);
169 let valueChanged = false;
170 if (this.chargingStation.configuration.configurationKey[keyIndex].value !== commandPayload.value) {
171 this.chargingStation.configuration.configurationKey[keyIndex].value = commandPayload.value;
172 valueChanged = true;
173 }
174 let triggerHeartbeatRestart = false;
175 if (keyToChange.key === OCPP16StandardParametersKey.HeartBeatInterval && valueChanged) {
176 this.chargingStation.setConfigurationKeyValue(OCPP16StandardParametersKey.HeartbeatInterval, commandPayload.value);
177 triggerHeartbeatRestart = true;
178 }
179 if (keyToChange.key === OCPP16StandardParametersKey.HeartbeatInterval && valueChanged) {
180 this.chargingStation.setConfigurationKeyValue(OCPP16StandardParametersKey.HeartBeatInterval, commandPayload.value);
181 triggerHeartbeatRestart = true;
182 }
183 if (triggerHeartbeatRestart) {
184 this.chargingStation.restartHeartbeat();
185 }
186 if (keyToChange.key === OCPP16StandardParametersKey.WebSocketPingInterval && valueChanged) {
187 this.chargingStation.restartWebSocketPing();
188 }
189 if (keyToChange.reboot) {
190 return Constants.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED;
191 }
192 return Constants.OCPP_CONFIGURATION_RESPONSE_ACCEPTED;
193 }
194 }
195
196 private handleRequestSetChargingProfile(commandPayload: SetChargingProfileRequest): SetChargingProfileResponse {
734d790d 197 if (!this.chargingStation.getConnectorStatus(commandPayload.connectorId)) {
a4cc42ea 198 logger.error(`${this.chargingStation.logPrefix()} Trying to set charging profile(s) to a non existing connector Id ${commandPayload.connectorId}`);
c0560973
JB
199 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED;
200 }
201 if (commandPayload.csChargingProfiles.chargingProfilePurpose === ChargingProfilePurposeType.CHARGE_POINT_MAX_PROFILE && commandPayload.connectorId !== 0) {
202 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED;
203 }
734d790d 204 if (commandPayload.csChargingProfiles.chargingProfilePurpose === ChargingProfilePurposeType.TX_PROFILE && (commandPayload.connectorId === 0 || !this.chargingStation.getConnectorStatus(commandPayload.connectorId)?.transactionStarted)) {
c0560973
JB
205 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED;
206 }
207 this.chargingStation.setChargingProfile(commandPayload.connectorId, commandPayload.csChargingProfiles);
734d790d 208 logger.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set, dump their stack: %j`, this.chargingStation.getConnectorStatus(commandPayload.connectorId).chargingProfiles);
c0560973
JB
209 return Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED;
210 }
211
212 private handleRequestClearChargingProfile(commandPayload: ClearChargingProfileRequest): ClearChargingProfileResponse {
734d790d 213 if (!this.chargingStation.getConnectorStatus(commandPayload.connectorId)) {
a4cc42ea 214 logger.error(`${this.chargingStation.logPrefix()} Trying to clear a charging profile(s) to a non existing connector Id ${commandPayload.connectorId}`);
c0560973
JB
215 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN;
216 }
734d790d
JB
217 if (commandPayload.connectorId && !Utils.isEmptyArray(this.chargingStation.getConnectorStatus(commandPayload.connectorId).chargingProfiles)) {
218 this.chargingStation.getConnectorStatus(commandPayload.connectorId).chargingProfiles = [];
219 logger.debug(`${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`, this.chargingStation.getConnectorStatus(commandPayload.connectorId).chargingProfiles);
c0560973
JB
220 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED;
221 }
222 if (!commandPayload.connectorId) {
223 let clearedCP = false;
734d790d
JB
224 for (const connectorId of this.chargingStation.connectors.keys()) {
225 if (!Utils.isEmptyArray(this.chargingStation.getConnectorStatus(connectorId).chargingProfiles)) {
226 this.chargingStation.getConnectorStatus(connectorId).chargingProfiles?.forEach((chargingProfile: OCPP16ChargingProfile, index: number) => {
c0560973
JB
227 let clearCurrentCP = false;
228 if (chargingProfile.chargingProfileId === commandPayload.id) {
229 clearCurrentCP = true;
230 }
231 if (!commandPayload.chargingProfilePurpose && chargingProfile.stackLevel === commandPayload.stackLevel) {
232 clearCurrentCP = true;
233 }
234 if (!chargingProfile.stackLevel && chargingProfile.chargingProfilePurpose === commandPayload.chargingProfilePurpose) {
235 clearCurrentCP = true;
236 }
237 if (chargingProfile.stackLevel === commandPayload.stackLevel && chargingProfile.chargingProfilePurpose === commandPayload.chargingProfilePurpose) {
238 clearCurrentCP = true;
239 }
240 if (clearCurrentCP) {
734d790d
JB
241 this.chargingStation.getConnectorStatus(commandPayload.connectorId).chargingProfiles[index] = {} as OCPP16ChargingProfile;
242 logger.debug(`${this.chargingStation.logPrefix()} Charging profile(s) cleared, dump their stack: %j`, this.chargingStation.getConnectorStatus(commandPayload.connectorId).chargingProfiles);
c0560973
JB
243 clearedCP = true;
244 }
245 });
246 }
247 }
248 if (clearedCP) {
249 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED;
250 }
251 }
252 return Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN;
253 }
254
e268356b 255 private async handleRequestChangeAvailability(commandPayload: ChangeAvailabilityRequest): Promise<ChangeAvailabilityResponse> {
c0560973 256 const connectorId: number = commandPayload.connectorId;
734d790d 257 if (!this.chargingStation.getConnectorStatus(connectorId)) {
c0560973
JB
258 logger.error(`${this.chargingStation.logPrefix()} Trying to change the availability of a non existing connector Id ${connectorId.toString()}`);
259 return Constants.OCPP_AVAILABILITY_RESPONSE_REJECTED;
260 }
734d790d
JB
261 const chargePointStatus: OCPP16ChargePointStatus = commandPayload.type === OCPP16AvailabilityType.OPERATIVE
262 ? OCPP16ChargePointStatus.AVAILABLE
263 : OCPP16ChargePointStatus.UNAVAILABLE;
c0560973
JB
264 if (connectorId === 0) {
265 let response: ChangeAvailabilityResponse = Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED;
734d790d
JB
266 for (const id of this.chargingStation.connectors.keys()) {
267 if (this.chargingStation.getConnectorStatus(id)?.transactionStarted) {
c0560973
JB
268 response = Constants.OCPP_AVAILABILITY_RESPONSE_SCHEDULED;
269 }
734d790d 270 this.chargingStation.getConnectorStatus(id).availability = commandPayload.type;
c0560973 271 if (response === Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED) {
734d790d
JB
272 await this.chargingStation.ocppRequestService.sendStatusNotification(id, chargePointStatus);
273 this.chargingStation.getConnectorStatus(id).status = chargePointStatus;
c0560973
JB
274 }
275 }
276 return response;
734d790d
JB
277 } else if (connectorId > 0 && (this.chargingStation.getConnectorStatus(0).availability === OCPP16AvailabilityType.OPERATIVE || (this.chargingStation.getConnectorStatus(0).availability === OCPP16AvailabilityType.INOPERATIVE && commandPayload.type === OCPP16AvailabilityType.INOPERATIVE))) {
278 if (this.chargingStation.getConnectorStatus(connectorId)?.transactionStarted) {
279 this.chargingStation.getConnectorStatus(connectorId).availability = commandPayload.type;
c0560973
JB
280 return Constants.OCPP_AVAILABILITY_RESPONSE_SCHEDULED;
281 }
734d790d 282 this.chargingStation.getConnectorStatus(connectorId).availability = commandPayload.type;
e268356b 283 await this.chargingStation.ocppRequestService.sendStatusNotification(connectorId, chargePointStatus);
734d790d 284 this.chargingStation.getConnectorStatus(connectorId).status = chargePointStatus;
c0560973
JB
285 return Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED;
286 }
287 return Constants.OCPP_AVAILABILITY_RESPONSE_REJECTED;
288 }
289
290 private async handleRequestRemoteStartTransaction(commandPayload: RemoteStartTransactionRequest): Promise<DefaultResponse> {
a7fc8211
JB
291 const transactionConnectorId: number = commandPayload.connectorId;
292 if (transactionConnectorId) {
293 await this.chargingStation.ocppRequestService.sendStatusNotification(transactionConnectorId, OCPP16ChargePointStatus.PREPARING);
734d790d 294 this.chargingStation.getConnectorStatus(transactionConnectorId).status = OCPP16ChargePointStatus.PREPARING;
a7fc8211 295 if (this.chargingStation.isChargingStationAvailable() && this.chargingStation.isConnectorAvailable(transactionConnectorId)) {
e060fe58 296 // Check if authorized
a7fc8211
JB
297 if (this.chargingStation.getAuthorizeRemoteTxRequests()) {
298 let authorized = false;
a7fc8211 299 if (this.chargingStation.getLocalAuthListEnabled() && this.chargingStation.hasAuthorizedTags()
16cd35ad 300 && this.chargingStation.authorizedTags.find((value) => value === commandPayload.idTag)) {
a2653482
JB
301 this.chargingStation.getConnectorStatus(transactionConnectorId).localAuthorizeIdTag = commandPayload.idTag;
302 this.chargingStation.getConnectorStatus(transactionConnectorId).idTagLocalAuthorized = true;
36f6a92e 303 authorized = true;
71068fb9 304 } else if (this.chargingStation.getMayAuthorizeAtRemoteStart()) {
a7fc8211
JB
305 const authorizeResponse = await this.chargingStation.ocppRequestService.sendAuthorize(transactionConnectorId, commandPayload.idTag);
306 if (authorizeResponse?.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED) {
307 authorized = true;
a7fc8211 308 }
71068fb9 309 } else {
b4d1b412 310 logger.warn(`${this.chargingStation.logPrefix()} The charging station configuration expects authorize at remote start transaction but local authorization or authorize isn't enabled`);
a7fc8211
JB
311 }
312 if (authorized) {
313 // Authorization successful, start transaction
e060fe58 314 if (this.setRemoteStartTransactionChargingProfile(transactionConnectorId, commandPayload.chargingProfile)) {
a2653482 315 this.chargingStation.getConnectorStatus(transactionConnectorId).transactionRemoteStarted = true;
e060fe58
JB
316 if ((await this.chargingStation.ocppRequestService.sendStartTransaction(transactionConnectorId, commandPayload.idTag)).idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED) {
317 logger.debug(this.chargingStation.logPrefix() + ' Transaction remotely STARTED on ' + this.chargingStation.stationInfo.chargingStationId + '#' + transactionConnectorId.toString() + ' for idTag ' + commandPayload.idTag);
318 return Constants.OCPP_RESPONSE_ACCEPTED;
319 }
57939a9d 320 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
e060fe58 321 }
57939a9d 322 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
a7fc8211 323 }
57939a9d 324 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
36f6a92e 325 }
a7fc8211 326 // No authorization check required, start transaction
e060fe58 327 if (this.setRemoteStartTransactionChargingProfile(transactionConnectorId, commandPayload.chargingProfile)) {
a2653482 328 this.chargingStation.getConnectorStatus(transactionConnectorId).transactionRemoteStarted = true;
e060fe58
JB
329 if ((await this.chargingStation.ocppRequestService.sendStartTransaction(transactionConnectorId, commandPayload.idTag)).idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED) {
330 logger.debug(this.chargingStation.logPrefix() + ' Transaction remotely STARTED on ' + this.chargingStation.stationInfo.chargingStationId + '#' + transactionConnectorId.toString() + ' for idTag ' + commandPayload.idTag);
331 return Constants.OCPP_RESPONSE_ACCEPTED;
332 }
57939a9d 333 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
e060fe58 334 }
57939a9d 335 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
c0560973 336 }
57939a9d 337 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
c0560973 338 }
57939a9d 339 return this.notifyRemoteStartTransactionRejected(transactionConnectorId, commandPayload.idTag);
a7fc8211
JB
340 }
341
342 private async notifyRemoteStartTransactionRejected(connectorId: number, idTag: string): Promise<DefaultResponse> {
734d790d 343 if (this.chargingStation.getConnectorStatus(connectorId).status !== OCPP16ChargePointStatus.AVAILABLE) {
e060fe58 344 await this.chargingStation.ocppRequestService.sendStatusNotification(connectorId, OCPP16ChargePointStatus.AVAILABLE);
734d790d 345 this.chargingStation.getConnectorStatus(connectorId).status = OCPP16ChargePointStatus.AVAILABLE;
e060fe58 346 }
734d790d 347 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);
c0560973
JB
348 return Constants.OCPP_RESPONSE_REJECTED;
349 }
350
e060fe58 351 private setRemoteStartTransactionChargingProfile(connectorId: number, cp: OCPP16ChargingProfile): boolean {
a7fc8211
JB
352 if (cp && cp.chargingProfilePurpose === ChargingProfilePurposeType.TX_PROFILE) {
353 this.chargingStation.setChargingProfile(connectorId, cp);
734d790d 354 logger.debug(`${this.chargingStation.logPrefix()} Charging profile(s) set at remote start transaction, dump their stack: %j`, this.chargingStation.getConnectorStatus(connectorId).chargingProfiles);
a7fc8211
JB
355 return true;
356 } else if (cp && cp.chargingProfilePurpose !== ChargingProfilePurposeType.TX_PROFILE) {
a7fc8211
JB
357 logger.warn(`${this.chargingStation.logPrefix()} Not allowed to set ${cp.chargingProfilePurpose} charging profile(s) at remote start transaction`);
358 return false;
e060fe58
JB
359 } else if (!cp) {
360 return true;
a7fc8211
JB
361 }
362 }
363
c0560973
JB
364 private async handleRequestRemoteStopTransaction(commandPayload: RemoteStopTransactionRequest): Promise<DefaultResponse> {
365 const transactionId = commandPayload.transactionId;
734d790d
JB
366 for (const connectorId of this.chargingStation.connectors.keys()) {
367 if (connectorId > 0 && this.chargingStation.getConnectorStatus(connectorId)?.transactionId === transactionId) {
368 await this.chargingStation.ocppRequestService.sendStatusNotification(connectorId, OCPP16ChargePointStatus.FINISHING);
369 this.chargingStation.getConnectorStatus(connectorId).status = OCPP16ChargePointStatus.FINISHING;
6ed92bc1 370 await this.chargingStation.ocppRequestService.sendStopTransaction(transactionId, this.chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId),
035742f7 371 this.chargingStation.getTransactionIdTag(transactionId));
c0560973
JB
372 return Constants.OCPP_RESPONSE_ACCEPTED;
373 }
374 }
375 logger.info(this.chargingStation.logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId.toString());
376 return Constants.OCPP_RESPONSE_REJECTED;
377 }
47e22477
JB
378
379 private async handleRequestGetDiagnostics(commandPayload: GetDiagnosticsRequest): Promise<GetDiagnosticsResponse> {
58144adb 380 logger.debug(this.chargingStation.logPrefix() + ' ' + OCPP16IncomingRequestCommand.GET_DIAGNOSTICS + ' request received: %j', commandPayload);
a3868ec4 381 const uri = new URL(commandPayload.location);
47e22477
JB
382 if (uri.protocol.startsWith('ftp:')) {
383 let ftpClient: Client;
384 try {
385 const logFiles = fs.readdirSync(path.resolve(__dirname, '../../../../')).filter((file) => file.endsWith('.log')).map((file) => path.join('./', file));
386 const diagnosticsArchive = this.chargingStation.stationInfo.chargingStationId + '_logs.tar.gz';
387 tar.create({ gzip: true }, logFiles).pipe(fs.createWriteStream(diagnosticsArchive));
388 ftpClient = new Client();
389 const accessResponse = await ftpClient.access({
390 host: uri.host,
391 ...(uri.port !== '') && { port: Utils.convertToInt(uri.port) },
392 ...(uri.username !== '') && { user: uri.username },
393 ...(uri.password !== '') && { password: uri.password },
394 });
395 let uploadResponse: FTPResponse;
396 if (accessResponse.code === 220) {
397 // eslint-disable-next-line @typescript-eslint/no-misused-promises
398 ftpClient.trackProgress(async (info) => {
399 logger.info(`${this.chargingStation.logPrefix()} ${info.bytes / 1024} bytes transferred from diagnostics archive ${info.name}`);
400 await this.chargingStation.ocppRequestService.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus.Uploading);
401 });
402 uploadResponse = await ftpClient.uploadFrom(path.join(path.resolve(__dirname, '../../../../'), diagnosticsArchive), uri.pathname + diagnosticsArchive);
403 if (uploadResponse.code === 226) {
404 await this.chargingStation.ocppRequestService.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus.Uploaded);
405 if (ftpClient) {
406 ftpClient.close();
407 }
408 return { fileName: diagnosticsArchive };
409 }
58144adb 410 throw new OCPPError(ErrorType.GENERIC_ERROR, `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${uploadResponse?.code && '|' + uploadResponse?.code.toString()}`, OCPP16IncomingRequestCommand.GET_DIAGNOSTICS);
47e22477 411 }
58144adb 412 throw new OCPPError(ErrorType.GENERIC_ERROR, `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${uploadResponse?.code && '|' + uploadResponse?.code.toString()}`, OCPP16IncomingRequestCommand.GET_DIAGNOSTICS);
47e22477
JB
413 } catch (error) {
414 await this.chargingStation.ocppRequestService.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus.UploadFailed);
47e22477
JB
415 if (ftpClient) {
416 ftpClient.close();
417 }
88184022 418 return this.handleIncomingRequestError(OCPP16IncomingRequestCommand.GET_DIAGNOSTICS, error as Error, Constants.OCPP_RESPONSE_EMPTY);
47e22477
JB
419 }
420 } else {
421 logger.error(`${this.chargingStation.logPrefix()} Unsupported protocol ${uri.protocol} to transfer the diagnostic logs archive`);
422 await this.chargingStation.ocppRequestService.sendDiagnosticsStatusNotification(OCPP16DiagnosticsStatus.UploadFailed);
423 return Constants.OCPP_RESPONSE_EMPTY;
424 }
425 }
802cfa13
JB
426
427 private handleRequestTriggerMessage(commandPayload: OCPP16TriggerMessageRequest): OCPP16TriggerMessageResponse {
428 try {
429 switch (commandPayload.requestedMessage) {
430 case MessageTrigger.BootNotification:
431 setTimeout(() => {
432 this.chargingStation.ocppRequestService.sendBootNotification(this.chargingStation.getBootNotificationRequest().chargePointModel,
433 this.chargingStation.getBootNotificationRequest().chargePointVendor, this.chargingStation.getBootNotificationRequest().chargeBoxSerialNumber,
0dad4bda 434 this.chargingStation.getBootNotificationRequest().firmwareVersion).catch(() => { /* This is intentional */ });
802cfa13
JB
435 }, Constants.OCPP_TRIGGER_MESSAGE_DELAY);
436 return Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED;
437 case MessageTrigger.Heartbeat:
438 setTimeout(() => {
0dad4bda 439 this.chargingStation.ocppRequestService.sendHeartbeat().catch(() => { /* This is intentional */ });
802cfa13
JB
440 }, Constants.OCPP_TRIGGER_MESSAGE_DELAY);
441 return Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED;
442 default:
443 return Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED;
444 }
445 } catch (error) {
88184022 446 return this.handleIncomingRequestError(OCPP16IncomingRequestCommand.TRIGGER_MESSAGE, error as Error, Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED);
802cfa13
JB
447 }
448 }
c0560973 449}