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