Skip to content

Commit

Permalink
ble notify / security sync
Browse files Browse the repository at this point in the history
  • Loading branch information
diegocardoso93 committed Jun 12, 2017
1 parent a91fe58 commit d128289
Show file tree
Hide file tree
Showing 8 changed files with 277 additions and 390 deletions.
2 changes: 1 addition & 1 deletion DroidUltrasonicScanner/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
android:theme="@style/AppTheme">
</activity>
<activity
android:name=".DeviceControlActivity"
android:name=".DeviceControl"
android:label="@string/app_name"
android:theme="@style/AppTheme">
</activity>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import android.app.Service
import android.bluetooth.BluetoothGattService
import android.bluetooth.BluetoothGattDescriptor
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothDevice
import android.content.Context.BLUETOOTH_SERVICE
import android.bluetooth.BluetoothManager
import android.os.IBinder
import android.content.Intent
Expand All @@ -17,7 +15,6 @@ import android.content.Context
import android.os.Binder
import android.util.Log
import java.util.*
import kotlin.collections.ArrayList


/**
Expand Down Expand Up @@ -69,6 +66,7 @@ class BluetoothLeService : Service() {
characteristic: BluetoothGattCharacteristic) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic)
}

}

private fun broadcastUpdate(action: String) {
Expand All @@ -79,31 +77,13 @@ class BluetoothLeService : Service() {
private fun broadcastUpdate(action: String,
characteristic: BluetoothGattCharacteristic) {
val intent = Intent(action)
// This is special handling for the Heart Rate Measurement profile. Data parsing is
// carried out as per profile specifications:
// http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.uuid)) {
val flag = characteristic.properties
var format = -1
if (flag and 0x01 != 0) {
format = BluetoothGattCharacteristic.FORMAT_UINT16
Log.d(TAG, "Heart rate format UINT16.")
} else {
format = BluetoothGattCharacteristic.FORMAT_UINT8
Log.d(TAG, "Heart rate format UINT8.")
}
val heartRate = characteristic.getIntValue(format, 1)!!
Log.d(TAG, String.format("Received heart rate: %d", heartRate))
intent.putExtra(EXTRA_DATA, heartRate.toString())
} else {
// For all other profiles, writes the data formatted in HEX.
val data = characteristic.value
if (data != null && data.size > 0) {
val stringBuilder = StringBuilder(data.size)
for (byteChar in data)
stringBuilder.append(String.format("%02X ", byteChar))
intent.putExtra(EXTRA_DATA, String(data) + "\n" + stringBuilder.toString())
}

val data = characteristic.value
if (data != null && data.size > 0) {
val stringBuilder = StringBuilder(data.size)
for (byteChar in data)
stringBuilder.append(String.format("%02X ", byteChar))
intent.putExtra(EXTRA_DATA, String(data) + "\n" + stringBuilder.toString())
}
sendBroadcast(intent)
}
Expand Down Expand Up @@ -245,52 +225,46 @@ class BluetoothLeService : Service() {
return
}
mBluetoothGatt!!.setCharacteristicNotification(characteristic, enabled)
/*
if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.uuid)) {
if (UUID_SCANNER_SENSOR.equals(characteristic.uuid)) {
val descriptor = characteristic.getDescriptor(
UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG))
UUID.fromString(CurieBleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG))
descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
mBluetoothGatt!!.writeDescriptor(descriptor)
}*/
}
}


fun readCustomCharacteristic() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w("errro", "BluetoothAdapter not initialized")
Log.w("BluetoothLeServiceError", "BluetoothAdapter not initialized")
return
}
/*check if the service is available on the device*/
val mCustomService = mBluetoothGatt!!.getService(UUID.fromString(CurieBleGattAttributes.SCANNER_SENSOR_SERVICE))
if (mCustomService == null) {
Log.w("errro", "Custom BLE Service not found")
Log.w("BluetoothLeServiceError", "Custom BLE Service not found")
return
}
/*get the read characteristic from the service*/
val mReadCharacteristic = mCustomService!!.getCharacteristic(UUID.fromString(CurieBleGattAttributes.SCANNER_SENSOR_CHARACTERISTIC))
if (mBluetoothGatt!!.readCharacteristic(mReadCharacteristic) === false) {
Log.w("errro", "Failed to read characteristic")
Log.w("BluetoothLeServiceError", "Failed to read characteristic")
}
}

fun writeCustomCharacteristic(value: ByteArray) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w("errro", "BluetoothAdapter not initialized")
Log.w("BluetoothLeServiceError", "BluetoothAdapter not initialized")
return
}
/*check if the service is available on the device*/
val mCustomService = mBluetoothGatt!!.getService(UUID.fromString(CurieBleGattAttributes.SCANNER_SENSOR_SERVICE))
if (mCustomService == null) {
Log.w("errro", "Custom BLE Service not found")
Log.w("BluetoothLeServiceError", "Custom BLE Service not found")
return
}
/*get the read characteristic from the service*/
val mWriteCharacteristic = mCustomService!!.getCharacteristic(UUID.fromString(CurieBleGattAttributes.SCANNER_SENSOR_CHARACTERISTIC))
mWriteCharacteristic.setValue(value)
if (mBluetoothGatt!!.writeCharacteristic(mWriteCharacteristic) === false) {
Log.w("errro", "Failed to write characteristic")
Log.w("BluetoothLeServiceError", "Failed to write characteristic")
}
Log.d("sucesss","yea")
}

/**
Expand All @@ -315,6 +289,6 @@ class BluetoothLeService : Service() {
val ACTION_GATT_SERVICES_DISCOVERED = "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED"
val ACTION_DATA_AVAILABLE = "com.example.bluetooth.le.ACTION_DATA_AVAILABLE"
val EXTRA_DATA = "com.example.bluetooth.le.EXTRA_DATA"
val UUID_HEART_RATE_MEASUREMENT = UUID.fromString(CurieBleGattAttributes.SCANNER_SENSOR_SERVICE)
val UUID_SCANNER_SENSOR = UUID.fromString(CurieBleGattAttributes.SCANNER_SENSOR_CHARACTERISTIC)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ object CurieBleGattAttributes {
private val attributes = HashMap<String, String>()
val SCANNER_SENSOR_SERVICE = "19b10010-e8f2-537e-4f6c-d104768a1214"
val SCANNER_SENSOR_CHARACTERISTIC = "19b10011-e8f2-537e-4f6c-d104768a1214"
var CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb"

init {
// Service
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
package br.unisc.sisemb.ultrasonicscanner

import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattService
import android.os.IBinder
import android.content.*
import android.util.Log
import java.util.*
import android.content.ComponentName
import android.content.IntentFilter
import android.content.Intent
import android.content.BroadcastReceiver
import android.content.ServiceConnection
import android.os.Handler


/**
* Created by dieg0 on 11/06/2017.
*/
class DeviceControl {
var mDeviceAddress: String? = null
var mBluetoothLeService: BluetoothLeService? = null
var mGattCharacteristics = ArrayList<ArrayList<BluetoothGattCharacteristic>>()
var mConnected = false
var mNotifyCharacteristic: BluetoothGattCharacteristic? = null

// Code to manage Service lifecycle.
val mServiceConnection = object : ServiceConnection {
override fun onServiceConnected(componentName: ComponentName, service: IBinder) {
mBluetoothLeService = (service as BluetoothLeService.LocalBinder).service
if (!mBluetoothLeService!!.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth")
}
// Automatically connects to the device upon successful start-up initialization.
mBluetoothLeService!!.connect(mDeviceAddress)
}

override fun onServiceDisconnected(componentName: ComponentName) {
mBluetoothLeService = null
}
}

// Handles various events fired by the Service.
// ACTION_GATT_CONNECTED: connected to a GATT server.
// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
// ACTION_DATA_AVAILABLE: received data from the device. This can be a result of read
// or notification operations.
val mGattUpdateReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
if (BluetoothLeService.ACTION_GATT_CONNECTED == action) {
mConnected = true
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED == action) {
mConnected = false
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED == action) {
writeInit()
val handler = Handler()
handler.postDelayed({
registerGattServices(mBluetoothLeService!!.supportedGattServices)
}, 1000)
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE == action) {
if (intent.getStringExtra(BluetoothLeService.EXTRA_DATA)!=null){
Log.d("data", intent.getStringExtra(BluetoothLeService.EXTRA_DATA))
}
}
}
}

private fun registerGattServices(gattServices: List<BluetoothGattService>?) {
if (gattServices == null) return
var uuid: String? = null
val unknownServiceString = ""
val unknownCharaString = ""
val gattServiceData = ArrayList<HashMap<String, String>>()
val gattCharacteristicData = ArrayList<ArrayList<HashMap<String, String>>>()
mGattCharacteristics = ArrayList<ArrayList<BluetoothGattCharacteristic>>()
// Loops through available GATT Services.
for (gattService in gattServices) {
uuid = gattService.uuid.toString()
if (uuid == CurieBleGattAttributes.SCANNER_SENSOR_SERVICE) {
val currentServiceData = HashMap<String, String>()
currentServiceData.put(
LIST_NAME, CurieBleGattAttributes.lookup(uuid, unknownServiceString))
currentServiceData.put(LIST_UUID, uuid)
gattServiceData.add(currentServiceData)
val gattCharacteristicGroupData = ArrayList<HashMap<String, String>>()
val gattCharacteristics = gattService.characteristics
val charas = ArrayList<BluetoothGattCharacteristic>()
// Loops through available Characteristics.
for (gattCharacteristic in gattCharacteristics) {
charas.add(gattCharacteristic)
val currentCharaData = HashMap<String, String>()
uuid = gattCharacteristic.uuid.toString()
currentCharaData.put(
LIST_NAME, CurieBleGattAttributes.lookup(uuid, unknownCharaString))
currentCharaData.put(LIST_UUID, uuid)
gattCharacteristicGroupData.add(currentCharaData)
}
mGattCharacteristics!!.add(charas)
}
}

if (mGattCharacteristics != null) {
val characteristic = mGattCharacteristics!![0].get(0)
val charaProp = characteristic.getProperties()
if (charaProp or BluetoothGattCharacteristic.PROPERTY_READ > 0) {
if (mNotifyCharacteristic != null) {
mBluetoothLeService!!.setCharacteristicNotification(
mNotifyCharacteristic!!, false)
mNotifyCharacteristic = null
}
mBluetoothLeService!!.readCharacteristic(characteristic)
}
if (charaProp or BluetoothGattCharacteristic.PROPERTY_NOTIFY > 0) {
mNotifyCharacteristic = characteristic
mBluetoothLeService!!.setCharacteristicNotification(
characteristic, true)
}
}

}

companion object {
private val TAG = DeviceControl::class.java.simpleName
val LIST_NAME = "NAME"
val LIST_UUID = "LIST_UUID"
}

fun makeGattUpdateIntentFilter(): IntentFilter {
val intentFilter = IntentFilter()
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED)
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED)
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED)
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE)
return intentFilter
}

fun writeInit() {
if (mBluetoothLeService != null){
mBluetoothLeService!!.writeCustomCharacteristic(byteArrayOf(0x02,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x01,0x00,0x02,0x04))
}
}

fun writeBle(characteristicVal: ByteArray) {
if (mBluetoothLeService != null) {
mBluetoothLeService!!.writeCustomCharacteristic(characteristicVal)
}
}

fun readBle() {
if (mBluetoothLeService != null) {
mBluetoothLeService!!.readCustomCharacteristic()
}
}
}
Loading

0 comments on commit d128289

Please sign in to comment.