forked from Blendman974/faceclaw
Merge upstream main preserving custom feature integrations
This commit is contained in:
commit
6150a1ac57
228 files changed
+16844
-1388
No files matched your search
@@ -0,0 +1,108 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.roundToInt
|
||||
import kotlin.test.*
|
||||
|
||||
class ColorGlyphArtTest {
|
||||
private val size = 16
|
||||
|
||||
private val clear = 0
|
||||
private val white = argb(255, 255, 255, 255)
|
||||
private val yellow = argb(255, 255, 204, 50)
|
||||
private val brown = argb(255, 90, 50, 20)
|
||||
private val darkGray = argb(255, 60, 60, 60)
|
||||
private val green = argb(255, 120, 170, 60)
|
||||
private val red = argb(255, 230, 60, 50)
|
||||
private val lightRed = argb(255, 250, 140, 130)
|
||||
|
||||
private fun argb(a: Int, r: Int, g: Int, b: Int): Int = (a shl 24) or (r shl 16) or (g shl 8) or b
|
||||
|
||||
private fun glyph(pixel: (x: Int, y: Int) -> Int): IntArray = IntArray(size * size) { pixel(it % size, it / size) }
|
||||
|
||||
private fun inDisc(x: Int, y: Int): Boolean {
|
||||
val dx = x + 0.5 - size / 2.0
|
||||
val dy = y + 0.5 - size / 2.0
|
||||
return dx * dx + dy * dy <= 7.0 * 7.0
|
||||
}
|
||||
|
||||
private fun at(shade: ByteArray, x: Int, y: Int): Int = shade[y * size + x].toInt() and 0xff
|
||||
|
||||
private fun lit(level: Double): Int = (255 * level.pow(NotificationIconArt.GAMMA)).roundToInt()
|
||||
|
||||
@Test fun whiteGlyphIsItsAlpha() {
|
||||
// An ordinary glyph drawn in white: antialiased edges, no color anywhere.
|
||||
val pixels = glyph { x, y -> if (x in 4..11) argb(if (x == 4 || x == 11) 90 else 255, 255, 255, 255) else clear }
|
||||
assertFalse(ColorGlyphArt.isColor(pixels))
|
||||
assertContentEquals(ByteArray(pixels.size) { ((pixels[it] ushr 24) and 0xff).toByte() }, ColorGlyphArt.coverage(pixels))
|
||||
}
|
||||
|
||||
@Test fun faintColorFringeIsNotColor() {
|
||||
// Unpremultiplying a nearly transparent pixel can land anywhere; only real ink counts.
|
||||
val pixels = glyph { x, _ -> if (x == 3) argb(8, 0, 0, 0) else if (x in 4..11) white else clear }
|
||||
assertFalse(ColorGlyphArt.isColor(pixels))
|
||||
}
|
||||
|
||||
@Test fun oneColorGlyphLightsFully() {
|
||||
// 🖤: dark by lightness, but its shape is what matters.
|
||||
val pixels = glyph { x, y -> if (inDisc(x, y)) darkGray else clear }
|
||||
assertTrue(ColorGlyphArt.isColor(pixels))
|
||||
val shade = ColorGlyphArt.coverage(pixels)
|
||||
assertEquals(255, at(shade, 8, 8))
|
||||
assertEquals(0, at(shade, 0, 0))
|
||||
}
|
||||
|
||||
@Test fun darkDetailOnALightBodyStaysVisibleButDim() {
|
||||
// 😀: a yellow disc with dark eyes and mouth; the body stays full, the features dim.
|
||||
val pixels = glyph { x, y ->
|
||||
when {
|
||||
!inDisc(x, y) -> clear
|
||||
(y in 5..6 && (x == 5 || x == 10)) || (y == 11 && x in 5..10) -> brown
|
||||
else -> yellow
|
||||
}
|
||||
}
|
||||
val shade = ColorGlyphArt.coverage(pixels)
|
||||
assertEquals(255, at(shade, 8, 8))
|
||||
assertEquals(lit(0.3), at(shade, 5, 5))
|
||||
assertTrue(at(shade, 5, 5) > 0)
|
||||
}
|
||||
|
||||
@Test fun lightDetailOnADarkerBodyDimsTheBody() {
|
||||
// ✅: a green tile with a large white check; the check lights fully above a dimmer tile.
|
||||
val pixels = glyph { x, y ->
|
||||
when {
|
||||
x !in 1..14 || y !in 1..14 -> clear
|
||||
(x in 4..7 && y in 9..11) || (x in 7..12 && y in 4..8) -> white
|
||||
else -> green
|
||||
}
|
||||
}
|
||||
val shade = ColorGlyphArt.coverage(pixels)
|
||||
assertEquals(255, at(shade, 9, 6))
|
||||
assertEquals(lit(0.6), at(shade, 2, 2))
|
||||
}
|
||||
|
||||
@Test fun smallHighlightLeavesTheBodyFull() {
|
||||
// ❤️: a red body with a small glint; the glint is not detail worth dimming the body for.
|
||||
val pixels = glyph { x, y ->
|
||||
when {
|
||||
!inDisc(x, y) -> clear
|
||||
x in 4..5 && y in 4..5 -> lightRed
|
||||
else -> red
|
||||
}
|
||||
}
|
||||
val shade = ColorGlyphArt.coverage(pixels)
|
||||
assertEquals(255, at(shade, 8, 8))
|
||||
assertEquals(255, at(shade, 4, 4))
|
||||
}
|
||||
|
||||
@Test fun edgeAlphaScalesTheShade() {
|
||||
val pixels = glyph { x, y -> if (x == 2) argb(128, 60, 60, 60) else if (x in 3..12 && y in 3..12) darkGray else clear }
|
||||
val shade = ColorGlyphArt.coverage(pixels)
|
||||
assertEquals(128, at(shade, 2, 8))
|
||||
assertEquals(0, at(shade, 1, 8))
|
||||
}
|
||||
|
||||
@Test fun emptyGlyphIsEmpty() {
|
||||
assertTrue(ColorGlyphArt.shade(IntArray(size * size)).all { it.toInt() == 0 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,986 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertContentEquals
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFailsWith
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
private const val ARM = "F4:27:E9:CA:E8:3F"
|
||||
|
||||
private fun hex(text: String): ByteArray = ByteArray(text.length / 2) { text.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
|
||||
|
||||
/** An image the way MCUboot lays one out: header, payload, then a TLV area with its SHA-256. */
|
||||
private fun testImage(version: Triple<Int, Int, Int> = Triple(0, 5, 64), payloadSize: Int = 5000): ByteArray {
|
||||
val headerSize = 512
|
||||
val hash = ByteArray(32) { (it * 3 + version.third).toByte() }
|
||||
val image = ByteArray(headerSize + payloadSize + 4 + 4 + 32)
|
||||
fun put16(at: Int, value: Int) {
|
||||
image[at] = value.toByte()
|
||||
image[at + 1] = (value ushr 8).toByte()
|
||||
}
|
||||
fun put32(at: Int, value: Int) {
|
||||
put16(at, value and 0xffff)
|
||||
put16(at + 2, value ushr 16)
|
||||
}
|
||||
put32(0, 0x96f3b83d.toInt())
|
||||
put16(8, headerSize)
|
||||
put32(12, payloadSize)
|
||||
image[20] = version.first.toByte()
|
||||
image[21] = version.second.toByte()
|
||||
put16(22, version.third)
|
||||
for (i in 0 until payloadSize) image[headerSize + i] = (i * 7).toByte()
|
||||
val tlv = headerSize + payloadSize
|
||||
put16(tlv, 0x6907)
|
||||
put16(tlv + 2, 4 + 4 + 32)
|
||||
put16(tlv + 4, 0x10)
|
||||
put16(tlv + 6, 32)
|
||||
hash.copyInto(image, tlv + 8)
|
||||
return image
|
||||
}
|
||||
|
||||
/**
|
||||
* One arm behind the StockLink port: MCUmgr's image and OS groups as flash.py meets them on real arms, and g1v0's HELLO,
|
||||
* PROPS and asset store. Requests are answered synchronously, from the write. [netImage] is what a restore puts in image
|
||||
* 1's slot.
|
||||
*/
|
||||
private class FakeArm(private val image: ByteArray, var stock: Boolean = false, private val netImage: ByteArray? = null) : StockLink {
|
||||
var inbound: StockLinkListener? = null
|
||||
var connected = false
|
||||
var bond = BondState.BONDED
|
||||
var bondRequests = 0
|
||||
var bondResult = BondState.BONDED
|
||||
val subscribed = ArrayList<String>()
|
||||
val heartbeats = ArrayList<ByteArray>()
|
||||
val calls = ArrayList<String>()
|
||||
|
||||
var runningVersion = "0.5.63"
|
||||
var safeMode = false
|
||||
var battery = 80
|
||||
|
||||
/** The hash in each image's second slot. */
|
||||
val slotHashes = HashMap<Int, ByteArray>()
|
||||
var slot1Hash: ByteArray?
|
||||
get() = slotHashes[0]
|
||||
set(value) {
|
||||
if (value == null) slotHashes.remove(0) else slotHashes[0] = value
|
||||
}
|
||||
/** Images marked for the next boot, and whether permanently. */
|
||||
val pending = HashMap<Int, Boolean>()
|
||||
val confirms = ArrayList<Pair<Int, Boolean>>()
|
||||
/** The image of the upload in progress, and what each image's last whole upload was. */
|
||||
var uploadImage = -1
|
||||
val uploads = HashMap<Int, ByteArray>()
|
||||
var uploaded = ByteArray(0)
|
||||
var uploadOffset = 0
|
||||
var uploadRefusal = 0
|
||||
/** After the upload the list shows this instead of the image's hash. */
|
||||
var corruptAfterUpload = false
|
||||
var confirmRefusal = 0
|
||||
/** Only this image's confirm is refused; -1: any. */
|
||||
var confirmRefusalImage = -1
|
||||
/** This image's confirm is answered, and the list doesn't show it pending. */
|
||||
var unmarkedImage = -1
|
||||
|
||||
/** No `ASSET_INFO`, as before 0.5.56. */
|
||||
var storeSupported = true
|
||||
var storeAvailable = true
|
||||
var storeAssets = 0
|
||||
var storeSeq = 0L
|
||||
var storeState = 0
|
||||
var storeError = 0
|
||||
/** Bytes that aren't 0xFF in the store's directory sectors: Even's data, until a format. */
|
||||
var directoryNonErased = 4096L
|
||||
/** The format's NOTICE 8 never comes. */
|
||||
var loseStoreNotice = false
|
||||
/** The arm restarts during the wipe: no notice, and the job state back to idle. */
|
||||
var wipeInterrupted = false
|
||||
val formats = ArrayList<Boolean>()
|
||||
var dropAtOffset = -1
|
||||
var silentRequests = 0
|
||||
/** The chunk at this offset gets no answer, once. */
|
||||
var silentAtOffset = -1
|
||||
var onChunk: (() -> Unit)? = null
|
||||
var connects = 0
|
||||
/** The OS remembers a table without g1v0's services, as after an install at the same address. */
|
||||
var staleTable = false
|
||||
var refreshes = 0
|
||||
/** Android says bonded and the arm has lost its half. */
|
||||
var staleBond = false
|
||||
var removedBonds = 0
|
||||
var inCase = false
|
||||
/** Even's firmware's answer to its battery query; null: it says nothing. */
|
||||
var stockBatteryReply: ByteArray? = null
|
||||
|
||||
val wantHash = G1Smp.imageHash(image)
|
||||
|
||||
override fun setListener(listener: StockLinkListener?) { inbound = listener }
|
||||
override fun connect(address: String, timeoutMs: Int): Boolean {
|
||||
connects++
|
||||
connected = true
|
||||
return true
|
||||
}
|
||||
override fun prepareLink(address: String, desiredMtu: Int, timeoutMs: Int) {}
|
||||
override fun discoverServices(address: String, timeoutMs: Int): Boolean = connected
|
||||
/** As FaceclawBleManager: a characteristic the table lacks throws, a refused one (no encryption) returns false. */
|
||||
override fun enableNotifications(address: String, characteristicUuid: String, timeoutMs: Int): Boolean {
|
||||
if (!connected) throw IllegalStateException("Not connected")
|
||||
if (!hasCharacteristic(address, characteristicUuid)) throw IllegalStateException("Characteristic not found: $characteristicUuid")
|
||||
if (stock && staleBond && characteristicUuid == G1Smp.NUS_TX_UUID) return false
|
||||
subscribed.add(characteristicUuid)
|
||||
return true
|
||||
}
|
||||
override fun hasCharacteristic(address: String, characteristicUuid: String): Boolean = when (characteristicUuid) {
|
||||
G1Ble.EVT_CHAR_UUID -> !stock && !staleTable
|
||||
G1Smp.NUS_TX_UUID -> stock
|
||||
else -> true
|
||||
}
|
||||
override fun refreshServices(address: String, timeoutMs: Int): Boolean {
|
||||
refreshes++
|
||||
staleTable = false
|
||||
return connected
|
||||
}
|
||||
override fun removeBond(address: String): Boolean {
|
||||
removedBonds++
|
||||
bond = BondState.NONE
|
||||
staleBond = false
|
||||
connected = false
|
||||
return true
|
||||
}
|
||||
override fun isConnected(address: String): Boolean = connected
|
||||
override fun bondState(address: String): BondState = bond
|
||||
override fun requestBond(address: String) {
|
||||
bondRequests++
|
||||
bond = bondResult
|
||||
}
|
||||
override fun negotiatedMtu(address: String): Int = 100
|
||||
override fun disconnect(address: String) { connected = false }
|
||||
override fun close() { connected = false }
|
||||
|
||||
fun drop() {
|
||||
connected = false
|
||||
inbound?.onConnectionStateChange(ARM, false)
|
||||
}
|
||||
|
||||
override fun writeFrames(address: String, characteristicUuid: String, frames: List<ByteArray>, mode: GattWriteMode, timeoutMs: Int): Boolean {
|
||||
if (!connected) throw IllegalStateException("Not connected")
|
||||
when (characteristicUuid) {
|
||||
G1Smp.NUS_RX_UUID -> {
|
||||
val frame = frames.single()
|
||||
if (frame[0].toInt() == 0x2c) {
|
||||
stockBatteryReply?.let { inbound?.onNotification(ARM, G1Smp.NUS_TX_UUID, it) }
|
||||
} else {
|
||||
heartbeats.add(frame)
|
||||
}
|
||||
}
|
||||
G1Ble.PAIR_CHAR_UUID -> return bond == BondState.BONDED && !staleBond
|
||||
G1Ble.CTRL_CHAR_UUID -> control(frames.single())
|
||||
G1Smp.SMP_CHAR_UUID -> {
|
||||
for (frame in frames) assertTrue(frame.size <= 97, "a write longer than the MTU allows")
|
||||
smp(frames.reduce { a, b -> a + b })
|
||||
}
|
||||
else -> throw IllegalStateException("write to $characteristicUuid")
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun control(request: ByteArray) {
|
||||
val op = request[0].toInt() and 0xff
|
||||
val tag = request[1]
|
||||
val args = request.copyOfRange(2, request.size)
|
||||
var status = 0
|
||||
var after: (() -> Unit)? = null
|
||||
val body = when (op) {
|
||||
G1Protocol.OP_HELLO -> {
|
||||
val parts = runningVersion.split(".").map { it.toInt().toByte() }
|
||||
val flags = (if (safeMode) 1 else 0) or 2 or (if (staleBond) 0 else 64) or (if (inCase) 128 else 0)
|
||||
byteArrayOf(5, parts[0], parts[1], parts[2], 1, flags.toByte(), 0)
|
||||
}
|
||||
G1Protocol.OP_PROPS -> byteArrayOf(battery.toByte(), 0, 0, 0)
|
||||
G1Protocol.OP_ASSET_INFO -> {
|
||||
if (!storeSupported) {
|
||||
status = 2
|
||||
ByteArray(0)
|
||||
} else {
|
||||
ByteArray(12) + byteArrayOf(storeAssets.toByte(), storeState.toByte(), storeError.toByte(), if (storeAvailable) 1 else 0) +
|
||||
le32(storeSeq.toInt())
|
||||
}
|
||||
}
|
||||
G1Protocol.OP_FLASH_CRC -> {
|
||||
calls.add("crc")
|
||||
assertContentEquals(G1Protocol.flashCrcRequest(G1Protocol.STORE_ADDRESS, G1Protocol.STORE_DIRECTORY_BYTES), args)
|
||||
if (safeMode) {
|
||||
status = 7
|
||||
} else {
|
||||
after = { storeNotice(G1Protocol.STORE_JOB_CRC, 0, args + le32(0x1234) + le32(directoryNonErased.toInt())) }
|
||||
}
|
||||
ByteArray(0)
|
||||
}
|
||||
G1Protocol.OP_ASSET_FORMAT -> {
|
||||
calls.add("format")
|
||||
assertContentEquals(G1Protocol.assetFormatRequest(wipe = true), args)
|
||||
when {
|
||||
safeMode -> status = 7
|
||||
storeState in 1..3 -> status = 13
|
||||
else -> {
|
||||
formats.add(true)
|
||||
storeAssets = 0
|
||||
storeSeq = 0
|
||||
directoryNonErased = 0
|
||||
if (wipeInterrupted) {
|
||||
storeState = 0
|
||||
} else {
|
||||
storeState = 4
|
||||
storeError = 0
|
||||
if (!loseStoreNotice) after = { storeNotice(G1Protocol.STORE_JOB_FORMAT, 0, ByteArray(16)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
ByteArray(0)
|
||||
}
|
||||
else -> ByteArray(0)
|
||||
}
|
||||
val event = ByteArray(9) + byteArrayOf(tag, status.toByte()) + body
|
||||
event[0] = (0x80 or op).toByte()
|
||||
inbound?.onNotification(ARM, G1Ble.EVT_CHAR_UUID, event)
|
||||
after?.invoke()
|
||||
}
|
||||
|
||||
private fun storeNotice(job: Int, result: Int, detail: ByteArray) {
|
||||
val event = ByteArray(9) + byteArrayOf(G1Protocol.NOTICE_STORE_JOB.toByte(), job.toByte(), result.toByte()) + detail
|
||||
event[0] = G1Protocol.EV_NOTICE.toByte()
|
||||
inbound?.onNotification(ARM, G1Ble.EVT_CHAR_UUID, event)
|
||||
}
|
||||
|
||||
private fun le32(value: Int): ByteArray = byteArrayOf(value.toByte(), (value ushr 8).toByte(), (value ushr 16).toByte(), (value ushr 24).toByte())
|
||||
|
||||
private fun imageOf(index: Int): ByteArray = when (index) {
|
||||
0 -> image
|
||||
1 -> netImage ?: throw AssertionError("an upload to image 1")
|
||||
else -> throw AssertionError("an upload to image $index")
|
||||
}
|
||||
|
||||
private fun smp(frame: ByteArray) {
|
||||
val op = frame[0].toInt()
|
||||
val group = frame[5].toInt()
|
||||
val seq = frame[6].toInt() and 0xff
|
||||
val cmd = frame[7].toInt()
|
||||
val body = G1Cbor.decode(frame, 8) as Map<*, *>
|
||||
if (silentRequests > 0) {
|
||||
silentRequests--
|
||||
return
|
||||
}
|
||||
when {
|
||||
group == 1 && cmd == 1 -> {
|
||||
calls.add("upload")
|
||||
val off = (body["off"] as Long).toInt()
|
||||
onChunk?.invoke()
|
||||
if (off == silentAtOffset) {
|
||||
silentAtOffset = -1
|
||||
return
|
||||
}
|
||||
if (uploadRefusal != 0) return reply(op, group, seq, cmd, mapOf("rc" to uploadRefusal))
|
||||
if (off == 0) {
|
||||
// A first chunk names the image; the same file again resumes where it stopped, as MCUmgr does.
|
||||
val index = (body["image"] as Long).toInt()
|
||||
val expected = imageOf(index)
|
||||
assertEquals(expected.size.toLong(), body["len"])
|
||||
assertContentEquals(sha256(expected), body["sha"] as ByteArray)
|
||||
if (index != uploadImage || uploadOffset >= expected.size) {
|
||||
uploadImage = index
|
||||
uploadOffset = 0
|
||||
uploaded = ByteArray(0)
|
||||
}
|
||||
}
|
||||
if (off == uploadOffset) {
|
||||
val data = body["data"] as ByteArray
|
||||
uploaded += data
|
||||
uploadOffset += data.size
|
||||
if (uploadOffset == imageOf(uploadImage).size) {
|
||||
uploads[uploadImage] = uploaded
|
||||
slotHashes[uploadImage] = if (corruptAfterUpload) ByteArray(32) else G1Smp.imageHash(uploaded)
|
||||
}
|
||||
}
|
||||
if (uploadOffset >= dropAtOffset && dropAtOffset >= 0) {
|
||||
dropAtOffset = -1
|
||||
drop()
|
||||
return
|
||||
}
|
||||
reply(op, group, seq, cmd, mapOf("rc" to 0, "off" to uploadOffset))
|
||||
}
|
||||
group == 1 && cmd == 0 && op == G1Smp.OP_READ -> {
|
||||
calls.add("list")
|
||||
val images = ArrayList<Map<String, Any?>>()
|
||||
images.add(mapOf("image" to 0, "slot" to 0, "version" to runningVersion, "hash" to ByteArray(32), "active" to true, "confirmed" to true, "bootable" to true))
|
||||
for ((index, hash) in slotHashes.toSortedMap()) {
|
||||
val marked = pending[index]
|
||||
val entry = mutableMapOf<String, Any?>("image" to index, "slot" to 1, "version" to "0.5.64", "hash" to hash, "bootable" to true)
|
||||
if (marked != null && index != unmarkedImage) {
|
||||
entry["pending"] = true
|
||||
if (marked) entry["permanent"] = true
|
||||
}
|
||||
images.add(entry)
|
||||
}
|
||||
reply(op, group, seq, cmd, mapOf("images" to images))
|
||||
}
|
||||
group == 1 && cmd == 0 -> {
|
||||
calls.add("confirm")
|
||||
val hash = body["hash"] as ByteArray
|
||||
val index = slotHashes.entries.firstOrNull { it.value.contentEquals(hash) }?.key
|
||||
assertNotNull(index, "a confirm for a hash no slot holds")
|
||||
if (index == 0 && netImage == null) {
|
||||
assertEquals(true, body["confirm"])
|
||||
assertContentEquals(wantHash, hash)
|
||||
}
|
||||
val permanent = body["confirm"] as Boolean
|
||||
confirms.add(index to permanent)
|
||||
val refused = if (confirmRefusalImage < 0 || confirmRefusalImage == index) confirmRefusal else 0
|
||||
if (refused == 0) pending[index] = permanent
|
||||
reply(op, group, seq, cmd, mapOf("rc" to refused))
|
||||
}
|
||||
group == 0 && cmd == 5 -> {
|
||||
calls.add("reset")
|
||||
reply(op, group, seq, cmd, emptyMap())
|
||||
drop()
|
||||
}
|
||||
else -> throw IllegalStateException("SMP $group/$cmd")
|
||||
}
|
||||
}
|
||||
|
||||
/** The reply comes in pieces, as notifications do. */
|
||||
private fun reply(op: Int, group: Int, seq: Int, cmd: Int, body: Map<String, Any?>) {
|
||||
val frame = G1Smp.frame(op or 1, group, seq, cmd, body)
|
||||
for (piece in G1Smp.split(frame, 23)) inbound?.onNotification(ARM, G1Smp.SMP_CHAR_UUID, piece)
|
||||
}
|
||||
}
|
||||
|
||||
private class Recorder : FaceclawFirmwareFlasherListener {
|
||||
val states = ArrayList<String>()
|
||||
val logs = ArrayList<String>()
|
||||
var progress = 0L
|
||||
var total = 0L
|
||||
var success: Boolean? = null
|
||||
var detail = ""
|
||||
|
||||
override fun onLog(line: String?) { logs.add(line ?: "") }
|
||||
override fun onProgress(lens: String?, componentIndex: Int, componentCount: Int, blockIndex: Int, blockCount: Int, bytesSent: Long, bytesTotal: Long) {
|
||||
progress = bytesSent
|
||||
total = bytesTotal
|
||||
}
|
||||
override fun onState(state: String?, detail: String?) { states.add(state ?: "") }
|
||||
override fun onComplete(success: Boolean, detail: String?) {
|
||||
this.success = success
|
||||
this.detail = detail ?: ""
|
||||
}
|
||||
}
|
||||
|
||||
private val FAST = G1FlashTimings(
|
||||
connectTimeoutMs = 50, servicesTimeoutMs = 50, descriptorTimeoutMs = 50, writeTimeoutMs = 50, pairingMs = 200, retryDelayMs = 1,
|
||||
controlReplyMs = 20, controlTries = 2, uploadReplyMs = 150, smpReplyMs = 150, resetReplyMs = 50, heartbeatMs = 30, pollMs = 5, uploadRetries = 5,
|
||||
storePollMs = 10, wipeMs = 2_000, crcMs = 200,
|
||||
)
|
||||
|
||||
class G1SmpStockTest {
|
||||
@Test
|
||||
fun stocksBatteryReplyIsReadOnlyWhenItIsOne() {
|
||||
// What the real firmware answered in emulation (g1-fw BLE_COMMAND_SET_REPORT), first bytes.
|
||||
assertEquals(100, G1Smp.parseStockBattery(byteArrayOf(0x2c, 0x66, 0x64, 0x64, 0xf9.toByte(), 0x80.toByte())))
|
||||
assertEquals(null, G1Smp.parseStockBattery(byteArrayOf(0x2c, 0x66, 0)))
|
||||
assertEquals(null, G1Smp.parseStockBattery(byteArrayOf(0x2c, 0x66, 101)))
|
||||
assertEquals(null, G1Smp.parseStockBattery(byteArrayOf(0x2c, 0xc9.toByte(), 50)))
|
||||
assertEquals(null, G1Smp.parseStockBattery(byteArrayOf(0x25, 0x66, 50)))
|
||||
assertEquals(null, G1Smp.parseStockBattery(byteArrayOf(0x2c, 0x66)))
|
||||
}
|
||||
}
|
||||
|
||||
class G1SmpTest {
|
||||
private val sha = ByteArray(32) { it.toByte() }
|
||||
|
||||
/** The expected bytes come from scouter_kit's tools/g1host.py, whose requests were proven on real arms. */
|
||||
@Test
|
||||
fun requestsMatchTheProvenPythonTool() {
|
||||
val image = ByteArray(574408)
|
||||
image[0] = 1
|
||||
image[1] = 2
|
||||
image[2] = 3
|
||||
val first = G1Smp.uploadRequest(image, 0, sha).toMutableMap()
|
||||
first["data"] = byteArrayOf(1, 2, 3)
|
||||
assertEquals(
|
||||
"0200004e00010001a665696d61676500636c656e1a0008c3c8636f666600637368615820000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f6464617461430102036775706772616465f4",
|
||||
BinaryEncoding.bytesToHex(G1Smp.frame(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, 0, G1Smp.CMD_IMAGE_UPLOAD, first)),
|
||||
)
|
||||
assertEquals(
|
||||
"0200001100010101a2636f6666190800646461746143010203",
|
||||
BinaryEncoding.bytesToHex(G1Smp.frame(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, 1, G1Smp.CMD_IMAGE_UPLOAD, mapOf("off" to 2048, "data" to byteArrayOf(1, 2, 3)))),
|
||||
)
|
||||
assertEquals(
|
||||
"0200003100010500a264686173685820000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f67636f6e6669726df5",
|
||||
BinaryEncoding.bytesToHex(G1Smp.frame(G1Smp.OP_WRITE, G1Smp.GROUP_IMAGE, 5, G1Smp.CMD_IMAGE_STATE, G1Smp.confirmRequest(sha))),
|
||||
)
|
||||
assertEquals("0000000100010700a0", BinaryEncoding.bytesToHex(G1Smp.frame(G1Smp.OP_READ, G1Smp.GROUP_IMAGE, 7, G1Smp.CMD_IMAGE_STATE, emptyMap())))
|
||||
assertEquals("020000010000ff05a0", BinaryEncoding.bytesToHex(G1Smp.frame(G1Smp.OP_WRITE, G1Smp.GROUP_OS, 255, G1Smp.CMD_OS_RESET, emptyMap())))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun cborMatchesPythonAndRoundTrips() {
|
||||
val value = mapOf("n" to -5, "big" to 70000, "huge" to 5000000000L, "t" to true, "s" to "ab")
|
||||
val encoded = G1Cbor.encode(value)
|
||||
assertEquals("a5616e24636269671a0001117064687567651b000000012a05f2006174f56173626162", BinaryEncoding.bytesToHex(encoded))
|
||||
val decoded = G1Cbor.decode(encoded) as Map<*, *>
|
||||
assertEquals(-5L, decoded["n"])
|
||||
assertEquals(70000L, decoded["big"])
|
||||
assertEquals(5000000000L, decoded["huge"])
|
||||
assertEquals(true, decoded["t"])
|
||||
assertEquals("ab", decoded["s"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun cborReadsTheIndefiniteLengthsOfAnImageList() {
|
||||
// {"images": [{"slot": 1, "active": true}]}, each container of indefinite length.
|
||||
val data = hex("bf66696d616765739fbf64736c6f74016661637469766" + "5f5ffffff")
|
||||
val slots = (G1Cbor.decode(data) as Map<*, *>)["images"] as List<*>
|
||||
val slot = slots.single() as Map<*, *>
|
||||
assertEquals(1L, slot["slot"])
|
||||
assertEquals(true, slot["active"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun malformedCborIsAnErrorNotAWrongValue() {
|
||||
assertFailsWith<IllegalArgumentException> { G1Cbor.decode(hex("5820")) }
|
||||
assertFailsWith<IllegalArgumentException> { G1Cbor.decode(hex("bf")) }
|
||||
assertFailsWith<IllegalArgumentException> { G1Cbor.decode(ByteArray(0)) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun repliesAreJoinedAcrossNotifications() {
|
||||
val assembler = G1Smp.Assembler()
|
||||
val one = G1Smp.frame(3, 1, 7, 1, mapOf("off" to 2048, "rc" to 0))
|
||||
val two = G1Smp.frame(3, 1, 8, 0, emptyMap())
|
||||
val all = one + two
|
||||
val replies = ArrayList<Pair<Int, Map<*, *>>>()
|
||||
for (start in all.indices step 5) replies += assembler.feed(all.copyOfRange(start, minOf(start + 5, all.size)))
|
||||
assertEquals(listOf(7, 8), replies.map { it.first })
|
||||
assertEquals(2048, G1Smp.replyOffset(replies[0].second))
|
||||
assertEquals(0, G1Smp.replyCode(replies[1].second))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anImageSaysWhatItIs() {
|
||||
val image = testImage(Triple(0, 5, 300))
|
||||
assertEquals("0.5.300", G1Smp.imageVersion(image))
|
||||
assertContentEquals(ByteArray(32) { (it * 3 + 300).toByte() }, G1Smp.imageHash(image))
|
||||
assertFailsWith<IllegalArgumentException> { G1Smp.imageVersion(ByteArray(100)) }
|
||||
val cut = image.copyOf(image.size - 20)
|
||||
assertFailsWith<IllegalArgumentException> { G1Smp.imageHash(cut) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun writesFitTheMtu() {
|
||||
val pieces = G1Smp.split(ByteArray(1000), 247)
|
||||
assertTrue(pieces.all { it.size <= 244 })
|
||||
assertEquals(1000, pieces.sumOf { it.size })
|
||||
}
|
||||
}
|
||||
|
||||
class G1ArmFlashFlowTest {
|
||||
private val image = testImage()
|
||||
|
||||
private fun flow(arm: FakeArm, listener: Recorder, mode: G1ArmFlashFlow.Mode, window: Int = 100) =
|
||||
G1ArmFlashFlow(arm, ARM, "left", "image.bin", "", mode, window, listener, FAST, testPlatform(), { image })
|
||||
|
||||
private fun run(arm: FakeArm, mode: G1ArmFlashFlow.Mode, window: Int = 100): Recorder {
|
||||
val listener = Recorder()
|
||||
flow(arm, listener, mode, window).run()
|
||||
assertNotNull(listener.success, "the flow must always finish")
|
||||
return listener
|
||||
}
|
||||
|
||||
private fun confirmIsLast(arm: FakeArm) {
|
||||
assertEquals(listOf("confirm", "reset"), arm.calls.takeLast(2))
|
||||
assertEquals(1, arm.calls.count { it == "confirm" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anUpdateUploadsChecksThenConfirmsAndResets() {
|
||||
val arm = FakeArm(image)
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertEquals("""{"flashed":true,"version":"0.5.64"}""", result.detail)
|
||||
assertContentEquals(image, arm.uploaded)
|
||||
assertEquals(image.size.toLong(), result.progress)
|
||||
assertEquals(image.size.toLong(), result.total)
|
||||
confirmIsLast(arm)
|
||||
// The list before the confirm is what proves the slot holds this image.
|
||||
assertEquals("list", arm.calls[arm.calls.indexOf("confirm") - 1])
|
||||
assertTrue(arm.heartbeats.isEmpty(), "g1v0 has no heartbeat")
|
||||
assertTrue("rebooting" in result.states)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anArmAlreadyOnThisVersionIsLeftAlone() {
|
||||
val arm = FakeArm(image)
|
||||
arm.runningVersion = "0.5.64"
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
|
||||
assertEquals(true, result.success)
|
||||
assertEquals("""{"flashed":false,"version":"0.5.64"}""", result.detail)
|
||||
assertTrue(arm.calls.isEmpty(), "nothing goes to the update service")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anArmInSafeModeOnThisVersionIsInstalledAgain() {
|
||||
val arm = FakeArm(image)
|
||||
arm.runningVersion = "0.5.64"
|
||||
arm.safeMode = true
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
|
||||
assertEquals("""{"flashed":true,"version":"0.5.64"}""", result.detail)
|
||||
confirmIsLast(arm)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aSlotThatDoesNotHoldTheImageIsNeverConfirmed() {
|
||||
val arm = FakeArm(image)
|
||||
arm.corruptAfterUpload = true
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
|
||||
assertEquals(false, result.success)
|
||||
assertFalse("confirm" in arm.calls)
|
||||
assertFalse("reset" in arm.calls)
|
||||
assertTrue("Nothing was installed" in result.detail, result.detail)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRefusedUploadIsNeverConfirmed() {
|
||||
val arm = FakeArm(image)
|
||||
arm.uploadRefusal = 9
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
|
||||
assertEquals(false, result.success)
|
||||
assertFalse("confirm" in arm.calls)
|
||||
assertTrue("error 9" in result.detail, result.detail)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRefusedConfirmIsNotAReset() {
|
||||
val arm = FakeArm(image)
|
||||
arm.confirmRefusal = 2
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
|
||||
assertEquals(false, result.success)
|
||||
assertFalse("reset" in arm.calls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aLowBatteryStopsAnUpdateBeforeAnyUpload() {
|
||||
val arm = FakeArm(image)
|
||||
arm.battery = 12
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
|
||||
assertEquals(false, result.success)
|
||||
assertTrue("12%" in result.detail, result.detail)
|
||||
assertTrue(arm.calls.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aDamagedImageFailsBeforeTheLinkIsTouched() {
|
||||
val listener = Recorder()
|
||||
val arm = FakeArm(image)
|
||||
G1ArmFlashFlow(arm, ARM, "left", "image.bin", "", G1ArmFlashFlow.Mode.UPDATE, 100, listener, FAST, testPlatform(), { ByteArray(100) }).run()
|
||||
assertEquals(false, listener.success)
|
||||
assertEquals(0, arm.connects)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anUnreadableImageIsAClearFailure() {
|
||||
val listener = Recorder()
|
||||
val arm = FakeArm(image)
|
||||
G1ArmFlashFlow(arm, ARM, "left", "image.bin", "", G1ArmFlashFlow.Mode.STOCK, 100, listener, FAST, testPlatform(), { throw IllegalStateException("gone") }).run()
|
||||
assertEquals(false, listener.success)
|
||||
assertTrue("could not read the firmware" in listener.detail, listener.detail)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aLostLinkResumesTheUpload() {
|
||||
val arm = FakeArm(image)
|
||||
arm.dropAtOffset = 2048
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertContentEquals(image, arm.uploaded)
|
||||
assertTrue(arm.connects >= 2, "it connected again")
|
||||
confirmIsLast(arm)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aChunkThatGetsNoAnswerIsSentAgain() {
|
||||
val arm = FakeArm(image)
|
||||
arm.silentAtOffset = 2048
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertContentEquals(image, arm.uploaded)
|
||||
confirmIsLast(arm)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anUploadThatNeverGetsAnswersGivesUpWithoutConfirming() {
|
||||
val arm = FakeArm(image)
|
||||
arm.silentRequests = 1000
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
|
||||
assertEquals(false, result.success)
|
||||
assertFalse("confirm" in arm.calls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aSlotAlreadyHoldingTheImageSkipsTheUpload() {
|
||||
val arm = FakeArm(image)
|
||||
arm.slot1Hash = arm.wantHash
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertFalse("upload" in arm.calls)
|
||||
confirmIsLast(arm)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stockGetsAHeartbeatEvenWhileAChunkWaits() {
|
||||
val arm = FakeArm(image, stock = true)
|
||||
// A chunk can wait a long time, as the first does while the arm erases its slot: the heartbeat has to keep going.
|
||||
arm.silentAtOffset = 2048
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.STOCK)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertTrue(arm.heartbeats.size >= 3, "heartbeats: ${arm.heartbeats.size}")
|
||||
assertTrue(G1Smp.NUS_TX_UUID in arm.subscribed)
|
||||
assertEquals(0x25, arm.heartbeats[0][0].toInt())
|
||||
assertEquals(arm.heartbeats[1][3], 1.toByte())
|
||||
assertEquals(arm.heartbeats[1][5], 1.toByte())
|
||||
confirmIsLast(arm)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stockIsPairedWithFirst() {
|
||||
val arm = FakeArm(image, stock = true)
|
||||
arm.bond = BondState.NONE
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.STOCK)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertEquals(1, arm.bondRequests)
|
||||
assertTrue("pairing" in result.states)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRefusedBondIsRetriedThenReported() {
|
||||
val arm = FakeArm(image)
|
||||
arm.bond = BondState.NONE
|
||||
arm.bondResult = BondState.NONE
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE, window = 1)
|
||||
assertEquals(false, result.success)
|
||||
assertTrue(arm.calls.isEmpty())
|
||||
assertTrue("Couldn't reach the left arm" in result.detail, result.detail)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPlatformThatCannotSeeBondsReliesOnTheEncryptedWrite() {
|
||||
val arm = FakeArm(image)
|
||||
arm.bond = BondState.UNKNOWN
|
||||
val listener = Recorder()
|
||||
// The write to PAIR fails on an unknown bond in this fake, as on an arm out of the case: no encrypted link.
|
||||
flow(arm, listener, G1ArmFlashFlow.Mode.PROBE, 1).run()
|
||||
assertEquals(false, listener.success)
|
||||
assertEquals(0, arm.bondRequests)
|
||||
assertTrue("an arm pairs only in its case" in listener.detail, listener.detail)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aStaleBondInTheCaseIsRemovedAndMadeAgain() {
|
||||
val arm = FakeArm(image)
|
||||
arm.staleBond = true
|
||||
arm.inCase = true
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertEquals(1, arm.removedBonds)
|
||||
assertEquals(1, arm.bondRequests)
|
||||
confirmIsLast(arm)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aBondIsNeverGivenUpOutOfTheCase() {
|
||||
val arm = FakeArm(image)
|
||||
arm.staleBond = true
|
||||
arm.inCase = false
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.UPDATE, window = 1)
|
||||
assertEquals(false, result.success)
|
||||
assertEquals(0, arm.removedBonds, "no new bond can be made out of the case")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aStaleBondOnStockIsRemovedAndMadeAgain() {
|
||||
val arm = FakeArm(image, stock = true)
|
||||
arm.staleBond = true
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.STOCK)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertEquals(1, arm.removedBonds)
|
||||
assertEquals(1, arm.bondRequests)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anOldServiceTableIsReadAgainBeforeItIsBelieved() {
|
||||
val arm = FakeArm(image)
|
||||
arm.staleTable = true
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.PROBE)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertEquals(1, arm.refreshes)
|
||||
assertTrue("\"firmware\":\"g1v0\"" in result.detail, result.detail)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aLowBatteryOnStockStopsBeforeAnyUpload() {
|
||||
val arm = FakeArm(image, stock = true)
|
||||
arm.stockBatteryReply = byteArrayOf(0x2c, 0x66, 12, 12)
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.STOCK)
|
||||
assertEquals(false, result.success)
|
||||
assertTrue("12%" in result.detail, result.detail)
|
||||
assertFalse("upload" in arm.calls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aChargedArmOnStockGoesOn() {
|
||||
val arm = FakeArm(image, stock = true)
|
||||
arm.stockBatteryReply = byteArrayOf(0x2c, 0x66, 100, 100)
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.STOCK)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertTrue(result.logs.any { "battery 100%" in it }, result.logs.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aStockArmThatSaysNothingAboutItsBatteryGoesOn() {
|
||||
val arm = FakeArm(image, stock = true)
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.STOCK)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertTrue(result.logs.any { "battery unknown" in it }, result.logs.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aProbeSaysWhatAnArmRuns() {
|
||||
val arm = FakeArm(image)
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.PROBE)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertEquals("""{"firmware":"g1v0","version":"0.5.63","safeMode":false,"inCase":false,"battery":80}""", result.detail)
|
||||
assertTrue(arm.calls.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aProbeOfEvensFirmwareNeedsNoPairing() {
|
||||
val arm = FakeArm(image, stock = true)
|
||||
arm.bond = BondState.NONE
|
||||
val result = run(arm, G1ArmFlashFlow.Mode.PROBE)
|
||||
assertEquals("""{"firmware":"stock"}""", result.detail)
|
||||
assertEquals(0, arm.bondRequests)
|
||||
}
|
||||
|
||||
// ---- back to Even's firmware ----
|
||||
|
||||
private val evenApp = testImage(Triple(0, 0, 0), payloadSize = 7000)
|
||||
private val evenNet = testImage(Triple(0, 0, 1), payloadSize = 3000)
|
||||
|
||||
private fun restoreArm(): FakeArm = FakeArm(evenApp, netImage = evenNet).also { it.runningVersion = "0.5.66" }
|
||||
|
||||
private fun restore(arm: FakeArm, window: Int = 100): Recorder {
|
||||
val listener = Recorder()
|
||||
G1ArmFlashFlow(arm, ARM, "right", "app.bin", "net.bin", G1ArmFlashFlow.Mode.RESTORE, window, listener, FAST, testPlatform(), { path ->
|
||||
when (path) {
|
||||
"app.bin" -> evenApp
|
||||
"net.bin" -> evenNet
|
||||
else -> throw IllegalStateException("no $path")
|
||||
}
|
||||
}).run()
|
||||
assertNotNull(listener.success, "the flow must always finish")
|
||||
return listener
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRestoreUploadsBothImagesThenMarksTheNetworkCoreFirst() {
|
||||
val arm = restoreArm()
|
||||
val result = restore(arm)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertEquals("""{"flashed":true,"firmware":"stock","wiped":false}""", result.detail)
|
||||
assertContentEquals(evenNet, arm.uploads[1])
|
||||
assertContentEquals(evenApp, arm.uploads[0])
|
||||
// Image 1 as a test install, as Even's app and g1v0's fallback do; the application for good.
|
||||
assertEquals(listOf(1 to false, 0 to true), arm.confirms)
|
||||
assertEquals(listOf("confirm", "confirm", "list", "reset"), arm.calls.takeLast(4))
|
||||
assertEquals((evenApp.size + evenNet.size).toLong(), result.total)
|
||||
assertEquals(result.total, result.progress)
|
||||
assertTrue("rebooting" in result.states)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aStoreNeverWrittenKeepsEvensData() {
|
||||
val arm = restoreArm()
|
||||
val result = restore(arm)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertEquals(listOf("crc"), arm.calls.filter { it == "crc" || it == "format" })
|
||||
assertTrue(arm.formats.isEmpty())
|
||||
assertFalse("wiping" in result.states)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aStoreThatHoldsAssetsIsWipedBeforeAnyUpload() {
|
||||
val arm = restoreArm()
|
||||
arm.storeAssets = 2
|
||||
arm.storeSeq = 5
|
||||
val result = restore(arm)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertEquals("""{"flashed":true,"firmware":"stock","wiped":true}""", result.detail)
|
||||
assertEquals(listOf(true), arm.formats)
|
||||
assertTrue(arm.calls.indexOf("format") < arm.calls.indexOf("upload"))
|
||||
assertFalse("crc" in arm.calls, "a store with assets needs no fingerprint")
|
||||
assertTrue("wiping" in result.states)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anEmptyStoreWhoseDirectoryWasErasedIsWiped() {
|
||||
// A format resets the commit count, and erased the two directory sectors over Even's data.
|
||||
val arm = restoreArm()
|
||||
arm.directoryNonErased = 0
|
||||
val result = restore(arm)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertEquals(listOf("crc", "format"), arm.calls.filter { it == "crc" || it == "format" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun firmwareWithoutTheStoreIsNotWiped() {
|
||||
val arm = restoreArm()
|
||||
arm.storeSupported = false
|
||||
val result = restore(arm)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertFalse("crc" in arm.calls)
|
||||
assertFalse("format" in arm.calls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aLostWipeNoticeIsReadFromTheStoreState() {
|
||||
val arm = restoreArm()
|
||||
arm.storeAssets = 1
|
||||
arm.storeSeq = 1
|
||||
arm.loseStoreNotice = true
|
||||
val result = restore(arm)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertTrue("\"wiped\":true" in result.detail, result.detail)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anArmThatRestartsDuringTheWipeGetsNothingInstalled() {
|
||||
val arm = restoreArm()
|
||||
arm.storeAssets = 1
|
||||
arm.storeSeq = 1
|
||||
arm.wipeInterrupted = true
|
||||
val result = restore(arm)
|
||||
assertEquals(false, result.success)
|
||||
assertTrue("restarted while erasing" in result.detail, result.detail)
|
||||
assertFalse("upload" in arm.calls)
|
||||
assertFalse("confirm" in arm.calls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun safeModeWithAWrittenStoreInstallsNothing() {
|
||||
val arm = restoreArm()
|
||||
arm.safeMode = true
|
||||
arm.storeAssets = 1
|
||||
arm.storeSeq = 1
|
||||
val result = restore(arm)
|
||||
assertEquals(false, result.success)
|
||||
assertTrue("safe mode" in result.detail, result.detail)
|
||||
assertFalse("format" in arm.calls)
|
||||
assertFalse("upload" in arm.calls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aLowBatteryStopsARestoreBeforeTheWipe() {
|
||||
val arm = restoreArm()
|
||||
arm.battery = 12
|
||||
arm.storeAssets = 1
|
||||
arm.storeSeq = 1
|
||||
val result = restore(arm)
|
||||
assertEquals(false, result.success)
|
||||
assertTrue("12%" in result.detail, result.detail)
|
||||
assertFalse("format" in arm.calls)
|
||||
assertFalse("upload" in arm.calls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRefusedNetworkCoreNeverLeavesTheApplicationMarked() {
|
||||
val arm = restoreArm()
|
||||
arm.confirmRefusal = 3
|
||||
arm.confirmRefusalImage = 1
|
||||
val result = restore(arm)
|
||||
assertEquals(false, result.success)
|
||||
assertEquals(listOf(1 to false), arm.confirms)
|
||||
assertFalse(0 in arm.pending)
|
||||
assertFalse("reset" in arm.calls)
|
||||
assertTrue("network core" in result.detail, result.detail)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anImageTheArmDidNotMarkIsNoReset() {
|
||||
val arm = restoreArm()
|
||||
arm.unmarkedImage = 0
|
||||
val result = restore(arm)
|
||||
assertEquals(false, result.success)
|
||||
assertFalse("reset" in arm.calls)
|
||||
assertTrue("didn't mark" in result.detail, result.detail)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aLostLinkResumesARestoreUpload() {
|
||||
val arm = restoreArm()
|
||||
arm.dropAtOffset = 2048
|
||||
val result = restore(arm)
|
||||
assertEquals(true, result.success, result.detail)
|
||||
assertContentEquals(evenNet, arm.uploads[1])
|
||||
assertContentEquals(evenApp, arm.uploads[0])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun cancellingDuringTheUploadStopsBeforeTheConfirm() {
|
||||
val arm = FakeArm(image)
|
||||
val listener = Recorder()
|
||||
val flow = flow(arm, listener, G1ArmFlashFlow.Mode.UPDATE)
|
||||
arm.onChunk = { flow.cancel() }
|
||||
flow.run()
|
||||
assertEquals(false, listener.success)
|
||||
assertEquals("Cancelled.", listener.detail)
|
||||
assertFalse("confirm" in arm.calls)
|
||||
}
|
||||
}
|
||||
|
||||
class G1StoreProtocolTest {
|
||||
/** The bytes of scouter_kit's tools/g1host.py: `struct.pack("<II", FORMAT_MAGIC, WIPE_MAGIC)`. */
|
||||
@Test
|
||||
fun requestsMatchThePythonTool() {
|
||||
assertEquals("53414b5300005750", BinaryEncoding.bytesToHex(G1Protocol.assetFormatRequest(wipe = true)))
|
||||
assertEquals("53414b53", BinaryEncoding.bytesToHex(G1Protocol.assetFormatRequest(wipe = false)))
|
||||
assertEquals("0000140000200000", BinaryEncoding.bytesToHex(G1Protocol.flashCrcRequest(0x140000, 8192)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun assetInfoIsRead() {
|
||||
// data 10, free 20, largest 30, 2 assets, state 4, error 0, flags 1, seq 0x01020304
|
||||
val info = G1Protocol.parseAssetInfo(hex("0a000000140000001e00000002040001" + "04030201"))
|
||||
assertNotNull(info)
|
||||
assertEquals(2, info.assets)
|
||||
assertEquals(4, info.state)
|
||||
assertTrue(info.available)
|
||||
assertFalse(info.running)
|
||||
assertEquals(0x01020304L, info.seq)
|
||||
assertEquals(null, G1Protocol.parseAssetInfo(ByteArray(19)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aStoreJobsNoticeIsRead() {
|
||||
val crc = hex("05" + "0000000000000000" + "08" + "0400" + "00001400" + "00200000" + "78563412" + "00100000")
|
||||
val notice = G1Protocol.parseStoreNotice(crc)
|
||||
assertNotNull(notice)
|
||||
assertEquals(G1Protocol.STORE_JOB_CRC, notice.job)
|
||||
assertEquals(0, notice.result)
|
||||
assertEquals(0x140000, notice.address)
|
||||
assertEquals(8192, notice.n)
|
||||
assertEquals(4096L, notice.nonErased)
|
||||
// Another notice kind, or a short one, is none.
|
||||
assertEquals(null, G1Protocol.parseStoreNotice(hex("05" + "0000000000000000" + "07" + "2a2a")))
|
||||
assertEquals(null, G1Protocol.parseStoreNotice(hex("05" + "0000000000000000" + "08" + "0300")))
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -316,6 +316,24 @@ private class Session {
|
||||
}
|
||||
|
||||
class GlassesSessionCoreTest {
|
||||
@Test fun headUpEnqueueIsG2OnlyAndPreservesPreferencesForOtherModels() {
|
||||
for (model in listOf(GlassesType.G2, GlassesType.G1, GlassesType.RAYNEO_IO)) {
|
||||
val s = Session()
|
||||
try {
|
||||
s.core.monitor.withLock {
|
||||
s.core.glassesType = model
|
||||
s.core.sessionReady = true
|
||||
s.core.headUpPreferences = 1 to 35
|
||||
s.core.enqueueHeadUpPreferencesLocked()
|
||||
val writes = s.core.pendingMessages.filter { it.kind == "head-up-control" }
|
||||
assertEquals(if (model == GlassesType.G2) 4 else 0, writes.size, "$model")
|
||||
assertEquals(1 to 35, s.core.headUpPreferences, "keep stored choices for $model")
|
||||
assertEquals(if (model == GlassesType.G2) 1 to 35 else null, s.core.headUpSent, "$model")
|
||||
}
|
||||
} finally { s.core.close() }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun headUpWritesOnlyExplicitFieldsToBothArmsAndResendsAfterReconnect() {
|
||||
val s = Session()
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import kotlin.test.*
|
||||
|
||||
/** Vectors are bytes captured from a RayNeo iO (Strix OS 1.0.5.12 / 1.0.4.12 + CFW) on 2026-11-01. */
|
||||
class RayNeoIoProtocolTest {
|
||||
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
|
||||
|
||||
private val phoneId = hex("fac582dfa91e")
|
||||
private val glassesId = hex("006a5e5f33c2")
|
||||
|
||||
@Test
|
||||
fun crcAndFrames() {
|
||||
assertEquals(0x31c3, RayNeoIoProtocol.crc16Xmodem("123456789".encodeToByteArray()))
|
||||
val payload = hex("100001")
|
||||
val frame = RayNeoIoProtocol.encodeFrame(0x1234, RayNeoIoProtocol.BUSINESS_CFW, payload)
|
||||
assertEquals(13, frame.size)
|
||||
assertContentEquals(hex("aa55000712340" + "0f0100001"), frame.copyOfRange(0, 11))
|
||||
val decoded = RayNeoIoProtocol.decodeFrame(frame)!!
|
||||
assertEquals(0x1234, decoded.messageNumber)
|
||||
assertEquals(0xf0, decoded.business)
|
||||
assertContentEquals(payload, decoded.payload)
|
||||
frame[9] = 9
|
||||
assertNull(RayNeoIoProtocol.decodeFrame(frame))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reassemblerSpansNotificationsAndSkipsJunk() {
|
||||
val a = RayNeoIoProtocol.encodeFrame(1, 15, ByteArray(300) { it.toByte() })
|
||||
val b = RayNeoIoProtocol.encodeFrame(2, 0xf0, hex("0195000001070024cf"))
|
||||
val stream = hex("0102") + a + b
|
||||
val r = RayNeoIoProtocol.FrameReassembler()
|
||||
val frames = RayNeoIoProtocol.writes(stream, 23).flatMap { r.ingest(it) }
|
||||
assertEquals(listOf(1, 2), frames.map { it.messageNumber })
|
||||
assertEquals(300, frames[0].payload.size)
|
||||
assertEquals(0, r.pendingBytes)
|
||||
// a corrupt head is skipped, the next good frame still decodes
|
||||
val bad = a.copyOf().also { it[20] = (it[20] + 1).toByte() }
|
||||
assertEquals(listOf(2), r.ingest(bad + b).map { it.messageNumber })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handshakeMatchesCapture() {
|
||||
// the Mac harness's request (iOS platform byte, name "Amoli", model "Mac")
|
||||
assertContentEquals(
|
||||
hex("11002810000101110006fac582dfa91e120005416d6f6c69130001011600066950686f6e651700034d6163"),
|
||||
RayNeoIoProtocol.versionRequest(phoneId, "Amoli", "iPhone", "Mac", RayNeoIoProtocol.PLATFORM_IOS),
|
||||
)
|
||||
val reply = RayNeoIoProtocol.parseVersionReply(
|
||||
hex("11004a10000102110006006a5e5f33c212000e5261794e656f20694f2d323232391300010514000f3030364135453546333343323232391500010518000f303036413545354633334332323239"),
|
||||
)!!
|
||||
assertContentEquals(glassesId, reply.glassesId)
|
||||
assertEquals(2, reply.protocolVersion)
|
||||
assertEquals("006A5E5F33C2229", reply.serial)
|
||||
assertFalse(reply.accountBound)
|
||||
assertContentEquals(
|
||||
hex("18002a100004875e2013110020efed651a6aacd1834e8023891eaf80ec4a25814db5222e42655b71fdd373ab96"),
|
||||
RayNeoIoProtocol.guestAuthRequest(hex("875e2013"), phoneId, glassesId),
|
||||
)
|
||||
val authReply = hex("19002a1000042316e62111002082289251b37c1ddb76694d5a4bb4e911a79ad8f2867d7379bb8125f36ae6acac")
|
||||
assertTrue(RayNeoIoProtocol.isGuestAuthReply(authReply))
|
||||
assertTrue(RayNeoIoProtocol.verifyGuestAuthReply(authReply, phoneId, glassesId))
|
||||
assertFalse(RayNeoIoProtocol.verifyGuestAuthReply(authReply, hex("fac582dfa91f"), glassesId))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun envelopes() {
|
||||
assertContentEquals(
|
||||
hex("080110011a027b7d"),
|
||||
RayNeoIoProtocol.encodeEnvelope(RayNeoIoProtocol.Envelope(RayNeoIoProtocol.OTA_VERSION, "{}")),
|
||||
)
|
||||
val status = RayNeoIoProtocol.decodeEnvelope(hex(GENERAL_STATUS))!!
|
||||
assertEquals(1, status.type)
|
||||
assertEquals(98, RayNeoIoProtocol.batteryFromLauncherJson(status.json))
|
||||
assertEquals(100, RayNeoIoProtocol.batteryFromLauncherJson("""{"cmd":"battery_change","payload":{"value":100,"mode":1}}"""))
|
||||
assertEquals(-1, RayNeoIoProtocol.batteryFromLauncherJson("""{"cmd":"screen_status","payload":{"value":1}}"""))
|
||||
val request = RayNeoIoProtocol.Envelope(1, RayNeoIoProtocol.GENERAL_STATUS_REQUEST, sequence = 300, mode = RayNeoIoProtocol.MODE_REQUEST)
|
||||
val back = RayNeoIoProtocol.decodeEnvelope(RayNeoIoProtocol.encodeEnvelope(request))!!
|
||||
assertEquals(300, back.sequence)
|
||||
assertEquals(RayNeoIoProtocol.MODE_REQUEST, back.mode)
|
||||
assertEquals(request.json, back.json)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun cfwLink() {
|
||||
assertContentEquals(hex("100001"), RayNeoIoProtocol.controlPacket(RayNeoIoProtocol.CTRL_QUERY))
|
||||
val record = ByteArray(500) { it.toByte() }
|
||||
val packets = RayNeoIoProtocol.cfwPackets(record, 0x95, 240)
|
||||
assertEquals(listOf(0x81, 0x01, 0x41), packets.map { it[0].toInt() and 255 })
|
||||
assertTrue(packets.all { it[1] == 0x95.toByte() })
|
||||
assertContentEquals(record, packets.flatMap { it.drop(2) }.toByteArray())
|
||||
assertEquals(0xc1, RayNeoIoProtocol.cfwPackets(ByteArray(5), 1)[0][0].toInt() and 255)
|
||||
|
||||
val ack = RayNeoIoProtocol.parseCfwAck(hex("0195000001070024cf"))!!
|
||||
assertFalse(ack.nack)
|
||||
assertEquals(0x95, ack.streamId)
|
||||
assertEquals(0, ack.messageId)
|
||||
assertEquals(1, ack.lens)
|
||||
assertEquals(7, ack.size)
|
||||
assertEquals(0xcf24, ack.checksum)
|
||||
assertTrue(RayNeoIoProtocol.parseCfwAck(hex("0395000002070024cf"))!!.nack)
|
||||
assertNull(RayNeoIoProtocol.parseCfwAck(hex("0195000003070024cf")))
|
||||
|
||||
// Glassly v13 IDENT, then the Faceclaw fork's with the revision string appended
|
||||
val v13 = RayNeoIoProtocol.parseIdent(hex("110d1c02dc00f00000010d007f474c4153534c594346572d494f2f31330019"))!!
|
||||
assertEquals(540, v13.width)
|
||||
assertEquals(220, v13.height)
|
||||
assertEquals(240, v13.maxChunk)
|
||||
assertEquals(13, v13.revision)
|
||||
assertEquals("GLASSLYCFW-IO/13", v13.name)
|
||||
assertFalse(v13.faceclaw)
|
||||
val fc = RayNeoIoProtocol.parseIdent(hex("110d1c02dc00f00000010d00ff474c4153534c594346572d494f2f3133001946616365636c61772f333800"))!!
|
||||
assertTrue(fc.faceclaw)
|
||||
assertEquals(38, fc.faceclawRevision)
|
||||
assertFalse(fc.brightnessControl)
|
||||
val bright = RayNeoIoProtocol.parseIdent(hex("110d1c02dc00f00000010d00ff474c4153534c594346572d494f2f3133001946616365636c61772f33380062726967687433302061" + "6c73313600"))!!
|
||||
assertEquals(listOf("bright30", "als16"), bright.features)
|
||||
assertEquals(38, bright.faceclawRevision)
|
||||
assertTrue(bright.brightnessControl)
|
||||
// a Glassly build with no display lists has no brightness control, whatever else it says
|
||||
assertFalse(RayNeoIoProtocol.Ident(540, 220, 240, 13, 0x7f, "x", -1, listOf("bright30", "als16")).brightnessControl)
|
||||
|
||||
val als = ByteArray(25)
|
||||
als[0] = 0x1f; als[1] = 65; als[2] = 76; als[3] = 1
|
||||
assertEquals(24, RayNeoIoProtocol.parseAlsReport(als)!!.size)
|
||||
assertEquals(65, RayNeoIoProtocol.parseAlsReport(als)!![0].toInt())
|
||||
assertNull(RayNeoIoProtocol.parseAlsReport(als.copyOf(24)))
|
||||
assertNull(RayNeoIoProtocol.parseAlsReport(als.copyOf().also { it[3] = 2 }))
|
||||
assertNull(RayNeoIoProtocol.parseAlsReport(als.copyOf().also { it[0] = 0x15 }))
|
||||
|
||||
assertEquals(1, RayNeoIoProtocol.parsePageState(hex("130100")))
|
||||
val g = RayNeoIoProtocol.parseGesture(hex("0703010a000000"))!!
|
||||
assertEquals(3, g.eventType)
|
||||
assertEquals(1, g.source)
|
||||
assertEquals(10L, g.tick)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun recordsShareTheG2Encoder() {
|
||||
// the G2 envelope is unchanged by the record/packet split
|
||||
val g2 = CfwTransport.frame("123456789abcdef".encodeToByteArray(), 255, 3, 23)
|
||||
assertContentEquals(hex("aa21ff0c0101f000830b0f0078c331323334862b"), g2[0])
|
||||
// an iO record carries the same flags/length/CRC header
|
||||
val t = CfwTransport(testPlatform())
|
||||
val message = ByteArray(64) { (it % 7).toByte() }
|
||||
val rec = t.encodeRecord(message, CfwTransport.BOTH)
|
||||
assertEquals(CfwTransport.BOTH or CfwTransport.COMPRESSED or CfwTransport.RESET_CONTEXT, rec[0].toInt())
|
||||
assertEquals(CfwTransport.crc(message), (rec[3].toInt() and 255) or ((rec[4].toInt() and 255) shl 8))
|
||||
assertContentEquals(message, inflateRecords(listOf(rec))[0])
|
||||
// the next record continues the same compression context
|
||||
val second = t.encodeRecord(message, CfwTransport.BOTH)
|
||||
assertEquals(CfwTransport.BOTH or CfwTransport.COMPRESSED, second[0].toInt())
|
||||
t.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun advertisement() {
|
||||
assertEquals("00:6A:5E:5F:33:C2", RayNeoIoBle.macFromManufacturerData(hex("07006a5e5f33c2130000000000000001")))
|
||||
assertNull(RayNeoIoBle.macFromManufacturerData(hex("0800")))
|
||||
assertTrue(RayNeoIoBle.matchesName("RayNeo iO-2229"))
|
||||
assertFalse(RayNeoIoBle.matchesName("Even G2_32_L_693CCB"))
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val GENERAL_STATUS = "080110011aa6037b2267656e6572616c537461747573223a7b226175746f6d617469634272696768746e657373223a66616c73652c2262617474657279223a39382c22626174745f74656d70223a33342c22626c7565746f6f746841646472657373223a2230303a36413a35453a35463a33333a4332222c226272696768746e657373223a312c226465766963654e616d65223a225261794e656f20694f2d32323239222c2269734368617267696e67223a747275652c2263686172676554797065223a302c2273637265656e537461747573223a312c2268616c6c537461747573223a302c226d6963537461747573223a302c22666f6375734d6f6465223a7b22656e61626c65223a302c22656e61626c65476c617373436c6f7365223a312c22706f6c696379223a7b226175746f223a312c22626567696e223a2230393a3030222c22656e64223a2231383a3030222c227765656b646179223a5b302c312c322c332c342c352c365d7d7d2c22707265736372697074696f6e223a7b22656e61626c65223a312c22646567726565223a222d332c302c2d322e37352c30222c227064223a223633227d7d7d"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,608 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import kotlin.concurrent.Volatile
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
private const val IO = "00:6A:5E:5F:33:C2"
|
||||
private const val RING = "FF:AA:F1:F6:7E:28"
|
||||
private val PHONE_ID = byteArrayOf(1, 2, 3, 4, 5, 6)
|
||||
|
||||
private class IoClock(private val base: ProtocolPlatform) : ProtocolPlatform by base {
|
||||
@Volatile var offsetMs = 0L
|
||||
|
||||
override fun elapsedRealtimeMs(): Long = base.elapsedRealtimeMs() + offsetMs
|
||||
}
|
||||
|
||||
private fun awaitTrue(timeoutMs: Long, condition: () -> Boolean): Boolean {
|
||||
val platform = testPlatform()
|
||||
val deadline = platform.elapsedRealtimeMs() + timeoutMs
|
||||
while (platform.elapsedRealtimeMs() < deadline) {
|
||||
if (condition()) return true
|
||||
sleepMs(10)
|
||||
}
|
||||
return condition()
|
||||
}
|
||||
|
||||
/**
|
||||
* A RayNeo iO running faceclaw-rayneo-cfw, as the phone sees it over GATT: answers the
|
||||
* handshake, guest auth, launcher status, OS version, QUERY and page controls, reassembles
|
||||
* and inflates CFW records, and ACKs each lens of every record whose CRC checks out.
|
||||
*/
|
||||
private class FakeIoGlasses(platform: ProtocolPlatform) : SessionLink {
|
||||
lateinit var core: GlassesSessionCore
|
||||
private val lock = platform.createLock()
|
||||
val glassesId = byteArrayOf(0x00, 0x6a, 0x5e, 0x5f, 0x33, 0xc2.toByte())
|
||||
/** The phone id the glasses accept; null = pairing mode (they bind to the next one). */
|
||||
@Volatile var boundTo: ByteArray? = null
|
||||
@Volatile var faceclaw = true
|
||||
/** Firmware with message 30 and the light sensor (IDENT's features string). */
|
||||
@Volatile var brightnessFirmware = false
|
||||
@Volatile var pageOpen = false
|
||||
@Volatile var hangUps = 0
|
||||
private val controlsList = ArrayList<Int>()
|
||||
private val messagesList = ArrayList<ByteArray>()
|
||||
private val launcherList = ArrayList<String>()
|
||||
val launcher: List<String> get() = lock.withLock { launcherList.toList() }
|
||||
/** Voice-channel (business 13) messages from the phone: type to JSON. */
|
||||
private val voiceList = ArrayList<Pair<Int, String>>()
|
||||
val voice: List<Pair<Int, String>> get() = lock.withLock { voiceList.toList() }
|
||||
|
||||
/** A voice-channel message from the glasses. */
|
||||
fun voiceNotify(type: Int, json: String = "{}", binary: ByteArray? = null) =
|
||||
notify(13, RayNeoIoProtocol.encodeEnvelope(RayNeoIoProtocol.Envelope(type, json, binary)))
|
||||
private val records = ArrayList<ByteArray>()
|
||||
private var current = ByteArray(0)
|
||||
private val inbound = RayNeoIoProtocol.FrameReassembler()
|
||||
private var number = 1
|
||||
|
||||
val controls: List<Int> get() = lock.withLock { controlsList.toList() }
|
||||
val messages: List<ByteArray> get() = lock.withLock { messagesList.toList() }
|
||||
/** Writes to the R1 on [RING] (characteristic, bytes), and the CCCDs the session enabled on it. */
|
||||
private val ringWritesList = ArrayList<Pair<String, ByteArray>>()
|
||||
private val ringCccdsList = ArrayList<String>()
|
||||
val ringWrites: List<Pair<String, ByteArray>> get() = lock.withLock { ringWritesList.toList() }
|
||||
val ringCccds: List<String> get() = lock.withLock { ringCccdsList.toList() }
|
||||
|
||||
/** A notification from the R1, as its link delivers it. */
|
||||
fun ringNotify(characteristicUuid: String, data: ByteArray) = core.onNotification(RING, characteristicUuid, data)
|
||||
|
||||
fun notify(business: Int, payload: ByteArray) {
|
||||
val frame = lock.withLock { RayNeoIoProtocol.encodeFrame(number++, business, payload) }
|
||||
core.onNotification(IO, RayNeoIoBle.NOTIFY_CHAR_UUID, frame)
|
||||
}
|
||||
|
||||
fun page(state: Int, reason: Int) = notify(0xf0, byteArrayOf(0x13, state.toByte(), reason.toByte()))
|
||||
|
||||
override fun connect(address: String, timeoutMs: Int): Boolean = true
|
||||
|
||||
override fun isConnected(address: String): Boolean = true
|
||||
|
||||
override fun requestHighPriority(address: String) {}
|
||||
|
||||
override fun requestMtu(address: String, mtu: Int, timeoutMs: Int): Boolean = true
|
||||
|
||||
override fun negotiatedMtu(address: String): Int = 185
|
||||
|
||||
override fun discoverServices(address: String, timeoutMs: Int): Boolean = true
|
||||
|
||||
override fun enableNotifications(address: String, characteristicUuid: String, enable: Boolean, timeoutMs: Int): Boolean {
|
||||
if (address == RING) {
|
||||
lock.withLock { ringCccdsList.add(characteristicUuid) }
|
||||
return true
|
||||
}
|
||||
return characteristicUuid == RayNeoIoBle.NOTIFY_CHAR_UUID
|
||||
}
|
||||
|
||||
override fun writeFrames(address: String, characteristicUuid: String, frames: List<ByteArray>, mode: GattWriteMode, timeoutMs: Int): Boolean {
|
||||
if (address == RING) {
|
||||
lock.withLock { for (frame in frames) ringWritesList.add(characteristicUuid to frame) }
|
||||
return true
|
||||
}
|
||||
assertEquals(RayNeoIoBle.WRITE_CHAR_UUID, characteristicUuid)
|
||||
assertTrue(frames.all { it.size <= 185 - 3 }, "writes must fit the MTU")
|
||||
val decoded = lock.withLock { frames.flatMap { inbound.ingest(it) } }
|
||||
for (frame in decoded) handle(frame)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun handle(frame: RayNeoIoProtocol.Frame) {
|
||||
val p = frame.payload
|
||||
when (frame.business) {
|
||||
0x10 -> {
|
||||
val tlvs = RayNeoIoProtocol.decodeTlvs(p)!!
|
||||
val version = tlvs.firstOrNull { it.tag == 0x11 }
|
||||
val auth = tlvs.firstOrNull { it.tag == 0x18 }
|
||||
if (version != null) {
|
||||
val phone = RayNeoIoProtocol.decodeTlvs(version.value)!!.first { it.tag == 0x11 }.value
|
||||
val bound = boundTo
|
||||
if (bound != null && !bound.contentEquals(phone)) {
|
||||
hangUps++
|
||||
core.onConnectionStateChange(IO, false)
|
||||
return
|
||||
}
|
||||
notify(0x10, RayNeoIoProtocol.tlv(0x11, RayNeoIoProtocol.tlv(0x10, byteArrayOf(2)) +
|
||||
RayNeoIoProtocol.tlv(0x11, glassesId) + RayNeoIoProtocol.tlv(0x14, "006A5E5F33C2229".encodeToByteArray())))
|
||||
} else if (auth != null) {
|
||||
val fields = RayNeoIoProtocol.decodeTlvs(auth.value)!!
|
||||
val phoneRandom = fields.first { it.tag == 0x10 }.value
|
||||
val phone = PHONE_ID
|
||||
assertTrue(RayNeoIoProtocol.authProof(phoneRandom, phone, glassesId).contentEquals(fields.first { it.tag == 0x11 }.value))
|
||||
boundTo = phone
|
||||
val random = byteArrayOf(9, 8, 7, 6)
|
||||
notify(0x10, RayNeoIoProtocol.tlv(0x19, RayNeoIoProtocol.tlv(0x10, random) +
|
||||
RayNeoIoProtocol.tlv(0x11, RayNeoIoProtocol.authProof(random, phone, glassesId))))
|
||||
}
|
||||
}
|
||||
15 -> {
|
||||
lock.withLock { launcherList.add(RayNeoIoProtocol.decodeEnvelope(p)!!.json) }
|
||||
notify(15, RayNeoIoProtocol.encodeEnvelope(RayNeoIoProtocol.Envelope(1,
|
||||
"""{"generalStatus":{"battery":77,"isCharging":false}}""", sequence = RayNeoIoProtocol.decodeEnvelope(p)!!.sequence, mode = 2)))
|
||||
}
|
||||
9 -> notify(9, RayNeoIoProtocol.encodeEnvelope(RayNeoIoProtocol.Envelope(1, """{"OsVersion":"Strix OS 1.0.4.12"}""")))
|
||||
13 -> {
|
||||
val envelope = RayNeoIoProtocol.decodeEnvelope(p)!!
|
||||
lock.withLock { voiceList.add(envelope.type to envelope.json) }
|
||||
}
|
||||
0xf0 -> cfw(p)
|
||||
}
|
||||
}
|
||||
|
||||
private fun cfw(p: ByteArray) {
|
||||
val opt = p[0].toInt() and 255
|
||||
val stream = p[1].toInt() and 255
|
||||
if (opt and RayNeoIoProtocol.OPT_CONTROL != 0) {
|
||||
val ctrl = p[2].toInt() and 255
|
||||
lock.withLock { controlsList.add(ctrl) }
|
||||
when (ctrl) {
|
||||
RayNeoIoProtocol.CTRL_QUERY -> if (faceclaw) notify(0xf0, ident())
|
||||
RayNeoIoProtocol.CTRL_PAGE_OPEN, RayNeoIoProtocol.CTRL_KEEPALIVE -> { pageOpen = true; page(1, 0) }
|
||||
RayNeoIoProtocol.CTRL_PAGE_CLOSE -> { pageOpen = false; page(0, 0) }
|
||||
}
|
||||
return
|
||||
}
|
||||
val complete = lock.withLock {
|
||||
if (opt and RayNeoIoProtocol.OPT_RESET != 0) current = ByteArray(0)
|
||||
current += p.copyOfRange(2, p.size)
|
||||
val len = if (current.size >= 5) (current[1].toInt() and 255) or ((current[2].toInt() and 255) shl 8) else -1
|
||||
if (len >= 0 && current.size == 5 + len) current.also { records.add(it); current = ByteArray(0) } else null
|
||||
} ?: return
|
||||
val message = lock.withLock { inflateRecords(records).last() }
|
||||
val crc = (complete[3].toInt() and 255) or ((complete[4].toInt() and 255) shl 8)
|
||||
val type = message[0].toInt() and 255
|
||||
val ok = pageOpen && CfwTransport.crc(message) == crc &&
|
||||
(ioSupportsCfwType(type) || (brightnessFirmware && (type == CFW_MSG_BRIGHTNESS || type == CFW_MSG_AMBIENT_LIGHT)))
|
||||
if (ok) lock.withLock { messagesList.add(message) }
|
||||
for (lens in 1..2) {
|
||||
notify(0xf0, byteArrayOf(if (ok) 1 else 3, stream.toByte(), 0, 0, lens.toByte(),
|
||||
message.size.toByte(), (message.size ushr 8).toByte(), crc.toByte(), (crc ushr 8).toByte()))
|
||||
}
|
||||
}
|
||||
|
||||
private fun ident(): ByteArray {
|
||||
val name = "GLASSLYCFW-IO/13".encodeToByteArray()
|
||||
return byteArrayOf(0x11, 13, 0x1c, 0x02, 0xdc.toByte(), 0x00, 0xf0.toByte(), 0x00, 0x00, 0x01, 0x0d, 0x00, 0xff.toByte()) +
|
||||
name + byteArrayOf(0, 25) + "Faceclaw/38".encodeToByteArray() + byteArrayOf(0) +
|
||||
(if (brightnessFirmware) "bright30 als16".encodeToByteArray() + byteArrayOf(0) else ByteArray(0))
|
||||
}
|
||||
|
||||
/** RPL_ALS as the firmware sends it: a poll of [tenths] of a lux from a healthy sensor. */
|
||||
fun alsPoll(tenths: Int) {
|
||||
val report = ByteArray(25)
|
||||
report[0] = 0x1f
|
||||
report[1] = 65
|
||||
report[2] = 76
|
||||
report[3] = 1
|
||||
report[4] = 2 // poll
|
||||
report[5] = 0x0b // opened, passive, read ok
|
||||
report[6] = 3
|
||||
for (i in 0..3) report[7 + i] = (tenths ushr (8 * i)).toByte()
|
||||
notify(0xf0, report)
|
||||
}
|
||||
|
||||
override fun disconnect(address: String) {}
|
||||
|
||||
override fun close() {}
|
||||
|
||||
override fun isBonded(address: String): Boolean = false
|
||||
|
||||
override fun prepareBenchmarkLink(address: String, mode: Int) {}
|
||||
|
||||
override fun recordDisplayFrameSent() {}
|
||||
}
|
||||
|
||||
private class IoListener : FaceclawBleCommunicatorListener {
|
||||
val phases = ArrayList<String>()
|
||||
@Volatile var lastStatus = ""
|
||||
val events = ArrayList<String>()
|
||||
val batteries = ArrayList<String>()
|
||||
val ringBatteries = ArrayList<String>()
|
||||
val firmware = ArrayList<String>()
|
||||
|
||||
override fun onStateChange(phase: String?, status: String?) {
|
||||
phases.add(phase ?: "")
|
||||
lastStatus = status ?: ""
|
||||
}
|
||||
|
||||
override fun onRingEvent(kind: String?, containerName: String?, eventType: Int, eventSource: Int, systemExitReasonCode: Int, frameId: Int, ringTick: Long, ringType: Int, ringAux: Int, ringSpeed: Int) {
|
||||
events.add("$kind:$eventType:$eventSource")
|
||||
}
|
||||
|
||||
override fun onBatteryState(headsetBattery: Int, headsetCharging: Int, ringBattery: Int, ringCharging: Int) {
|
||||
batteries.add("$headsetBattery/$headsetCharging")
|
||||
if (ringBattery >= 0) ringBatteries.add("$ringBattery/$ringCharging")
|
||||
}
|
||||
|
||||
override fun onSilentMode(silent: Boolean) {}
|
||||
|
||||
override fun onWearState(wearing: Boolean) {}
|
||||
|
||||
override fun onPhoneLockState(locked: Boolean) {}
|
||||
|
||||
override fun onCaseState(caseBattery: Int, caseCharging: Int, caseDocked: Boolean) {}
|
||||
|
||||
override fun onEvenAppConflict(message: String?) {}
|
||||
|
||||
override fun onFrameMetrics(paintMs: Int, transmitMs: Int, tileCount: Int) {}
|
||||
|
||||
override fun onFrameFinished(frameId: Int, outcome: String?) {}
|
||||
|
||||
override fun onFirmwareInfo(leftVersion: String?, rightVersion: String?, extension: String?) {
|
||||
firmware.add("$leftVersion|$extension")
|
||||
}
|
||||
}
|
||||
|
||||
/** An iO session; with [ring], also the phone's own link to an R1 in the glasses role (Direct). */
|
||||
private class IoSession(ring: String = "") {
|
||||
val platform = IoClock(testPlatform())
|
||||
val glasses = FakeIoGlasses(platform)
|
||||
private val host = object : SessionHost {
|
||||
private val lock = platform.createLock()
|
||||
private val lines = ArrayList<String>()
|
||||
private var done: Latch? = null
|
||||
|
||||
fun logs(): List<String> = lock.withLock { lines.toList() }
|
||||
|
||||
override fun postToMain(action: () -> Unit) = action()
|
||||
|
||||
override fun currentThreadDispatcher(): SessionDispatcher = SessionDispatcher { it() }
|
||||
|
||||
override fun isPhoneLocked(): Boolean = false
|
||||
|
||||
override fun setScreenWakeLock(on: Boolean) {}
|
||||
|
||||
override fun isEvenAppActive(): Boolean = false
|
||||
|
||||
override fun startWorker(body: () -> Unit) {
|
||||
val latch = Latch(1, platform)
|
||||
done = latch
|
||||
startThread("io-test-session", true) {
|
||||
try {
|
||||
body()
|
||||
} finally {
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun joinWorker(timeoutMs: Long) {
|
||||
done?.await(timeoutMs)
|
||||
}
|
||||
|
||||
override fun log(level: SessionLogLevel, tag: String, message: String, error: Throwable?) {
|
||||
lock.withLock { lines.add("$level $tag: $message") }
|
||||
}
|
||||
}
|
||||
val listener = IoListener()
|
||||
val core = GlassesSessionCore(glasses, host, FrameTimingsCore(platform), platform, IO, IO, ring)
|
||||
|
||||
init {
|
||||
glasses.core = core
|
||||
core.setListener(listener)
|
||||
core.setRequiredFirmwareRevision(38)
|
||||
core.useRayNeoIo(PHONE_ID, "Pixel", "Google", "Pixel 11")
|
||||
if (ring.isNotEmpty()) core.setDirectRingRole("glasses")
|
||||
}
|
||||
|
||||
fun pageUp(): Boolean = core.monitor.withLock { core.sessionReady && core.fixedLayoutCreated }
|
||||
|
||||
fun displayedMatchesDesired(): Boolean = core.monitor.withLock {
|
||||
core.desiredTilesLock.locked { core.desiredFingerprint.isNotEmpty() && core.desiredFingerprint == core.displayedFingerprint }
|
||||
}
|
||||
|
||||
fun submitFrame(value: Byte, frameId: Int) {
|
||||
val pixels = ByteArray(64 * 32) { if (it % 7 == 0) value else 0 }
|
||||
core.submitSurfaceFrame(ArrayByteReader(pixels), "s", 0, 0, 64, 32, "content-$value", 0, frameId, null)
|
||||
}
|
||||
|
||||
fun tail(): String = host.logs().takeLast(25).joinToString("\n")
|
||||
}
|
||||
|
||||
class RayNeoIoSessionTest {
|
||||
@Test
|
||||
fun connectsAuthenticatesOpensThePageAndPresentsFrames() {
|
||||
val s = IoSession()
|
||||
s.core.configureBrightness(false, 70, 2, 100, "0:0,1000:100", 280)
|
||||
s.core.configureCompositorScreen(540, 220)
|
||||
s.core.configureSurface("s", 0, 0, 64, 32, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
|
||||
try {
|
||||
assertTrue(s.core.start())
|
||||
assertTrue(awaitTrue(5_000) { s.pageUp() }, "page never opened:\n" + s.tail())
|
||||
assertTrue(s.core.isRayNeoIo())
|
||||
assertTrue(s.listener.firmware.contains("Strix OS 1.0.4.12|Faceclaw/38"), s.listener.firmware.toString())
|
||||
assertTrue(awaitTrue(2_000) { s.listener.batteries.contains("77/0") }, s.listener.batteries.toString())
|
||||
assertEquals(listOf(RayNeoIoProtocol.CTRL_QUERY, RayNeoIoProtocol.CTRL_PAGE_OPEN), s.glasses.controls.take(2))
|
||||
|
||||
s.submitFrame(0x7f, 1)
|
||||
assertTrue(awaitTrue(5_000) { s.displayedMatchesDesired() }, "frame never displayed:\n" + s.tail())
|
||||
val types = s.glasses.messages.map { it[0].toInt() and 255 }
|
||||
assertTrue(types.contains(CFW_MSG_PRESENT), types.toString())
|
||||
// nothing G2-only (brightness 30, ENTER_EVENHUB 31, debug flags 7, ...) reaches the iO
|
||||
assertTrue(types.all { ioSupportsCfwType(it) }, types.toString())
|
||||
// a visible frame wakes the screen through the launcher's brightness (70% -> level 6)
|
||||
assertTrue(awaitTrue(3_000) { s.glasses.launcher.any { it.contains("brightness_change") && it.contains("\"value\":6") } },
|
||||
s.glasses.launcher.toString())
|
||||
|
||||
// a second, different frame goes out as an update
|
||||
val before = s.glasses.messages.size
|
||||
s.submitFrame(0x30, 2)
|
||||
assertTrue(awaitTrue(5_000) { s.displayedMatchesDesired() && s.glasses.messages.size > before })
|
||||
} finally {
|
||||
s.core.close()
|
||||
}
|
||||
// disconnect closes the page so the glasses go back to their own UI at once
|
||||
assertEquals(RayNeoIoProtocol.CTRL_PAGE_CLOSE, s.glasses.controls.last())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun firmwareWithBrightnessControlGetsTheG2Messages() {
|
||||
val s = IoSession()
|
||||
s.glasses.brightnessFirmware = true
|
||||
s.core.configureBrightness(false, 70, 2, 100, "0:0,1000:100", 280)
|
||||
s.core.configureCompositorScreen(540, 220)
|
||||
s.core.configureSurface("s", 0, 0, 64, 32, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
|
||||
val reportLock = s.platform.createLock()
|
||||
val reports = ArrayList<ByteArray>()
|
||||
s.core.addAmbientLightListener(object : FaceclawAmbientLightListener {
|
||||
override fun onAmbientLight(body: ByteArray?) { reportLock.withLock { reports.add(body!!) } }
|
||||
})
|
||||
fun ofType(type: Int) = s.glasses.messages.filter { (it[0].toInt() and 255) == type }
|
||||
try {
|
||||
assertTrue(s.core.start())
|
||||
assertTrue(awaitTrue(5_000) { s.pageUp() }, "page never opened:\n" + s.tail())
|
||||
s.submitFrame(0x7f, 1)
|
||||
assertTrue(awaitTrue(5_000) { s.displayedMatchesDesired() }, "frame never displayed:\n" + s.tail())
|
||||
|
||||
// visible at 70%, fading over the configured 280 ms, ahead of the frame it fades in
|
||||
val wake = byteArrayOf(30, 1, 70, 1, 0x18, 0x01)
|
||||
assertTrue(awaitTrue(3_000) { ofType(CFW_MSG_BRIGHTNESS).isNotEmpty() }, s.tail())
|
||||
assertTrue(ofType(CFW_MSG_BRIGHTNESS).first().contentEquals(wake))
|
||||
val order = s.glasses.messages.map { it[0].toInt() and 255 }
|
||||
assertTrue(order.indexOf(CFW_MSG_BRIGHTNESS) < order.indexOf(CFW_MSG_PRESENT), order.toString())
|
||||
// the launcher's command writes preferences and loses to stock auto: not used
|
||||
assertTrue(s.glasses.launcher.none { "brightness_change" in it }, s.glasses.launcher.toString())
|
||||
|
||||
// the light sensor, at the manual rate; the iO needs telling only once
|
||||
assertTrue(awaitTrue(3_000) { ofType(CFW_MSG_AMBIENT_LIGHT).isNotEmpty() }, s.tail())
|
||||
val poll = ofType(CFW_MSG_AMBIENT_LIGHT).first()
|
||||
assertEquals(listOf(16, 1), poll.take(2).map { it.toInt() })
|
||||
assertEquals(5000, (poll[3].toInt() and 255) or ((poll[4].toInt() and 255) shl 8))
|
||||
|
||||
// each 5 s the same command, as the screen keepalive
|
||||
val sent = ofType(CFW_MSG_BRIGHTNESS).size
|
||||
s.platform.offsetMs += IoTimings.SCREEN_REFRESH_MS + 1
|
||||
assertTrue(awaitTrue(3_000) { ofType(CFW_MSG_BRIGHTNESS).size > sent }, s.tail())
|
||||
assertTrue(ofType(CFW_MSG_BRIGHTNESS).last().let { it[2].toInt() == 70 && it[3].toInt() == 1 })
|
||||
assertEquals(1, ofType(CFW_MSG_AMBIENT_LIGHT).size)
|
||||
|
||||
// Auto: reports reach the policy and listeners, the sample rate follows, a target goes out
|
||||
s.core.configureBrightness(true, 70, 20, 100, "0:0,100:100", 280)
|
||||
assertTrue(awaitTrue(3_000) { ofType(CFW_MSG_AMBIENT_LIGHT).size == 2 }, s.tail())
|
||||
assertEquals(500, ofType(CFW_MSG_AMBIENT_LIGHT).last().let { (it[3].toInt() and 255) or ((it[4].toInt() and 255) shl 8) })
|
||||
s.glasses.alsPoll(1000) // 100 lux, the curve's top
|
||||
assertTrue(awaitTrue(3_000) { ofType(CFW_MSG_BRIGHTNESS).last()[2].toInt() == 100 }, s.tail())
|
||||
assertTrue(awaitTrue(1_000) { reportLock.withLock { reports.isNotEmpty() } })
|
||||
assertEquals(65, reportLock.withLock { reports.first()[0].toInt() })
|
||||
|
||||
// A request dropped with the queue before it was written goes out again
|
||||
s.core.monitor.withLock { s.core.clearAllMessagesLocked("test") }
|
||||
val queued = ofType(CFW_MSG_AMBIENT_LIGHT).size
|
||||
s.glasses.alsPoll(1000)
|
||||
assertTrue(awaitTrue(3_000) { ofType(CFW_MSG_AMBIENT_LIGHT).size > queued }, s.tail())
|
||||
|
||||
// A reopened page starts over: the firmware gave brightness back when it closed
|
||||
val before = ofType(CFW_MSG_AMBIENT_LIGHT).size
|
||||
s.glasses.pageOpen = false
|
||||
s.glasses.page(0, 3)
|
||||
assertTrue(awaitTrue(5_000) { s.glasses.pageOpen && s.pageUp() }, s.tail())
|
||||
s.submitFrame(0x30, 2)
|
||||
assertTrue(awaitTrue(5_000) { ofType(CFW_MSG_AMBIENT_LIGHT).size > before }, s.tail())
|
||||
} finally {
|
||||
s.core.close()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun refusalAsksForPairingModeAndConnectsOnceItIsOn() {
|
||||
val s = IoSession()
|
||||
s.glasses.boundTo = byteArrayOf(9, 9, 9, 9, 9, 9)
|
||||
try {
|
||||
assertTrue(s.core.start())
|
||||
assertTrue(awaitTrue(5_000) { s.glasses.hangUps >= 1 && s.listener.lastStatus.contains("pairing mode") },
|
||||
"no pairing-mode prompt:\n" + s.tail())
|
||||
assertFalse(s.pageUp())
|
||||
s.glasses.boundTo = null // the wearer held the button
|
||||
s.platform.offsetMs += 5_000
|
||||
s.core.interruptibleSleep.interrupt()
|
||||
assertTrue(awaitTrue(5_000) { s.pageUp() }, "never connected after pairing mode:\n" + s.tail())
|
||||
assertTrue(s.glasses.boundTo!!.contentEquals(PHONE_ID))
|
||||
} finally {
|
||||
s.core.close()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stockFirmwareIsIncompatible() {
|
||||
val s = IoSession()
|
||||
s.glasses.faceclaw = false
|
||||
try {
|
||||
assertTrue(s.core.start())
|
||||
assertTrue(awaitTrue(8_000) { s.listener.phases.contains("incompatible-firmware") }, "not halted:\n" + s.tail())
|
||||
assertTrue(s.listener.firmware.contains("Strix OS 1.0.4.12|"))
|
||||
assertFalse(s.glasses.controls.contains(RayNeoIoProtocol.CTRL_PAGE_OPEN))
|
||||
} finally {
|
||||
s.core.close()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gesturesPageLossAndKeepalive() {
|
||||
val s = IoSession()
|
||||
s.core.configureCompositorScreen(540, 220)
|
||||
try {
|
||||
assertTrue(s.core.start())
|
||||
assertTrue(awaitTrue(5_000) { s.pageUp() }, s.tail())
|
||||
// taps/crown arrive as G2 sys-events from the right temple; head up wakes; head down is dropped
|
||||
s.glasses.notify(0xf0, byteArrayOf(7, 3, 1, 0, 0, 0, 0))
|
||||
s.glasses.notify(0xf0, byteArrayOf(7, 1, 0, 0, 0, 0, 0))
|
||||
s.glasses.notify(0xf0, byteArrayOf(7, 12, 2, 0, 0, 0, 0))
|
||||
s.glasses.notify(0xf0, byteArrayOf(7, 15, 2, 0, 0, 0, 0))
|
||||
assertEquals(listOf("sys-event:3:1", "sys-event:1:1", "display-wake:12:1"), s.listener.events)
|
||||
|
||||
// the lease ran out on the glasses: the session reopens the page
|
||||
s.glasses.pageOpen = false
|
||||
s.glasses.page(0, 3)
|
||||
assertFalse(s.pageUp())
|
||||
s.platform.offsetMs += 4_000
|
||||
s.core.interruptibleSleep.interrupt()
|
||||
assertTrue(awaitTrue(5_000) { s.pageUp() }, "page not reopened:\n" + s.tail())
|
||||
|
||||
// keepalives well inside the 120 s lease
|
||||
val keepalives = s.glasses.controls.count { it == RayNeoIoProtocol.CTRL_KEEPALIVE }
|
||||
s.platform.offsetMs += 31_000
|
||||
s.core.interruptibleSleep.interrupt()
|
||||
assertTrue(awaitTrue(5_000) { s.glasses.controls.count { it == RayNeoIoProtocol.CTRL_KEEPALIVE } > keepalives })
|
||||
|
||||
// the wearer closed it: stay closed until they touch the glasses again
|
||||
s.glasses.pageOpen = false
|
||||
s.glasses.page(0, 4)
|
||||
s.platform.offsetMs += 4_000
|
||||
s.core.interruptibleSleep.interrupt()
|
||||
sleepMs(300)
|
||||
assertFalse(s.pageUp())
|
||||
s.glasses.notify(0xf0, byteArrayOf(7, 0, 1, 0, 0, 0, 0))
|
||||
s.core.interruptibleSleep.interrupt()
|
||||
assertTrue(awaitTrue(5_000) { s.pageUp() }, "touch did not reopen:\n" + s.tail())
|
||||
} finally {
|
||||
s.core.close()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anR1BesideTheIoIsTheSessionsOwnRingInput() {
|
||||
val s = IoSession(RING)
|
||||
s.core.configureCompositorScreen(540, 220)
|
||||
try {
|
||||
assertTrue(s.core.start())
|
||||
assertTrue(awaitTrue(5_000) { s.pageUp() }, s.tail())
|
||||
// The phone takes the ring's glasses role itself: legacy CCCD, the glasses
|
||||
// pair-auth, then the touch source on, all on the ring's link.
|
||||
assertTrue(awaitTrue(5_000) { s.glasses.ringWrites.size >= 2 }, "ring setup not sent:\n" + s.tail())
|
||||
assertTrue(BleProtocol.R1_LEGACY_NOTIFY_CHAR_UUID in s.glasses.ringCccds)
|
||||
val (authChar, auth) = s.glasses.ringWrites[0]
|
||||
assertEquals(BleProtocol.R1_LEGACY_WRITE_CHAR_UUID, authChar)
|
||||
assertTrue(auth.contentEquals(RingProtocol.LEGACY_GLASSES_PAIR_AUTH))
|
||||
|
||||
// Its battery and gestures reach the listener as they do beside a G2,
|
||||
// not the iO's protocol parser.
|
||||
s.glasses.ringNotify(BleProtocol.R1_LEGACY_NOTIFY_CHAR_UUID, byteArrayOf(0x00, 0x09, 0x8b.toByte(), 0x00, 64, 1))
|
||||
assertTrue(awaitTrue(2_000) { "64/1" in s.listener.ringBatteries }, s.listener.ringBatteries.toString())
|
||||
val swipe = byteArrayOf(0x00, 0x09, 0x61, 0x00, 0x04, 0x35, 0x00, 0x09, 0xcc.toByte(), 0x00, 0x00)
|
||||
s.glasses.ringNotify(BleProtocol.R1_LEGACY_NOTIFY_CHAR_UUID, swipe)
|
||||
assertTrue(awaitTrue(2_000) { s.listener.events.isNotEmpty() }, s.tail())
|
||||
val expected = FaceclawRingEventDecoder.decode(swipe)!!.event
|
||||
assertEquals("${expected.kind}:${expected.eventType}:${expected.eventSource}", s.listener.events.single())
|
||||
|
||||
// The wearer closed the page: a ring gesture takes it back, as a temple touch does.
|
||||
s.glasses.pageOpen = false
|
||||
s.glasses.page(0, 4)
|
||||
s.platform.offsetMs += 4_000
|
||||
s.core.interruptibleSleep.interrupt()
|
||||
sleepMs(300)
|
||||
assertFalse(s.pageUp())
|
||||
s.glasses.ringNotify(BleProtocol.R1_LEGACY_NOTIFY_CHAR_UUID, byteArrayOf(0x00, 0x09, 0x61, 0x00, 0x01, 0x00, 0x00, 0x10, 0xcc.toByte(), 0x00, 0x00))
|
||||
s.core.interruptibleSleep.interrupt()
|
||||
assertTrue(awaitTrue(5_000) { s.pageUp() }, "ring input did not reopen:\n" + s.tail())
|
||||
} finally {
|
||||
s.core.close()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theWakeWordAndTheMicStream() {
|
||||
val s = IoSession()
|
||||
s.core.configureCompositorScreen(540, 220)
|
||||
val lock = s.platform.createLock()
|
||||
val packets = ArrayList<ByteArray>()
|
||||
val listener = object : FaceclawAudioPacketListener {
|
||||
override fun onAudioPacket(data: ByteArray?, arm: String?, arrivalMs: Long) {
|
||||
lock.withLock { packets.add(data!!) }
|
||||
}
|
||||
}
|
||||
val count = { lock.withLock { packets.size } }
|
||||
fun sent(type: Int, json: String) = s.glasses.voice.count { it == type to json }
|
||||
val start = """{"rc":1}"""
|
||||
val stop = """{"rc":2}"""
|
||||
try {
|
||||
assertTrue(s.core.start())
|
||||
assertTrue(awaitTrue(5_000) { s.pageUp() }, s.tail())
|
||||
|
||||
// "Hey RayNeo" goes to Faceclaw: the launcher's switch on, then each wake ends the
|
||||
// stock session (declined, then aborted) and arrives as the G2's EVEN_AI_WAKE_UP.
|
||||
s.core.setVoiceWakeEnabled(true)
|
||||
// The firmware reads the switch from "mode", not "value".
|
||||
assertTrue(awaitTrue(3_000) { s.glasses.launcher.any { "set_ai_voice_wakeup" in it && "\"mode\":1" in it } }, s.tail())
|
||||
s.glasses.voiceNotify(RayNeoIoProtocol.VOICE_WAKE, """{"rc":2,"mode":2,"linkType":0}""")
|
||||
assertTrue(awaitTrue(2_000) { "even-ai:${BleProtocol.EVEN_AI_STATUS_WAKE_UP}:0" in s.listener.events }, s.listener.events.toString())
|
||||
// The same phrase's second-stage wake is not a second wake.
|
||||
s.glasses.voiceNotify(RayNeoIoProtocol.VOICE_WAKE, """{"rc":2,"mode":3,"linkType":0}""")
|
||||
sleepMs(200)
|
||||
assertEquals(1, s.listener.events.count { it.startsWith("even-ai:") })
|
||||
assertTrue(awaitTrue(2_000) {
|
||||
sent(RayNeoIoProtocol.VOICE_RC, stop) >= 1 && sent(RayNeoIoProtocol.VOICE_ABORT, start) >= 1
|
||||
}, s.glasses.voice.toString())
|
||||
|
||||
// The mic: capture opens the remote stream, its Opus packets go to the listener as
|
||||
// they came, and stopping closes it.
|
||||
assertTrue(s.core.startG2AudioCapture(listener))
|
||||
assertTrue(awaitTrue(2_000) { sent(RayNeoIoProtocol.VOICE_STREAM_CONTROL, start) == 1 }, s.tail())
|
||||
s.glasses.voiceNotify(RayNeoIoProtocol.VOICE_STREAM_AUDIO, binary = byteArrayOf(0x78, 1, 2, 3))
|
||||
assertTrue(awaitTrue(2_000) { count() == 1 })
|
||||
assertTrue(lock.withLock { packets[0] }.contentEquals(byteArrayOf(0x78, 1, 2, 3)))
|
||||
assertTrue(s.core.isAudioCaptureActive())
|
||||
// A voice session that took the recorder ended: the stream is asked for again.
|
||||
s.glasses.voiceNotify(RayNeoIoProtocol.VOICE_EXITED)
|
||||
assertTrue(awaitTrue(2_000) { sent(RayNeoIoProtocol.VOICE_STREAM_CONTROL, start) == 2 }, s.tail())
|
||||
s.core.stopG2AudioCapture()
|
||||
assertTrue(awaitTrue(2_000) { sent(RayNeoIoProtocol.VOICE_STREAM_CONTROL, stop) == 1 }, s.tail())
|
||||
assertFalse(s.core.isAudioCaptureActive())
|
||||
s.glasses.voiceNotify(RayNeoIoProtocol.VOICE_STREAM_AUDIO, binary = byteArrayOf(9))
|
||||
sleepMs(200)
|
||||
assertEquals(1, count())
|
||||
|
||||
// With the wake action off: the switch follows, and a wake is ended but not reported.
|
||||
s.core.setVoiceWakeEnabled(false)
|
||||
assertTrue(awaitTrue(3_000) { s.glasses.launcher.any { "set_ai_voice_wakeup" in it && "\"mode\":0" in it } }, s.tail())
|
||||
val events = s.listener.events.size
|
||||
val aborts = sent(RayNeoIoProtocol.VOICE_ABORT, start)
|
||||
s.platform.offsetMs += 5_000
|
||||
s.glasses.voiceNotify(RayNeoIoProtocol.VOICE_WAKE)
|
||||
assertTrue(awaitTrue(2_000) { sent(RayNeoIoProtocol.VOICE_ABORT, start) > aborts }, s.glasses.voice.toString())
|
||||
assertEquals(events, s.listener.events.size)
|
||||
} finally {
|
||||
s.core.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user