Git Product home page Git Product logo

easyble's Introduction

发现还有挺多人不知道怎么用kotlin,所以用java重构了,这个库就不维护了。点击跳转新库

English

学习提高

最新版本

Maven Central

功能

  • 支持多设备同时连接
  • 支持连接同时配对
  • 支持搜索已连接设备
  • 支持搜索器设置
  • 支持自定义搜索过滤条件
  • 支持自动重连、最大重连次数限制、直接重连或搜索到设备再重连控制
  • 支持请求延时及发送延时设置
  • 支持分包大小设置、最大传输单元设置
  • 支持注册和取消通知监听
  • 支持回调方式,支持使用注解@InvokeThread控制回调线程。注意:观察者监听和回调只能取其一!
  • 支持发送设置(是否等待发送结果回调再发送下一包)
  • 支持写入模式设置
  • 支持设置连接的传输方式
  • 支持连接超时设置

配置

  1. module的build.gradle中的添加依赖,自行修改为最新版本,同步后通常就可以用了:
dependencies {
	...
	implementation 'com.github.wandersnail:easyble:1.1.10'
}
  1. 如果从jcenter下载失败。在project的build.gradle里的repositories添加内容,最好两个都加上,有时jitpack会抽风,同步不下来。添加完再次同步即可。
allprojects {
	repositories {
		...
		maven { url 'https://jitpack.io' }
		maven { url 'https://dl.bintray.com/wandersnail/android/' }
	}
}

使用方法(kotlin)

  1. 初始化SDK
Ble.instance.initialize(application)//在Application中初始化
BleLogger.logEnabled = true//只控制打印,不控制回调
BleLogger.logCallback = object : LogCallback {
	override fun onLog(priority: Int, log: String) {
		when (priority) {
			Log.VERBOSE -> TODO()
			Log.INFO -> TODO()
			Log.DEBUG -> TODO()
			Log.WARN -> TODO()
			Log.ERROR -> TODO()
			Log.ASSERT -> TODO()
		}
	}
}
  1. 蓝牙搜索
//1. 搜索监听
private val scanListener = object : ScanListener {
	override fun onScanStart() {
		
	}

	override fun onScanStop() {
		
	}

	override fun onScanResult(device: Device) {
		//搜索到蓝牙设备
	}

	override fun onScanError(errorCode: Int, errorMsg: String) {
		when (errorCode) {
			ScanListener.ERROR_LACK_LOCATION_PERMISSION -> {//缺少定位权限
				
			}
			ScanListener.ERROR_LOCATION_SERVICE_CLOSED -> {//位置服务未开启
				
			}
		}
	}
}

//2. 添加监听
Ble.instance.addScanListener(scanListener)

//3. 搜索设置
Ble.instance.bleConfig.scanConfig.setScanPeriodMillis(30000)
		.setUseBluetoothLeScanner(true)
		.setAcceptSysConnectedDevice(true)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
	Ble.instance.bleConfig.scanConfig.setScanSettings(ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build())
}

//4. 开始搜索
Ble.instance.startScan()

//停止搜索
Ble.instance.stopScan()

  1. 连接
//连接设置
val config = ConnectionConfig()
config.setDiscoverServicesDelayMillis(500)
config.setAutoReconnect(autoReconnect)
...

//建立连接
Ble.instance.connect(device!!, config, object : ConnectionStateChangeListener {
	override fun onConnectionStateChanged(device: Device) {
		when (device.connectionState) {
			IConnection.STATE_SCANNING -> {

			}
			IConnection.STATE_CONNECTING -> {

			}
			IConnection.STATE_CONNECTED -> {

			}
			IConnection.STATE_DISCONNECTED -> {

			}
			IConnection.STATE_SERVICE_DISCOVERING -> {

			}
			IConnection.STATE_SERVICE_DISCOVERED -> {

			}
			IConnection.STATE_RELEASED -> {

			}
		}
	}

	override fun onConnectFailed(device: Device?, type: Int) {
		when (type) {
			IConnection.CONNECT_FAIL_TYPE_NON_CONNECTABLE -> {}
			IConnection.CONNECT_FAIL_TYPE_UNSPECIFIED_ADDRESS -> {}
			IConnection.CONNECT_FAIL_TYPE_MAXIMUM_RECONNECTION -> {}
		}
	}

	override fun onConnectTimeout(device: Device, type: Int) {
		when (type) {
			IConnection.TIMEOUT_TYPE_CANNOT_CONNECT -> {}
			IConnection.TIMEOUT_TYPE_CANNOT_DISCOVER_SERVICES -> {}
		}
	}
})

//断开指定连接
Ble.instance.disconnectConnection(device)
//断开所有连接
Ble.instance.disconnectAllConnections()

//释放指定连接
Ble.instance.releaseConnection(device)
//释放所有连接
Ble.instance.releaseAllConnections()
  1. 读写特征值、开启Notify
//方式一:
//1. 实例化观察者
val eventObserver = object : EventObserver {
	override fun onBluetoothStateChanged(state: Int) {
	}

	override fun onLogChanged(log: String, level: Int) {
	}

	override fun onCharacteristicRead(device: Device, tag: String, serviceUuid: UUID, characteristicUuid: UUID, value: ByteArray) {
	}

	override fun onRequestFailed(device: Device, tag: String, requestType: Request.RequestType, failType: Int, src: ByteArray?) {
	}

	override fun onCharacteristicWrite(device: Device, tag: String, serviceUuid: UUID, characteristicUuid: UUID, value: ByteArray) {
	}

	override fun onRemoteRssiRead(device: Device, tag: String, rssi: Int) {
	}

	override fun onDescriptorRead(device: Device, tag: String, serviceUuid: UUID, characteristicUuid: UUID, descriptorUuid: UUID, value: ByteArray) {
	}

	override fun onNotificationChanged(device: Device, tag: String, serviceUuid: UUID, characteristicUuid: UUID, descriptorUuid: UUID, isEnabled: Boolean) {
	}

	override fun onIndicationChanged(device: Device, tag: String, serviceUuid: UUID, characteristicUuid: UUID, descriptorUuid: UUID, isEnabled: Boolean) {
	}

	override fun onMtuChanged(device: Device, tag: String, mtu: Int) {
	}

	override fun onPhyRead(device: Device, tag: String, txPhy: Int, rxPhy: Int) {
	}

	override fun onPhyUpdate(device: Device, tag: String, txPhy: Int, rxPhy: Int) {
	}

	override fun onConnectionStateChanged(device: Device) {
	}

	override fun onConnectFailed(device: Device?, type: Int) {
	}

	override fun onConnectTimeout(device: Device, type: Int) {
	}

	override fun onCharacteristicChanged(device: Device, serviceUuid: UUID, characteristicUuid: UUID, value: ByteArray) {
	}
}
//2. 注册观察者
Ble.instance.registerObserver(eventObserver)
//3. 调用相应方法
val connection = Ble.instance.getConnection(device)
connection?.readCharacteristic(tag, service, characteristic)
connection?.enableNotification(tag, service, characteristic)
connection?.disableNotification(tag, service, characteristic)
connection?.writeCharacteristic(tag, service, characteristic, byteArrayOf(0x05, 0x06))
connection?.readRssi(tag)
...
//取消注册观察者
Ble.instance.unregisterObserver(eventObserver)

//方式二:
val connection = Ble.instance.getConnection(device)
connection?.readCharacteristic(tag, service, characteristic, object : CharacteristicReadCallback {
	@InvokeThread(RunOn.MAIN)
	override fun onCharacteristicRead(device: Device, tag: String, serviceUuid: UUID, characteristicUuid: UUID, value: ByteArray) {
	}

	@InvokeThread(RunOn.BACKGROUND)
	override fun onRequestFailed(device: Device, tag: String, requestType: Request.RequestType, failType: Int, src: ByteArray?) {
	}
})
connection?.enableNotification(tag, service, characteristic, object : CharacteristicWriteCallback {
	override fun onCharacteristicWrite(device: Device, tag: String, serviceUuid: UUID, characteristicUuid: UUID, value: ByteArray) {
	}

	override fun onRequestFailed(device: Device, tag: String, requestType: Request.RequestType, failType: Int, src: ByteArray?) {
	}
})
...
  1. 释放SDK
Ble.instance.release()

基于此库的BLE调试app

image

easyble's People

Contributors

wandersnail avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

easyble's Issues

2.8版本闪退

我的使用环境是安卓7.0/MIUI 10稳定版.在更新2.8版本后,打开app显示完广告后会闪退.
从小米商店下载的和app内更新都有此问题

Data write failure

Write data is prompt error, go to onRequestFailed callback failType = 3, what is this error, I wrote the operation is like this
IConnection.STATE_CONNECTED -> {
Log.d("测试结果","设备已连接状态")
val connection = Ble.instance.getConnection(device)
connection?.writeCharacteristic("bb", serviceUuid, characteristicUuid, "726561645F4C4544".toByteArray())//726561645F4C4544
}

easeble

这个Demo也提供的调试APP截图差距有点大,是功能还没实现吗?

部分安卓设备无法弹出PIN码

您好,我正在使用您的库,用于连接我们的中控设备。我在发现服务后,设置通知。触发设置通知代码后,基本上安卓手机就会弹出PIN码输入框,但是目前我们公司的测试机的里面,有一部华为mate9和一部OPPO手机无法弹出PIN码。下面是我的代码,请问是什么原因导致的?需要设置什么参数吗?我脱离APP在手机的设置,蓝牙列表里面去点击连接,可以正常弹出PIN码输入框。万分感激

        private fun vehicleConnect(device: Device) {
        // 连接配置
        val config = ConnectionConfiguration()
        config.setConnectTimeoutMillis(20000)
        config.setRequestTimeoutMillis(2000)
        config.setTryReconnectMaxTimes(3)
        config.setAutoReconnect(true)
        // 观察者监听连接状态
        vehicleDevice = device
        vehicleConnection = EasyBLE.getInstance().connect(device, config, object : EventObserver {
            @Tag("onConnectionStateChanged")
            @Observe
            @RunOn(ThreadMode.MAIN)
            @Override
            override fun onConnectionStateChanged(device: Device) {
                super.onConnectionStateChanged(device)
                Log.d("EasyBLE", "当前线程:${Thread.currentThread().name}")
                when (device.connectionState) {
                    ConnectionState.DISCONNECTED -> {
                        Log.d("EasyBLE", "已断开连接")
                        runOnUiThread {
                            // 如果是车辆
                            methodChannel?.invokeMethod("vehicleBlueConnectStateChange", "disconnected")
                            clearVehicleGatt()
                        }
                    }
                    ConnectionState.CONNECTING -> {
                        Log.d("EasyBLE", "正在连接")

                    }
                    ConnectionState.SCANNING_FOR_RECONNECTION -> {
                        Log.d("EasyBLE", "正在搜索重连")

                    }

                    ConnectionState.CONNECTED -> {
                        Log.d("EasyBLE", "已连接,还未执行发现服务")

                    }
                    ConnectionState.SERVICE_DISCOVERING -> {
                        Log.d("EasyBLE", "已连接,正在发现服务")

                    }
                    ConnectionState.SERVICE_DISCOVERED -> {
                        Log.d("EasyBLE", "已连接,成功发现服务")
                        // 车子获取PIN码,如果有绑定记录,直接成功
                       if (isAuto) {
                           runOnUiThread(Runnable {
                               methodChannel?.invokeMethod("vehicleBlueConnectStateChange", "connected")
                           })
                       } else {
                           // 发送PIN码获取
                           runOnUiThread(Runnable {
                               methodChannel?.invokeMethod("handlerLoadPin", null)
                           })
                       }

                        // 设置通知
                        setVehicleNotification()
                    }

                    ConnectionState.RELEASED -> {
                        Log.d("EasyBLE", "连接已释放")
                    }
                    else -> {

                    }
                }
            }


    /**
     * 车控设置通知
     */
    private fun setVehicleNotification() {
        vehicleConnection?.let {
            val serverUUID = UUID.fromString("18424398-7CBC-11E9-8F9E-2A86E4085A59")
            val writeUUID = UUID.fromString("772AE377-B3D2-4F8E-4042-5481D1E0098C")
            setNotification(it, serverUUID, writeUUID, object : NotificationChangeCallback {
                override fun onRequestFailed(request: Request, failType: Int, gattStatus: Int, value: Any?) {
                    Log.e("EasyBLE", "开启通知失败")
                }
                override fun onNotificationChanged(request: Request, isEnabled: Boolean) {
                    Log.e("EasyBLE", "通知开启")
                }
            })
        }
    }
    
    private fun setNotification(connection: Connection?, serverUUID: UUID, notificationUUID: UUID,callBack:NotificationChangeCallback) {
        Log.d("EasyBLE", "设置开启通知")
        connection?.let {
            val builder = RequestBuilderFactory().getSetNotificationBuilder(
                serverUUID,
                notificationUUID,
                true
            )
            builder.setCallback(callBack)
            builder.build().execute(it)
        }
    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.