This commit is contained in:
2025-01-04 15:46:02 +01:00
parent 09b3ec6d68
commit d854b5ceec
9 changed files with 1008 additions and 951 deletions

View File

@@ -32,8 +32,10 @@ class BLEConnectionService : Service() {
startActivity(Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)) startActivity(Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS))
} }
Log.d("Debug", "bleController null") Log.d("Debug", "bleController null")
// bleController = BLEController.getInstance(applicationContext)
bleController = BLEController(applicationContext) bleController = BLEController(applicationContext)
if(!bleController!!.isConnected()){
bleController!!.init()
}
} else if(!bleController!!.isConnected()){ } else if(!bleController!!.isConnected()){
// not connected // not connected
@@ -56,10 +58,16 @@ class BLEConnectionService : Service() {
} }
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d("DEBUG", "onStartCommand of BLE Connection Service")
if(intent?.action.equals("STARTService")){ if(intent?.action.equals("STARTService")){
Log.d("DEBUG", "Startflag set") Log.d("DEBUG", "Startflag set")
myThread.start() try {
myThread.start()
}
catch (e: Exception){
Log.d("DEBUG", "tried to start Thread, but failed :(")
}
// setup ble connection // setup ble connection
val channel_id = val channel_id =
@@ -77,13 +85,28 @@ class BLEConnectionService : Service() {
var flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK var flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
} }
val contentIntent: PendingIntent = PendingIntent.getActivity(this, 0, myIntent, PendingIntent.FLAG_IMMUTABLE) val activityIntent = Intent(this, MainActivity::class.java)
// val contentIntent: PendingIntent = PendingIntent.getActivity(this, 0, myIntent, PendingIntent.FLAG_IMMUTABLE)
val contentIntent = PendingIntent.getActivity(this, 0, activityIntent, PendingIntent.FLAG_MUTABLE);
// create stop button
// val intent = Intent(this, BLEConnectionService::class.java)
// .setAction("STOPService")
// val stopIntent = PendingIntent.getBroadcast(this, 0, intent, 0)
val notification: Notification = Notification.Builder(this, channel_id) val notification: Notification = Notification.Builder(this, channel_id)
.setContentTitle("Oil-Check") .setContentTitle("Oil-Check")
.setContentText("running") .setContentText("running")
.setSmallIcon(R.drawable.icon) .setSmallIcon(R.drawable.icon)
.setContentIntent(serviceIntent) .setContentIntent(serviceIntent)
// .setContentIntent(contentIntent)
// .setTicker(getText(R.string.ticker_text)) // .setTicker(getText(R.string.ticker_text))
// .addAction(R.drawable.icon, "Stop", contentIntent)
.build() .build()
startForeground(101, notification) startForeground(101, notification)
@@ -103,6 +126,7 @@ class BLEConnectionService : Service() {
.setContentText("running") .setContentText("running")
.setSmallIcon(R.drawable.icon) .setSmallIcon(R.drawable.icon)
.setContentIntent(nlServiceIntent) .setContentIntent(nlServiceIntent)
// .addAction(R.drawable.icon, "Stop", contentIntent)
// .setTicker(getText(R.string.ticker_text)) // .setTicker(getText(R.string.ticker_text))
.build() .build()
startForeground(101, nlNotification) startForeground(101, nlNotification)
@@ -137,7 +161,7 @@ class BLEConnectionService : Service() {
} }
else if(intent?.action.equals("Toggle")){ else if(intent?.action.equals("Toggle")){
try { try {
bleController!!.sendData("X".toByteArray(Charsets.UTF_8)) bleController!!.sendData("XX".toByteArray(Charsets.UTF_8))
} }
catch (e: Exception){ catch (e: Exception){
Log.d("Debug", "tried to toggle, but failed") Log.d("Debug", "tried to toggle, but failed")

View File

@@ -1,6 +1,8 @@
package com.example.oilcheckkotlin package com.example.oilcheckkotlin
import android.Manifest import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter.LeScanCallback
import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCallback import android.bluetooth.BluetoothGattCallback
@@ -9,15 +11,19 @@ import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile import android.bluetooth.BluetoothProfile
import android.bluetooth.le.BluetoothLeScanner import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context import android.content.Context
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.os.Build import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log import android.util.Log
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat import androidx.core.app.ActivityCompat
import java.util.Locale import java.util.Locale
class BLEController(ctx: Context) : BLEControllerListener{ class BLEController(ctx: Context) : BLEControllerListener{
companion object{ companion object{
var instance: BLEController? = null var instance: BLEController? = null
@@ -42,6 +48,8 @@ class BLEController(ctx: Context) : BLEControllerListener{
private var device: BluetoothDevice? = null private var device: BluetoothDevice? = null
private val listeners: ArrayList<BLEControllerListener> = ArrayList<BLEControllerListener>() private val listeners: ArrayList<BLEControllerListener> = ArrayList<BLEControllerListener>()
private var connectionState = false private var connectionState = false
private var scanning = false
fun stopScanner(){ fun stopScanner(){
if (ActivityCompat.checkSelfPermission( if (ActivityCompat.checkSelfPermission(
@@ -103,14 +111,44 @@ class BLEController(ctx: Context) : BLEControllerListener{
Log.d("Debug", "try to scan") Log.d("Debug", "try to scan")
this.scanner?.startScan(bleCallback) // this.scanner?.startScan(bleCallback)
this.scanForDevice()
} }
@SuppressLint("MissingPermission")
fun scanForDevice(){
Log.d("DEBUG", "SCAN for Device started")
if(!scanning){
Handler(Looper.getMainLooper()).postDelayed({
scanning = false
this.scanner?.stopScan(bleCallback)
}, SCAN_PERIOD)
Log.d("DEBUG", "nach Haendler")
scanning = true
val bleScanSettings =
ScanSettings.Builder().setCallbackType((ScanSettings.CALLBACK_TYPE_FIRST_MATCH or ScanSettings.CALLBACK_TYPE_MATCH_LOST)).build()
val filter = ScanFilter.Builder().setDeviceName("OilCheck").build()
//
val devFilter: MutableList<ScanFilter> = ArrayList()
devFilter.add(filter)
this.scanner?.startScan(devFilter, bleScanSettings, bleCallback)
}
else{
scanning = false
this.scanner?.stopScan(bleCallback)
}
}
var bleCallback = object: ScanCallback(){ var bleCallback = object: ScanCallback(){
override fun onScanResult(callbackType: Int, result: ScanResult?) { override fun onScanResult(callbackType: Int, result: ScanResult?) {
// Log.d("Debug", "onScanResult called") Log.d("Debug", "onScanResult called")
val device = result?.device // val device = result?.device
val device = result?.getDevice()
// Log.d("Debug", "device result exists") // Log.d("Debug", "device result exists")
if (!devices?.containsKey(device?.address)!! && isThisTheDevice(device)) { if (!devices?.containsKey(device?.address)!! && isThisTheDevice(device)) {
Log.d("Debug", "found the device") Log.d("Debug", "found the device")
@@ -145,8 +183,8 @@ class BLEController(ctx: Context) : BLEControllerListener{
// TODO: Consider calling // TODO: Consider calling
// ActivityCompat#requestPermissions // ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding // here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions, // public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults) // int[] grantResults)
// to handle the case where the user grants the permission. See the documentation // to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details. // for ActivityCompat#requestPermissions for more details.
return false return false
@@ -155,7 +193,12 @@ class BLEController(ctx: Context) : BLEControllerListener{
} catch (e: Exception) { } catch (e: Exception) {
Log.d("BLE", "Device with null-Name found") Log.d("BLE", "Device with null-Name found")
} }
return null != device!!.name && device.name.startsWith("OilCheck") // return null != device!!.name && device.name.startsWith("OilCheck")
// "94:B9:7E:C0:53:FE") debugger
// "30:83:98:00:89:86" KTM
return null != (device!!.address.startsWith("94:B9:7E:C0:53:FE")
or device!!.address.startsWith("30:83:98:00:89:86"))
} }
private fun deviceFound(device: BluetoothDevice) { private fun deviceFound(device: BluetoothDevice) {
Log.d("Debug", "deviceFound called") Log.d("Debug", "deviceFound called")
@@ -195,7 +238,7 @@ class BLEController(ctx: Context) : BLEControllerListener{
return return
} }
Log.d("Debug", "BLEDeviceFound called") Log.d("Debug", "BLEDeviceFound called")
BLEDeviceFound(device.name.trim { it <= ' ' }, device.address) BLEDeviceFound("device.name.trim { it <= ' ' }", device.address)
// } // }
} }
fun connectToDevice(address: String?) { fun connectToDevice(address: String?) {
@@ -327,7 +370,6 @@ class BLEController(ctx: Context) : BLEControllerListener{
} }
override fun BLEDeviceFound(name: String?, address: String?) { override fun BLEDeviceFound(name: String?, address: String?) {
// log("Device $name found with address $address")
deviceAddress = address deviceAddress = address
Log.d("Debug", "connectToDevice called") Log.d("Debug", "connectToDevice called")
// btnConnect.setEnabled(true) // btnConnect.setEnabled(true)

View File

@@ -6,15 +6,6 @@
android:layout_height="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity"> tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout <LinearLayout
android:layout_width="400dp" android:layout_width="400dp"
android:layout_height="257dp" android:layout_height="257dp"