-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathIPConnectionBase.java
More file actions
1137 lines (922 loc) · 30.3 KB
/
IPConnectionBase.java
File metadata and controls
1137 lines (922 loc) · 30.3 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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2012-2015, 2019, 2020 Matthias Bolte <[email protected]>
* Copyright (C) 2011-2012 Olaf Lüke <[email protected]>
*
* Redistribution and use in source and binary forms of this file,
* with or without modification, are permitted. See the Creative
* Commons Zero (CC0 1.0) License for more details.
*/
package com.tinkerforge;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.Hashtable;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
class ReceiveThread extends Thread {
IPConnectionBase ipcon = null;
ReceiveThread(IPConnectionBase ipcon) {
super("Brickd-Receiver");
setDaemon(true);
this.ipcon = ipcon;
}
@Override
public void run() {
byte[] pendingData = new byte[8192];
int pendingLength = 0;
long socketID = ipcon.socketID;
while (ipcon.receiveFlag) {
int length;
try {
length = ipcon.in.read(pendingData, pendingLength,
pendingData.length - pendingLength);
} catch (java.net.SocketException e) {
if (ipcon.receiveFlag) {
ipcon.handleDisconnectByPeer(IPConnectionBase.DISCONNECT_REASON_ERROR,
socketID, false);
}
return;
} catch (Exception e) {
if (ipcon.receiveFlag) {
e.printStackTrace();
}
return;
}
if (length <= 0) {
if (ipcon.receiveFlag) {
ipcon.handleDisconnectByPeer(IPConnectionBase.DISCONNECT_REASON_SHUTDOWN,
socketID, false);
}
return;
}
pendingLength += length;
while (ipcon.receiveFlag) {
if (pendingLength < 8) {
// Wait for complete header
break;
}
length = IPConnectionBase.getLengthFromData(pendingData);
if (pendingLength < length) {
// Wait for complete packet
break;
}
byte[] packet = new byte[length];
System.arraycopy(pendingData, 0, packet, 0, length);
System.arraycopy(pendingData, length, pendingData, 0, pendingLength - length);
pendingLength -= length;
ipcon.handleResponse(packet);
}
}
}
}
class CallbackThreadRestarter implements Thread.UncaughtExceptionHandler {
IPConnectionBase ipcon = null;
CallbackThreadRestarter(IPConnectionBase ipcon) {
this.ipcon = ipcon;
}
@Override
public void uncaughtException(Thread thread, Throwable exception) {
System.err.print("Exception in thread \"" + thread.getName() + "\" ");
exception.printStackTrace();
ipcon.callbackThread = new CallbackThread(ipcon, ((CallbackThread)thread).callbackQueue);
ipcon.callbackThread.start();
}
}
class CallbackThread extends Thread {
IPConnectionBase ipcon = null;
LinkedBlockingQueue<IPConnectionBase.CallbackQueueObject> callbackQueue = null;
Object mutex = new Object();
boolean packetDispatchAllowed = false;
CallbackThread(IPConnectionBase ipcon,
LinkedBlockingQueue<IPConnectionBase.CallbackQueueObject> callbackQueue) {
super("Callback-Processor");
setDaemon(true);
this.ipcon = ipcon;
this.callbackQueue = callbackQueue;
this.setUncaughtExceptionHandler(new CallbackThreadRestarter(ipcon));
}
void setPacketDispatchAllowed(boolean allowed) {
if (allowed) {
packetDispatchAllowed = true;
} else {
if (Thread.currentThread() != this) {
// FIXME: cannot lock callback mutex here because this can
// deadlock due to an ordering problem with the socket mutex
/*synchronized (mutex)*/ {
packetDispatchAllowed = false;
}
} else {
packetDispatchAllowed = false;
}
}
}
void dispatchMeta(IPConnectionBase.CallbackQueueObject cqo) {
switch(cqo.functionID) {
case IPConnectionBase.CALLBACK_CONNECTED:
ipcon.callConnectedListeners(cqo.parameter);
break;
case IPConnectionBase.CALLBACK_DISCONNECTED:
// need to do this here, the receive loop is not allowed to
// hold the socket mutex because this could cause a deadlock
// with a concurrent call to the (dis-)connect function
if (cqo.parameter != IPConnectionBase.DISCONNECT_REASON_REQUEST) {
synchronized (ipcon.socketMutex) {
// don't close the socket if it got disconnected or
// reconnected in the meantime
if (ipcon.socket != null && ipcon.socketID == cqo.socketID) {
ipcon.disconnectProbeThread.shutdown();
try {
ipcon.disconnectProbeThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
ipcon.closeSocket();
}
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
ipcon.callDisconnectedListeners(cqo.parameter);
if (cqo.parameter != IPConnectionBase.DISCONNECT_REASON_REQUEST &&
ipcon.autoReconnect && ipcon.autoReconnectAllowed) {
ipcon.autoReconnectPending = true;
boolean retry = true;
while (retry) {
retry = false;
synchronized (ipcon.socketMutex) {
if (ipcon.autoReconnectAllowed && ipcon.socket == null) {
try {
ipcon.connectUnlocked(true);
} catch (Exception e) {
retry = true;
}
} else {
ipcon.autoReconnectPending = true;
}
}
if (retry) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
break;
}
}
void dispatchPacket(IPConnectionBase.CallbackQueueObject cqo) {
byte functionID = IPConnectionBase.getFunctionIDFromData(cqo.packet);
if (functionID == IPConnectionBase.CALLBACK_ENUMERATE) {
if (ipcon.hasEnumerateListeners()) {
if (cqo.packet.length != 34) {
return; // silently ignoring callback with wrong length
}
ByteBuffer bb = ByteBuffer.wrap(cqo.packet, 8, cqo.packet.length - 8);
bb.order(ByteOrder.LITTLE_ENDIAN);
String uid_str = "";
for (int i = 0; i < 8; i++) {
char c = (char)bb.get();
if (c != '\0') {
uid_str += c;
}
}
String connectedUid_str = "";
for (int i = 0; i < 8; i++) {
char c = (char)bb.get();
if (c != '\0') {
connectedUid_str += c;
}
}
char position = (char)bb.get();
short[] hardwareVersion = new short[3];
hardwareVersion[0] = IPConnectionBase.unsignedByte(bb.get());
hardwareVersion[1] = IPConnectionBase.unsignedByte(bb.get());
hardwareVersion[2] = IPConnectionBase.unsignedByte(bb.get());
short[] firmwareVersion = new short[3];
firmwareVersion[0] = IPConnectionBase.unsignedByte(bb.get());
firmwareVersion[1] = IPConnectionBase.unsignedByte(bb.get());
firmwareVersion[2] = IPConnectionBase.unsignedByte(bb.get());
int deviceIdentifier = IPConnectionBase.unsignedShort(bb.getShort());
short enumerationType = IPConnectionBase.unsignedByte(bb.get());
ipcon.callEnumerateListeners(uid_str, connectedUid_str, position,
hardwareVersion, firmwareVersion,
deviceIdentifier, enumerationType);
}
} else {
long uid = IPConnectionBase.getUIDFromData(cqo.packet);
Device device = ipcon.devices.get(uid);
if (device == null) {
return; // packet for an unknown device, ignoring it
}
try {
device.checkValidity();
} catch (TinkerforgeException e) {
return; // silently ignoring callback for invalid device
}
ipcon.callDeviceListener(device, functionID, cqo.packet);
}
}
@Override
public void run() {
while (true) {
IPConnectionBase.CallbackQueueObject cqo = null;
try {
cqo = callbackQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
continue;
}
if (cqo == null) {
continue;
}
// FIXME: cannot lock callback mutex here because this can
// deadlock due to an ordering problem with the socket mutex
/*synchronized (mutex)*/ {
switch(cqo.kind) {
case IPConnectionBase.QUEUE_EXIT:
return;
case IPConnectionBase.QUEUE_META:
dispatchMeta(cqo);
break;
case IPConnectionBase.QUEUE_PACKET:
// don't dispatch callbacks when the receive thread isn't running
if (packetDispatchAllowed) {
dispatchPacket(cqo);
}
break;
}
}
}
}
}
// NOTE: the disconnect probe thread is not allowed to hold the socketMutex at any
// time because it is created and joined while the socketMutex is locked
class DisconnectProbeThread extends Thread {
IPConnectionBase ipcon = null;
byte[] request = null;
LinkedBlockingQueue<Boolean> queue = new LinkedBlockingQueue<Boolean>();
static final byte FUNCTION_DISCONNECT_PROBE = (byte)128;
static final int DISCONNECT_PROBE_INTERVAL = 5000;
DisconnectProbeThread(IPConnectionBase ipcon) {
super("Disconnect-Prober");
setDaemon(true);
this.ipcon = ipcon;
this.request = ipcon.createRequestPacket((byte)8, FUNCTION_DISCONNECT_PROBE, null).array();
}
void shutdown() {
try {
queue.put(Boolean.valueOf(true));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
Boolean item = null;
while (true) {
try {
item = queue.poll(DISCONNECT_PROBE_INTERVAL, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (item != null) {
break;
}
if (ipcon.disconnectProbeFlag) {
try {
synchronized (ipcon.socketSendMutex) {
ipcon.out.write(request);
}
} catch (java.net.SocketException e) {
ipcon.handleDisconnectByPeer(IPConnectionBase.DISCONNECT_REASON_ERROR,
ipcon.socketID, false);
break;
} catch (Exception e) {
e.printStackTrace();
}
} else {
ipcon.disconnectProbeFlag = true;
}
}
}
}
public abstract class IPConnectionBase implements java.io.Closeable {
private static final String BASE58 = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
public static final byte FUNCTION_ENUMERATE = (byte)254;
public static final byte CALLBACK_ENUMERATE = (byte)253;
public static final byte CALLBACK_CONNECTED = 0;
public static final byte CALLBACK_DISCONNECTED = 1;
private static final int BROADCAST_UID = 0;
// enumeration_type parameter to the enumerate callback
public static final short ENUMERATION_TYPE_AVAILABLE = 0;
public static final short ENUMERATION_TYPE_CONNECTED = 1;
public static final short ENUMERATION_TYPE_DISCONNECTED = 2;
// connect_reason parameter to the connected callback
public static final short CONNECT_REASON_REQUEST = 0;
public static final short CONNECT_REASON_AUTO_RECONNECT = 1;
// disconnect_reason parameter to the disconnected callback
public static final short DISCONNECT_REASON_REQUEST = 0;
public static final short DISCONNECT_REASON_ERROR = 1;
public static final short DISCONNECT_REASON_SHUTDOWN = 2;
// returned by get_connection_state
public static final short CONNECTION_STATE_DISCONNECTED = 0;
public static final short CONNECTION_STATE_CONNECTED = 1;
public static final short CONNECTION_STATE_PENDING = 2; // auto-reconnect in process
static final int QUEUE_EXIT = 0;
static final int QUEUE_META = 1;
static final int QUEUE_PACKET = 2;
BrickDaemon brickd = null;
int responseTimeout = 2500;
Hashtable<Long, Device> devices = new Hashtable<Long, Device>();
private Object replaceMutex = new Object(); // used to synchronize replacements in the devices hashtable
LinkedBlockingQueue<CallbackQueueObject> callbackQueue = null;
Object socketMutex = new Object();
Object socketSendMutex = new Object();
private String host;
private int port;
private static final int SEQUENCE_NUMBER_POS = 4;
private int nextSequenceNumber = 0; // protected by sequenceNumberMutex
private Object sequenceNumberMutex = new Object();
private long nextAuthenticationNonce = 0; // protected by authenticationMutex
private Object authenticationMutex = new Object(); // protects authentication handshake
boolean receiveFlag = false;
boolean autoReconnect = true;
boolean autoReconnectAllowed = false;
boolean autoReconnectPending = false;
Socket socket = null; // protected by socketMutex
long socketID = 0; // protected by socketMutex
OutputStream out = null;
InputStream in = null;
ReceiveThread receiveThread = null;
CallbackThread callbackThread = null;
DisconnectProbeThread disconnectProbeThread = null;
boolean disconnectProbeFlag = false;
static class CallbackQueueObject {
final int kind;
final byte functionID;
final short parameter;
final long socketID;
final byte[] packet;
public CallbackQueueObject(int kind, byte functionID, short parameter,
long socketID, byte[] packet) {
this.kind = kind;
this.functionID = functionID;
this.parameter = parameter;
this.socketID = socketID;
this.packet = packet;
}
}
static class DeviceHighLevelCallback {
Object data = null;
int length = 0;
}
public IPConnectionBase() {
}
/**
* Creates a TCP/IP connection to the given \c host and \c port. The host
* and port can point to a Brick Daemon or to a WIFI/Ethernet Extension.
*
* Devices can only be controlled when the connection was established
* successfully.
*
* Blocks until the connection is established and throws an exception if
* there is no Brick Daemon or WIFI/Ethernet Extension listening at the
* given host and port.
*/
public void connect(String host, int port) throws NetworkException, AlreadyConnectedException {
NetworkException exception = null;
CallbackThread callbackThreadTmp = null;
LinkedBlockingQueue<CallbackQueueObject> callbackQueueTmp = null;
synchronized (socketMutex) {
if (socket != null) {
throw new AlreadyConnectedException("Already connected to " + this.host + ":" + this.port);
}
this.host = host;
this.port = port;
try {
connectUnlocked(false);
} catch (NetworkException e) {
exception = e;
callbackThreadTmp = callbackThread;
callbackQueueTmp = callbackQueue;
callbackThread = null;
callbackQueue = null;
}
}
if (exception != null) {
try {
callbackQueueTmp.put(new CallbackQueueObject(QUEUE_EXIT, (byte)0, (short)0, 0, null));
} catch (InterruptedException e1) {
// This thread is typically interrupted here because of the connection establishment above.
// The raised exception should have cleared the interrupted flag, so just retry to put into
// the (unbounded) queue, to ensure, that the callback thread exits.
try {
callbackQueueTmp.put(new CallbackQueueObject(QUEUE_EXIT, (byte)0, (short)0, 0, null));
} catch (InterruptedException e2) {
e2.printStackTrace();
}
}
if (Thread.currentThread() != callbackThreadTmp) {
try {
callbackThreadTmp.join();
} catch (InterruptedException e1) {
// Same reasoning as above.
try {
callbackThreadTmp.join();
} catch (InterruptedException e2) {
e2.printStackTrace();
}
}
}
throw exception;
}
}
// NOTE: Assumes that socket is null and socketMutex is locked
void connectUnlocked(boolean isAutoReconnect) throws NetworkException {
if (callbackThread == null) {
callbackQueue = new LinkedBlockingQueue<CallbackQueueObject>();
callbackThread = new CallbackThread(this, callbackQueue);
callbackThread.start();
}
Socket tmpSocket;
try {
tmpSocket = new Socket(host, port);
} catch (Exception e) {
throw new NetworkException("Could not create socket: " + e.getMessage(), e);
}
try {
tmpSocket.setTcpNoDelay(true);
} catch (Exception e) {
throw new NetworkException("Could not enable TCP-No-Delay socket option: " + e.getMessage(), e);
}
InputStream tmpIn;
OutputStream tmpOut;
try {
tmpIn = tmpSocket.getInputStream();
} catch (Exception e) {
throw new NetworkException("Could not get socket input stream: " + e.getMessage(), e);
}
try {
tmpOut = tmpSocket.getOutputStream();
} catch (Exception e) {
throw new NetworkException("Could not get socket output stream: " + e.getMessage(), e);
}
try {
tmpOut.flush();
} catch (Exception e) {
throw new NetworkException("Could not flush socket output stream: " + e.getMessage(), e);
}
socket = tmpSocket;
in = tmpIn;
out = tmpOut;
++socketID;
// create disconnect probe thread
disconnectProbeFlag = true;
disconnectProbeThread = new DisconnectProbeThread(this);
disconnectProbeThread.start();
callbackThread.setPacketDispatchAllowed(true);
receiveFlag = true;
receiveThread = new ReceiveThread(this);
receiveThread.start();
autoReconnectAllowed = false;
autoReconnectPending = false;
short connectReason = IPConnectionBase.CONNECT_REASON_REQUEST;
if (isAutoReconnect) {
connectReason = CONNECT_REASON_AUTO_RECONNECT;
}
try {
callbackQueue.put(new CallbackQueueObject(QUEUE_META, CALLBACK_CONNECTED,
connectReason, 0, null));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Implement Closable interface to allow something like
*
* try (IPConnection ipcon = new IPConnection()) { }
*/
@Override
public void close() throws java.io.IOException {
try {
disconnect();
} catch (NotConnectedException e) {
throw new java.io.IOException(e.getMessage(), e);
}
}
/**
* Disconnects the TCP/IP connection from the Brick Daemon or the
* WIFI/Ethernet Extension.
*/
public void disconnect() throws NotConnectedException {
CallbackThread callbackThreadTmp = null;
LinkedBlockingQueue<CallbackQueueObject> callbackQueueTmp = null;
synchronized (socketMutex) {
autoReconnectAllowed = false;
if (autoReconnectPending) {
autoReconnectPending = false;
} else {
if (socket == null) {
throw new NotConnectedException();
}
disconnectUnlocked();
}
callbackThreadTmp = callbackThread;
callbackQueueTmp = callbackQueue;
callbackThread = null;
callbackQueue = null;
}
try {
callbackQueueTmp.put(new CallbackQueueObject(QUEUE_META, CALLBACK_DISCONNECTED,
DISCONNECT_REASON_REQUEST, 0, null));
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
callbackQueueTmp.put(new CallbackQueueObject(QUEUE_EXIT, (byte)0, (short)0, 0, null));
} catch (InterruptedException e) {
e.printStackTrace();
}
if (Thread.currentThread() != callbackThreadTmp) {
try {
callbackThreadTmp.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// NOTE: Assumes that socket is not null and socketMutex is locked
void disconnectUnlocked() {
disconnectProbeThread.shutdown();
try {
disconnectProbeThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// stop dispatching packet callbacks before ending the receive
// thread to avoid timeout exceptions due to callback functions
// trying to call getters
callbackThread.setPacketDispatchAllowed(false);
receiveFlag = false;
closeSocket();
if (receiveThread != null) {
try {
receiveThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
receiveThread = null;
}
}
boolean isASCII(String s) {
return StandardCharsets.US_ASCII.newEncoder().canEncode(s);
}
ByteBuffer encodeToASCII(String s) {
return StandardCharsets.US_ASCII.encode(s);
}
/**
* Performs an authentication handshake with the connected Brick Daemon or
* WIFI/Ethernet Extension. If the handshake succeeds the connection switches
* from non-authenticated to authenticated state and communication can
* continue as normal. If the handshake fails then the connection gets closed.
* Authentication can fail if the wrong secret was used or if authentication
* is not enabled at all on the Brick Daemon or the WIFI/Ethernet Extension.
*
* For more information about authentication see
* https://www.tinkerforge.com/en/doc/Tutorials/Tutorial_Authentication/Tutorial.html
*/
public void authenticate(String secret) throws TinkerforgeException {
if (!isASCII(secret)) {
throw new IllegalArgumentException("Authentication secret contains non-ASCII characters.");
}
synchronized (authenticationMutex) {
if (nextAuthenticationNonce == 0) {
byte[] seed = new SecureRandom().generateSeed(4);
ByteBuffer bb = ByteBuffer.wrap(seed, 0, 4);
bb.order(ByteOrder.LITTLE_ENDIAN);
nextAuthenticationNonce = bb.getInt();
}
byte[] serverNonce = brickd.getAuthenticationNonce();
byte[] clientNonce;
ByteBuffer bb = ByteBuffer.allocate(4);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.putInt((int)nextAuthenticationNonce);
clientNonce = bb.array();
nextAuthenticationNonce = (nextAuthenticationNonce + 1) % ((long)1 << 32);
byte[] data = new byte[serverNonce.length + clientNonce.length];
System.arraycopy(serverNonce, 0, data, 0, serverNonce.length);
System.arraycopy(clientNonce, 0, data, serverNonce.length, clientNonce.length);
byte[] digest;
try {
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(new SecretKeySpec(encodeToASCII(secret).array(), "HmacSHA1"));
digest = mac.doFinal(data);
} catch (Exception e) {
throw new CryptoException("Could not generate HMAC-SHA1: " + e.getMessage(), e);
}
brickd.authenticate(clientNonce, digest);
}
}
/**
* Can return the following states:
*
* - CONNECTION_STATE_DISCONNECTED: No connection is established.
* - CONNECTION_STATE_CONNECTED: A connection to the Brick Daemon or
* the WIFI/Ethernet Extension is established.
* - CONNECTION_STATE_PENDING: IP Connection is currently trying to
* connect.
*/
public short getConnectionState() {
if (socket != null) {
return CONNECTION_STATE_CONNECTED;
}
if (autoReconnectPending) {
return CONNECTION_STATE_PENDING;
}
return CONNECTION_STATE_DISCONNECTED;
}
/**
* Enables or disables auto-reconnect. If auto-reconnect is enabled,
* the IP Connection will try to reconnect to the previously given
* host and port, if the connection is lost.
*
* Default value is *true*.
*/
public void setAutoReconnect(boolean autoReconnect) {
this.autoReconnect = autoReconnect;
if (!autoReconnect) {
autoReconnectAllowed = false;
}
}
/**
* Returns *true* if auto-reconnect is enabled, *false* otherwise.
*/
public boolean getAutoReconnect() {
return autoReconnect;
}
/**
* Sets the timeout in milliseconds for getters and for setters for which the
* response expected flag is activated.
*
* Default timeout is 2500.
*/
public void setTimeout(int timeout) {
if (timeout < 0) {
throw new IllegalArgumentException("Timeout cannot be negative");
}
responseTimeout = timeout;
}
/**
* Returns the timeout as set by setTimeout.
*/
public int getTimeout() {
return responseTimeout;
}
/**
* Broadcasts an enumerate request. All devices will respond with an enumerate
* callback.
*/
public void enumerate() throws NotConnectedException {
ByteBuffer request = createRequestPacket((byte)8, FUNCTION_ENUMERATE, null);
sendRequest(request.array());
}
// to preserve the exact current behavior of the IPConnection all of the
// following abstract methods have to operate synchronous. all listeners
// have to be called before the methods return. this is especially important
// for the DisconnectedListener, because the callback thread expects that
// the user got informed about the disconnect event before it starts the
// auto-reconnect logic. this is because the user shall get a chance to act
// upon the disconnect event before the auto-reconnect logic starts.
//
// synchronous dispatch of the callback is only important if the current
// behavior should be preserved exactly. all callbacks can also be dispatched
// asynchronously. the only negative effect of asynchronous dispatch is
// that the current order of operations around the disconnected callback
// cannot be guaranteed anymore.
protected abstract void callEnumerateListeners(String uid, String connectedUid, char position,
short[] hardwareVersion, short[] firmwareVersion,
int deviceIdentifier, short enumerationType);
protected abstract boolean hasEnumerateListeners();
protected abstract void callConnectedListeners(short connectReason);
protected abstract void callDisconnectedListeners(short disconnectReason);
protected abstract void callDeviceListener(Device device, byte functionID, byte[] packet);
void addDevice(Device device) {
synchronized (replaceMutex) {
Device replacedDevice = devices.get(device.uidNumber);
if (replacedDevice != null) {
replacedDevice.replaced = true;
}
devices.put(device.uidNumber, device); // FIXME: use weakref here
}
}
void handleResponse(byte[] packet) {
byte functionID = getFunctionIDFromData(packet);
short sequenceNumber = unsignedByte(getSequenceNumberFromData(packet));
disconnectProbeFlag = false;
if (sequenceNumber == 0 && functionID == CALLBACK_ENUMERATE) {
if (hasEnumerateListeners()) {
try {
callbackQueue.put(new CallbackQueueObject(QUEUE_PACKET, (byte)0,
(short)0, 0, packet));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return;
}
long uid = getUIDFromData(packet);
Device device = devices.get(uid);
if (device == null) {
return; // Message for an unknown device, ignoring it
}
if (sequenceNumber == 0) {
if (device.callbacks[IPConnectionBase.unsignedByte(functionID)] != null) {
try {
callbackQueue.put(new CallbackQueueObject(QUEUE_PACKET, (byte)0,
(short)0, 0, packet));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return;
}
if (functionID == device.expectedResponseFunctionID &&
sequenceNumber == device.expectedResponseSequenceNumber) {
try {
device.responseQueue.put(packet);
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
// Response seems to be OK, but can't be handled
}
// NOTE: Assumes that socketMutex is locked, if disconnectImmediately is true
void handleDisconnectByPeer(short disconnectReason, long socketID, boolean disconnectImmediately) {
autoReconnectAllowed = true;
if (disconnectImmediately) {
disconnectUnlocked();
}
try {
callbackQueue.put(new CallbackQueueObject(QUEUE_META, CALLBACK_DISCONNECTED,
disconnectReason, socketID, null));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// NOTE: Assumes that socketMutex is locked
void closeSocket() {
if (in != null) {
try {
in.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
in = null;
out = null;
socket = null;
}
static long getUIDFromData(byte[] data) {
return (long)(data[0] & 0xFF) | ((long)(data[1] & 0xFF) << 8) |
((long)(data[2] & 0xFF) << 16) | ((long)(data[3] & 0xFF) << 24);
}
static byte getLengthFromData(byte[] data) {
return data[4];
}
static byte getFunctionIDFromData(byte[] data) {
return data[5];
}
static byte getSequenceNumberFromData(byte[] data) {
return (byte)((((int)data[6]) >> 4) & 0x0F);