zhuguifei
2025-12-30 61eee1173c00a7ba9d9c748d28fe3acdb33b9441
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
package com.shlb.comb.activity;
 
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
 
 
import com.blakequ.bluetooth_manager_lib.connect.BluetoothConnectManager;
import com.blakequ.bluetooth_manager_lib.connect.ConnectState;
import com.blakequ.bluetooth_manager_lib.connect.ConnectStateListener;
import com.blakequ.bluetooth_manager_lib.device.BluetoothLeDevice;
import com.blakequ.bluetooth_manager_lib.util.BluetoothUtils;
import com.blankj.utilcode.util.LogUtils;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView;
import com.shlb.comb.R;
import com.shlb.comb.base.BaseActivity;
import com.shlb.comb.event.UpdateEvent;
import com.shlb.comb.util.Singletion;
 
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class ConnActivity extends BaseActivity {
    QMUIGroupListView mGroupListView;
    QMUIEmptyView mEmptyView;
 
    //连接管理
    private BluetoothConnectManager connectManager;
    //连接状态
    private int connectState = 0;
    //是否连接
    private boolean mConnected = false;
 
 
    @Override
    protected void contentView() {
        setContentView(R.layout.activity_conn);
        mGroupListView = findViewById(R.id.groupListView);
        mEmptyView = findViewById(R.id.emptyView);
    }
 
    @Override
    protected void initView() {
        super.initHead();
        initTitlebar();
        tv_center.setText("蓝牙信息");
        mEmptyView.show(true);
 
 
        initGroupListView();
 
    }
 
    @Override
    protected void initData() {
        BluetoothLeDevice mDevice = Singletion.getInstance().mDevice;
        initConn(mDevice);
 
 
    }
 
    @Override
    protected void initEvent() {
 
    }
 
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_left) {
            this.onBackPressed();
        } else if (id == R.id.iv_right) {
        }
    }
 
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventRefresh(UpdateEvent event) {
        switch (event.getType()) {
            case CONN_STATU:
 
                int statu = (int) event.getObj();
                //0-断开  2-连接
                switch (statu) {
                    case 0:
                        mConnected = false;
                        Singletion.getInstance().mConnected = false;
                        break;
                    case 2:
                        mConnected = true;
                        Singletion.getInstance().mConnected = true;
                        mEmptyView.hide();
                        Toast("连接成功!");
                        break;
                }
 
                break;
            case CONN_SERVICE:
                //获取服务成功后更新UI
                updateUi();
                break;
 
 
            case SCAN_UPDATE:
 
 
                break;
            case CONFIG_CHANGE:
 
                break;
        }
    }
 
    private ConnectStateListener stateListener = new ConnectStateListener() {
        @Override
        public void onConnectStateChanged(String address, ConnectState state) {
            switch (state) {
                case CONNECTED:
 
 
                    break;
                case CONNECTING:
 
 
                    break;
                case NORMAL:
 
 
                    break;
            }
            invalidateOptionsMenu();
        }
    };
 
    //连接设备
    private void initConn(BluetoothLeDevice device) {
        if (connectManager == null) {
            connectManager = BluetoothConnectManager.getInstance(this);
            connectManager.addConnectStateListener(stateListener);
            connectManager.setBluetoothGattCallback(new BluetoothGattCallback() {
 
                @Override
                public void onCharacteristicRead(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int status) {
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        EventBus.getDefault().post(new UpdateEvent(UpdateEvent.Type.BLE_DATA, characteristic, "read"));
                    } else {
                        EventBus.getDefault().post(new UpdateEvent(UpdateEvent.Type.BLE_DATA, characteristic, "fail"));
                        LogUtils.e(TAG, "fail to read characteristic");
                    }
                }
 
                @Override
                public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                    super.onCharacteristicWrite(gatt, characteristic, status);
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        EventBus.getDefault().post(new UpdateEvent(UpdateEvent.Type.BLE_DATA, characteristic, "write"));
                    } else {
                        EventBus.getDefault().post(new UpdateEvent(UpdateEvent.Type.BLE_DATA, characteristic, "fail"));
                        LogUtils.e(TAG, "fail to write characteristic");
                    }
                }
 
                @Override
                public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                    super.onCharacteristicChanged(gatt, characteristic);
                    EventBus.getDefault().post(new UpdateEvent(UpdateEvent.Type.BLE_DATA, characteristic, "notify"));
                }
 
                @Override
                public void onConnectionStateChange(BluetoothGatt gatt, final int status, int newState) {
                    super.onConnectionStateChange(gatt, status, newState);
                    EventBus.getDefault().post(new UpdateEvent(UpdateEvent.Type.CONN_STATU, newState, "conn_statu"));
                    connectState = newState;
 
 
                }
 
                @Override
                public void onServicesDiscovered(final BluetoothGatt gatt, int status) {
                    super.onServicesDiscovered(gatt, status);
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                displayGattServices(gatt.getServices());
                            }
                        });
                    }
 
                }
            });
        }
        connectManager.connect(device.getAddress());
    }
 
 
    /**
     * 获取当前连接蓝牙可写服务
     *
     * @param gattServices
     */
    private void displayGattServices(List<BluetoothGattService> gattServices) {
        Singletion.getInstance().mbluetoothServices.clear();
        List<Map<String, String>> res = new ArrayList<>();
        for (final BluetoothGattService gattService : gattServices) {
            final List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
            for (final BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                Map<String, String> map = new HashMap<>();
 
                String property = getPropertyString(gattCharacteristic.getProperties());
                //只需要可写服务
                if (property.contains("Write")) {
                    map.put("name", property);
                    map.put("uuid", gattCharacteristic.getUuid().toString());
                    res.add(map);
                }
            }
        }
        Singletion.getInstance().mbluetoothServices.addAll(res);
        EventBus.getDefault().post(new UpdateEvent(UpdateEvent.Type.CONN_SERVICE));
 
    }
 
    private String getPropertyString(int property) {
        StringBuilder sb = new StringBuilder("(");
        //Read
        if ((property & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
            sb.append("Read ");
        }
        //Write
        if ((property & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) > 0
                || (property & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
            sb.append("Write ");
        }
        //Notify
        if ((property & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
            sb.append("Notity ");
        }
 
        if ((property & BluetoothGattCharacteristic.PROPERTY_INDICATE) > 0) {
            sb.append("Indicate ");
        }
 
        //Broadcast
        if ((property & BluetoothGattCharacteristic.PROPERTY_BROADCAST) > 0) {
            sb.append("Broadcast ");
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append(")");
        return sb.toString();
    }
 
    public void initTitlebar() {
        iv_right.setVisibility(View.VISIBLE);
        iv_left.setImageDrawable(getResources().getDrawable(R.mipmap.icon_back));
        iv_right.setImageDrawable(getResources().getDrawable(R.mipmap.icon_topbar_overflow));
    }
 
    QMUICommonListItemView nameItem;
    QMUICommonListItemView macItem;
    QMUICommonListItemView statuItem;
    View.OnClickListener onClickListener;
 
    private void initGroupListView() {
        nameItem = mGroupListView.createItemView(null,
                "蓝牙", "未连接",
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_NONE);
        nameItem.setId(R.id.address_ble_name);
 
        macItem = mGroupListView.createItemView(null,
                "mac", "",
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_NONE);
        macItem.setId(R.id.address_ble_mac);
 
        statuItem = mGroupListView.createItemView(null,
                "状态", "未连接",
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_NONE);
        statuItem.setId(R.id.address_ble_statu);
 
 
        onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v instanceof QMUICommonListItemView) {
                    CharSequence text = ((QMUICommonListItemView) v).getDetailText();
                    List<Map<String, String>> mbluetoothServices = Singletion.getInstance().mbluetoothServices;
 
                    CharSequence title = ((QMUICommonListItemView) v).getText();
                    if(title.equals("(传感器编址)简易模式")){
                        if(mbluetoothServices == null ||  mbluetoothServices.size() < 1 ){
                            Toast("服务信息错误,请重新连接");
                            return;
                        }
                        Map<String, String> map = mbluetoothServices.get(0);
                        Singletion.getInstance().uuid  = map.get("uuid").toString();
                        Intent intent = new Intent(ConnActivity.this,WriteActivity.class);
                        startActivity(intent);
                    }else if(title.equals("(传感器编址)专家模式")){
                        if(mbluetoothServices == null ||  mbluetoothServices.size() < 2 ){
                            Toast("服务信息错误,请重新连接");
                            return;
                        }
                        Map<String, String> map = mbluetoothServices.get(1);
                        Singletion.getInstance().uuid  = map.get("uuid").toString();
                        Intent intent = new Intent(ConnActivity.this,NormalWriteActivity.class);
                        startActivity(intent);
                    }
 
                }
            }
        };
 
        int size = QMUIDisplayHelper.dp2px(this, 20);
        QMUIGroupListView.newSection(this)
                .setTitle("Section 1:蓝牙信息")
                .setDescription("")
                .setLeftIconSize(size, ViewGroup.LayoutParams.WRAP_CONTENT)
                .addItemView(nameItem, onClickListener)
                .addItemView(statuItem, onClickListener)
                .addItemView(macItem, onClickListener)
                .addTo(mGroupListView);
 
 
    }
 
    private void updateUi() {
        //TODO 动态更新UI
        BluetoothLeDevice mDevice = Singletion.getInstance().mDevice;
        List<Map<String, String>> mbluetoothServices = Singletion.getInstance().mbluetoothServices;
        boolean mConnected = Singletion.getInstance().mConnected;
        if (!mConnected || mbluetoothServices == null || mDevice == null) {
            Toast("异常错误,请退出重试!");
 
        } else {
            if (nameItem != null) nameItem.setDetailText(mDevice.getName());
            if (statuItem != null) statuItem.setDetailText("已连接");
            if (macItem != null) macItem.setDetailText(mDevice.getAddress());
 
            //创建可写服务信息
            for (int i = 0; i < mbluetoothServices.size(); i++) {
                Map<String, String> map = mbluetoothServices.get(i);
                //map.get("uuid")
                String title =  i == 0 ? "(传感器编址)简易模式"   : "(传感器编址)专家模式" ;
                QMUICommonListItemView itemView = mGroupListView.createItemView(title);
                itemView.setOrientation(QMUICommonListItemView.VERTICAL);
                itemView.setDetailText(map.get("name"));
                int size = QMUIDisplayHelper.dp2px(this, 20);
                int section = i + 2;
                int service = i + 1;
                itemView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
                QMUIGroupListView.newSection(this)
                        .setTitle("Section " + section + ":编址服务" + service)
                        .setDescription("")
                        .setLeftIconSize(size, ViewGroup.LayoutParams.WRAP_CONTENT)
                        .addItemView(itemView, onClickListener)
                        .addTo(mGroupListView);
 
 
            }
        }
 
 
    }
 
    private void disconnect() {
        if (connectManager != null) {
            if (connectManager.isConnectDevice()) {
                if (Singletion.getInstance().mDevice != null && Singletion.getInstance().mDevice.getAddress() != null) {
                    connectManager.disconnect(Singletion.getInstance().mDevice.getAddress());
                    connectManager.removeConnectStateListener(stateListener);
                }
 
            }
        }
    }
 
    private void connect() {
        if (connectManager != null) {
            if (!connectManager.isConnectDevice()) {
                if (Singletion.getInstance().mDevice != null && Singletion.getInstance().mDevice.getAddress() != null)
                    connectManager.connect(Singletion.getInstance().mDevice.getAddress());
            }
        }
    }
 
    private void showDisconnectDialog() {
 
        new QMUIDialog.MessageDialogBuilder(ConnActivity.this)
                .setTitle("提示")
                .setMessage("蓝牙已连接,是否断开连接?")
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        disconnect();
                        dialog.dismiss();
                        finish();
 
                    }
                })
                .create(com.qmuiteam.qmui.R.style.QMUI_Dialog).show();
    }
 
 
    @Override
    public void onBackPressed() {
        if (connectManager != null && connectManager.isConnectDevice()) {
            showDisconnectDialog();
        } else {
            super.onBackPressed();
        }
 
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        disconnect();
 
    }
}