Skip to content

Commit

Permalink
Merge pull request #31 from BIDMCDigitalPsychiatry/increase_wifi_scan…
Browse files Browse the repository at this point in the history
…_repeat_interval

Issue fix for Updated sensor frequency is not used by lamp.nearby_device #787
  • Loading branch information
ZCOEngineer authored Dec 15, 2023
2 parents a7afaac + 54eb9c1 commit b8a868a
Show file tree
Hide file tree
Showing 3 changed files with 271 additions and 6 deletions.
11 changes: 11 additions & 0 deletions lamp_kotlin/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="digital.lamp.lamp_kotlin">

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /><!-- needed for Android 28 P -->
Expand All @@ -15,6 +18,10 @@
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
<!-- Required for 29+. -->
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<application
android:usesCleartextTraffic="true">
Expand Down Expand Up @@ -45,6 +52,9 @@
<service
android:name="digital.lamp.lamp_kotlin.sensor_core.WiFi$BackgroundService"
android:exported="true" />
<service
android:name="digital.lamp.lamp_kotlin.sensor_core.WiFi$BluetoothBackgroundService"
android:exported="true" />
<service
android:name="digital.lamp.lamp_kotlin.sensor_core.Rotation"
android:exported="true" />
Expand All @@ -68,5 +78,6 @@
<service
android:name="digital.lamp.lamp_kotlin.sensor_core.TelephonySensor"
android:exported="true" />

</application>
</manifest>
264 changes: 259 additions & 5 deletions lamp_kotlin/src/main/java/digital/lamp/lamp_kotlin/sensor_core/WiFi.kt
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
package digital.lamp.lamp_kotlin.sensor_core

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlarmManager
import android.app.IntentService
import android.app.PendingIntent
import android.app.Service
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.*
import android.content.pm.PackageManager
import android.net.wifi.ScanResult
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import digital.lamp.lamp_kotlin.sensor_core.utils.LampConstants
import java.util.concurrent.Callable
import java.util.concurrent.Executors
Expand All @@ -30,32 +38,142 @@ class WiFi : Service() {
registerReceiver(wifiMonitor, filter)
backgroundService = Intent(this, BackgroundService::class.java)
backgroundService!!.action = ACTION_LAMP_WIFI_REQUEST_SCAN
wifiScan = PendingIntent.getService(this, 0, backgroundService!!, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
wifiScan = PendingIntent.getService(
this,
0,
backgroundService!!,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)

val bluetoothFilter = IntentFilter(BluetoothDevice.ACTION_FOUND)
registerReceiver(bluetoothMonitor, bluetoothFilter)
bluetoothBackgroundService = Intent(this, BluetoothBackgroundService::class.java)
bluetoothBackgroundService!!.action = BluetoothDevice.ACTION_FOUND
bluetoothScan = PendingIntent.getService(
this,
0,
bluetoothBackgroundService!!,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)

// Start discovery
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.BLUETOOTH_SCAN
) != PackageManager.PERMISSION_GRANTED
) {

}else{
val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering) {
bluetoothAdapter.cancelDiscovery()
}

// Start discovery
val filter = IntentFilter()
filter.addAction(BluetoothDevice.ACTION_FOUND)
registerReceiver(bluetoothMonitor, filter)
bluetoothAdapter?.startDiscovery()
}
}



interface LAMPSensorObserver {
fun onWiFiAPDetected(data: ContentValues?)
fun onWiFiDisabled()
fun onWiFiScanStarted()
fun onWiFiScanEnded()
fun onBluetoothDetected(data: ContentValues?)

}

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)

if (wifiManager == null) {
stopSelf()
} else {
alarmManager!!.cancel(wifiScan)
alarmManager!!.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000, LampConstants.FREQUENCY_WIFI * 1000.toLong(), wifiScan)

if (frequency != null) {
if (frequency!! >= LampConstants.FREQUENCY_WIFI) {
alarmManager?.cancel(wifiScan)
alarmManager?.setRepeating(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + 1000,
frequency!! * 1000,
wifiScan
)
}else{
alarmManager?.cancel(wifiScan)
alarmManager?.setRepeating(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + 1000,
LampConstants.FREQUENCY_WIFI * 1000.toLong(),
wifiScan
)

}
} else {
alarmManager?.cancel(wifiScan)
alarmManager?.setRepeating(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + 1000,
LampConstants.FREQUENCY_WIFI * 1000.toLong(),
wifiScan
)

}


if (Lamp.DEBUG) Log.d(TAG, "WiFi service active...")
}

scheduleBluetoothAlarm()
return START_REDELIVER_INTENT
}

private fun scheduleBluetoothAlarm() {
val alarmMgr = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val startTime = System.currentTimeMillis() + 1000
if (frequency != null) {
if (frequency!! >= LampConstants.FREQUENCY_WIFI) {
alarmMgr.cancel(bluetoothScan)
alarmMgr.setRepeating(
AlarmManager.RTC_WAKEUP,
startTime,
frequency!! * 1000,
bluetoothScan
)
}else {
alarmMgr.cancel(bluetoothScan)
alarmMgr.setRepeating(
AlarmManager.RTC_WAKEUP,
startTime,
LampConstants.FREQUENCY_WIFI * 1000.toLong(),
bluetoothScan
)
}

} else {
alarmMgr.cancel(bluetoothScan)
alarmMgr.setRepeating(
AlarmManager.RTC_WAKEUP,
startTime,
LampConstants.FREQUENCY_WIFI * 1000.toLong(),
bluetoothScan
)
}


}

override fun onDestroy() {
super.onDestroy()
unregisterReceiver(wifiMonitor)
unregisterReceiver(bluetoothMonitor)
if (wifiScan != null) alarmManager!!.cancel(wifiScan)
if (bluetoothScan != null) alarmManager!!.cancel(bluetoothScan)
if (Lamp.DEBUG) Log.d(TAG, "WiFi service terminated...")
}

Expand All @@ -73,12 +191,127 @@ class WiFi : Service() {
}
}

inner class BluetoothMonitor : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {

val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
if (bluetoothAdapter != null && bluetoothAdapter.isEnabled) {
when (intent?.action) {
BluetoothDevice.ACTION_FOUND -> {
if (ActivityCompat.checkSelfPermission(
context,
Manifest.permission.BLUETOOTH_CONNECT
) != PackageManager.PERMISSION_GRANTED
) {


}else{
val device =
intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
device?.let {
// Do something with the discovered Bluetooth device
// For example, display device information in a list
// or add it to a collection
Log.e("device", it.address)
val rowData = ContentValues()
rowData.put(TIMESTAMP, System.currentTimeMillis())
rowData.put(BLUETOOTH_ADDRESS, device.address)
rowData.put(BLUETOOTH_NAME, device.name)
rowData.put(BLUETOOTH_RSSI, device.type)
if (sensorObserver != null) sensorObserver!!.onBluetoothDetected(
rowData
)
}
}
}
}
}
}

}

class BluetoothBackgroundService : IntentService(TAG) {
private val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()

private val bluetoothReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val action = intent?.action

when (action) {
BluetoothDevice.ACTION_FOUND -> {
if (ActivityCompat.checkSelfPermission(
this@BluetoothBackgroundService,
Manifest.permission.BLUETOOTH_CONNECT
) != PackageManager.PERMISSION_GRANTED
) {

}else{
val device =
intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
device?.let {

Log.e("device", it.address)
val rowData = ContentValues()
rowData.put(TIMESTAMP, System.currentTimeMillis())
rowData.put(BLUETOOTH_ADDRESS, device.address)
rowData.put(BLUETOOTH_NAME, device.type)
/*rowData.put(BLUETOOTH_RSSI, device.type)*/
if (sensorObserver != null) sensorObserver!!.onBluetoothDetected(
rowData
)
}
}
}
}
}
}

override fun onHandleIntent(intent: Intent?) {
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
return
}

// Register for broadcasts when a device is discovered
val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
registerReceiver(bluetoothReceiver, filter)
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.BLUETOOTH_SCAN
) != PackageManager.PERMISSION_GRANTED
) {

}else{
// Start discovery
bluetoothAdapter.startDiscovery()

// The discovery will continue for 12 seconds (adjust as needed)
Thread.sleep(12000)

// Stop discovery
bluetoothAdapter.cancelDiscovery()
}

// Unregister the receiver
unregisterReceiver(bluetoothReceiver)
}
}

/**
* Asynchronously process the APs we can see around us
*/

private val wifiMonitor = WiFiMonitor()
private val bluetoothMonitor = BluetoothMonitor()


/**
* Asynchronously get the AP we are currently connected to.
*/
private class WifiInfoFetch internal constructor(private val mContext: Context, private val mWifi: WifiInfo) : Callable<String> {
private class WifiInfoFetch internal constructor(
private val mContext: Context,
private val mWifi: WifiInfo
) : Callable<String> {
@SuppressLint("HardwareIds")
@Throws(Exception::class)
override fun call(): String {
Expand All @@ -94,7 +327,10 @@ class WiFi : Service() {
/**
* Asynchronously process the APs we can see around us
*/
private class WifiApResults internal constructor(private val mContext: Context, private val mAPS: List<ScanResult>) : Callable<String> {
private class WifiApResults internal constructor(
private val mContext: Context,
private val mAPS: List<ScanResult>
) : Callable<String> {
@Throws(Exception::class)
override fun call(): String {
if (Lamp.DEBUG) Log.d(TAG, "Found " + mAPS.size + " access points")
Expand Down Expand Up @@ -173,11 +409,21 @@ class WiFi : Service() {
const val MAC_ADDRESS = "mac_address"
const val RSSI = "rssi"

const val BLUETOOTH_ADDRESS = "bluetoothAddress"
const val BLUETOOTH_NAME = "bluetoothName"
const val BLUETOOTH_RSSI = "bluetoothRSSI"

private const val TAG = "LAMP::WiFi"
private var alarmManager: AlarmManager? = null
private var wifiManager: WifiManager? = null

private var wifiScan: PendingIntent? = null
private var bluetoothScan: PendingIntent? = null

private var backgroundService: Intent? = null
private var bluetoothBackgroundService: Intent? = null

private var frequency: Long? = null

/**
* Broadcasted event: WiFi scan started
Expand All @@ -193,6 +439,14 @@ class WiFi : Service() {
* Broadcast receiving event: request a WiFi scan
*/
const val ACTION_LAMP_WIFI_REQUEST_SCAN = "ACTION_LAMP_WIFI_REQUEST_SCAN"


var sensorObserver: LAMPSensorObserver? = null

@JvmStatic
fun setInterval(frequency: Long) {
this.frequency = frequency
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ internal object LampConstants {
const val FREQUENCY_GYROSCOPE : Int = 200000
const val THRESHOLD_GYROSCOPE : Double = 1.0

const val FREQUENCY_WIFI : Int = 5
const val FREQUENCY_WIFI : Int = 60 * 5

const val INTERVAL : Long = 200//1000

Expand Down

0 comments on commit b8a868a

Please sign in to comment.