HDL Home App 第二版本 旧平台金堂用 正在使用
hxb
2022-08-29 9a4629512ccf8359efd88671c9317c3cc7faf0c8
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
using System;
using System.Collections.Generic;
using System.Text;
 
namespace Shared.Phone.UserCenter
{
#if Android
    public class HdlAndroidBluetoothLogic
    {
        #region ■ 变量声明___________________________
 
        /// <summary>
        /// 安卓蓝牙的逻辑
        /// </summary>
        private static HdlAndroidBluetoothLogic m_Current = null;
        /// <summary>
        /// 安卓蓝牙的逻辑
        /// </summary>
        public static HdlAndroidBluetoothLogic Current
        {
            get
            {
                if (m_Current == null)
                {
                    m_Current = new HdlAndroidBluetoothLogic();
                }
                return m_Current;
            }
        }
 
        /// <summary>
        /// 当前蓝牙客户端
        /// </summary>
        private Blufi.Espressif.BlufiClient nowBlufiClient = null;
        /// <summary>
        /// 发送状态(0:发送失败 1:发送成功)
        /// </summary>
        private int sendStatuValue = -1;
 
        #endregion
 
        #region ■ 蓝牙扫描___________________________
 
        /// <summary>
        /// 搜索蓝牙
        /// </summary>
        /// <param name="waitTime">搜索时间(秒)</param>
        /// <param name="FinishEvent">搜索结束的事件</param>
        public void ScanBluetooth(int waitTime, Action<List<BluetoothInfo>> FinishEvent)
        {
            //读取蓝牙权限
            ((BaseActivity)Application.Activity).SetPermission((result1) =>
            {
                if (result1 == false) { return; }
                ((BaseActivity)Application.Activity).SetPermission((result2) =>
                {
                    if (result2 == false) { return; }
 
                    HdlThreadLogic.Current.RunThread(() =>
                    {
                        this.DoScanBluetooth(waitTime, FinishEvent);
                    });
                }, "android.permission.ACCESS_FINE_LOCATION");
 
            }, "android.permission.ACCESS_COARSE_LOCATION");
        }
 
        /// <summary>
        /// 开始搜索蓝牙
        /// </summary>
        /// <param name="waitTime">搜索时间(秒)</param>
        /// <param name="FinishEvent">搜索结束的事件</param>
        private void DoScanBluetooth(int waitTime, Action<List<BluetoothInfo>> FinishEvent)
        {
            ProgressBar.Show();
 
            var listBluetoothInfo = new List<BluetoothInfo>();
 
            var adapter = Android.Bluetooth.BluetoothAdapter.DefaultAdapter;
            var scanner = adapter.BluetoothLeScanner;
            if (adapter.IsEnabled == false || scanner == null)
            {
                HdlMessageLogic.Current.ShowMassage(ShowMsgType.Tip, "请打开蓝牙");
                ProgressBar.Close();
                return;
            }
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.M)
            {
                var locationManager = (Android.Locations.LocationManager)Application.Activity.GetSystemService(Android.Content.Context.LocationService);
                if (locationManager == null)
                {
                    HdlMessageLogic.Current.ShowMassage(ShowMsgType.Tip, "位置信息(GBS)不可用");
                    ProgressBar.Close();
                    return;
                }
                if (locationManager.IsProviderEnabled("network") == false || locationManager.IsProviderEnabled("gps") == false)
                {
                    HdlMessageLogic.Current.ShowMassage(ShowMsgType.Tip, "位置信息(GBS)不可用");
                    ProgressBar.Close();
                    return;
                }
            }
 
            var scanCallback = new BluetoothScanCallback();
            scanner.StartScan(null, new Android.Bluetooth.LE.ScanSettings.Builder().SetScanMode(Android.Bluetooth.LE.ScanMode.LowLatency).Build(), scanCallback);
 
            System.Threading.Thread.Sleep(waitTime * 1000);
 
            scanner.StopScan(scanCallback);
            adapter.Dispose();
 
            foreach (var data in scanCallback.listData)
            {
                listBluetoothInfo.Add(data);
            }
            scanCallback.listData.Clear();
 
            ProgressBar.Close();
 
            FinishEvent?.Invoke(listBluetoothInfo);
        }
 
        /// <summary>
        /// 蓝牙的回调对象
        /// </summary>
        private class BluetoothScanCallback : Android.Bluetooth.LE.ScanCallback
        {
            /// <summary>
            /// 蓝牙列表
            /// </summary>
            public List<BluetoothInfo> listData = new List<BluetoothInfo>();
            /// <summary>
            /// 重复检测
            /// </summary>
            private List<string> listCheck = new List<string>();
 
            /// <summary>
            /// 蓝牙结果接收
            /// </summary>
            /// <param name="listResult"></param>
            public override void OnBatchScanResults(IList<Android.Bluetooth.LE.ScanResult> listResult)
            {
                foreach (var result in listResult)
                {
                    this.AddBluetoothResult(result);
                }
            }
 
            /// <summary>
            /// 蓝牙结果接收
            /// </summary>
            /// <param name="callbackType"></param>
            /// <param name="result"></param>
            public override void OnScanResult(Android.Bluetooth.LE.ScanCallbackType callbackType, Android.Bluetooth.LE.ScanResult result)
            {
                this.AddBluetoothResult(result);
            }
 
            /// <summary>
            /// 添加蓝牙缓存
            /// </summary>
            /// <param name="result"></param>
            private void AddBluetoothResult(Android.Bluetooth.LE.ScanResult result)
            {
                var device = result.Device;
                if (device == null || listCheck.Contains(device.Address) == true)
                {
                    return;
                }
                listCheck.Add(device.Address);
 
                var data = new BluetoothInfo();
                data.Name = device.Name;
                if (data.Name == null) { data.Name = string.Empty; }
                data.Address = device.Address;
                data.Device = device;
                listData.Add(data);
            }
        }
 
        #endregion
 
        #region ■ 蓝牙链接___________________________
 
        /// <summary>
        /// 蓝牙链接(0:失败 1:成功)
        /// </summary>
        /// <param name="bluetooth">需要链接的蓝牙对象</param>
        /// <param name="StatuEvent">0:连接失败 1:连接成功</param>
        public void ContectBluetooth(BluetoothInfo bluetooth, Action<int> StatuEvent)
        {
            try
            {
                this.nowBlufiClient = new Blufi.Espressif.BlufiClient(Application.Activity, bluetooth.Device);
 
                //一个回调事件
                var callback = new InnerGattCallback();
                callback.ConnectionStateEvent += (div, newState) =>
                {
                    //OnConnectionStateChange
                    if (div == 1)
                    {
                        if (newState == Android.Bluetooth.ProfileState.Connected)
                        {
                            //链接建立成功
                            StatuEvent?.Invoke(1);
                        }
                        else if (newState == Android.Bluetooth.ProfileState.Disconnected)
                        {
                            //关闭链接
                            this.DisContectBluetooth();
                            StatuEvent?.Invoke(0);
                        }
                    }
                    else if (div == -1)
                    {
                        //关闭链接
                        this.DisContectBluetooth();
                        StatuEvent?.Invoke(0);
                    }
                };
                nowBlufiClient.SetGattCallback(callback);
 
                //另外一个回调事件
                var blufiCall = new BlufiCallbackMain();
                blufiCall.StateEvent += (div) =>
                {
                    //-1:异常 1:正常 2:发送数据成功 3:发送数据失败
                    if (div == -1)
                    {
                        //关闭链接
                        this.DisContectBluetooth();
                        StatuEvent?.Invoke(0);
                    }
                    if (div == 2 || div == 3)
                    {
                        sendStatuValue = div == 2 ? 1 : 0;
                    }
                };
                nowBlufiClient.SetBlufiCallback(blufiCall);
                //执行链接
                nowBlufiClient.Connect();
            }
            catch
            {
                StatuEvent?.Invoke(0);
            }
        }
 
        /// <summary>
        /// 先这么定义一个空的继承
        /// </summary>
        private class InnerGattCallback : Android.Bluetooth.BluetoothGattCallback
        {
            /// <summary>
            /// 状态事件回调(-1:异常 1:OnConnectionStateChange)
            /// </summary>
            public Action<int,Android.Bluetooth.ProfileState> ConnectionStateEvent = null;
            /// <summary>
            /// 链接状态改变
            /// </summary>
            /// <param name="gatt"></param>
            /// <param name="status"></param>
            /// <param name="newState"></param>
            public override void OnConnectionStateChange(Android.Bluetooth.BluetoothGatt gatt, Android.Bluetooth.GattStatus status, Android.Bluetooth.ProfileState newState)
            {
                if (status == Android.Bluetooth.GattStatus.Success)
                {
                    //回调事件
                    this.ConnectionStateEvent?.Invoke(1, newState);
                }
                else
                {
                    //回调事件
                    this.ConnectionStateEvent?.Invoke(-1, 0);
                }
            }
 
            /// <summary>
            /// 成功发现设备的services时,调用此方法
            /// </summary>
            /// <param name="gatt"></param>
            /// <param name="status"></param>
            public override void OnServicesDiscovered(Android.Bluetooth.BluetoothGatt gatt, Android.Bluetooth.GattStatus status)
            {
                if (status != Android.Bluetooth.GattStatus.Success)
                {
                    //回调事件
                    this.ConnectionStateEvent?.Invoke(-1, 0);
                }
            }
 
            /// <summary>
            /// 应该是写入事件吧
            /// </summary>
            /// <param name="gatt"></param>
            /// <param name="characteristic"></param>
            /// <param name="status"></param>
            public override void OnCharacteristicWrite(Android.Bluetooth.BluetoothGatt gatt, Android.Bluetooth.BluetoothGattCharacteristic characteristic, Android.Bluetooth.GattStatus status)
            {
                if (status != Android.Bluetooth.GattStatus.Success)
                {
                    //回调事件
                    this.ConnectionStateEvent?.Invoke(-1, 0);
                }
            }
        }
 
        /// <summary>
        /// 抄SDK的,我也不知道这个是什么
        /// </summary>
        private class BlufiCallbackMain : Blufi.Espressif.BlufiCallback
        {
            /// <summary>
            /// 状态事件回调(-1:异常 1:正常 2:发送数据成功 3:发送数据失败)
            /// </summary>
            public Action<int> StateEvent = null;
 
            /// <summary>
            /// 抄SDK的,我也不知道这个是什么
            /// </summary>
            /// <param name="client"></param>
            /// <param name="gatt"></param>
            /// <param name="service"></param>
            /// <param name="writeChar"></param>
            /// <param name="notifyChar"></param>
            public override void OnGattPrepared(Blufi.Espressif.BlufiClient client, Android.Bluetooth.BluetoothGatt gatt, Android.Bluetooth.BluetoothGattService service,
                Android.Bluetooth.BluetoothGattCharacteristic writeChar, Android.Bluetooth.BluetoothGattCharacteristic notifyChar)
            {
                if (service == null || writeChar == null || notifyChar == null)
                {
                    StateEvent?.Invoke(-1);
                    return;
                }
 
                try
                {
                    int mtu = 128;
                    if ((int)Android.OS.Build.VERSION.SdkInt == 29
                      && Android.OS.Build.Manufacturer.ToLower().StartsWith("samsung") == true)
                    {
                        mtu = 23;
                    }
 
                    var requestMtu = gatt.RequestMtu(mtu);
                    if (!requestMtu)
                    {
                        //Request mtu failed
                        client.SetPostPackageLengthLimit(20);
                    }
                    StateEvent?.Invoke(1);
                }
                catch
                {
                    StateEvent?.Invoke(-1);
                    return;
                }
            }
 
            /// <summary>
            /// 手机端发送数据到蓝牙的结果
            /// </summary>
            /// <param name="client"></param>
            /// <param name="status">0:成功 其他都是失败</param>
            /// <param name="data">手机端发送的数据</param>
            public override void OnPostCustomDataResult(Blufi.Espressif.BlufiClient client, int status, byte[] data)
            {
                StateEvent?.Invoke(status == 0 ? 2 : 3);
            }
        }
 
        #endregion
 
        #region ■ 蓝牙关闭___________________________
 
        /// <summary>
        ///  关闭蓝牙链接
        /// </summary>
        public void DisContectBluetooth()
        {
            HdlThreadLogic.Current.RunMain(() =>
            {
                this.nowBlufiClient?.RequestCloseConnection();
                this.nowBlufiClient = null;
 
                m_Current = null;
 
            }, ShowErrorMode.NO);
        }
 
        #endregion
 
        #region ■ 发送数据___________________________
 
        /// <summary>
        /// 发送数据给蓝牙
        /// </summary>
        /// <param name="i_data">发送的数据</param>
        /// <param name="waiTime">等待时间(秒),如果设置为0,则只要发送不出现异常,直接判定为成功</param>
        public bool SendData(string i_data, int waiTime = 0)
        {
            if (this.nowBlufiClient == null)
            {
                return false;
            }
 
            try
            {
                this.sendStatuValue = -1;
                //发送数据
                var byteData = System.Text.Encoding.UTF8.GetBytes(i_data);
                this.nowBlufiClient.PostCustomData(byteData);
                if (waiTime == 0) { return true; }
 
                waiTime *= 5;
                while (this.sendStatuValue == -1 && waiTime > 0)
                {
                    System.Threading.Thread.Sleep(200);
                    waiTime--;
                }
                return this.sendStatuValue == 1;
            }
            catch { return false; }
        }
 
        #endregion
 
        #region ■ 结构体_____________________________
 
        /// <summary>
        /// 蓝牙返回的信息
        /// </summary>
        public class BluetoothInfo
        {
            /// <summary>
            /// 名字
            /// </summary>
            public string Name = string.Empty;
            /// <summary>
            /// 地址
            /// </summary>
            public string Address = string.Empty;
            /// <summary>
            /// 蓝牙设备
            /// </summary>
            public Android.Bluetooth.BluetoothDevice Device = null;
        }
        #endregion
    }
#endif
}