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