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