Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package family.emotion.emtracker
- import android.annotation.TargetApi
- import android.app.Service
- import android.bluetooth.*
- import android.content.Context
- import android.content.Intent
- import android.os.Binder
- import android.os.Build
- import android.os.DeadObjectException
- import android.os.IBinder
- import android.util.Log
- import family.emotion.emtracker.SupportedGattAttributes
- import java.util.*
- /**
- * Created by Ruslan Kishai aka creageek on 29.03.16.
- * Copyright FORCE, LLC (2016)
- */
- @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
- class BluetoothService : Service() {
- private var mBluetoothGatt: BluetoothGatt? = null
- private val serviceStack = Stack<UUID>()
- private val charStack = Stack<UUID>()
- /**
- * Variable that defines interaction with Bluetooth device: gets data from and sends broadcasts
- * notifications about new data; checks connection state and looks for Bluetooth services that
- * can be discovered
- */
- private val STATE_DISCONNECTED = 0
- private val STATE_CONNECTING = 1
- private val STATE_CONNECTED = 2
- private val mGattCallback = object : BluetoothGattCallback() {
- override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
- var intentAction: String
- if (newState == BluetoothProfile.STATE_CONNECTED) {
- intentAction = ACTION_GATT_CONNECTED
- connectionState = STATE_CONNECTED
- sendBroadcast(Intent(ACTION_GATT_CONNECTED))
- // broadcastUpdate(intentAction)
- Log.i("BLE Service", "Connected to GATT server.")
- Log.i("BLE Service", "Attempting to start service discovery:"+
- mBluetoothGatt?.discoverServices())
- } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
- intentAction = ACTION_GATT_DISCONNECTED
- connectionState = STATE_DISCONNECTED
- // bleGatt!!.connect()
- sendBroadcast(Intent(ACTION_GATT_DISCONNECTED))
- Log.i("BLE Service", "Disconnected from GATT server.")
- // broadcastUpdate(intentAction)
- } else {
- intentAction = ACTION_GATT_CONNECTING
- connectionState = STATE_CONNECTING
- sendBroadcast(Intent(ACTION_GATT_CONNECTING))
- mBluetoothGatt?.discoverServices()
- Log.i("BLE Service", "Connecting to GATT server.")
- }
- }
- override fun onCharacteristicRead(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
- super.onCharacteristicRead(gatt, characteristic, status)
- }
- override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
- super.onCharacteristicWrite(gatt, characteristic, status)
- }
- override fun onDescriptorRead(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {
- super.onDescriptorRead(gatt, descriptor, status)
- }
- override fun onReliableWriteCompleted(gatt: BluetoothGatt, status: Int) {
- super.onReliableWriteCompleted(gatt, status)
- }
- override fun onReadRemoteRssi(gatt: BluetoothGatt, rssi: Int, status: Int) {
- super.onReadRemoteRssi(gatt, rssi, status)
- }
- override fun onMtuChanged(gatt: BluetoothGatt, mtu: Int, status: Int) {
- super.onMtuChanged(gatt, mtu, status)
- }
- override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
- val value: Int
- val type: String
- try {
- if (characteristic.uuid.equals(SupportedGattAttributes.Characteristics.Heartrate)) {
- // Heartrate
- value = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1)!!
- type = TYPE_HEARTRATE
- //if (BuildConfig.DEBUG)
- Log.i(LOG_TAG, String.format("Heartrate is %d", value))
- } else if (characteristic.uuid.equals(SupportedGattAttributes.Characteristics.EDA)) {
- // EDA
- value = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 0)!!
- type = TYPE_EDA
- //if (BuildConfig.DEBUG)
- Log.i(LOG_TAG, String.format("Eda is %d", value))
- } else if (characteristic.uuid.equals(SupportedGattAttributes.Characteristics.Oxi)) {
- // Oxi
- value = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 0)!!
- type = TYPE_OXY
- //if (BuildConfig.DEBUG)
- Log.i(LOG_TAG, String.format("Oxy is %d", value))
- } else if (characteristic.uuid.equals(SupportedGattAttributes.Characteristics.Battery)) {
- // Battery
- value = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0)!!
- type = TYPE_BATTERY
- //if (BuildConfig.DEBUG)
- Log.i(LOG_TAG, String.format("Battery is %d", value))
- } else if (characteristic.uuid.equals(SupportedGattAttributes.Characteristics.FallSensor)) {
- // Fall Sensor
- value = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0)!!
- if (value != 0xAA)
- return
- type = TYPE_FALLEN
- //if (BuildConfig.DEBUG)
- Log.i(LOG_TAG, "Fallen")
- } else if (characteristic.uuid.equals(SupportedGattAttributes.Characteristics.AlertButton)) {
- // Alarm Button
- value = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0)!!
- type = TYPE_ALARM_BUTTON
- //if (BuildConfig.DEBUG)
- Log.i(LOG_TAG, "Button pressed")
- } else
- //NEW API
- if (characteristic.uuid.equals(SupportedGattAttributes.Characteristics.HRV)) {
- //HRV
- value = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0)!!
- type = TYPE_HRV
- //if (BuildConfig.DEBUG)
- Log.i(LOG_TAG, String.format("HRV is %d", value))
- } else if (characteristic.uuid.equals(SupportedGattAttributes.Characteristics.SI)) {
- //SI
- value = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0)!!
- type = TYPE_SI
- // if(BuildConfig.DEBUG)
- Log.i(LOG_TAG, String.format("SI is %d", value))
- } else {
- Log.wtf(LOG_TAG, "Unsupported characteristic")
- return
- }
- val broadcast = Intent(ACTION_GATT_EXTRA_DATA)
- broadcast.putExtra("value", value)
- broadcast.putExtra("type", type)
- sendBroadcast(broadcast)
- } catch (e: NullPointerException) {
- Log.wtf(LOG_TAG, "NullPointerException with characteristic UUID " + characteristic.uuid.toString())
- e.printStackTrace()
- }
- }
- override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
- if (status == BluetoothGatt.GATT_SUCCESS) {
- val serviceUuidList = arrayOf<UUID>(
- SupportedGattAttributes.Services.Heartrate,
- SupportedGattAttributes.Services.EDA,
- SupportedGattAttributes.Services.Oxi,
- SupportedGattAttributes.Services.Battery,
- SupportedGattAttributes.Services.HRV,
- SupportedGattAttributes.Services.SI,
- SupportedGattAttributes.Services.AlertButton,
- SupportedGattAttributes.Services.ForceAlert)
- val charUuidList = arrayOf<UUID>(
- SupportedGattAttributes.Characteristics.Heartrate,
- SupportedGattAttributes.Characteristics.EDA,
- SupportedGattAttributes.Characteristics.Oxi,
- SupportedGattAttributes.Characteristics.Battery,
- SupportedGattAttributes.Characteristics.HRV,
- SupportedGattAttributes.Characteristics.SI,
- SupportedGattAttributes.Characteristics.AlertButton,
- SupportedGattAttributes.Characteristics.FallSensor)
- val services = gatt.services
- for (i in services.indices) {
- var knownService = false
- var position = 0
- //if (BuildConfig.DEBUG)
- Log.i(LOG_TAG, "Found service with UUID " + services[i].uuid.toString())
- for (knownServices in serviceUuidList) {
- knownService = knownServices == services[i].uuid
- if (knownService)
- break
- ++position
- }
- if (knownService) {
- serviceStack.add(serviceUuidList[position])
- charStack.add(charUuidList[position])
- }
- }
- if (serviceStack.size > 0 && charStack.size > 0)
- performSubscribing(gatt)
- } else {
- Log.e(LOG_TAG, "onServicesDiscovered received: " + status)
- }
- }
- private fun performSubscribing(gatt: BluetoothGatt) {
- val pop = serviceStack.pop()
- val service = gatt.getService(pop)
- val characteristic = service.getCharacteristic(charStack.pop())
- gatt.setCharacteristicNotification(characteristic, true)
- val descriptor = characteristic.getDescriptor(SupportedGattAttributes.DEFAULT)
- descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
- if (gatt.writeDescriptor(descriptor))
- Log.i(LOG_TAG, "Started " + pop.toString())
- }
- override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {
- super.onDescriptorWrite(gatt, descriptor, status)
- if (serviceStack.size > 0 && charStack.size > 0) {
- performSubscribing(gatt)
- }
- }
- }
- var connectionState = STATE_DISCONNECTED
- override fun onDestroy() {
- super.onDestroy()
- Log.wtf(LOG_TAG, "Service stopped")
- if (mBluetoothGatt == null)
- return
- try {
- mBluetoothGatt!!.disconnect()
- mBluetoothGatt!!.close()
- mBluetoothGatt = null
- this@BluetoothService.stopSelf()
- } catch (e: DeadObjectException) {
- }
- }
- private val mLocalBinder = LocalBinder()
- inner class LocalBinder : Binder() {
- val service: BluetoothService
- get() = this@BluetoothService
- }
- override fun onBind(intent: Intent): IBinder? {
- return mLocalBinder
- }
- var device: BluetoothDevice? = null
- // override fun onStartCommand(intent: Intent?
- // , flags: Int, startId: Int): Int {
- // // if (BuildConfig.DEBUG)
- // Log.wtf(LOG_TAG, "Started service")
- // if (LocalStorage(this).getDeviceAddress() == null) {
- // Log.wtf(LOG_TAG, "Device address == null :(")
- // return Service.START_NOT_STICKY
- // }
- //
- // if (mBluetoothGatt == null || !mBluetoothGatt!!.device.address.equals(LocalStorage(this).getDeviceAddress())) {
- // val mBluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
- // val mBluetoothAdapter = mBluetoothManager.adapter
- // device = mBluetoothAdapter.getRemoteDevice(LocalStorage(this).getDeviceAddress())
- //
- // mBluetoothGatt = device?.connectGatt(this, true, mGattCallback)
- // sendBroadcast(Intent(ACTION_GATT_CONNECTING))
- // } else
- // mBluetoothGatt!!.connect()
- // return Service.START_STICKY_COMPATIBILITY
- // }
- fun getFromPrefs(key: String): String = getSharedPreferences("ble", Context.MODE_PRIVATE).getString(key, "")
- override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
- val mng = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
- val adapter = BluetoothAdapter.getDefaultAdapter()//.adapter
- val device = adapter!!.getRemoteDevice(getFromPrefs("device-address")) ?: return START_NOT_STICKY
- if (mBluetoothGatt == null) {
- mBluetoothGatt = device.connectGatt(this, true, mGattCallback)
- sendBroadcast(Intent(ACTION_GATT_CONNECTING))
- } else mBluetoothGatt!!.connect()
- return START_STICKY_COMPATIBILITY
- }
- companion object {
- private val LOG_TAG = BluetoothService::class.java.name
- val AUTHORITY = "family.emotion.emtracker"
- val ACTION_GATT_CONNECTED = AUTHORITY + ".ACTION_GATT_CONNECTED"
- val ACTION_GATT_CONNECTING = AUTHORITY + ".ACTION_GATT_CONNECTING"
- val ACTION_GATT_DISCONNECTED = AUTHORITY + ".ACTION_GATT_DISCONNECTED"
- val ACTION_GATT_DATA_AVAILABLE = AUTHORITY + ".ACTION_GATT_DATA_AVAILABLE"
- val ACTION_GATT_EXTRA_DATA = AUTHORITY + ".ACTION_GATT_EXTRA_DATA"
- val ACTION_FORGET_DEVICE = AUTHORITY + ".FORGET"
- val TYPE_HEARTRATE = AUTHORITY + ".TYPE_HEARTRATE"
- val TYPE_EDA = AUTHORITY + ".TYPE_EDA"
- val TYPE_OXY = AUTHORITY + ".TYPE_OXY"
- val TYPE_BATTERY = AUTHORITY + ".TYPE_BATTERY"
- val TYPE_FALLEN = AUTHORITY + ".TYPE_FALLEN"
- val TYPE_ALARM_BUTTON = AUTHORITY + ".TYPE_ALARM_BUTTON"
- val TYPE_HRV = AUTHORITY + ".TYPE_HRV"
- val TYPE_SI = AUTHORITY + ".TYPE_SI"
- val HEARTRATE = 1
- val OXI = 2
- val EDA = 3
- val BATTERY = 4
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement