2020-02-10 15:31:56 -08:00
package com.geeksville.mesh.service
2020-01-22 21:25:31 -08:00
2020-02-16 14:22:24 -08:00
import android.annotation.SuppressLint
2020-02-28 13:53:16 -08:00
import android.app.*
2020-02-25 08:10:23 -08:00
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
2020-02-04 13:24:04 -08:00
import android.graphics.Color
import android.os.Build
2020-01-22 21:25:31 -08:00
import android.os.IBinder
2020-02-17 18:46:20 -08:00
import android.os.RemoteException
2020-02-04 13:24:04 -08:00
import androidx.annotation.RequiresApi
2020-04-04 14:37:44 -07:00
import androidx.annotation.UiThread
2020-02-04 13:24:04 -08:00
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationCompat.PRIORITY_MIN
2020-02-25 09:28:47 -08:00
import com.geeksville.analytics.DataPair
import com.geeksville.android.GeeksvilleApplication
2020-01-22 22:16:30 -08:00
import com.geeksville.android.Logging
2020-02-25 08:10:23 -08:00
import com.geeksville.android.ServiceClient
2020-02-10 17:05:51 -08:00
import com.geeksville.mesh.*
2020-01-24 20:35:42 -08:00
import com.geeksville.mesh.MeshProtos.MeshPacket
import com.geeksville.mesh.MeshProtos.ToRadio
2020-02-24 15:33:35 -08:00
import com.geeksville.util.Exceptions
2020-02-04 13:24:04 -08:00
import com.geeksville.util.exceptionReporter
2020-01-25 11:40:13 -08:00
import com.geeksville.util.toOneLineString
2020-01-26 10:44:42 -08:00
import com.geeksville.util.toRemoteExceptions
2020-02-16 14:22:24 -08:00
import com.google.android.gms.common.api.ResolvableApiException
import com.google.android.gms.location.*
2020-01-24 20:35:42 -08:00
import com.google.protobuf.ByteString
2020-04-04 14:37:44 -07:00
import kotlinx.coroutines.*
2020-01-25 06:16:10 -08:00
import java.nio.charset.Charset
2020-04-04 14:37:44 -07:00
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
2020-01-24 17:05:55 -08:00
2020-02-04 13:24:04 -08:00
2020-02-17 15:56:04 -08:00
class RadioNotConnectedException ( ) : Exception ( " Not connected to radio " )
2020-01-26 11:33:51 -08:00
2020-02-09 05:52:17 -08:00
2020-04-04 14:37:44 -07:00
private val errorHandler = CoroutineExceptionHandler { _ , exception ->
Exceptions . report ( exception , " MeshService-coroutine " , " coroutine-exception " )
}
/// Wrap launch with an exception handler, FIXME, move into a utility lib
fun CoroutineScope . handledLaunch (
context : CoroutineContext = EmptyCoroutineContext ,
start : CoroutineStart = CoroutineStart . DEFAULT ,
block : suspend CoroutineScope . ( ) -> Unit
) = this . launch ( context = context + errorHandler , start = start , block = block )
2020-01-23 08:09:50 -08:00
/ * *
2020-01-24 17:05:55 -08:00
* Handles all the communication with android apps . Also keeps an internal model
* of the network state .
*
2020-01-23 08:09:50 -08:00
* Note : this service will go away once all clients are unbound from it .
* /
2020-01-22 22:16:30 -08:00
class MeshService : Service ( ) , Logging {
2020-02-12 15:47:06 -08:00
companion object : Logging {
2020-02-09 05:52:17 -08:00
/// Intents broadcast by MeshService
const val ACTION _RECEIVED _DATA = " $prefix .RECEIVED_DATA "
const val ACTION _NODE _CHANGE = " $prefix .NODE_CHANGE "
2020-02-10 15:31:56 -08:00
const val ACTION _MESH _CONNECTED = " $prefix .MESH_CONNECTED "
2020-02-09 05:52:17 -08:00
2020-01-25 10:00:57 -08:00
class IdNotFoundException ( id : String ) : Exception ( " ID not found $id " )
class NodeNumNotFoundException ( id : Int ) : Exception ( " NodeNum not found $id " )
2020-01-25 12:24:53 -08:00
class NotInMeshException ( ) : Exception ( " We are not yet in a mesh " )
2020-02-12 15:47:06 -08:00
/// Helper function to start running our service, returns the intent used to reach it
/// or null if the service could not be started (no bluetooth or no bonded device set)
fun startService ( context : Context ) : Intent ? {
if ( RadioInterfaceService . getBondedDeviceAddress ( context ) == null ) {
warn ( " No mesh radio is bonded, not starting service " )
return null
} else {
// bind to our service using the same mechanism an external client would use (for testing coverage)
// The following would work for us, but not external users
//val intent = Intent(this, MeshService::class.java)
//intent.action = IMeshService::class.java.name
val intent = Intent ( )
intent . setClassName (
" com.geeksville.mesh " ,
" com.geeksville.mesh.service.MeshService "
)
2020-02-09 05:52:17 -08:00
2020-02-12 15:47:06 -08:00
// Before binding we want to explicitly create - so the service stays alive forever (so it can keep
// listening for the bluetooth packets arriving from the radio. And when they arrive forward them
// to Signal or whatever.
logAssert (
( if ( Build . VERSION . SDK _INT >= Build . VERSION_CODES . O ) {
context . startForegroundService ( intent )
} else {
context . startService ( intent )
} ) != null
)
return intent
}
}
2020-02-28 14:07:04 -08:00
/// A model object for a Text message
data class TextMessage ( val fromId : String , val text : String )
2020-01-25 10:00:57 -08:00
}
2020-04-04 15:29:16 -07:00
public enum class ConnectionState {
DISCONNECTED ,
CONNECTED ,
DEVICE _SLEEP // device is in LS sleep state, it will reconnected to us over bluetooth once it has data
}
2020-01-26 11:33:51 -08:00
/// A mapping of receiver class name to package name - used for explicit broadcasts
private val clientPackages = mutableMapOf < String , String > ( )
2020-02-25 08:10:23 -08:00
val radio = ServiceClient {
IRadioInterfaceService . Stub . asInterface ( it )
}
2020-01-27 16:00:00 -08:00
2020-04-04 14:37:44 -07:00
private val serviceJob = Job ( )
private val serviceScope = CoroutineScope ( Dispatchers . IO + serviceJob )
2020-04-04 15:29:16 -07:00
/// The current state of our connection
private var connectionState = ConnectionState . DISCONNECTED
2020-01-22 22:16:30 -08:00
/ *
2020-01-23 06:34:15 -08:00
see com . geeksville . mesh broadcast intents
2020-01-22 22:16:30 -08:00
// RECEIVED_OPAQUE for data received from other nodes
// NODE_CHANGE for new IDs appearing or disappearing
2020-02-10 15:31:56 -08:00
// ACTION_MESH_CONNECTED for losing/gaining connection to the packet radio (note, this is not
the same as RadioInterfaceService . RADIO _CONNECTED _ACTION , because it implies we have assembled a valid
node db .
2020-01-22 22:16:30 -08:00
* /
2020-01-24 17:05:55 -08:00
2020-01-26 11:33:51 -08:00
private fun explicitBroadcast ( intent : Intent ) {
2020-02-09 05:52:17 -08:00
sendBroadcast ( intent ) // We also do a regular (not explicit broadcast) so any context-registered rceivers will work
2020-01-26 11:33:51 -08:00
clientPackages . forEach {
intent . setClassName ( it . value , it . key )
sendBroadcast ( intent )
}
}
2020-02-16 14:22:24 -08:00
private val locationCallback = object : LocationCallback ( ) {
2020-02-19 18:51:59 -08:00
private var lastSendMsec = 0L
2020-02-16 14:22:24 -08:00
override fun onLocationResult ( locationResult : LocationResult ) {
2020-04-04 14:37:44 -07:00
serviceScope . handledLaunch {
2020-02-24 20:08:18 -08:00
super . onLocationResult ( locationResult )
var l = locationResult . lastLocation
// Docs say lastLocation should always be !null if there are any locations, but that's not the case
if ( l == null ) {
// try to only look at the accurate locations
val locs =
locationResult . locations . filter { ! it . hasAccuracy ( ) || it . accuracy < 200 }
l = locs . lastOrNull ( )
}
if ( l != null ) {
2020-04-13 15:23:46 -07:00
info ( " got phone location " )
2020-02-24 20:08:18 -08:00
if ( l . hasAccuracy ( ) && l . accuracy >= 200 ) // if more than 200 meters off we won't use it
warn ( " accuracy ${l.accuracy} is too poor to use " )
else {
val now = System . currentTimeMillis ( )
// we limit our sends onto the lora net to a max one once every FIXME
val sendLora = ( now - lastSendMsec >= 30 * 1000 )
if ( sendLora )
lastSendMsec = now
try {
sendPosition (
l . latitude , l . longitude , l . altitude . toInt ( ) ,
destNum = if ( sendLora ) NODENUM _BROADCAST else myNodeNum ,
wantResponse = sendLora
)
} catch ( ex : RadioNotConnectedException ) {
warn ( " Lost connection to radio, stopping location requests " )
2020-04-04 15:29:16 -07:00
onConnectionChanged ( ConnectionState . DEVICE _SLEEP )
2020-02-24 20:08:18 -08:00
}
}
2020-02-16 14:22:24 -08:00
}
}
}
}
private var fusedLocationClient : FusedLocationProviderClient ? = null
/ * *
2020-02-19 10:53:36 -08:00
* start our location requests ( if they weren ' t already running )
2020-02-16 14:22:24 -08:00
*
* per https : //developer.android.com/training/location/change-location-settings
* /
@SuppressLint ( " MissingPermission " )
2020-04-04 14:37:44 -07:00
@UiThread
2020-02-16 14:22:24 -08:00
private fun startLocationRequests ( ) {
2020-02-19 10:53:36 -08:00
if ( fusedLocationClient == null ) {
2020-02-25 09:28:47 -08:00
GeeksvilleApplication . analytics . track ( " location_start " ) // Figure out how many users needed to use the phone GPS
2020-02-19 10:53:36 -08:00
val request = LocationRequest . create ( ) . apply {
interval =
2020-02-24 18:10:25 -08:00
5 * 60 * 1000 // FIXME, do more like once every 5 mins while we are connected to our radio _and_ someone else is in the mesh
2020-02-16 14:22:24 -08:00
2020-02-19 10:53:36 -08:00
priority = LocationRequest . PRIORITY _HIGH _ACCURACY
}
val builder = LocationSettingsRequest . Builder ( ) . addLocationRequest ( request )
val locationClient = LocationServices . getSettingsClient ( this )
val locationSettingsResponse = locationClient . checkLocationSettings ( builder . build ( ) )
2020-02-16 14:22:24 -08:00
2020-02-19 10:53:36 -08:00
locationSettingsResponse . addOnSuccessListener {
debug ( " We are now successfully listening to the GPS " )
}
2020-02-16 14:22:24 -08:00
2020-02-19 10:53:36 -08:00
locationSettingsResponse . addOnFailureListener { exception ->
2020-02-29 13:21:05 -08:00
errormsg ( " Failed to listen to GPS " )
2020-02-19 10:53:36 -08:00
if ( exception is ResolvableApiException ) {
2020-02-25 07:23:35 -08:00
Exceptions . report ( exception ) // FIXME, not yet implemented, report failure to mothership
2020-02-19 10:53:36 -08:00
exceptionReporter {
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
// FIXME
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
/ * exception . startResolutionForResult (
this @MainActivity ,
REQUEST _CHECK _SETTINGS
) * /
}
} else
2020-02-24 15:33:35 -08:00
Exceptions . report ( exception )
2020-02-19 10:53:36 -08:00
}
2020-02-16 14:22:24 -08:00
2020-02-19 10:53:36 -08:00
val client = LocationServices . getFusedLocationProviderClient ( this )
2020-02-16 14:22:24 -08:00
2020-02-19 10:53:36 -08:00
// FIXME - should we use Looper.myLooper() in the third param per https://github.com/android/location-samples/blob/432d3b72b8c058f220416958b444274ddd186abd/LocationUpdatesForegroundService/app/src/main/java/com/google/android/gms/location/sample/locationupdatesforegroundservice/LocationUpdatesService.java
client . requestLocationUpdates ( request , locationCallback , null )
2020-02-16 14:22:24 -08:00
2020-02-19 10:53:36 -08:00
fusedLocationClient = client
}
2020-02-16 14:22:24 -08:00
}
private fun stopLocationRequests ( ) {
2020-02-19 10:53:36 -08:00
if ( fusedLocationClient != null ) {
debug ( " Stopping location requests " )
2020-02-25 09:28:47 -08:00
GeeksvilleApplication . analytics . track ( " location_stop " )
2020-02-19 10:53:36 -08:00
fusedLocationClient ?. removeLocationUpdates ( locationCallback )
fusedLocationClient = null
}
2020-02-16 14:22:24 -08:00
}
2020-02-10 15:31:56 -08:00
2020-01-24 17:05:55 -08:00
/ * *
* The RECEIVED _OPAQUE :
* Payload will be the raw bytes which were contained within a MeshPacket . Opaque field
* Sender will be a user ID string
2020-01-25 06:33:30 -08:00
* Type will be the Data . Type enum code for this payload
2020-01-24 17:05:55 -08:00
* /
2020-02-09 05:52:17 -08:00
private fun broadcastReceivedData ( senderId : String , payload : ByteArray , typ : Int ) {
val intent = Intent ( ACTION _RECEIVED _DATA )
2020-01-24 17:05:55 -08:00
intent . putExtra ( EXTRA _SENDER , senderId )
intent . putExtra ( EXTRA _PAYLOAD , payload )
2020-01-25 06:33:30 -08:00
intent . putExtra ( EXTRA _TYP , typ )
2020-01-26 11:33:51 -08:00
explicitBroadcast ( intent )
2020-01-22 22:16:30 -08:00
}
2020-02-09 05:52:17 -08:00
private fun broadcastNodeChange ( info : NodeInfo ) {
debug ( " Broadcasting node change $info " )
val intent = Intent ( ACTION _NODE _CHANGE )
2020-02-25 09:28:47 -08:00
2020-02-09 05:52:17 -08:00
intent . putExtra ( EXTRA _NODEINFO , info )
2020-01-26 11:33:51 -08:00
explicitBroadcast ( intent )
2020-01-22 22:16:30 -08:00
}
2020-01-22 21:25:31 -08:00
2020-02-04 12:12:29 -08:00
/// Safely access the radio service, if not connected an exception will be thrown
private val connectedRadio : IRadioInterfaceService
2020-04-04 15:29:16 -07:00
get ( ) = ( if ( connectionState == ConnectionState . CONNECTED ) radio . serviceP else null )
?: throw RadioNotConnectedException ( )
2020-01-27 19:23:34 -08:00
/// Send a command/packet to our radio. But cope with the possiblity that we might start up
/// before we are fully bound to the RadioInterfaceService
2020-01-24 20:35:42 -08:00
private fun sendToRadio ( p : ToRadio . Builder ) {
2020-01-27 19:23:34 -08:00
val b = p . build ( ) . toByteArray ( )
2020-02-04 12:12:29 -08:00
connectedRadio . sendToRadio ( b )
2020-01-24 20:35:42 -08:00
}
2020-01-26 11:33:51 -08:00
override fun onBind ( intent : Intent ? ) : IBinder ? {
2020-01-22 21:25:31 -08:00
return binder
}
2020-02-04 13:24:04 -08:00
@RequiresApi ( Build . VERSION_CODES . O )
private fun createNotificationChannel ( ) : String {
val channelId = " my_service "
val channelName = " My Background Service "
val chan = NotificationChannel (
channelId ,
channelName , NotificationManager . IMPORTANCE _HIGH
)
chan . lightColor = Color . BLUE
chan . importance = NotificationManager . IMPORTANCE _NONE
chan . lockscreenVisibility = Notification . VISIBILITY _PRIVATE
2020-02-28 20:09:00 -08:00
notificationManager . createNotificationChannel ( chan )
2020-02-04 13:24:04 -08:00
return channelId
}
2020-02-28 13:53:16 -08:00
private val notifyId = 101
val notificationManager : NotificationManager by lazy ( ) {
getSystemService ( Context . NOTIFICATION _SERVICE ) as NotificationManager
}
2020-02-04 13:24:04 -08:00
2020-02-28 20:09:00 -08:00
/// This must be lazy because we use Context
private val channelId : String by lazy ( ) {
2020-02-28 13:53:16 -08:00
if ( Build . VERSION . SDK _INT >= Build . VERSION_CODES . O ) {
createNotificationChannel ( )
} else {
// If earlier version channel ID is not used
// https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
" "
}
2020-02-28 20:09:00 -08:00
}
2020-02-28 13:53:16 -08:00
2020-02-28 20:09:00 -08:00
private val openAppIntent : PendingIntent by lazy ( ) {
PendingIntent . getActivity ( this , 0 , Intent ( this , MainActivity :: class . java ) , 0 )
}
2020-02-28 14:07:04 -08:00
/// A text message that has a arrived since the last notification update
private var recentReceivedText : TextMessage ? = null
2020-02-28 13:53:16 -08:00
2020-04-04 15:29:16 -07:00
private val summaryString
get ( ) = when ( connectionState ) {
ConnectionState . CONNECTED -> " Connected: $numOnlineNodes of $numNodes online "
ConnectionState . DISCONNECTED -> " Disconnected "
ConnectionState . DEVICE _SLEEP -> " Device sleeping "
}
2020-02-28 13:53:16 -08:00
override fun toString ( ) = summaryString
2020-02-04 13:24:04 -08:00
2020-02-28 13:53:16 -08:00
/ * *
* Generate a new version of our notification - reflecting current app state
* /
private fun createNotification ( ) : Notification {
2020-02-28 20:09:00 -08:00
val notificationBuilder = NotificationCompat . Builder ( this , channelId )
2020-02-28 13:53:16 -08:00
val builder = notificationBuilder . setOngoing ( true )
2020-02-04 13:24:04 -08:00
. setPriority ( PRIORITY _MIN )
2020-02-28 14:07:04 -08:00
. setCategory ( if ( recentReceivedText != null ) Notification . CATEGORY _SERVICE else Notification . CATEGORY _MESSAGE )
2020-02-04 13:24:04 -08:00
. setSmallIcon ( android . R . drawable . stat _sys _data _bluetooth )
2020-02-28 20:09:00 -08:00
. setContentTitle ( summaryString ) // leave this off for now so our notification looks smaller
2020-02-28 13:53:16 -08:00
. setVisibility ( NotificationCompat . VISIBILITY _PUBLIC )
. setContentIntent ( openAppIntent )
2020-02-04 13:24:04 -08:00
2020-02-28 14:11:42 -08:00
// FIXME, show information about the nearest node
// if(shortContent != null) builder.setContentText(shortContent)
2020-01-24 17:05:55 -08:00
2020-02-28 14:07:04 -08:00
// If a text message arrived include it with our notification
recentReceivedText ?. let { msg ->
2020-04-19 09:33:41 -07:00
// Try to show the human name of the sender if possible
val sender = nodeDBbyID [ msg . fromId ] ?. user ?. longName ?: msg . fromId
builder . setContentText ( " Message from $sender " )
2020-02-28 14:07:04 -08:00
2020-02-28 13:53:16 -08:00
builder . setStyle (
NotificationCompat . BigTextStyle ( )
2020-02-28 14:07:04 -08:00
. bigText ( msg . text )
2020-02-28 13:53:16 -08:00
)
2020-02-28 14:07:04 -08:00
}
2020-01-24 20:35:42 -08:00
2020-02-28 13:53:16 -08:00
return builder . build ( )
}
2020-02-04 13:24:04 -08:00
2020-02-28 13:53:16 -08:00
/ * *
* Update our notification with latest data
* /
private fun updateNotification ( ) {
notificationManager . notify ( notifyId , createNotification ( ) )
}
/ * *
* tell android not to kill us
* /
private fun startForeground ( ) {
startForeground ( notifyId , createNotification ( ) )
}
2020-02-04 13:24:04 -08:00
2020-02-28 13:53:16 -08:00
override fun onCreate ( ) {
super . onCreate ( )
2020-02-04 13:24:04 -08:00
2020-02-28 13:53:16 -08:00
info ( " Creating mesh service " )
2020-02-04 13:24:04 -08:00
startForeground ( )
2020-02-04 12:12:29 -08:00
// we listen for messages from the radio receiver _before_ trying to create the service
2020-02-04 13:24:04 -08:00
val filter = IntentFilter ( )
filter . addAction ( RadioInterfaceService . RECEIVE _FROMRADIO _ACTION )
2020-02-10 15:31:56 -08:00
filter . addAction ( RadioInterfaceService . RADIO _CONNECTED _ACTION )
2020-02-04 12:12:29 -08:00
registerReceiver ( radioInterfaceReceiver , filter )
2020-01-27 16:00:00 -08:00
// We in turn need to use the radiointerface service
val intent = Intent ( this , RadioInterfaceService :: class . java )
// intent.action = IMeshService::class.java.name
2020-02-25 08:10:23 -08:00
radio . connect ( this , intent , Context . BIND _AUTO _CREATE )
2020-01-24 20:35:42 -08:00
2020-01-27 16:00:00 -08:00
// the rest of our init will happen once we are in radioConnection.onServiceConnected
2020-01-24 17:05:55 -08:00
}
2020-01-27 16:00:00 -08:00
2020-01-24 17:05:55 -08:00
override fun onDestroy ( ) {
2020-01-25 10:00:57 -08:00
info ( " Destroying mesh service " )
2020-02-04 12:12:29 -08:00
unregisterReceiver ( radioInterfaceReceiver )
2020-02-25 08:10:23 -08:00
radio . close ( )
2020-01-27 16:00:00 -08:00
2020-01-24 17:05:55 -08:00
super . onDestroy ( )
2020-04-04 14:37:44 -07:00
serviceJob . cancel ( )
2020-01-24 17:05:55 -08:00
}
2020-02-25 08:10:23 -08:00
2020-01-24 22:22:30 -08:00
///
/// BEGINNING OF MODEL - FIXME, move elsewhere
///
2020-02-16 14:22:24 -08:00
/// special broadcast address
val NODENUM _BROADCAST = 255
// MyNodeInfo sent via special protobuf from radio
2020-03-12 11:58:10 -07:00
data class MyNodeInfo (
val myNodeNum : Int ,
val hasGPS : Boolean ,
val region : String ,
val model : String ,
val firmwareVersion : String
)
2020-02-16 14:22:24 -08:00
var myNodeInfo : MyNodeInfo ? = null
2020-04-04 15:29:16 -07:00
private var radioConfig : MeshProtos . RadioConfig ? = null
2020-01-24 22:22:30 -08:00
2020-03-30 17:35:33 -07:00
/// True after we've done our initial node db init
private var haveNodeDB = false
2020-01-24 20:35:42 -08:00
// The database of active nodes, index is the node number
private val nodeDBbyNodeNum = mutableMapOf < Int , NodeInfo > ( )
/// The database of active nodes, index is the node user ID string
2020-01-24 22:22:30 -08:00
/// NOTE: some NodeInfos might be in only nodeDBbyNodeNum (because we don't yet know
/// an ID). But if a NodeInfo is in both maps, it must be one instance shared by
/// both datastructures.
2020-01-24 20:35:42 -08:00
private val nodeDBbyID = mutableMapOf < String , NodeInfo > ( )
2020-01-24 22:22:30 -08:00
///
/// END OF MODEL
///
2020-01-24 20:35:42 -08:00
2020-01-24 22:22:30 -08:00
/// Map a nodenum to a node, or throw an exception if not found
2020-02-10 15:31:56 -08:00
private fun toNodeInfo ( n : Int ) = nodeDBbyNodeNum [ n ] ?: throw NodeNumNotFoundException (
n
)
2020-01-24 22:22:30 -08:00
/// Map a nodenum to the nodeid string, or throw an exception if not present
private fun toNodeID ( n : Int ) = toNodeInfo ( n ) . user ?. id
/// given a nodenum, return a db entry - creating if necessary
2020-01-25 06:16:10 -08:00
private fun getOrCreateNodeInfo ( n : Int ) =
nodeDBbyNodeNum . getOrPut ( n ) { -> NodeInfo ( n ) }
2020-01-24 22:22:30 -08:00
/// Map a userid to a node/ node num, or throw an exception if not found
2020-01-25 11:40:13 -08:00
private fun toNodeInfo ( id : String ) =
nodeDBbyID [ id ]
2020-02-10 15:31:56 -08:00
?: throw IdNotFoundException (
id
)
2020-01-26 15:01:59 -08:00
2020-02-19 10:53:36 -08:00
2020-02-25 09:28:47 -08:00
private val numNodes get ( ) = nodeDBbyNodeNum . size
2020-02-19 10:53:36 -08:00
/ * *
* How many nodes are currently online ( including our local node )
* /
private val numOnlineNodes get ( ) = nodeDBbyNodeNum . values . count { it . isOnline }
2020-01-24 22:22:30 -08:00
private fun toNodeNum ( id : String ) = toNodeInfo ( id ) . num
/// A helper function that makes it easy to update node info objects
private fun updateNodeInfo ( nodeNum : Int , updatefn : ( NodeInfo ) -> Unit ) {
val info = getOrCreateNodeInfo ( nodeNum )
updatefn ( info )
2020-02-04 12:12:29 -08:00
// This might have been the first time we know an ID for this node, so also update the by ID map
2020-02-14 04:41:20 -08:00
val userId = info . user ?. id . orEmpty ( )
if ( userId . isNotEmpty ( ) )
2020-02-04 12:12:29 -08:00
nodeDBbyID [ userId ] = info
2020-02-09 05:52:17 -08:00
2020-02-09 10:18:26 -08:00
// parcelable is busted
2020-02-10 16:34:01 -08:00
broadcastNodeChange ( info )
2020-01-24 22:22:30 -08:00
}
2020-02-17 13:14:53 -08:00
/// My node num
private val myNodeNum get ( ) = myNodeInfo !! . myNodeNum
/// My node ID string
private val myNodeID get ( ) = toNodeID ( myNodeNum )
2020-01-24 22:22:30 -08:00
/// Generate a new mesh packet builder with our node as the sender, and the specified node num
private fun newMeshPacketTo ( idNum : Int ) = MeshPacket . newBuilder ( ) . apply {
2020-02-16 14:22:24 -08:00
if ( myNodeInfo == null )
2020-01-25 12:24:53 -08:00
throw RadioNotConnectedException ( )
2020-02-17 13:14:53 -08:00
from = myNodeNum
2020-01-24 20:35:42 -08:00
to = idNum
}
2020-02-17 15:39:49 -08:00
/ * *
* Generate a new mesh packet builder with our node as the sender , and the specified recipient
*
* If id is null we assume a broadcast message
* /
private fun newMeshPacketTo ( id : String ? ) =
newMeshPacketTo ( if ( id != null ) toNodeNum ( id ) else NODENUM _BROADCAST )
2020-01-24 22:22:30 -08:00
2020-02-17 15:39:49 -08:00
/ * *
* Helper to make it easy to build a subpacket in the proper protobufs
*
* If destId is null we assume a broadcast message
* /
2020-01-25 10:00:57 -08:00
private fun buildMeshPacket (
2020-02-17 15:39:49 -08:00
destId : String ? ,
2020-01-25 10:00:57 -08:00
initFn : MeshProtos . SubPacket . Builder . ( ) -> Unit
) : MeshPacket = newMeshPacketTo ( destId ) . apply {
2020-02-02 18:38:01 -08:00
payload = MeshProtos . SubPacket . newBuilder ( ) . also {
initFn ( it )
2020-01-25 10:00:57 -08:00
} . build ( )
} . build ( )
2020-01-25 06:16:10 -08:00
/// Update our model and resend as needed for a MeshPacket we just received from the radio
private fun handleReceivedData ( fromNum : Int , data : MeshProtos . Data ) {
val bytes = data . payload . toByteArray ( )
val fromId = toNodeID ( fromNum )
/// the sending node ID if possible, else just its number
val fromString = fromId ?: fromId . toString ( )
2020-02-09 05:52:17 -08:00
fun forwardData ( ) {
if ( fromId == null )
warn ( " Ignoring data from $fromNum because we don't yet know its ID " )
else {
debug ( " Received data from $fromId ${bytes.size} " )
broadcastReceivedData ( fromId , bytes , data . typValue )
}
}
2020-01-25 06:16:10 -08:00
when ( data . typValue ) {
2020-02-09 05:52:17 -08:00
MeshProtos . Data . Type . CLEAR _TEXT _VALUE -> {
2020-02-28 14:07:04 -08:00
val text = bytes . toString ( Charset . forName ( " UTF-8 " ) )
debug ( " Received CLEAR_TEXT from $fromString " )
recentReceivedText = TextMessage ( fromString , text )
2020-02-28 14:11:42 -08:00
updateNotification ( )
2020-02-09 05:52:17 -08:00
forwardData ( )
}
2020-01-25 06:16:10 -08:00
MeshProtos . Data . Type . CLEAR _READACK _VALUE ->
warn (
" TODO ignoring CLEAR_READACK from $fromString "
)
MeshProtos . Data . Type . SIGNAL _OPAQUE _VALUE ->
2020-02-09 05:52:17 -08:00
forwardData ( )
2020-01-25 06:16:10 -08:00
else -> TODO ( )
}
2020-03-04 11:16:43 -08:00
2020-03-08 15:22:31 -07:00
GeeksvilleApplication . analytics . track (
" data_receive " ,
DataPair ( " num_bytes " , bytes . size ) ,
DataPair ( " type " , data . typValue )
)
2020-01-25 06:16:10 -08:00
}
2020-01-25 10:00:57 -08:00
/// Update our DB of users based on someone sending out a User subpacket
private fun handleReceivedUser ( fromNum : Int , p : MeshProtos . User ) {
updateNodeInfo ( fromNum ) {
2020-02-25 10:30:10 -08:00
val oldId = it . user ?. id . orEmpty ( )
2020-02-10 15:31:56 -08:00
it . user = MeshUser (
2020-02-25 10:30:10 -08:00
if ( p . id . isNotEmpty ( ) ) p . id else oldId , // If the new update doesn't contain an ID keep our old value
2020-02-10 15:31:56 -08:00
p . longName ,
p . shortName
)
2020-01-25 10:00:57 -08:00
}
}
2020-02-16 14:22:24 -08:00
/// Update our DB of users based on someone sending out a Position subpacket
private fun handleReceivedPosition ( fromNum : Int , p : MeshProtos . Position ) {
updateNodeInfo ( fromNum ) {
it . position = Position (
p . latitude ,
p . longitude ,
2020-02-19 10:53:36 -08:00
p . altitude ,
if ( p . time != 0 ) p . time else it . position ?. time
?: 0 // if this position didn't include time, just keep our old one
2020-02-16 14:22:24 -08:00
)
}
}
2020-03-30 17:35:33 -07:00
/// If packets arrive before we have our node DB, we delay parsing them until the DB is ready
2020-04-04 15:29:16 -07:00
private val earlyReceivedPackets = mutableListOf < MeshPacket > ( )
/// If apps try to send packets when our radio is sleeping, we queue them here instead
private val offlineSentPackets = mutableListOf < MeshPacket > ( )
2020-03-30 17:35:33 -07:00
2020-01-24 22:22:30 -08:00
/// Update our model and resend as needed for a MeshPacket we just received from the radio
private fun handleReceivedMeshPacket ( packet : MeshPacket ) {
2020-03-30 17:35:33 -07:00
if ( haveNodeDB ) {
processReceivedMeshPacket ( packet )
onNodeDBChanged ( )
} else {
2020-04-04 15:29:16 -07:00
earlyReceivedPackets . add ( packet )
logAssert ( earlyReceivedPackets . size < 128 ) // The max should normally be about 32, but if the device is messed up it might try to send forever
2020-03-30 17:35:33 -07:00
}
}
/// Process any packets that showed up too early
private fun processEarlyPackets ( ) {
2020-04-04 15:29:16 -07:00
earlyReceivedPackets . forEach { processReceivedMeshPacket ( it ) }
earlyReceivedPackets . clear ( )
offlineSentPackets . forEach { sendMeshPacket ( it ) }
offlineSentPackets . clear ( )
2020-03-30 17:35:33 -07:00
}
2020-04-04 15:29:16 -07:00
2020-03-30 17:35:33 -07:00
/// Update our model and resend as needed for a MeshPacket we just received from the radio
private fun processReceivedMeshPacket ( packet : MeshPacket ) {
2020-01-24 22:22:30 -08:00
val fromNum = packet . from
// FIXME, perhaps we could learn our node ID by looking at any to packets the radio
// decided to pass through to us (except for broadcast packets)
2020-02-29 13:42:15 -08:00
//val toNum = packet.to
2020-01-24 22:22:30 -08:00
2020-02-02 18:38:01 -08:00
val p = packet . payload
2020-02-09 05:52:17 -08:00
2020-02-19 11:35:16 -08:00
// Update last seen for the node that sent the packet, but also for _our node_ because anytime a packet passes
// through our node on the way to the phone that means that local node is also alive in the mesh
2020-02-19 10:53:36 -08:00
updateNodeInfo ( fromNum ) {
2020-02-19 11:35:16 -08:00
// Update our last seen based on any valid timestamps. If the device didn't provide a timestamp make one
val lastSeen =
if ( packet . rxTime != 0 ) packet . rxTime else currentSecond ( )
2020-02-19 10:53:36 -08:00
it . position = it . position ?. copy ( time = lastSeen )
2020-02-09 05:52:17 -08:00
}
2020-02-19 11:35:16 -08:00
updateNodeInfo ( myNodeNum ) {
it . position = it . position ?. copy ( time = currentSecond ( ) )
}
2020-02-09 05:52:17 -08:00
2020-04-19 09:23:57 -07:00
if ( p . hasPosition ( ) )
handleReceivedPosition ( fromNum , p . position )
2020-02-16 14:22:24 -08:00
2020-04-19 09:23:57 -07:00
if ( p . hasData ( ) )
handleReceivedData ( fromNum , p . data )
2020-02-02 18:38:01 -08:00
2020-04-19 09:23:57 -07:00
if ( p . hasUser ( ) )
handleReceivedUser ( fromNum , p . user )
2020-01-24 22:22:30 -08:00
}
2020-01-24 20:35:42 -08:00
2020-02-19 11:35:16 -08:00
private fun currentSecond ( ) = ( System . currentTimeMillis ( ) / 1000 ) . toInt ( )
2020-04-04 15:29:16 -07:00
2020-02-18 20:19:40 -08:00
/// We are reconnecting to a radio, redownload the full state. This operation might take hundreds of milliseconds
private fun reinitFromRadio ( ) {
// Read the MyNodeInfo object
val myInfo = MeshProtos . MyNodeInfo . parseFrom (
connectedRadio . readMyNode ( )
)
2020-03-12 11:58:10 -07:00
val mi = with ( myInfo ) {
MyNodeInfo ( myNodeNum , hasGps , region , hwModel , firmwareVersion )
}
myNodeInfo = mi
2020-04-04 15:29:16 -07:00
radioConfig = MeshProtos . RadioConfig . parseFrom ( connectedRadio . readRadioConfig ( ) )
2020-03-12 11:58:10 -07:00
/// Track types of devices and firmware versions in use
GeeksvilleApplication . analytics . setUserInfo (
DataPair ( " region " , mi . region ) ,
DataPair ( " firmware " , mi . firmwareVersion ) ,
DataPair ( " has_gps " , mi . hasGPS ) ,
2020-03-24 13:48:00 -07:00
DataPair ( " hw_model " , mi . model ) ,
DataPair ( " dev_error_count " , myInfo . errorCount )
2020-03-12 11:58:10 -07:00
)
2020-02-18 20:19:40 -08:00
2020-03-24 13:48:00 -07:00
if ( myInfo . errorCode != 0 ) {
GeeksvilleApplication . analytics . track (
" dev_error " ,
DataPair ( " code " , myInfo . errorCode ) ,
DataPair ( " address " , myInfo . errorAddress ) ,
// We also include this info, because it is required to correctly decode address from the map file
DataPair ( " firmware " , mi . firmwareVersion ) ,
DataPair ( " hw_model " , mi . model ) ,
DataPair ( " region " , mi . region )
)
}
2020-02-18 20:19:40 -08:00
// Ask for the current node DB
connectedRadio . restartNodeInfo ( )
// read all the infos until we get back null
var infoBytes = connectedRadio . readNodeInfo ( )
while ( infoBytes != null ) {
val info =
MeshProtos . NodeInfo . parseFrom ( infoBytes )
2020-04-12 10:56:45 -07:00
debug ( " Received initial nodeinfo num= ${info.num} , hasUser= ${info.hasUser()} , hasPosition= ${info.hasPosition()} " )
2020-02-18 20:19:40 -08:00
// Just replace/add any entry
updateNodeInfo ( info . num ) {
if ( info . hasUser ( ) )
it . user =
MeshUser (
info . user . id ,
info . user . longName ,
info . user . shortName
)
2020-02-19 11:35:16 -08:00
if ( info . hasPosition ( ) ) {
// For the local node, it might not be able to update its times because it doesn't have a valid GPS reading yet
// so if the info is for _our_ node we always assume time is current
val time =
2020-03-12 11:58:10 -07:00
if ( it . num == mi . myNodeNum ) currentSecond ( ) else info . position . time
2020-02-19 11:35:16 -08:00
2020-02-18 20:19:40 -08:00
it . position = Position (
info . position . latitude ,
info . position . longitude ,
2020-02-19 10:53:36 -08:00
info . position . altitude ,
2020-02-19 11:35:16 -08:00
time
2020-02-18 20:19:40 -08:00
)
2020-02-19 11:35:16 -08:00
}
2020-02-18 20:19:40 -08:00
}
// advance to next
infoBytes = connectedRadio . readNodeInfo ( )
}
2020-02-19 10:53:36 -08:00
2020-03-30 17:35:33 -07:00
haveNodeDB = true // we've done our initial node db initialization
processEarlyPackets ( ) // handle any packets that showed up while we were booting
2020-02-19 10:53:36 -08:00
onNodeDBChanged ( )
2020-02-18 20:19:40 -08:00
}
2020-02-19 10:53:36 -08:00
/// If we just changed our nodedb, we might want to do somethings
private fun onNodeDBChanged ( ) {
2020-02-28 14:11:42 -08:00
updateNotification ( )
2020-02-28 20:09:00 -08:00
2020-02-19 10:53:36 -08:00
// we don't ask for GPS locations from android if our device has a built in GPS
if ( ! myNodeInfo !! . hasGPS ) {
// If we have at least one other person in the mesh, send our GPS position otherwise stop listening to GPS
2020-04-04 14:37:44 -07:00
serviceScope . handledLaunch ( Dispatchers . Main ) {
if ( numOnlineNodes >= 2 )
startLocationRequests ( )
else
stopLocationRequests ( )
}
2020-02-19 10:53:36 -08:00
} else
debug ( " Our radio has a built in GPS, so not reading GPS in phone " )
}
2020-02-04 12:12:29 -08:00
2020-04-04 14:37:44 -07:00
2020-04-04 15:29:16 -07:00
private var sleepTimeout : Job ? = null
2020-02-04 12:12:29 -08:00
/// Called when we gain/lose connection to our radio
2020-04-04 15:29:16 -07:00
private fun onConnectionChanged ( c : ConnectionState ) {
debug ( " onConnectionChanged= $c " )
/// Perform all the steps needed once we start waiting for device sleep to complete
fun startDeviceSleep ( ) {
// lost radio connection, therefore no need to keep listening to GPS
stopLocationRequests ( )
// Have our timeout fire in the approprate number of seconds
sleepTimeout = serviceScope . handledLaunch {
try {
// If we have a valid timeout, wait that long (+30 seconds) otherwise, just wait 30 seconds
val timeout = ( radioConfig ?. preferences ?. lsSecs ?: 0 ) + 30
debug ( " Waiting for sleeping device, timeout= $timeout secs " )
delay ( timeout * 1000L )
warn ( " Device timeout out, setting disconnected " )
onConnectionChanged ( ConnectionState . DISCONNECTED )
} catch ( ex : CancellationException ) {
debug ( " device sleep timeout cancelled " )
}
}
}
fun startDisconnect ( ) {
GeeksvilleApplication . analytics . track (
" mesh_disconnect " ,
DataPair ( " num_nodes " , numNodes ) ,
DataPair ( " num_online " , numOnlineNodes )
)
}
fun startConnect ( ) {
2020-02-04 12:12:29 -08:00
// Do our startup init
2020-02-17 18:46:20 -08:00
try {
2020-02-18 20:19:40 -08:00
reinitFromRadio ( )
2020-02-25 09:28:47 -08:00
2020-03-12 11:58:10 -07:00
val radioModel = DataPair ( " radio_model " , myNodeInfo ?. model ?: " unknown " )
2020-02-25 09:28:47 -08:00
GeeksvilleApplication . analytics . track (
" mesh_connect " ,
DataPair ( " num_nodes " , numNodes ) ,
2020-03-09 12:51:54 -07:00
DataPair ( " num_online " , numOnlineNodes ) ,
radioModel
2020-02-25 09:28:47 -08:00
)
2020-03-08 15:22:31 -07:00
// Once someone connects to hardware start tracking the approximate number of nodes in their mesh
// this allows us to collect stats on what typical mesh size is and to tell difference between users who just
// downloaded the app, vs has connected it to some hardware.
2020-03-09 12:51:54 -07:00
GeeksvilleApplication . analytics . setUserInfo (
DataPair ( " num_nodes " , numNodes ) ,
radioModel
)
2020-02-17 18:46:20 -08:00
} catch ( ex : RemoteException ) {
// It seems that when the ESP32 goes offline it can briefly come back for a 100ms ish which
// causes the phone to try and reconnect. If we fail downloading our initial radio state we don't want to
// claim we have a valid connection still
2020-04-04 15:29:16 -07:00
connectionState = ConnectionState . DEVICE _SLEEP
startDeviceSleep ( )
2020-02-17 18:46:20 -08:00
throw ex ; // Important to rethrow so that we don't tell the app all is well
2020-02-04 12:12:29 -08:00
}
2020-04-04 15:29:16 -07:00
}
2020-02-25 09:28:47 -08:00
2020-04-04 15:29:16 -07:00
// Cancel any existing timeouts
sleepTimeout ?. let {
it . cancel ( )
sleepTimeout = null
}
connectionState = c
when ( c ) {
ConnectionState . CONNECTED ->
startConnect ( )
ConnectionState . DEVICE _SLEEP ->
startDeviceSleep ( )
ConnectionState . DISCONNECTED ->
startDisconnect ( )
2020-02-04 12:12:29 -08:00
}
2020-02-28 13:53:16 -08:00
2020-04-04 15:29:16 -07:00
// broadcast an intent with our new connection state
val intent = Intent ( ACTION _MESH _CONNECTED )
intent . putExtra (
EXTRA _CONNECTED ,
connectionState . toString ( )
)
explicitBroadcast ( intent )
// Update the android notification in the status bar
2020-02-28 13:53:16 -08:00
updateNotification ( )
2020-01-25 06:16:10 -08:00
}
2020-01-24 17:05:55 -08:00
/ * *
* Receives messages from our BT radio service and processes them to update our model
* and send to clients as needed .
* /
private val radioInterfaceReceiver = object : BroadcastReceiver ( ) {
2020-02-04 13:24:04 -08:00
// Important to never throw exceptions out of onReceive
override fun onReceive ( context : Context , intent : Intent ) = exceptionReporter {
2020-04-04 14:37:44 -07:00
serviceScope . handledLaunch {
debug ( " Received broadcast ${intent.action} " )
when ( intent . action ) {
RadioInterfaceService . RADIO _CONNECTED _ACTION -> {
try {
2020-04-04 15:29:16 -07:00
onConnectionChanged (
if ( intent . getBooleanExtra ( EXTRA _CONNECTED , false ) )
ConnectionState . CONNECTED
else
ConnectionState . DEVICE _SLEEP
)
2020-04-04 14:37:44 -07:00
} catch ( ex : RemoteException ) {
// This can happen sometimes (especially if the device is slowly dying due to killing power, don't report to crashlytics
warn ( " Abandoning reconnect attempt, due to errors during init: ${ex.message} " )
}
2020-02-17 20:00:11 -08:00
}
2020-02-04 12:12:29 -08:00
2020-04-04 14:37:44 -07:00
RadioInterfaceService . RECEIVE _FROMRADIO _ACTION -> {
val proto =
MeshProtos . FromRadio . parseFrom (
intent . getByteArrayExtra (
EXTRA _PAYLOAD
) !!
)
info ( " Received from radio service: ${proto.toOneLineString()} " )
when ( proto . variantCase . number ) {
MeshProtos . FromRadio . PACKET _FIELD _NUMBER -> handleReceivedMeshPacket (
proto . packet
)
2020-02-04 12:12:29 -08:00
2020-04-04 14:37:44 -07:00
else -> TODO ( " Unexpected FromRadio variant " )
}
2020-02-04 12:12:29 -08:00
}
2020-04-04 14:37:44 -07:00
else -> TODO ( " Unexpected radio interface broadcast " )
}
2020-01-24 22:22:30 -08:00
}
2020-01-24 17:05:55 -08:00
}
}
2020-02-16 14:22:24 -08:00
/// Send a position (typically from our built in GPS) into the mesh
2020-02-19 18:51:59 -08:00
private fun sendPosition (
lat : Double ,
lon : Double ,
alt : Int ,
destNum : Int = NODENUM _BROADCAST ,
wantResponse : Boolean = false
) {
debug ( " Sending our position to= $destNum lat= $lat , lon= $lon , alt= $alt " )
2020-02-16 14:22:24 -08:00
val position = MeshProtos . Position . newBuilder ( ) . also {
it . latitude = lat
it . longitude = lon
it . altitude = alt
2020-02-19 11:35:16 -08:00
it . time = currentSecond ( ) // Include our current timestamp
2020-02-16 14:22:24 -08:00
} . build ( )
// encapsulate our payload in the proper protobufs and fire it off
val packet = newMeshPacketTo ( destNum )
packet . payload = MeshProtos . SubPacket . newBuilder ( ) . also {
it . position = position
2020-02-19 18:51:59 -08:00
it . wantResponse = wantResponse
2020-02-16 14:22:24 -08:00
} . build ( )
// Also update our own map for our nodenum, by handling the packet just like packets from other users
handleReceivedPosition ( myNodeInfo !! . myNodeNum , position )
// send the packet into the mesh
sendToRadio ( ToRadio . newBuilder ( ) . apply {
this . packet = packet . build ( )
} )
}
2020-04-04 15:29:16 -07:00
/ * *
* Send a mesh packet to the radio , if the radio is not currently connected this function will throw NotConnectedException
* /
private fun sendMeshPacket ( packet : MeshPacket ) {
sendToRadio ( ToRadio . newBuilder ( ) . apply {
this . packet = packet
} )
}
2020-01-22 21:25:31 -08:00
private val binder = object : IMeshService . Stub ( ) {
2020-01-25 10:00:57 -08:00
// Note: bound methods don't get properly exception caught/logged, so do that with a wrapper
// per https://blog.classycode.com/dealing-with-exceptions-in-aidl-9ba904c6d63
2020-01-26 11:33:51 -08:00
override fun subscribeReceiver ( packageName : String , receiverName : String ) =
toRemoteExceptions {
clientPackages [ receiverName ] = packageName
}
2020-01-22 21:25:31 -08:00
2020-02-17 13:14:53 -08:00
override fun getMyId ( ) = toRemoteExceptions { myNodeID }
2020-02-14 04:41:20 -08:00
override fun setOwner ( myId : String ? , longName : String , shortName : String ) =
2020-01-26 10:44:42 -08:00
toRemoteExceptions {
2020-02-14 04:41:20 -08:00
debug ( " SetOwner $myId : $longName : $shortName " )
2020-01-25 10:00:57 -08:00
val user = MeshProtos . User . newBuilder ( ) . also {
2020-02-14 04:41:20 -08:00
if ( myId != null ) // Only set the id if it was provided
it . id = myId
2020-01-25 10:00:57 -08:00
it . longName = longName
it . shortName = shortName
2020-01-24 20:35:42 -08:00
} . build ( )
2020-01-25 10:00:57 -08:00
// Also update our own map for our nodenum, by handling the packet just like packets from other users
2020-02-16 14:22:24 -08:00
if ( myNodeInfo != null ) {
handleReceivedUser ( myNodeInfo !! . myNodeNum , user )
2020-01-25 10:00:57 -08:00
}
2020-02-04 12:12:29 -08:00
// set my owner info
connectedRadio . writeOwner ( user . toByteArray ( ) )
2020-01-25 10:00:57 -08:00
}
2020-04-04 15:29:16 -07:00
override fun sendData ( destId : String ? , payloadIn : ByteArray , typ : Int ) : Boolean =
2020-01-26 10:44:42 -08:00
toRemoteExceptions {
2020-04-04 15:29:16 -07:00
info ( " sendData dest= $destId <- ${payloadIn.size} bytes (connectionState= $connectionState ) " )
2020-01-25 10:00:57 -08:00
// encapsulate our payload in the proper protobufs and fire it off
val packet = buildMeshPacket ( destId ) {
data = MeshProtos . Data . newBuilder ( ) . also {
2020-02-17 18:46:20 -08:00
it . typ = MeshProtos . Data . Type . forNumber ( typ )
2020-01-25 10:00:57 -08:00
it . payload = ByteString . copyFrom ( payloadIn )
} . build ( )
}
2020-04-04 15:29:16 -07:00
// If radio is sleeping, queue the packet
when ( connectionState ) {
ConnectionState . DEVICE _SLEEP ->
offlineSentPackets . add ( packet )
else ->
sendMeshPacket ( packet )
}
2020-03-04 11:16:43 -08:00
2020-03-08 15:22:31 -07:00
GeeksvilleApplication . analytics . track (
" data_send " ,
DataPair ( " num_bytes " , payloadIn . size ) ,
DataPair ( " type " , typ )
)
2020-04-04 15:29:16 -07:00
connectionState == ConnectionState . CONNECTED
2020-01-25 10:00:57 -08:00
}
2020-01-22 21:25:31 -08:00
2020-02-11 19:19:56 -08:00
override fun getRadioConfig ( ) : ByteArray = toRemoteExceptions {
2020-04-04 15:29:16 -07:00
this @MeshService . radioConfig ?. toByteArray ( ) ?: throw RadioNotConnectedException ( )
2020-02-11 19:19:56 -08:00
}
override fun setRadioConfig ( payload : ByteArray ) = toRemoteExceptions {
2020-04-04 15:29:16 -07:00
// Update our device
2020-02-11 19:19:56 -08:00
connectedRadio . writeRadioConfig ( payload )
2020-04-04 15:29:16 -07:00
// Update our cached copy
this @MeshService . radioConfig = MeshProtos . RadioConfig . parseFrom ( payload )
2020-02-11 19:19:56 -08:00
}
2020-02-10 17:05:51 -08:00
override fun getNodes ( ) : Array < NodeInfo > = toRemoteExceptions {
val r = nodeDBbyID . values . toTypedArray ( )
2020-01-24 20:46:29 -08:00
info ( " in getOnline, count= ${r.size} " )
2020-01-24 20:35:42 -08:00
// return arrayOf("+16508675309")
2020-01-25 10:00:57 -08:00
r
2020-01-22 21:25:31 -08:00
}
2020-04-04 15:29:16 -07:00
override fun connectionState ( ) : String = toRemoteExceptions {
val r = this @MeshService . connectionState
info ( " in connectionState= $r " )
r . toString ( )
2020-01-22 21:25:31 -08:00
}
}
}