forked from Blendman974/faceclaw
G1 support: Flashing within the Android app
This commit is contained in:
1 parent
345ba36c33
commit
38c52ebc31
37 files changed
+2819
-32
No files matched your search
@@ -0,0 +1,467 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import kotlin.concurrent.Volatile
|
||||
import kotlin.jvm.JvmField
|
||||
|
||||
class G1FlashTimings(
|
||||
@JvmField val connectTimeoutMs: Int = ConnectionOptions.CONNECT_TIMEOUT_MS,
|
||||
@JvmField val servicesTimeoutMs: Int = ConnectionOptions.SERVICES_TIMEOUT_MS,
|
||||
@JvmField val descriptorTimeoutMs: Int = ConnectionOptions.DESCRIPTOR_TIMEOUT_MS,
|
||||
@JvmField val writeTimeoutMs: Int = ConnectionOptions.WRITE_TIMEOUT_MS,
|
||||
/** The OS may be showing its pairing dialog. */
|
||||
@JvmField val pairingMs: Int = 60_000,
|
||||
@JvmField val retryDelayMs: Int = 2_000,
|
||||
@JvmField val controlReplyMs: Int = 1_500,
|
||||
@JvmField val controlTries: Int = 4,
|
||||
/** The first chunk of an upload waits for the arm to erase its slot. */
|
||||
@JvmField val uploadReplyMs: Int = 30_000,
|
||||
@JvmField val smpReplyMs: Int = 20_000,
|
||||
/** The arm may go down before its reply leaves. */
|
||||
@JvmField val resetReplyMs: Int = 5_000,
|
||||
@JvmField val heartbeatMs: Int = 8_000,
|
||||
@JvmField val pollMs: Int = 200,
|
||||
@JvmField val uploadRetries: Int = 40,
|
||||
)
|
||||
|
||||
/**
|
||||
* Installs an MCUboot image on one G1 arm through MCUmgr SMP, or asks an arm what it runs; a port of scouter_kit's
|
||||
* g1_firmware/flash.py. The caller handles one arm at a time, left first, and looks for the arm again afterwards: it
|
||||
* restarts, and coming off Even's firmware it has a new address.
|
||||
*
|
||||
* Nothing changes on the arm until the confirm, which comes only after the arm's image list shows that its second slot
|
||||
* holds exactly this image. MCUboot then overwrites the running firmware with no way back. [run] blocks; the worker thread
|
||||
* is the host's.
|
||||
*/
|
||||
class G1ArmFlashFlow(
|
||||
private val link: StockLink,
|
||||
private val address: String,
|
||||
private val side: String,
|
||||
private val firmwarePath: String,
|
||||
private val mode: Mode,
|
||||
/** How long to keep trying to reach the arm and pair with it. */
|
||||
private val connectWindowMs: Int,
|
||||
private val listener: FaceclawFirmwareFlasherListener,
|
||||
private val timings: G1FlashTimings = G1FlashTimings(),
|
||||
platform: ProtocolPlatform = protocolPlatform(),
|
||||
private val readImage: (String) -> ByteArray = ::readFileData,
|
||||
) : StockLinkListener {
|
||||
enum class Mode {
|
||||
/** The arm runs Even's firmware. */
|
||||
STOCK,
|
||||
/** The arm runs g1v0: it answers what it runs, and an arm that already has this version is left alone. */
|
||||
UPDATE,
|
||||
/** Only say what the arm runs, and pair with it. */
|
||||
PROBE,
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val TAG = "FaceclawG1Flash"
|
||||
private const val MIN_BATTERY_PERCENT = 30
|
||||
|
||||
fun mode(name: String): Mode = when (name) {
|
||||
"stock" -> Mode.STOCK
|
||||
"update" -> Mode.UPDATE
|
||||
"probe" -> Mode.PROBE
|
||||
else -> throw IllegalArgumentException("unknown mode $name")
|
||||
}
|
||||
}
|
||||
|
||||
private class LinkLostException(message: String) : Exception(message)
|
||||
|
||||
/** The arm has no g1v0 service. */
|
||||
private class NotG1v0Exception : Exception("this arm doesn't run g1v0")
|
||||
|
||||
private val platform = platform
|
||||
private val lock = platform.createLock()
|
||||
private val sleeper = InterruptibleSleep(platform)
|
||||
private val assembler = G1Smp.Assembler()
|
||||
|
||||
private var smpSeq = -1
|
||||
private var smpReply: Map<*, *>? = null
|
||||
private var smpLatch: Latch? = null
|
||||
private var nextSmpSeq = 0
|
||||
|
||||
private var controlTag = -1
|
||||
private var controlReply: G1Protocol.Reply? = null
|
||||
private var controlLatch: Latch? = null
|
||||
private var nextControlTag = 0
|
||||
|
||||
private var linkLost = false
|
||||
private var heartbeats = 0
|
||||
private var nextHeartbeatAtMs = 0L
|
||||
|
||||
@Volatile
|
||||
private var cancelled = false
|
||||
|
||||
fun cancel() {
|
||||
cancelled = true
|
||||
lock.withLock {
|
||||
smpLatch?.countDown()
|
||||
controlLatch?.countDown()
|
||||
}
|
||||
sleeper.interrupt()
|
||||
}
|
||||
|
||||
fun run() {
|
||||
link.setListener(this)
|
||||
try {
|
||||
if (mode == Mode.PROBE) probe() else install()
|
||||
} catch (e: Exception) {
|
||||
val message = if (cancelled) "Cancelled." else StockLinkSession.messageOf(e)
|
||||
log("failed: $message")
|
||||
listener.onState("error", message)
|
||||
listener.onComplete(false, message)
|
||||
} finally {
|
||||
quietly { link.disconnect(address) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun probe() {
|
||||
listener.onState("connecting", side)
|
||||
try {
|
||||
bringUp()
|
||||
} catch (e: NotG1v0Exception) {
|
||||
listener.onComplete(true, """{"firmware":"stock"}""")
|
||||
return
|
||||
}
|
||||
listener.onState("checking", side)
|
||||
val hello = hello()
|
||||
listener.onComplete(true, """{"firmware":"g1v0","version":"${hello.version}","safeMode":${hello.safeMode},"inCase":${hello.inCase},"battery":${batteryPercent()}}""")
|
||||
}
|
||||
|
||||
private fun install() {
|
||||
listener.onState("validating", side)
|
||||
val image = try {
|
||||
readImage(firmwarePath)
|
||||
} catch (e: Exception) {
|
||||
throw IllegalStateException("could not read the firmware: " + StockLinkSession.messageOf(e), e)
|
||||
}
|
||||
val version = G1Smp.imageVersion(image)
|
||||
val hash = G1Smp.imageHash(image)
|
||||
log("image $version, ${image.size} bytes, hash ${BinaryEncoding.bytesToHex(hash.copyOf(8))}")
|
||||
|
||||
listener.onState("connecting", side)
|
||||
bringUp()
|
||||
if (mode == Mode.UPDATE) {
|
||||
listener.onState("checking", side)
|
||||
val hello = hello()
|
||||
log("runs g1v0 ${hello.version}, safe mode ${hello.safeMode}, in the case ${hello.inCase}, encrypted ${hello.encrypted}")
|
||||
if (hello.version == version && !hello.safeMode) {
|
||||
listener.onComplete(true, """{"flashed":false,"version":"$version"}""")
|
||||
return
|
||||
}
|
||||
val battery = batteryPercent()
|
||||
if (battery != null && battery < MIN_BATTERY_PERCENT) {
|
||||
throw IllegalStateException("The $side arm's battery is at $battery%, too low to install safely. " +
|
||||
"Charge both arms to at least $MIN_BATTERY_PERCENT% in the case, then try again.")
|
||||
}
|
||||
}
|
||||
|
||||
val slots = retrying { images() }
|
||||
for (slot in slots) log(slot.toString())
|
||||
listener.onState("flashing", side)
|
||||
if (holdsImage(slots, hash)) {
|
||||
log("the second slot already holds this image")
|
||||
listener.onProgress(side, 1, 1, image.size, image.size, image.size.toLong(), image.size.toLong())
|
||||
} else {
|
||||
val startedAt = now()
|
||||
upload(image)
|
||||
log("uploaded in ${(now() - startedAt) / 1000} s")
|
||||
}
|
||||
if (!holdsImage(retrying { images() }, hash)) {
|
||||
throw IllegalStateException("The $side arm's second slot doesn't hold the image after the upload. Nothing was installed.")
|
||||
}
|
||||
throwIfCancelled()
|
||||
|
||||
listener.onState("committing", side)
|
||||
val confirm = smp(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, G1Smp.CMD_IMAGE_STATE, G1Smp.confirmRequest(hash), timings.smpReplyMs)
|
||||
val code = G1Smp.replyCode(confirm)
|
||||
if (code != 0) throw IllegalStateException("The $side arm refused the image (error $code). Nothing was installed.")
|
||||
log("confirmed: MCUboot installs it at the next boot")
|
||||
try {
|
||||
smp(G1Smp.OP_WRITE, G1Smp.GROUP_OS, G1Smp.CMD_OS_RESET, emptyMap(), timings.resetReplyMs)
|
||||
} catch (e: StockTimeoutException) {
|
||||
log("no answer to the reset")
|
||||
} catch (e: LinkLostException) {
|
||||
log("the link went down with the reset")
|
||||
}
|
||||
listener.onState("rebooting", side)
|
||||
listener.onComplete(true, """{"flashed":true,"version":"$version"}""")
|
||||
}
|
||||
|
||||
private fun holdsImage(slots: List<G1Smp.Slot>, hash: ByteArray): Boolean =
|
||||
slots.any { it.image == 0 && it.slot == 1 && it.hash.contentEquals(hash) }
|
||||
|
||||
private fun images(): List<G1Smp.Slot> =
|
||||
G1Smp.parseSlots(smp(G1Smp.OP_READ, G1Smp.GROUP_IMAGE, G1Smp.CMD_IMAGE_STATE, emptyMap(), timings.smpReplyMs))
|
||||
|
||||
/** MCUmgr answers each chunk with the offset it wants next, so an upload resumes after a lost link. */
|
||||
private fun upload(image: ByteArray) {
|
||||
val fileSha = sha256(image)
|
||||
var offset = 0
|
||||
var failures = 0
|
||||
while (offset < image.size) {
|
||||
throwIfCancelled()
|
||||
val reply = try {
|
||||
smp(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, G1Smp.CMD_IMAGE_UPLOAD, G1Smp.uploadRequest(image, offset, fileSha), timings.uploadReplyMs)
|
||||
} catch (e: Exception) {
|
||||
if (e !is StockTimeoutException && e !is LinkLostException) throw e
|
||||
failures++
|
||||
if (failures > timings.uploadRetries) throw e
|
||||
log("chunk at $offset failed (${e.message}), trying again")
|
||||
reconnectIfNeeded()
|
||||
continue
|
||||
}
|
||||
val code = G1Smp.replyCode(reply)
|
||||
val next = G1Smp.replyOffset(reply)
|
||||
if (code != 0 || next == null || next < 0 || next > image.size) {
|
||||
throw IllegalStateException("The $side arm refused the upload at $offset (error $code). Nothing was installed.")
|
||||
}
|
||||
offset = next
|
||||
listener.onProgress(side, 1, 1, offset, image.size, offset.toLong(), image.size.toLong())
|
||||
}
|
||||
}
|
||||
|
||||
private fun <T> retrying(request: () -> T): T {
|
||||
var attempt = 0
|
||||
while (true) {
|
||||
try {
|
||||
return request()
|
||||
} catch (e: Exception) {
|
||||
if (e !is StockTimeoutException && e !is LinkLostException) throw e
|
||||
attempt++
|
||||
if (attempt >= 10) throw e
|
||||
log("request failed (${e.message}), trying again")
|
||||
reconnectIfNeeded()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun reconnectIfNeeded() {
|
||||
throwIfCancelled()
|
||||
lock.withLock { assembler.reset() }
|
||||
if (!link.isConnected(address)) bringUp()
|
||||
}
|
||||
|
||||
// ---- the link ------------------------------------------------------------
|
||||
|
||||
private fun bringUp() {
|
||||
val deadline = now() + connectWindowMs
|
||||
var attempt = 0
|
||||
while (true) {
|
||||
throwIfCancelled()
|
||||
attempt++
|
||||
val failure = try {
|
||||
connectOnce()
|
||||
log("connected (attempt $attempt)")
|
||||
return
|
||||
} catch (e: NotG1v0Exception) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
StockLinkSession.messageOf(e)
|
||||
}
|
||||
log("connect attempt $attempt failed: $failure")
|
||||
quietly { link.disconnect(address) }
|
||||
if (now() >= deadline) {
|
||||
throw IllegalStateException("Couldn't reach the $side arm: $failure." + if (mode == Mode.STOCK) {
|
||||
" If this phone was paired with these glasses before, remove them from its Bluetooth settings and try again."
|
||||
} else {
|
||||
""
|
||||
})
|
||||
}
|
||||
sleeper.sleep(timings.retryDelayMs.toLong())
|
||||
}
|
||||
}
|
||||
|
||||
private fun connectOnce() {
|
||||
if (!link.connect(address, timings.connectTimeoutMs)) throw IllegalStateException("connect failed")
|
||||
lock.withLock {
|
||||
linkLost = false
|
||||
assembler.reset()
|
||||
}
|
||||
link.prepareLink(address, G1Ble.REQUESTED_MTU, timings.connectTimeoutMs)
|
||||
if (!link.discoverServices(address, timings.servicesTimeoutMs)) throw IllegalStateException("service discovery failed")
|
||||
if (mode == Mode.STOCK) {
|
||||
// Even's firmware serves its own service only on an encrypted link, and the heartbeat goes there.
|
||||
settleBond()
|
||||
if (!link.enableNotifications(address, G1Smp.NUS_TX_UUID, timings.descriptorTimeoutMs)) {
|
||||
throw IllegalStateException("no link to Even's service")
|
||||
}
|
||||
heartbeats = 0
|
||||
nextHeartbeatAtMs = 0
|
||||
} else {
|
||||
if (!link.enableNotifications(address, G1Ble.EVT_CHAR_UUID, timings.descriptorTimeoutMs)) {
|
||||
if (!link.isConnected(address)) throw LinkLostException("the link went down")
|
||||
throw NotG1v0Exception()
|
||||
}
|
||||
// Out of the case the arm obeys only an encrypted link.
|
||||
settleBond()
|
||||
val paired = try {
|
||||
link.writeFrames(address, G1Ble.PAIR_CHAR_UUID, listOf(byteArrayOf(1)), GattWriteMode.WITH_RESPONSE, timings.pairingMs)
|
||||
} catch (e: IllegalStateException) {
|
||||
false
|
||||
}
|
||||
if (!paired) throw IllegalStateException("no encrypted link: an arm pairs only in its case")
|
||||
}
|
||||
if (mode != Mode.PROBE && !link.enableNotifications(address, G1Smp.SMP_CHAR_UUID, timings.descriptorTimeoutMs)) {
|
||||
throw IllegalStateException("no update service")
|
||||
}
|
||||
}
|
||||
|
||||
/** Asks the OS to pair if it hasn't, and waits for that to end; a platform that doesn't say pairs by itself. */
|
||||
private fun settleBond() {
|
||||
if (link.bondState(address) == BondState.NONE) {
|
||||
listener.onState("pairing", side)
|
||||
link.requestBond(address)
|
||||
}
|
||||
val deadline = now() + timings.pairingMs
|
||||
var sawBonding = false
|
||||
while (true) {
|
||||
throwIfCancelled()
|
||||
when (link.bondState(address)) {
|
||||
BondState.BONDED, BondState.UNKNOWN -> return
|
||||
BondState.BONDING -> sawBonding = true
|
||||
BondState.NONE -> if (sawBonding) throw IllegalStateException("pairing was refused")
|
||||
}
|
||||
if (!link.isConnected(address)) throw LinkLostException("the link went down while pairing")
|
||||
if (now() >= deadline) throw IllegalStateException("pairing took too long")
|
||||
sleeper.sleep(timings.pollMs.toLong())
|
||||
}
|
||||
}
|
||||
|
||||
private fun heartbeatIfDue() {
|
||||
if (mode != Mode.STOCK || now() < nextHeartbeatAtMs) return
|
||||
val seq = heartbeats % 0xff
|
||||
heartbeats++
|
||||
nextHeartbeatAtMs = now() + timings.heartbeatMs
|
||||
try {
|
||||
link.writeFrames(address, G1Smp.NUS_RX_UUID, listOf(G1Smp.stockHeartbeat(seq)), GattWriteMode.WITHOUT_RESPONSE, timings.writeTimeoutMs)
|
||||
} catch (e: IllegalStateException) {
|
||||
// The request waiting now finds out.
|
||||
}
|
||||
}
|
||||
|
||||
private fun smp(op: Int, group: Int, cmd: Int, payload: Map<String, Any?>, timeoutMs: Int): Map<*, *> {
|
||||
val seq = nextSmpSeq
|
||||
nextSmpSeq = (nextSmpSeq + 1) and 0xff
|
||||
val latch = Latch(1, platform)
|
||||
lock.withLock {
|
||||
smpSeq = seq
|
||||
smpReply = null
|
||||
smpLatch = latch
|
||||
}
|
||||
try {
|
||||
heartbeatIfDue()
|
||||
val frames = G1Smp.split(G1Smp.frame(op, group, seq, cmd, payload), link.negotiatedMtu(address))
|
||||
val written = try {
|
||||
link.writeFrames(address, G1Smp.SMP_CHAR_UUID, frames, GattWriteMode.WITHOUT_RESPONSE, timings.writeTimeoutMs)
|
||||
} catch (e: IllegalStateException) {
|
||||
false
|
||||
}
|
||||
if (!written) throw LinkLostException("write failed")
|
||||
val deadline = now() + timeoutMs
|
||||
while (true) {
|
||||
throwIfCancelled()
|
||||
heartbeatIfDue()
|
||||
val remaining = deadline - now()
|
||||
if (remaining <= 0) throw StockTimeoutException("no answer from the $side arm within $timeoutMs ms")
|
||||
latch.await(minOf(remaining, timings.pollMs.toLong()))
|
||||
val (reply, lost) = lock.withLock { smpReply to linkLost }
|
||||
if (reply != null) return reply
|
||||
if (lost) throw LinkLostException("the link went down")
|
||||
}
|
||||
} finally {
|
||||
lock.withLock {
|
||||
if (smpLatch === latch) smpLatch = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun control(op: Int, body: ByteArray = ByteArray(0)): G1Protocol.Reply {
|
||||
repeat(timings.controlTries) {
|
||||
val tag = nextControlTag % 255 + 1
|
||||
nextControlTag = tag
|
||||
val latch = Latch(1, platform)
|
||||
lock.withLock {
|
||||
controlTag = tag
|
||||
controlReply = null
|
||||
controlLatch = latch
|
||||
}
|
||||
val written = try {
|
||||
link.writeFrames(address, G1Ble.CTRL_CHAR_UUID, listOf(G1Protocol.control(op, tag, body)), GattWriteMode.WITHOUT_RESPONSE, timings.writeTimeoutMs)
|
||||
} catch (e: IllegalStateException) {
|
||||
false
|
||||
}
|
||||
if (!written) throw LinkLostException("write failed")
|
||||
latch.await(timings.controlReplyMs.toLong())
|
||||
throwIfCancelled()
|
||||
val (reply, lost) = lock.withLock {
|
||||
controlLatch = null
|
||||
controlReply to linkLost
|
||||
}
|
||||
if (reply != null) return reply
|
||||
if (lost) throw LinkLostException("the link went down")
|
||||
}
|
||||
throw StockTimeoutException("no answer to request $op from the $side arm")
|
||||
}
|
||||
|
||||
private fun hello(): G1Protocol.Hello {
|
||||
val reply = control(G1Protocol.OP_HELLO)
|
||||
return G1Protocol.parseHello(reply.body) ?: throw IllegalStateException("The $side arm's firmware isn't one this app knows.")
|
||||
}
|
||||
|
||||
/** Null when the arm doesn't know yet, or a firmware doesn't say. */
|
||||
private fun batteryPercent(): Int? {
|
||||
val reply = control(G1Protocol.OP_PROPS, byteArrayOf(G1Protocol.PROP_BATT_PCT.toByte()))
|
||||
if (reply.status != 0) return null
|
||||
val value = G1Protocol.parseProps(reply.body, 1)?.get(0) ?: return null
|
||||
return if (value in 0..100) value else null
|
||||
}
|
||||
|
||||
private fun throwIfCancelled() {
|
||||
if (cancelled) throw IllegalStateException("Cancelled.")
|
||||
}
|
||||
|
||||
private fun now(): Long = platform.elapsedRealtimeMs()
|
||||
|
||||
private fun log(line: String) = listener.onLog("$side arm: $line")
|
||||
|
||||
private inline fun quietly(action: () -> Unit) {
|
||||
try {
|
||||
action()
|
||||
} catch (ignored: Exception) {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- inbound -------------------------------------------------------------
|
||||
|
||||
override fun onNotification(address: String, characteristicUuid: String, data: ByteArray) {
|
||||
if (characteristicUuid.equals(G1Smp.SMP_CHAR_UUID, ignoreCase = true)) {
|
||||
lock.withLock {
|
||||
for ((seq, body) in assembler.feed(data)) {
|
||||
if (seq == smpSeq) {
|
||||
smpReply = body
|
||||
smpLatch?.countDown()
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (characteristicUuid.equals(G1Ble.EVT_CHAR_UUID, ignoreCase = true)) {
|
||||
val reply = G1Protocol.parseReply(data) ?: return
|
||||
lock.withLock {
|
||||
if (reply.tag == controlTag) {
|
||||
controlReply = reply
|
||||
controlLatch?.countDown()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onConnectionStateChange(address: String, connected: Boolean) {
|
||||
if (connected) return
|
||||
lock.withLock {
|
||||
linkLost = true
|
||||
smpLatch?.countDown()
|
||||
controlLatch?.countDown()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,19 @@ object G1Ble {
|
||||
/** Faceclaw's records (VM.md §6.11). */
|
||||
const val FC_CHAR_UUID = "f3da4d59-277a-4fc9-a1ed-41c9c22d4405"
|
||||
const val REQUESTED_MTU = 247
|
||||
/** The oldest firmware this app works with: `PROP_SET` came in here. */
|
||||
const val REQUIRED_FIRMWARE = "0.5.63"
|
||||
|
||||
/** Dotted versions, component by component. */
|
||||
fun firmwareAtLeast(version: String, required: String = REQUIRED_FIRMWARE): Boolean {
|
||||
val have = version.split(".").map { it.toIntOrNull() ?: 0 }
|
||||
val want = required.split(".").map { it.toIntOrNull() ?: 0 }
|
||||
for (i in 0 until maxOf(have.size, want.size)) {
|
||||
val delta = have.getOrElse(i) { 0 } - want.getOrElse(i) { 0 }
|
||||
if (delta != 0) return delta > 0
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import kotlin.jvm.JvmField
|
||||
|
||||
/** The part of CBOR that MCUmgr uses: integers, byte and text strings, arrays, maps, booleans and null. */
|
||||
object G1Cbor {
|
||||
fun encode(value: Any?): ByteArray {
|
||||
val out = Output()
|
||||
write(out, value)
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
fun decode(data: ByteArray, start: Int = 0): Any? = Reader(data, start).value()
|
||||
|
||||
private class Output {
|
||||
private var bytes = ByteArray(256)
|
||||
private var size = 0
|
||||
|
||||
private fun reserve(extra: Int) {
|
||||
if (size + extra > bytes.size) bytes = bytes.copyOf(maxOf(bytes.size * 2, size + extra))
|
||||
}
|
||||
|
||||
fun add(byte: Int) {
|
||||
reserve(1)
|
||||
bytes[size++] = byte.toByte()
|
||||
}
|
||||
|
||||
fun add(data: ByteArray) {
|
||||
reserve(data.size)
|
||||
data.copyInto(bytes, size)
|
||||
size += data.size
|
||||
}
|
||||
|
||||
fun toByteArray(): ByteArray = bytes.copyOf(size)
|
||||
}
|
||||
|
||||
private fun head(out: Output, major: Int, n: Long) {
|
||||
val first = major shl 5
|
||||
val width = when {
|
||||
n < 24 -> {
|
||||
out.add(first or n.toInt())
|
||||
return
|
||||
}
|
||||
n < 0x100L -> 1
|
||||
n < 0x10000L -> 2
|
||||
n < 0x100000000L -> 4
|
||||
else -> 8
|
||||
}
|
||||
out.add(first or (24 + width.countTrailingZeroBits()))
|
||||
for (i in width - 1 downTo 0) out.add(((n ushr (8 * i)) and 0xff).toInt())
|
||||
}
|
||||
|
||||
private fun write(out: Output, value: Any?) {
|
||||
when (value) {
|
||||
null -> out.add(0xf6)
|
||||
is Boolean -> out.add(if (value) 0xf5 else 0xf4)
|
||||
is Int -> write(out, value.toLong())
|
||||
is Long -> if (value >= 0) head(out, 0, value) else head(out, 1, -1 - value)
|
||||
is ByteArray -> {
|
||||
head(out, 2, value.size.toLong())
|
||||
out.add(value)
|
||||
}
|
||||
is String -> {
|
||||
val text = value.encodeToByteArray()
|
||||
head(out, 3, text.size.toLong())
|
||||
out.add(text)
|
||||
}
|
||||
is List<*> -> {
|
||||
head(out, 4, value.size.toLong())
|
||||
for (item in value) write(out, item)
|
||||
}
|
||||
is Map<*, *> -> {
|
||||
head(out, 5, value.size.toLong())
|
||||
for ((key, item) in value) {
|
||||
write(out, key)
|
||||
write(out, item)
|
||||
}
|
||||
}
|
||||
else -> throw IllegalArgumentException("not CBOR: $value")
|
||||
}
|
||||
}
|
||||
|
||||
private class Reader(private val data: ByteArray, private var at: Int) {
|
||||
private fun u8(): Int {
|
||||
if (at >= data.size) throw IllegalArgumentException("CBOR cut short")
|
||||
return data[at++].toInt() and 0xff
|
||||
}
|
||||
|
||||
fun value(): Any? {
|
||||
val first = u8()
|
||||
val major = first ushr 5
|
||||
val info = first and 31
|
||||
val n: Long? = when {
|
||||
info < 24 -> info.toLong()
|
||||
info in 24..27 -> {
|
||||
var v = 0L
|
||||
repeat(1 shl (info - 24)) { v = (v shl 8) or u8().toLong() }
|
||||
v
|
||||
}
|
||||
info == 31 -> null
|
||||
else -> throw IllegalArgumentException("bad CBOR header $first")
|
||||
}
|
||||
return when (major) {
|
||||
0 -> n ?: throw IllegalArgumentException("bad CBOR integer")
|
||||
1 -> -1 - (n ?: throw IllegalArgumentException("bad CBOR integer"))
|
||||
2, 3 -> {
|
||||
val size = (n ?: throw IllegalArgumentException("indefinite CBOR string")).toInt()
|
||||
if (size < 0 || at + size > data.size) throw IllegalArgumentException("CBOR cut short")
|
||||
val bytes = data.copyOfRange(at, at + size)
|
||||
at += size
|
||||
if (major == 2) bytes else bytes.decodeToString()
|
||||
}
|
||||
4 -> {
|
||||
val items = ArrayList<Any?>()
|
||||
while (more(n, items.size)) items.add(value())
|
||||
if (n == null) at++
|
||||
items
|
||||
}
|
||||
5 -> {
|
||||
val items = LinkedHashMap<Any?, Any?>()
|
||||
while (more(n, items.size)) {
|
||||
val key = value()
|
||||
items[key] = value()
|
||||
}
|
||||
if (n == null) at++
|
||||
items
|
||||
}
|
||||
7 -> when (info) {
|
||||
20 -> false
|
||||
21 -> true
|
||||
22 -> null
|
||||
else -> throw IllegalArgumentException("unsupported CBOR simple value $info")
|
||||
}
|
||||
else -> throw IllegalArgumentException("unsupported CBOR major type $major")
|
||||
}
|
||||
}
|
||||
|
||||
/** An indefinite-length array or map (what Zephyr's image list uses) ends at a 0xFF. */
|
||||
private fun more(n: Long?, count: Int): Boolean {
|
||||
if (n != null) return count < n
|
||||
if (at >= data.size) throw IllegalArgumentException("CBOR cut short")
|
||||
return (data[at].toInt() and 0xff) != 0xff
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* MCUmgr SMP, the update service of both Even's firmware and g1v0: as much of it as installing an image takes, and what
|
||||
* an MCUboot image says about itself. The same requests as scouter_kit's tools/g1host.py (class Smp), which was proven on
|
||||
* real arms first.
|
||||
*/
|
||||
object G1Smp {
|
||||
const val SMP_CHAR_UUID = "da2e7828-fbce-4e01-ae9e-261174997c48"
|
||||
const val NUS_RX_UUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
|
||||
const val NUS_TX_UUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"
|
||||
|
||||
const val OP_READ = 0
|
||||
const val OP_WRITE = 2
|
||||
const val GROUP_OS = 0
|
||||
const val GROUP_IMAGE = 1
|
||||
const val CMD_IMAGE_STATE = 0
|
||||
const val CMD_IMAGE_UPLOAD = 1
|
||||
const val CMD_OS_RESET = 5
|
||||
const val UPLOAD_CHUNK = 2048
|
||||
private const val HEADER = 8
|
||||
|
||||
/** Even's firmware drops a link it hears no heartbeat on. */
|
||||
fun stockHeartbeat(seq: Int): ByteArray =
|
||||
byteArrayOf(0x25, 0x06, 0x00, seq.toByte(), 0x04, seq.toByte())
|
||||
|
||||
fun frame(op: Int, group: Int, seq: Int, cmd: Int, payload: Map<String, Any?>): ByteArray {
|
||||
val body = G1Cbor.encode(payload)
|
||||
val out = ByteArray(HEADER + body.size)
|
||||
out[0] = op.toByte()
|
||||
out[2] = (body.size ushr 8).toByte()
|
||||
out[3] = body.size.toByte()
|
||||
out[4] = (group ushr 8).toByte()
|
||||
out[5] = group.toByte()
|
||||
out[6] = seq.toByte()
|
||||
out[7] = cmd.toByte()
|
||||
body.copyInto(out, HEADER)
|
||||
return out
|
||||
}
|
||||
|
||||
/** One ATT write at most [mtu] - 3 bytes long; MCUmgr joins them again. */
|
||||
fun split(frame: ByteArray, mtu: Int): List<ByteArray> {
|
||||
val size = maxOf(mtu - 3, 20)
|
||||
return (frame.indices step size).map { frame.copyOfRange(it, minOf(it + size, frame.size)) }
|
||||
}
|
||||
|
||||
/** The first chunk also says what is coming, which lets the arm resume an upload of the same file. */
|
||||
fun uploadRequest(image: ByteArray, offset: Int, fileSha256: ByteArray): Map<String, Any?> {
|
||||
val data = image.copyOfRange(offset, minOf(offset + UPLOAD_CHUNK, image.size))
|
||||
return if (offset == 0) {
|
||||
mapOf("image" to 0, "len" to image.size, "off" to 0, "sha" to fileSha256, "data" to data, "upgrade" to false)
|
||||
} else {
|
||||
mapOf("off" to offset, "data" to data)
|
||||
}
|
||||
}
|
||||
|
||||
fun confirmRequest(imageHash: ByteArray): Map<String, Any?> = mapOf("hash" to imageHash, "confirm" to true)
|
||||
|
||||
/** Joins notifications into replies; [feed] gives each complete one as sequence number and body. */
|
||||
class Assembler {
|
||||
private var pending = ByteArray(0)
|
||||
|
||||
fun reset() {
|
||||
pending = ByteArray(0)
|
||||
}
|
||||
|
||||
fun feed(data: ByteArray): List<Pair<Int, Map<*, *>>> {
|
||||
pending += data
|
||||
val replies = ArrayList<Pair<Int, Map<*, *>>>()
|
||||
while (pending.size >= HEADER) {
|
||||
val size = ((pending[2].toInt() and 0xff) shl 8) or (pending[3].toInt() and 0xff)
|
||||
if (pending.size < HEADER + size) break
|
||||
val seq = pending[6].toInt() and 0xff
|
||||
val body = try {
|
||||
if (size == 0) emptyMap<Any?, Any?>() else G1Cbor.decode(pending, HEADER) as? Map<*, *>
|
||||
} catch (e: IllegalArgumentException) {
|
||||
null
|
||||
}
|
||||
if (body == null) {
|
||||
// A frame cut by a lost link: the request is sent again.
|
||||
pending = ByteArray(0)
|
||||
break
|
||||
}
|
||||
pending = pending.copyOfRange(HEADER + size, pending.size)
|
||||
replies.add(seq to body)
|
||||
}
|
||||
return replies
|
||||
}
|
||||
}
|
||||
|
||||
class Slot(
|
||||
@JvmField val image: Int,
|
||||
@JvmField val slot: Int,
|
||||
@JvmField val version: String,
|
||||
@JvmField val hash: ByteArray,
|
||||
@JvmField val flags: List<String>,
|
||||
) {
|
||||
override fun toString(): String =
|
||||
"image $image slot $slot: $version ${BinaryEncoding.bytesToHex(hash.copyOf(minOf(8, hash.size)))} ${flags.joinToString(" ")}".trim()
|
||||
}
|
||||
|
||||
fun parseSlots(reply: Map<*, *>): List<Slot> {
|
||||
val images = reply["images"] as? List<*> ?: return emptyList()
|
||||
return images.mapNotNull { item ->
|
||||
val entry = item as? Map<*, *> ?: return@mapNotNull null
|
||||
val hash = entry["hash"] as? ByteArray ?: return@mapNotNull null
|
||||
Slot((entry["image"] as? Long ?: 0L).toInt(), (entry["slot"] as? Long ?: -1L).toInt(), entry["version"] as? String ?: "?", hash,
|
||||
listOf("bootable", "pending", "confirmed", "active", "permanent").filter { entry[it] == true })
|
||||
}
|
||||
}
|
||||
|
||||
fun replyCode(reply: Map<*, *>): Int = (reply["rc"] as? Long ?: 0L).toInt()
|
||||
|
||||
fun replyOffset(reply: Map<*, *>): Int? = (reply["off"] as? Long)?.toInt()
|
||||
|
||||
/** The dotted version in an MCUboot header. */
|
||||
fun imageVersion(image: ByteArray): String {
|
||||
requireImage(image)
|
||||
val revision = (image[22].toInt() and 0xff) or ((image[23].toInt() and 0xff) shl 8)
|
||||
return "${image[20].toInt() and 0xff}.${image[21].toInt() and 0xff}.$revision"
|
||||
}
|
||||
|
||||
/** The SHA-256 TLV: how MCUmgr names an image. */
|
||||
fun imageHash(image: ByteArray): ByteArray {
|
||||
requireImage(image)
|
||||
var at = u16(image, 8) + u32(image, 12)
|
||||
require(at + 4 <= image.size && u16(image, at) == 0x6907) { "the image has no TLV area" }
|
||||
val end = at + u16(image, at + 2)
|
||||
require(end <= image.size) { "the image's TLV area is cut short" }
|
||||
at += 4
|
||||
while (at + 4 <= end) {
|
||||
val type = u16(image, at)
|
||||
val size = u16(image, at + 2)
|
||||
if (type == 0x10 && size == 32 && at + 4 + size <= end) return image.copyOfRange(at + 4, at + 4 + size)
|
||||
at += 4 + size
|
||||
}
|
||||
throw IllegalArgumentException("the image has no SHA-256 TLV")
|
||||
}
|
||||
|
||||
private fun requireImage(image: ByteArray) {
|
||||
require(image.size > 32 && u32(image, 0) == 0x96f3b83d.toInt()) { "not an MCUboot image" }
|
||||
}
|
||||
|
||||
private fun u16(data: ByteArray, at: Int): Int = (data[at].toInt() and 0xff) or ((data[at + 1].toInt() and 0xff) shl 8)
|
||||
|
||||
private fun u32(data: ByteArray, at: Int): Int = u16(data, at) or (u16(data, at + 2) shl 16)
|
||||
}
|
||||
@@ -48,6 +48,12 @@ interface StockLink {
|
||||
|
||||
fun bondState(address: String): BondState
|
||||
|
||||
/** The ATT MTU agreed on this link. */
|
||||
fun negotiatedMtu(address: String): Int = 23
|
||||
|
||||
/** Ask the OS to pair with a connected device; a platform that pairs by itself on demand does nothing. */
|
||||
fun requestBond(address: String) {}
|
||||
|
||||
fun disconnect(address: String)
|
||||
|
||||
fun close()
|
||||
|
||||
+14
-3
@@ -94,6 +94,8 @@ internal object G1Timings {
|
||||
const val LENS_RIGHT = 2
|
||||
}
|
||||
|
||||
/** What the Install prompt says an arm runs when it isn't g1v0. */
|
||||
private const val G1_OTHER_FIRMWARE = "Even's firmware"
|
||||
private val G1_PROPS = intArrayOf(G1Protocol.PROP_BATT_PCT, G1Protocol.PROP_CHARGE, G1Protocol.PROP_IN_CASE, G1Protocol.PROP_WORN)
|
||||
private val G1_LIGHT = intArrayOf(G1Protocol.PROP_LIGHT)
|
||||
private val G1_IMU = intArrayOf(G1Protocol.PROP_ACC_X, G1Protocol.PROP_ACC_Y, G1Protocol.PROP_ACC_Z)
|
||||
@@ -421,6 +423,9 @@ internal fun GlassesSessionCore.g1HideBeforeDisconnect() {
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Connect (worker thread)
|
||||
|
||||
/** The arm has no g1v0 service: it runs Even's firmware. */
|
||||
private class G1OtherFirmwareException : Exception("not g1v0 firmware")
|
||||
|
||||
private fun GlassesSessionCore.g1ConnectArm(arm: Int, deadlineMs: Long) {
|
||||
val address = g1ArmAddress(arm)
|
||||
val timeoutMs = maxOf(deadlineMs - now(), ConnectionOptions.CONNECT_TIMEOUT_MS.toLong())
|
||||
@@ -433,7 +438,8 @@ private fun GlassesSessionCore.g1ConnectArm(arm: Int, deadlineMs: Long) {
|
||||
throw IllegalStateException("discoverServices failed: $address")
|
||||
}
|
||||
if (!link.enableNotifications(address, G1Ble.EVT_CHAR_UUID, true, ConnectionOptions.DESCRIPTOR_TIMEOUT_MS)) {
|
||||
throw IllegalStateException("no event characteristic on $address: not g1v0 firmware?")
|
||||
if (!link.isConnected(address)) throw IllegalStateException("link lost: $address")
|
||||
throw G1OtherFirmwareException()
|
||||
}
|
||||
link.requestLe2mPhy(address)
|
||||
monitor.withLock {
|
||||
@@ -495,9 +501,9 @@ internal fun GlassesSessionCore.g1ConnectLoopOnce() {
|
||||
logLine("G1 " + (if (arm == 0) "left" else "right") + " arm: " + versions[arm]
|
||||
+ " display path " + fcVersion + " encrypted=" + hello.encrypted + " inCase=" + hello.inCase
|
||||
+ " panelOk=" + hello.panelOk + " phy=" + link.describePhy(g1ArmAddress(arm)))
|
||||
compatible = compatible && fcVersion >= 1
|
||||
compatible = compatible && fcVersion >= 1 && G1Ble.firmwareAtLeast(hello.version)
|
||||
}
|
||||
// The firmware's own number, not the G2 custom firmware's: the path has one version so far, and TS compares this.
|
||||
// Not the G2 custom firmware's revision: this firmware has its own version, compared here, and TS compares this.
|
||||
val firmware = BleProtocol.FirmwareInfo(versions[0], versions[1],
|
||||
if (compatible) BleProtocol.FirmwareInfo.FACECLAW_EXTENSION_PREFIX + requiredFirmwareRevision else "")
|
||||
emitFirmwareInfo(firmware)
|
||||
@@ -533,6 +539,11 @@ internal fun GlassesSessionCore.g1ConnectLoopOnce() {
|
||||
}
|
||||
setStateDisplay("connected", "Connected.")
|
||||
interruptibleSleep.interrupt()
|
||||
} catch (t: G1OtherFirmwareException) {
|
||||
logLine("G1: an arm runs Even's firmware")
|
||||
val firmware = BleProtocol.FirmwareInfo(G1_OTHER_FIRMWARE, G1_OTHER_FIRMWARE, "")
|
||||
emitFirmwareInfo(firmware)
|
||||
monitor.withLock { incompatibleFirmware = firmware }
|
||||
} catch (t: Throwable) {
|
||||
logLine("G1 connect failed: " + safeMessage(t))
|
||||
val unpaired = firstUnpairedArm()
|
||||
|
||||
@@ -461,6 +461,9 @@ class IosBleCentral(private val platform: ProtocolPlatform = IosProtocolPlatform
|
||||
|
||||
override fun isBonded(address: String): Boolean = true
|
||||
|
||||
/** CoreBluetooth pairs by itself when an attribute needs it. */
|
||||
override fun requestBond(address: String) {}
|
||||
|
||||
override fun prepareBenchmarkLink(address: String, mode: Int) {}
|
||||
|
||||
override fun recordDisplayFrameSent() {
|
||||
|
||||
@@ -171,3 +171,56 @@ class IosFirmwareFlasher(rightAddress: String, leftAddress: String, firmwarePath
|
||||
lock.withLock { listener }?.let(action)
|
||||
}
|
||||
}
|
||||
|
||||
/** iOS host for the shared [G1ArmFlashFlow]: one G1 arm's install, or a question about what it runs. */
|
||||
class IosG1Flasher(address: String, side: String, firmwarePath: String, mode: String, connectWindowMs: Int) {
|
||||
private val link = IosBleCentral()
|
||||
private val lock = IosProtocolPlatform.createLock()
|
||||
private var started = false
|
||||
private var listener: FaceclawFirmwareFlasherListener? = null
|
||||
|
||||
private val flow = G1ArmFlashFlow(
|
||||
link,
|
||||
address,
|
||||
side,
|
||||
firmwarePath,
|
||||
G1ArmFlashFlow.mode(mode),
|
||||
connectWindowMs,
|
||||
object : FaceclawFirmwareFlasherListener {
|
||||
override fun onLog(line: String?) {
|
||||
PlatformLog.i(G1ArmFlashFlow.TAG, line ?: "")
|
||||
post { it.onLog(line) }
|
||||
}
|
||||
|
||||
override fun onProgress(lens: String?, componentIndex: Int, componentCount: Int, blockIndex: Int, blockCount: Int, bytesSent: Long, bytesTotal: Long) =
|
||||
post { it.onProgress(lens, componentIndex, componentCount, blockIndex, blockCount, bytesSent, bytesTotal) }
|
||||
|
||||
override fun onState(state: String?, detail: String?) = post { it.onState(state, detail ?: "") }
|
||||
|
||||
override fun onComplete(success: Boolean, detail: String?) = post { it.onComplete(success, detail ?: "") }
|
||||
},
|
||||
)
|
||||
|
||||
fun setListener(listener: FaceclawFirmwareFlasherListener?) {
|
||||
lock.withLock { this.listener = listener }
|
||||
}
|
||||
|
||||
fun start() {
|
||||
lock.withLock {
|
||||
if (started) return
|
||||
started = true
|
||||
}
|
||||
runOnThread("faceclaw-g1-flash") { flow.run() }
|
||||
}
|
||||
|
||||
fun cancel() = flow.cancel()
|
||||
|
||||
fun close() {
|
||||
cancel()
|
||||
runCatching { link.close() }
|
||||
}
|
||||
|
||||
private fun post(action: (FaceclawFirmwareFlasherListener) -> Unit) = main {
|
||||
lock.withLock { listener }?.let(action)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user