Repository navigation
Expand file tree
/
Copy pathIPConnection.cs
More file actions
2653 lines (2239 loc) · 65.1 KB
/
Copy pathIPConnection.cs
File metadata and controls
2653 lines (2239 loc) · 65.1 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, 2017, 2020 Matthias Bolte <matthias@tinkerforge.com>
* Copyright (C) 2011-2012 Olaf Lüke <olaf@tinkerforge.com>
*
* 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.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
using System.Reflection;
#if WINDOWS_UWP || WINDOWS_UAP
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.ApplicationModel.AppService;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
#else
using System.Security.Cryptography;
#endif
[assembly: CLSCompliant(true)]
namespace Tinkerforge
{
/// <summary>
/// The IPConnection creates a TCP/IP connection to the Brick Daemon.
/// </summary>
public class IPConnection
{
internal int responseTimeout = 2500;
internal const byte FUNCTION_DISCONNECT_PROBE = 128;
internal const byte FUNCTION_ENUMERATE = 254;
internal const byte CALLBACK_ENUMERATE = 253;
internal const int CALLBACK_CONNECTED = 0;
internal const int CALLBACK_DISCONNECTED = 1;
internal const long BROADCAST_UID = (long)0;
internal const int DISCONNECT_PROBE_INTERVAL = 5000;
internal static Dictionary<int, string> deviceDisplayNames = new Dictionary<int, string>();
// enumeration_type parameter to the enumerate callback
/// <summary>
/// Device is available (enumeration triggered by user: Enumerate()).
/// This enumeration type can occur multiple times for the same device.
/// </summary>
public const short ENUMERATION_TYPE_AVAILABLE = 0;
/// <summary>
/// Device is newly connected (automatically send by Brick after
/// establishing a communication connection). This indicates that the
/// device has potentially lost its previous configuration and needs
/// to be reconfigured.
/// </summary>
public const short ENUMERATION_TYPE_CONNECTED = 1;
/// <summary>
/// Device is disconnected (only possible for USB connection). In this
/// case only uid and enumerationType are valid.
/// </summary>
public const short ENUMERATION_TYPE_DISCONNECTED = 2;
// connect_reason parameter to the connected callback
/// <summary>
/// Connection established after request from user.
/// </summary>
public const short CONNECT_REASON_REQUEST = 0;
/// <summary>
/// Connection after auto-reconnect.
/// </summary>
public const short CONNECT_REASON_AUTO_RECONNECT = 1;
// disconnect_reason parameter to the disconnected callback
/// <summary>
/// Disconnect was requested by user.
/// </summary>
public const short DISCONNECT_REASON_REQUEST = 0;
/// <summary>
/// Disconnect because of an unresolvable error.
/// </summary>
public const short DISCONNECT_REASON_ERROR = 1;
/// <summary>
/// Disconnect initiated by Brick Daemon or WIFI/Ethernet Extension.
/// </summary>
public const short DISCONNECT_REASON_SHUTDOWN = 2;
// returned by get_connection_state
/// <summary>
/// No connection is established.
/// </summary>
public const short CONNECTION_STATE_DISCONNECTED = 0;
/// <summary>
/// A connection to the Brick Daemon or the WIFI/Ethernet Extension is
/// established.
/// </summary>
public const short CONNECTION_STATE_CONNECTED = 1;
/// <summary>
/// IP Connection is currently trying to connect.
/// </summary>
public const short CONNECTION_STATE_PENDING = 2; // auto-reconnect in process
internal const int QUEUE_EXIT = 0;
internal const int QUEUE_META = 1;
internal const int QUEUE_PACKET = 2;
internal int nextSequenceNumber = 0; // protected by sequenceNumberLock
private object sequenceNumberLock = new object();
private uint nextAuthenticationNonce = 0; // protected by authenticationLock
private object authenticationLock = new object(); // protects authentication handshake
internal bool autoReconnectAllowed = false;
internal bool autoReconnectPending = false;
internal bool autoReconnect = true;
#if !(WINDOWS_UWP || WINDOWS_UAP)
private static RNGCryptoServiceProvider randomGenerator = null; // protected by randomGeneratorLock
private static object randomGeneratorLock = new object();
#endif
internal BrickDaemon brickd = null;
string host;
int port;
ISocketWrapper socket = null; // protected by socketLock
internal object socketLock = new object();
internal object socketWriteLock = new object(); // used to synchronize write access to socket
long socketID = 0; // protected by socketLock
Thread receiveThread = null;
bool receiveFlag = true;
CallbackContext callback = null;
internal Dictionary<int, Device> devices = new Dictionary<int, Device>();
internal object replaceLock = new object(); // used to synchronize replacements in the devices dictionary
BlockingQueue<bool> waiter = new BlockingQueue<bool>();
bool disconnectProbeFlag = false;
BlockingQueue<bool> disconnectProbeQueue = null;
Thread disconnectProbeThread = null;
/// <summary>
/// </summary>
public event EnumerateEventHandler EnumerateCallback;
/// <summary>
/// </summary>
public delegate void EnumerateEventHandler(IPConnection sender, string uid, string connectedUid,
char position, short[] hardwareVersion, short[] firmwareVersion,
int deviceIdentifier, short enumerationType);
/// <summary>
/// </summary>
public event ConnectedEventHandler ConnectedCallback;
/// <summary>
/// </summary>
public delegate void ConnectedEventHandler(IPConnection sender, short connectReason);
/// <summary>
/// </summary>
public event ConnectedEventHandler Connected // for backward compatibility
{
add { ConnectedCallback += value; }
remove { ConnectedCallback -= value; }
}
/// <summary>
/// </summary>
public event DisconnectedEventHandler DisconnectedCallback;
/// <summary>
/// </summary>
public delegate void DisconnectedEventHandler(IPConnection sender, short disconnectReason);
/// <summary>
/// </summary>
public event DisconnectedEventHandler Disconnected // for backward compatibility
{
add { DisconnectedCallback += value; }
remove { DisconnectedCallback -= value; }
}
class CallbackQueueObject
{
public int kind;
public byte functionID;
public short parameter;
public long socketID;
public 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;
}
}
class CallbackContext
{
public Thread thread = null;
public BlockingQueue<CallbackQueueObject> queue = null;
public object lock_ = null;
public bool packetDispatchAllowed = false;
}
static IPConnection()
{
Type[] types = typeof(Device).Assembly.GetTypes();
foreach (Type type in types)
{
if (type.BaseType != typeof(Device) || type == typeof(BrickDaemon))
{
continue;
}
FieldInfo deviceIdentifierInfo = type.GetField("DEVICE_IDENTIFIER", BindingFlags.Public | BindingFlags.Static);
int deviceIdentifier = (int)deviceIdentifierInfo.GetValue(null);
FieldInfo deviceDisplayNameInfo = type.GetField("DEVICE_DISPLAY_NAME", BindingFlags.Public | BindingFlags.Static);
string deviceDisplayName = (string)deviceDisplayNameInfo.GetValue(null);
deviceDisplayNames[deviceIdentifier] = deviceDisplayName;
}
}
internal static string GetDeviceDisplayName(int deviceIdentifier)
{
string deviceDisplayName;
if (!deviceDisplayNames.TryGetValue(deviceIdentifier, out deviceDisplayName))
{
deviceDisplayName = "Unknown Device [" + deviceIdentifier + "]";
}
return deviceDisplayName;
}
/// <summary>
/// Creates an IP Connection object that can be used to enumerate the
/// available devices. It is also required for the constructor of
/// Bricks and Bricklets.
/// </summary>
public IPConnection()
{
brickd = new BrickDaemon("2", this);
}
/// <summary>
/// Creates a TCP/IP connection to the given *host* and *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.
/// </summary>
public void Connect(string host, int port)
{
lock (socketLock)
{
if (socket != null)
{
throw new AlreadyConnectedException("Already connected to " + this.host + ":" + this.port);
}
this.host = host;
this.port = port;
ConnectUnlocked(false);
}
}
// NOTE: assumes that socket is null and socketLock is locked
private void ConnectUnlocked(bool isAutoReconnect)
{
if (callback == null)
{
callback = new CallbackContext();
callback.packetDispatchAllowed = false;
callback.queue = new BlockingQueue<CallbackQueueObject>();
callback.lock_ = new object();
callback.thread = new Thread(delegate() { this.CallbackLoop(callback); });
callback.thread.IsBackground = true;
callback.thread.Name = "Callback-Processor";
callback.thread.Start();
}
#if WINDOWS_UWP || WINDOWS_UAP
if (host == "localhost" || host == "127.0.0.1")
{
socket = new AppServiceWrapper();
}
else
{
socket = new SocketWrapper(host, port);
}
#else
socket = new SocketWrapper(host, port);
#endif
++socketID;
// create disconnect probe thread
disconnectProbeFlag = true;
disconnectProbeQueue = new BlockingQueue<bool>();
disconnectProbeThread = new Thread(delegate() { this.DisconnectProbeLoop(disconnectProbeQueue); });
disconnectProbeThread.IsBackground = true;
disconnectProbeThread.Name = "Disconnect-Prober";
disconnectProbeThread.Start();
callback.packetDispatchAllowed = true;
receiveFlag = true;
receiveThread = new Thread(delegate() { this.ReceiveLoop(socketID); });
receiveThread.IsBackground = true;
receiveThread.Name = "Brickd-Receiver";
receiveThread.Start();
autoReconnectAllowed = false;
autoReconnectPending = false;
short connectReason = IPConnection.CONNECT_REASON_REQUEST;
if (isAutoReconnect)
{
connectReason = CONNECT_REASON_AUTO_RECONNECT;
}
callback.queue.Enqueue(new CallbackQueueObject(QUEUE_META, CALLBACK_CONNECTED,
connectReason, 0, null));
}
/// <summary>
/// Disconnects the TCP/IP connection from the Brick Daemon or the
/// WIFI/Ethernet Extension.
/// </summary>
public void Disconnect()
{
CallbackContext localCallback = null;
lock (socketLock)
{
autoReconnectAllowed = false;
if (autoReconnectPending)
{
autoReconnectPending = false;
}
else
{
if (socket == null)
{
throw new NotConnectedException();
}
DisconnectUnlocked();
}
localCallback = callback;
callback = null;
}
localCallback.queue.Enqueue(new CallbackQueueObject(QUEUE_META, CALLBACK_DISCONNECTED,
DISCONNECT_REASON_REQUEST, 0, null));
localCallback.queue.Enqueue(new CallbackQueueObject(QUEUE_EXIT, 0, 0, 0, null));
if (Thread.CurrentThread != localCallback.thread)
{
localCallback.thread.Join();
}
}
// NOTE: assumes that socket is not null and socketLock is locked
private void DisconnectUnlocked()
{
// destroy disconnect probe thread
disconnectProbeQueue.Enqueue(true);
disconnectProbeThread.Join();
disconnectProbeThread = null;
// stop dispatching packet callbacks before ending the receive
// thread to avoid timeout exceptions due to callback functions
// trying to call getters
if (Thread.CurrentThread != callback.thread)
{
// FIXME: cannot lock callback lock here because this can
// deadlock due to an ordering problem with the socket lock
//lock (callback.lock_)
{
callback.packetDispatchAllowed = false;
}
}
else
{
callback.packetDispatchAllowed = false;
}
receiveFlag = false;
socket.Close();
socket = null;
if (receiveThread != null)
{
receiveThread.Join();
receiveThread = null;
}
}
/// <summary>
/// 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
/// </summary>
public void Authenticate(string secret)
{
for (int i = 0; i < secret.Length; ++i)
{
if (secret[i] > 0x7f)
{
throw new ArgumentException("Authentication secret contains non-ASCII characters.");
}
}
lock (authenticationLock)
{
if (nextAuthenticationNonce == 0)
{
#if WINDOWS_UWP || WINDOWS_UAP
nextAuthenticationNonce = CryptographicBuffer.GenerateRandomNumber();
#else
lock (randomGeneratorLock)
{
if (randomGenerator == null)
{
randomGenerator = new RNGCryptoServiceProvider();
}
try
{
byte[] randomNumber = new byte[4];
randomGenerator.GetBytes(randomNumber);
nextAuthenticationNonce = (uint)LEConverter.IntFrom(0, randomNumber);
}
catch (CryptographicException)
{
ulong milliseconds = (ulong)DateTime.Now.Ticks / (ulong)TimeSpan.TicksPerMillisecond;
ulong seconds = milliseconds / 1000;
ulong remainder = milliseconds % 1000;
ulong pid = (ulong)System.Diagnostics.Process.GetCurrentProcess().Id;
nextAuthenticationNonce = (uint)((seconds << 26 | seconds >> 6) + remainder + pid); // overflow is intended
}
}
#endif
}
byte[] serverNonce = brickd.GetAuthenticationNonce();
byte[] clientNonce = new byte[4];
LEConverter.To((int)nextAuthenticationNonce++, 0, clientNonce);
byte[] data = new byte[serverNonce.Length + clientNonce.Length];
System.Buffer.BlockCopy(serverNonce, 0, data, 0, serverNonce.Length);
System.Buffer.BlockCopy(clientNonce, 0, data, serverNonce.Length, clientNonce.Length);
#if WINDOWS_UWP || WINDOWS_UAP
MacAlgorithmProvider hmac = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
CryptographicKey key = hmac.CreateKey(Encoding.ASCII.GetBytes(secret).AsBuffer());
byte[] digest = CryptographicEngine.Sign(key, data.AsBuffer()).ToArray();
#else
HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes(secret));
byte[] digest = hmac.ComputeHash(data);
#endif
brickd.Authenticate(clientNonce, digest);
}
}
/// <summary>
/// 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.
/// </summary>
public short GetConnectionState()
{
if (socket != null)
{
return CONNECTION_STATE_CONNECTED;
}
if (autoReconnectPending)
{
return CONNECTION_STATE_PENDING;
}
return CONNECTION_STATE_DISCONNECTED;
}
/// <summary>
/// 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*.
/// </summary>
public void SetAutoReconnect(bool autoReconnect)
{
this.autoReconnect = autoReconnect;
if (!autoReconnect)
{
autoReconnectAllowed = false;
}
}
/// <summary>
/// Returns *true* if auto-reconnect is enabled, *false* otherwise.
/// </summary>
public bool GetAutoReconnect()
{
return autoReconnect;
}
/// <summary>
/// Sets the timeout in milliseconds for getters and for setters for
/// which the response expected flag is activated.
///
/// Default timeout is 2500.
/// </summary>
public void SetTimeout(int timeout)
{
if (timeout < 0)
{
throw new ArgumentOutOfRangeException("Timeout cannot be negative");
}
responseTimeout = timeout;
}
/// <summary>
/// Returns the timeout as set by SetTimeout.
/// </summary>
public int GetTimeout()
{
return responseTimeout;
}
/// <summary>
/// Broadcasts an enumerate request. All devices will respond with an
/// enumerate callback.
/// </summary>
public void Enumerate()
{
byte[] request = new byte[8];
LEConverter.To((byte)0, 0, request);
LEConverter.To((byte)8, 4, request);
LEConverter.To(FUNCTION_ENUMERATE, 5, request);
LEConverter.To((byte)((GetNextSequenceNumber() << 4)), 6, request);
LEConverter.To((byte)0, 7, request);
SendRequest(request);
}
/// <summary>
/// Stops the current thread until Unwait is called.
///
/// This is useful if you rely solely on callbacks for events, if you
/// want to wait for a specific callback or if the IP Connection was
/// created in a thread.
///
/// Wait and Unwait act in the same way as "acquire" and "release" of
/// a semaphore.
/// </summary>
public void Wait()
{
bool value;
waiter.TryDequeue(out value);
}
/// <summary>
/// Unwaits the thread previously stopped by Wait.
///
/// Wait and Unwait act in the same way as "acquire" and "release" of
/// a semaphore.
/// </summary>
public void Unwait()
{
waiter.Enqueue(true);
}
internal int GetNextSequenceNumber()
{
int currentSequenceNumber;
lock (sequenceNumberLock)
{
currentSequenceNumber = nextSequenceNumber + 1;
nextSequenceNumber = currentSequenceNumber % 15;
}
return currentSequenceNumber;
}
private void ReceiveLoop(long localSocketID)
{
byte[] pendingData = new byte[8192];
int pendingLength = 0;
while (receiveFlag)
{
int length = 0;
try
{
length = socket.Read(pendingData, pendingLength, pendingData.Length - pendingLength);
}
catch (IOException e)
{
if (e.InnerException != null && e.InnerException is SocketException)
{
if (receiveFlag)
{
HandleDisconnectByPeer(DISCONNECT_REASON_ERROR, localSocketID, false);
}
}
return;
}
catch (ObjectDisposedException)
{
return;
}
catch (NullReferenceException)
{
return;
}
if (length == 0)
{
if (receiveFlag)
{
HandleDisconnectByPeer(DISCONNECT_REASON_SHUTDOWN, localSocketID, false);
return;
}
}
pendingLength += length;
while (receiveFlag)
{
if (pendingLength < 8)
{
// Wait for complete header
break;
}
length = GetLengthFromData(pendingData);
if (pendingLength < length)
{
// Wait for complete packet
break;
}
byte[] packet = new byte[length];
Array.Copy(pendingData, 0, packet, 0, length);
Array.Copy(pendingData, length, pendingData, 0, pendingLength - length);
pendingLength -= length;
HandleResponse(packet);
}
}
}
private void DispatchMeta(CallbackQueueObject cqo)
{
switch (cqo.functionID)
{
case IPConnection.CALLBACK_CONNECTED:
var handler = ConnectedCallback;
if (handler != null)
{
handler(this, cqo.parameter);
}
break;
case IPConnection.CALLBACK_DISCONNECTED:
if (cqo.parameter != DISCONNECT_REASON_REQUEST)
{
// need to do this here, the receive loop is not allowed to
// hold the socket lock because this could cause a deadlock
// with a concurrent call to the (dis-)connect function
lock (socketLock)
{
// don't close the socket if it got disconnected or
// reconnected in the meantime
if (socket != null && socketID == cqo.socketID)
{
// destroy disconnect probe thread
disconnectProbeQueue.Enqueue(true);
disconnectProbeThread.Join();
disconnectProbeThread = null;
// destroy socket
socket.Close();
socket = null;
}
}
}
Thread.Sleep(100);
var disconHandler = DisconnectedCallback;
if (disconHandler != null)
{
disconHandler(this, cqo.parameter);
}
if (cqo.parameter != DISCONNECT_REASON_REQUEST &&
autoReconnect && autoReconnectAllowed)
{
autoReconnectPending = true;
bool retry = true;
while (retry)
{
retry = false;
lock (socketLock)
{
if (autoReconnectAllowed && socket == null)
{
try
{
ConnectUnlocked(true);
}
catch (Exception)
{
retry = true;
}
}
else
{
autoReconnectPending = false;
}
}
if (retry)
{
Thread.Sleep(100);
}
}
}
break;
}
}
private void DispatchPacket(CallbackQueueObject cqo)
{
byte fid = GetFunctionIDFromData(cqo.packet);
if (fid == CALLBACK_ENUMERATE)
{
var enumHandler = EnumerateCallback;
if (enumHandler != null)
{
if (cqo.packet.Length != 34)
{
return; // silently ignoring callback with wrong length
}
string uid_str = LEConverter.StringFrom(8, cqo.packet, 8);
string connectedUid_str = LEConverter.StringFrom(16, cqo.packet, 8);
char position = (char)LEConverter.CharFrom(24, cqo.packet);
short[] hardwareVersion = new short[3];
hardwareVersion[0] = LEConverter.ByteFrom(25, cqo.packet);
hardwareVersion[1] = LEConverter.ByteFrom(26, cqo.packet);
hardwareVersion[2] = LEConverter.ByteFrom(27, cqo.packet);
short[] firmwareVersion = new short[3];
firmwareVersion[0] = LEConverter.ByteFrom(28, cqo.packet);
firmwareVersion[1] = LEConverter.ByteFrom(29, cqo.packet);
firmwareVersion[2] = LEConverter.ByteFrom(30, cqo.packet);
int deviceIdentifier = LEConverter.ShortFrom(31, cqo.packet);
short enumerationType = LEConverter.ByteFrom(33, cqo.packet);
enumHandler(this, uid_str, connectedUid_str, position, hardwareVersion,
firmwareVersion, deviceIdentifier, enumerationType);
}
}
else
{
int uid = GetUIDFromData(cqo.packet);
Device device;
if (devices.TryGetValue(uid, out device))
{
Device.CallbackWrapper wrapper = device.callbackWrappers[fid];
if (wrapper != null)
{
try
{
device.CheckValidity();
}
catch (TinkerforgeException)
{
return; // silently ignoring callback for invalid device
}
wrapper(cqo.packet);
}
}
}
}
private void CallbackLoop(CallbackContext localCallback)
{
while (true)
{
CallbackQueueObject cqo;
if (!localCallback.queue.TryDequeue(out cqo, Timeout.Infinite))
{
continue;
}
if (cqo == null)
{
continue;
}
// FIXME: cannot lock callback lock here because this can
// deadlock due to an ordering problem with the socket lock
//lock (localCallback.lock_)
{
switch (cqo.kind)
{
case IPConnection.QUEUE_EXIT:
return;
case IPConnection.QUEUE_META:
DispatchMeta(cqo);
break;
case IPConnection.QUEUE_PACKET:
// don't dispatch callbacks when the receive thread isn't running
if (localCallback.packetDispatchAllowed)
{
DispatchPacket(cqo);
}
break;
}
}
}
}
// NOTE: the disconnect probe loop is not allowed to hold the socketLock at any
// time because it is created and joined while the socketLock is locked
private void DisconnectProbeLoop(BlockingQueue<bool> localDisconnectProbeQueue)
{
byte[] request = new byte[8];
LEConverter.To((byte)0, 0, request);
LEConverter.To((byte)8, 4, request);
LEConverter.To(FUNCTION_DISCONNECT_PROBE, 5, request);
LEConverter.To((byte)((GetNextSequenceNumber() << 4)), 6, request);
LEConverter.To((byte)0, 7, request);
bool response;
while (true)
{
if (localDisconnectProbeQueue.TryDequeue(out response, DISCONNECT_PROBE_INTERVAL))
{
break;
}
if (disconnectProbeFlag)
{
try
{
lock (socketWriteLock)
{
socket.Write(request, 0, request.Length);
}
}
catch (IOException e)
{
if (e.InnerException != null && e.InnerException is SocketException)
{
HandleDisconnectByPeer(DISCONNECT_REASON_ERROR, socketID, false);
break;
}
}
}
else
{
disconnectProbeFlag = true;
}
}
}
internal static byte GetFunctionIDFromData(byte[] data)
{
return data[5];
}
internal static int GetLengthFromData(byte[] data)
{
return data[4];
}
internal static int GetUIDFromData(byte[] data)
{
return LEConverter.IntFrom(0, data);
}
internal static byte GetSequenceNumberFromData(byte[] data)
{
return (byte)((((int)data[6]) >> 4) & 0x0F);
}
internal static bool GetResponseExpectedFromData(byte[] data)
{
return (((int)(data[6]) >> 3) & 0x01) == 0x01;
}
internal static byte GetErrorCodeFromData(byte[] data)
{
return (byte)(((int)(data[7] >> 6)) & 0x03);
}
// NOTE: assumes that socketLock is locked if disconnectImmediately is true
private void HandleDisconnectByPeer(short disconnectReason, long socketID,
bool disconnectImmediately)
{
autoReconnectAllowed = true;
if (disconnectImmediately)
{
DisconnectUnlocked();
}
callback.queue.Enqueue(new CallbackQueueObject(QUEUE_META, CALLBACK_DISCONNECTED,
disconnectReason, socketID, null));
}
private void HandleResponse(byte[] packet)
{
byte functionID = GetFunctionIDFromData(packet);
byte sequenceNumber = GetSequenceNumberFromData(packet);
disconnectProbeFlag = false;
if (sequenceNumber == 0 && functionID == CALLBACK_ENUMERATE)
{
callback.queue.Enqueue(new CallbackQueueObject(QUEUE_PACKET, 0, 0, 0, packet));
return;
}