Repository navigation
Expand file tree
/
Copy pathDeviceListActivity.cs
More file actions
2206 lines (2021 loc) · 93.2 KB
/
Copy pathDeviceListActivity.cs
File metadata and controls
2206 lines (2021 loc) · 93.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
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) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Android.Bluetooth;
using Android.Content;
using Android.OS;
using Android.Views;
using Android.Widget;
using EdiabasLib;
using Android.Text.Method;
using Android.Content.PM;
using AndroidX.AppCompat.App;
using AndroidX.Core.App;
using AndroidX.Core.Content;
using BmwDeepObd.Dialogs;
namespace BmwDeepObd
{
/// <summary>
/// This Activity appears as a dialog. It lists any paired devices and
/// devices detected in the area after discovery. When a device is chosen
/// by the user, the MAC address of the device is sent back to the parent
/// Activity in the result Intent.
/// </summary>
[Android.App.Activity (Label = "@string/select_device",
Name = ActivityCommon.AppNameSpace + "." + nameof(DeviceListActivity),
ConfigurationChanges = ActivityConfigChanges)]
public class DeviceListActivity : BaseActivity, View.IOnClickListener
{
enum BtOperation
{
SelectAdapter, // select the adapter
PairDevice, // pair device
UnpairDevice, // unpair device
ConnectObd, // connect device as OBD
ConnectPhone, // connect device as phone
DisconnectPhone, // disconnect phone
DeleteDevice, // delete device
}
public class InstanceData
{
public bool BtPermissionWarningShown { get; set; }
public bool LocationProviderShown { get; set; }
public bool MtcAntennaInfoShown { get; set; }
public bool MtcBtModuleErrorShown { get; set; }
public bool MtcFirmwareErrorShown { get; set; }
public bool MtcBtPwdMismatchShown { get; set; }
public bool MtcBtEscapeModeShown { get; set; }
public bool MtcErrorShown { get; set; }
public bool MtcOffline { get; set; }
}
private static readonly Java.Util.UUID SppUuid = Java.Util.UUID.FromString("00001101-0000-1000-8000-00805F9B34FB");
private static readonly Java.Util.UUID ZeroUuid = Java.Util.UUID.FromString("00000000-0000-0000-0000-000000000000");
private const string DefaultModulePwd = "1234";
private const string InvalidHtcFwName = "hct2.20221115";
private const string InvalidHtcFwUpdateLink = "https://xtrons.ibus-app.de/index.php?title=Aktuelle_Firmware#Xtrons_Android_12.0_Octacore_Xtrons_ROM_IQ-Serie_[Qualcomm_665]";
private const string InvalidHtcFwHowToLink = "https://xtrons.ibus-app.de/index.php?title=Firmwareupdate";
// Return Intent extra
#if DEBUG
private static readonly string Tag = typeof(DeviceListActivity).FullName;
#endif
public const string ExtraAppDataDir = "app_data_dir";
public const string ExtraDeviceName = "device_name";
public const string ExtraDeviceAddress = "device_address";
public const string ExtraCallAdapterConfig = "adapter_configuration";
// Member fields
private InstanceData _instanceData = new InstanceData();
private AdapterTypeDetect _adapterTypeDetect;
private Thread _detectThread;
private BluetoothAdapter _btAdapter;
private BtLeGattSpp _btLeGattSpp;
private Timer _deviceUpdateTimer;
private ListView _pairedListView;
private ArrayAdapter<string> _pairedDevicesArrayAdapter;
private View _pairedViewClick;
private ListView _newDevicesListView;
private ArrayAdapter<string> _newDevicesArrayAdapter;
private View _newDevicesViewClick;
private Receiver _receiver;
private ProgressBar _progressBar;
private TextView _textViewTitlePairedDevices;
private Button _scanButton;
private Button _btSettingsButton;
private ActivityCommon _activityCommon;
private string _appDataDir;
private ManualResetEvent _transmitCancelEvent;
private AutoResetEvent _connectedEvent;
private volatile string _connectDeviceAddress = string.Empty;
private bool _btPermissionRequested;
private bool _btPermissionGranted;
private enum ActivityRequest
{
RequestBluetoothSettings,
RequestLocationSettings,
RequestAppDetailSettings,
}
protected override void OnCreate (Bundle savedInstanceState)
{
SetTheme();
base.OnCreate (savedInstanceState);
_allowFullScreenMode = false;
if (savedInstanceState != null)
{
_instanceData = GetInstanceState(savedInstanceState, _instanceData) as InstanceData;
}
SupportActionBar.SetHomeButtonEnabled(true);
SupportActionBar.SetDisplayShowHomeEnabled(true);
SupportActionBar.SetDisplayHomeAsUpEnabled(true);
// Setup the window
SetContentView(Resource.Layout.device_list);
// Set result CANCELED incase the user backs out
SetResult (Android.App.Result.Canceled);
_transmitCancelEvent = new ManualResetEvent(false);
_connectedEvent = new AutoResetEvent(false);
// ReSharper disable once UseObjectOrCollectionInitializer
_activityCommon = new ActivityCommon(this, () =>
{
if (_activityCommon.MtcBtServiceBound)
{
UpdateMtcDevices();
}
},
(context, intent) =>
{
if (_activityCommon == null)
{
return;
}
if (intent != null && intent.Action == GlobalBroadcastReceiver.NotificationBroadcastAction)
{
if (intent.HasExtra(GlobalBroadcastReceiver.BtScanFinished))
{
#if DEBUG
Android.Util.Log.Info(Tag, "BtScanFinished");
#endif
ShowScanState(false);
}
}
});
_activityCommon.SelectedInterface = ActivityCommon.InterfaceType.Bluetooth;
_appDataDir = Intent.GetStringExtra(ExtraAppDataDir);
_progressBar = FindViewById<ProgressBar>(Resource.Id.progress_bar);
_textViewTitlePairedDevices = FindViewById<TextView>(Resource.Id.title_paired_devices);
// Initialize the button to perform device discovery
_scanButton = FindViewById<Button>(Resource.Id.button_scan);
_scanButton.Click += (sender, e) =>
{
if (_activityCommon.MtcBtServiceBound)
{
DoMtcDiscovery();
}
else
{
DoDiscovery();
}
};
_btSettingsButton = FindViewById<Button>(Resource.Id.button_bt_settings);
_btSettingsButton.Visibility = _activityCommon.MtcBtService ? ViewStates.Gone : ViewStates.Visible;
_btSettingsButton.Click += (sender, e) =>
{
OpenBluetoothSettings();
};
// Initialize array adapters. One for already paired devices and
// one for newly discovered devices
_pairedDevicesArrayAdapter = new ArrayAdapter<string> (this, Resource.Layout.device_name);
_newDevicesArrayAdapter = new ArrayAdapter<string> (this, Resource.Layout.device_name);
// Find and set up the ListView for paired devices
_pairedListView = FindViewById<ListView> (Resource.Id.paired_devices);
_pairedListView.Adapter = _pairedDevicesArrayAdapter;
_pairedListView.ItemClick += (sender, args) =>
{
DeviceListClick(sender, args, true);
};
_pairedViewClick = FindViewById<View>(Resource.Id.paired_devices_click);
_pairedViewClick.SetOnClickListener(this);
// Find and set up the ListView for newly discovered devices
_newDevicesListView = FindViewById<ListView> (Resource.Id.new_devices);
_newDevicesListView.Adapter = _newDevicesArrayAdapter;
//pairedListView.SetOnClickListener(this);
_newDevicesListView.ItemClick += (sender, args) =>
{
DeviceListClick(sender, args, false);
};
_newDevicesViewClick = FindViewById<View>(Resource.Id.new_devices_click);
_newDevicesViewClick.SetOnClickListener(this);
// Register for broadcasts when a device is discovered
_receiver = new Receiver (this);
var filter = new IntentFilter (BluetoothDevice.ActionFound);
RegisterReceiver (_receiver, filter); // system broadcasts
// Register for broadcasts when a device name changed
filter = new IntentFilter(BluetoothDevice.ActionNameChanged);
RegisterReceiver(_receiver, filter); // system broadcasts
// Register for broadcasts when discovery has finished
filter = new IntentFilter (BluetoothAdapter.ActionDiscoveryFinished);
RegisterReceiver (_receiver, filter); // system broadcasts
// register device changes
filter = new IntentFilter();
filter.AddAction(BluetoothDevice.ActionAclConnected);
filter.AddAction(BluetoothDevice.ActionAclDisconnected);
filter.AddAction(BluetoothDevice.ActionBondStateChanged);
RegisterReceiver(_receiver, filter); // system broadcasts
_adapterTypeDetect = new AdapterTypeDetect(_activityCommon);
// Get the local Bluetooth adapter
_btAdapter = _activityCommon.BtAdapter;
_btLeGattSpp = new BtLeGattSpp(LogString);
// Get a set of currently paired devices
if (!_activityCommon.MtcBtService)
{
UpdatePairedDevices();
}
}
private void _btSettingsButton_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
protected override void OnSaveInstanceState(Bundle outState)
{
StoreInstanceState(outState, _instanceData);
base.OnSaveInstanceState(outState);
}
protected override void OnStart()
{
base.OnStart();
_btPermissionRequested = false;
_btPermissionGranted = false;
_transmitCancelEvent.Reset();
if (_activityCommon != null)
{
if (_activityCommon.MtcBtService)
{
_activityCommon.StartMtcService();
}
_activityCommon?.RequestUsbPermission(null);
}
}
protected override void OnResume()
{
base.OnResume();
RequestBtPermissions();
if (_activityCommon.MtcBtService)
{
if (_deviceUpdateTimer == null)
{
_deviceUpdateTimer = new Timer(state =>
{
RunOnUiThread(() =>
{
if (_activityCommon == null)
{
return;
}
UpdateMtcDevices();
});
}, null, 1000, 5000);
}
}
else
{
UpdatePairedDevices();
}
}
protected override void OnPause()
{
base.OnPause();
DisposeTimer();
}
protected override void OnStop()
{
base.OnStop();
if (_activityCommon != null && _activityCommon.MtcBtService)
{
MtcStopScan();
_activityCommon.StopMtcService();
}
}
protected override void OnDestroy ()
{
base.OnDestroy ();
if (IsJobRunning())
{
_detectThread?.Join();
}
// Make sure we're not doing discovery anymore
try
{
_btAdapter?.CancelDiscovery();
}
#pragma warning disable 168
catch (Exception ex)
#pragma warning restore 168
{
// ignored
#if DEBUG
Android.Util.Log.Info(Tag, string.Format("OnDestroy exception: {0}", EdiabasNet.GetExceptionText(ex)));
#endif
}
DisposeTimer();
if (_btLeGattSpp != null)
{
_btLeGattSpp.Dispose();
_btLeGattSpp = null;
}
// Unregister broadcast listeners
UnregisterReceiver(_receiver);
if (_activityCommon != null)
{
_activityCommon.Dispose();
_activityCommon = null;
}
if (_connectedEvent != null)
{
_connectedEvent.Dispose();
_connectedEvent = null;
}
if (_transmitCancelEvent != null)
{
_transmitCancelEvent.Dispose();
_transmitCancelEvent = null;
}
}
public void OnClick(View v)
{
MtcManualAddressEntry();
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
case Android.Resource.Id.Home:
Finish();
return true;
}
return base.OnOptionsItemSelected(item);
}
public override bool IsFinishAllowed()
{
if (IsJobRunning())
{
return false;
}
return true;
}
protected override void OnActivityResult(int requestCode, Android.App.Result resultCode, Intent data)
{
switch ((ActivityRequest)requestCode)
{
case ActivityRequest.RequestBluetoothSettings:
UpdatePairedDevices();
break;
case ActivityRequest.RequestLocationSettings:
break;
case ActivityRequest.RequestAppDetailSettings:
break;
}
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
if (_activityCommon == null)
{
return;
}
switch (requestCode)
{
case ActivityCommon.RequestPermissionBluetooth:
if (grantResults.Length > 0 && grantResults.All(permission => permission == Permission.Granted))
{
BtPermissionGranted();
break;
}
if (!_instanceData.BtPermissionWarningShown)
{
_instanceData.BtPermissionWarningShown = true;
new AlertDialog.Builder(this)
.SetPositiveButton(Resource.String.button_yes, (sender, args) =>
{
ActivityCommon.OpenAppSettingDetails(this, (int) ActivityRequest.RequestAppDetailSettings);
})
.SetNegativeButton(Resource.String.button_no, (sender, args) =>
{
})
.SetCancelable(true)
.SetMessage(Resource.String.access_permission_rejected)
.SetTitle(Resource.String.alert_title_warning)
.Show();
}
break;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Interoperability", "CA1416: Validate platform compatibility")]
private void RequestBtPermissions()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.Q)
{
return;
}
if (_btPermissionRequested || _btPermissionGranted)
{
return;
}
string[] requestPermissions = Build.VERSION.SdkInt < BuildVersionCodes.S ? ActivityCommon.PermissionsFineLocation : ActivityCommon.PermissionsBluetooth;
if (requestPermissions.All(permission => ContextCompat.CheckSelfPermission(this, permission) == Permission.Granted))
{
BtPermissionGranted();
return;
}
_btPermissionRequested = true;
ActivityCompat.RequestPermissions(this, requestPermissions, ActivityCommon.RequestPermissionBluetooth);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Interoperability", "CA1416: Validate platform compatibility")]
private void BtPermissionGranted()
{
_btPermissionGranted = true;
if (Build.VERSION.SdkInt >= BuildVersionCodes.Q && Build.VERSION.SdkInt < BuildVersionCodes.S)
{
if (_activityCommon.LocationManager != null)
{
try
{
if (!_activityCommon.LocationManager.IsLocationEnabled)
{
if (!_instanceData.LocationProviderShown)
{
_instanceData.LocationProviderShown = true;
new AlertDialog.Builder(this)
.SetPositiveButton(Resource.String.button_yes, (sender, args) =>
{
ActivityCommon.OpenLocationSettings(this, (int)ActivityRequest.RequestLocationSettings);
})
.SetNegativeButton(Resource.String.button_no, (sender, args) =>
{
})
.SetCancelable(true)
.SetMessage(Resource.String.location_provider_disabled_bt)
.SetTitle(Resource.String.alert_title_warning)
.Show();
}
}
}
catch (Exception)
{
// ignored
}
}
}
}
private void UpdatePairedDevices()
{
try
{
// If there are paired devices, add each one to the ArrayAdapter
_pairedDevicesArrayAdapter.Clear();
// Get a set of currently paired devices
ICollection<BluetoothDevice> pairedDevices = _btAdapter.BondedDevices;
if (pairedDevices?.Count > 0)
{
foreach (BluetoothDevice device in pairedDevices)
{
if (device == null)
{
continue;
}
try
{
_pairedDevicesArrayAdapter.Add(device.Name + "\n" + device.Address);
}
catch (Exception)
{
// ignored
}
}
}
if (_pairedDevicesArrayAdapter.Count == 0)
{
// ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
if (_btAdapter.IsEnabled)
{
_pairedDevicesArrayAdapter.Add(Resources.GetText(Resource.String.none_paired));
}
else
{
_pairedDevicesArrayAdapter.Add(Resources.GetText(Resource.String.bt_not_enabled));
}
}
}
#pragma warning disable 168
catch (Exception ex)
#pragma warning restore 168
{
// ignored
#if DEBUG
Android.Util.Log.Info(Tag, string.Format("UpdatePairedDevices exception: {0}", EdiabasNet.GetExceptionText(ex)));
#endif
}
}
private void DisposeTimer()
{
if (_deviceUpdateTimer != null)
{
_deviceUpdateTimer.Dispose();
_deviceUpdateTimer = null;
}
}
private static bool IsBtDeviceValid(BluetoothDevice device)
{
ParcelUuid[] uuids = device?.GetUuids();
List<Java.Util.UUID> uuidList = new List<Java.Util.UUID>();
if (uuids != null)
{
#if DEBUG
Android.Util.Log.Info(Tag, "IsBtDeviceValid: Name: {0}", device.Name ?? string.Empty);
#endif
foreach (ParcelUuid parcelUuid in uuids)
{
if (parcelUuid.Uuid != null && ZeroUuid.CompareTo(parcelUuid.Uuid) != 0)
{
uuidList.Add(parcelUuid.Uuid);
#if DEBUG
Android.Util.Log.Info(Tag, "IsBtDeviceValid: UUID: {0}", parcelUuid.Uuid.ToString());
#endif
}
}
}
if (uuidList.Count == 0)
{
return true;
}
return uuidList.Any(uuid => SppUuid.CompareTo(uuid) == 0);
}
private void UpdateMtcDevices()
{
_pairedDevicesArrayAdapter.Clear();
_newDevicesArrayAdapter.Clear();
if (!_activityCommon.MtcBtServiceBound)
{
#if DEBUG
Android.Util.Log.Info(Tag, "UpdateMtcDevices: Service not bound");
#endif
return;
}
MtcServiceConnection mtcServiceConnection = _activityCommon.MtcServiceConnection;
try
{
FindViewById<View>(Resource.Id.layout_new_devices).Visibility = ViewStates.Visible;
bool autoConnect = mtcServiceConnection.GetAutoConnect();
string modulePwd = mtcServiceConnection.GetModulePassword() ?? string.Empty;
#if DEBUG
string moduleName = mtcServiceConnection.GetModuleName() ?? string.Empty;
string btPin = mtcServiceConnection.CarManagerGetBtPin() ?? string.Empty;
string btName = mtcServiceConnection.CarManagerGetBtName() ?? string.Empty;
sbyte btState = mtcServiceConnection.GetBtState();
Android.Util.Log.Info(Tag, string.Format("UpdateMtcDevices: api={0}, time={1:yyyy-MM-dd HH:mm:ss}", mtcServiceConnection.ApiVersion, DateTime.Now));
Android.Util.Log.Info(Tag, string.Format("BtState: {0}", btState));
Android.Util.Log.Info(Tag, string.Format("AutoConnect: {0}", autoConnect));
Android.Util.Log.Info(Tag, string.Format("Module Pwd: {0}", modulePwd));
Android.Util.Log.Info(Tag, string.Format("Module Name: {0}", moduleName));
Android.Util.Log.Info(Tag, string.Format("Bt Pin: {0}", btPin));
Android.Util.Log.Info(Tag, string.Format("Bt Name: {0}", btName));
#endif
bool oldOffline = _instanceData.MtcOffline;
bool newOffline = false;
if (!autoConnect)
{
mtcServiceConnection.SetAutoConnect(true);
if (!mtcServiceConnection.GetAutoConnect())
{
newOffline = true;
}
}
_instanceData.MtcOffline = newOffline;
#if DEBUG
Android.Util.Log.Info(Tag, string.Format("MTC offline: {0}", _instanceData.MtcOffline));
#endif
if (_instanceData.MtcOffline)
{
if (!_instanceData.MtcErrorShown)
{
_instanceData.MtcErrorShown = true;
_activityCommon.ShowAlert(GetString(Resource.String.bt_mtc_service_error), Resource.String.alert_title_warning);
}
UpdatePairedDevices();
ShowScanState(false);
return;
}
StringBuilder sbTitle = new StringBuilder();
sbTitle.Append(GetString(Resource.String.title_paired_devices));
if (!string.IsNullOrEmpty(_activityCommon.MtcBtModuleName))
{
sbTitle.Append(" ");
sbTitle.Append(string.Format(CultureInfo.InvariantCulture, GetString(Resource.String.bt_module_name), _activityCommon.MtcBtModuleName));
}
string titlePairedDevices = sbTitle.ToString();
if (_textViewTitlePairedDevices.Text != titlePairedDevices)
{
_textViewTitlePairedDevices.Text = titlePairedDevices;
}
#if false
if (!_instanceData.MtcAntennaInfoShown && !string.IsNullOrEmpty(_activityCommon.MtcBtModuleName) &&
string.Compare(_activityCommon.MtcBtModuleName, "WQ_BC6", StringComparison.OrdinalIgnoreCase) == 0)
{
_instanceData.MtcAntennaInfoShown = true;
_activityCommon.ShowAlert(GetString(Resource.String.bt_mtc_antenna_info), Resource.String.alert_title_info);
}
#endif
#if false
if (!_instanceData.MtcBtModuleErrorShown && !string.IsNullOrEmpty(_activityCommon.MtcBtModuleName) &&
string.Compare(_activityCommon.MtcBtModuleName, "FSC-BW124", StringComparison.OrdinalIgnoreCase) == 0)
{
_instanceData.MtcBtModuleErrorShown = true;
_activityCommon.ShowAlert(GetString(Resource.String.bt_mtc_module_error), Resource.String.alert_title_warning);
}
#endif
if (!_instanceData.MtcFirmwareErrorShown && !string.IsNullOrEmpty(Build.Fingerprint))
{
if (Build.Fingerprint.Contains(InvalidHtcFwName, StringComparison.OrdinalIgnoreCase))
{
_instanceData.MtcFirmwareErrorShown = true;
string message = string.Format(CultureInfo.InvariantCulture, GetString(Resource.String.bt_mtc_firmware_error), InvalidHtcFwName, InvalidHtcFwUpdateLink, InvalidHtcFwHowToLink);
AlertDialog alertDialog = new AlertDialog.Builder(this)
.SetNeutralButton(Resource.String.button_ok, (sender, args) => { })
.SetCancelable(true)
.SetMessage(ActivityCommon.FromHtml(message))
.SetTitle(Resource.String.alert_title_warning)
.Show();
if (alertDialog != null)
{
TextView messageView = alertDialog.FindViewById<TextView>(Android.Resource.Id.Message);
if (messageView != null)
{
messageView.MovementMethod = new LinkMovementMethod();
}
}
}
}
if (!_instanceData.MtcBtPwdMismatchShown &&
!string.IsNullOrEmpty(modulePwd) && string.Compare(modulePwd, DefaultModulePwd, StringComparison.OrdinalIgnoreCase) != 0)
{
_instanceData.MtcBtPwdMismatchShown = true;
string message = string.Format(GetString(Resource.String.bt_mtc_module_pwd), modulePwd, DefaultModulePwd);
new AlertDialog.Builder(this)
.SetPositiveButton(Resource.String.button_yes, (sender, args) =>
{
try
{
mtcServiceConnection.SetModulePassword(DefaultModulePwd);
}
catch (Exception)
{
_instanceData.MtcBtPwdMismatchShown = false;
}
})
.SetNegativeButton(Resource.String.button_no, (sender, args) =>
{
})
.SetCancelable(true)
.SetMessage(message)
.SetTitle(Resource.String.alert_title_warning)
.Show();
}
else
{
if (!_instanceData.MtcBtEscapeModeShown && _activityCommon.MtcBtEscapeMode)
{
_instanceData.MtcBtEscapeModeShown = true;
string message = string.Format(GetString(Resource.String.bt_mtc_module_escape_mode), _activityCommon.MtcBtModuleName);
_activityCommon.ShowAlert(message, Resource.String.alert_title_info);
}
}
if (oldOffline != _instanceData.MtcOffline)
{
ShowScanState(false);
}
long nowDevAddr = mtcServiceConnection.GetNowDevAddr();
#if DEBUG
Android.Util.Log.Info(Tag, string.Format("NowDevAddr: {0}", nowDevAddr));
#endif
string nowDevAddrString = string.Format(CultureInfo.InvariantCulture, "{0:X012}", nowDevAddr);
IList<string> deviceList = mtcServiceConnection.GetDeviceList();
IList<string> matchList = mtcServiceConnection.GetMatchList();
int offset = mtcServiceConnection.ApiVersion < 2 ? 0 : 1;
if (matchList != null)
{
foreach (string device in matchList)
{
if (string.IsNullOrEmpty(device))
{
continue;
}
#if DEBUG
Android.Util.Log.Info(Tag, string.Format("MatchList: device={0}", device));
#endif
if (ExtractMtcDeviceInfo(offset, device, out string name, out string address))
{
#if DEBUG
Android.Util.Log.Info(Tag, string.Format("Extracted name={0}, address={1}", name, address));
#endif
string mac = address.Replace(":", string.Empty);
if (string.Compare(mac, nowDevAddrString, StringComparison.OrdinalIgnoreCase) == 0)
{
name += " " + GetString(Resource.String.bt_device_connected);
}
_pairedDevicesArrayAdapter.Add(name + "\n" + address);
}
}
}
if (_pairedDevicesArrayAdapter.Count == 0)
{
_pairedDevicesArrayAdapter.Add(Resources.GetText(Resource.String.none_paired));
}
if (deviceList != null)
{
foreach (string device in deviceList)
{
if (string.IsNullOrEmpty(device))
{
continue;
}
#if DEBUG
Android.Util.Log.Info(Tag, string.Format("DeviceList: device={0}", device));
#endif
if (ExtractMtcDeviceInfo(offset, device, out string name, out string address))
{
#if DEBUG
Android.Util.Log.Info(Tag, string.Format("Extracted name={0}, address={1}", name, address));
#endif
_newDevicesArrayAdapter.Add(name + "\n" + address);
}
}
}
if (_newDevicesArrayAdapter.Count == 0)
{
_newDevicesArrayAdapter.Add(Resources.GetText(Resource.String.none_found));
}
}
#pragma warning disable 168
catch (Exception ex)
#pragma warning restore 168
{
// ignored
#if DEBUG
Android.Util.Log.Info(Tag, string.Format("UpdateMtcDevices exception: {0}", EdiabasNet.GetExceptionText(ex)));
#endif
}
}
/// <summary>
/// Extract device info for MTC devices
/// </summary>
/// <param name="offset">MAC offset: 0, 1</param>
/// <param name="device">Complete device info text</param>
/// <param name="name">Device name</param>
/// <param name="address">Device address</param>
/// <returns>True: Success</returns>
private static bool ExtractMtcDeviceInfo(int offset, string device, out string name, out string address)
{
name = string.Empty;
address = string.Empty;
if (device.Length < offset + 12)
{
return false;
}
string mac = device.Substring(offset, 12);
StringBuilder sb = new StringBuilder();
address = string.Empty;
for (int i = 0; i < 12; i += 2)
{
if (sb.Length > 0)
{
sb.Append(":");
}
sb.Append(mac.Substring(i, 2));
}
address = sb.ToString();
name = device.Substring(offset + 12);
return true;
}
/// <summary>
/// MTC stop BT scan
/// </summary>
/// <returns>True if successful</returns>
// ReSharper disable once UnusedMethodReturnValue.Local
private bool MtcStopScan()
{
if (_activityCommon.MtcBtServiceBound)
{
try
{
_activityCommon.MtcServiceConnection.ScanStop();
return true;
}
catch (Exception)
{
return false;
}
}
return false;
}
/// <summary>
/// Show scan state
/// </summary>
/// <param name="enabled">True if scanning is enabled</param>
private void ShowScanState(bool enabled)
{
if (_activityCommon.MtcBtServiceBound && _instanceData.MtcOffline)
{
_progressBar.Visibility = ViewStates.Invisible;
SetTitle(Resource.String.select_device);
_scanButton.Enabled = false;
_btSettingsButton.Enabled = false;
return;
}
if (enabled)
{
_progressBar.Visibility = ViewStates.Visible;
SetTitle(Resource.String.scanning);
_scanButton.Enabled = false;
_btSettingsButton.Enabled = false;
}
else
{
_progressBar.Visibility = ViewStates.Invisible;
SetTitle(Resource.String.select_device);
_scanButton.Enabled = true;
_btSettingsButton.Enabled = true;
}
}
/// <summary>
/// Start device discover with the BluetoothAdapter
/// </summary>
private void DoDiscovery ()
{
// Log.Debug (Tag, "doDiscovery()");
try
{
_newDevicesArrayAdapter.Clear();
// If we're already discovering, stop it
if (_btAdapter.IsDiscovering)
{
_btAdapter.CancelDiscovery();
}
// Request discover from BluetoothAdapter
if (_btAdapter.StartDiscovery())
{
// Indicate scanning in the title
ShowScanState(true);
// Turn on area for new devices
FindViewById<View>(Resource.Id.layout_new_devices).Visibility = ViewStates.Visible;
}
else
{
OpenBluetoothSettings();
}
}
#pragma warning disable 168
catch (Exception ex)
#pragma warning restore 168
{
// ignored
#if DEBUG
Android.Util.Log.Info(Tag, string.Format("DoDiscovery Exception: {0}", EdiabasNet.GetExceptionText(ex)));
#endif
}
}
private bool OpenBluetoothSettings()
{
try
{
Intent intent = new Intent(Android.Provider.Settings.ActionBluetoothSettings);
StartActivityForResult(intent, (int)ActivityRequest.RequestBluetoothSettings);
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// Start MTC device discovery
/// </summary>
private void DoMtcDiscovery()
{
// Log.Debug (Tag, "doDiscovery()");
if (_activityCommon.MtcBtServiceBound)
{
try
{
_activityCommon.MtcServiceConnection.ScanStart();
// Indicate scanning in the title
ShowScanState(true);
// Turn on area for new devices
FindViewById<View>(Resource.Id.layout_new_devices).Visibility = ViewStates.Visible;
}
catch (Exception)
{
// ignored
}
}
}
/// <summary>