-
Notifications
You must be signed in to change notification settings - Fork 9
/
Devices.cs
1525 lines (1317 loc) · 56.3 KB
/
Devices.cs
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
using System;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using GeoFramework.Gps.IO;
using Microsoft.Win32;
namespace GeoFramework.Gps.IO
{
/// <summary>
/// Encapsulates GPS device detection features and information about known devices.
/// </summary>
public static class Devices
{
private static List<ManualResetEvent> _CurrentlyDetectingWaitHandles = new List<ManualResetEvent>(16);
private static List<SerialDevice> _SerialDevices;
private static List<BluetoothDevice> _BluetoothDevices;
private static List<Device> _GpsDevices;
private static Thread _DetectionThread;
private static bool _IsDetectionInProgress;
private static bool _IsClockSynchronizationEnabled;
private static ManualResetEvent _DeviceDetectedWaitHandle = new ManualResetEvent(false);
private static ManualResetEvent _DetectionCompleteWaitHandle = new ManualResetEvent(false);
private static TimeSpan _DeviceDetectionTimeout = TimeSpan.FromMinutes(20);
private static bool _IsStreamNeeded;
private static bool _IsOnlyFirstDeviceDetected;
private static bool _AllowBluetoothConnections = true;
private static bool _AllowSerialConnections = true;
private static bool _AllowExhaustiveSerialPortScanning = false;
private static int _MaximumSerialPortNumber = 20;
private static Position _Position;
private static Distance _Altitude;
private static DateTime _UtcDateTime;
private static Azimuth _Bearing;
private static Speed _Speed;
private static List<Satellite> _Satellites;
#if PocketPC
private static bool _AllowGpsIntermediateDriver = true;
private static bool _AllowInfraredConnections = false;
private static bool _IsDetectionThreadAlive;
#endif
#region Constants
internal const string DebugCategory = "GPS.Net";
internal const string RootKeyName = @"SOFTWARE\GeoFrameworks\GPS.NET\3.0\Devices\";
#endregion
#region Events
/// <summary>
/// Occurs when the process of finding GPS devices has begun.
/// </summary>
public static event EventHandler DeviceDetectionStarted;
/// <summary>
/// Occurs immediately before a device is about to be tested for GPS data.
/// </summary>
public static event EventHandler<DeviceEventArgs> DeviceDetectionAttempted;
/// <summary>
/// Occurs when a device has failed to transmit recognizable GPS data.
/// </summary>
public static event EventHandler<DeviceDetectionExceptionEventArgs> DeviceDetectionAttemptFailed;
/// <summary>
/// Occurs when a device is responding and transmitting GPS data.
/// </summary>
public static event EventHandler<DeviceEventArgs> DeviceDetected;
/// <summary>
/// Occurs when a Bluetooth device has been found.
/// </summary>
public static event EventHandler<DeviceEventArgs> DeviceDiscovered;
/// <summary>
/// Occurs when the process of finding GPS devices has been interrupted.
/// </summary>
public static event EventHandler DeviceDetectionCanceled;
/// <summary>
/// Occurs when the process of finding GPS devices has finished.
/// </summary>
public static event EventHandler DeviceDetectionCompleted;
/// <summary>
/// Occurs when any interpreter detects a change in the current location.
/// </summary>
public static event EventHandler<PositionEventArgs> PositionChanged;
/// <summary>
/// Occurs when any interpreter detects a change in the distance above sea level.
/// </summary>
public static event EventHandler<DistanceEventArgs> AltitudeChanged;
/// <summary>
/// Occurs when any interpreter detects a change in the current rate of travel.
/// </summary>
public static event EventHandler<SpeedEventArgs> SpeedChanged;
/// <summary>
/// Occurs when any interpreter detects a change in GPS satellite information.
/// </summary>
public static event EventHandler<SatelliteListEventArgs> SatellitesChanged;
/// <summary>
/// Occurs when any interpreter detects a change in the direction of travel.
/// </summary>
public static event EventHandler<AzimuthEventArgs> BearingChanged;
/// <summary>
/// Occurs when any interpreter detects when a GPS device can no longer calculate the current location.
/// </summary>
public static event EventHandler<DeviceEventArgs> FixLost;
/// <summary>
/// Occurs when any interpreter detects when a GPS device becomes able to calculate the current location.
/// </summary>
public static event EventHandler<DeviceEventArgs> FixAcquired;
/// <summary>
/// Occurs when any interpreter detects a change in the satellite-derived date and time.
/// </summary>
public static event EventHandler<DateTimeEventArgs> UtcDateTimeChanged;
#endregion
#region Constructors
static Devices()
{
// Get notified when a BT device is discovered
BluetoothDevice.DeviceDiscovered += new EventHandler<DeviceEventArgs>(BluetoothDevice_DeviceDiscovered);
// Reset everything
_GpsDevices = new List<Device>();
}
#endregion
#region Static Properties
/// <summary>
/// Returns a GPS device which is connectable and is reporting data.
/// </summary>
/// <remarks></remarks>
public static Device Any
{
get
{
try
{
// A stream is needed!
_IsStreamNeeded = true;
#if PocketPC
/* On mobile devices, the GPS Intermediate Driver can handle responsibility
* of opening and sharing connections to a GPS device. GPS.NET will defer to the
* GPSID so long as it is supported AND enabled for the device.
*/
// Are GPSID connections allowed?
GpsIntermediateDriver gpsid = GpsIntermediateDriver.Current;
if (
// Is it supported?
gpsid != null
// Are we allowing connections?
&& gpsid.AllowConnections
// Has the GPSID not yet been tested?
&& (!gpsid.IsDetectionCompleted
// OR, has it been tested AND it's confirmed as a GPS device?
|| (gpsid.IsDetectionCompleted && gpsid.IsGpsDevice)
)
)
{
try
{
// Open a connection
gpsid.Open();
// It worked!
return gpsid;
}
catch
{
// Feck. Continue with regular detection
}
}
#endif
// Is any GPS device already detected?
if (!IsDeviceDetected)
{
// No. Go look for one now.
BeginDetection();
// Wait for a device to be found.
if (!WaitForDevice())
{
// No device was found! Return null.
return null;
}
}
/* If we get here, a device has been found. If detection completed while
* this method executes, a device will currently have it's stream OPEN
* in anticipation of being used by this property.
*
* So, let's first look for that device with an open stream. Then, if none
* exist, start testing devices until we get a valid stream.
*/
Device device = null;
//Stream stream = null;
Exception connectionException = null;
#region Pass 1: Look for a device with an open connection
// Sort the devices, "best" device first
_GpsDevices.Sort(Device.BestDeviceComparer);
// Examine each device
for (int index = 0; index < _GpsDevices.Count; index++)
{
// Get the device and it's base stream
device = _GpsDevices[index];
// Skip devices which are not open
if (!device.IsOpen)
continue;
// Return the stream
return device;
}
#endregion
/* If we get here, there are no devices with an open connection. So,
* try opening new connections.
*/
#region Pass 2: Attempt new connections
// Test all known GPS devices
for (int index = 0; index < _GpsDevices.Count; index++)
{
try
{
// Get the device
device = _GpsDevices[index];
// Is it allowed?
if (!device.AllowConnections)
continue;
// Open a new connection
device.Open();
// This stream looks valid
return device;
}
catch (Exception ex)
{
// Make sure the device is closed
device.Close();
// We may get all kinds of exceptions when trying to open varying kinds of streams.
// If anything fails, just try the next device.
connectionException = ex;
continue;
}
}
#endregion
#region Pass #3: Any detected devices have failed. Restart detection.
// No. Go look for one now.
BeginDetection();
// Wait for a device to be found.
WaitForDetection();
// Try one last time for devices
for (int index = 0; index < _GpsDevices.Count; index++)
{
try
{
// Get the device
device = _GpsDevices[index];
// Is it allowed?
if (!device.AllowConnections)
continue;
// Open a new connection
device.Open();
// This stream looks valid
return device;
}
catch (Exception ex)
{
// Make sure the device is closed
device.Close();
// We may get all kinds of exceptions when trying to open varying kinds of streams.
// If anything fails, just try the next device.
connectionException = ex;
continue;
}
}
#endregion
// If we get here, no connection is possible!
if (connectionException != null)
{
// Some exception occurred, so re-throw it to help people troubleshoot their connections.
throw connectionException;
}
else
{
// No device was found, and no exception was raised. Return null.
return null;
}
}
catch
{
throw;
}
finally
{
// Flag that we no longer need a stream.
_IsStreamNeeded = false;
}
}
}
/// <summary>
/// Controls whether Bluetooth devices are included in the search for GPS devices.
/// </summary>
public static bool AllowBluetoothConnections
{
get { return _AllowBluetoothConnections; }
set { _AllowBluetoothConnections = value; }
}
/// <summary>
/// Controls whether serial devices are included in the search for GPS devices.
/// </summary>
public static bool AllowSerialConnections
{
get { return _AllowSerialConnections; }
set { _AllowSerialConnections = value; }
}
/// <summary>
/// Controls whether a complete range of serial devices is searched, regardless of which device appear to actually exist.
/// </summary>
public static bool AllowExhaustiveSerialPortScanning
{
get { return _AllowExhaustiveSerialPortScanning; }
set { _AllowExhaustiveSerialPortScanning = value; }
}
/// <summary>
/// Controls the maximum serial port to test when exhaustive detection is enabled.
/// </summary>
public static int MaximumSerialPortNumber
{
get { return _MaximumSerialPortNumber; }
set
{
if (_MaximumSerialPortNumber < 0 || _MaximumSerialPortNumber > 100)
{
#if !PocketPC
throw new ArgumentOutOfRangeException("MaximumSerialPortNumber", _MaximumSerialPortNumber, "The maximum serial port number must be between 0 (for COM0:) and 100 (for COM100:).");
#else
throw new ArgumentOutOfRangeException("MaximumSerialPortNumber", "The maximum serial port number must be between 0 (for COM0:) and 100 (for COM100:).");
#endif
}
_MaximumSerialPortNumber = value;
}
}
#if PocketPC
public static bool AllowInfraredConnections
{
get { return _AllowInfraredConnections; }
set { _AllowInfraredConnections = value; }
}
#endif
/// <summary>
/// Returns a list of confirmed GPS devices.
/// </summary>
public static IList<Device> GpsDevices
{
get
{
return _GpsDevices;
}
}
/// <summary>
/// Returns a list of known wireless Bluetooth devices (not necessarily GPS devices).
/// </summary>
public static IList<BluetoothDevice> BluetoothDevices
{
get
{
if (_BluetoothDevices == null)
_BluetoothDevices = new List<BluetoothDevice>(BluetoothDevice.Cache);
return _BluetoothDevices;
}
}
/// <summary>
/// Returns a list of known serial devices (not necessarily GPS devices).
/// </summary>
public static IList<SerialDevice> SerialDevices
{
get
{
if (_SerialDevices == null)
_SerialDevices = new List<SerialDevice>(SerialDevice.Cache);
return _SerialDevices;
}
}
/// <summary>
/// Controls the amount of time allowed for device detection to complete before it is aborted.
/// </summary>
public static TimeSpan DeviceDetectionTimeout
{
get
{
return _DeviceDetectionTimeout;
}
set
{
// Valid8
if (value.TotalMilliseconds <= 0)
{
#if !PocketPC
throw new ArgumentOutOfRangeException("DeviceDetectionTimeout", value, "The total timeout for device detection must be a value greater than zero. Typically, about ten seconds are required to complete detection.");
#else
throw new ArgumentOutOfRangeException("DeviceDetectionTimeout", "The total timeout for device detection must be a value greater than zero. Typically, about ten seconds are required to complete detection.");
#endif
}
// Set the new value
_DeviceDetectionTimeout = value;
}
}
#if PocketPC
/// <summary>
/// Returns the current GPS multiplexer if it is supported by the system.
/// </summary>
public static GpsIntermediateDriver GpsIntermediateDriver
{
get { return GpsIntermediateDriver.Current; }
}
/// <summary>
/// Controls whether the GPS Intermediate Driver is used.
/// </summary>
public static bool AllowGpsIntermediateDriver
{
get { return _AllowGpsIntermediateDriver; }
set { _AllowGpsIntermediateDriver = value; }
}
#endif
/// <summary>
/// Controls whether detection is aborted once one device has been found.
/// </summary>
public static bool IsOnlyFirstDeviceDetected
{
get
{
return _IsOnlyFirstDeviceDetected;
}
set
{
_IsOnlyFirstDeviceDetected = value;
}
}
/// <summary>
/// Controls whether the system clock should be synchronized to GPS-derived date and time.
/// </summary>
public static bool IsClockSynchronizationEnabled
{
get { return _IsClockSynchronizationEnabled; }
set { _IsClockSynchronizationEnabled = value; }
}
/// <summary>
/// Controls whether the Bluetooth receiver is on and accepting connections.
/// </summary>
public static bool IsBluetoothEnabled
{
get
{
/* We can get the state of the radio if it's a Microsoft stack.
* Thankfully, Microsoft BT stacks are part of Wista, Wnidows 7, and
* Windows Mobile 5+, making it very common. However, it's still in 2nd
* place behind Broadcom (Widcomm). Though, I doubt this will last long.
* So, screw Broadcom.
*/
#if PocketPC
GeoFramework.Gps.IO.NativeMethods.BluetoothRadioMode mode =
GeoFramework.Gps.IO.NativeMethods.BluetoothRadioMode.PowerOff;
int errorCode = GeoFramework.Gps.IO.NativeMethods.BthGetMode(out mode);
if (errorCode != 0)
{
/* I get error "1359" (Internal error) on my HP iPaq 2945, which does NOT have a Microsoft Bluetooth stack.
* I'm guessing that this API just isn't supported on the Widcomm stack. Rather
* than throw a fit, just gracefully indicate an Off radio. This will prevent
* BT functions in GPS.NET.
*/
return false;
}
/* Connectable and Discoverable both mean "ON". The only difference is that a
* "discoverable" Bluetooth radio can be seen by other devices.
*/
return mode != GeoFramework.Gps.IO.NativeMethods.BluetoothRadioMode.PowerOff;
#else
return BluetoothRadio.Current != null
&& BluetoothRadio.Current.IsConnectable;
#endif
}
set
{
#if PocketPC
// Convert the boolean to a numeric mode
GeoFramework.Gps.IO.NativeMethods.BluetoothRadioMode mode =
value ? GeoFramework.Gps.IO.NativeMethods.BluetoothRadioMode.Connectable
: GeoFramework.Gps.IO.NativeMethods.BluetoothRadioMode.PowerOff;
// Set the new mode
int result = GeoFramework.Gps.IO.NativeMethods.BthSetMode(mode);
if (result != 0)
{
// throw new Win32Exception(result);
}
#else
// TODO: Add support for turning the Bluetooth radio on or off on the desktop.
#endif
}
}
/// <summary>
/// Returns whether the Bluetooth stack on the local machine is supported by GPS.NET.
/// </summary>
public static bool IsBluetoothSupported
{
get
{
#if PocketPC
try
{
// TODO: Is there any more specific way to detect MICROSOFT bluetooth without falsely detecting a stack which doesn't support sockets?
// Try and get the Bluetooth Radio status
GeoFramework.Gps.IO.NativeMethods.BluetoothRadioMode mode =
GeoFramework.Gps.IO.NativeMethods.BluetoothRadioMode.PowerOff;
int errorCode = GeoFramework.Gps.IO.NativeMethods.BthGetMode(out mode);
// If there's no error, we can proceed.
return errorCode == 0;
}
catch
{
// Nope, not supported
return false;
}
#else
/* The Microsoft Bluetooth stack provides an API used to enumerate all of the
* "radios" on the local machine. A "radio" is just a Bluetooth transmitter.
* A vast majority of people will only have one radio; multiple radios would happen
* if, say, somebody had two USB Bluetooth dongles plugged in.
*
* We can confirm that Bluetooth is supported by looking for a local radio.
* This method will return immediately with a non-zero handle if one exists.
*/
return BluetoothRadio.Current != null;
#endif
}
}
/// <summary>
/// Returns whether a GPS device has been found.
/// </summary>
public static bool IsDeviceDetected
{
get
{
return _GpsDevices.Count != 0;
}
}
/// <summary>
/// Returns whether the process of finding a GPS device is still working.
/// </summary>
public static bool IsDetectionInProgress
{
get
{
#if !PocketPC
return _DetectionThread != null && _DetectionThread.IsAlive;
#else
return _DetectionThread != null && _IsDetectionThreadAlive;
#endif
}
}
/// <summary>
/// Controls the current location on Earth's surface.
/// </summary>
public static Position Position
{
get { return _Position; }
set
{
// Has anything actually changed?
if(_Position.Equals(value))
return;
// Yes.
_Position = value;
// Raise an event
if(PositionChanged != null)
PositionChanged(null, new PositionEventArgs(_Position));
}
}
/// <summary>
/// Controls the current rate of travel.
/// </summary>
public static Speed Speed
{
get { return _Speed; }
set
{
// Has anything actually changed?
if (_Speed.Equals(value))
return;
// Yes.
_Speed = value;
// Raise an event
if (SpeedChanged != null)
SpeedChanged(null, new SpeedEventArgs(_Speed));
}
}
/// <summary>
/// Controls the current list of GPS satellites.
/// </summary>
public static List<Satellite> Satellites
{
get { return _Satellites; }
set
{
// Look for changes. A quick check is for a varying number of
// items in the list.
bool isChanged = _Satellites.Count != value.Count;
// Has anything changed?
if (!isChanged)
{
// No. Yet, the lists match counts. Compare them
for (int index = 0; index < _Satellites.Count; index++)
{
if (!_Satellites[index].Equals(value[index]))
{
// The object has changed
isChanged = true;
break;
}
}
}
if (!isChanged)
return;
// Set the new value
_Satellites = value;
// Raise an event
if (SatellitesChanged != null)
SatellitesChanged(null, new SatelliteListEventArgs(_Satellites));
}
}
/// <summary>
/// Controls the current satellite-derived date and time.
/// </summary>
public static DateTime UtcDateTime
{
get { return _UtcDateTime; }
set
{
// Has anything actually changed?
if (_UtcDateTime.Equals(value))
return;
// Yes.
_UtcDateTime = value;
// Raise an event
if (UtcDateTimeChanged != null)
UtcDateTimeChanged(null, new DateTimeEventArgs(_UtcDateTime));
}
}
/// <summary>
/// Controls the current satellite-derived date and time.
/// </summary>
public static DateTime DateTime
{
get
{
return _UtcDateTime.ToLocalTime();
}
set
{
UtcDateTime = value.ToUniversalTime();
}
}
/// <summary>
/// Controls the current distance above sea level.
/// </summary>
public static Distance Altitude
{
get { return _Altitude; }
set
{
// Has anything actually changed?
if (_Altitude.Equals(value))
return;
// Yes.
_Altitude = value;
// Raise an event
if (AltitudeChanged != null)
AltitudeChanged(null, new DistanceEventArgs(_Altitude));
}
}
/// <summary>
/// Controls the current direction of travel.
/// </summary>
public static Azimuth Bearing
{
get { return _Bearing; }
set
{
// Has anything actually changed?
if (_Bearing.Equals(value))
return;
// Yes.
_Bearing = value;
// Raise an event
if (BearingChanged != null)
BearingChanged(null, new AzimuthEventArgs(_Bearing));
}
}
#endregion
#region Static Methods
/// <summary>
/// Aborts the process of finding GPS devices and blocks until the cancellation is complete.
/// </summary>
public static void CancelDetection()
{
CancelDetection(false);
}
/// <summary>
/// Aborts the process of finding GPS devices and optionally blocks until the cancellation is complete.
/// </summary>
/// <param name="async">
/// If set to <see langword="true"/>, then the method will return immediately rather than waiting
/// for the cancellation to complete.
/// </param>
public static void CancelDetection(bool async)
{
// If the detection thread is alive, abort it
if (IsDetectionInProgress)
{
// Abort the thread
Debug.WriteLine("Canceling device detection", DebugCategory);
_DetectionThread.Abort(async);
if (!async)
{
// Wait for the abort to wrap up
_DetectionCompleteWaitHandle.WaitOne();
}
// Detection is complete
Debug.WriteLine("Device detection has been canceled successfully", DebugCategory);
OnDeviceDetectionCompleted();
}
}
/// <summary>
/// Starts looking for GPS devices on a separate thread.
/// </summary>
public static void BeginDetection()
{
// Start detection on another thread.
if (_IsDetectionInProgress)
return;
// Signal that detection is in progress
_IsDetectionInProgress = true;
// Start a thread for managing detection
_DetectionThread = new Thread(new ThreadStart(DetectionThreadProc));
_DetectionThread.Name = "GPS.NET Device Detector (http://www.geoframeworks.com)";
_DetectionThread.IsBackground = true;
#if !PocketPC
// Do detection in the background
_DetectionThread.Priority = ThreadPriority.Lowest;
#endif
_DetectionThread.Start();
#if PocketPC
// Signal that the thread is alive (no Thread.IsAlive on the CF :P)
_IsDetectionThreadAlive = true;
#endif
}
/// <summary>
/// Cancels detection and removes any cached information about known devices.
/// Use the <see cref="BeginDetection"/> method to re-detect devices and re-create the device cache.
/// </summary>
public static void Undetect()
{
// Undetect all devices (even non-GPS devices) and clear their cache
foreach (Device device in _BluetoothDevices)
device.Undetect();
foreach (Device device in _SerialDevices)
device.Undetect();
#if PocketPC
if (GpsIntermediateDriver.Current != null)
GpsIntermediateDriver.Current.Undetect();
#endif
try
{
// Clear any remaining entries in the device cache by deleting the root registry key
Registry.LocalMachine.DeleteSubKeyTree(RootKeyName);
}
catch (UnauthorizedAccessException)
{ }
ClearDeviceCache();
}
/// <summary>
/// Waits for any GPS device to be detected.
/// </summary>
/// <returns></returns>
public static bool WaitForDevice()
{
return WaitForDevice(DeviceDetectionTimeout);
}
/// <summary>
/// Waits for any GPS device to be detected up to the specified timeout period.
/// </summary>
/// <returns></returns>
public static bool WaitForDevice(TimeSpan timeout)
{
// Is a device already detected? If so, just exit
if (IsDeviceDetected)
return true;
// Is detection in progress? If so, wait until the timeout, or a device is found
if (IsDetectionInProgress)
{
#if !PocketPC
// Wait for either a device to be detected, or for detection to complete
ManualResetEvent[] waiters = new ManualResetEvent[] {
_DetectionCompleteWaitHandle, _DeviceDetectedWaitHandle };
ManualResetEvent.WaitAny(waiters, timeout);
#else
/* Mobile devices don't support "WaitAny" to wait on two wait handles. In rare
* cases, detection may have nothing to do. So, wait briefly for the entire thread
* to exit.
*/
// Wait briefly for the entire thread to exit
if (_DetectionCompleteWaitHandle.WaitOne(2000, false))
return IsDeviceDetected;
// Wait longer for a device to be found
_DeviceDetectedWaitHandle.WaitOne((int)timeout.TotalMilliseconds, false);
#endif
}
// No GPS device is known, and detection is not in progress
return IsDeviceDetected;
}
/// <summary>
/// Waits for device detection to complete.
/// </summary>
/// <returns></returns>
public static bool WaitForDetection()
{
return WaitForDetection(DeviceDetectionTimeout);
}
/// <summary>
/// Waits for device detection to complete up to the specified timeout period.
/// </summary>
/// <returns></returns>
public static bool WaitForDetection(TimeSpan timeout)
{
if (!IsDetectionInProgress)
return true;
#if PocketPC
return _DetectionCompleteWaitHandle.WaitOne((int)timeout.TotalMilliseconds, false);
#else
return _DetectionCompleteWaitHandle.WaitOne(timeout, false);
#endif
}
/// <summary>
/// Raises the <see cref="FixLost"/> event.
/// </summary>
internal static void RaiseFixLost(DeviceEventArgs e)
{
EventHandler<DeviceEventArgs> handler = FixLost;
if (handler != null)
{
handler(null, e);
}
}
/// <summary>
/// Raises the <see cref="FixAcquired"/> event.
/// </summary>
internal static void RaiseFixAcquired(DeviceEventArgs e)
{
EventHandler<DeviceEventArgs> handler = FixAcquired;
if (handler != null)
{
handler(null, e);
}
}
#endregion
#region Private Methods
private static void BluetoothDevice_DeviceDiscovered(object sender, DeviceEventArgs e)
{
/* When this event occurs, a new Bluetooth device has been found. Check
* to see if the device is already in our list of known devices.
*/
BluetoothDevice newDevice = (BluetoothDevice)e.Device;
// Examine each known device
for (int index = 0; index < _BluetoothDevices.Count; index++)
{
BluetoothDevice device = _BluetoothDevices[index];
// Is it the same address as this new device?
if (device.Address.Equals(newDevice.Address))
{
// Yes. No need to add it again. Get rid of it.
newDevice.Dispose();
return;
}
}
// If we get here, the device is brand new. Add it to the list