Explorar o código

1.使用厂商蓝牙SDK去连接蓝牙
2.部分优化

JaycePC hai 1 mes
pai
achega
81e325914d

BIN=BIN
app/libs/armeabi-v7a/libfacp.so


BIN=BIN
app/libs/armeabi-v7a/libota.so


BIN=BIN
app/libs/armeabi-v7a/libutil.so


BIN=BIN
app/libs/feasyblue.jar


+ 3 - 0
app/src/main/java/xn/hxp/app/ChemicalApp.kt

@@ -19,6 +19,7 @@ import com.rc.httpcore.bean.UserData
 import com.tencent.smtt.export.external.TbsCoreSettings
 import com.tencent.smtt.sdk.QbSdk
 import xn.hxp.R
+import xn.hxp.utils.bluetooth.SppTool
 
 //新版化学品-使用V3版本API
 class ChemicalApp : Application() {
@@ -53,6 +54,8 @@ class ChemicalApp : Application() {
 
     override fun onCreate() {
         super.onCreate()
+
+        SppTool.INSTANCE.init()
         BleManager.getInstance().enableLog(true).setReConnectCount(3).init(this)
 
         DialogX.init(this)

+ 2 - 6
app/src/main/java/xn/hxp/ui/MainActivity.kt

@@ -56,7 +56,6 @@ import xn.hxp.utils.RelativeLayoutDebouncer
 import xn.hxp.utils.SharedPreferencesHelper
 import xn.hxp.utils.TimeUpdater
 import xn.hxp.utils.UiManager
-import xn.hxp.utils.bluetooth.BleTool
 import xn.hxp.weidith.CustomDialog
 import java.net.ConnectException
 import java.net.SocketTimeoutException
@@ -180,12 +179,10 @@ public class MainActivity : BaseActivity() {
             }
         }
         viewBinding.inc.bleIV.visibility = View.VISIBLE
-        val bleKey = SPUtils.getInstance().getString("bleKey", "")
-        if (null == bleKey || TextUtils.isEmpty(bleKey)) {
+        val sppMac = SPUtils.getInstance().getString("sppMac", "")
+        if (null == sppMac || TextUtils.isEmpty(sppMac)) {
             viewBinding.inc.bleIV.setBackgroundResource(R.drawable.ic_ble_unconnected)
             PopTip.show("未配置蓝牙称设备!").showLong()
-        } else {
-            BleTool.INSTANCE.connect()
         }
     }
 
@@ -399,7 +396,6 @@ public class MainActivity : BaseActivity() {
 
     override fun onDestroy() {
         super.onDestroy()
-        BleTool.INSTANCE.disconnect()
         unregisterReceiver(timeTickReceiver)
         try {
             // 停止定时更新

+ 12 - 6
app/src/main/java/xn/hxp/ui/SettingActivity.java

@@ -18,6 +18,7 @@ import com.rc.core.ui.activity.BaseActivity;
 import xn.hxp.databinding.ActivitySettingBinding;
 import xn.hxp.utils.SharedPreferencesHelper;
 import xn.hxp.utils.Tool;
+import xn.hxp.utils.bluetooth.SppTool;
 import xn.hxp.weidith.ble.BleSelectorDialog;
 
 public class SettingActivity extends BaseActivity {
@@ -39,7 +40,8 @@ public class SettingActivity extends BaseActivity {
         binding.settingBT.setOnClickListener(v -> Tool.INSTANCE.openSetting());
         binding.barSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> Tool.INSTANCE.showBar(isChecked));
         binding.httpUriET.setText(Tool.INSTANCE.getBaseUrl().toString());
-        binding.bleTV.setText(SPUtils.getInstance().getString("bleKey", ""));
+        binding.bleET.setText(SPUtils.getInstance().getString("sppMac", ""));
+        binding.bleNameTV.setText(SPUtils.getInstance().getString("sppName", ""));
         // 前同事代码
         SettingsBean settingsBean = SharedPreferencesHelper.INSTANCE.getUrlBase(this);
         if (null != settingsBean) {
@@ -73,10 +75,14 @@ public class SettingActivity extends BaseActivity {
         binding.httpUriTestBT.setOnClickListener(v -> binding.httpUriET.setText("http://192.168.1.8/api/"));
         // 西农地址输入
         binding.httpUriXnBT.setOnClickListener(v -> binding.httpUriET.setText("http://172.16.0.65/api/"));
-        // 蓝牙配置
-        binding.bleTV.setOnClickListener(v -> {
+        // 蓝牙扫描
+        binding.scanBT.setOnClickListener(v -> {
             BleSelectorDialog bleSelectorDialog = new BleSelectorDialog(SettingActivity.this);
-            bleSelectorDialog.setOnDismissListener(dialog -> binding.bleTV.setText(SPUtils.getInstance().getString("bleKey", "")));
+            bleSelectorDialog.setOnDismissListener(dialog -> {
+                binding.bleET.setText(SPUtils.getInstance().getString("sppMac", ""));
+                binding.bleNameTV.setText(SPUtils.getInstance().getString("sppName", ""));
+                SppTool.INSTANCE.disconnect();
+            });
             bleSelectorDialog.show();
         });
         // 保存
@@ -100,9 +106,9 @@ public class SettingActivity extends BaseActivity {
                 binding.oldPasswordET.setError("请输入管理员密码");
                 return;
             }
-            CharSequence bleTVText = binding.bleTV.getText();
+            CharSequence bleTVText = binding.bleET.getText();
             if (null == bleTVText || TextUtils.isEmpty(bleTVText)) {
-                PopTip.show("请配置蓝牙称设备");
+                binding.oldPasswordET.setError("请配置蓝牙称设备");
                 return;
             }
             SPUtils.getInstance().put("cameraSelector", binding.backRB.isChecked() ? 1 : 0);

+ 9 - 1
app/src/main/java/xn/hxp/ui/plan/PlanAddActivity.java

@@ -142,6 +142,7 @@ public class PlanAddActivity extends BaseActivity {
         binding.subAdd.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
+                binding.subAdd.setEnabled(false);
                 List<InventoryItemBean> inventoryItemBeans = hxpInventoryDAO.getAll();
                 if (null == inventoryItemBeans || inventoryItemBeans.isEmpty()) {
                     PopTip.show("请录入化学品!");
@@ -209,7 +210,6 @@ public class PlanAddActivity extends BaseActivity {
 
                     @Override
                     public void onSuccess(PlanAddData planAddData) {
-                        dismissLoading();
                         List<HxpCabinetVo> cabinetList = planAddData.getCabinetList();
                         List<HxpCabinetDoorVo> doorList = planAddData.getDoorList();
                         // 不需要开门
@@ -218,11 +218,19 @@ public class PlanAddActivity extends BaseActivity {
                             return;
                         }
                         String json = GsonUtils.toJson(planAddData);
+                        dismissLoading();
                         Intent intent = new Intent(PlanAddActivity.this, UnlockActivity.class);
                         intent.putExtra("data", json);
                         startActivity(intent);
                         finish();
                     }
+
+                    @Override
+                    public void onFail(Throwable t) {
+                        super.onFail(t);
+                        PopTip.show(t.getMessage());
+                        binding.subAdd.setEnabled(true);
+                    }
                 });
             }
         });

+ 3 - 0
app/src/main/java/xn/hxp/ui/plan/PlanAddActivityHelp.java

@@ -371,6 +371,7 @@ public class PlanAddActivityHelp {
             public void onSuccess(String result) {
                 activity.dismissLoading();
                 if (!TextUtils.isEmpty(result)) {
+                    activity.binding.subAdd.setEnabled(true);
                     PopTip.show(result);
                 } else {
                     activity.finish();
@@ -381,6 +382,8 @@ public class PlanAddActivityHelp {
             @Override
             public void onFail(Throwable t) {
                 super.onFail(t);
+                PopTip.show(t.getMessage());
+                activity.binding.subAdd.setEnabled(true);
                 activity.dismissLoading();
             }
         });

+ 3 - 0
app/src/main/java/xn/hxp/ui/plan/unlock/UnlockActivityHelp.java

@@ -494,6 +494,7 @@ public class UnlockActivityHelp {
     }
 
     public void save() {
+        activity.binding.saveBT.setEnabled(false);
         activity.showLoading("入库中...");
         ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<String>() {
             @Override
@@ -557,6 +558,7 @@ public class UnlockActivityHelp {
                 activity.dismissLoading();
                 if (!TextUtils.isEmpty(result)) {
                     PopTip.show(result);
+                    activity.binding.saveBT.setEnabled(true);
                 } else {
                     activity.finish();
 
@@ -572,6 +574,7 @@ public class UnlockActivityHelp {
             public void onFail(Throwable t) {
                 super.onFail(t);
                 activity.dismissLoading();
+                activity.binding.saveBT.setEnabled(true);
                 PopTip.show(t.getMessage());
             }
         });

+ 50 - 20
app/src/main/java/xn/hxp/ui/still/ChemicalsAlsoActivity.kt

@@ -1,11 +1,13 @@
 package xn.hxp.ui.still
 
+import android.bluetooth.BluetoothDevice
 import android.content.IntentFilter
 import android.hardware.usb.UsbManager
 import android.os.Bundle
 import android.os.CountDownTimer
 import android.os.Handler
 import android.os.Looper
+import android.text.TextUtils
 import android.view.KeyEvent
 import android.view.LayoutInflater
 import android.view.View
@@ -22,6 +24,7 @@ import com.blankj.utilcode.util.ThreadUtils.SimpleTask
 import com.bumptech.glide.Glide
 import com.bumptech.glide.load.engine.DiskCacheStrategy
 import com.bumptech.glide.request.RequestOptions
+import com.feasycom.common.bean.ConnectType
 import com.kongzue.dialogx.dialogs.PopTip
 import com.rc.core.ui.activity.BaseActivity
 import com.rc.httpcore.HttpConfig
@@ -48,7 +51,8 @@ import xn.hxp.ui.PrintBean
 import xn.hxp.ui.adapter.ReturningChemicalsAdapter
 import xn.hxp.ui.verify.TwoVerificationActivity
 import xn.hxp.utils.*
-import xn.hxp.utils.bluetooth.BleTool
+import xn.hxp.utils.bluetooth.SppTool
+import xn.hxp.utils.bluetooth.SppTool.BleSppCallback
 import xn.hxp.weidith.*
 import java.lang.Runnable
 import java.net.ConnectException
@@ -688,7 +692,7 @@ class ChemicalsAlsoActivity : BaseActivity() {
 
                     //确定 关闭  获取文本值 跳转新的页面
                     override fun viewCloses() {
-                        BleTool.INSTANCE.setBleCallback(null)
+                        SppTool.INSTANCE.disconnect()
                         closEnd()
                         closEndTwo()
                         try {
@@ -734,27 +738,53 @@ class ChemicalsAlsoActivity : BaseActivity() {
         mWeighingValue!!.requestFocus()
     }
 
+    var weight: String = ""
     private fun connectToDeviceWithTimeout() {
-        showToast("连接中...", Toast.LENGTH_SHORT)
-        BleTool.INSTANCE.setBleCallback(object : BleTool.BleCallback {
-            override fun onSuccess() {
-                AudioPlayer.getInstance().play(R.raw.weight_hint)
-            }
+        val sppMac = SPUtils.getInstance().getString("sppMac", "")
+        if (!TextUtils.isEmpty(sppMac)) {
+            showToast("连接中...", Toast.LENGTH_SHORT)
+            SppTool.INSTANCE.connect(sppMac, object : BleSppCallback {
+                override fun sppPeripheralConnected(
+                    bluetoothDevice: BluetoothDevice?,
+                    connectType: ConnectType?
+                ) {
+                    AudioPlayer.getInstance().play(R.raw.weight_hint)
+                }
 
-            override fun onNotifyFailure(exception: java.lang.Exception?) {
-                showToast("请手动输入")
-                weiView()
-            }
+                override fun packetReceived(address: String, strValue: String) {
+                    if (weight != strValue) {
+                        runOnUiThread {
+                            mWeighingValue!!.setText("$weight")
+                        }
+                    }
+                    weight = strValue
+                }
 
-            override fun onChanged(weight: String) {
-                if (weight.isEmpty()) {
-                    showToast("请手动输入")
-                    weiView()
-                } else {
-                    mWeighingValue!!.setText("$weight")
+                override fun sppPeripheralDisconnected(address: String?) {
                 }
-            }
-        })
+            })
+        } else {
+            showToast("未配置蓝牙称!", Toast.LENGTH_SHORT)
+        }
+//        BleTool.INSTANCE.setBleCallback(object : BleTool.BleCallback {
+//            override fun onSuccess() {
+//
+//            }
+//
+//            override fun onNotifyFailure(exception: java.lang.Exception?) {
+//                showToast("请手动输入")
+//                weiView()
+//            }
+//
+//            override fun onChanged(weight: String) {
+//                if (weight.isEmpty()) {
+//                    showToast("请手动输入")
+//                    weiView()
+//                } else {
+//                    mWeighingValue!!.setText("$weight")
+//                }
+//            }
+//        })
     }
 
     private fun showToast(message: String, duration: Int) {
@@ -1432,7 +1462,7 @@ class ChemicalsAlsoActivity : BaseActivity() {
 
     override fun onDestroy() {
         super.onDestroy()
-        BleTool.INSTANCE.setBleCallback(null)
+        SppTool.INSTANCE.disconnect()
         mPortScanHelper.onPause()
         try {
 //            jobTow?.cancel()

+ 30 - 19
app/src/main/java/xn/hxp/ui/uses/UseActivity.kt

@@ -1,8 +1,10 @@
 package xn.hxp.ui.uses
 
+import android.bluetooth.BluetoothDevice
 import android.os.CountDownTimer
 import android.os.Handler
 import android.os.Looper
+import android.text.TextUtils
 import android.util.Log
 import android.view.KeyEvent
 import android.view.View
@@ -17,6 +19,7 @@ import com.blankj.utilcode.util.SPUtils
 import com.bumptech.glide.Glide
 import com.bumptech.glide.load.engine.DiskCacheStrategy
 import com.bumptech.glide.request.RequestOptions
+import com.feasycom.common.bean.ConnectType
 import com.rc.core.ui.activity.BaseActivity
 import com.rc.httpcore.HttpConfig
 import com.rc.httpcore.bean.ChemistryBean
@@ -42,7 +45,8 @@ import xn.hxp.utils.HandlerUtil
 import xn.hxp.utils.SharedPreferencesHelper
 import xn.hxp.utils.TimeUpdater
 import xn.hxp.utils.UiManager
-import xn.hxp.utils.bluetooth.BleTool
+import xn.hxp.utils.bluetooth.SppTool
+import xn.hxp.utils.bluetooth.SppTool.BleSppCallback
 import xn.hxp.weidith.CustomDialog
 import xn.hxp.weidith.StorageDialog
 import xn.hxp.weidith.UsageLabelDialog
@@ -555,27 +559,34 @@ class UseActivity : BaseActivity() {
         mWeighingValue!!.requestFocus()
     }
 
+    var weight: String = ""
     private fun connectToDeviceWithTimeout() {
-        showToast("连接中...", Toast.LENGTH_SHORT)
-        BleTool.INSTANCE.setBleCallback(object : BleTool.BleCallback {
-            override fun onSuccess() {
-                AudioPlayer.getInstance().play(R.raw.weight_hint)
-            }
+        val sppMac = SPUtils.getInstance().getString("sppMac", "")
+        if (!TextUtils.isEmpty(sppMac)) {
+            showToast("连接中...", Toast.LENGTH_SHORT)
+            SppTool.INSTANCE.connect(sppMac, object : BleSppCallback {
+                override fun sppPeripheralConnected(
+                    bluetoothDevice: BluetoothDevice?,
+                    connectType: ConnectType?
+                ) {
+                    AudioPlayer.getInstance().play(R.raw.weight_hint)
+                }
 
-            override fun onNotifyFailure(exception: java.lang.Exception?) {
-                showToast("请手动输入")
-                weiView()
-            }
+                override fun packetReceived(address: String, strValue: String) {
+                    if (weight != strValue) {
+                        runOnUiThread {
+                            mWeighingValue!!.setText("$weight")
+                        }
+                    }
+                    weight = strValue
+                }
 
-            override fun onChanged(weight: String) {
-                if (weight.isEmpty()) {
-                    showToast("请手动输入")
-                    weiView()
-                } else {
-                    mWeighingValue!!.setText("$weight")
+                override fun sppPeripheralDisconnected(address: String?) {
                 }
-            }
-        })
+            })
+        } else {
+            showToast("未配置蓝牙称!", Toast.LENGTH_SHORT)
+        }
     }
 
     private fun showToast(message: String, duration: Int) {
@@ -1264,7 +1275,7 @@ class UseActivity : BaseActivity() {
         if (null != mUsageLabelDialog && mUsageLabelDialog!!.isShowing) {
             mUsageLabelDialog!!.dismiss()
         }
-        BleTool.INSTANCE.setBleCallback(null)
+        SppTool.INSTANCE.disconnect()
 //        jobTow?.cancel()
         try {
             handlerUtil.stopAllTasks()

+ 231 - 231
app/src/main/java/xn/hxp/utils/bluetooth/BleTool.java

@@ -1,231 +1,231 @@
-package xn.hxp.utils.bluetooth;
-
-import android.bluetooth.BluetoothGatt;
-import android.bluetooth.BluetoothGattCharacteristic;
-import android.bluetooth.BluetoothGattService;
-import android.util.Log;
-
-import com.blankj.utilcode.util.AppUtils;
-import com.blankj.utilcode.util.LogUtils;
-import com.blankj.utilcode.util.SPUtils;
-import com.clj.fastble.BleManager;
-import com.clj.fastble.callback.BleGattCallback;
-import com.clj.fastble.callback.BleNotifyCallback;
-import com.clj.fastble.callback.BleScanCallback;
-import com.clj.fastble.data.BleDevice;
-import com.clj.fastble.data.BleScanState;
-import com.clj.fastble.exception.BleException;
-
-import java.nio.charset.StandardCharsets;
-import java.util.List;
-
-public enum BleTool {
-    INSTANCE;
-
-    private final String SERVICE_UUID = "0000fff0-0000-1000-8000-00805f9b34fb";
-    private final String CHARACTERISTIC_UUID = "0000fff1-0000-1000-8000-00805f9b34fb";
-
-    private BleScanCallback bleScanCallback;
-    private BleCallback bleCallback;
-    private BleDevice bleDevice;
-    private BleNotifyCallback bleNotifyCallback;
-
-    private String weight = "";
-    private long lastWeightTime = 0;
-
-    public interface BleCallback {
-        void onSuccess();
-
-        void onNotifyFailure(Exception exception);
-
-        void onChanged(String data);
-    }
-
-    public void setBleCallback(BleCallback bleCallback) {
-        weight = "";
-        this.bleCallback = bleCallback;
-    }
-
-    public synchronized void connect() {
-        if (BleManager.getInstance().getScanSate() != BleScanState.STATE_SCANNING) {
-            if (null == bleScanCallback) {
-                bleScanCallback = new BleScanCallback() {
-                    @Override
-                    public void onScanFinished(List<BleDevice> scanResultList) {
-                    }
-
-                    @Override
-                    public void onScanStarted(boolean success) {
-                        if (null != bleCallback) {
-                            LogUtils.d("蓝牙", success);
-                        }
-                    }
-
-                    @Override
-                    public void onScanning(BleDevice bleDevice) {
-                        try {
-                            String bleMac = SPUtils.getInstance().getString("bleMac", "");
-                            LogUtils.d("蓝牙", bleMac);
-                            if (bleDevice.getMac().equals(bleMac)) {
-                                BleManager.getInstance().cancelScan();
-                                BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
-                                    @Override
-                                    public void onStartConnect() {
-                                        LogUtils.d("蓝牙", "开始连接", bleDevice.getName(), bleDevice.getMac());
-                                    }
-
-                                    @Override
-                                    public void onConnectFail(BleDevice bleDevice, BleException exception) {
-                                        LogUtils.e(bleDevice.getMac(), bleDevice.getName(), exception.getDescription());
-                                        if (null != bleCallback) {
-                                            LogUtils.d("蓝牙", exception.getDescription());
-                                            bleCallback.onNotifyFailure(new Exception(exception.getDescription()));
-                                        }
-                                    }
-
-                                    @Override
-                                    public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
-                                        BleTool.INSTANCE.bleDevice = bleDevice;
-                                        LogUtils.d("蓝牙", "连接成功", bleDevice.getName(), bleDevice.getMac());
-                                        if (null != gatt) {
-                                            List<BluetoothGattService> bluetoothGattServiceList = gatt.getServices();
-                                            if (null != bluetoothGattServiceList) {
-                                                BluetoothGattService bluetoothGattService = null;
-                                                for (int i = 0; i < bluetoothGattServiceList.size(); i++) {
-                                                    BluetoothGattService gattService = bluetoothGattServiceList.get(i);
-                                                    if (SERVICE_UUID.equals(gattService.getUuid().toString())) {
-                                                        bluetoothGattService = gattService;
-                                                        break;
-                                                    }
-                                                }
-                                                if (null != bluetoothGattService) {
-                                                    List<BluetoothGattCharacteristic> bluetoothGattCharacteristicList = bluetoothGattService.getCharacteristics();
-                                                    if (null != bluetoothGattCharacteristicList) {
-                                                        BluetoothGattCharacteristic bluetoothGattCharacteristic = null;
-                                                        for (int i = 0; i < bluetoothGattCharacteristicList.size(); i++) {
-                                                            BluetoothGattCharacteristic gattCharacteristic = bluetoothGattCharacteristicList.get(i);
-                                                            if (null != gattCharacteristic) {
-                                                                if (CHARACTERISTIC_UUID.equals(gattCharacteristic.getUuid().toString())) {
-                                                                    bluetoothGattCharacteristic = gattCharacteristic;
-                                                                    break;
-                                                                }
-                                                            }
-                                                        }
-
-                                                        if (bluetoothGattCharacteristic != null) {
-                                                            if (null == bleNotifyCallback) {
-                                                                bleNotifyCallback = new BleNotifyCallback() {
-                                                                    @Override
-                                                                    public void onNotifySuccess() {
-                                                                        if (null != bleCallback) {
-                                                                            bleCallback.onSuccess();
-                                                                        }
-                                                                        LogUtils.d("蓝牙", "订阅成功");
-                                                                    }
-
-                                                                    @Override
-                                                                    public void onNotifyFailure(BleException exception) {
-                                                                        if (null != bleCallback) {
-                                                                            bleCallback.onNotifyFailure(new Exception(exception.getDescription()));
-                                                                        }
-                                                                        LogUtils.e("蓝牙", "订阅失败", exception);
-                                                                    }
-
-                                                                    @Override
-                                                                    public void onCharacteristicChanged(byte[] data) {
-                                                                        String string = new String(data, StandardCharsets.UTF_8);
-                                                                        String[] split = string.split("\n", -1);
-                                                                        if (AppUtils.isAppDebug()) {
-                                                                            LogUtils.d("蓝牙", "处理前的蓝牙数据", data, split);
-                                                                        }
-                                                                        if (null != bleCallback) {
-                                                                            if (split.length > 0) {
-                                                                                String line = split[0].trim();
-                                                                                if (!weight.equals(line) || (System.currentTimeMillis() - lastWeightTime > 3000)) {
-                                                                                    lastWeightTime = System.currentTimeMillis();
-                                                                                    weight = line;
-                                                                                    LogUtils.d("蓝牙", "处理前的蓝牙数据", data, split);
-                                                                                    if (weight.startsWith("=")) {
-                                                                                        try {
-                                                                                            String wD = new StringBuilder(weight.replace("=", "")).reverse().toString();
-                                                                                            bleCallback.onChanged(wD);
-                                                                                        } catch (Exception e) {
-                                                                                            LogUtils.e(e.getMessage());
-                                                                                        }
-                                                                                    } else {
-                                                                                        bleCallback.onChanged(weight);
-                                                                                    }
-                                                                                }
-                                                                            }
-                                                                        }
-                                                                    }
-                                                                };
-                                                            }
-                                                            BleManager.getInstance().notify(bleDevice, SERVICE_UUID, CHARACTERISTIC_UUID, bleNotifyCallback);
-                                                        } else {
-                                                            if (null != bleCallback) {
-                                                                Exception exception = new Exception("ble_gatt_service is not found");
-                                                                LogUtils.d("蓝牙", exception.getMessage());
-                                                                bleCallback.onNotifyFailure(exception);
-                                                            }
-                                                        }
-                                                    } else {
-                                                        if (null != bleCallback) {
-                                                            Exception exception = new Exception("ble_gatt_service is null");
-                                                            LogUtils.d("蓝牙", exception.getMessage());
-                                                            bleCallback.onNotifyFailure(exception);
-                                                        }
-                                                    }
-                                                } else {
-                                                    if (null != bleCallback) {
-                                                        Exception exception = new Exception("ble_gatt_service is not found");
-                                                        LogUtils.d("蓝牙", exception.getMessage());
-                                                        bleCallback.onNotifyFailure(exception);
-                                                    }
-                                                }
-                                            } else {
-                                                if (null != bleCallback) {
-                                                    Exception exception = new Exception("ble_service is null");
-                                                    LogUtils.d("蓝牙", exception.getMessage());
-                                                    bleCallback.onNotifyFailure(exception);
-                                                }
-                                            }
-                                        }
-                                    }
-
-                                    @Override
-                                    public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
-                                        LogUtils.e(isActiveDisConnected, device.getMac(), device.getName(), status);
-                                    }
-                                });
-                            } else {
-                                if (null != bleCallback) {
-                                    Exception exception = new Exception("ble_device is not found");
-                                    LogUtils.d("蓝牙", exception.getMessage());
-                                    bleCallback.onNotifyFailure(exception);
-                                }
-                            }
-                        } catch (Exception e) {
-                            LogUtils.e(Log.getStackTraceString(e));
-                            if (null != bleCallback) {
-                                LogUtils.d("蓝牙", e.getMessage());
-                                bleCallback.onNotifyFailure(e);
-                            }
-                        }
-                    }
-                };
-            }
-            BleManager.getInstance().scan(bleScanCallback);
-        }
-    }
-
-    public synchronized void disconnect() {
-        try {
-            BleManager.getInstance().removeNotifyCallback(bleDevice, CHARACTERISTIC_UUID);
-            BleManager.getInstance().disconnect(bleDevice);
-        } catch (Exception e) {
-            LogUtils.e(Log.getStackTraceString(e));
-        }
-    }
-
-}
+//package xn.hxp.utils.bluetooth;
+//
+//import android.bluetooth.BluetoothGatt;
+//import android.bluetooth.BluetoothGattCharacteristic;
+//import android.bluetooth.BluetoothGattService;
+//import android.util.Log;
+//
+//import com.blankj.utilcode.util.AppUtils;
+//import com.blankj.utilcode.util.LogUtils;
+//import com.blankj.utilcode.util.SPUtils;
+//import com.clj.fastble.BleManager;
+//import com.clj.fastble.callback.BleGattCallback;
+//import com.clj.fastble.callback.BleNotifyCallback;
+//import com.clj.fastble.callback.BleScanCallback;
+//import com.clj.fastble.data.BleDevice;
+//import com.clj.fastble.data.BleScanState;
+//import com.clj.fastble.exception.BleException;
+//
+//import java.nio.charset.StandardCharsets;
+//import java.util.List;
+//
+//public enum BleTool {
+//    INSTANCE;
+//
+//    private final String SERVICE_UUID = "0000fff0-0000-1000-8000-00805f9b34fb";
+//    private final String CHARACTERISTIC_UUID = "0000fff1-0000-1000-8000-00805f9b34fb";
+//
+//    private BleScanCallback bleScanCallback;
+//    private BleCallback bleCallback;
+//    private BleDevice bleDevice;
+//    private BleNotifyCallback bleNotifyCallback;
+//
+//    private String weight = "";
+//    private long lastWeightTime = 0;
+//
+//    public interface BleCallback {
+//        void onSuccess();
+//
+//        void onNotifyFailure(Exception exception);
+//
+//        void onChanged(String data);
+//    }
+//
+//    public void setBleCallback(BleCallback bleCallback) {
+//        weight = "";
+//        this.bleCallback = bleCallback;
+//    }
+//
+//    public synchronized void connect() {
+//        if (BleManager.getInstance().getScanSate() != BleScanState.STATE_SCANNING) {
+//            if (null == bleScanCallback) {
+//                bleScanCallback = new BleScanCallback() {
+//                    @Override
+//                    public void onScanFinished(List<BleDevice> scanResultList) {
+//                    }
+//
+//                    @Override
+//                    public void onScanStarted(boolean success) {
+//                        if (null != bleCallback) {
+//                            LogUtils.d("蓝牙", success);
+//                        }
+//                    }
+//
+//                    @Override
+//                    public void onScanning(BleDevice bleDevice) {
+//                        try {
+//                            String bleMac = SPUtils.getInstance().getString("bleMac", "");
+//                            LogUtils.d("蓝牙", bleMac);
+//                            if (bleDevice.getMac().equals(bleMac)) {
+//                                BleManager.getInstance().cancelScan();
+//                                BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
+//                                    @Override
+//                                    public void onStartConnect() {
+//                                        LogUtils.d("蓝牙", "开始连接", bleDevice.getName(), bleDevice.getMac());
+//                                    }
+//
+//                                    @Override
+//                                    public void onConnectFail(BleDevice bleDevice, BleException exception) {
+//                                        LogUtils.e(bleDevice.getMac(), bleDevice.getName(), exception.getDescription());
+//                                        if (null != bleCallback) {
+//                                            LogUtils.d("蓝牙", exception.getDescription());
+//                                            bleCallback.onNotifyFailure(new Exception(exception.getDescription()));
+//                                        }
+//                                    }
+//
+//                                    @Override
+//                                    public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
+//                                        BleTool.INSTANCE.bleDevice = bleDevice;
+//                                        LogUtils.d("蓝牙", "连接成功", bleDevice.getName(), bleDevice.getMac());
+//                                        if (null != gatt) {
+//                                            List<BluetoothGattService> bluetoothGattServiceList = gatt.getServices();
+//                                            if (null != bluetoothGattServiceList) {
+//                                                BluetoothGattService bluetoothGattService = null;
+//                                                for (int i = 0; i < bluetoothGattServiceList.size(); i++) {
+//                                                    BluetoothGattService gattService = bluetoothGattServiceList.get(i);
+//                                                    if (SERVICE_UUID.equals(gattService.getUuid().toString())) {
+//                                                        bluetoothGattService = gattService;
+//                                                        break;
+//                                                    }
+//                                                }
+//                                                if (null != bluetoothGattService) {
+//                                                    List<BluetoothGattCharacteristic> bluetoothGattCharacteristicList = bluetoothGattService.getCharacteristics();
+//                                                    if (null != bluetoothGattCharacteristicList) {
+//                                                        BluetoothGattCharacteristic bluetoothGattCharacteristic = null;
+//                                                        for (int i = 0; i < bluetoothGattCharacteristicList.size(); i++) {
+//                                                            BluetoothGattCharacteristic gattCharacteristic = bluetoothGattCharacteristicList.get(i);
+//                                                            if (null != gattCharacteristic) {
+//                                                                if (CHARACTERISTIC_UUID.equals(gattCharacteristic.getUuid().toString())) {
+//                                                                    bluetoothGattCharacteristic = gattCharacteristic;
+//                                                                    break;
+//                                                                }
+//                                                            }
+//                                                        }
+//
+//                                                        if (bluetoothGattCharacteristic != null) {
+//                                                            if (null == bleNotifyCallback) {
+//                                                                bleNotifyCallback = new BleNotifyCallback() {
+//                                                                    @Override
+//                                                                    public void onNotifySuccess() {
+//                                                                        if (null != bleCallback) {
+//                                                                            bleCallback.onSuccess();
+//                                                                        }
+//                                                                        LogUtils.d("蓝牙", "订阅成功");
+//                                                                    }
+//
+//                                                                    @Override
+//                                                                    public void onNotifyFailure(BleException exception) {
+//                                                                        if (null != bleCallback) {
+//                                                                            bleCallback.onNotifyFailure(new Exception(exception.getDescription()));
+//                                                                        }
+//                                                                        LogUtils.e("蓝牙", "订阅失败", exception);
+//                                                                    }
+//
+//                                                                    @Override
+//                                                                    public void onCharacteristicChanged(byte[] data) {
+//                                                                        String string = new String(data, StandardCharsets.UTF_8);
+//                                                                        String[] split = string.split("\n", -1);
+//                                                                        if (AppUtils.isAppDebug()) {
+//                                                                            LogUtils.d("蓝牙", "处理前的蓝牙数据", data, split);
+//                                                                        }
+//                                                                        if (null != bleCallback) {
+//                                                                            if (split.length > 0) {
+//                                                                                String line = split[0].trim();
+//                                                                                if (!weight.equals(line) || (System.currentTimeMillis() - lastWeightTime > 3000)) {
+//                                                                                    lastWeightTime = System.currentTimeMillis();
+//                                                                                    weight = line;
+//                                                                                    LogUtils.d("蓝牙", "处理前的蓝牙数据", data, split);
+//                                                                                    if (weight.startsWith("=")) {
+//                                                                                        try {
+//                                                                                            String wD = new StringBuilder(weight.replace("=", "")).reverse().toString();
+//                                                                                            bleCallback.onChanged(wD);
+//                                                                                        } catch (Exception e) {
+//                                                                                            LogUtils.e(e.getMessage());
+//                                                                                        }
+//                                                                                    } else {
+//                                                                                        bleCallback.onChanged(weight);
+//                                                                                    }
+//                                                                                }
+//                                                                            }
+//                                                                        }
+//                                                                    }
+//                                                                };
+//                                                            }
+//                                                            BleManager.getInstance().notify(bleDevice, SERVICE_UUID, CHARACTERISTIC_UUID, bleNotifyCallback);
+//                                                        } else {
+//                                                            if (null != bleCallback) {
+//                                                                Exception exception = new Exception("ble_gatt_service is not found");
+//                                                                LogUtils.d("蓝牙", exception.getMessage());
+//                                                                bleCallback.onNotifyFailure(exception);
+//                                                            }
+//                                                        }
+//                                                    } else {
+//                                                        if (null != bleCallback) {
+//                                                            Exception exception = new Exception("ble_gatt_service is null");
+//                                                            LogUtils.d("蓝牙", exception.getMessage());
+//                                                            bleCallback.onNotifyFailure(exception);
+//                                                        }
+//                                                    }
+//                                                } else {
+//                                                    if (null != bleCallback) {
+//                                                        Exception exception = new Exception("ble_gatt_service is not found");
+//                                                        LogUtils.d("蓝牙", exception.getMessage());
+//                                                        bleCallback.onNotifyFailure(exception);
+//                                                    }
+//                                                }
+//                                            } else {
+//                                                if (null != bleCallback) {
+//                                                    Exception exception = new Exception("ble_service is null");
+//                                                    LogUtils.d("蓝牙", exception.getMessage());
+//                                                    bleCallback.onNotifyFailure(exception);
+//                                                }
+//                                            }
+//                                        }
+//                                    }
+//
+//                                    @Override
+//                                    public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
+//                                        LogUtils.e(isActiveDisConnected, device.getMac(), device.getName(), status);
+//                                    }
+//                                });
+//                            } else {
+//                                if (null != bleCallback) {
+//                                    Exception exception = new Exception("ble_device is not found");
+//                                    LogUtils.d("蓝牙", exception.getMessage());
+//                                    bleCallback.onNotifyFailure(exception);
+//                                }
+//                            }
+//                        } catch (Exception e) {
+//                            LogUtils.e(Log.getStackTraceString(e));
+//                            if (null != bleCallback) {
+//                                LogUtils.d("蓝牙", e.getMessage());
+//                                bleCallback.onNotifyFailure(e);
+//                            }
+//                        }
+//                    }
+//                };
+//            }
+//            BleManager.getInstance().scan(bleScanCallback);
+//        }
+//    }
+//
+//    public synchronized void disconnect() {
+//        try {
+//            BleManager.getInstance().removeNotifyCallback(bleDevice, CHARACTERISTIC_UUID);
+//            BleManager.getInstance().disconnect(bleDevice);
+//        } catch (Exception e) {
+//            LogUtils.e(Log.getStackTraceString(e));
+//        }
+//    }
+//
+//}

+ 0 - 112
app/src/main/java/xn/hxp/utils/bluetooth/BluetoothTool.java

@@ -1,112 +0,0 @@
-//package xn.hxp.utils.bluetooth;
-//
-//import android.annotation.SuppressLint;
-//import android.bluetooth.BluetoothAdapter;
-//import android.bluetooth.BluetoothDevice;
-//import android.bluetooth.BluetoothManager;
-//import android.bluetooth.BluetoothSocket;
-//import android.util.Log;
-//
-//import com.blankj.utilcode.util.LogUtils;
-//import com.blankj.utilcode.util.Utils;
-//
-//import java.io.InputStream;
-//import java.nio.charset.StandardCharsets;
-//import java.util.Set;
-//import java.util.UUID;
-//
-//import xn.hxp.utils.Tool;
-//
-//public enum BluetoothTool {
-//    INSTANCE;
-//    BluetoothAdapter bluetoothAdapter;
-//    private UUID uuid;
-//    private byte[] buffer = new byte[1024];
-//    private BluetoothDevice bluetoothDevice;
-//    private BluetoothSocket bluetoothSocket;
-//    private InputStream inputStream;
-//
-//    private BluetoothTool() {
-//        uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
-//        BluetoothManager bluetoothManager = Utils.getApp().getSystemService(BluetoothManager.class);
-//        bluetoothAdapter = bluetoothManager.getAdapter();
-//    }
-//
-//    @SuppressLint("MissingPermission")
-//    public void connect(BluetoothCallBack bluetoothCallBack) {
-//        if (!bluetoothAdapter.isEnabled()) {
-//            Tool.INSTANCE.setBluetooth(true);
-//        }
-//        bluetoothDevice = getWeighDevice();
-//        if (null == bluetoothDevice) {
-//            bluetoothCallBack.connectFailed("未找到蓝牙称");
-//            return;
-//        }
-//        try {
-//            bluetoothSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid);
-//            LogUtils.d("连接蓝牙前");
-//            bluetoothSocket.connect();
-//            inputStream = bluetoothSocket.getInputStream();
-//            int bytesRead;
-//            String weight = "";
-//            LogUtils.d("读取蓝牙数据前");
-//            while (null != bluetoothSocket && bluetoothSocket.isConnected() && null != inputStream && (bytesRead = inputStream.read(buffer)) != -1) {
-//                // 处理读取的数据
-//                String data = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
-//                String[] split = data.split("\n", -1);
-//                LogUtils.d("处理前的蓝牙数据", data, split);
-//                if (split.length > 0) {
-//                    String line = split[0].trim();
-//                    if (!weight.equals(line)) {
-//                        weight = line;
-//                        bluetoothCallBack.callBack(weight);
-//                    }
-//                }
-//                Thread.sleep(5);
-//            }
-//        } catch (Exception e) {
-//            disconnect();
-//            LogUtils.e(Log.getStackTraceString(e));
-//        }
-//    }
-//
-//    public void disconnect() {
-//        if (null != bluetoothDevice) {
-//            bluetoothDevice = null;
-//        }
-//        if (null != bluetoothSocket && bluetoothSocket.isConnected()) {
-//            try {
-//                inputStream.close();
-//                inputStream = null;
-//                bluetoothSocket.close();
-//                bluetoothSocket = null;
-//            } catch (Exception e) {
-//                LogUtils.e(Log.getStackTraceString(e));
-//            }
-//        }
-//    }
-//
-//    public interface BluetoothCallBack {
-//        void callBack(String weight);
-//
-//        void connectFailed(String msg);
-//    }
-//
-//    @SuppressLint("MissingPermission")
-//    private BluetoothDevice getWeighDevice() {
-//        if (null != bluetoothDevice) {
-//            return bluetoothDevice;
-//        }
-//        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
-//        if (!pairedDevices.isEmpty()) {
-//            // There are paired devices. Get the name and address of each paired device.
-//            for (BluetoothDevice device : pairedDevices) {
-//                String deviceName = device.getName();
-//                if ("HF-18".equals(deviceName)) {
-//                    return device;
-//                }
-//            }
-//        }
-//        return null;
-//    }
-//}

+ 90 - 0
app/src/main/java/xn/hxp/utils/bluetooth/SppTool.java

@@ -0,0 +1,90 @@
+package xn.hxp.utils.bluetooth;
+
+import android.bluetooth.BluetoothDevice;
+
+import com.blankj.utilcode.util.LogUtils;
+import com.blankj.utilcode.util.Utils;
+import com.feasycom.common.bean.ConnectType;
+import com.feasycom.spp.controler.FscSppCentralApi;
+import com.feasycom.spp.controler.FscSppCentralApiImp;
+import com.feasycom.spp.controler.FscSppCentralCallbacks;
+
+/**
+ * https://document.feasycom.com/docs/app/sdk/FeasycomSDK/CN/latest/FeasyBlue_Android.html
+ * 蓝牙操作SDK 适用于乐琪称
+ */
+public enum SppTool {
+    INSTANCE;
+
+    private FscSppCentralApi sppApi;
+
+    public void init() {
+        sppApi = FscSppCentralApiImp.getInstance(Utils.getApp());
+        sppApi.isShowLog(true);
+        sppApi.initialize();
+    }
+
+    public interface BleSppCallback {
+        void sppPeripheralConnected(BluetoothDevice bluetoothDevice, ConnectType connectType);
+
+        void packetReceived(String address, String strValue);
+
+        void sppPeripheralDisconnected(String address);
+    }
+
+    public void sacn(FscSppCentralCallbacks fscSppCentralCallbacks) {
+        sppApi.setCallbacks(fscSppCentralCallbacks);
+        sppApi.startScan();
+    }
+
+    public void connect(String mac, BleSppCallback bleSppCallback) {
+        if (null != mac) {
+            sppApi.setCallbacks(new FscSppCentralCallbacks() {
+                @Override
+                public void sppPeripheralConnected(BluetoothDevice bluetoothDevice, ConnectType connectType) {
+                    LogUtils.d(bluetoothDevice, connectType);
+                    bleSppCallback.sppPeripheralConnected(bluetoothDevice, connectType);
+                }
+
+                /**
+                 * 收到数据
+                 * @param address 设备地址
+                 * @param strValue 字符串
+                 * @param dataHexString 十六进制
+                 * @param data 源数据
+                 */
+                @Override
+                public void packetReceived(String address, String strValue, String dataHexString, byte[] data) {
+                    strValue = strValue.replace(" ", "");
+                    strValue = strValue.replace("\r", "");
+                    strValue = strValue.replace("\n", "");
+                    strValue = strValue.trim();
+                    if (strValue.startsWith("=")) {
+                        try {
+                            String wD = new StringBuilder(strValue.replace("=", "")).reverse().toString();
+                            bleSppCallback.packetReceived(address, wD);
+                        } catch (Exception e) {
+                            LogUtils.e(e.getMessage());
+                        }
+                    } else {
+                        bleSppCallback.packetReceived(address, strValue);
+                    }
+                }
+
+                /**
+                 * 断开连接
+                 */
+                @Override
+                public void sppPeripheralDisconnected(String address) {
+                    LogUtils.d("sppPeripheralDisconnected", address);
+                    bleSppCallback.sppPeripheralDisconnected(address);
+                }
+            });
+            sppApi.connect(mac);
+        }
+    }
+
+    public void disconnect() {
+        sppApi.disconnect();
+    }
+}

+ 8 - 8
app/src/main/java/xn/hxp/weidith/ble/BleScanAdapter.java

@@ -1,5 +1,7 @@
 package xn.hxp.weidith.ble;
 
+import android.annotation.SuppressLint;
+import android.bluetooth.BluetoothDevice;
 import android.content.Context;
 import android.text.TextUtils;
 import android.view.LayoutInflater;
@@ -7,17 +9,15 @@ import android.view.View;
 import android.view.ViewGroup;
 import android.widget.BaseAdapter;
 
-import com.clj.fastble.data.BleDevice;
-
 import java.util.List;
 
 import xn.hxp.databinding.ItemBleBinding;
 
 public class BleScanAdapter extends BaseAdapter {
     private Context context;
-    private List<BleDevice> deviceList;
+    private List<BluetoothDevice> deviceList;
 
-    public BleScanAdapter(Context context, List<BleDevice> deviceList) {
+    public BleScanAdapter(Context context, List<BluetoothDevice> deviceList) {
         this.context = context;
         this.deviceList = deviceList;
     }
@@ -28,7 +28,7 @@ public class BleScanAdapter extends BaseAdapter {
     }
 
     @Override
-    public BleDevice getItem(int position) {
+    public BluetoothDevice getItem(int position) {
         return deviceList.get(position);
     }
 
@@ -48,10 +48,10 @@ public class BleScanAdapter extends BaseAdapter {
         } else {
             viewHolder = (ViewHolder) convertView.getTag();
         }
-        BleDevice bleDevice = getItem(position);
+        BluetoothDevice bleDevice = getItem(position);
         if (null != bleDevice) {
-            String mac = bleDevice.getMac();
-            String name = bleDevice.getName();
+            String mac = bleDevice.getAddress();
+            @SuppressLint("MissingPermission") String name = bleDevice.getName();
             viewHolder.binding.bleMac.setText(TextUtils.isEmpty(mac) ? "" : mac);
             viewHolder.binding.bleName.setText(TextUtils.isEmpty(name) ? "" : name);
         }

+ 20 - 38
app/src/main/java/xn/hxp/weidith/ble/BleSelectorDialog.java

@@ -1,5 +1,7 @@
 package xn.hxp.weidith.ble;
 
+import android.annotation.SuppressLint;
+import android.bluetooth.BluetoothDevice;
 import android.content.Context;
 import android.os.Bundle;
 import android.text.TextUtils;
@@ -9,24 +11,23 @@ import android.widget.AdapterView;
 import androidx.annotation.NonNull;
 import androidx.appcompat.app.AppCompatDialog;
 
-import com.blankj.utilcode.util.LogUtils;
 import com.blankj.utilcode.util.SPUtils;
 import com.clj.fastble.BleManager;
-import com.clj.fastble.callback.BleScanCallback;
-import com.clj.fastble.data.BleDevice;
 import com.clj.fastble.data.BleScanState;
-import com.clj.fastble.scan.BleScanRuleConfig;
+import com.feasycom.common.bean.FscDevice;
+import com.feasycom.spp.controler.FscSppCentralCallbacks;
 import com.kongzue.dialogx.dialogs.PopTip;
 
 import java.util.ArrayList;
 import java.util.List;
 
 import xn.hxp.databinding.DialogBleSelectorBinding;
+import xn.hxp.utils.bluetooth.SppTool;
 
 public class BleSelectorDialog extends AppCompatDialog {
     private Context context;
     private DialogBleSelectorBinding binding;
-    private List<BleDevice> deviceList = new ArrayList<>();
+    private List<BluetoothDevice> deviceList = new ArrayList<>();
     private BleScanAdapter bleScanAdapter;
 
     public BleSelectorDialog(@NonNull Context context) {
@@ -49,11 +50,11 @@ public class BleSelectorDialog extends AppCompatDialog {
         bleScanAdapter = new BleScanAdapter(context, deviceList);
         binding.bleLV.setAdapter(bleScanAdapter);
         binding.bleLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+            @SuppressLint("MissingPermission")
             @Override
             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
-                SPUtils.getInstance().put("bleMac", deviceList.get(position).getMac());
-                SPUtils.getInstance().put("bleName", deviceList.get(position).getName());
-                SPUtils.getInstance().put("bleKey", deviceList.get(position).getKey());
+                SPUtils.getInstance().put("sppMac", deviceList.get(position).getAddress());
+                SPUtils.getInstance().put("sppName", deviceList.get(position).getName());
                 dismiss();
             }
         });
@@ -65,38 +66,19 @@ public class BleSelectorDialog extends AppCompatDialog {
                 binding.bleLV.setVisibility(View.VISIBLE);
                 binding.loadingLAV.setVisibility(View.VISIBLE);
                 binding.loadingLAV.playAnimation();
-                BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
-                        .setScanTimeOut(5000)
-                        .build();
-                BleManager.getInstance().initScanRule(scanRuleConfig);
-                BleManager.getInstance().scan(new BleScanCallback() {
+                SppTool.INSTANCE.sacn(new FscSppCentralCallbacks() {
                     @Override
-                    public void onScanFinished(List<BleDevice> scanResultList) {
-                        if (null != scanResultList && !scanResultList.isEmpty()) {
-                            for (int i = 0; i < scanResultList.size(); i++) {
-                                BleDevice bleDevice = scanResultList.get(i);
-                                String name = bleDevice.getName();
-                                if (!TextUtils.isEmpty(name)) {
-                                    deviceList.add(bleDevice);
-                                }
-                            }
-                            LogUtils.d(deviceList.size());
-                            if (!deviceList.isEmpty()) {
-                                bleScanAdapter.notifyDataSetChanged();
-                                binding.loadingLAV.cancelAnimation();
-                                binding.loadingLAV.setVisibility(View.GONE);
-                            } else {
-                                PopTip.show("未找到蓝牙称!");
-                            }
+                    public void sppPeripheralFound(FscDevice fscDevice, int i) {
+                        if (!TextUtils.isEmpty(fscDevice.getName())) {
+                            deviceList.add(fscDevice.getDevice());
+                        }
+                        if (!deviceList.isEmpty()) {
+                            bleScanAdapter.notifyDataSetChanged();
+                            binding.loadingLAV.cancelAnimation();
+                            binding.loadingLAV.setVisibility(View.GONE);
+                        } else {
+                            PopTip.show("未找到蓝牙称!");
                         }
-                    }
-
-                    @Override
-                    public void onScanStarted(boolean success) {
-                    }
-
-                    @Override
-                    public void onScanning(BleDevice bleDevice) {
                     }
                 });
             }

+ 73 - 26
app/src/main/java/xn/hxp/weidith/ble/BluetoothWeighDialog.java

@@ -1,5 +1,6 @@
 package xn.hxp.weidith.ble;
 
+import android.bluetooth.BluetoothDevice;
 import android.graphics.Color;
 import android.graphics.drawable.ColorDrawable;
 import android.os.Bundle;
@@ -14,10 +15,12 @@ import android.widget.Toast;
 import androidx.appcompat.app.AppCompatDialog;
 
 import com.blankj.utilcode.util.ActivityUtils;
+import com.blankj.utilcode.util.SPUtils;
 import com.blankj.utilcode.util.ThreadUtils;
 import com.bumptech.glide.Glide;
 import com.bumptech.glide.load.engine.DiskCacheStrategy;
 import com.bumptech.glide.request.RequestOptions;
+import com.feasycom.common.bean.ConnectType;
 import com.kongzue.dialogx.dialogs.PopTip;
 import com.kongzue.dialogx.dialogs.WaitDialog;
 import com.rc.httpcore.HttpConfig;
@@ -31,7 +34,7 @@ import xn.hxp.R;
 import xn.hxp.app.ChemicalApp;
 import xn.hxp.databinding.DialogBluetoothWeighBinding;
 import xn.hxp.ui.plan.add.AddActivity;
-import xn.hxp.utils.bluetooth.BleTool;
+import xn.hxp.utils.bluetooth.SppTool;
 
 public class BluetoothWeighDialog extends AppCompatDialog {
     private DialogBluetoothWeighBinding binding;
@@ -72,35 +75,79 @@ public class BluetoothWeighDialog extends AppCompatDialog {
         // 规格
         binding.specsTV.setText(hxpChemicalVo.getSpecNum() + hxpChemicalVo.getSpecUnit());
         // 蓝牙称
-        BleTool.INSTANCE.setBleCallback(new BleTool.BleCallback() {
-            @Override
-            public void onSuccess() {
+        String sppMac = SPUtils.getInstance().getString("sppMac", "");
+        if (TextUtils.isEmpty(sppMac)) {
+            Toast.makeText(ActivityUtils.getTopActivity(), "未配置蓝牙称!", Toast.LENGTH_LONG).show();
+        } else {
+            SppTool.INSTANCE.connect(sppMac, new SppTool.BleSppCallback() {
+                String weight = "";
 
-            }
-
-            @Override
-            public void onNotifyFailure(Exception exception) {
-                dialogCallBack.cancel(BluetoothWeighDialog.this, exception.getMessage());
-            }
+                @Override
+                public void sppPeripheralConnected(BluetoothDevice bluetoothDevice, ConnectType connectType) {
 
-            @Override
-            public void onChanged(String weight) {
-                try {
-                    double w = Double.parseDouble(weight);
-                    hxpChemicalVo.setWeigh(w);
-                    binding.weighTV.setText(weight + "g");
-                } catch (Exception e) {
-                    ThreadUtils.runOnUiThread(() -> Toast.makeText(ActivityUtils.getTopActivity(), "蓝牙称值异常! " + weight, Toast.LENGTH_SHORT).show());
                 }
-                if (binding.weightRL.getVisibility() != View.VISIBLE) {
-                    binding.weightRL.setVisibility(View.VISIBLE);
+
+                @Override
+                public void packetReceived(String address, String strValue) {
+                    if (!weight.equals(strValue)) {
+                        ThreadUtils.runOnUiThread(new Runnable() {
+                            @Override
+                            public void run() {
+                                try {
+                                    double w = Double.parseDouble(strValue);
+                                    hxpChemicalVo.setWeigh(w);
+                                    binding.weighTV.setText(strValue + "g");
+                                    weight = strValue;
+                                } catch (Exception e) {
+                                    Toast.makeText(ActivityUtils.getTopActivity(), "蓝牙称值异常! " + weight, Toast.LENGTH_SHORT).show();
+                                }
+                                if (binding.weightRL.getVisibility() != View.VISIBLE) {
+                                    binding.weightRL.setVisibility(View.VISIBLE);
+                                }
+                                if (binding.loadingLAV.getVisibility() == View.VISIBLE) {
+                                    binding.loadingLAV.cancelAnimation();
+                                    binding.loadingLAV.setVisibility(View.GONE);
+                                }
+                            }
+                        });
+                    }
                 }
-                if (binding.loadingLAV.getVisibility() == View.VISIBLE) {
-                    binding.loadingLAV.cancelAnimation();
-                    binding.loadingLAV.setVisibility(View.GONE);
+
+                @Override
+                public void sppPeripheralDisconnected(String address) {
+
                 }
-            }
-        });
+            });
+        }
+//        BleTool.INSTANCE.setBleCallback(new BleTool.BleCallback() {
+//            @Override
+//            public void onSuccess() {
+//
+//            }
+//
+//            @Override
+//            public void onNotifyFailure(Exception exception) {
+//                dialogCallBack.cancel(BluetoothWeighDialog.this, exception.getMessage());
+//            }
+//
+//            @Override
+//            public void onChanged(String weight) {
+//                try {
+//                    double w = Double.parseDouble(weight);
+//                    hxpChemicalVo.setWeigh(w);
+//                    binding.weighTV.setText(weight + "g");
+//                } catch (Exception e) {
+//                    ThreadUtils.runOnUiThread(() -> Toast.makeText(ActivityUtils.getTopActivity(), "蓝牙称值异常! " + weight, Toast.LENGTH_SHORT).show());
+//                }
+//                if (binding.weightRL.getVisibility() != View.VISIBLE) {
+//                    binding.weightRL.setVisibility(View.VISIBLE);
+//                }
+//                if (binding.loadingLAV.getVisibility() == View.VISIBLE) {
+//                    binding.loadingLAV.cancelAnimation();
+//                    binding.loadingLAV.setVisibility(View.GONE);
+//                }
+//            }
+//        });
         // 确认
         binding.confirmBT.setOnClickListener(v -> {
             Editable netWtETText = binding.netWtET.getText();
@@ -170,7 +217,7 @@ public class BluetoothWeighDialog extends AppCompatDialog {
     @Override
     protected void onStop() {
         super.onStop();
-        BleTool.INSTANCE.setBleCallback(null);
+        SppTool.INSTANCE.disconnect();
     }
 
 

+ 35 - 13
app/src/main/res/layout/activity_setting.xml

@@ -206,9 +206,9 @@
 
                         <RadioButton
                             android:id="@+id/back_RB"
-                            android:checked="true"
                             android:layout_width="wrap_content"
                             android:layout_height="match_parent"
+                            android:checked="true"
                             android:paddingHorizontal="10dp"
                             android:text="后置相机" />
                     </RadioGroup>
@@ -297,32 +297,54 @@
 
                     </LinearLayout>
 
-                    <TextView
-                        android:layout_width="wrap_content"
+                    <LinearLayout
+                        android:layout_width="match_parent"
                         android:layout_height="wrap_content"
                         android:layout_marginTop="10dp"
-                        android:text="蓝牙称配置"
-                        android:textSize="16sp"
-                        android:textStyle="bold" />
+                        android:gravity="center_vertical"
+                        android:orientation="horizontal">
 
-                    <LinearLayout
+                        <TextView
+                            android:layout_width="wrap_content"
+                            android:layout_height="wrap_content"
+                            android:text="蓝牙称配置"
+                            android:textSize="16sp"
+                            android:textStyle="bold" />
+
+                        <TextView
+                            android:id="@+id/ble_name_TV"
+                            android:layout_width="wrap_content"
+                            android:layout_height="wrap_content"
+                            android:layout_marginStart="20dp"
+                            android:textColor="@color/colorAccent" />
+                    </LinearLayout>
+
+                    <RelativeLayout
                         android:layout_width="match_parent"
                         android:layout_height="45dp"
                         android:layout_marginTop="5dp"
                         android:background="@drawable/shape_rect"
                         android:orientation="horizontal">
 
-                        <TextView
-                            android:id="@+id/ble_TV"
+                        <Button
+                            android:id="@+id/scan_BT"
+                            android:layout_width="wrap_content"
+                            android:layout_height="wrap_content"
+                            android:layout_alignParentEnd="true"
+                            android:text="扫描" />
+
+                        <androidx.appcompat.widget.AppCompatEditText
+                            android:id="@+id/ble_ET"
                             android:layout_width="match_parent"
                             android:layout_height="match_parent"
+                            android:layout_toStartOf="@id/scan_BT"
                             android:drawableStart="@drawable/ic_ble"
                             android:drawablePadding="20dp"
-                            android:gravity="center_vertical"
-                            android:hint="请配置蓝牙称"
-                            android:textSize="16sp" />
+                            android:hint="MAC地址"
+                            android:maxLines="1"
+                            android:paddingEnd="20dp" />
 
-                    </LinearLayout>
+                    </RelativeLayout>
 
                 </LinearLayout>
 

+ 12 - 12
serialport/.cxx/Debug/6e5q1f5t/arm64-v8a/configure_fingerprint.bin

@@ -2,28 +2,28 @@ C/C++ Structured Logb
 `
 ^D:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\additional_project_files.txtC
 A
-?com.android.build.gradle.internal.cxx.io.EncodedFileFingerPrint	̦ŸÖÕ2 —’¼‘Ò2_
+?com.android.build.gradle.internal.cxx.io.EncodedFileFingerPrint	¸áË€Ö2 —’¼‘Ò2_
 ]
-[D:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\android_gradle_build.json	̦ŸÖÕ2˜
+[D:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\android_gradle_build.json	¸áË€Ö2˜
  œ’¼‘Ò2d
 b
-`D:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\android_gradle_build_mini.json	̦ŸÖÕ2”	 ¼’¼‘Ò2Q
+`D:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\android_gradle_build_mini.json	¸áË€Ö2”	 ¼’¼‘Ò2Q
 O
-MD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\build.ninja	̦ŸÖÕ2މ 쑼‘Ò2U
+MD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\build.ninja	¸áË€Ö2މ 쑼‘Ò2U
 S
-QD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\build.ninja.txt	̦ŸÖÕ2Z
+QD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\build.ninja.txt	¸áË€Ö2Z
 X
-VD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\build_file_index.txt	̦ŸÖÕ2
? ¿’¼‘Ò2[
+VD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\build_file_index.txt	¸áË€Ö2
? ¿’¼‘Ò2[
 Y
-WD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\compile_commands.json	̦ŸÖÕ2¸ 둼‘Ò2_
+WD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\compile_commands.json	¸áË€Ö2¸ 둼‘Ò2_
 ]
-[D:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\compile_commands.json.bin	̦ŸÖÕ2	… 둼‘Ò2e
+[D:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\compile_commands.json.bin	¸áË€Ö2	… 둼‘Ò2e
 c
-aD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\metadata_generation_command.txt	ͦŸÖÕ2
+aD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\metadata_generation_command.txt	¸áË€Ö2
 ž ¾’¼‘Ò2X
 V
-TD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\prefab_config.json	ͦŸÖÕ2
( ¾’¼‘Ò2]
+TD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\prefab_config.json	¸áË€Ö2
( ¾’¼‘Ò2]
 [
-YD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\symbol_folder_index.txt	ͦŸÖÕ2
X ¾’¼‘Ò2C
+YD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\arm64-v8a\symbol_folder_index.txt	¸áË€Ö2
X ¾’¼‘Ò2C
 A
-?D:\work\HuaXuePin\xn_hxp\serialport\src\main\cpp\CMakeLists.txt	ͦŸÖÕ2
Ó ÈÒðê©2
+?D:\work\HuaXuePin\xn_hxp\serialport\src\main\cpp\CMakeLists.txt	¸áË€Ö2
Ó ÈÒðê©2

+ 12 - 12
serialport/.cxx/Debug/6e5q1f5t/x86/configure_fingerprint.bin

@@ -2,27 +2,27 @@ C/C++ Structured Log\
 Z
 XD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\additional_project_files.txtC
 A
-?com.android.build.gradle.internal.cxx.io.EncodedFileFingerPrint	„ã–ŒÔ2 ï“…‘Ò2Y
+?com.android.build.gradle.internal.cxx.io.EncodedFileFingerPrint	ܸè÷Õ2 ï“…‘Ò2Y
 W
-UD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\android_gradle_build.json	„ã–ŒÔ2ô	 ô“…‘Ò2^
+UD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\android_gradle_build.json	ܸè÷Õ2ô	 ô“…‘Ò2^
 \
-ZD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\android_gradle_build_mini.json	„ã–ŒÔ2ð –”…‘Ò2K
+ZD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\android_gradle_build_mini.json	ܸè÷Õ2ð –”…‘Ò2K
 I
-GD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\build.ninja	„ã–ŒÔ2Õˆ “…‘Ò2O
+GD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\build.ninja	ܸè÷Õ2Õˆ “…‘Ò2O
 M
-KD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\build.ninja.txt	„ã–ŒÔ2T
+KD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\build.ninja.txt	ܸè÷Õ2T
 R
-PD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\build_file_index.txt	„ã–ŒÔ2
? ™”…‘Ò2U
+PD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\build_file_index.txt	ܸè÷Õ2
? ™”…‘Ò2U
 S
-QD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\compile_commands.json	„ã–ŒÔ2¯ Á“…‘Ò2Y
+QD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\compile_commands.json	ܸè÷Õ2¯ Á“…‘Ò2Y
 W
-UD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\compile_commands.json.bin	„ã–ŒÔ2	ü Á“…‘Ò2_
+UD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\compile_commands.json.bin	ܸè÷Õ2	ü Á“…‘Ò2_
 ]
-[D:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\metadata_generation_command.txt	„ã–ŒÔ2
+[D:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\metadata_generation_command.txt	ܸè÷Õ2
 € ˜”…‘Ò2R
 P
-ND:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\prefab_config.json	„ã–ŒÔ2
( ˜”…‘Ò2W
+ND:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\prefab_config.json	ܸè÷Õ2
( ˜”…‘Ò2W
 U
-SD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\symbol_folder_index.txt	„ã–ŒÔ2
R ™”…‘Ò2C
+SD:\work\HuaXuePin\xn_hxp\serialport\.cxx\Debug\6e5q1f5t\x86\symbol_folder_index.txt	ݸè÷Õ2
R ™”…‘Ò2C
 A
-?D:\work\HuaXuePin\xn_hxp\serialport\src\main\cpp\CMakeLists.txt	„ã–ŒÔ2
Ó ÈÒðê©2
+?D:\work\HuaXuePin\xn_hxp\serialport\src\main\cpp\CMakeLists.txt	ݸè÷Õ2
Ó ÈÒðê©2