瀏覽代碼

修改lib

slambb 4 年之前
父節點
當前提交
54dd5ac875

二進制
.idea/caches/build_file_checksums.ser


+ 0 - 29
.idea/codeStyles/Project.xml

@@ -1,29 +0,0 @@
-<component name="ProjectCodeStyleConfiguration">
-  <code_scheme name="Project" version="173">
-    <Objective-C-extensions>
-      <file>
-        <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Import" />
-        <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Macro" />
-        <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Typedef" />
-        <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Enum" />
-        <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Constant" />
-        <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Global" />
-        <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Struct" />
-        <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="FunctionPredecl" />
-        <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Function" />
-      </file>
-      <class>
-        <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Property" />
-        <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Synthesize" />
-        <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="InitMethod" />
-        <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="StaticMethod" />
-        <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="InstanceMethod" />
-        <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="DeallocMethod" />
-      </class>
-      <extensions>
-        <pair source="cpp" header="h" fileNamingConvention="NONE" />
-        <pair source="c" header="h" fileNamingConvention="NONE" />
-      </extensions>
-    </Objective-C-extensions>
-  </code_scheme>
-</component>

+ 17 - 1
.idea/misc.xml

@@ -24,10 +24,26 @@
       </value>
     </option>
   </component>
-  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" project-jdk-name="JDK" project-jdk-type="JavaSDK">
+  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
     <output url="file://$PROJECT_DIR$/build/classes" />
   </component>
   <component name="ProjectType">
     <option name="id" value="Android" />
   </component>
+  <component name="masterDetails">
+    <states>
+      <state key="ProjectJDKs.UI">
+        <settings>
+          <last-edited>1.8</last-edited>
+          <splitter-proportions>
+            <option name="proportions">
+              <list>
+                <option value="0.2" />
+              </list>
+            </option>
+          </splitter-proportions>
+        </settings>
+      </state>
+    </states>
+  </component>
 </project>

+ 1 - 1
.idea/modules.xml

@@ -2,7 +2,7 @@
 <project version="4">
   <component name="ProjectModuleManager">
     <modules>
-      <module fileurl="file://$PROJECT_DIR$/BBOXBLE.iml" filepath="$PROJECT_DIR$/BBOXBLE.iml" />
+      <module fileurl="file://$PROJECT_DIR$/android-bboxble.iml" filepath="$PROJECT_DIR$/android-bboxble.iml" />
       <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
       <module fileurl="file://$PROJECT_DIR$/bboxblelib/bboxblelib.iml" filepath="$PROJECT_DIR$/bboxblelib/bboxblelib.iml" />
     </modules>

+ 1 - 0
app/build.gradle

@@ -22,6 +22,7 @@ android {
 dependencies {
     implementation fileTree(include: ['*.jar'], dir: 'libs')
     implementation 'com.android.support:appcompat-v7:26.0.0-beta1'
+    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
     testImplementation 'junit:junit:4.12'
     androidTestImplementation 'com.android.support.test:runner:0.5'
     androidTestImplementation 'com.android.support.test.espresso:espresso-core:2.2.2'

+ 32 - 13
app/src/main/AndroidManifest.xml

@@ -1,3 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.slam.bboxble">
 
@@ -7,23 +8,41 @@
         android:label="@string/app_name"
         android:roundIcon="@mipmap/ic_launcher_round"
         android:supportsRtl="true"
-        android:theme="@style/AppTheme" >
+        android:theme="@style/AppTheme">
+        <!--<activity-->
+            <!--android:name=".DeviceScanActivity"-->
+            <!--android:configChanges="orientation"-->
+            <!--android:label="@string/app_name"-->
+            <!--android:screenOrientation="portrait">-->
+            <!--&lt;!&ndash;<intent-filter>&ndash;&gt;-->
+                <!--&lt;!&ndash;<action android:name="android.intent.action.MAIN" />&ndash;&gt;-->
 
-        <activity android:name="com.slam.bboxble.DeviceScanActivity"
-            android:label="@string/app_name"
+                <!--&lt;!&ndash;<category android:name="android.intent.category.LAUNCHER" />&ndash;&gt;-->
+            <!--&lt;!&ndash;</intent-filter>&ndash;&gt;-->
+        <!--</activity>-->
+        <!--<activity-->
+            <!--android:name=".DeviceControlActivity"-->
+            <!--android:configChanges="orientation"-->
+            <!--android:screenOrientation="portrait"-->
+            <!--android:windowSoftInputMode="stateHidden|adjustPan" />-->
+
+
+
+        <activity android:name=".TestActivity"
             android:configChanges="orientation"
-            android:screenOrientation="portrait">
+            android:label="@string/app_name"
+            android:screenOrientation="portrait"
+            android:exported="true">
             <intent-filter>
-                <action android:name="android.intent.action.MAIN"/>
-                <category android:name="android.intent.category.LAUNCHER"/>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
-        <activity android:name="com.slam.bboxble.DeviceControlActivity"
-            android:configChanges="orientation"
-            android:screenOrientation="portrait"
-            android:windowSoftInputMode="stateHidden|adjustPan"/>
-        <service android:name="com.slam.bboxblelib.BluetoothLeService" android:enabled="true"/>
-    </application>
 
+        <service
+            android:name="com.slam.bboxblelib.BluetoothLeService"
+            android:enabled="true" />
+    </application>
 
-</manifest>
+</manifest>

+ 15 - 8
app/src/main/java/com/slam/bboxble/DeviceScanActivity.java

@@ -42,6 +42,7 @@ import android.widget.ListView;
 import android.widget.TextView;
 import android.widget.Toast;
 
+import com.slam.bboxblelib.DataEvent;
 import com.slam.bboxblelib.DeviceEvent;
 import com.slam.bboxblelib.MainBluetooth;
 import com.slam.bboxblelib.impl.MainBluetoothImpl;
@@ -89,7 +90,7 @@ public class DeviceScanActivity extends Activity implements View.OnClickListener
         super.onCreate(savedInstanceState);
 
 
-        getActionBar().setTitle(R.string.title_devices);
+//        getActionBar().setTitle(R.string.title_devices);
         setContentView(R.layout.list_device_view);
 
         if (Build.VERSION.SDK_INT >= 23) {
@@ -134,7 +135,7 @@ public class DeviceScanActivity extends Activity implements View.OnClickListener
                 intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
                 mScanning = false;
                 //蓝牙部分
-                mainBluetooth.stopScanLeDevice();
+                mainBluetooth.stopConnectLeDevice();
                 noNeedShowDialog = false;
                 startActivityForResult(intent, 2);
             }
@@ -150,7 +151,7 @@ public class DeviceScanActivity extends Activity implements View.OnClickListener
                 intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
                 mScanning = false;
                 //蓝牙部分
-                mainBluetooth.stopScanLeDevice();
+                mainBluetooth.stopConnectLeDevice();
                 noNeedShowDialog = false;
                 startActivityForResult(intent, 2);
             }
@@ -170,7 +171,7 @@ public class DeviceScanActivity extends Activity implements View.OnClickListener
         //初始化蓝牙参数部分
         Responser responser = new Responser() {
             @Override
-            public void onSuccess(DeviceEvent deviceEvent) {
+            public void onSuccess(Integer code,String prompt, DeviceEvent deviceEvent) {
                 if (deviceEvent.getType().equals("pairedDevices")) {
                     if (deviceEvent.getDevices().size() > 0) {
                         for (BluetoothDevice device : deviceEvent.getDevices()) {
@@ -200,7 +201,7 @@ public class DeviceScanActivity extends Activity implements View.OnClickListener
             }
 
             @Override
-            public void onFailed(String prompt) {
+            public void onFailed(Integer arv1,String prompt) {
 
             }
 
@@ -226,9 +227,15 @@ public class DeviceScanActivity extends Activity implements View.OnClickListener
 //                            }
 //                        });
 //                    }
+
+
+            @Override
+            public void onUpdateData(Integer code, String prompt, DataEvent dataEvent) {
+
+            }
         };
 
-        mainBluetooth.onCreate(this,responser);
+        mainBluetooth.onRegisterEvent(this,responser);
 
         // Checks if Bluetooth is supported on the device.
         if (mBluetoothAdapter == null) {
@@ -339,13 +346,13 @@ public class DeviceScanActivity extends Activity implements View.OnClickListener
                 mPairLeDeviceListAdapter.clear();
                 mButtonStopScan.setVisibility(View.VISIBLE);
                 mButtonStartScan.setVisibility(View.GONE);
-                mainBluetooth.startScanLeDevice();
+//                mainBluetooth.startScanLeDevice();
                 invalidateOptionsMenu();
                 break;
             case R.id.button_stopScan:
                 mButtonStopScan.setVisibility(View.GONE);
                 mButtonStartScan.setVisibility(View.VISIBLE);
-                mainBluetooth.stopScanLeDevice();
+                mainBluetooth.stopConnectLeDevice();
                 break;
             default:
                 break;

+ 4 - 4
app/src/main/java/com/slam/bboxble/ServiceFragment.java

@@ -32,7 +32,7 @@ public class ServiceFragment extends Fragment implements View.OnClickListener {
     private Button mButtonUUID, mButtonOTA;
     private Button mButtonSend;
     private ExpandableListView mGattServicesList;
-    private UUID uuida =     UUID.fromString(GattAttributes.uuid_identification_code);
+    private UUID uuida =     UUID.fromString(GattAttributes.CLIENT_CHARACTERISTIC_CONFIG);
     //ota 下面的两个特征值
     private UUID uuid_ota1 = UUID.fromString(GattAttributes.uuid_ota1);
     private UUID uuid_ota2 = UUID.fromString(GattAttributes.uuid_ota2);
@@ -68,7 +68,7 @@ public class ServiceFragment extends Fragment implements View.OnClickListener {
         mButtonUUID = (Button) view.findViewById(R.id.button_uuidToUUID);
         mButtonOTA = (Button) view.findViewById(R.id.button_uuidToOTA);
 //        button_send
-        mButtonSend = (Button) view.findViewById(R.id.button_send);
+        mButtonSend = (Button) view.findViewById(R.id.button_send1);
         mGattServicesList = (ExpandableListView) view.findViewById(R.id.gatt_services_list);
         mGattServicesList.setOnChildClickListener(servicesListClickListner);
         mButtonUUID.setOnClickListener(this);
@@ -287,7 +287,7 @@ public class ServiceFragment extends Fragment implements View.OnClickListener {
                     Toast.makeText(getContext(), "Not Support OTA Function", Toast.LENGTH_SHORT).show();
                 }
                 break;
-            case R.id.button_send:
+            case R.id.button_send1:
                 Log.e(TAG, "button_send");
                 String str = Conversion.str2HexStr("V");
                 Log.i(TAG,str);
@@ -296,7 +296,7 @@ public class ServiceFragment extends Fragment implements View.OnClickListener {
                 UUID characteristic =UUID.fromString("0000FFF2-0000-1000-8000-00805F9B34FB");
                 int mode = 0;
                 ((DeviceControlActivity)getActivity()).getmBluetoothLeService().setServiceandCharacteristic(service,characteristic,mode);
-                ((DeviceControlActivity)getActivity()).getmBluetoothLeService().writeBLECharacteristicValue(result);
+//                ((DeviceControlActivity)getActivity()).getmBluetoothLeService().writeBLECharacteristicValue(result);
                 break;
             default:
                 break;

+ 215 - 0
app/src/main/java/com/slam/bboxble/TestActivity.java

@@ -0,0 +1,215 @@
+package com.slam.bboxble;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.View;
+import android.widget.Button;
+import android.widget.TextView;
+
+import com.slam.bboxblelib.Conversion;
+import com.slam.bboxblelib.DataEvent;
+import com.slam.bboxblelib.DeviceEvent;
+import com.slam.bboxblelib.MainBluetooth;
+import com.slam.bboxblelib.Responser;
+import com.slam.bboxblelib.WriteEvent;
+import com.slam.bboxblelib.WriteResponser;
+import com.slam.bboxblelib.impl.MainBluetoothImpl;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class TestActivity extends Activity implements View.OnClickListener {
+
+    private final static String TAG = TestActivity.class.getSimpleName();
+
+    private MainBluetooth mainBluetooth = new MainBluetoothImpl();
+
+    private Button mButtonSend1;
+    private Button mButtonSend2;
+    private Button mButtonSend3;
+    private Button mButtonConnect;
+    private Button mButtonDisconnect;
+    private Button mButtonUpdate;
+
+    private TextView textView;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_test);
+
+        mButtonDisconnect = this.findViewById(R.id.button_dis_connect);
+        mButtonDisconnect.setOnClickListener(this);
+
+        mButtonConnect = this.findViewById(R.id.button_connect);
+        mButtonSend1 = this.findViewById(R.id.button_send1);
+        mButtonConnect.setOnClickListener(this);
+        mButtonSend1.setOnClickListener(this);
+
+        mButtonSend2 = this.findViewById(R.id.button_send2);
+        mButtonSend2.setOnClickListener(this);
+
+        mButtonSend3 = this.findViewById(R.id.button_send3);
+        mButtonSend3.setOnClickListener(this);
+
+        mButtonUpdate = this.findViewById(R.id.button_update);
+        mButtonUpdate.setOnClickListener(this);
+
+        textView = findViewById(R.id.textView6);
+        textView.setMovementMethod(new ScrollingMovementMethod());
+
+
+        Responser responser = new Responser() {
+            @Override
+            public void onSuccess(Integer code, String prompt, DeviceEvent deviceEvent) {
+                Log.w(TAG, "onSuccess code:" + code.toString() + ",prompt:" + prompt);
+                if (deviceEvent != null) {
+                    Log.i(TAG, deviceEvent.getDeviceAddress());
+                    Log.i(TAG, deviceEvent.getDeviceName());
+
+                    String _tip = textView.getText().toString();
+                    _tip += "设备,address:" + deviceEvent.getDeviceAddress() + ",deviceName:" + deviceEvent.getDeviceName() + "\n";
+                    textView.setText(_tip);
+                }
+                //todo 返回成功对象信息
+                //约定处理信息 onSuccess
+                // {
+                //      "code":code,
+                //      "prompt":prompt,
+                //      "deviceName":deviceEvent.getDeviceName(),
+                //      "deviceAddress":deviceEvent.getDeviceAddress(),
+                //      "rssi":deviceEvent.getRssi(),
+                //  }
+
+            }
+
+            @Override
+            public void onFailed(Integer code, String prompt) {
+                Log.e(TAG, "onFailed code:" + code.toString() + ",prompt:" + prompt);
+                //todo 返回错误的提示信息
+                //约定处理信息 onFailed
+                // {
+                //      "code":code,
+                //      "prompt":prompt,
+                //  }
+            }
+
+            @Override
+            public void onUpdateData(Integer code, String prompt, DataEvent dataEvent) {
+
+                if (MainBluetoothImpl.GATT_CHARACTERISTIC_NOTIFICATION_CHANGED == code) {
+
+//                    Log.i(TAG, "type  =" + dataEvent.getDataType());
+                    String hand = dataEvent.getHand();
+                    double ax = dataEvent.getAcc().get("ax");
+                    double ay = dataEvent.getAcc().get("ay");
+                    double az = dataEvent.getAcc().get("az");
+                    double gx = dataEvent.getGyro().get("gx");
+                    double gy = dataEvent.getGyro().get("gy");
+                    double gz = dataEvent.getGyro().get("gz");
+                    Integer min = dataEvent.getMin();
+                    Integer s = dataEvent.getS();
+                    Integer ms = dataEvent.getMs();
+
+                    textView.setText("hand =" + hand + "\n" +
+                            "acc   = " + String.format("%.2f", ax) + " = " + String.format("%.2f", ay) + " = " + String.format("%.2f", az) +
+                            "\n gyro  = " + String.format("%.2f", gx) + " = " + String.format("%.2f", gy) + " = " + String.format("%.2f", gz) +
+                            "\n min = " + min + " s= " + s + " ms= " + ms);
+
+                    //todo 此处回调硬件解析的信息
+                    //约定处理信息 onUpdateData
+                    // {
+                    //      "code":code,
+                    //      "prompt":prompt,
+                    //      "type": "CHANGED",
+                    //      "hand": hand,
+                    //      "acc": {ax:ax,ay:ay,az:az}
+                    //      "gyro": {gx:gx,gy:gy,gz:gz}
+                    //      "min": min,
+                    //      "s": s,
+                    //      "ms": ms
+                    //  }
+                } else if (MainBluetoothImpl.GATT_CHARACTERISTIC_NOTIFICATION_STRING == code) {
+                    //todo 此处回调字符串JSON信息
+                    //约定处理信息 onUpdateData
+                    // {
+                    //      "code": code,
+                    //      "prompt": prompt,
+                    //      "type": "STRING",
+                    //      "data": dataEvent.getDataStr()
+                    //  }
+                    Log.i(TAG, "prompt:" + prompt + " " + dataEvent.getDataStr());
+                }
+            }
+        };
+        //todo 1.注册一下事件
+        mainBluetooth.onRegisterEvent(this, responser);
+    }
+
+    @Override
+    protected void onDestroy() {
+        super.onDestroy();
+        //todo 2.释放注册事件
+        mainBluetooth.onUnregisterEvent();
+    }
+
+    @Override
+    public void onClick(View view) {
+        switch (view.getId()) {
+            case R.id.button_connect:
+                onConnect("BGBox");
+                break;
+            case R.id.button_send1:
+                onWriteValue("V");
+                break;
+            case R.id.button_send2:
+                onWriteValue("3");
+                break;
+            case R.id.button_send3:
+                onWriteValue("4");
+                break;
+
+            case R.id.button_update:
+                onWriteValue("a");
+//                mainBluetooth.findNotifyCharacteristic(textView);
+                break;
+
+            case R.id.button_dis_connect:
+                onDisconnect();
+                break;
+
+            default:
+                break;
+        }
+    }
+
+    //搜索自定义名字
+    //TODO 提供接口给webview 连接设备
+    /**
+     * 连接蓝牙设备
+     * @param address
+     */
+    public void onConnect(String address) {
+        mainBluetooth.startConnectLeDevice(address);
+    }
+    //写入特征值数值
+    //TODO 提供接口给webview 写入数据给设备
+    /**
+     * 写入FFF服务
+     * @param value
+     */
+    public void onWriteValue(String value) {
+        mainBluetooth.writeValueToFFF(value);
+    }
+    //断开设备连接
+    //TODO 提供接口给webview 可断开蓝牙连接
+    /**
+     * 断开连接
+     */
+    public void onDisconnect() {
+        mainBluetooth.disConnectLeDevice();
+    }
+
+}

+ 90 - 0
app/src/main/res/layout/activity_test.xml

@@ -0,0 +1,90 @@
+<?xml version="1.0" encoding="utf-8"?>
+<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    tools:context="com.slam.bboxble.TestActivity">
+
+    <Button
+        android:id="@+id/button_dis_connect"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_marginEnd="8dp"
+        android:layout_marginStart="8dp"
+        android:layout_marginTop="32dp"
+        android:text="断开连接"
+        app:layout_constraintEnd_toStartOf="@+id/button_send1"
+        app:layout_constraintStart_toEndOf="@+id/button_connect"
+        app:layout_constraintTop_toTopOf="parent" />
+
+    <Button
+        android:id="@+id/button_send1"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_marginEnd="28dp"
+        android:layout_marginTop="32dp"
+        android:text="发送数据v"
+        app:layout_constraintEnd_toEndOf="parent"
+        app:layout_constraintTop_toTopOf="parent" />
+
+    <Button
+        android:id="@+id/button_send2"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_marginTop="112dp"
+        android:text="发送数据3"
+        app:layout_constraintTop_toTopOf="parent"
+        tools:layout_editor_absoluteX="10dp" />
+
+    <Button
+        android:id="@+id/button_send3"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_marginEnd="16dp"
+        android:layout_marginStart="8dp"
+        android:layout_marginTop="112dp"
+        android:text="发送数据4"
+        app:layout_constraintEnd_toEndOf="parent"
+        app:layout_constraintHorizontal_bias="0.028"
+        app:layout_constraintStart_toEndOf="@+id/button_send2"
+        app:layout_constraintTop_toTopOf="parent" />
+
+    <Button
+        android:id="@+id/button_update"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_marginEnd="16dp"
+        android:layout_marginStart="8dp"
+        android:layout_marginTop="112dp"
+        android:text="发送数据a"
+        app:layout_constraintEnd_toEndOf="parent"
+        app:layout_constraintHorizontal_bias="0.47"
+        app:layout_constraintStart_toEndOf="@+id/button_send3"
+        app:layout_constraintTop_toTopOf="parent" />
+
+    <Button
+        android:id="@+id/button_connect"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_marginStart="8dp"
+        android:layout_marginTop="32dp"
+        android:text="连接蓝牙"
+        app:layout_constraintStart_toStartOf="parent"
+        app:layout_constraintTop_toTopOf="parent" />
+
+    <TextView
+        android:id="@+id/textView6"
+        android:layout_width="292dp"
+        android:layout_height="233dp"
+        android:layout_marginBottom="8dp"
+        android:layout_marginEnd="8dp"
+        android:layout_marginStart="8dp"
+        android:layout_marginTop="8dp"
+        android:maxLines="20"
+        android:scrollbars="vertical"
+        app:layout_constraintBottom_toBottomOf="parent"
+        app:layout_constraintEnd_toEndOf="parent"
+        app:layout_constraintStart_toStartOf="parent"
+        app:layout_constraintTop_toBottomOf="@+id/button_update" />
+</android.support.constraint.ConstraintLayout>

+ 1 - 1
app/src/main/res/layout/fragment_srivce.xml

@@ -62,7 +62,7 @@
         android:text="send"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:id="@+id/button_send"
+        android:id="@+id/button_send1"
         android:layout_weight="1" />
 
     </LinearLayout>

+ 1 - 1
app/src/main/res/values/base-strings.xml

@@ -16,7 +16,7 @@
 -->
 
 <resources>
-    <string name="app_name">RC OTA</string>
+    <string name="app_name">BBOXBLELIB</string>
     <string name="intro_message">
         <![CDATA[
         

+ 1 - 2
app/src/main/res/values/strings.xml

@@ -1,5 +1,4 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2013 The Android Open Source Project
+<?xml version="1.0" encoding="utf-8"?><!-- Copyright (C) 2013 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.

+ 223 - 76
bboxblelib/src/main/java/com/slam/bboxblelib/BluetoothLeService.java

@@ -30,7 +30,9 @@ import android.content.Context;
 import android.content.Intent;
 import android.os.Binder;
 import android.os.IBinder;
+import android.text.method.ScrollingMovementMethod;
 import android.util.Log;
+import android.widget.TextView;
 
 import org.greenrobot.eventbus.EventBus;
 
@@ -41,6 +43,30 @@ import java.util.UUID;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
 
+
+enum ResponseEnum {
+    GATT_GET_ERROR(30004,"获取Gatt特服务失败!"),
+    GATT_GET_SERVICE_ERROR(30005,"获取写入服务失败!"),
+    GATT_GET_CHARACTERISTIC_ERROR(30006,"获取写入特征值失败!"),
+    GATT_WRITE_ERROR(30007,"写入数据失败!"),
+    ;
+    private Integer code;
+
+    private String message;
+
+    ResponseEnum(Integer code, String message) {
+        this.code = code;
+        this.message = message;
+    }
+
+    public Integer getCode() {
+        return code;
+    }
+
+    public String getMessage() {
+        return message;
+    }
+}
 /**
  * Service for managing connection and data communication with a GATT server hosted on a
  * given Bluetooth LE device.
@@ -54,7 +80,6 @@ public class BluetoothLeService extends Service {
     private int mConnectionState = STATE_DISCONNECTED;
     private Queue writeQueue = new LinkedList();
     private boolean isWriting = false;
-    private WriteResponser mWriteResponser = null;
     private static final int STATE_DISCONNECTED = 0;
     private static final int STATE_CONNECTING = 1;
     private static final int STATE_CONNECTED = 2;
@@ -62,6 +87,16 @@ public class BluetoothLeService extends Service {
     public final static String ACTION_GATT_DISCONNECTED ="com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
     public final static String ACTION_GATT_SERVICES_DISCOVERED ="com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
     public final static String ACTION_DATA_AVAILABLE ="com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
+    //ADD MAKE
+    public final static String ACTION_DATA_AVAILABLE_SUCCESS ="com.example.bluetooth.le.ACTION_DATA_AVAILABLE_SUCCESS";
+    public final static String ACTION_RESPONSE_FAIL ="com.example.bluetooth.le.ACTION_RESPONSE_FAIL";
+    public final static String ACTION_RESPONSE_SUCCESS ="com.example.bluetooth.le.ACTION_RESPONSE_SUCCESS";
+
+    public final static String BLUETOOTH_INIT_ERROR ="com.example.bluetooth.le.ACTION_DATA_AVAILABLE_SUCCESS";
+
+    public final static String EXTRA_CODE ="com.example.bluetooth.le.EXTRA_CODE";
+    public final static String EXTRA_MESSAGE ="com.example.bluetooth.le.EXTRA_MESSAGE";
+
     public final static String EXTRA_DATA ="com.example.bluetooth.le.EXTRA_DATA";
     public final static String EXTRA_DATA_BYTE ="com.example.bluetooth.le.EXTRA_DATA_BYTE";
     public final static String EXTRA_UUID ="com.example.bluetooth.le.EXTRA_UUID";
@@ -99,7 +134,6 @@ public class BluetoothLeService extends Service {
     private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
         @Override
         public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
-            Log.e(TAG, "onConnectionStateChange");
             String intentAction;
             if (newState == BluetoothProfile.STATE_CONNECTED) {
                 intentAction = ACTION_GATT_CONNECTED;
@@ -133,7 +167,7 @@ public class BluetoothLeService extends Service {
                                          BluetoothGattCharacteristic characteristic,
                                          int status) {
             if (status == BluetoothGatt.GATT_SUCCESS) {
-                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
+                broadcastUpdate(ACTION_DATA_AVAILABLE_SUCCESS, characteristic);
             }
         }
 
@@ -148,13 +182,11 @@ public class BluetoothLeService extends Service {
             super.onCharacteristicWrite(gatt, characteristic, status);
             final byte[] data = characteristic.getValue();
             String out = Conversion.BytetohexString(data,false);
-            Log.i(TAG,"*******onCharacteristicWrite = "+ out + characteristic.getWriteType() + "=="+status);
+//            Log.i(TAG,"*******onCharacteristicWrite = "+ out + characteristic.getWriteType() + "=="+status +"="+characteristic.getUuid()+"="+Conversion.hexStringToString(Conversion.BytetohexString(characteristic.getValue(),false)));
             if (characteristic.getWriteType() == BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE && status == BluetoothGatt.GATT_SUCCESS) {
-                Log.i(TAG,"*******onCharacteristicWrite CheckboxEvent(11)");
-                if (mWriteResponser != null) {
-                    WriteEvent writeEvent = new WriteEvent(characteristic.getWriteType(), status);
-                    mWriteResponser.onSuccess(writeEvent);
-                }
+//                Log.i(TAG,"*******onCharacteristicWrite CheckboxEvent(11)");
+                //写入成功
+                broadcastUpdateResponse(ACTION_RESPONSE_SUCCESS,status,"写入数据成功!",characteristic);
 
             }else if(characteristic.getWriteType() == BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE && status != BluetoothGatt.GATT_SUCCESS)
             {
@@ -200,7 +232,9 @@ public class BluetoothLeService extends Service {
         @Override
         public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
             super.onDescriptorRead(gatt, descriptor, status);
+            Log.i(TAG,"onDescriptorRead =="+ descriptor.getUuid().toString());
             if (status == BluetoothGatt.GATT_SUCCESS) {
+                Log.i(TAG,"onDescriptorRead =="+ descriptor.getUuid().toString());
                 final byte[] data = descriptor.getValue();
                 if (data != null && data.length > 0) {
                     final StringBuilder stringBuilder = new StringBuilder(data.length);
@@ -226,10 +260,36 @@ public class BluetoothLeService extends Service {
         sendBroadcast(intent);
     }
 
-    private void broadcastUpdate(final String action,
+    //更新 response
+    private void broadcastUpdateResponse(final String action,Integer code,String prompt) {
+        final Intent intent = new Intent(action);
+        intent.putExtra(EXTRA_CODE, code);
+        intent.putExtra(EXTRA_MESSAGE, prompt);
+        sendBroadcast(intent);
+    }
+
+    private void broadcastUpdateResponse(final String action,Integer code,String prompt,
                                  final BluetoothGattCharacteristic characteristic) {
         final Intent intent = new Intent(action);
+        // For all other profiles, writes the data formatted in HEX.
+        final byte[] data = characteristic.getValue();
+        if (data != null && data.length > 0) {
+            final StringBuilder stringBuilder = new StringBuilder(data.length);
+            for (byte byteChar : data)
+                stringBuilder.append(String.format("%02X", byteChar));
+            intent.putExtra(EXTRA_DATA, stringBuilder.toString());
+            intent.putExtra(EXTRA_DATA_BYTE, characteristic.getValue());
+            intent.putExtra(EXTRA_UUID, characteristic.getUuid().toString());
+            intent.putExtra(EXTRA_CODE, code);
+            intent.putExtra(EXTRA_MESSAGE, prompt);
+
+            sendBroadcast(intent);
+        }
+    }
 
+    private void broadcastUpdate(final String action,
+                                 final BluetoothGattCharacteristic characteristic) {
+        final Intent intent = new Intent(action);
         // This is special handling for the Heart Rate Measurement profile.  Data parsing is
         // carried out as per profile specifications:
         // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
@@ -253,7 +313,7 @@ public class BluetoothLeService extends Service {
                 final StringBuilder stringBuilder = new StringBuilder(data.length);
                 for (byte byteChar : data)
                     stringBuilder.append(String.format("%02X", byteChar));
-//                Log.e(TAG, "broadcastUpdate " + stringBuilder.toString() + " " + action.toString());
+//                Log.e(TAG, "broadcastUpdate " + stringBuilder.toString() + " " + action.toString() + " " + characteristic.getUuid().toString());
                 intent.putExtra(EXTRA_DATA, stringBuilder.toString());
                 intent.putExtra(EXTRA_DATA_BYTE, characteristic.getValue());
                 intent.putExtra(EXTRA_UUID, characteristic.getUuid().toString());
@@ -290,14 +350,13 @@ public class BluetoothLeService extends Service {
      *
      * @return Return true if the initialization is successful.
      */
-    public boolean initialize(Responser responser) {
+    public boolean initialize() {
         // For API level 18 and above, get a reference to BluetoothAdapter through
         // BluetoothManager.
         if (mBluetoothManager == null) {
             mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
             if (mBluetoothManager == null) {
                 Log.e(TAG, "Unable to initialize BluetoothManager.");
-                responser.onFailed(10004, "不能初始化蓝牙BluetoothManager");
                 return false;
             }
         }
@@ -305,7 +364,6 @@ public class BluetoothLeService extends Service {
         mBluetoothAdapter = mBluetoothManager.getAdapter();
         if (mBluetoothAdapter == null) {
             Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
-            responser.onFailed(10001, "不支持蓝牙适配器");
             return false;
         }
         return true;
@@ -315,50 +373,9 @@ public class BluetoothLeService extends Service {
         return this.mBluetoothAdapter;
     }
 
-
-    public void writeBLECharacteristicValue(byte[] value, WriteResponser writeResponser){
-        if (mBluetoothGatt != null) {
-            this.mWriteResponser = writeResponser;
-            BluetoothGattService service = mBluetoothGatt.getService(uuidService);
-            if (service != null) {
-                mBluetoothGattCharateristic = service.getCharacteristic(uuidCharacteristic);
-                if (mBluetoothGattCharateristic == null) {
-                    Log.e(TAG, "mBluetoothGattCharateristic is null");
-                    this.mWriteResponser.onFailed(10007, "获取写入特征值失败!");
-                    return;
-                }
-                Log.e(TAG, "isWrite set true");
-                if(writeType == 0) {
-                    mBluetoothGattCharateristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
-                }else
-                {
-                    mBluetoothGattCharateristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
-                }
-                mBluetoothGattCharateristic.setValue(value);
-                boolean flagWriteCharacteristic = mBluetoothGatt.writeCharacteristic(mBluetoothGattCharateristic);
-                Log.e(TAG, "flagWriteCharacteristic:"+flagWriteCharacteristic);
-                if (!flagWriteCharacteristic) {
-                    Log.e(TAG, "false write");
-                    this.mWriteResponser.onFailed(10005, "写入特征值失败!");
-                }
-            } else {
-                Log.e(TAG, "get service fail");
-                this.mWriteResponser.onFailed(10006, "获取写入特服务失败!");
-            }
-        }
-    }
-
-    public void testDiscoverService() {
+    public boolean discoverService() {
         Log.e(TAG, "DiscoverService");
-        if (mBluetoothGatt != null) {
-            boolean flag = mBluetoothGatt.discoverServices();
-
-            if (flag) {
-                Log.e(TAG, "discoverServices success");
-            } else {
-                Log.e(TAG, "discoverServices fail");
-            }
-        }
+        return mBluetoothGatt.discoverServices();
     }
     public void rssiTest() {
         mBluetoothGatt.readRemoteRssi();
@@ -399,6 +416,7 @@ public class BluetoothLeService extends Service {
         // parameter to false.
         //chengyi to false //2017|10|25|1509|
         //set true will cause app can not get services
+        Log.i(TAG,"=====================this?:"+this);
         mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
         if (mBluetoothGatt != null) {
             Log.e(TAG, "Trying to create a new connection.");
@@ -470,26 +488,105 @@ public class BluetoothLeService extends Service {
             Log.w(TAG, "BluetoothAdapter not initialized");
             return false;
         }
-        Log.e(TAG, characteristic.getUuid().toString());
-        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
-        Log.w(TAG, "setCharacteristicNotification initialized ----------->");
-        BluetoothGattDescriptor desc = characteristic.getDescriptor(UUID.fromString(GattAttributes.uuid_identification_code));
-        if (enabled) {
-            desc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
-            returnValue = mBluetoothGatt.writeDescriptor(desc);
-        } else {
-            desc.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
-            returnValue = mBluetoothGatt.writeDescriptor(desc);
+        Log.i(TAG,characteristic.getUuid().toString());
+        Boolean isOpen =  mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
+//        Log.w(TAG, "setCharacteristicNotification initialized ----------->"+isOpen);
+        if(isOpen){
+//            for(BluetoothGattDescriptor dp:characteristic.getDescriptors()){
+//                Log.w(TAG,"BluetoothGattDescriptor ==>"+dp.getUuid().toString());
+//                boolean b1 = dp.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
+//                if(b1){
+//                    returnValue = mBluetoothGatt.writeDescriptor(dp);
+//                    Log.i(TAG,"BluetoothGattDescriptor writeDescriptor == "+dp.getUuid().toString());
+//                }
+//
+//            }
+
+            for(BluetoothGattDescriptor dp: characteristic.getDescriptors()){
+                if (dp != null) {
+                    if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
+                        dp.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
+                    } else if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
+                        dp.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
+                    }
+//                    Log.w(TAG,"BluetoothGattDescriptor ==>"+dp.getUuid().toString());
+                    returnValue = mBluetoothGatt.writeDescriptor(dp);
+                }
+            }
         }
-        // This is specific to Heart Rate Measurement.
-//        if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
-//            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
-//                    UUID.fromString(GattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
-//            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
-//            mBluetoothGatt.writeDescriptor(descriptor);
+
+        //UUID_FFF_characteristic_notify uuid_identification_code
+//        BluetoothGattDescriptor desc = characteristic.getDescriptor(UUID.fromString(GattAttributes.uuid_identification_code));
+//        if (enabled) {
+//            desc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
+//            returnValue = mBluetoothGatt.writeDescriptor(desc);
+//        } else {
+//            desc.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
+//            returnValue = mBluetoothGatt.writeDescriptor(desc);
 //        }
+        // This is specific to Heart Rate Measurement.
+        if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
+            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
+                    UUID.fromString(GattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
+            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
+            mBluetoothGatt.writeDescriptor(descriptor);
+        }
+
+
         return returnValue;
     }
+
+    public BluetoothGattCharacteristic findNotifyCharacteristic(UUID serviceUUID, UUID characteristicUUID, TextView textView) {
+        Log.i(TAG,"characteristic1 -->>"+serviceUUID+"=="+characteristicUUID);
+
+        String _tip = textView.getText().toString();
+        _tip += "characteristic1 -->>"+serviceUUID+"=="+characteristicUUID + "\n";
+        textView.setText(_tip);
+        List<BluetoothGattService>  gattServices=  mBluetoothGatt.getServices();
+        for (BluetoothGattService s : gattServices) {
+            Log.e(TAG,"gattServices -->>"+s.getUuid());
+            if(s.getUuid().equals(serviceUUID)){
+                Log.w(TAG,"get gattService -->>"+s.getUuid());
+                _tip += "get gattService -->>"+s.getUuid() + "\n";
+                textView.setText(_tip);
+
+                BluetoothGattService service = mBluetoothGatt.getService(s.getUuid());
+                BluetoothGattCharacteristic characteristic = null;
+                List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
+                for (BluetoothGattCharacteristic c : characteristics) {
+                    Log.e(TAG,"characteristic2 -->>"+c.getUuid() + " = " + c.getProperties() );
+                    _tip += "characteristic2 -->>"+c.getUuid() + " = " + c.getProperties() + "\n";
+                    textView.setText(_tip);
+                    if ((c.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0
+                            && characteristicUUID.equals(c.getUuid())) {
+                        characteristic = c;
+                        break;
+                    }
+                }
+                if (characteristic != null)
+                    return characteristic;
+                for (BluetoothGattCharacteristic c : characteristics) {
+                    Log.w(TAG,"characteristic3 -->>"+c.getUuid() + " = " + c.getProperties() );
+                    _tip += "characteristic3 -->>"+c.getUuid() + " = " + c.getProperties() + "\n";
+                    textView.setText(_tip);
+                    if ((c.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0
+                            && characteristicUUID.equals(c.getUuid())) {
+                        characteristic = c;
+                        break;
+                    }
+                }
+                Log.i(TAG,"characteristic4 -->>"+characteristic);
+                _tip += "characteristic4 -->>"+characteristic + "\n";
+                textView.setText(_tip);
+                return characteristic;
+            }
+        }
+
+
+        return null;
+
+    }
+
     public boolean setCharacteristicIndication(BluetoothGattCharacteristic characteristic,
                                                  boolean enabled) {
         boolean returnValue = false;
@@ -525,11 +622,31 @@ public class BluetoothLeService extends Service {
         return mBluetoothGatt.getServices();
     }
 
+    public BluetoothGattService getGattService(UUID uuid){
+        if(mBluetoothGatt == null){
+            return null;
+        }
+        return mBluetoothGatt.getService(uuid);
+    }
+
 
     public void readDescriptor(BluetoothGattDescriptor descriptor) {
         mBluetoothGatt.readDescriptor(descriptor);
     }
 
+    public String getCharacteristicUUID()
+    {
+        return uuidCharacteristic.toString();
+    }
+
+
+    public void setServiceandCharacteristic(UUID service , UUID characteristic, int mode, WriteResponser writeResponser)
+    {
+        uuidService = service;
+        uuidCharacteristic = characteristic;
+        writeType = mode;
+    }
+
     public void setServiceandCharacteristic(UUID service , UUID characteristic, int mode)
     {
         uuidService = service;
@@ -596,9 +713,39 @@ public class BluetoothLeService extends Service {
         return false;
     }
 
-    public String getCharacteristicUUID()
-    {
-        return uuidCharacteristic.toString();
+    //写入特征值
+    public void writeBLECharacteristicValue(byte[] value){
+
+        if (mBluetoothGatt != null ) {
+            BluetoothGattService service = mBluetoothGatt.getService(uuidService);
+            if (service != null) {
+                mBluetoothGattCharateristic = service.getCharacteristic(uuidCharacteristic);
+                if (mBluetoothGattCharateristic == null) {
+                    Log.e(TAG, "mBluetoothGattCharateristic is null");
+                    broadcastUpdateResponse(ACTION_RESPONSE_FAIL,ResponseEnum.GATT_GET_CHARACTERISTIC_ERROR.getCode(), ResponseEnum.GATT_GET_CHARACTERISTIC_ERROR.getMessage());
+                    return;
+                }
+                if(writeType == 0) {
+                    mBluetoothGattCharateristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
+                }else
+                {
+                    mBluetoothGattCharateristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
+                }
+                mBluetoothGattCharateristic.setValue(value);
+                boolean flagWriteCharacteristic = mBluetoothGatt.writeCharacteristic(mBluetoothGattCharateristic);
+//                Log.e(TAG, "flagWriteCharacteristic:"+flagWriteCharacteristic);
+                if (!flagWriteCharacteristic) {
+                    Log.e(TAG, "false write");
+                    broadcastUpdateResponse(ACTION_RESPONSE_FAIL,ResponseEnum.GATT_WRITE_ERROR.getCode(), ResponseEnum.GATT_WRITE_ERROR.getMessage());
+                }
+            } else {
+                Log.e(TAG, "get service fail");
+                broadcastUpdateResponse(ACTION_RESPONSE_FAIL,ResponseEnum.GATT_GET_SERVICE_ERROR.getCode(), ResponseEnum.GATT_GET_SERVICE_ERROR.getMessage());
+            }
+        }else{
+            Log.i(TAG,"11="+ResponseEnum.GATT_GET_ERROR.getCode());
+            broadcastUpdateResponse(ACTION_RESPONSE_FAIL,ResponseEnum.GATT_GET_ERROR.getCode(), ResponseEnum.GATT_GET_ERROR.getMessage());
+        }
     }
 
 }

+ 15 - 1
bboxblelib/src/main/java/com/slam/bboxblelib/Conversion.java

@@ -42,7 +42,7 @@ public class Conversion {
         return sb.toString();
     }
 
-    static String BytetohexString(byte[] b, boolean reverse) {
+    public  static String BytetohexString(byte[] b, boolean reverse) {
         StringBuilder sb = new StringBuilder(b.length * (2 + 1));
         Formatter formatter = new Formatter(sb);
 
@@ -189,4 +189,18 @@ public class Conversion {
         return ch >= 32 && ch < 127;
     }
 
+
+    /**
+     * 十六进制转正负数
+
+     * (2个字节的)
+     */
+    public static double parseHex4(String num) {
+        if (num.length() != 4) {
+            throw new NumberFormatException("Wrong length: " + num.length() + ", must be 4.");
+        }
+        int ret = Integer.parseInt(num, 16);
+        ret = ((ret & 0x8000) > 0) ? (ret - 0x10000) : (ret);
+        return (double) ret;
+    }
 }

+ 65 - 8
bboxblelib/src/main/java/com/slam/bboxblelib/DataEvent.java

@@ -1,19 +1,76 @@
 package com.slam.bboxblelib;
 
+import java.util.HashMap;
+import java.util.Map;
+
 public class DataEvent {
     String dataType = "hex";
-    String dataHex = "";
+    String dataStr = "";
+
+    String Hand = "";
+    Map<String, Double> acc = new HashMap<String, Double>();
+    Map<String, Double> gyro = new HashMap<String, Double>();
+    Integer min = 0;
+    Integer s = 0;
+    Integer ms = 0;
+
+
+    public DataEvent(String type,
+                     String data,
+                     String hand,
+                     Map<String, Double> accMap,
+                     Map<String, Double> gyroMap,
+                     Integer minTemp,
+                     Integer sTemp,
+                     Integer msTemp
+    ) {
+        dataType = type;
+        dataStr = data;
+        Hand = hand;
+        acc = accMap;
+        gyro = gyroMap;
+        min = minTemp;
+        s = sTemp;
+        ms = msTemp;
+    }
+
+
+    public DataEvent(String type,
+                     String data
+    ) {
+        dataType = type;
+        dataStr = data;
+    }
+
+    public String getDataType() {
+        return dataType;
+    }
+
+    public String getDataStr() {
+        return dataStr;
+    }
+
+    public String getHand() {
+        return Hand;
+    }
+
+    public Map<String, Double> getAcc() {
+        return acc;
+    }
+
+    public Map<String, Double> getGyro() {
+        return gyro;
+    }
 
-    public DataEvent(String type, String data) {
-        this.dataType = type;
-        this.dataHex = data;
+    public Integer getMin() {
+        return min;
     }
 
-    public String getType() {
-        return this.dataType;
+    public Integer getS() {
+        return s;
     }
 
-    public String getDataHex() {
-        return this.dataHex;
+    public Integer getMs() {
+        return ms;
     }
 }

+ 2 - 3
bboxblelib/src/main/java/com/slam/bboxblelib/GattAttributes.java

@@ -24,15 +24,14 @@ import java.util.HashMap;
 public class GattAttributes {
     private static HashMap<String, String> attributes = new HashMap();
     public static String HEART_RATE_MEASUREMENT = "00002a37-0000-1000-8000-00805f9b34fb";
-    public static String CLIENT_CHARACTERISTIC_CONFIG = "0000ffe1-0000-1000-8000-00805f9b34fb";
+    //0000ffe1-0000-1000-8000-00805f9b34fb
+    public static String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";
     public static String UUID_characteristic = "0000ffe6-0000-1000-8000-00805f9b34fb"; // maybe 32bytes?
     //数据传送部分服务FFF
     public static String UUID_FFF_service = "0000FFF0-0000-1000-8000-00805F9B34FB";
     public static String UUID_FFF_characteristic_write = "0000FFF2-0000-1000-8000-00805F9B34FB"; // maybe 32bytes?
     public static String UUID_FFF_characteristic_notify = "0000FFF1-0000-1000-8000-00805F9B34FB"; // maybe 32bytes?
 
-    //硬件唯一识别码
-    public static String uuid_identification_code = "00002902-0000-1000-8000-00805f9b34fb";
     //ota 下面的两个特征值
     public static String uuid_ota1 = "f000ffc1-0451-4000-b000-000000000000";
     public static String uuid_ota2 = "f000ffc2-0451-4000-b000-000000000000";

+ 30 - 5
bboxblelib/src/main/java/com/slam/bboxblelib/MainBluetooth.java

@@ -2,6 +2,7 @@ package com.slam.bboxblelib;
 
 import android.bluetooth.BluetoothAdapter;
 import android.content.Context;
+import android.widget.TextView;
 
 /**
  * Created by slambb on 2021/1/15.
@@ -9,16 +10,40 @@ import android.content.Context;
 
 public interface MainBluetooth {
 
-    void onCreate(Context context,Responser responser);
-    void onDestroy();
+    /**
+     * 注册部分事件
+     * @param context
+     * @param responser
+     */
+    void onRegisterEvent(Context context,Responser responser);
+    /**
+     * 注销部分事件
+     */
+    void onUnregisterEvent();
 
     BluetoothAdapter getBluetoothAdapter();
 
     BluetoothLeService getBluetoothLeService();
 
-    void startScanLeDevice(String var1);
+    /**
+     * 连接蓝牙设备
+     * @param address
+     */
+    void startConnectLeDevice(String address);
 
-    void stopScanLeDevice();
+    //停止搜索蓝牙设备
+    void stopConnectLeDevice();
 
-    void writeValueToFFF(String var1, WriteResponser var2);
+    /**
+     * 断开连接
+     */
+    void disConnectLeDevice();
+
+    /**
+     * 写入FFF服务
+     * @param value
+     */
+    void writeValueToFFF(String value);
+
+    void findNotifyCharacteristic(TextView textView);
 }

+ 3 - 2
bboxblelib/src/main/java/com/slam/bboxblelib/Responser.java

@@ -5,6 +5,7 @@ package com.slam.bboxblelib;
  */
 
 public interface Responser{
-    void onSuccess(DeviceEvent deviceEvent);
-    void onFailed(Integer var1, String prompt);
+    void onSuccess(Integer code,  String prompt , DeviceEvent deviceEvent);
+    void onFailed(Integer code, String prompt);
+    void onUpdateData(Integer code,  String prompt ,DataEvent dataEvent);
 }

+ 331 - 113
bboxblelib/src/main/java/com/slam/bboxblelib/impl/MainBluetoothImpl.java

@@ -4,7 +4,6 @@ import android.bluetooth.BluetoothAdapter;
 import android.bluetooth.BluetoothDevice;
 import android.bluetooth.BluetoothGattCharacteristic;
 import android.bluetooth.BluetoothGattService;
-import android.bluetooth.BluetoothManager;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.Context;
@@ -14,10 +13,9 @@ import android.content.ServiceConnection;
 import android.os.Handler;
 import android.os.IBinder;
 import android.util.Log;
-import android.widget.Toast;
+import android.widget.TextView;
 
 import com.slam.bboxblelib.BluetoothLeService;
-import com.slam.bboxblelib.CheckboxEvent;
 import com.slam.bboxblelib.Conversion;
 import com.slam.bboxblelib.DataEvent;
 import com.slam.bboxblelib.DeviceEvent;
@@ -26,16 +24,18 @@ import com.slam.bboxblelib.MainBluetooth;
 import com.slam.bboxblelib.Responser;
 import com.slam.bboxblelib.WriteResponser;
 
-import org.greenrobot.eventbus.EventBus;
-import org.greenrobot.eventbus.Subscribe;
-import org.greenrobot.eventbus.ThreadMode;
-
+import java.lang.reflect.Method;
+import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
+import java.util.Timer;
+import java.util.TimerTask;
 import java.util.UUID;
 
 import static android.content.Context.BIND_AUTO_CREATE;
+import static com.slam.bboxblelib.GattAttributes.UUID_FFF_service;
 
 /**
  * Created by slambb on 2021/1/14.
@@ -43,6 +43,25 @@ import static android.content.Context.BIND_AUTO_CREATE;
 
 public class MainBluetoothImpl implements MainBluetooth {
     private final static String TAG = MainBluetoothImpl.class.getSimpleName();
+
+    //Responser value
+    public static final int UNABLE_INIT_BLUETOOTH = 10000;
+    public static final int DISABLE_BLUETOOTH = 10001;
+    public static final int STATE_CONNECTED = 10002;
+    public static final int UNABLE_CONNECT_BLUETOOTH = 10003;
+    public static final int STOP_SCAN_BLUETOOTH = 10004;
+    public static final int CONNECT_BLUETOOTH = 10005;
+    public static final int BONED_NOT_CONNECTED = 10007;
+    public static final int GATT_CONNECTION = 20001;
+    public static final int GATT_DISCONNECTED = 20002;
+    public static final int GATT_SERVICES_DISCOVERED = 20002;
+    public static final int GATT_SERVICES_NULL = 20003;
+    public static final int GATT_CHARACTERISTIC_NOTIFICATION_SUCCESS = 20004;
+    public static final int GATT_CHARACTERISTIC_NOTIFICATION_CHANGED = 20005;
+    public static final int GATT_CHARACTERISTIC_NOTIFICATION_STRING = 20006;
+    public static final int GATT_CHARACTERISTIC_WRITE_SUCCESS = 20007;
+    public static final int GATT_RESPONSE_FAIL = 20008;
+
     // Stops scanning after 10 seconds.
     private static final long SCAN_PERIOD = 10000;
     private BluetoothLeService mBluetoothLeService;
@@ -50,23 +69,26 @@ public class MainBluetoothImpl implements MainBluetooth {
     private String mDeviceName;
     private String mDeviceAddress;
     private BluetoothAdapter mBluetoothAdapter;
-    private int mFragmentIndex = 2; //0: query 1: script 2:uuid 3: report 4: bekenTest
     private int retryNo = 3;
     private Handler mHandler;
     private boolean flagDiscoverFail = false;
+    //是否解析数据,默认是开启解析数据
+    private boolean bParsingData = true;
     private Context mContext;
+    private BluetoothGattCharacteristic mNotifyCharacteristic;
+    private String searName = "BGBox";
+
     //回调
     private Responser mResponser;
-    private WriteResponser mWriteResponser = null;
     // Code to manage Service lifecycle.
     private final ServiceConnection mServiceConnection = new ServiceConnection() {
 
         @Override
         public void onServiceConnected(ComponentName componentName, IBinder service) {
-            mBluetoothLeService = ((BluetoothLeService.LocalBinder)service).getService();
-            if (!mBluetoothLeService.initialize(mResponser)) {
+            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
+            if (!mBluetoothLeService.initialize()) {
                 Log.e(TAG, "Unable to initialize Bluetooth");
-                mResponser.onFailed(10000, "未初始化蓝牙!");
+                mResponser.onFailed(UNABLE_INIT_BLUETOOTH, "未初始化蓝牙!");
             }
             mConnected = 1;
             mBluetoothAdapter = mBluetoothLeService.getmBluetoothAdapter();
@@ -77,7 +99,7 @@ public class MainBluetoothImpl implements MainBluetooth {
         @Override
         public void onServiceDisconnected(ComponentName componentName) {
             Log.e(TAG, "get disconnect event11");
-           mBluetoothLeService = null;
+            mBluetoothLeService = null;
         }
     };
 
@@ -91,23 +113,30 @@ public class MainBluetoothImpl implements MainBluetooth {
         @Override
         public void onReceive(Context context, Intent intent) {
             final String action = intent.getAction();
-            Log.e(TAG, "蓝牙action:" + action);
-            if ("android.bluetooth.adapter.action.STATE_CHANGED".equals(action)) {
-                switch(mBluetoothAdapter.getState()) {
+            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
+                switch (mBluetoothAdapter.getState()) {
                     case 10:
                         Log.e(TAG, "蓝牙状态:disable");
-                       mResponser.onFailed(10002, "蓝牙功能禁用!");
+                        mResponser.onFailed(DISABLE_BLUETOOTH, "蓝牙功能禁用!");
                 }
             }
 
-            if ("com.example.bluetooth.le.ACTION_GATT_CONNECTED".equals(action)) {
+            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                 Log.e(TAG, "蓝牙状态:ACTION_GATT_CONNECTED");
-                if (mBluetoothLeService != null) {
-                   mBluetoothLeService.testDiscoverService();
+                boolean bDiscover = mBluetoothLeService.discoverService();
+                if (bDiscover) {
+                    mResponser.onSuccess(GATT_CONNECTION, "GATT连接成功", null);
+                } else {
+                    mResponser.onFailed(GATT_DISCONNECTED, "GATT连接失败");
                 }
-            } else if ("com.example.bluetooth.le.ACTION_GATT_DISCONNECTED".equals(action)) {
+
+            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                 Log.e(TAG, "蓝牙状态:Gatt Disconnected");
-            } else if ("com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED".equals(action)) {
+                mResponser.onFailed(GATT_DISCONNECTED, "GATT断开连接。");
+
+            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
+                mResponser.onSuccess(GATT_SERVICES_DISCOVERED, "GATT服务搜索成功。", null);
+                //已查询到
                 mConnected = 2;
                 retryNo = 3;
                 flagDiscoverFail = false;
@@ -115,44 +144,165 @@ public class MainBluetoothImpl implements MainBluetooth {
                 List<BluetoothGattService> gattServices = mBluetoothLeService.getSupportedGattServices();
                 if (gattServices == null) {
                     Log.e(TAG, "gattService is null");
+                    mResponser.onFailed(GATT_SERVICES_NULL, "获取gatt服务列表为空。");
                     return;
                 }
-
-                Iterator var5 = gattServices.iterator();
-
-                while(var5.hasNext()) {
-                    BluetoothGattService gattService = (BluetoothGattService)var5.next();
-                    List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
-                    Iterator var8 = gattCharacteristics.iterator();
-
-                    while(var8.hasNext()) {
-                        BluetoothGattCharacteristic gattCharacteristic = (BluetoothGattCharacteristic)var8.next();
-                        if (gattCharacteristic.getUuid().equals(UUID.fromString(GattAttributes.UUID_FFF_characteristic_notify))) {
-                            Log.i(TAG, "监听匹配成功:" + GattAttributes.UUID_FFF_characteristic_notify + " ==" + gattCharacteristic.getUuid());
-                            if (mBluetoothLeService.setCharacteristicNotification(gattCharacteristic, true)) {
-                                mBluetoothLeService.readDescriptor(gattCharacteristic.getDescriptor(UUID.fromString(GattAttributes.uuid_identification_code)));
-                            }
-
-                            return;
-                        }
+                BluetoothGattService gattService = mBluetoothLeService.getGattService(UUID.fromString(UUID_FFF_service));
+                BluetoothGattCharacteristic characteristic = gattService.getCharacteristic(UUID.fromString(GattAttributes.UUID_FFF_characteristic_notify));
+
+                final int charaProp = characteristic.getProperties();
+                if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
+                    // If there is an active notification on a characteristic, clear
+                    // it first so it doesn't update the data field on the user interface.
+                    if (mNotifyCharacteristic != null) {
+                        mBluetoothLeService.setCharacteristicNotification(
+                                mNotifyCharacteristic, false);
+                        mNotifyCharacteristic = null;
                     }
+                    mBluetoothLeService.readCharacteristic(characteristic);
                 }
+                if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
+                    mNotifyCharacteristic = characteristic;
+                    boolean b1 = mBluetoothLeService.setCharacteristicNotification(
+                            characteristic, true);
+                    if (b1) {
+                        mBluetoothLeService.readDescriptor(characteristic.getDescriptor(UUID.fromString(GattAttributes.CLIENT_CHARACTERISTIC_CONFIG)));
+                        Log.i(TAG, "setCharacteristicNotification1==成功!");
+                        mResponser.onSuccess(GATT_CHARACTERISTIC_NOTIFICATION_SUCCESS, "设置GATT通知成功。", null);
+                    }
+                }
+
+//                if (mBluetoothLeService.setCharacteristicNotification(characteristic, true)) {
+//                    //uuid_identification_code
+//                    mBluetoothLeService.readDescriptor(characteristic.getDescriptor(UUID.fromString(GattAttributes.uuid_identification_code)));
+//                    Log.i(TAG, "setCharacteristicNotification1==成功!");
+//
+//                }
+//                Iterator var5 = gattServices.iterator();
+//                while(var5.hasNext()) {
+//                    BluetoothGattService gattService = (BluetoothGattService)var5.next();
+//                    BluetoothGattCharacteristic characteristic = gattService.getCharacteristic(UUID.fromString(GattAttributes.UUID_FFF_characteristic_notify));
+//
+//                    if (mBluetoothLeService.setCharacteristicNotification(characteristic, true)) {
+//                        //uuid_identification_code
+//                        mBluetoothLeService.readDescriptor(characteristic.getDescriptor(UUID.fromString(GattAttributes.uuid_identification_code)));
+//                        Log.i(TAG, "setCharacteristicNotification1==成功!");
+//
+//                    }
+//                    List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
+//                    Log.i(TAG,"11----->" + gattService.getUuid().toString());
+//                    Iterator var8 = gattCharacteristics.iterator();
+//                    while(var8.hasNext()) {
+//                        BluetoothGattCharacteristic gattCharacteristic = (BluetoothGattCharacteristic)var8.next();
+//                        if (gattCharacteristic.getUuid().equals(UUID.fromString(GattAttributes.UUID_FFF_characteristic_notify))) {
+//                            Log.i(TAG, "监听匹配成功:" + GattAttributes.UUID_FFF_characteristic_notify + " ==" + gattCharacteristic.getUuid());
+//
+//                            if (mBluetoothLeService.setCharacteristicNotification(gattCharacteristic, true)) {
+//                                //uuid_identification_code
+//                                mBluetoothLeService.readDescriptor(gattCharacteristic.getDescriptor(UUID.fromString(GattAttributes.uuid_identification_code)));
+//                                Log.i(TAG, "setCharacteristicNotification1==成功!");
+//
+//                            }
+//
+//                            return;
+//                        }
+//                    }
+//                }
+            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE_SUCCESS.equals(action)) {
+//                    Pattern pattern = Pattern.compile("[0]*");
+//                    Matcher isNum = pattern.matcher(_hexStr);
+//                    if(isNum.matches()){
+//                        Log.e(TAG, "返回0不走解析");
+//                        return;
+////                    }
+//                String _hexStr;
+//                _hexStr = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
+//                Log.i(TAG, "hex:" + _hexStr + Integer.parseInt(_hexStr));
+
+            } else if (BluetoothLeService.ACTION_RESPONSE_SUCCESS.equals(action)) {
+//                String data = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
+//                String code = intent.getStringExtra(BluetoothLeService.EXTRA_CODE);
+//                String message = intent.getStringExtra(BluetoothLeService.EXTRA_MESSAGE);
+                //todo 目前只处理写入成功回调
+                mResponser.onSuccess(GATT_CHARACTERISTIC_WRITE_SUCCESS, "设置GATT写入数据成功!", null);
+            } else if (BluetoothLeService.ACTION_RESPONSE_FAIL.equals(action)) {
+//              GATT_GET_ERROR(10004,"获取Gatt特服务失败!"),
+//              GATT_GET_SERVICE_ERROR(10005,"获取写入服务失败!"),
+//              GATT_GET_CHARACTERISTIC_ERROR(10006,"获取写入特征值失败!"),
+//              GATT_WRITE_ERROR(10007,"写入数据失败!"),
+                Integer code = intent.getIntExtra(BluetoothLeService.EXTRA_CODE, 0);
+                String message = intent.getStringExtra(BluetoothLeService.EXTRA_MESSAGE);
+                //连接错误
+                mResponser.onFailed(code, message);
             } else {
-                String a;
-                if ("com.example.bluetooth.le.ACTION_DATA_AVAILABLE".equals(action)) {
-                    a = intent.getStringExtra("com.example.bluetooth.le.EXTRA_DATA");
-                    if (mWriteResponser != null) {
-                        DataEvent dataEvent = new DataEvent("hex", a);
-                        mWriteResponser.onUpdateData(dataEvent);
+                //更新change数据
+                String _hexStr;
+                if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
+                    _hexStr = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
+                    if (bParsingData) {
+                        //R/L 左手还是右手
+                        String _hand = _hexStr.substring(6, 8);
+                        String axStr = _hexStr.substring(8, 12);
+                        String ayStr = _hexStr.substring(12, 16);
+                        String azStr = _hexStr.substring(16, 20);
+                        //一个字节最大只能表示265  2个字节可以表示65536  然后你这边做一下转换 例如00 3E   3*16+14=62 ----->0.03  g
+                        //(真实值= AD值 /32768  * 16)
+                        //0.003 = 62 / 2768  * 16
+                        double ax = Conversion.parseHex4(axStr) / 32768 * 16;
+                        double ay = Conversion.parseHex4(ayStr) / 32768 * 16;
+                        double az = Conversion.parseHex4(azStr) / 32768 * 16;
+                        Map<String, Double> _acc = new HashMap<String, Double>();
+                        _acc.put("ax", ax);
+                        _acc.put("ay", ay);
+                        _acc.put("az", az);
+                        String gxStr = _hexStr.substring(20, 24);
+                        String gyStr = _hexStr.substring(24, 28);
+                        String gzStr = _hexStr.substring(28, 32);
+                        //角速度(AD值/32768 * 2000) 角速度单位是 °/s  范围是 正负2000
+                        double gx = Conversion.parseHex4(gxStr) / 32768 * 2000;
+                        double gy = Conversion.parseHex4(gyStr) / 32768 * 2000;
+                        double gz = Conversion.parseHex4(gzStr) / 32768 * 2000;
+                        Map<String, Double> _gyro = new HashMap<String, Double>();
+                        _gyro.put("gx", gx);
+                        _gyro.put("gy", gy);
+                        _gyro.put("gz", gz);
+                        //毫秒
+                        Integer ms = Integer.parseInt(_hexStr.substring(2, 6), 16);
+                        //分
+                        Integer min = Integer.parseInt(_hexStr.substring(32, 34), 16);
+                        //秒
+                        Integer s = Integer.parseInt(_hexStr.substring(34, 36), 16);
+
+
+                        DataEvent dataEvent = new DataEvent(
+                                "CHANGED", //dataType
+                                _hexStr,    //dataStr
+                                Conversion.hexStr2Str(_hand), //hand
+                                _acc, //加速计
+                                _gyro, //陀螺仪
+                                min, //分
+                                s,   //秒
+                                ms   //毫秒
+                        );
+                        mResponser.onUpdateData(GATT_CHARACTERISTIC_NOTIFICATION_CHANGED, "蓝牙数据回调刷新对象", dataEvent);
+                    } else {
+                        //直接返回字符串
+                        DataEvent dataEvent = new DataEvent(
+                                "STRING",
+                                Conversion.hexStringToString(_hexStr)
+                        );
+                        mResponser.onUpdateData(GATT_CHARACTERISTIC_NOTIFICATION_STRING, "蓝牙数据回调JSON字符串", dataEvent);
                     }
-                } else if (!"com.example.bluetooth.le.ACTION_DATA_WRITE_FAIL".equals(action) && !"com.example.bluetooth.le.ACTION_DATA_WRITE_SUCCESS".equals(action)) {
-                    if ("com.example.bluetooth.le.ACTION_DATA_READ_FAIL".equals(action)) {
-                    } else if ("com.example.bluetooth.le.QUERY_SUCCESS".equals(action)) {
-                    } else if ("com.example.bluetooth.le.ACTION_NOTIFY_SUCCESS".equals(action)) {
-                        a = intent.getStringExtra("com.example.bluetooth.le.EXTRA_DATA");
-
-                    } else if ("com.example.bluetooth.le.ACTION_NOTIFY_FAIL".equals(action)) {
-                    } else if ("com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED_FAIL".equals(action)) {
+
+
+                } else if (!BluetoothLeService.ACTION_DATA_WRITE_FAIL.equals(action) && !BluetoothLeService.ACTION_DATA_WRITE_SUCCESS.equals(action)) {
+                    if (BluetoothLeService.ACTION_DATA_READ_FAIL.equals(action)) {
+                    } else if (BluetoothLeService.ACTION_QUERY_SUCCESS.equals(action)) {
+                    } else if (BluetoothLeService.ACTION_NOTIFY_SUCCESS.equals(action)) {
+                        _hexStr = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
+
+                    } else if (BluetoothLeService.ACTION_NOTIFY_FAIL.equals(action)) {
+                    } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED_FAIL.equals(action)) {
                         Log.e(TAG, "get service fail");
                         if (retryNo > 0) {
                             flagDiscoverFail = true;
@@ -170,8 +320,8 @@ public class MainBluetoothImpl implements MainBluetooth {
                         } else {
                             mBluetoothLeService.disconnect();
                         }
-                    } else if ("android.bluetooth.device.action.BOND_STATE_CHANGED".equals(action)) {
-                        BluetoothDevice aaa = (BluetoothDevice)intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
+                    } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
+                        BluetoothDevice aaa = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                         if (aaa.getBondState() == 12) {
                             Log.e(TAG, "bonded");
                         } else if (aaa.getBondState() == 11) {
@@ -179,7 +329,7 @@ public class MainBluetoothImpl implements MainBluetooth {
                         } else {
                             Log.e(TAG, "unbound");
                         }
-                    } else if ("android.bluetooth.device.action.PAIRING_REQUEST".equals(action)) {
+                    } else if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {
 
                     }
                 }
@@ -194,6 +344,9 @@ public class MainBluetoothImpl implements MainBluetooth {
         intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
         intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
         intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
+        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE_SUCCESS);
+        intentFilter.addAction(BluetoothLeService.ACTION_RESPONSE_FAIL);
+        intentFilter.addAction(BluetoothLeService.ACTION_RESPONSE_SUCCESS);
         //vers add
         intentFilter.addAction(BluetoothLeService.ACTION_DATA_WRITE_FAIL);
         intentFilter.addAction(BluetoothLeService.ACTION_DATA_WRITE_SUCCESS);
@@ -215,7 +368,7 @@ public class MainBluetoothImpl implements MainBluetooth {
         @Override
         public void run() {
             mBluetoothAdapter.stopLeScan(mLeScanCallback);
-            mResponser.onSuccess(new DeviceEvent("none"));
+            mResponser.onSuccess(STOP_SCAN_BLUETOOTH, "停止扫描蓝牙。", null);
         }
     };
     // Device scan callback.
@@ -223,23 +376,24 @@ public class MainBluetoothImpl implements MainBluetooth {
             new BluetoothAdapter.LeScanCallback() {
                 @Override
                 public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
-                    //todo 返回查找到的设备对象
                     String _name = device.getName();
-                    if (_name != null && _name.indexOf("BGBox") > -1) {
-                        mDeviceAddress = device.getAddress();
-                       mDeviceName = device.getName();
-                        if (mBluetoothLeService != null) {
-                            boolean result =mBluetoothLeService.connect(mDeviceAddress);
-                            Log.e(TAG, "device Connect request result =" + result);
+                    if (_name != null && _name.indexOf(searName) > -1) {
+                        //获取到已经连接的设备 ,进行连接操作
+                        boolean _bSuccess = mBluetoothLeService.connect(mDeviceAddress);
+                        if (_bSuccess) {
+                            mDeviceAddress = device.getAddress();
+                            mDeviceName = device.getName();
+                            DeviceEvent outDevice = new DeviceEvent("device", device, rssi);
+                            outDevice.setDeviceAddress(mDeviceAddress);
+                            outDevice.setDeviceName(mDeviceName);
+                            mResponser.onSuccess(CONNECT_BLUETOOTH, "设备成功连接", outDevice);
+                            stopConnectLeDevice();
+                        } else {
+                            mResponser.onFailed(UNABLE_CONNECT_BLUETOOTH, "搜索连接失败!");
                         }
 
-                        DeviceEvent outDevice = new DeviceEvent("device", device, rssi);
-                        outDevice.setDeviceAddress(mDeviceAddress);
-                        outDevice.setDeviceName(mDeviceName);
-                        mResponser.onSuccess(outDevice);
-                        stopScanLeDevice();
                     } else {
-                        mResponser.onFailed(10003, "搜索连接失败!");
+                        mResponser.onFailed(UNABLE_CONNECT_BLUETOOTH, "搜索连接失败!");
                     }
                 }
             };
@@ -251,78 +405,142 @@ public class MainBluetoothImpl implements MainBluetooth {
      * @param context
      */
     @Override
-    public void onCreate(Context context, Responser responser) {
+    public void onRegisterEvent(Context context, Responser responser) {
+        Log.w(TAG, "*************************onCreate**********************");
         //回调赋值
         mResponser = responser;
         mHandler = new Handler();
         mContext = context;
         Intent gattServiceIntent = new Intent(mContext, BluetoothLeService.class);
-        context.bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
-        context.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
+        mContext.bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
+        mContext.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
     }
 
     @Override
-    public void onDestroy() {
-        this.mContext.unregisterReceiver(this.mGattUpdateReceiver);
-        this.mBluetoothLeService.disconnect();
-        this.mContext.unbindService(this.mServiceConnection);
-        this.mBluetoothLeService = null;
+    public void onUnregisterEvent() {
+        Log.w(TAG, "*****************************onDestroy***********************");
+        mBluetoothLeService.disconnect();
+        mContext.unregisterReceiver(mGattUpdateReceiver);
+        mContext.unbindService(mServiceConnection);
     }
 
-    //扫描设备,包括返回已连接的设备
+    //扫描设备,并连接
     @Override
-    public void startScanLeDevice(String searName) {
-        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
-        //todo 返回已连接的设备对象
-        if (pairedDevices.size() != 0) {
-            Iterator var3 = pairedDevices.iterator();
-            while(var3.hasNext()) {
-                BluetoothDevice device = (BluetoothDevice)var3.next();
-                if (device.getName().indexOf("BGBox") > -1) {
-                    Log.e(TAG, "**********DeviceEvent responser2=" + device.getAddress() + "=" + device.getName());
-                    this.mDeviceAddress = device.getAddress();
-                    this.mDeviceName = device.getName();
-                    if (this.mBluetoothLeService != null) {
-                        boolean result = this.mBluetoothLeService.connect(this.mDeviceAddress);
-                        Log.e(TAG, "pairedDevices Connect request result =" + result);
+    public void startConnectLeDevice(String searNameTemp) {
+        searName = searNameTemp;
+        Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象
+        try {//得到连接状态的方法
+            Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
+            //打开权限
+            method.setAccessible(true);
+            //获取蓝牙已匹配的设备
+            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
+            if (pairedDevices.size() != 0) {
+                Iterator pairedDevice = pairedDevices.iterator();
+                boolean _bConnectSuccess = false;
+                while (pairedDevice.hasNext()) {
+                    BluetoothDevice device = (BluetoothDevice) pairedDevice.next();
+                    //获取名称为BGBox的设备
+                    if (device.getName().indexOf(searName) > -1) {
+                        Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
+                        method.setAccessible(true);
+                        boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);
+                        if (isConnected) {
+                            Log.i(TAG, "connected:" + device.getName() + " = " + device.getAddress());
+                            //获取到已经连接的设备 ,进行连接操作
+                            boolean _bSuccess = mBluetoothLeService.connect(device.getAddress());
+                            if (_bSuccess) {
+                                mDeviceAddress = device.getAddress();
+                                mDeviceName = device.getName();
+                                DeviceEvent devices = new DeviceEvent("pairedDevices", pairedDevices);
+                                devices.setDeviceAddress(mDeviceAddress);
+                                devices.setDeviceName(mDeviceName);
+                                mResponser.onSuccess(CONNECT_BLUETOOTH, "设备成功连接", devices);
+                                _bConnectSuccess = _bSuccess;
+                                break;
+                            }
+                        }
                     }
-
-                    DeviceEvent devices = new DeviceEvent("pairedDevices", pairedDevices);
-                    devices.setDeviceAddress(this.mDeviceAddress);
-                    devices.setDeviceName(this.mDeviceName);
-                    this.mResponser.onSuccess(devices);
-                    return;
                 }
+                //todo 如果有匹配的设备,但是没有连接的。提示需要跳转手机蓝牙页面操作
+                if (!_bConnectSuccess) {
+                    mResponser.onFailed(BONED_NOT_CONNECTED, "匹配列表设备未连接。");
+                }
+
+
+            } else {
+                //没有匹配的设备,搜索设备
+                mBluetoothAdapter.startLeScan(mLeScanCallback);
+                mHandler.postDelayed(mGetVersionTimeoutThread, 10000L);
             }
+
+
+        } catch (Exception e) {
+            e.printStackTrace();
         }
 
-        this.mBluetoothAdapter.startLeScan(this.mLeScanCallback);
-        this.mHandler.postDelayed(this.mGetVersionTimeoutThread, 10000L);
+
     }
 
     @Override
-    public void writeValueToFFF(String value, WriteResponser writeResponser) {
+    public void stopConnectLeDevice() {
+        mBluetoothAdapter.stopLeScan(mLeScanCallback);
+        mHandler.removeCallbacks(mGetVersionTimeoutThread);
+    }
+
+    @Override
+    public void disConnectLeDevice() {
+
+        //先发送一个关闭指令到蓝牙
+        String str = Conversion.str2HexStr("4");
+        byte[] result = Conversion.hexStringToBytes(str);
+        UUID service = UUID.fromString(GattAttributes.UUID_FFF_service);
+        UUID characteristic = UUID.fromString(GattAttributes.UUID_FFF_characteristic_write);
+        mBluetoothLeService.setServiceandCharacteristic(service, characteristic, 0);
+        mBluetoothLeService.writeBLECharacteristicValue(result);
+
+        Timer timer = new Timer();
+        timer.schedule(new TimerTask() {
+            public void run() {
+                //断开蓝牙连接
+                mBluetoothLeService.disconnect();
+            }
+        }, 200);
+
+    }
+
+    @Override
+    public void writeValueToFFF(String value) {
+
+        if (value.equals("3") || value.equals("4")) {
+            bParsingData = true;
+        } else if (value.equals("V")) {
+            bParsingData = false;
+        }
+
         String str = Conversion.str2HexStr(value);
         byte[] result = Conversion.hexStringToBytes(str);
-        UUID service = UUID.fromString("0000FFF0-0000-1000-8000-00805F9B34FB");
-        UUID characteristic = UUID.fromString("0000FFF2-0000-1000-8000-00805F9B34FB");
-        int mode = 0;
-        this.mWriteResponser = writeResponser;
-        this.mBluetoothLeService.setServiceandCharacteristic(service, characteristic, mode);
-        this.mBluetoothLeService.writeBLECharacteristicValue(result, writeResponser);
+        UUID service = UUID.fromString(GattAttributes.UUID_FFF_service);
+        UUID characteristic = UUID.fromString(GattAttributes.UUID_FFF_characteristic_write);
+        mBluetoothLeService.setServiceandCharacteristic(service, characteristic, 0);
+        mBluetoothLeService.writeBLECharacteristicValue(result);
     }
 
     @Override
-    public void stopScanLeDevice() {
-        mBluetoothAdapter.stopLeScan(mLeScanCallback);
-        mHandler.removeCallbacks(mGetVersionTimeoutThread);
+    public void findNotifyCharacteristic(TextView textView) {
+        UUID service = UUID.fromString(GattAttributes.UUID_FFF_service);
+        UUID characteristic = UUID.fromString(GattAttributes.UUID_FFF_characteristic_write);
+        mBluetoothLeService.findNotifyCharacteristic(service, characteristic, textView);
     }
 
+
     @Override
     public BluetoothAdapter getBluetoothAdapter() {
         return mBluetoothAdapter;
     }
 
     @Override
-    public BluetoothLeService getBluetoothLeService() {return this.mBluetoothLeService; }
+    public BluetoothLeService getBluetoothLeService() {
+        return mBluetoothLeService;
+    }
 }