Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.seesharp.app.bodysensor
- import android.Manifest
- import android.animation.ArgbEvaluator
- import android.animation.ObjectAnimator
- import android.animation.ValueAnimator
- import android.app.Activity
- import android.app.ProgressDialog
- import android.bluetooth.*
- import android.bluetooth.BluetoothProfile.STATE_CONNECTED
- import android.os.Bundle
- import com.google.android.material.snackbar.Snackbar
- import androidx.appcompat.app.AppCompatActivity
- import android.view.Menu
- import android.view.MenuItem
- import com.mazenrashed.printooth.Printooth;
- import com.mazenrashed.printooth.data.printable.Printable;
- import com.mazenrashed.printooth.data.printable.TextPrintable;
- import com.mazenrashed.printooth.data.printer.DefaultPrinter;
- import com.mazenrashed.printooth.ui.ScanningActivity;
- import com.mazenrashed.printooth.utilities.Printing;
- import com.mazenrashed.printooth.utilities.PrintingCallback;
- import kotlinx.android.synthetic.main.activity_main.*
- import android.bluetooth.le.BluetoothLeScanner
- import android.bluetooth.le.ScanCallback
- import android.bluetooth.le.ScanResult
- import android.content.Context
- import android.content.Intent
- import android.content.pm.PackageManager
- import android.graphics.Color
- import android.net.Uri
- import android.os.Build
- import android.os.VibrationEffect
- import android.os.Vibrator
- import android.provider.Settings
- import android.util.Log
- import android.view.View
- import android.widget.Toast
- import androidx.core.app.ActivityCompat
- import androidx.core.content.ContextCompat
- import kotlinx.android.synthetic.main.content_main.*
- import org.jetbrains.anko.indeterminateProgressDialog
- import kotlin.math.abs
- class MainActivity : AppCompatActivity() {
- companion object{
- val POSTURE_SENSING_SERVICE = "0000FFE0-0000-1000-8000-00805F9B34FB"
- val POSTURE_SENSING_READING_1 = "0000ffe1-0000-1000-8000-00805f9b34fb"
- val POSTURE_SENSING_READING_2 = "0000ffe2-0000-1000-8000-00805f9b34fb"
- }
- private var bluetoothAdapter: BluetoothAdapter? = null
- private var gatt: BluetoothGatt? = null
- private var device: BluetoothDevice? = null
- private var bluetoothScanner: BluetoothLeScanner? = null
- private val REQUEST_ENABLE_BT: Int = 1
- private val PERMISSION_REQ_BLUETOOTH: Int = 2
- private var hasScannedStarted: Boolean = false
- private var hasFound: Boolean = false
- private var dialog: ProgressDialog? = null
- private var packetCount = 1
- private val stringBuilder = StringBuilder()
- private var dataInArray = ByteArray(3)
- private var vibrator: Vibrator? = null
- private val VIBRATOR_PATTERN : LongArray = longArrayOf(1000, 1000, 1000)
- private var isVibrating : Boolean = false
- private var hasChangeBackrgound : Boolean = false
- private var initialLineValue = 0f
- private var initialLineValue2 = 0f
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_main)
- setSupportActionBar(toolbar)
- vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
- bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
- dialog = indeterminateProgressDialog(message = "Searching for SKY-BLE…")
- }
- override fun onPostCreate(savedInstanceState: Bundle?) {
- super.onPostCreate(savedInstanceState)
- if(!vibrator!!.hasVibrator())
- vibrator = null
- if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
- != PackageManager.PERMISSION_GRANTED) {
- // Permission is not granted
- if (ActivityCompat.shouldShowRequestPermissionRationale(this,
- Manifest.permission.ACCESS_COARSE_LOCATION)) {
- // Show an explanation to the user *asynchronously* -- don't block
- // this thread waiting for the user's response! After the user
- // sees the explanation, try again to request the permission.
- } else {
- // No explanation needed, we can request the permission.
- ActivityCompat.requestPermissions(
- this,
- arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
- PERMISSION_REQ_BLUETOOTH
- )
- }
- }
- else{
- dialog!!.show()
- bluetoothScanner = bluetoothAdapter!!.bluetoothLeScanner
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
- bluetoothScanner!!.startScan(mLeScanCallback)
- } else {
- bluetoothScanner!!.startScan(mLeScanCallback)
- }
- hasScannedStarted = true
- }
- // if (bluetoothAdapter == null || bluetoothAdapter!!.isEnabled) {
- // val builder = AlertDialog.Builder(this@MainActivity)
- // builder.setTitle("Bluetooth")
- // builder.setMessage("Bluetooth is off. Turn it on?")
- // builder.setPositiveButton("YES"){dialog, which ->
- // val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
- // startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
- // }
- //
- // builder.setNegativeButton("No"){dialog,which ->
- // Snackbar.make(findViewById(R.id.root), // Parent view
- // "Bluetooth is off", // Message to show
- // Snackbar.LENGTH_INDEFINITE //
- // ).setAction("Enable") { // Action button click listener
- // val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
- // startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
- // }.show()
- // }
- // val dialog: AlertDialog = builder.create()
- // dialog.show()
- // }
- // else{
- //
- // }
- }
- // override fun onCreateOptionsMenu(menu: Menu): Boolean {
- // // Inflate the menu; this adds items to the action bar if it is present.
- // menuInflater.inflate(R.menu.menu_main, menu)
- // return true
- // }
- //
- // override fun onOptionsItemSelected(item: MenuItem): Boolean {
- // // Handle action bar item clicks here. The action bar will
- // // automatically handle clicks on the Home/Up button, so long
- // // as you specify a parent activity in AndroidManifest.xml.
- // return when (item.itemId) {
- // R.id.action_settings -> true
- // else -> super.onOptionsItemSelected(item)
- // }
- // }
- private val mLeScanCallback = object : ScanCallback() {
- override fun onScanResult(callbackType: Int, result: ScanResult) {
- super.onScanResult(callbackType, result)
- Log.e("Bluetooth", result.device.name+"|"+result.device.type+"|"+result.device.address)
- if(result.device.address == "50:8C:B1:52:16:3B"){
- if(device == null){ // Prevent duplicate
- device = result.device
- hasFound = true
- stopScan()
- dialog!!.dismiss()
- gatt = device!!.connectGatt(this@MainActivity, false, bluetoothGattCallback)
- // gatt!!.requestMtu(50)
- Toast.makeText(this@MainActivity, "Connected to "+device!!.name, Toast.LENGTH_LONG).show()
- meter.visibility = View.VISIBLE
- }
- }
- }
- override fun onBatchScanResults(results: List<ScanResult>) {
- super.onBatchScanResults(results)
- }
- override fun onScanFailed(errorCode: Int) {
- super.onScanFailed(errorCode)
- }
- }
- private val bluetoothGattCallback = object : BluetoothGattCallback() {
- override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
- super.onServicesDiscovered(gatt, status)
- for(service in gatt!!.services){
- Log.e("Service", service.uuid.toString())
- if(service.uuid.toString().equals(POSTURE_SENSING_SERVICE, ignoreCase = true)){
- Log.e("Service Found", "true")
- for(characteristic in service.characteristics){
- Log.e("Characteristic", characteristic!!.uuid.toString())
- if(characteristic.uuid.toString().equals(POSTURE_SENSING_READING_1, ignoreCase = true)){
- val char = gatt.getService(service.uuid).getCharacteristic(characteristic.uuid)
- gatt.setCharacteristicNotification(char, true)
- break
- }
- }
- break
- }
- }
- }
- override fun onMtuChanged(gatt: BluetoothGatt?, mtu: Int, status: Int) {
- super.onMtuChanged(gatt, mtu, status)
- Log.e("MTU", "has changed")
- }
- override fun onDescriptorWrite(gatt: BluetoothGatt?, descriptor: BluetoothGattDescriptor?, status: Int) {
- super.onDescriptorWrite(gatt, descriptor, status)
- // val characteristic = descriptor!!.characteristic
- // characteristic.setValue(100)
- }
- override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
- super.onConnectionStateChange(gatt, status, newState)
- when(newState){
- STATE_CONNECTED -> {
- if(null != gatt){
- gatt.discoverServices()
- }
- }
- }
- }
- override fun onCharacteristicRead(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?, status: Int) {
- super.onCharacteristicRead(gatt, characteristic, status)
- Log.e("BLEValue1", characteristic!!.value.toString(Charsets.UTF_8))
- }
- override fun onCharacteristicChanged(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?) {
- super.onCharacteristicChanged(gatt, characteristic)
- val data = characteristic!!.value.toString(Charsets.UTF_8)
- if(packetCount == 3){
- //Process and reset data
- //Pitch = -3.51,Roll = -0.77,Temp(C) = 23.
- val hashmap = HashMap<String, String>()
- val separatedString = stringBuilder.toString().split(",")
- for(s in separatedString){
- val separatedValues = s.split("=")
- if(separatedValues.size == 2){
- hashmap[separatedValues[0].trim()] = separatedValues[1].trim()
- }
- }
- Log.e("Data", hashmap.toString())
- if(hashmap.containsKey("Pitch")){
- val value = hashmap["Pitch"]!!.toDouble()
- val roundedValue = value.toFloat()
- if(value > 0){
- rotateLine1(false, roundedValue)
- //Positive value, set meter to more than 50
- val degree = (value/90) * 100
- val m = ((50 + (degree/2)) / 100)
- Log.e("Value mP", m.toString())
- if(value > 20){
- if(null != vibrator) {
- if(!isVibrating){
- isVibrating = true
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- vibrator!!.vibrate(VibrationEffect.createWaveform(VIBRATOR_PATTERN, 0))
- } else {
- vibrator!!.vibrate(VIBRATOR_PATTERN, 0)
- }
- }
- }
- changeBackgroundOnVibrate()
- }
- else{
- if(isVibrating){
- isVibrating = false
- vibrator!!.cancel()
- }
- resetBackground()
- }
- runOnUiThread {
- if(m in 0.45..0.52)
- meter.animate(0.5f, 0.0)
- else
- meter.animate(m.toFloat(), value)
- }
- }
- else{
- rotateLine1(true, roundedValue)
- //Positive value, set meter to more than 50
- val negateValue = abs(value)
- val degree = (negateValue/90) * 100
- val m = 1.0 - ((50 + (degree/2)) / 100)
- Log.e("Value mP", m.toString())
- runOnUiThread {
- if(m in 0.45..0.52)
- meter.animate(0.5f, 0.0)
- else
- meter.animate(m.toFloat(), value)
- }
- }
- }
- if(hashmap.containsKey("Roll")){
- val value = hashmap["Roll"]!!.toDouble()
- val roundedValue = value.toFloat()
- if(value > 0){
- rotateLine2(false, roundedValue)
- //Positive value, set meter to more than 50
- val degree = (value/90) * 100
- val m = 1.0 - ((50 + (degree/2)) / 100)
- Log.e("Value m", m.toString())
- runOnUiThread {
- if(m in 0.45..0.52)
- meter2.animate(0.5f, 0.0)
- else
- meter2.animate(m.toFloat(), value)
- }
- }
- else{
- rotateLine2(true, roundedValue)
- //Positive value, set meter to more than 50
- val negateValue = abs(value)
- val degree = (negateValue/90) * 100
- val m = (50 + (degree/2)) / 100
- Log.e("Value m", m.toString())
- runOnUiThread {
- if(m in 0.45..0.52)
- meter2.animate(0.5f, 0.0)
- else
- meter2.animate(m.toFloat(), value)
- }
- }
- }
- if(hashmap.containsKey("Temp(C)")){
- val value = hashmap["Temp(C)"]!!.toDouble()
- runOnUiThread {
- temp.text = value.toInt().toString() + "°C"
- }
- }
- stringBuilder.setLength(0)
- packetCount = 1
- }
- else{
- stringBuilder.append(data)
- packetCount++
- }
- }
- }
- override fun onResume() {
- super.onResume()
- if(null == device){
- if(!hasScannedStarted){
- requestPermission()
- }
- }
- }
- override fun onDestroy() {
- super.onDestroy()
- if(null == device){
- if(hasScannedStarted){
- stopScan()
- }
- }
- else{
- if(null != gatt){
- gatt!!.close()
- gatt = null
- }
- }
- }
- override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
- super.onActivityResult(requestCode, resultCode, data)
- if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_OK) {
- requestPermission()
- }
- }
- override fun onRequestPermissionsResult(requestCode: Int,
- permissions: Array<String>, grantResults: IntArray) {
- when (requestCode) {
- PERMISSION_REQ_BLUETOOTH -> {
- // If request is cancelled, the result arrays are empty.
- if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
- // permission was granted, yay! Do the
- // contacts-related task you need to do.
- if (bluetoothAdapter == null || bluetoothAdapter!!.isEnabled) {
- bluetoothScanner = bluetoothAdapter!!.bluetoothLeScanner
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
- bluetoothScanner!!.startScan(mLeScanCallback)
- } else {
- bluetoothScanner!!.startScan(mLeScanCallback)
- }
- hasScannedStarted = true
- }
- } else {
- // permission denied, boo! Disable the
- // functionality that depends on this permission.
- Snackbar.make(findViewById(R.id.root), // Parent view
- "Bluetooth is off pr permission was denied", // Message to show
- Snackbar.LENGTH_INDEFINITE //
- ).setAction("Enable") { // Action button click listener
- val enableBtIntent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
- val uri = Uri.fromParts("package", packageName, null)
- enableBtIntent.data = uri
- startActivity(enableBtIntent)
- }.show()
- }
- return
- }
- // Add other 'when' lines to check for other
- // permissions this app might request.
- else -> {
- // Ignore all other requests.
- }
- }
- }
- private fun requestPermission(){
- if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
- != PackageManager.PERMISSION_GRANTED) {
- // Permission is not granted
- if (ActivityCompat.shouldShowRequestPermissionRationale(this,
- Manifest.permission.ACCESS_COARSE_LOCATION)) {
- // Show an explanation to the user *asynchronously* -- don't block
- // this thread waiting for the user's response! After the user
- // sees the explanation, try again to request the permission.
- } else {
- // No explanation needed, we can request the permission.
- ActivityCompat.requestPermissions(this,
- arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
- PERMISSION_REQ_BLUETOOTH)
- // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
- // app-defined int constant. The callback method gets the
- // result of the request.
- }
- }
- else{
- if (bluetoothAdapter == null || bluetoothAdapter!!.isEnabled) {
- bluetoothScanner = bluetoothAdapter!!.bluetoothLeScanner
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
- bluetoothScanner!!.startScan(mLeScanCallback)
- } else {
- bluetoothScanner!!.startScan(mLeScanCallback)
- }
- hasScannedStarted = true
- }
- }
- }
- private fun stopScan(){
- hasScannedStarted = false
- bluetoothScanner!!.stopScan(mLeScanCallback)
- }
- private fun changeBackgroundOnVibrate(){
- if(!hasChangeBackrgound){
- hasChangeBackrgound = true
- runOnUiThread {
- ObjectAnimator.ofObject(rootView, "backgroundColor", ArgbEvaluator(), Color.argb(255, 0, 87, 75), Color.argb(255, 216, 27, 96))
- .setDuration(300)
- .start()
- ObjectAnimator.ofObject(toolbar, "backgroundColor", ArgbEvaluator(), Color.argb(255, 0, 87, 75), Color.argb(255, 216, 27, 96))
- .setDuration(300)
- .start()
- }
- }
- }
- private fun resetBackground(){
- if(hasChangeBackrgound){
- hasChangeBackrgound = false
- runOnUiThread {
- ObjectAnimator.ofObject(rootView, "backgroundColor", ArgbEvaluator(), Color.argb(255, 216, 27, 96), Color.argb(255, 0, 87, 75))
- .setDuration(300)
- .start()
- ObjectAnimator.ofObject(toolbar, "backgroundColor", ArgbEvaluator(), Color.argb(255, 216, 27, 96), Color.argb(255, 0, 87, 75))
- .setDuration(300)
- .start()
- }
- }
- }
- private fun rotateLine1(isNegative:Boolean, value: Float){
- runOnUiThread {
- if(isNegative){
- val newVal = abs(value)
- ObjectAnimator.ofFloat(postureLine, View.ROTATION, newVal, initialLineValue)
- .setDuration(100)
- .start()
- initialLineValue = newVal
- }
- else{
- val newVal = abs(value) * -1
- ObjectAnimator.ofFloat(postureLine, View.ROTATION, newVal, initialLineValue)
- .setDuration(100)
- .start()
- initialLineValue = newVal
- }
- }
- }
- private fun rotateLine2(isNegative: Boolean, value: Float){
- runOnUiThread {
- if(isNegative){
- ObjectAnimator.ofFloat(postureLine2, View.ROTATION, value, initialLineValue2)
- .setDuration(100)
- .start()
- initialLineValue2 = value
- }
- else{
- ObjectAnimator.ofFloat(postureLine2, View.ROTATION, value, initialLineValue2)
- .setDuration(100)
- .start()
- initialLineValue2 = value
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement