meshtastic-android/app/src/main/java/com/geeksville/mesh/MainActivity.kt

1004 wiersze
39 KiB
Kotlin
Czysty Zwykły widok Historia

2020-01-23 05:46:41 +00:00
package com.geeksville.mesh
2020-01-20 23:53:22 +00:00
2020-01-21 21:12:01 +00:00
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
2020-01-24 20:49:27 +00:00
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
2020-01-24 20:49:27 +00:00
import android.bluetooth.BluetoothManager
import android.companion.CompanionDeviceManager
2020-02-25 16:10:23 +00:00
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
2020-06-19 03:05:33 +00:00
import android.content.pm.PackageInfo
2020-01-21 21:12:01 +00:00
import android.content.pm.PackageManager
2020-06-08 21:04:56 +00:00
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.net.Uri
2020-02-14 17:09:40 +00:00
import android.os.Build
2020-01-20 23:53:22 +00:00
import android.os.Bundle
import android.os.Handler
import android.os.RemoteException
2020-04-07 18:27:51 +00:00
import android.view.Menu
import android.view.MenuItem
import android.view.MotionEvent
2020-06-19 03:05:33 +00:00
import android.view.View
2020-01-22 21:02:24 +00:00
import android.widget.Toast
2020-04-08 15:16:06 +00:00
import androidx.activity.viewModels
2020-01-24 20:49:27 +00:00
import androidx.appcompat.app.AppCompatActivity
2020-06-19 03:05:33 +00:00
import androidx.appcompat.widget.Toolbar
2020-01-21 21:12:01 +00:00
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
2020-04-07 16:36:12 +00:00
import androidx.fragment.app.Fragment
2020-09-24 02:47:45 +00:00
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
2020-04-08 18:57:31 +00:00
import androidx.lifecycle.Observer
2020-04-07 16:36:12 +00:00
import androidx.viewpager2.adapter.FragmentStateAdapter
2020-04-11 20:20:30 +00:00
import com.geeksville.android.GeeksvilleApplication
2020-01-22 22:27:22 +00:00
import com.geeksville.android.Logging
2020-02-25 16:10:23 +00:00
import com.geeksville.android.ServiceClient
import com.geeksville.concurrent.handledLaunch
import com.geeksville.mesh.databinding.ActivityMainBinding
import com.geeksville.mesh.model.Channel
import com.geeksville.mesh.model.UIViewModel
import com.geeksville.mesh.service.*
2020-04-09 01:42:17 +00:00
import com.geeksville.mesh.ui.*
2020-03-05 17:50:33 +00:00
import com.geeksville.util.Exceptions
2020-02-05 05:23:52 +00:00
import com.geeksville.util.exceptionReporter
2020-02-14 15:47:20 +00:00
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
2020-04-11 16:39:34 +00:00
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
2020-02-14 15:47:20 +00:00
import com.google.android.gms.tasks.Task
import com.google.android.material.dialog.MaterialAlertDialogBuilder
2020-04-07 16:36:12 +00:00
import com.google.android.material.tabs.TabLayoutMediator
import com.google.protobuf.InvalidProtocolBufferException
2020-04-11 16:39:34 +00:00
import com.vorlonsoft.android.rate.AppRate
import com.vorlonsoft.android.rate.StoreType
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
2020-02-09 13:52:17 +00:00
import java.nio.charset.Charset
import java.text.DateFormat
import java.util.*
2020-01-20 23:53:22 +00:00
/*
UI design
material setup instructions: https://material.io/develop/android/docs/getting-started/
dark theme (or use system eventually) https://material.io/develop/android/theming/dark/
NavDrawer is a standard draw which can be dragged in from the left or the menu icon inside the app
title.
Fragments:
2020-02-17 02:54:29 +00:00
SettingsFragment shows "Settings"
username
shortname
bluetooth pairing list
(eventually misc device settings that are not channel related)
2020-02-17 02:54:29 +00:00
Channel fragment "Channel"
qr code, copy link button
ch number
misc other settings
(eventually a way of choosing between past channels)
2020-02-17 02:54:29 +00:00
ChatFragment "Messages"
a text box to enter new texts
a scrolling list of rows. each row is a text and a sender info layout
2020-02-17 02:54:29 +00:00
NodeListFragment "Users"
a node info row for every node
ViewModels:
BTScanModel starts/stops bt scan and provides list of devices (manages entire scan lifecycle)
MeshModel contains: (manages entire service relationship)
current received texts
current radio macaddr
current node infos (updated dynamically)
eventually use bottom navigation bar to switch between, Members, Chat, Channel, Settings. https://material.io/develop/android/components/bottom-navigation-view/
use numbers of # chat messages and # of members in the badges.
(per this recommendation to not use top tabs: https://ux.stackexchange.com/questions/102439/android-ux-when-to-use-bottom-navigation-and-when-to-use-tabs )
eventually:
make a custom theme: https://github.com/material-components/material-components-android/tree/master/material-theme-builder
*/
val utf8 = Charset.forName("UTF-8")
class MainActivity : AppCompatActivity(), Logging,
ActivityCompat.OnRequestPermissionsResultCallback {
2020-01-20 23:53:22 +00:00
2020-01-21 17:37:39 +00:00
companion object {
const val REQUEST_ENABLE_BT = 10
2020-01-21 21:12:01 +00:00
const val DID_REQUEST_PERM = 11
2020-02-14 15:47:20 +00:00
const val RC_SIGN_IN = 12 // google signin completed
const val RC_SELECT_DEVICE =
13 // seems to be hardwired in CompanionDeviceManager to add 65536
2020-01-21 17:37:39 +00:00
}
private lateinit var binding: ActivityMainBinding
// Used to schedule a coroutine in the GUI thread
private val mainScope = CoroutineScope(Dispatchers.Main + Job())
2020-02-09 15:28:24 +00:00
2020-01-22 21:02:24 +00:00
private val bluetoothAdapter: BluetoothAdapter? by lazy(LazyThreadSafetyMode.NONE) {
2020-01-21 17:37:39 +00:00
val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
2020-01-22 21:02:24 +00:00
bluetoothManager.adapter
2020-01-21 17:37:39 +00:00
}
val model: UIViewModel by viewModels()
2020-04-08 15:16:06 +00:00
2020-04-07 17:40:01 +00:00
data class TabInfo(val text: String, val icon: Int, val content: Fragment)
// private val tabIndexes = generateSequence(0) { it + 1 } FIXME, instead do withIndex or zip? to get the ids below, also stop duplicating strings
private val tabInfos = arrayOf(
2020-04-08 23:49:27 +00:00
TabInfo(
"Messages",
R.drawable.ic_twotone_message_24,
MessagesFragment()
),
2020-04-08 22:25:57 +00:00
TabInfo(
"Users",
R.drawable.ic_twotone_people_24,
UsersFragment()
),
2020-04-09 01:42:17 +00:00
TabInfo(
"Map",
R.drawable.ic_twotone_map_24,
MapFragment()
),
2020-04-07 17:40:01 +00:00
TabInfo(
"Channel",
R.drawable.ic_twotone_contactless_24,
2020-04-07 23:04:58 +00:00
ChannelFragment()
),
2020-04-07 19:13:50 +00:00
TabInfo(
"Settings",
R.drawable.ic_twotone_settings_applications_24,
2020-04-09 01:42:17 +00:00
SettingsFragment()
)
2020-04-07 17:40:01 +00:00
)
private
val tabsAdapter = object : FragmentStateAdapter(this) {
override fun getItemCount(): Int = tabInfos.size
2020-04-07 16:36:12 +00:00
override fun createFragment(position: Int): Fragment {
// Return a NEW fragment instance in createFragment(int)
/*
fragment.arguments = Bundle().apply {
// Our object is just an integer :-P
putInt(ARG_OBJECT, position + 1)
} */
2020-04-07 17:40:01 +00:00
return tabInfos[position].content
2020-04-07 16:36:12 +00:00
}
}
private val btStateReceiver = BluetoothStateReceiver { _ ->
updateBluetoothEnabled()
}
/**
* Don't tell our app we have bluetooth until we have bluetooth _and_ location access
*/
private fun updateBluetoothEnabled() {
var enabled = false // assume failure
val requiredPerms = listOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN
)
if (getMissingPermissions(requiredPerms).isEmpty()) {
/// ask the adapter if we have access
bluetoothAdapter?.apply {
enabled = isEnabled
}
} else
errormsg("Still missing needed bluetooth permissions")
debug("Detected our bluetooth access=$enabled")
model.bluetoothEnabled.value = enabled
}
/**
* return a list of the permissions we don't have
*/
private fun getMissingPermissions(perms: List<String>) = perms.filter {
ContextCompat.checkSelfPermission(
this,
it
) != PackageManager.PERMISSION_GRANTED
}
private fun getMissingPermissions(): List<String> {
2020-02-14 17:09:40 +00:00
val perms = mutableListOf(
Manifest.permission.ACCESS_COARSE_LOCATION,
2020-01-23 00:45:27 +00:00
Manifest.permission.ACCESS_FINE_LOCATION,
2020-01-21 21:12:01 +00:00
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.WAKE_LOCK
// We only need this for logging to capture files for the simulator - turn off for most users
// Manifest.permission.WRITE_EXTERNAL_STORAGE
2020-01-23 00:45:27 +00:00
)
2020-02-14 17:09:40 +00:00
if (Build.VERSION.SDK_INT >= 29) // only added later
perms.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
// Some old phones complain about requesting perms they don't understand
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
perms.add(Manifest.permission.REQUEST_COMPANION_RUN_IN_BACKGROUND)
perms.add(Manifest.permission.REQUEST_COMPANION_USE_DATA_IN_BACKGROUND)
}
return getMissingPermissions(perms)
}
private fun requestPermission() {
debug("Checking permissions")
val missingPerms = getMissingPermissions()
2020-01-21 21:12:01 +00:00
if (missingPerms.isNotEmpty()) {
missingPerms.forEach {
// Permission is not granted
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this, it)) {
// FIXME
// 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.
}
}
// Ask for all the missing perms
2020-04-07 16:36:12 +00:00
ActivityCompat.requestPermissions(
this,
missingPerms.toTypedArray(),
DID_REQUEST_PERM
)
2020-01-21 21:12:01 +00:00
// DID_REQUEST_PERM is an
// app-defined int constant. The callback method gets the
// result of the request.
} else {
// Permission has already been granted
}
}
2020-01-23 16:09:50 +00:00
/**
* Remind user he's disabled permissions we need
*/
private fun warnMissingPermissions() {
// Older versions of android don't know about these permissions - ignore failure to grant
val ignoredPermissions = setOf(
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.REQUEST_COMPANION_RUN_IN_BACKGROUND,
Manifest.permission.REQUEST_COMPANION_USE_DATA_IN_BACKGROUND
)
val deniedPermissions = getMissingPermissions().filter { name ->
!ignoredPermissions.contains(name)
}
if (deniedPermissions.isNotEmpty()) {
errormsg("Denied permissions: ${deniedPermissions.joinToString(",")}")
Toast.makeText(
this,
getString(R.string.permission_missing),
Toast.LENGTH_LONG
).show()
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
updateBluetoothEnabled()
}
2020-02-14 15:47:20 +00:00
private fun sendTestPackets() {
exceptionReporter {
val m = model.meshService!!
2020-02-14 15:47:20 +00:00
// Do some test operations
val testPayload = "hello world".toByteArray()
m.send(
DataPacket(
"+16508675310",
testPayload,
2020-12-07 11:50:06 +00:00
Portnums.PortNum.PRIVATE_APP_VALUE
)
2020-02-14 15:47:20 +00:00
)
m.send(
DataPacket(
"+16508675310",
testPayload,
2020-12-07 11:50:06 +00:00
Portnums.PortNum.TEXT_MESSAGE_APP_VALUE
)
2020-02-14 15:47:20 +00:00
)
}
}
2020-04-11 16:39:34 +00:00
/// Ask user to rate in play store
private fun askToRate() {
2020-07-08 14:50:24 +00:00
exceptionReporter { // Got one IllegalArgumentException from inside this lib, but we don't want to crash our app because of bugs in this optional feature
val hasGooglePlay = GoogleApiAvailability.getInstance()
.isGooglePlayServicesAvailable(this) != ConnectionResult.SERVICE_MISSING
val rater = AppRate.with(this)
2020-07-08 14:50:24 +00:00
.setInstallDays(10.toByte()) // default is 10, 0 means install day, 10 means app is launched 10 or more days later than installation
.setLaunchTimes(10.toByte()) // default is 10, 3 means app is launched 3 or more times
.setRemindInterval(1.toByte()) // default is 1, 1 means app is launched 1 or more days after neutral button clicked
.setRemindLaunchesNumber(1.toByte()) // default is 0, 1 means app is launched 1 or more times after neutral button clicked
.setStoreType(if (hasGooglePlay) StoreType.GOOGLEPLAY else StoreType.AMAZON)
rater.monitor() // Monitors the app launch times
2020-07-08 14:50:24 +00:00
// Only ask to rate if the user has a suitable store
AppRate.showRateDialogIfMeetsConditions(this); // Shows the Rate Dialog when conditions are met
2020-04-11 16:39:34 +00:00
}
}
private val isInTestLab: Boolean by lazy {
(application as GeeksvilleApplication).isInTestLab
}
2020-04-11 20:20:30 +00:00
2020-02-14 15:47:20 +00:00
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val prefs = UIViewModel.getPreferences(this)
model.ownerName.value = prefs.getString("owner", "")!!
/// Set initial bluetooth state
updateBluetoothEnabled()
/// We now want to be informed of bluetooth state
registerReceiver(btStateReceiver, btStateReceiver.intentFilter)
// if (!isInTestLab) - very important - even in test lab we must request permissions because we need location perms for some of our tests to pass
requestPermission()
2020-02-18 18:40:02 +00:00
2020-02-17 19:22:47 +00:00
/* not yet working
2020-02-14 15:47:20 +00:00
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
val gso =
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build()
2020-01-25 18:00:57 +00:00
2020-02-14 15:47:20 +00:00
// Build a GoogleSignInClient with the options specified by gso.
UIState.googleSignInClient = GoogleSignIn.getClient(this, gso);
2020-02-17 19:22:47 +00:00
*/
2020-04-07 16:36:12 +00:00
/* setContent {
2020-03-17 18:35:19 +00:00
MeshApp()
2020-04-07 16:36:12 +00:00
} */
setContentView(binding.root)
2020-04-07 16:36:12 +00:00
2020-06-19 03:05:33 +00:00
initToolbar()
binding.pager.adapter = tabsAdapter
binding.pager.isUserInputEnabled =
false // Gestures for screen switching doesn't work so good with the map view
2020-04-09 18:03:17 +00:00
// pager.offscreenPageLimit = 0 // Don't keep any offscreen pages around, because we want to make sure our bluetooth scanning stops
TabLayoutMediator(binding.tabLayout, binding.pager) { tab, position ->
2020-04-07 19:13:50 +00:00
// tab.text = tabInfos[position].text // I think it looks better with icons only
2021-02-21 03:34:43 +00:00
tab.icon = ContextCompat.getDrawable(this, tabInfos[position].icon)
2020-04-07 16:36:12 +00:00
}.attach()
2020-04-08 18:57:31 +00:00
model.isConnected.observe(this, Observer { connected ->
2020-06-11 01:50:34 +00:00
updateConnectionStatusImage(connected)
2020-04-08 18:57:31 +00:00
})
2020-04-11 16:39:34 +00:00
// Handle any intent
handleIntent(intent)
2020-04-11 16:39:34 +00:00
askToRate()
}
2020-06-19 03:05:33 +00:00
private fun initToolbar() {
val toolbar =
findViewById<View>(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
supportActionBar?.setDisplayShowTitleEnabled(false)
}
2020-06-11 01:50:34 +00:00
private fun updateConnectionStatusImage(connected: MeshService.ConnectionState) {
2020-07-17 21:06:29 +00:00
if (model.actionBarMenu == null)
2020-06-19 03:05:33 +00:00
return
2020-06-11 01:50:34 +00:00
val (image, tooltip) = when (connected) {
MeshService.ConnectionState.CONNECTED -> Pair(R.drawable.cloud_on, R.string.connected)
MeshService.ConnectionState.DEVICE_SLEEP -> Pair(
R.drawable.ic_twotone_cloud_upload_24,
R.string.device_sleeping
)
MeshService.ConnectionState.DISCONNECTED -> Pair(
R.drawable.cloud_off,
R.string.disconnected
)
}
2020-07-17 21:06:29 +00:00
val item = model.actionBarMenu?.findItem(R.id.connectStatusImage)
2020-06-19 03:05:33 +00:00
if (item != null) {
item.setIcon(image)
item.setTitle(tooltip)
}
2020-06-11 01:50:34 +00:00
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handleIntent(intent)
}
private var requestedChannelUrl: Uri? = null
/** We keep the usb device here, so later we can give it to our service */
private var usbDevice: UsbDevice? = null
/// Handle any itents that were passed into us
private fun handleIntent(intent: Intent) {
val appLinkAction = intent.action
val appLinkData: Uri? = intent.data
when (appLinkAction) {
Intent.ACTION_VIEW -> {
debug("Asked to open a channel URL - ask user if they want to switch to that channel. If so send the config to the radio")
requestedChannelUrl = appLinkData
// if the device is connected already, process it now
if (model.isConnected.value == MeshService.ConnectionState.CONNECTED)
perhapsChangeChannel()
// We now wait for the device to connect, once connected, we ask the user if they want to switch to the new channel
}
UsbManager.ACTION_USB_DEVICE_ATTACHED -> {
val device: UsbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)!!
debug("Handle USB device attached! $device")
usbDevice = device
}
2020-06-08 21:04:56 +00:00
Intent.ACTION_MAIN -> {
}
else -> {
warn("Unexpected action $appLinkAction")
}
2020-06-08 21:04:56 +00:00
}
2020-02-14 15:47:20 +00:00
}
2020-01-21 17:37:39 +00:00
2020-02-14 15:47:20 +00:00
override fun onDestroy() {
unregisterReceiver(btStateReceiver)
2020-02-14 15:47:20 +00:00
unregisterMeshReceiver()
mainScope.cancel("Activity going away")
2020-02-14 15:47:20 +00:00
super.onDestroy()
}
2020-02-14 12:41:20 +00:00
2020-02-14 15:47:20 +00:00
/**
* Dispatch incoming result to the correct fragment.
*/
@SuppressLint("InlinedApi")
2020-04-07 17:40:01 +00:00
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
2020-02-14 15:47:20 +00:00
super.onActivityResult(requestCode, resultCode, data)
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
when (requestCode) {
RC_SIGN_IN -> {
// The Task returned from this call is always completed, no need to attach
// a listener.
val task: Task<GoogleSignInAccount> =
GoogleSignIn.getSignedInAccountFromIntent(data)
handleSignInResult(task)
}
(65536 + RC_SELECT_DEVICE) -> when (resultCode) {
Activity.RESULT_OK -> {
// User has chosen to pair with the Bluetooth device.
val device: BluetoothDevice =
2020-04-19 23:24:47 +00:00
data?.getParcelableExtra(CompanionDeviceManager.EXTRA_DEVICE)!!
debug("Received BLE pairing ${device.address}")
if (device.bondState != BluetoothDevice.BOND_BONDED) {
device.createBond()
// FIXME - wait for bond to complete
}
// ... Continue interacting with the paired device.
model.meshService?.let { service ->
MeshService.changeDeviceAddress(this@MainActivity, service, device.address)
}
}
else ->
warn("BLE device select intent failed")
}
2020-01-20 23:53:22 +00:00
}
2020-02-14 15:47:20 +00:00
}
2020-02-09 13:52:17 +00:00
2020-02-14 15:47:20 +00:00
private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
2020-02-18 18:40:02 +00:00
/*
2020-02-14 15:47:20 +00:00
try {
2020-02-18 18:40:02 +00:00
val account = completedTask.getResult(ApiException::class.java)
2020-02-14 15:47:20 +00:00
// Signed in successfully, show authenticated UI.
//updateUI(account)
} catch (e: ApiException) { // The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
warn("signInResult:failed code=" + e.statusCode)
//updateUI(null)
2020-02-18 18:40:02 +00:00
} */
2020-02-14 15:47:20 +00:00
}
2020-04-07 17:40:01 +00:00
private
var receiverRegistered = false
2020-02-14 15:47:20 +00:00
private fun registerMeshReceiver() {
unregisterMeshReceiver()
2020-02-14 15:47:20 +00:00
val filter = IntentFilter()
filter.addAction(MeshService.ACTION_MESH_CONNECTED)
filter.addAction(MeshService.ACTION_NODE_CHANGE)
filter.addAction(MeshService.actionReceived(Portnums.PortNum.TEXT_MESSAGE_APP_VALUE))
filter.addAction((MeshService.ACTION_MESSAGE_STATUS))
2020-02-14 15:47:20 +00:00
registerReceiver(meshServiceReceiver, filter)
receiverRegistered = true;
2020-02-14 15:47:20 +00:00
}
2020-02-09 13:52:17 +00:00
2020-02-14 15:47:20 +00:00
private fun unregisterMeshReceiver() {
if (receiverRegistered) {
receiverRegistered = false
unregisterReceiver(meshServiceReceiver)
}
2020-02-14 15:47:20 +00:00
}
2020-02-09 13:52:17 +00:00
2020-02-17 02:14:40 +00:00
/// Pull our latest node db from the device
private fun updateNodesFromDevice() {
model.meshService?.let { service ->
// Update our nodeinfos based on data from the device
val nodes = service.nodes.map {
it.user?.id!! to it
}.toMap()
model.nodeDB.nodes.value = nodes
try {
// Pull down our real node ID - This must be done AFTER reading the nodedb because we need the DB to find our nodeinof object
model.nodeDB.myId.value = service.myId
val ourNodeInfo = model.nodeDB.ourNodeInfo
model.ownerName.value = ourNodeInfo?.user?.longName
} catch (ex: Exception) {
warn("Ignoring failure to get myId, service is probably just uninited... ${ex.message}")
}
}
}
2020-02-14 15:47:20 +00:00
/// Called when we gain/lose a connection to our mesh radio
private fun onMeshConnectionChanged(connected: MeshService.ConnectionState) {
debug("connchange ${model.isConnected.value} -> $connected")
2021-01-08 07:19:20 +00:00
if (connected == MeshService.ConnectionState.CONNECTED) {
2020-04-09 19:22:41 +00:00
model.meshService?.let { service ->
val oldConnection = model.isConnected.value
model.isConnected.value = connected
2020-04-09 19:22:41 +00:00
debug("Getting latest radioconfig from service")
try {
model.radioConfig.value =
MeshProtos.RadioConfig.parseFrom(service.radioConfig)
val info = service.myNodeInfo
model.myNodeInfo.value = info
val isOld = info.minAppVersion > BuildConfig.VERSION_CODE
if (isOld)
MaterialAlertDialogBuilder(this)
.setTitle(getString(R.string.app_too_old))
.setMessage(getString(R.string.must_update))
.setPositiveButton("Okay") { _, _ ->
info("User acknowledged app is old")
}
.show()
2020-05-14 00:00:23 +00:00
updateNodesFromDevice()
// we have a connection to our device now, do the channel change
perhapsChangeChannel()
} catch (ex: RemoteException) {
warn("Abandoning connect $ex, because we probably just lost device connection")
model.isConnected.value = oldConnection
}
2020-04-09 19:22:41 +00:00
}
} else {
// For other connection states, just slam them in
model.isConnected.value = connected
}
2020-02-14 15:47:20 +00:00
}
2020-02-09 13:52:17 +00:00
private fun perhapsChangeChannel() {
// If the is opening a channel URL, handle it now
requestedChannelUrl?.let { url ->
try {
val channel = Channel(url)
requestedChannelUrl = null
MaterialAlertDialogBuilder(this)
.setTitle(R.string.new_channel_rcvd)
.setMessage(getString(R.string.do_you_want_switch).format(channel.name))
.setNeutralButton(R.string.cancel) { _, _ ->
// Do nothing
}
.setPositiveButton(R.string.accept) { _, _ ->
debug("Setting channel from URL")
try {
model.setChannel(channel.settings)
} catch (ex: RemoteException) {
errormsg("Couldn't change channel ${ex.message}")
Toast.makeText(
this,
"Couldn't change channel, because radio is not yet connected. Please try again.",
Toast.LENGTH_SHORT
).show()
}
}
.show()
} catch (ex: InvalidProtocolBufferException) {
Toast.makeText(
this,
R.string.channel_invalid,
Toast.LENGTH_LONG
).show()
}
}
}
2020-03-05 17:50:33 +00:00
override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
return try {
super.dispatchTouchEvent(ev)
} catch (ex: Throwable) {
2020-03-05 17:50:33 +00:00
Exceptions.report(
ex,
"dispatchTouchEvent"
) // hide this Compose error from the user but report to the mothership
false
}
}
2020-04-07 17:40:01 +00:00
private
val meshServiceReceiver = object : BroadcastReceiver() {
2020-02-09 13:52:17 +00:00
2020-04-07 17:40:01 +00:00
override fun onReceive(context: Context, intent: Intent) =
exceptionReporter {
debug("Received from mesh service $intent")
2020-02-09 13:52:17 +00:00
2020-04-07 17:40:01 +00:00
when (intent.action) {
MeshService.ACTION_NODE_CHANGE -> {
val info: NodeInfo =
intent.getParcelableExtra(EXTRA_NODEINFO)!!
debug("UI nodechange $info")
2020-02-09 13:52:17 +00:00
2020-04-07 17:40:01 +00:00
// We only care about nodes that have user info
info.user?.id?.let {
val newnodes = model.nodeDB.nodes.value!! + Pair(it, info)
model.nodeDB.nodes.value = newnodes
2020-04-07 17:40:01 +00:00
}
2020-02-09 13:52:17 +00:00
}
MeshService.actionReceived(Portnums.PortNum.TEXT_MESSAGE_APP_VALUE) -> {
debug("received new message from service")
2020-04-07 17:40:01 +00:00
val payload =
intent.getParcelableExtra<DataPacket>(EXTRA_PAYLOAD)!!
2020-04-07 17:40:01 +00:00
model.messagesState.addMessage(payload)
2020-02-09 13:52:17 +00:00
}
MeshService.ACTION_MESSAGE_STATUS -> {
debug("received message status from service")
val id = intent.getIntExtra(EXTRA_PACKET_ID, 0)
val status = intent.getParcelableExtra<MessageStatus>(EXTRA_STATUS)!!
model.messagesState.updateStatus(id, status)
}
2020-04-07 17:40:01 +00:00
MeshService.ACTION_MESH_CONNECTED -> {
val connected =
MeshService.ConnectionState.valueOf(
intent.getStringExtra(
EXTRA_CONNECTED
)!!
)
onMeshConnectionChanged(connected)
}
else -> TODO()
2020-02-09 13:52:17 +00:00
}
}
2020-02-14 15:47:20 +00:00
}
2020-01-20 23:53:22 +00:00
private var connectionJob: Job? = null
2020-04-07 17:40:01 +00:00
private
val mesh = object :
ServiceClient<com.geeksville.mesh.IMeshService>({
com.geeksville.mesh.IMeshService.Stub.asInterface(it)
}) {
override fun onConnected(service: com.geeksville.mesh.IMeshService) {
/*
Note: we must call this callback in a coroutine. Because apparently there is only a single activity looper thread. and if that onConnected override
also tries to do a service operation we can deadlock.
Old buggy stack trace:
at sun.misc.Unsafe.park (Unsafe.java)
- waiting on an unknown object
at java.util.concurrent.locks.LockSupport.park (LockSupport.java:190)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await (AbstractQueuedSynchronizer.java:2067)
at com.geeksville.android.ServiceClient.waitConnect (ServiceClient.java:46)
at com.geeksville.android.ServiceClient.getService (ServiceClient.java:27)
at com.geeksville.mesh.service.MeshService$binder$1$setDeviceAddress$1.invoke (MeshService.java:1519)
at com.geeksville.mesh.service.MeshService$binder$1$setDeviceAddress$1.invoke (MeshService.java:1514)
at com.geeksville.util.ExceptionsKt.toRemoteExceptions (ExceptionsKt.java:56)
at com.geeksville.mesh.service.MeshService$binder$1.setDeviceAddress (MeshService.java:1516)
at com.geeksville.mesh.MainActivity$mesh$1$onConnected$1.invoke (MainActivity.java:743)
at com.geeksville.mesh.MainActivity$mesh$1$onConnected$1.invoke (MainActivity.java:734)
at com.geeksville.util.ExceptionsKt.exceptionReporter (ExceptionsKt.java:34)
at com.geeksville.mesh.MainActivity$mesh$1.onConnected (MainActivity.java:738)
at com.geeksville.mesh.MainActivity$mesh$1.onConnected (MainActivity.java:734)
at com.geeksville.android.ServiceClient$connection$1$onServiceConnected$1.invoke (ServiceClient.java:89)
at com.geeksville.android.ServiceClient$connection$1$onServiceConnected$1.invoke (ServiceClient.java:84)
at com.geeksville.util.ExceptionsKt.exceptionReporter (ExceptionsKt.java:34)
at com.geeksville.android.ServiceClient$connection$1.onServiceConnected (ServiceClient.java:85)
at android.app.LoadedApk$ServiceDispatcher.doConnected (LoadedApk.java:2067)
at android.app.LoadedApk$ServiceDispatcher$RunConnection.run (LoadedApk.java:2099)
at android.os.Handler.handleCallback (Handler.java:883)
at android.os.Handler.dispatchMessage (Handler.java:100)
at android.os.Looper.loop (Looper.java:237)
at android.app.ActivityThread.main (ActivityThread.java:8016)
at java.lang.reflect.Method.invoke (Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1076)
*/
connectionJob = mainScope.handledLaunch {
model.meshService = service
try {
usbDevice?.let { usb ->
debug("Switching to USB radio ${usb.deviceName}")
service.setDeviceAddress(SerialInterface.toInterfaceName(usb.deviceName))
usbDevice =
null // Only switch once - thereafter it should be stored in settings
}
// We don't start listening for packets until after we are connected to the service
registerMeshReceiver()
// Init our messages table with the service's record of past text messages (ignore all other message types)
val allMsgs = service.oldMessages
val msgs =
allMsgs.filter { p -> p.dataType == Portnums.PortNum.TEXT_MESSAGE_APP_VALUE }
debug("Service provided ${msgs.size} messages and myNodeNum ${service.myNodeInfo?.myNodeNum}")
model.myNodeInfo.value = service.myNodeInfo
model.messagesState.setMessages(msgs)
val connectionState =
MeshService.ConnectionState.valueOf(service.connectionState())
// if we are not connected, onMeshConnectionChange won't fetch nodes from the service
// in that case, we do it here - because the service certainly has a better idea of node db that we have
if (connectionState != MeshService.ConnectionState.CONNECTED)
updateNodesFromDevice()
// We won't receive a notify for the initial state of connection, so we force an update here
onMeshConnectionChanged(connectionState)
} catch (ex: RemoteException) {
// If we get an exception while reading our service config, the device might have gone away, double check to see if we are really connected
errormsg("Device error during init ${ex.message}")
model.isConnected.value =
MeshService.ConnectionState.valueOf(service.connectionState())
}
debug("connected to mesh service, isConnected=${model.isConnected.value}")
connectionJob = null
}
2020-02-25 16:10:23 +00:00
}
2020-02-14 15:47:20 +00:00
2020-02-25 16:10:23 +00:00
override fun onDisconnected() {
2020-02-14 15:47:20 +00:00
unregisterMeshReceiver()
model.meshService = null
2020-01-23 16:09:50 +00:00
}
2020-02-14 15:47:20 +00:00
}
2020-01-23 16:09:50 +00:00
private fun bindMeshService() {
2020-02-14 15:47:20 +00:00
debug("Binding to mesh service!")
// we bind using the well known name, to make sure 3rd party apps could also
if (model.meshService != null) {
/* This problem can occur if we unbind, but there is already an onConnected job waiting to run. That job runs and then makes meshService != null again
I think I've fixed this by cancelling connectionJob. We'll see!
*/
Exceptions.reportError("meshService was supposed to be null, ignoring (but reporting a bug)")
}
2020-07-02 16:53:52 +00:00
try {
MeshService.startService(this) // Start the service so it stays running even after we unbind
} catch (ex: Exception) {
// Old samsung phones have a race condition andthis might rarely fail. Which is probably find because the bind will be sufficient most of the time
errormsg("Failed to start service from activity - but ignoring because bind will work ${ex.message}")
}
// ALSO bind so we can use the api
mesh.connect(
this,
MeshService.createIntent(),
Context.BIND_AUTO_CREATE + Context.BIND_ABOVE_CLIENT
)
2020-02-14 15:47:20 +00:00
}
2020-01-23 16:09:50 +00:00
private fun unbindMeshService() {
2020-02-14 15:47:20 +00:00
// If we have received the service, and hence registered with
// it, then now is the time to unregister.
// if we never connected, do nothing
2020-04-19 23:24:47 +00:00
debug("Unbinding from mesh service!")
connectionJob?.let { job ->
connectionJob = null
warn("We had a pending onConnection job, so we are cancelling it")
job.cancel("unbinding")
}
2020-04-19 23:24:47 +00:00
mesh.close()
model.meshService = null
2020-02-14 15:47:20 +00:00
}
2020-01-23 16:09:50 +00:00
2020-02-18 17:09:49 +00:00
override fun onStop() {
2020-02-14 15:47:20 +00:00
unregisterMeshReceiver() // No point in receiving updates while the GUI is gone, we'll get them when the user launches the activity
unbindMeshService()
2020-01-23 16:09:50 +00:00
2020-02-18 17:09:49 +00:00
super.onStop()
2020-02-14 15:47:20 +00:00
}
2020-01-23 16:09:50 +00:00
2020-02-18 17:09:49 +00:00
override fun onStart() {
super.onStart()
2020-01-23 16:09:50 +00:00
warnMissingPermissions()
// Ask to start bluetooth if no USB devices are visible
val hasUSB = SerialInterface.findDrivers(this).isNotEmpty()
if (!isInTestLab && !hasUSB) {
bluetoothAdapter?.let {
if (!it.isEnabled) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}
}
}
2020-02-14 15:47:20 +00:00
bindMeshService()
2020-02-25 23:07:09 +00:00
val bonded = RadioInterfaceService.getBondedDeviceAddress(this) != null
if (!bonded && usbDevice == null) // we will handle USB later
showSettingsPage()
}
private fun showSettingsPage() {
binding.pager.currentItem = 5
2020-02-14 15:47:20 +00:00
}
2020-01-23 16:09:50 +00:00
2020-02-14 15:47:20 +00:00
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)
2020-07-17 21:06:29 +00:00
model.actionBarMenu = menu
updateConnectionStatusImage(model.isConnected.value!!)
2020-02-14 15:47:20 +00:00
return true
}
2020-01-20 23:53:22 +00:00
val handler: Handler by lazy {
Handler(mainLooper)
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
menu.findItem(R.id.stress_test).isVisible = BuildConfig.DEBUG // only show stress test for debug builds (for now)
return super.onPrepareOptionsMenu(menu)
}
2020-02-14 15:47:20 +00:00
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) {
2020-06-19 03:05:33 +00:00
R.id.about -> {
getVersionInfo()
return true
}
R.id.connectStatusImage -> {
Toast.makeText(applicationContext, item.title, Toast.LENGTH_SHORT).show()
2020-06-19 03:05:33 +00:00
return true
}
2020-09-24 02:47:45 +00:00
R.id.debug -> {
val fragmentManager: FragmentManager = supportFragmentManager
val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
val nameFragment = DebugFragment()
fragmentTransaction.add(R.id.mainActivityLayout, nameFragment)
fragmentTransaction.addToBackStack(null)
fragmentTransaction.commit()
return true
}
R.id.stress_test -> {
fun postPing() {
2021-02-11 05:36:45 +00:00
// Send ping message and arrange delayed recursion.
debug("Sending ping")
val str = "Ping " + DateFormat.getTimeInstance(DateFormat.MEDIUM)
2021-02-11 05:36:45 +00:00
.format(Date(System.currentTimeMillis()))
model.messagesState.sendMessage(str)
handler.postDelayed(
Runnable {
postPing()
},
30000
)
}
item.isChecked = !item.isChecked // toggle ping test
if(item.isChecked)
postPing()
else
handler.removeCallbacksAndMessages(null)
return true
}
R.id.advanced_settings -> {
val fragmentManager: FragmentManager = supportFragmentManager
val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
val nameFragment = AdvancedSettingsFragment()
fragmentTransaction.add(R.id.mainActivityLayout, nameFragment)
fragmentTransaction.addToBackStack(null)
fragmentTransaction.commit()
return true
}
2020-02-14 15:47:20 +00:00
else -> super.onOptionsItemSelected(item)
2020-01-20 23:53:22 +00:00
}
}
2020-06-19 03:05:33 +00:00
private fun getVersionInfo() {
try {
val packageInfo: PackageInfo = packageManager.getPackageInfo(packageName, 0)
val versionName = packageInfo.versionName
Toast.makeText(applicationContext, versionName, Toast.LENGTH_LONG).show()
2020-06-19 03:05:33 +00:00
} catch (e: PackageManager.NameNotFoundException) {
errormsg("Can not find the version: ${e.message}")
}
}
2020-02-14 15:47:20 +00:00
}