forked from Blendman974/faceclaw
Firmware uninstall/revert-to-stock for G1s
This commit is contained in:
1 parent
e103b89510
commit
479308f4a6
17 files changed
+1014
-98
No files matched your search
@@ -21,22 +21,31 @@ class G1FlashTimings(
|
||||
@JvmField val heartbeatMs: Int = 8_000,
|
||||
@JvmField val pollMs: Int = 200,
|
||||
@JvmField val uploadRetries: Int = 40,
|
||||
/** How often a store job's state is asked for while its notice hasn't come. */
|
||||
@JvmField val storePollMs: Int = 2_000,
|
||||
/** Erasing the store over Even's old fonts and pictures takes minutes. */
|
||||
@JvmField val wipeMs: Int = 1_800_000,
|
||||
@JvmField val crcMs: Int = 30_000,
|
||||
)
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* g1_firmware/flash.py. The caller handles one arm at a time and looks for the arm again afterwards: it restarts, and
|
||||
* coming off firmware older than g1v0 0.5.66 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.
|
||||
*
|
||||
* [Mode.RESTORE] puts Even's firmware back on an arm running g1v0: both of a release's images, the application core's
|
||||
* ([firmwarePath]) and the network core's ([netCorePath]), as Even's own update does, so the two always match.
|
||||
*/
|
||||
class G1ArmFlashFlow(
|
||||
private val link: StockLink,
|
||||
private val address: String,
|
||||
private val side: String,
|
||||
private val firmwarePath: String,
|
||||
private val netCorePath: String,
|
||||
private val mode: Mode,
|
||||
/** How long to keep trying to reach the arm and pair with it. */
|
||||
private val connectWindowMs: Int,
|
||||
@@ -52,20 +61,30 @@ class G1ArmFlashFlow(
|
||||
UPDATE,
|
||||
/** Only say what the arm runs, and pair with it. */
|
||||
PROBE,
|
||||
/** The arm runs g1v0 and gets Even's firmware back. */
|
||||
RESTORE,
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val TAG = "FaceclawG1Flash"
|
||||
private const val MIN_BATTERY_PERCENT = 30
|
||||
private const val ANY_STORE_JOB = -1
|
||||
private const val STORE_JOB_INTERRUPTED = -1
|
||||
|
||||
fun mode(name: String): Mode = when (name) {
|
||||
"stock" -> Mode.STOCK
|
||||
"update" -> Mode.UPDATE
|
||||
"probe" -> Mode.PROBE
|
||||
"restore" -> Mode.RESTORE
|
||||
else -> throw IllegalArgumentException("unknown mode $name")
|
||||
}
|
||||
}
|
||||
|
||||
/** One image of an install: MCUboot's number for it, its bytes and the hash its slot is checked against. */
|
||||
private class Part(val imageIndex: Int, val bytes: ByteArray, val label: String) {
|
||||
val hash: ByteArray = G1Smp.imageHash(bytes)
|
||||
}
|
||||
|
||||
private class LinkLostException(message: String) : Exception(message)
|
||||
|
||||
/** The arm has no g1v0 service. */
|
||||
@@ -89,6 +108,9 @@ class G1ArmFlashFlow(
|
||||
private var stockBattery: Int? = null
|
||||
private var stockBatteryLatch: Latch? = null
|
||||
|
||||
/** `NOTICE` 8s since the store job now waited for was asked for. */
|
||||
private val storeNotices = ArrayList<G1Protocol.StoreNotice>()
|
||||
|
||||
/** The OS's half of a stale pairing goes once per run: a second failure isn't that. */
|
||||
private var bondRemoved = false
|
||||
|
||||
@@ -111,7 +133,11 @@ class G1ArmFlashFlow(
|
||||
fun run() {
|
||||
link.setListener(this)
|
||||
try {
|
||||
if (mode == Mode.PROBE) probe() else install()
|
||||
when (mode) {
|
||||
Mode.PROBE -> probe()
|
||||
Mode.RESTORE -> restore()
|
||||
else -> install()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
val message = if (cancelled) "Cancelled." else StockLinkSession.messageOf(e)
|
||||
log("failed: $message")
|
||||
@@ -135,13 +161,15 @@ class G1ArmFlashFlow(
|
||||
listener.onComplete(true, """{"firmware":"g1v0","version":"${hello.version}","safeMode":${hello.safeMode},"inCase":${hello.inCase},"battery":${batteryPercent()}}""")
|
||||
}
|
||||
|
||||
private fun readFirmware(path: String): ByteArray = try {
|
||||
readImage(path)
|
||||
} catch (e: Exception) {
|
||||
throw IllegalStateException("could not read the firmware: " + StockLinkSession.messageOf(e), e)
|
||||
}
|
||||
|
||||
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 image = readFirmware(firmwarePath)
|
||||
val version = G1Smp.imageVersion(image)
|
||||
val hash = G1Smp.imageHash(image)
|
||||
log("image $version, ${image.size} bytes, hash ${BinaryEncoding.bytesToHex(hash.copyOf(8))}")
|
||||
@@ -166,15 +194,15 @@ class G1ArmFlashFlow(
|
||||
val slots = retrying { images() }
|
||||
for (slot in slots) log(slot.toString())
|
||||
listener.onState("flashing", side)
|
||||
if (holdsImage(slots, hash)) {
|
||||
if (holdsImage(slots, G1Smp.IMAGE_APP, 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)
|
||||
upload(image, G1Smp.IMAGE_APP)
|
||||
log("uploaded in ${(now() - startedAt) / 1000} s")
|
||||
}
|
||||
if (!holdsImage(retrying { images() }, hash)) {
|
||||
if (!holdsImage(retrying { images() }, G1Smp.IMAGE_APP, hash)) {
|
||||
throw IllegalStateException("The $side arm's second slot doesn't hold the image after the upload. Nothing was installed.")
|
||||
}
|
||||
throwIfCancelled()
|
||||
@@ -184,6 +212,82 @@ class G1ArmFlashFlow(
|
||||
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")
|
||||
reset()
|
||||
listener.onState("rebooting", side)
|
||||
listener.onComplete(true, """{"flashed":true,"version":"$version"}""")
|
||||
}
|
||||
|
||||
/**
|
||||
* Even's firmware back on an arm running g1v0: the store cleared if g1v0 ever wrote to it, then both images uploaded
|
||||
* and checked, and only then marked for MCUboot, the network core first. MCUboot installs both at the reset, the
|
||||
* network core through its own path to that core, as at every update from Even.
|
||||
*/
|
||||
private fun restore() {
|
||||
listener.onState("validating", side)
|
||||
val parts = listOf(
|
||||
Part(G1Smp.IMAGE_NET_CORE, readFirmware(netCorePath), "network core"),
|
||||
Part(G1Smp.IMAGE_APP, readFirmware(firmwarePath), "application"),
|
||||
)
|
||||
for (part in parts) log("${part.label} image: ${part.bytes.size} bytes, hash ${BinaryEncoding.bytesToHex(part.hash.copyOf(8))}")
|
||||
|
||||
listener.onState("connecting", side)
|
||||
bringUp()
|
||||
listener.onState("checking", side)
|
||||
val hello = hello()
|
||||
log("runs g1v0 ${hello.version}, safe mode ${hello.safeMode}, in the case ${hello.inCase}, encrypted ${hello.encrypted}")
|
||||
requireBattery(batteryPercent())
|
||||
val wiped = clearStore(hello)
|
||||
|
||||
val slots = retrying { images() }
|
||||
for (slot in slots) log(slot.toString())
|
||||
listener.onState("flashing", side)
|
||||
val total = parts.sumOf { it.bytes.size }
|
||||
var before = 0
|
||||
for ((index, part) in parts.withIndex()) {
|
||||
if (holdsImage(slots, part.imageIndex, part.hash)) {
|
||||
log("the ${part.label}'s second slot already holds Even's image")
|
||||
listener.onProgress(side, index + 1, parts.size, part.bytes.size, part.bytes.size, (before + part.bytes.size).toLong(), total.toLong())
|
||||
} else {
|
||||
val startedAt = now()
|
||||
upload(part.bytes, part.imageIndex, index + 1, parts.size, before, total)
|
||||
log("${part.label} uploaded in ${(now() - startedAt) / 1000} s")
|
||||
}
|
||||
before += part.bytes.size
|
||||
}
|
||||
val uploaded = retrying { images() }
|
||||
for (part in parts) {
|
||||
if (!holdsImage(uploaded, part.imageIndex, part.hash)) {
|
||||
throw IllegalStateException("The $side arm's slot for its ${part.label} doesn't hold Even's image after the upload. Nothing was installed.")
|
||||
}
|
||||
}
|
||||
throwIfCancelled()
|
||||
|
||||
listener.onState("committing", side)
|
||||
// The network core first. If the second request fails, what's left pending is Even's network core under g1v0,
|
||||
// which g1v0 works with (its fallback installs this very image); Even's application over the older network core
|
||||
// is the combination that has never been tried.
|
||||
for (part in parts) {
|
||||
val permanent = part.imageIndex == G1Smp.IMAGE_APP
|
||||
val reply = smp(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, G1Smp.CMD_IMAGE_STATE, G1Smp.confirmRequest(part.hash, permanent), timings.smpReplyMs)
|
||||
val code = G1Smp.replyCode(reply)
|
||||
if (code != 0) {
|
||||
throw IllegalStateException("The $side arm refused Even's ${part.label} image (error $code). The arm wasn't restarted; retry to try again.")
|
||||
}
|
||||
}
|
||||
val marked = retrying { images() }
|
||||
for (slot in marked) log(slot.toString())
|
||||
for (part in parts) {
|
||||
if (!marked.any { it.image == part.imageIndex && it.slot == 1 && it.hash.contentEquals(part.hash) && "pending" in it.flags }) {
|
||||
throw IllegalStateException("The $side arm didn't mark Even's ${part.label} image for installing. The arm wasn't restarted; retry to try again.")
|
||||
}
|
||||
}
|
||||
log("both images marked: MCUboot installs them at the next boot")
|
||||
reset()
|
||||
listener.onState("rebooting", side)
|
||||
listener.onComplete(true, """{"flashed":true,"firmware":"stock","wiped":$wiped}""")
|
||||
}
|
||||
|
||||
private fun reset() {
|
||||
try {
|
||||
smp(G1Smp.OP_WRITE, G1Smp.GROUP_OS, G1Smp.CMD_OS_RESET, emptyMap(), timings.resetReplyMs)
|
||||
} catch (e: StockTimeoutException) {
|
||||
@@ -191,8 +295,144 @@ class G1ArmFlashFlow(
|
||||
} catch (e: LinkLostException) {
|
||||
log("the link went down with the reset")
|
||||
}
|
||||
listener.onState("rebooting", side)
|
||||
listener.onComplete(true, """{"flashed":true,"version":"$version"}""")
|
||||
}
|
||||
|
||||
// ---- the asset store ---------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Before Even's firmware goes back: g1v0's asset store took the flash where Even's fonts and pictures were, so if it
|
||||
* ever wrote there, Even's firmware must meet erased flash (flash.py's `wipe_store`). A store that was never written
|
||||
* is left alone, and Even's data with it. True when it was erased.
|
||||
*/
|
||||
private fun clearStore(hello: G1Protocol.Hello): Boolean {
|
||||
repeat(3) {
|
||||
val info = assetInfo()
|
||||
if (info == null) {
|
||||
log("no asset store: this firmware never wrote where Even's data is")
|
||||
return false
|
||||
}
|
||||
if (!info.available) {
|
||||
log("the asset store is unavailable, so nothing was written to it")
|
||||
return false
|
||||
}
|
||||
if (info.running) {
|
||||
// A retried request can find its own job running, as can a retry after a link lost during a wipe.
|
||||
log("a storage job is running: waiting for it to end")
|
||||
clearStoreNotices()
|
||||
waitStoreJob(ANY_STORE_JOB, timings.wipeMs.toLong())
|
||||
return@repeat
|
||||
}
|
||||
if (!storeWritten(info, hello)) {
|
||||
log("the asset store was never written: Even's fonts and pictures stay as they are")
|
||||
return false
|
||||
}
|
||||
if (hello.safeMode) throw IllegalStateException(safeModeMessage())
|
||||
listener.onState("wiping", side)
|
||||
log("erasing the asset store (${info.assets} assets, commit ${info.seq})")
|
||||
val startedAt = now()
|
||||
clearStoreNotices()
|
||||
when (val status = control(G1Protocol.OP_ASSET_FORMAT, G1Protocol.assetFormatRequest(wipe = true)).status) {
|
||||
0 -> {
|
||||
val result = waitStoreJob(G1Protocol.STORE_JOB_FORMAT, timings.wipeMs.toLong())
|
||||
if (result == STORE_JOB_INTERRUPTED) {
|
||||
throw IllegalStateException("The $side arm restarted while erasing Faceclaw's storage. Nothing was installed; retry to finish it.")
|
||||
}
|
||||
if (result != 0) {
|
||||
throw IllegalStateException("The $side arm couldn't erase Faceclaw's storage (error $result). Nothing was installed.")
|
||||
}
|
||||
log("asset store erased in ${(now() - startedAt) / 1000} s")
|
||||
return true
|
||||
}
|
||||
G1Protocol.STATUS_SAFE_MODE -> throw IllegalStateException(safeModeMessage())
|
||||
// A job runs: the next round waits for it.
|
||||
G1Protocol.STATUS_ASSET -> {}
|
||||
else -> throw IllegalStateException("The $side arm refused to erase Faceclaw's storage (error $status). Nothing was installed.")
|
||||
}
|
||||
}
|
||||
throw IllegalStateException("The $side arm's storage couldn't be erased. Nothing was installed.")
|
||||
}
|
||||
|
||||
private fun safeModeMessage(): String =
|
||||
"The $side arm is in safe mode (its firmware restarted repeatedly), where it can't erase Faceclaw's storage, and that has to " +
|
||||
"happen before Even's firmware goes back. Install Faceclaw's firmware again, then uninstall it. Nothing was installed."
|
||||
|
||||
/**
|
||||
* Whether g1v0 ever wrote to the store. It only reads it at boot, so with no assets and no commit nothing was written,
|
||||
* unless a format erased the directory's two sectors (a format resets the commit count), which their fingerprint shows.
|
||||
*/
|
||||
private fun storeWritten(info: G1Protocol.AssetInfo, hello: G1Protocol.Hello): Boolean {
|
||||
if (info.assets > 0 || info.seq != 0L) return true
|
||||
if (hello.safeMode) {
|
||||
log("safe mode: the directory can't be checked")
|
||||
return true
|
||||
}
|
||||
val nonErased = flashNonErased(G1Protocol.STORE_ADDRESS, G1Protocol.STORE_DIRECTORY_BYTES)
|
||||
log("the store's directory sectors: ${nonErased ?: "unknown"} bytes not erased")
|
||||
return nonErased == null || nonErased == 0L
|
||||
}
|
||||
|
||||
/** How many bytes of flash [from]…[from] + [n] - 1 aren't 0xFF, or null when the arm didn't say. */
|
||||
private fun flashNonErased(from: Int, n: Int): Long? {
|
||||
clearStoreNotices()
|
||||
val status = try {
|
||||
control(G1Protocol.OP_FLASH_CRC, G1Protocol.flashCrcRequest(from, n)).status
|
||||
} catch (e: StockTimeoutException) {
|
||||
return null
|
||||
}
|
||||
// 13: a crc job runs, which a retried request finds when the first one's reply was lost; its notice says the same.
|
||||
if (status != 0 && status != G1Protocol.STATUS_ASSET) return null
|
||||
val deadline = now() + timings.crcMs
|
||||
while (now() < deadline) {
|
||||
throwIfCancelled()
|
||||
val notice = lock.withLock {
|
||||
storeNotices.firstOrNull { it.job == G1Protocol.STORE_JOB_CRC && it.address == from && it.n == n }
|
||||
}
|
||||
if (notice != null) return if (notice.result == 0) notice.nonErased else null
|
||||
if (!link.isConnected(address)) return null
|
||||
sleeper.sleep(timings.pollMs.toLong())
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun assetInfo(): G1Protocol.AssetInfo? {
|
||||
val reply = control(G1Protocol.OP_ASSET_INFO)
|
||||
return if (reply.status == 0) G1Protocol.parseAssetInfo(reply.body) else null
|
||||
}
|
||||
|
||||
private fun clearStoreNotices() = lock.withLock { storeNotices.clear() }
|
||||
|
||||
/**
|
||||
* The result of the store job running now: its `NOTICE` 8, or `ASSET_INFO`'s state once it has ended (a notice is lost
|
||||
* with the link, and the job goes on without it). [STORE_JOB_INTERRUPTED] when the arm restarted meanwhile, which ends
|
||||
* a job unfinished.
|
||||
*/
|
||||
private fun waitStoreJob(job: Int, timeoutMs: Long): Int {
|
||||
val deadline = now() + timeoutMs
|
||||
var askAt = now() + timings.storePollMs
|
||||
while (true) {
|
||||
throwIfCancelled()
|
||||
val notice = lock.withLock { storeNotices.firstOrNull { job == ANY_STORE_JOB || it.job == job } }
|
||||
if (notice != null) return notice.result
|
||||
if (now() >= deadline) throw StockTimeoutException("the $side arm's storage job didn't end within ${timeoutMs / 60_000} minutes")
|
||||
if (now() >= askAt) {
|
||||
askAt = now() + timings.storePollMs
|
||||
val info = try {
|
||||
assetInfo()
|
||||
} catch (e: Exception) {
|
||||
if (e !is StockTimeoutException && e !is LinkLostException) throw e
|
||||
log("no answer while the storage job runs (${e.message})")
|
||||
reconnectIfNeeded()
|
||||
null
|
||||
}
|
||||
when (info?.state) {
|
||||
G1Protocol.STORE_DONE -> return info.lastError
|
||||
G1Protocol.STORE_FAILED -> return if (info.lastError != 0) info.lastError else G1Protocol.STATUS_ASSET
|
||||
// A job leaves the state at done or failed until the next boot.
|
||||
G1Protocol.STORE_IDLE -> return STORE_JOB_INTERRUPTED
|
||||
}
|
||||
}
|
||||
sleeper.sleep(timings.pollMs.toLong())
|
||||
}
|
||||
}
|
||||
|
||||
private fun requireBattery(percent: Int?) {
|
||||
@@ -202,21 +442,24 @@ class G1ArmFlashFlow(
|
||||
}
|
||||
}
|
||||
|
||||
private fun holdsImage(slots: List<G1Smp.Slot>, hash: ByteArray): Boolean =
|
||||
slots.any { it.image == 0 && it.slot == 1 && it.hash.contentEquals(hash) }
|
||||
private fun holdsImage(slots: List<G1Smp.Slot>, imageIndex: Int, hash: ByteArray): Boolean =
|
||||
slots.any { it.image == imageIndex && 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) {
|
||||
/**
|
||||
* MCUmgr answers each chunk with the offset it wants next, so an upload resumes after a lost link. Progress counts
|
||||
* [before] bytes of earlier parts out of [total].
|
||||
*/
|
||||
private fun upload(image: ByteArray, imageIndex: Int, part: Int = 1, parts: Int = 1, before: Int = 0, total: Int = image.size) {
|
||||
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)
|
||||
smp(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, G1Smp.CMD_IMAGE_UPLOAD, G1Smp.uploadRequest(image, offset, fileSha, imageIndex), timings.uploadReplyMs)
|
||||
} catch (e: Exception) {
|
||||
if (e !is StockTimeoutException && e !is LinkLostException) throw e
|
||||
failures++
|
||||
@@ -231,7 +474,7 @@ class G1ArmFlashFlow(
|
||||
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())
|
||||
listener.onProgress(side, part, parts, offset, image.size, (before + offset).toLong(), total.toLong())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -525,6 +768,11 @@ class G1ArmFlashFlow(
|
||||
stockBatteryLatch?.countDown()
|
||||
}
|
||||
} else if (characteristicUuid.equals(G1Ble.EVT_CHAR_UUID, ignoreCase = true)) {
|
||||
val notice = G1Protocol.parseStoreNotice(data)
|
||||
if (notice != null) {
|
||||
lock.withLock { storeNotices.add(notice) }
|
||||
return
|
||||
}
|
||||
val reply = G1Protocol.parseReply(data) ?: return
|
||||
lock.withLock {
|
||||
if (reply.tag == controlTag) {
|
||||
|
||||
@@ -39,9 +39,17 @@ object G1Protocol {
|
||||
const val OP_PROPS = 0x0A
|
||||
const val OP_MIC = 0x13
|
||||
const val OP_EVENTS = 0x14
|
||||
const val OP_ASSET_INFO = 0x17
|
||||
const val OP_ASSET_FORMAT = 0x1B
|
||||
const val OP_FLASH_CRC = 0x1C
|
||||
const val OP_FC_INFO = 0x1D
|
||||
const val OP_PROP_SET = 0x1E
|
||||
|
||||
/** Control statuses (VM.md §1). */
|
||||
const val STATUS_SAFE_MODE = 7
|
||||
/** A store request: a job runs, no space, no store. */
|
||||
const val STATUS_ASSET = 13
|
||||
|
||||
const val EV_NOTICE = 0x05
|
||||
const val EV_MIC_DATA = 0x06
|
||||
const val EV_INPUT = 0x07
|
||||
@@ -65,6 +73,18 @@ object G1Protocol {
|
||||
const val NOTICE_MIC_STOPPED = 5
|
||||
const val MIC_STOPPED_LEASE = 3
|
||||
const val NOTICE_GUARD = 7
|
||||
/** A store job ended (VM.md §6.10). */
|
||||
const val NOTICE_STORE_JOB = 8
|
||||
|
||||
const val STORE_JOB_FORMAT = 3
|
||||
const val STORE_JOB_CRC = 4
|
||||
/** `ASSET_INFO`'s job states. */
|
||||
const val STORE_IDLE = 0
|
||||
const val STORE_DONE = 4
|
||||
const val STORE_FAILED = 5
|
||||
/** The asset store's partition in the arm's QSPI flash, where Even's fonts and pictures were; its first two sectors hold its directory. */
|
||||
const val STORE_ADDRESS = 0x140000
|
||||
const val STORE_DIRECTORY_BYTES = 2 * 4096
|
||||
|
||||
const val PROP_BATT_PCT = 0x11
|
||||
const val PROP_CHARGE = 0x12
|
||||
@@ -156,6 +176,50 @@ object G1Protocol {
|
||||
return Notice(data[EVENT_HEADER].toInt() and 255, data.copyOfRange(EVENT_HEADER + 1, data.size))
|
||||
}
|
||||
|
||||
/** `ASSET_FORMAT` frees the whole store; with [wipe] it also erases every sector that isn't erased already. */
|
||||
fun assetFormatRequest(wipe: Boolean): ByteArray =
|
||||
le32(0x534B4153) + if (wipe) le32(0x50570000) else ByteArray(0)
|
||||
|
||||
/** `FLASH_CRC`: a read-only fingerprint of flash bytes address…address + n - 1, given in `NOTICE` 8. */
|
||||
fun flashCrcRequest(address: Int, n: Int): ByteArray = le32(address) + le32(n)
|
||||
|
||||
class AssetInfo(
|
||||
@JvmField val assets: Int,
|
||||
@JvmField val state: Int,
|
||||
@JvmField val lastError: Int,
|
||||
/** Without a usable flash there is no store, and nothing was ever written to it. */
|
||||
@JvmField val available: Boolean,
|
||||
/** The directory's commit count: 0 for a store that is empty and never was written, or was formatted since. */
|
||||
@JvmField val seq: Long,
|
||||
) {
|
||||
val running: Boolean get() = state in 1..3
|
||||
}
|
||||
|
||||
fun parseAssetInfo(body: ByteArray): AssetInfo? {
|
||||
if (body.size < 20) return null
|
||||
return AssetInfo(body[12].toInt() and 255, body[13].toInt() and 255, body[14].toInt() and 255, body[15].toInt() and 1 != 0,
|
||||
u32(body, 16).toLong() and 0xffffffffL)
|
||||
}
|
||||
|
||||
class StoreNotice(
|
||||
@JvmField val job: Int,
|
||||
@JvmField val result: Int,
|
||||
/** A crc job's range, crc32 and how many of its bytes are not 0xFF; 0 for the other jobs. */
|
||||
@JvmField val address: Int,
|
||||
@JvmField val n: Int,
|
||||
@JvmField val nonErased: Long,
|
||||
)
|
||||
|
||||
fun parseStoreNotice(data: ByteArray): StoreNotice? {
|
||||
val notice = parseNotice(data) ?: return null
|
||||
val body = notice.body
|
||||
if (notice.kind != NOTICE_STORE_JOB || body.size < 18) return null
|
||||
return StoreNotice(body[0].toInt() and 255, body[1].toInt() and 255, u32(body, 2), u32(body, 6), u32(body, 14).toLong() and 0xffffffffL)
|
||||
}
|
||||
|
||||
private fun le32(value: Int): ByteArray =
|
||||
byteArrayOf(value.toByte(), (value ushr 8).toByte(), (value ushr 16).toByte(), (value ushr 24).toByte())
|
||||
|
||||
/**
|
||||
* What the arm's light reading looks like to [BrightnessPolicy] and the Developer app: a live passive poll in the
|
||||
* G2 custom firmware's report (settings field 105), whose value counts tenths of a lux.
|
||||
|
||||
@@ -197,17 +197,28 @@ object G1Smp {
|
||||
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?> {
|
||||
/** MCUboot's image numbers on an nRF5340: the application core, and the network core (the Bluetooth controller). */
|
||||
const val IMAGE_APP = 0
|
||||
const val IMAGE_NET_CORE = 1
|
||||
|
||||
/**
|
||||
* The first chunk also says what is coming, which lets the arm resume an upload of the same file, and which image it
|
||||
* is: each has its own second slot.
|
||||
*/
|
||||
fun uploadRequest(image: ByteArray, offset: Int, fileSha256: ByteArray, imageIndex: Int = IMAGE_APP): 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)
|
||||
mapOf("image" to imageIndex, "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)
|
||||
/**
|
||||
* Marks the image with this hash for MCUboot's next boot. [permanent] false is a test install, which is what Even's app
|
||||
* and g1v0's own network-core fallback ask for on image 1; the network core has no copy to go back to either way.
|
||||
*/
|
||||
fun confirmRequest(imageHash: ByteArray, permanent: Boolean = true): Map<String, Any?> = mapOf("hash" to imageHash, "confirm" to permanent)
|
||||
|
||||
/** Joins notifications into replies; [feed] gives each complete one as sequence number and body. */
|
||||
class Assembler {
|
||||
|
||||
@@ -172,8 +172,8 @@ class IosFirmwareFlasher(rightAddress: String, leftAddress: String, firmwarePath
|
||||
}
|
||||
}
|
||||
|
||||
/** 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) {
|
||||
/** iOS host for the shared [G1ArmFlashFlow]: one G1 arm's install, its restore to Even's firmware, or a question about what it runs. */
|
||||
class IosG1Flasher(address: String, side: String, firmwarePath: String, netCorePath: String, mode: String, connectWindowMs: Int) {
|
||||
private val link = IosBleCentral()
|
||||
private val lock = IosProtocolPlatform.createLock()
|
||||
private var started = false
|
||||
@@ -184,6 +184,7 @@ class IosG1Flasher(address: String, side: String, firmwarePath: String, mode: St
|
||||
address,
|
||||
side,
|
||||
firmwarePath,
|
||||
netCorePath,
|
||||
G1ArmFlashFlow.mode(mode),
|
||||
connectWindowMs,
|
||||
object : FaceclawFirmwareFlasherListener {
|
||||
|
||||
Reference in new issue
Block a user