-
Notifications
You must be signed in to change notification settings - Fork 200
Expand file tree
/
Copy pathCommunicator.java
More file actions
452 lines (410 loc) · 15.2 KB
/
Copy pathCommunicator.java
File metadata and controls
452 lines (410 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
package eu.chargetime.ocpp;
/*
ChargeTime.eu - Java-OCA-OCPP
Copyright (C) 2015-2016 Thomas Volden <tv@chargetime.eu>
Copyright (C) 2022 Emil Melar <emil@iconsultable.no>
MIT License
Copyright (C) 2016-2018 Thomas Volden
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.model.*;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract class. Handles basic communication: Pack and send messages. Receive and unpack messages.
*
* <p>Requires a {@link Transmitter} to send and receive messages. Must be overloaded to implement a
* specific format.
*/
public abstract class Communicator {
private static final Logger logger = LoggerFactory.getLogger(Communicator.class);
private final ConcurrentLinkedDeque<Object> transactionQueue;
private RetryRunner retryRunner;
protected Radio radio;
private CommunicatorEvents events;
private final AtomicBoolean failedFlag = new AtomicBoolean(false);
/**
* Convert a formatted string into a {@link Request}/{@link Confirmation}. This is useful for call
* results, where the confirmation type isn't given.
*
* @param payload the raw formatted payload.
* @param type the expected return type.
* @return the unpacked payload.
* @param <T> the type of the unpacked payload.
* @throws Exception error occurred while converting.
*/
public abstract <T> T unpackPayload(Object payload, Class<T> type) throws Exception;
/**
* Convert a {@link Request}/{@link Confirmation} into a formatted string.
*
* @param payload the payload model.
* @return the payload in the form of a formatted string.
*/
public abstract Object packPayload(Object payload);
/**
* Create a call result envelope to transmit.
*
* @param uniqueId the id the receiver expects.
* @param action action name of the {@link Feature}.
* @param payload packed payload.
* @return a fully packed message ready to send.
*/
protected abstract Object makeCallResult(String uniqueId, String action, Object payload);
/**
* Create a call envelope to transmit to the server.
*
* @param uniqueId the id the receiver must reply with.
* @param action action name of the {@link Feature}.
* @param payload packed payload.
* @return a fully packed message ready to send.
*/
protected abstract Object makeCall(String uniqueId, String action, Object payload);
/**
* Create a call error envelope to transmit.
*
* @param uniqueId the id the receiver expects.
* @param action action name of the {@link Feature}.
* @param errorCode an OCPP error code.
* @param errorDescription an associated error description.
* @return a fully packed message ready to send.
*/
protected abstract Object makeCallError(
String uniqueId, String action, String errorCode, String errorDescription);
/**
* Create a call result error envelope to transmit.
*
* @param uniqueId the id the receiver expects.
* @param action action name of the {@link Feature}.
* @param errorCode an OCPP error code.
* @param errorDescription an associated error description.
* @return a fully packed message ready to send.
*/
protected abstract Object makeCallResultError(
String uniqueId, String action, String errorCode, String errorDescription);
/**
* Create a send envelope to transmit to the server.
*
* @param uniqueId the id of the message.
* @param action action name of the {@link Feature}.
* @param payload packed payload.
* @return a fully packed message ready to send.
*/
protected abstract Object makeSend(String uniqueId, String action, Object payload);
/**
* Identify an incoming call and parse it into one of the following: {@link CallMessage} a
* request. {@link CallResultMessage} a response.
*
* @param message the raw message
* @return CallMessage or {@link CallResultMessage}
*/
protected abstract Message parse(Object message);
/**
* Handle required injections.
*
* @param transmitter Injected {@link Transmitter}
*/
public Communicator(Radio transmitter) {
this(transmitter, true);
}
/**
* Handle required injections.
*
* @param transmitter Injected {@link Transmitter}
* @param enableTransactionQueue flag to enable/disable the transaction queue and associated
* processing
*/
public Communicator(Radio transmitter, boolean enableTransactionQueue) {
this.radio = transmitter;
this.transactionQueue = enableTransactionQueue ? new ConcurrentLinkedDeque<>() : null;
this.retryRunner = enableTransactionQueue ? new RetryRunner() : null;
}
/**
* Use the injected {@link Transmitter} to connect to server.
*
* @param uri the url and port of the server.
* @param events handler for call back events.
*/
public void connect(String uri, CommunicatorEvents events) {
this.events = events;
if (radio instanceof Transmitter) ((Transmitter) radio).connect(uri, new EventHandler(events));
}
/**
* Use the injected {@link Transmitter} to accept a client.
*
* @param events handler for call back events.
*/
public void accept(CommunicatorEvents events) {
this.events = events;
if (radio instanceof Receiver) ((Receiver) radio).accept(new EventHandler(events));
}
/**
* Send a new {@link Request}. Stores transaction-related {@link Request}s if offline. New
* transaction-related {@link Request}s will be placed behind the queue of stored {@link
* Request}s.
*
* @param uniqueId the id the receiver should use to reply.
* @param action action name of the {@link Feature}.
* @param request the outgoing {@link Request}
*/
public synchronized void sendCall(String uniqueId, String action, Request request) {
Object call = makeCall(uniqueId, action, packPayload(request));
try {
if (radio.isClosed()) {
if (request.transactionRelated() && transactionQueue != null) {
logger.warn("Not connected: storing request to queue: {}", request);
transactionQueue.add(call);
} else {
logger.warn("Not connected: can't send request: {}", request);
events.onError(
uniqueId,
"Not connected",
"The request can't be sent due to the lack of connection",
request);
}
} else if (request.transactionRelated()
&& transactionQueue != null
&& !transactionQueue.isEmpty()) {
transactionQueue.add(call);
processTransactionQueue();
} else {
radio.send(call);
}
} catch (NotConnectedException ex) {
logger.warn("sendCall() failed: not connected");
if (request.transactionRelated() && transactionQueue != null) {
transactionQueue.add(call);
} else {
events.onError(
uniqueId,
"Not connected",
"The request can't be sent due to the lack of connection",
request);
}
}
}
/**
* Send a {@link Confirmation} reply to a {@link Request}.
*
* @param uniqueId the id the receiver expects.
* @param action action name of the {@link Feature}.
* @param confirmation the outgoing {@link Confirmation}
*/
public void sendCallResult(String uniqueId, String action, Confirmation confirmation) {
try {
radio.send(makeCallResult(uniqueId, action, packPayload(confirmation)));
ConfirmationCompletedHandler completedHandler = confirmation.getCompletedHandler();
if (completedHandler != null) {
try {
completedHandler.onConfirmationCompleted();
} catch (Throwable e) {
events.onError(
uniqueId,
"ConfirmationCompletedHandlerFailed",
"The confirmation completed callback handler failed with exception " + e,
confirmation);
}
}
} catch (NotConnectedException ex) {
logger.warn("sendCallResult() failed", ex);
events.onError(
uniqueId,
"Not connected",
"The confirmation couldn't be send due to the lack of connection",
confirmation);
}
}
/**
* Send an error. If offline, the message is thrown away.
*
* @param uniqueId the id the receiver expects a response to.
* @param action action name of the {@link Feature}.
* @param errorCode an OCPP error Code.
* @param errorDescription a associated error description.
*/
public void sendCallError(
String uniqueId, String action, String errorCode, String errorDescription) {
logger.error(
"An error occurred. Sending this information: uniqueId {}: action: {}, errorCode: {},"
+ " errorDescription: {}",
uniqueId,
action,
errorCode,
errorDescription);
try {
radio.send(makeCallError(uniqueId, action, errorCode, errorDescription));
} catch (NotConnectedException ex) {
logger.warn("sendCallError() failed", ex);
events.onError(
uniqueId,
"Not connected",
"The error couldn't be send due to the lack of connection",
errorCode);
}
}
/**
* Send a call result error. If offline, the message is thrown away.
*
* @param uniqueId the id the receiver expects a response to.
* @param action action name of the {@link Feature}.
* @param errorCode an OCPP error Code.
* @param errorDescription a associated error description.
*/
public void sendCallResultError(
String uniqueId, String action, String errorCode, String errorDescription) {
logger.error(
"An error occurred while processing a call result. Sending this information: "
+ "uniqueId {}: action: {}, errorCode: {}, errorDescription: {}",
uniqueId,
action,
errorCode,
errorDescription);
try {
radio.send(makeCallResultError(uniqueId, action, errorCode, errorDescription));
} catch (NotConnectedException ex) {
logger.warn("sendCallResultError() failed", ex);
events.onError(
uniqueId,
"Not connected",
"The call result error couldn't be sent due to the lack of connection",
errorCode);
}
}
/**
* Send a {@link Request} which has no confirmation.
*
* @param uniqueId the id of the {@link Request}.
* @param action action name of the {@link Feature}.
* @param request the outgoing {@link Request}
*/
public synchronized void send(String uniqueId, String action, Request request) {
Object call = makeSend(uniqueId, action, packPayload(request));
try {
if (radio.isClosed()) {
logger.warn("Not connected: can't send request: {}", request);
events.onError(
uniqueId,
"Not connected",
"The request can't be sent due to the lack of connection",
request);
} else {
radio.send(call);
}
} catch (NotConnectedException ex) {
logger.warn("sendCall() failed: not connected");
events.onError(
uniqueId,
"Not connected",
"The request can't be sent due to the lack of connection",
request);
}
}
/** Close down the connection. Uses the {@link Transmitter}. */
public void disconnect() {
radio.disconnect();
}
private synchronized void processTransactionQueue() {
if (retryRunner != null && !retryRunner.isAlive()) {
if (retryRunner.getState() != Thread.State.NEW) {
retryRunner = new RetryRunner();
}
retryRunner.start();
}
}
private class EventHandler implements RadioEvents {
private final CommunicatorEvents events;
public EventHandler(CommunicatorEvents events) {
this.events = events;
}
@Override
public void connected() {
events.onConnected();
processTransactionQueue();
}
@Override
public void receivedMessage(Object input) {
Message message = parse(input);
if (message instanceof CallResultMessage) {
events.onCallResult(message.getId(), message.getAction(), message.getPayload());
} else if (message instanceof CallResultErrorMessage) {
CallResultErrorMessage call = (CallResultErrorMessage) message;
events.onCallResultError(
call.getId(), call.getErrorCode(), call.getErrorDescription(), call.getRawPayload());
} else if (message instanceof CallErrorMessage) {
failedFlag.set(true);
CallErrorMessage call = (CallErrorMessage) message;
events.onError(
call.getId(), call.getErrorCode(), call.getErrorDescription(), call.getRawPayload());
} else if (message instanceof CallMessage) {
CallMessage call = (CallMessage) message;
events.onCall(call.getId(), call.getAction(), call.getPayload());
} else if (message instanceof SendMessage) {
SendMessage send = (SendMessage) message;
events.onSend(send.getId(), send.getAction(), send.getPayload());
}
}
@Override
public void disconnected() {
events.onDisconnected();
}
}
/**
* Get queued transaction related request.
*
* @return request or null if queue is empty.
*/
private Object getRetryMessage() {
Object result = null;
if (transactionQueue != null && !transactionQueue.isEmpty()) result = transactionQueue.peek();
return result;
}
/**
* Check if an error message was received.
*
* @return whether a fail flag has been raised.
*/
private boolean hasFailed() {
return failedFlag.get();
}
private void popRetryMessage() {
if (transactionQueue != null) transactionQueue.pollFirst();
}
/** Will resend transaction related requests. */
private class RetryRunner extends Thread {
private static final long DELAY_IN_MILLISECONDS = 1000;
@Override
public void run() {
Object call;
try {
while ((call = getRetryMessage()) != null) {
failedFlag.set(false);
radio.send(call);
Thread.sleep(DELAY_IN_MILLISECONDS);
if (!hasFailed()) popRetryMessage();
}
} catch (InterruptedException ex) {
logger.warn("RetryRunner::run() interrupted", ex);
// restore thread interrupted state
Thread.currentThread().interrupt();
} catch (Exception ex) {
logger.warn("RetryRunner::run() failed", ex);
}
}
}
}