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