2020-01-22 21:46:41 -08:00
package com.geeksville.mesh
2020-01-21 09:37:39 -08:00
2020-01-21 10:39:01 -08:00
import android.bluetooth.*
2020-01-21 13:12:01 -08:00
import android.bluetooth.le.*
2020-01-21 09:37:39 -08:00
import android.content.Context
import android.content.Intent
import android.os.Handler
2020-01-21 13:12:01 -08:00
import android.os.ParcelUuid
2020-01-21 09:37:39 -08:00
import android.os.SystemClock
import android.widget.Toast
import androidx.core.app.JobIntentService
2020-01-22 14:27:22 -08:00
import com.geeksville.android.Logging
2020-01-23 12:56:06 -08:00
import java.io.IOException
2020-01-21 12:07:03 -08:00
import java.io.InputStream
2020-01-21 10:39:01 -08:00
import java.util.*
2020-01-23 09:19:53 -08:00
import java.util.zip.CRC32
2020-01-21 09:37:39 -08:00
/ * *
2020-01-21 10:39:01 -08:00
* typical flow
*
* startScan
* startUpdate
*
* stopScan
*
* FIXME - if we don ' t find a device stop our scan
* FIXME - broadcast when we found devices , made progress sending blocks or when the update is complete
* FIXME - make the user decide to start an update on a particular device
2020-01-21 09:37:39 -08:00
* /
2020-01-23 23:05:15 -08:00
class SoftwareUpdateService : JobIntentService ( ) , Logging {
2020-01-21 10:39:01 -08:00
private val bluetoothAdapter : BluetoothAdapter by lazy ( LazyThreadSafetyMode . NONE ) {
val bluetoothManager = getSystemService ( Context . BLUETOOTH _SERVICE ) as BluetoothManager
bluetoothManager . adapter !!
}
2020-01-23 21:58:23 -08:00
lateinit var device : BluetoothDevice
2020-01-23 10:39:54 -08:00
2020-01-21 10:39:01 -08:00
fun startUpdate ( ) {
2020-01-23 09:04:06 -08:00
info ( " starting update " )
2020-01-21 12:07:03 -08:00
2020-01-23 21:58:23 -08:00
val sync = SyncBluetoothDevice ( this @SoftwareUpdateService , device )
val firmwareStream = assets . open ( " firmware.bin " )
val firmwareCrc = CRC32 ( )
var firmwareNumSent = 0
val firmwareSize = firmwareStream . available ( )
2020-01-21 10:39:01 -08:00
2020-01-23 21:58:23 -08:00
sync . connect ( )
sync . discoverServices ( ) // Get our services
2020-01-23 10:39:54 -08:00
2020-01-23 21:58:23 -08:00
val service = sync . gatt . services . find { it . uuid == SW _UPDATE _UUID } !!
2020-01-21 12:07:03 -08:00
2020-01-23 21:58:23 -08:00
val totalSizeDesc = service . getCharacteristic ( SW _UPDATE _TOTALSIZE _CHARACTER )
val dataDesc = service . getCharacteristic ( SW _UPDATE _DATA _CHARACTER )
val crc32Desc = service . getCharacteristic ( SW _UPDATE _CRC32 _CHARACTER )
val updateResultDesc = service . getCharacteristic ( SW _UPDATE _RESULT _CHARACTER )
2020-01-21 10:39:01 -08:00
2020-01-23 21:58:23 -08:00
// we begin by setting our MTU size as high as it can go
sync . requestMtu ( 512 )
// Start the update by writing the # of bytes in the image
logAssert (
totalSizeDesc . setValue (
firmwareSize ,
BluetoothGattCharacteristic . FORMAT _UINT32 ,
0
)
)
sync . writeCharacteristic ( totalSizeDesc )
// Our write completed, queue up a readback
val totalSizeReadback = sync . readCharacteristic ( totalSizeDesc )
. getIntValue ( BluetoothGattCharacteristic . FORMAT _UINT32 , 0 )
logAssert ( totalSizeReadback != 0 ) // FIXME - handle this case
// Send all the blocks
while ( firmwareNumSent < firmwareSize ) {
info ( " sending block ${firmwareNumSent * 100 / firmwareSize} % " )
var blockSize = 512 - 3 // Max size MTU excluding framing
if ( blockSize > firmwareStream . available ( ) )
blockSize = firmwareStream . available ( )
val buffer = ByteArray ( blockSize )
// slightly expensive to keep reallocing this buffer, but whatever
logAssert ( firmwareStream . read ( buffer ) == blockSize )
firmwareCrc . update ( buffer )
// updateGatt.beginReliableWrite()
dataDesc . value = buffer
sync . writeCharacteristic ( dataDesc )
firmwareNumSent += blockSize
}
2020-01-21 12:07:03 -08:00
2020-01-23 09:19:53 -08:00
// We have finished sending all our blocks, so post the CRC so our state machine can advance
2020-01-23 10:39:54 -08:00
val c = firmwareCrc . value
info ( " Sent all blocks, crc is $c " )
logAssert ( crc32Desc . setValue ( c . toInt ( ) , BluetoothGattCharacteristic . FORMAT _UINT32 , 0 ) )
2020-01-23 21:58:23 -08:00
sync . writeCharacteristic ( crc32Desc )
2020-01-23 09:04:06 -08:00
2020-01-23 21:58:23 -08:00
// we just read the update result if !0 we have an error
val updateResult =
sync . readCharacteristic ( updateResultDesc )
. getIntValue ( BluetoothGattCharacteristic . FORMAT _UINT8 , 0 )
logAssert ( updateResult == 0 ) // FIXME - handle this case
2020-01-23 09:04:06 -08:00
2020-01-23 21:58:23 -08:00
// FIXME perhaps ask device to reboot
2020-01-23 09:04:06 -08:00
}
2020-01-23 21:58:23 -08:00
2020-01-21 13:12:01 -08:00
private val scanCallback = object : ScanCallback ( ) {
override fun onScanFailed ( errorCode : Int ) {
throw NotImplementedError ( )
}
2020-01-21 18:26:28 -08:00
override fun onBatchScanResults ( results : MutableList < ScanResult > ? ) {
throw NotImplementedError ( )
}
2020-01-21 13:12:01 -08:00
// For each device that appears in our scan, ask for its GATT, when the gatt arrives,
// check if it is an eligable device and store it in our list of candidates
// if that device later disconnects remove it as a candidate
override fun onScanResult ( callbackType : Int , result : ScanResult ) {
2020-01-23 09:04:06 -08:00
info ( " onScanResult " )
2020-01-21 13:12:01 -08:00
// We don't need any more results now
bluetoothAdapter . bluetoothLeScanner . stopScan ( this )
2020-01-23 21:58:23 -08:00
device = result . device
2020-01-21 10:39:01 -08:00
}
}
2020-01-23 09:04:06 -08:00
// Until my race condition with scanning is fixed
fun connectToTestDevice ( ) {
2020-01-23 21:58:23 -08:00
device = bluetoothAdapter . getRemoteDevice ( " B4:E6:2D:EA:32:B7 " )
2020-01-23 09:04:06 -08:00
}
2020-01-21 13:12:01 -08:00
2020-01-21 10:39:01 -08:00
private fun scanLeDevice ( enable : Boolean ) {
when ( enable ) {
true -> {
// Stops scanning after a pre-defined scan period.
/ * handler . postDelayed ( {
mScanning = false
bluetoothAdapter . stopLeScan ( leScanCallback )
} , SCAN _PERIOD )
mScanning = true * /
2020-01-21 13:12:01 -08:00
val scanner = bluetoothAdapter . bluetoothLeScanner
// filter and only accept devices that have a sw update service
val filter = ScanFilter . Builder ( ) . setServiceUuid ( ParcelUuid ( SW _UPDATE _UUID ) ) . build ( )
2020-01-21 18:26:28 -08:00
/ * ScanSettings . CALLBACK _TYPE _FIRST _MATCH seems to trigger a bug returning an error of
SCAN _FAILED _OUT _OF _HARDWARE _RESOURCES ( error # 5 )
* /
2020-01-22 16:45:27 -08:00
val settings =
ScanSettings . Builder ( ) . setScanMode ( ScanSettings . SCAN _MODE _LOW _LATENCY ) .
// setMatchMode(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT).
// setCallbackType(ScanSettings.CALLBACK_TYPE_FIRST_MATCH).
build ( )
2020-01-21 13:12:01 -08:00
scanner . startScan ( listOf ( filter ) , settings , scanCallback )
2020-01-21 10:39:01 -08:00
}
else -> {
// mScanning = false
2020-01-21 13:12:01 -08:00
// bluetoothAdapter.stopLeScan(leScanCallback)
2020-01-21 10:39:01 -08:00
}
}
}
2020-01-21 09:37:39 -08:00
override fun onHandleWork ( intent : Intent ) { // We have received work to do. The system or framework is already
// holding a wake lock for us at this point, so we can just go.
2020-01-23 10:39:54 -08:00
debug ( " Executing work: $intent " )
2020-01-22 16:45:27 -08:00
when ( intent . action ) {
2020-01-23 21:58:23 -08:00
scanDevicesIntent . action -> scanLeDevice ( true )
startUpdateIntent . action -> {
connectToTestDevice ( ) // FIXME, pass in as an intent arg instead
startUpdate ( )
}
2020-01-22 14:27:22 -08:00
else -> logAssert ( false )
2020-01-21 12:07:03 -08:00
}
2020-01-23 10:39:54 -08:00
debug (
2020-01-22 16:45:27 -08:00
" Completed service @ " + SystemClock . elapsedRealtime ( )
2020-01-21 09:37:39 -08:00
)
}
override fun onDestroy ( ) {
super . onDestroy ( )
2020-01-23 10:39:54 -08:00
// toast("All work complete")
2020-01-21 09:37:39 -08:00
}
val mHandler = Handler ( )
// Helper for showing tests
fun toast ( text : CharSequence ? ) {
mHandler . post {
2020-01-21 10:39:01 -08:00
Toast . makeText ( this @SoftwareUpdateService , text , Toast . LENGTH _SHORT ) . show ( )
2020-01-21 09:37:39 -08:00
}
}
companion object {
/ * *
* Unique job ID for this service . Must be the same for all work .
* /
const val JOB _ID = 1000
2020-01-22 21:46:41 -08:00
val scanDevicesIntent = Intent ( " com.geeksville.com.geeeksville.mesh.SCAN_DEVICES " )
val startUpdateIntent = Intent ( " com.geeksville.com.geeeksville.mesh.START_UPDATE " )
2020-01-21 10:39:01 -08:00
private const val SCAN _PERIOD : Long = 10000
//const val ACTION_GATT_CONNECTED = "com.example.bluetooth.le.ACTION_GATT_CONNECTED"
//const val ACTION_GATT_DISCONNECTED = "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED"
private val TAG =
MainActivity :: class . java . simpleName // FIXME - use my logging class instead
private val SW _UPDATE _UUID = UUID . fromString ( " cb0b9a0b-a84c-4c0d-bdbb-442e3144ee30 " )
private val SW _UPDATE _TOTALSIZE _CHARACTER =
UUID . fromString ( " e74dd9c0-a301-4a6f-95a1-f0e1dbea8e1e " ) // write|read total image size, 32 bit, write this first, then read read back to see if it was acceptable (0 mean not accepted)
private val SW _UPDATE _DATA _CHARACTER =
UUID . fromString ( " e272ebac-d463-4b98-bc84-5cc1a39ee517 " ) // write data, variable sized, recommended 512 bytes, write one for each block of file
private val SW _UPDATE _CRC32 _CHARACTER =
UUID . fromString ( " 4826129c-c22a-43a3-b066-ce8f0d5bacc6 " ) // write crc32, write last - writing this will complete the OTA operation, now you can read result
private val SW _UPDATE _RESULT _CHARACTER =
UUID . fromString ( " 5e134862-7411-4424-ac4a-210937432c77 " ) // read|notify result code, readable but will notify when the OTA operation completes
2020-01-21 09:37:39 -08:00
/ * *
* Convenience method for enqueuing work in to this service .
* /
fun enqueueWork ( context : Context , work : Intent ) {
enqueueWork (
context ,
2020-01-21 10:39:01 -08:00
SoftwareUpdateService :: class . java , JOB _ID , work
2020-01-21 09:37:39 -08:00
)
}
}
}