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