mirror of
https://github.com/Dasemu/NavFrame.git
synced 2026-11-26 15:26:05 +00:00
Initial public NavFrame release with global regional package pipeline
This commit is contained in:
commit
d863f2b940
143 files changed
+17906
No files matched your search
@@ -0,0 +1,19 @@
|
||||
plugins {
|
||||
id("com.android.library")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
}
|
||||
android {
|
||||
namespace = "dev.navframe.navilite"
|
||||
compileSdk = 36
|
||||
defaultConfig { minSdk = 26 }
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
kotlinOptions { jvmTarget = "17" }
|
||||
}
|
||||
dependencies {
|
||||
api(project(":core"))
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
|
||||
</manifest>
|
||||
@@ -0,0 +1,90 @@
|
||||
/* Adapted from Pillion 6647af22f035ad74dc98f0e2a29e0c8a769a1caa.
|
||||
* Required Notice: Copyright 2026 the Pillion authors
|
||||
* PolyForm Noncommercial 1.0.0; see third_party/pillion/LICENSE.md. */
|
||||
package dev.navframe.navilite
|
||||
|
||||
import java.io.EOFException
|
||||
import java.io.InputStream
|
||||
|
||||
internal data class NaviLitePacket(val service: Int, val payload: ByteArray)
|
||||
|
||||
internal object NaviLiteCodec {
|
||||
const val MAX_PAYLOAD = 1024 * 1024
|
||||
private val magic = byteArrayOf(0x6e, 0x41, 0x6c, 0x40)
|
||||
|
||||
fun crc(bytes: ByteArray): Int {
|
||||
var result = -1
|
||||
for (byte in bytes) {
|
||||
result = result xor ((byte.toInt() and 255) shl 24)
|
||||
repeat(8) {
|
||||
result = if (result < 0) (result shl 1) xor 0x04c11db7 else result shl 1
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
fun packet(service: Int, pointer: Boolean, payload: ByteArray): ByteArray {
|
||||
require(service in 0..255 && payload.size <= MAX_PAYLOAD)
|
||||
val out = ByteArray(16 + payload.size)
|
||||
magic.copyInto(out)
|
||||
out[4] = 1
|
||||
out[5] = 6
|
||||
out[6] = service.toByte()
|
||||
putInt(out, 7, payload.size)
|
||||
out[11] = if (pointer) 1 else 0
|
||||
payload.copyInto(out, 16)
|
||||
putInt(out, 12, crc(out.copyOfRange(0, 12) + payload))
|
||||
return out
|
||||
}
|
||||
|
||||
fun read(input: InputStream): NaviLitePacket {
|
||||
// Resynchronize on the four-byte magic without trusting stream read boundaries.
|
||||
var matched = 0
|
||||
while (matched < magic.size) {
|
||||
val byte = input.read()
|
||||
if (byte < 0) throw EOFException("NaviLite connection closed")
|
||||
matched = if (byte == (magic[matched].toInt() and 255)) matched + 1
|
||||
else if (byte == (magic[0].toInt() and 255)) 1 else 0
|
||||
}
|
||||
val header = ByteArray(16)
|
||||
magic.copyInto(header)
|
||||
readFully(input, header, 4, 12)
|
||||
check(header[4].toInt() == 1) { "Unsupported NaviLite version" }
|
||||
check(header[11].toInt() in 0..1) { "Invalid payload data type" }
|
||||
val length = getInt(header, 7).toLong() and 0xffffffffL
|
||||
check(length <= MAX_PAYLOAD) { "NaviLite payload exceeds receive limit" }
|
||||
val payload = ByteArray(length.toInt())
|
||||
readFully(input, payload, 0, payload.size)
|
||||
check(getInt(header, 12) == crc(header.copyOfRange(0, 12) + payload)) { "NaviLite CRC mismatch" }
|
||||
return NaviLitePacket(header[6].toInt() and 255, payload)
|
||||
}
|
||||
|
||||
fun nonce(payload: ByteArray): ByteArray {
|
||||
require(payload.size >= 4) { "Incomplete NaviLite challenge" }
|
||||
return ByteArray(4) { (payload[payload.size - 4 + it].toInt() xor 0x0a).toByte() }
|
||||
}
|
||||
|
||||
fun image(jpeg: ByteArray, sequence: Int): ByteArray {
|
||||
require(jpeg.size <= MAX_PAYLOAD - 3)
|
||||
return byteArrayOf(3, sequence.toByte(), (sequence ushr 8).toByte()) + jpeg
|
||||
}
|
||||
|
||||
private fun putInt(bytes: ByteArray, offset: Int, value: Int) {
|
||||
repeat(4) { bytes[offset + it] = (value ushr (8 * it)).toByte() }
|
||||
}
|
||||
private fun getInt(bytes: ByteArray, offset: Int): Int =
|
||||
(0..3).fold(0) { value, i -> value or ((bytes[offset + i].toInt() and 255) shl (8 * i)) }
|
||||
|
||||
private fun readFully(input: InputStream, bytes: ByteArray, offset: Int, count: Int) {
|
||||
var read = 0
|
||||
while (read < count) {
|
||||
val n = input.read(bytes, offset + read, count - read)
|
||||
if (n < 0) throw EOFException("Incomplete NaviLite packet")
|
||||
if (n == 0) {
|
||||
val byte = input.read()
|
||||
if (byte < 0) throw EOFException("Incomplete NaviLite packet")
|
||||
bytes[offset + read++] = byte.toByte()
|
||||
} else read += n
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
/* Adapted from Pillion 6647af22f035ad74dc98f0e2a29e0c8a769a1caa.
|
||||
* Required Notice: Copyright 2026 the Pillion authors
|
||||
* PolyForm Noncommercial 1.0.0; see third_party/pillion/LICENSE.md. */
|
||||
package dev.navframe.navilite
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.bluetooth.BluetoothDevice
|
||||
import android.bluetooth.BluetoothManager
|
||||
import android.bluetooth.BluetoothSocket
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import dev.navframe.core.ConnectionState
|
||||
import dev.navframe.core.TftFrame
|
||||
import dev.navframe.core.TftTransport
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import java.util.UUID
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
/** One selected bonded CCU, one outstanding JPEG; no screen capture. */
|
||||
class NaviLiteTransport(context: Context, private val deviceAddress: String) : TftTransport {
|
||||
private val context = context.applicationContext
|
||||
private val state = MutableStateFlow(ConnectionState.DISCONNECTED)
|
||||
override val connectionState: StateFlow<ConnectionState> = state.asStateFlow()
|
||||
private val operation = Mutex()
|
||||
private val lifecycle = Any()
|
||||
private var socket: BluetoothSocket? = null
|
||||
private var generation = 0L
|
||||
private var sequence = 1
|
||||
|
||||
override suspend fun connect() = operation.withLock {
|
||||
val token = synchronized(lifecycle) {
|
||||
closeLocked()
|
||||
generation++
|
||||
state.value = ConnectionState.CONNECTING
|
||||
generation
|
||||
}
|
||||
try {
|
||||
io(token, 15_000) { open(token) }
|
||||
synchronized(lifecycle) {
|
||||
check(generation == token) { "Connection cancelled" }
|
||||
state.value = ConnectionState.HANDSHAKING
|
||||
}
|
||||
io(token, 10_000) { handshake(token) }
|
||||
synchronized(lifecycle) {
|
||||
check(generation == token) { "Connection cancelled" }
|
||||
sequence = 1
|
||||
state.value = ConnectionState.CONNECTED
|
||||
}
|
||||
} catch (failure: Throwable) {
|
||||
fail(token)
|
||||
throw failure
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun disconnect() {
|
||||
synchronized(lifecycle) {
|
||||
generation++
|
||||
closeLocked()
|
||||
state.value = ConnectionState.DISCONNECTED
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun sendFrame(frame: TftFrame) = operation.withLock {
|
||||
require(frame.width == 480 && frame.height == 240) { "TFT frame must be 480×240" }
|
||||
val jpeg = frame.encodedBytes
|
||||
require(jpeg.size >= 4 && jpeg[0] == 0xff.toByte() && jpeg[1] == 0xd8.toByte() &&
|
||||
jpeg[jpeg.size - 2] == 0xff.toByte() && jpeg.last() == 0xd9.toByte()) { "Frame must contain JPEG bytes" }
|
||||
require(jpeg.size <= NaviLiteCodec.MAX_PAYLOAD - 3) { "JPEG exceeds transport limit" }
|
||||
val token = synchronized(lifecycle) {
|
||||
check(state.value == ConnectionState.CONNECTED) { "NaviLite is disconnected" }
|
||||
generation
|
||||
}
|
||||
try {
|
||||
io(token, 5_000) {
|
||||
send(token, 0, true, NaviLiteCodec.image(jpeg, sequence))
|
||||
await(token, 80)
|
||||
}
|
||||
synchronized(lifecycle) {
|
||||
check(generation == token) { "Connection cancelled" }
|
||||
sequence = (sequence + 1) and 0xffff
|
||||
}
|
||||
} catch (failure: Throwable) {
|
||||
fail(token)
|
||||
throw failure
|
||||
}
|
||||
}
|
||||
|
||||
private fun fail(token: Long) = synchronized(lifecycle) {
|
||||
if (generation == token) {
|
||||
closeLocked()
|
||||
state.value = ConnectionState.ERROR
|
||||
}
|
||||
}
|
||||
|
||||
// A cancellable continuation lets timeout close the socket while its blocking I/O runs on IO.
|
||||
private suspend fun io(token: Long, timeoutMs: Long, action: () -> Unit) {
|
||||
withTimeout(timeoutMs) {
|
||||
suspendCancellableCoroutine<Unit> { continuation ->
|
||||
continuation.invokeOnCancellation {
|
||||
synchronized(lifecycle) {
|
||||
if (generation == token) {
|
||||
generation++
|
||||
closeLocked()
|
||||
state.value = ConnectionState.ERROR
|
||||
}
|
||||
}
|
||||
}
|
||||
CoroutineScope(continuation.context).launch(Dispatchers.IO) {
|
||||
try {
|
||||
if (continuation.isActive) action()
|
||||
if (continuation.isActive) continuation.resume(Unit)
|
||||
} catch (failure: Throwable) {
|
||||
if (continuation.isActive) continuation.resumeWithException(failure)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
private fun open(token: Long) {
|
||||
if (Build.VERSION.SDK_INT >= 31) {
|
||||
check(context.checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
|
||||
"Bluetooth connection permission is required"
|
||||
}
|
||||
}
|
||||
val adapter = context.getSystemService(BluetoothManager::class.java)?.adapter
|
||||
?: error("Bluetooth is unavailable")
|
||||
check(adapter.isEnabled) { "Enable Bluetooth first" }
|
||||
val device = adapter.getRemoteDevice(deviceAddress)
|
||||
check(device.bondState == BluetoothDevice.BOND_BONDED) { "Pair the motorcycle in Android settings first" }
|
||||
val created = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00007220-0000-1000-8000-00805F9B34FB"))
|
||||
synchronized(lifecycle) {
|
||||
if (generation != token || state.value != ConnectionState.CONNECTING) {
|
||||
created.close()
|
||||
error("Connection cancelled")
|
||||
}
|
||||
socket = created // Publish before connect so disconnect/timeout can unblock it.
|
||||
}
|
||||
created.connect()
|
||||
}
|
||||
|
||||
private fun currentSocket(token: Long): BluetoothSocket = synchronized(lifecycle) {
|
||||
check(generation == token) { "Connection cancelled" }
|
||||
socket ?: error("NaviLite socket closed")
|
||||
}
|
||||
|
||||
private fun send(token: Long, service: Int, pointer: Boolean, payload: ByteArray) {
|
||||
val out = currentSocket(token).outputStream
|
||||
out.write(NaviLiteCodec.packet(service, pointer, payload))
|
||||
out.flush()
|
||||
}
|
||||
|
||||
private fun await(token: Long, service: Int): NaviLitePacket {
|
||||
val input = currentSocket(token).inputStream
|
||||
while (true) {
|
||||
val packet = NaviLiteCodec.read(input)
|
||||
if (packet.service == service) return packet
|
||||
}
|
||||
}
|
||||
|
||||
private fun handshake(token: Long) {
|
||||
await(token, 66)
|
||||
send(token, 81, false, byteArrayOf(1, 0))
|
||||
send(token, 33, true, byteArrayOf(0x1c, 7, 0, 1, 0, 0, 0, 0))
|
||||
send(token, 84, true, NaviLiteCodec.nonce(await(token, 83).payload))
|
||||
val setup = listOf(
|
||||
Triple(2, false, byteArrayOf(0, 0)), Triple(31, false, byteArrayOf(1, 0)),
|
||||
Triple(10, false, byteArrayOf(0, 0)), Triple(11, false, byteArrayOf(0, 0)),
|
||||
Triple(13, false, byteArrayOf(1, 0)), Triple(12, false, byteArrayOf(0, 0)),
|
||||
Triple(14, true, byteArrayOf(7, 0x19, 6, 0, 0x30, 0x2e, 0x32, 0x20, 0x6d, 0x69)),
|
||||
Triple(3, true, byteArrayOf()), Triple(17, true, byteArrayOf(0, 0, 0, 0, 3, 0x6d, 0x70, 0x68)),
|
||||
Triple(13, false, byteArrayOf(1, 0)), Triple(12, false, byteArrayOf(1, 0)),
|
||||
)
|
||||
setup.forEach { (service, pointer, payload) -> send(token, service, pointer, payload) }
|
||||
}
|
||||
|
||||
private fun closeLocked() {
|
||||
val closing = socket
|
||||
socket = null
|
||||
runCatching { closing?.close() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/* Captured vector tests adapted from Pillion ProtocolTest at 6647af22f035ad74dc98f0e2a29e0c8a769a1caa.
|
||||
* Required Notice: Copyright 2026 the Pillion authors
|
||||
* PolyForm Noncommercial 1.0.0; see third_party/pillion/LICENSE.md. */
|
||||
package dev.navframe.navilite
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.EOFException
|
||||
|
||||
class NaviLiteCodecTest {
|
||||
@Test fun standardMpeg2CrcVector() {
|
||||
assertEquals(0x0376e6e7, NaviLiteCodec.crc("123456789".toByteArray()))
|
||||
}
|
||||
|
||||
@Test fun framingMatchesIndependentKnownWireVector() {
|
||||
// Header nAl@ 01 06 51 02 00 00 00 00 + payload 01 00.
|
||||
// CRC independently computed using Python bitwise CRC-32/MPEG-2.
|
||||
val packet = NaviLiteCodec.packet(81, false, byteArrayOf(1, 0))
|
||||
assertArrayEquals(hex("6e416c4001065102000000001a4d1cec0100"), packet)
|
||||
}
|
||||
|
||||
@Test fun handlesFragmentationNoiseAndConcatenatedFrames() {
|
||||
val bytes = byteArrayOf(0x6e, 0x6e, 1) +
|
||||
NaviLiteCodec.packet(66, true, byteArrayOf(9, 8)) +
|
||||
NaviLiteCodec.packet(80, false, byteArrayOf())
|
||||
val fragmented = object : ByteArrayInputStream(bytes) {
|
||||
override fun read(b: ByteArray, off: Int, len: Int): Int = super.read(b, off, minOf(1, len))
|
||||
}
|
||||
assertArrayEquals(byteArrayOf(9, 8), NaviLiteCodec.read(fragmented).payload)
|
||||
assertEquals(80, NaviLiteCodec.read(fragmented).service)
|
||||
}
|
||||
|
||||
@Test fun rejectsBadChecksum() {
|
||||
val packet = NaviLiteCodec.packet(80, false, byteArrayOf(1))
|
||||
packet[16] = 2
|
||||
assertThrows(IllegalStateException::class.java) { NaviLiteCodec.read(ByteArrayInputStream(packet)) }
|
||||
}
|
||||
|
||||
@Test fun rejectsUnsignedOversizeBeforeReadingOrAllocatingPayload() {
|
||||
val header = NaviLiteCodec.packet(80, false, byteArrayOf())
|
||||
for (i in 7..10) header[i] = 0xff.toByte()
|
||||
assertThrows(IllegalStateException::class.java) { NaviLiteCodec.read(ByteArrayInputStream(header)) }
|
||||
}
|
||||
|
||||
@Test fun rejectsTruncationAndUnknownVersion() {
|
||||
val packet = NaviLiteCodec.packet(80, false, byteArrayOf(1))
|
||||
assertThrows(EOFException::class.java) { NaviLiteCodec.read(ByteArrayInputStream(packet.copyOf(16))) }
|
||||
packet[4] = 2
|
||||
assertThrows(IllegalStateException::class.java) { NaviLiteCodec.read(ByteArrayInputStream(packet)) }
|
||||
}
|
||||
|
||||
@Test fun deobfuscatesLastFourNonceBytesAndRejectsShortChallenge() {
|
||||
assertArrayEquals(byteArrayOf(1, 2, 3, 4), NaviLiteCodec.nonce(byteArrayOf(99, 11, 8, 9, 14)))
|
||||
assertThrows(IllegalArgumentException::class.java) { NaviLiteCodec.nonce(byteArrayOf(1, 2, 3)) }
|
||||
}
|
||||
|
||||
@Test fun imageHeaderUsesLittleEndianWrappingSequence() {
|
||||
assertArrayEquals(hex("03ffff0102"), NaviLiteCodec.image(byteArrayOf(1, 2), 65535))
|
||||
assertArrayEquals(hex("0300000102"), NaviLiteCodec.image(byteArrayOf(1, 2), 0))
|
||||
}
|
||||
|
||||
@Test fun matchesUpstreamCapturedAuthenticationAck() {
|
||||
val packet = NaviLiteCodec.packet(84, true, hex("b0a04756"))
|
||||
assertArrayEquals(hex("24f0735b"), packet.copyOfRange(12, 16))
|
||||
}
|
||||
|
||||
@Test fun matchesAllThreeUpstreamCapturedNonces() {
|
||||
val vectors = listOf("baaa4d5c" to "b0a04756", "c12b8a7b" to "cb218071", "43719e55" to "497b945f")
|
||||
for ((seed, expected) in vectors) {
|
||||
assertArrayEquals(hex(expected), NaviLiteCodec.nonce(hex("3a3a3c27483e3b3c3a273a3a" + seed)))
|
||||
}
|
||||
}
|
||||
|
||||
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
|
||||
}
|
||||
Reference in new issue
Block a user