From 936dac090d098379c20d7e3e0aa1c2b2c24ef5cb Mon Sep 17 00:00:00 2001 From: oxy <70512220+oxyroid@users.noreply.github.com> Date: Tue, 28 Jul 2026 09:22:53 +0800 Subject: [PATCH 1/2] Document supported Pixel Candy devices --- README.md | 4 ++++ README.zh-CN.md | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/README.md b/README.md index d7bca51..4d4dd71 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,10 @@ A portable protocol library and BLE SDKs for compatible smart bead boards. > before the first stable release. Incubating builds use prerelease tags such > as `v0.3.0-incubating.2`. +## Supported devices + +- 像素糖果: `HPD-3232`, `HPD-5252`, `HPD-7878`, `HPD-104104` + ## Packages - `PixDot::Protocol`: portable ISO C11 protocol core. diff --git a/README.zh-CN.md b/README.zh-CN.md index 66afcfc..1308786 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -11,6 +11,10 @@ > 本项目仍在孵化,首个稳定版本发布前,协议覆盖范围和公开 API 可能调整。 > 孵化版本使用 `v0.3.0-incubating.2` 形式的预发布 tag。 +## 支持设备 + +- 像素糖果:`HPD-3232`、`HPD-5252`、`HPD-7878`、`HPD-104104` + ## 组件 - `PixDot::Protocol`:可移植的 ISO C11 协议核心。 From 84d83a021945299d3c570871c8600dabd11cc0c7 Mon Sep 17 00:00:00 2001 From: oxy <70512220+oxyroid@users.noreply.github.com> Date: Wed, 29 Jul 2026 22:34:28 +0800 Subject: [PATCH 2/2] fix: detect board size and stabilize web transfers --- .gitignore | 1 + README.md | 5 +- README.zh-CN.md | 5 +- android-sdk/README.md | 6 +- android-sdk/README.zh-CN.md | 6 +- android-sdk/src/main/cpp/pixdot_jni.c | 35 ++++--- .../io/github/oxyroid/pixdot/PixDotClient.kt | 31 ++++++- .../oxyroid/pixdot/PixDotDeviceScanner.kt | 20 +++- .../io/github/oxyroid/pixdot/PixDotTypes.kt | 9 +- .../oxyroid/pixdot/internal/NativeProtocol.kt | 10 +- .../oxyroid/pixdot/internal/Protocol.kt | 26 ++---- core/include/pixdot/protocol.h | 7 ++ core/src/protocol.c | 53 +++++++++-- ios-sdk/README.md | 4 + ios-sdk/README.zh-CN.md | 4 + ios-sdk/Sources/PixDot/PixDotClient.swift | 4 + .../Sources/PixDot/PixDotDeviceScanner.swift | 5 +- ios-sdk/Sources/PixDot/PixDotProtocol.swift | 12 ++- ios-sdk/Sources/PixDot/PixDotTypes.swift | 4 +- ios-sdk/Tests/PixDotConformance/main.swift | 11 +++ tests/native_protocol_test.c | 23 +++++ web-sdk/README.md | 16 +++- web-sdk/README.zh-CN.md | 16 +++- web-sdk/src/client.ts | 64 ++++++++----- web-sdk/test/client.test.mjs | 92 ++++++++++++++++++- 25 files changed, 362 insertions(+), 107 deletions(-) diff --git a/.gitignore b/.gitignore index c96a80d..6d199bb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ .DS_Store .build/ .gradle/ +.kotlin/ .idea/ build/ **/build/ diff --git a/README.md b/README.md index 4d4dd71..d9cb083 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,9 @@ if (pixdot_encode_brightness(50, &packet) == PIXDOT_OK) { All output buffers are caller-owned. Encoders set `packet.size` to the required size and return `PIXDOT_ERROR_BUFFER_TOO_SMALL` when capacity is insufficient. +Use `pixdot_try_board_size_from_device_name` or +`pixdot_try_board_size_from_advertisement` when scanning. A false result means +the size must be obtained from the board-information response. ## Android SDK @@ -77,7 +80,7 @@ val client = PixDotClient(context) scanner.start { device -> scanner.stop() - client.connect(device.bluetoothDevice) + client.connect(device) } ``` diff --git a/README.zh-CN.md b/README.zh-CN.md index 1308786..8733a47 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -66,6 +66,9 @@ if (pixdot_encode_brightness(50, &packet) == PIXDOT_OK) { 输出缓冲区由调用方持有。编码器会写入所需的 `packet.size`;容量不足时返回 `PIXDOT_ERROR_BUFFER_TOO_SMALL`。 +扫描时使用 `pixdot_try_board_size_from_device_name` 或 +`pixdot_try_board_size_from_advertisement`。返回 `false` 表示需要通过板信息 +响应取得尺寸。 ## Android SDK @@ -75,7 +78,7 @@ val client = PixDotClient(context) scanner.start { device -> scanner.stop() - client.connect(device.bluetoothDevice) + client.connect(device) } ``` diff --git a/android-sdk/README.md b/android-sdk/README.md index 43296ba..24c7280 100644 --- a/android-sdk/README.md +++ b/android-sdk/README.md @@ -43,7 +43,7 @@ val client = PixDotClient(context, object : PixDotClientListener { scanner.start( callback = { device -> scanner.stop() - client.connect(device.bluetoothDevice) + client.connect(device) }, onError = { error -> handle(error) }, ) @@ -53,6 +53,10 @@ scanner.start( `PixDotClient` selects a service containing both a writable characteristic and a notifying or indicating characteristic. +`device.boardSize` is `null` when neither the advertisement nor device name +contains a size. After `READY`, call `requestBoardInfo`; the client updates +`client.boardSize` and `client.device?.boardSize` before `onBoardInfo`. + ## Commands ```kotlin diff --git a/android-sdk/README.zh-CN.md b/android-sdk/README.zh-CN.md index 1e754a4..91dfe7d 100644 --- a/android-sdk/README.zh-CN.md +++ b/android-sdk/README.zh-CN.md @@ -41,7 +41,7 @@ val client = PixDotClient(context, object : PixDotClientListener { scanner.start( callback = { device -> scanner.stop() - client.connect(device.bluetoothDevice) + client.connect(device) }, onError = { error -> handle(error) }, ) @@ -50,6 +50,10 @@ scanner.start( `PixDotDeviceScanner` 返回广播名称包含 `PDD_` 的设备。`PixDotClient` 会选择 同时具有可写特征和通知或指示特征的服务。 +广播和设备名均不含尺寸时,`device.boardSize` 为 `null`。进入 `READY` 后调用 +`requestBoardInfo`;触发 `onBoardInfo` 前,SDK 会更新 `client.boardSize` 和 +`client.device?.boardSize`。 + ## 命令 ```kotlin diff --git a/android-sdk/src/main/cpp/pixdot_jni.c b/android-sdk/src/main/cpp/pixdot_jni.c index 4498f17..b2605ac 100644 --- a/android-sdk/src/main/cpp/pixdot_jni.c +++ b/android-sdk/src/main/cpp/pixdot_jni.c @@ -695,20 +695,15 @@ JNIEXPORT jintArray JNICALL Java_io_github_oxyroid_pixdot_internal_NativeProtocol_parseAdvertisement( JNIEnv *env, jobject receiver, - jbyteArray scan_record, - jint fallback_value) { - pixdot_board_size fallback; + jbyteArray scan_record) { jbyte *bytes = NULL; jsize size = 0; pixdot_advertisement advertisement; + pixdot_board_size detected; pixdot_status status; jint values[3]; jintArray result; (void)receiver; - if (!as_board_size(fallback_value, &fallback)) { - throw_invalid(env, "fallback board size is invalid"); - return NULL; - } if (scan_record != NULL) { size = (*env)->GetArrayLength(env, scan_record); bytes = (*env)->GetByteArrayElements(env, scan_record, NULL); @@ -719,8 +714,14 @@ Java_io_github_oxyroid_pixdot_internal_NativeProtocol_parseAdvertisement( status = pixdot_parse_advertisement( (const uint8_t *)bytes, (size_t)size, - fallback, + PIXDOT_BOARD_52X52, &advertisement); + values[2] = pixdot_try_board_size_from_advertisement( + (const uint8_t *)bytes, + (size_t)size, + &detected) + ? (jint)detected + : -1; if (scan_record != NULL) { (*env)->ReleaseByteArrayElements( env, @@ -734,7 +735,6 @@ Java_io_github_oxyroid_pixdot_internal_NativeProtocol_parseAdvertisement( } values[0] = advertisement.cid; values[1] = advertisement.pid; - values[2] = advertisement.board_size; result = (*env)->NewIntArray(env, 3); if (result != NULL) { (*env)->SetIntArrayRegion(env, result, 0, 3, values); @@ -780,23 +780,22 @@ JNIEXPORT jint JNICALL Java_io_github_oxyroid_pixdot_internal_NativeProtocol_boardSizeFromDeviceName( JNIEnv *env, jobject receiver, - jstring name, - jint fallback_value) { + jstring name) { const char *characters; - pixdot_board_size fallback; pixdot_board_size result; + bool found; (void)receiver; - if (name == NULL || !as_board_size(fallback_value, &fallback)) { - throw_invalid(env, "device name arguments are invalid"); - return 0; + if (name == NULL) { + throw_invalid(env, "device name must not be null"); + return -1; } characters = (*env)->GetStringUTFChars(env, name, NULL); if (characters == NULL) { - return 0; + return -1; } - result = pixdot_board_size_from_device_name(characters, fallback); + found = pixdot_try_board_size_from_device_name(characters, &result); (*env)->ReleaseStringUTFChars(env, name, characters); - return (jint)result; + return found ? (jint)result : -1; } JNIEXPORT jlong JNICALL diff --git a/android-sdk/src/main/java/io/github/oxyroid/pixdot/PixDotClient.kt b/android-sdk/src/main/java/io/github/oxyroid/pixdot/PixDotClient.kt index cd74046..f26d5a2 100644 --- a/android-sdk/src/main/java/io/github/oxyroid/pixdot/PixDotClient.kt +++ b/android-sdk/src/main/java/io/github/oxyroid/pixdot/PixDotClient.kt @@ -66,6 +66,12 @@ class PixDotClient( private var connectionTimeout: Runnable? = null private var mtuTimeout: Runnable? = null + var device: PixDotDevice? = null + private set + + var boardSize: BoardSize? = null + private set + var state: ConnectionState = ConnectionState.DISCONNECTED private set @@ -226,21 +232,34 @@ class PixDotClient( } } - @SuppressLint("MissingPermission") - @Synchronized fun connect( device: BluetoothDevice, callback: OperationCallback = NoOpOperationCallback, + ) = connect(device, null, callback) + + fun connect( + device: PixDotDevice, + callback: OperationCallback = NoOpOperationCallback, + ) = connect(device.bluetoothDevice, device, callback) + + @SuppressLint("MissingPermission") + @Synchronized + private fun connect( + bluetoothDevice: BluetoothDevice, + pixDotDevice: PixDotDevice?, + callback: OperationCallback, ) { if (state != ConnectionState.DISCONNECTED) { callback.onError(PixDotError(ErrorCode.BUSY, "A device is already connected")) return } + device = pixDotDevice + boardSize = pixDotDevice?.boardSize connectCallback = callback changeState(ConnectionState.CONNECTING) scheduleConnectionTimeout() try { - gatt = device.connectGatt( + gatt = bluetoothDevice.connectGatt( applicationContext, false, gattCallback, @@ -584,7 +603,11 @@ class PixDotClient( val copy = value.copyOf() listener.onNotification(copy) when (val event = Protocol.parseDeviceEvent(copy)) { - is DeviceEvent.Board -> listener.onBoardInfo(event.info) + is DeviceEvent.Board -> { + boardSize = event.info.boardSize + device?.boardSize = event.info.boardSize + listener.onBoardInfo(event.info) + } is DeviceEvent.Firmware -> listener.onFirmwareVersion(event.version) null -> Unit } diff --git a/android-sdk/src/main/java/io/github/oxyroid/pixdot/PixDotDeviceScanner.kt b/android-sdk/src/main/java/io/github/oxyroid/pixdot/PixDotDeviceScanner.kt index e2bdfcd..b2bad59 100644 --- a/android-sdk/src/main/java/io/github/oxyroid/pixdot/PixDotDeviceScanner.kt +++ b/android-sdk/src/main/java/io/github/oxyroid/pixdot/PixDotDeviceScanner.kt @@ -51,8 +51,17 @@ class PixDotDeviceScanner(context: Context) : AutoCloseable { result: ScanResult, ) { parse(result)?.let { device -> - val previous = seen.put(device.bluetoothDevice.address, device) - if (previous != device) callback.onDevice(device) + val address = device.bluetoothDevice.address + val previous = seen[address] + if (previous == null || + previous.advertisedName != device.advertisedName || + previous.cid != device.cid || + previous.pid != device.pid || + previous.boardSize != device.boardSize + ) { + seen[address] = device + callback.onDevice(device) + } } } @@ -120,14 +129,15 @@ class PixDotDeviceScanner(context: Context) : AutoCloseable { val name = result.device.name ?: result.scanRecord?.deviceName ?: return null if (!Protocol.isSupportedDeviceName(name)) return null val bytes = result.scanRecord?.bytes - val fallback = Protocol.boardSizeFromDeviceName(name, BoardSize.SIZE_52X52) - val advertisement = Protocol.parseAdvertisement(bytes, fallback) + val advertisement = Protocol.parseAdvertisement(bytes) + val boardSize = + advertisement.boardSize ?: Protocol.boardSizeFromDeviceName(name) return PixDotDevice( result.device, name, advertisement.cid, advertisement.pid, - advertisement.boardSize, + boardSize, ) } diff --git a/android-sdk/src/main/java/io/github/oxyroid/pixdot/PixDotTypes.kt b/android-sdk/src/main/java/io/github/oxyroid/pixdot/PixDotTypes.kt index e4cbc12..5687917 100644 --- a/android-sdk/src/main/java/io/github/oxyroid/pixdot/PixDotTypes.kt +++ b/android-sdk/src/main/java/io/github/oxyroid/pixdot/PixDotTypes.kt @@ -49,13 +49,16 @@ data class PixelCoordinate( } } -data class PixDotDevice( +class PixDotDevice( val bluetoothDevice: BluetoothDevice, val advertisedName: String, val cid: Int, val pid: Int, - val boardSize: BoardSize, -) + boardSize: BoardSize?, +) { + var boardSize: BoardSize? = boardSize + internal set +} data class BoardInfo( val boardSize: BoardSize, diff --git a/android-sdk/src/main/java/io/github/oxyroid/pixdot/internal/NativeProtocol.kt b/android-sdk/src/main/java/io/github/oxyroid/pixdot/internal/NativeProtocol.kt index abc205a..1780b41 100644 --- a/android-sdk/src/main/java/io/github/oxyroid/pixdot/internal/NativeProtocol.kt +++ b/android-sdk/src/main/java/io/github/oxyroid/pixdot/internal/NativeProtocol.kt @@ -61,19 +61,13 @@ internal object NativeProtocol { external fun parseDeviceEvent(data: ByteArray): IntArray - external fun parseAdvertisement( - scanRecord: ByteArray?, - fallbackBoardSize: Int, - ): IntArray + external fun parseAdvertisement(scanRecord: ByteArray?): IntArray external fun boardSideLength(boardSize: Int): Int external fun isSupportedDeviceName(name: String): Boolean - external fun boardSizeFromDeviceName( - name: String, - fallbackBoardSize: Int, - ): Int + external fun boardSizeFromDeviceName(name: String): Int external fun crc32(data: ByteArray): Long } diff --git a/android-sdk/src/main/java/io/github/oxyroid/pixdot/internal/Protocol.kt b/android-sdk/src/main/java/io/github/oxyroid/pixdot/internal/Protocol.kt index d414583..e92d1ff 100644 --- a/android-sdk/src/main/java/io/github/oxyroid/pixdot/internal/Protocol.kt +++ b/android-sdk/src/main/java/io/github/oxyroid/pixdot/internal/Protocol.kt @@ -25,7 +25,7 @@ internal sealed interface DeviceEvent { internal data class Advertisement( val cid: Int, val pid: Int, - val boardSize: BoardSize, + val boardSize: BoardSize?, ) internal enum class TransferStep { @@ -146,15 +146,14 @@ internal object Protocol { } } - fun parseAdvertisement( - scanRecord: ByteArray?, - fallback: BoardSize, - ): Advertisement { - val values = NativeProtocol.parseAdvertisement(scanRecord, fallback.ordinal) + fun parseAdvertisement(scanRecord: ByteArray?): Advertisement { + val values = NativeProtocol.parseAdvertisement(scanRecord) require(values.size == 3) { "Invalid native advertisement result" } - val boardSize = BoardSize.fromNativeValue(values[2]) - ?: throw IllegalStateException("Native core returned an invalid board size") - return Advertisement(values[0], values[1], boardSize) + return Advertisement( + values[0], + values[1], + BoardSize.fromNativeValue(values[2]), + ) } fun boardSideLength(boardSize: BoardSize): Int = @@ -163,13 +162,8 @@ internal object Protocol { fun isSupportedDeviceName(name: String): Boolean = NativeProtocol.isSupportedDeviceName(name) - fun boardSizeFromDeviceName( - name: String, - fallback: BoardSize, - ): BoardSize = - BoardSize.fromNativeValue( - NativeProtocol.boardSizeFromDeviceName(name, fallback.ordinal), - ) ?: fallback + fun boardSizeFromDeviceName(name: String): BoardSize? = + BoardSize.fromNativeValue(NativeProtocol.boardSizeFromDeviceName(name)) fun crc32(data: ByteArray): Long = NativeProtocol.crc32(data) } diff --git a/core/include/pixdot/protocol.h b/core/include/pixdot/protocol.h index 2ee22ab..32fd559 100644 --- a/core/include/pixdot/protocol.h +++ b/core/include/pixdot/protocol.h @@ -114,9 +114,16 @@ PIXDOT_API size_t pixdot_frame_payload_capacity(pixdot_board_size board_size); PIXDOT_API uint32_t pixdot_crc32(const uint8_t *data, size_t size); PIXDOT_API const char *pixdot_device_name_prefix(void); PIXDOT_API bool pixdot_is_supported_device_name(const char *name); +PIXDOT_API bool pixdot_try_board_size_from_device_name( + const char *name, + pixdot_board_size *out); PIXDOT_API pixdot_board_size pixdot_board_size_from_device_name( const char *name, pixdot_board_size fallback); +PIXDOT_API bool pixdot_try_board_size_from_advertisement( + const uint8_t *scan_record, + size_t size, + pixdot_board_size *out); PIXDOT_API pixdot_status pixdot_encode_brightness( uint8_t percent, diff --git a/core/src/protocol.c b/core/src/protocol.c index 6ec3783..fd2ba07 100644 --- a/core/src/protocol.c +++ b/core/src/protocol.c @@ -170,27 +170,56 @@ bool pixdot_is_supported_device_name(const char *name) { return contains_text(name, pixdot_device_name_prefix()); } -pixdot_board_size pixdot_board_size_from_device_name( +bool pixdot_try_board_size_from_device_name( const char *name, - pixdot_board_size fallback) { - if (!valid_board_size(fallback)) { - return PIXDOT_BOARD_52X52; + pixdot_board_size *out) { + if (out == NULL) { + return false; } if (contains_text(name, "32*32")) { - return PIXDOT_BOARD_32X32; + *out = PIXDOT_BOARD_32X32; + return true; } if (contains_text(name, "52*52")) { - return PIXDOT_BOARD_52X52; + *out = PIXDOT_BOARD_52X52; + return true; } if (contains_text(name, "78*78")) { - return PIXDOT_BOARD_78X78; + *out = PIXDOT_BOARD_78X78; + return true; } if (contains_text(name, "104*104")) { - return PIXDOT_BOARD_104X104; + *out = PIXDOT_BOARD_104X104; + return true; + } + return false; +} + +pixdot_board_size pixdot_board_size_from_device_name( + const char *name, + pixdot_board_size fallback) { + pixdot_board_size detected; + if (!valid_board_size(fallback)) { + return PIXDOT_BOARD_52X52; + } + if (pixdot_try_board_size_from_device_name(name, &detected)) { + return detected; } return fallback; } +bool pixdot_try_board_size_from_advertisement( + const uint8_t *scan_record, + size_t size, + pixdot_board_size *out) { + if (scan_record == NULL || size <= 32 || out == NULL || + scan_record[25] > PIXDOT_BOARD_104X104) { + return false; + } + *out = (pixdot_board_size)scan_record[25]; + return true; +} + pixdot_status pixdot_encode_brightness(uint8_t percent, pixdot_buffer *out) { uint8_t packet[] = {0x05, 0x00, 0x04, 0x80, percent}; if (percent > 100) { @@ -574,6 +603,7 @@ pixdot_status pixdot_parse_advertisement( size_t size, pixdot_board_size fallback_board_size, pixdot_advertisement *out) { + pixdot_board_size detected; if (out == NULL || !valid_board_size(fallback_board_size) || (scan_record == NULL && size != 0)) { return PIXDOT_ERROR_INVALID_ARGUMENT; @@ -586,8 +616,11 @@ pixdot_status pixdot_parse_advertisement( } out->cid = (uint16_t)scan_record[21] + (uint16_t)scan_record[22]; out->pid = scan_record[23]; - out->board_size = scan_record[25] <= PIXDOT_BOARD_104X104 - ? scan_record[25] + out->board_size = pixdot_try_board_size_from_advertisement( + scan_record, + size, + &detected) + ? (uint8_t)detected : (uint8_t)fallback_board_size; return PIXDOT_OK; } diff --git a/ios-sdk/README.md b/ios-sdk/README.md index 565d2f1..4500fb2 100644 --- a/ios-sdk/README.md +++ b/ios-sdk/README.md @@ -42,6 +42,8 @@ scanner.start( The scanner selects names supported by the C core. `makeClient(for:)` stops the scan and keeps the discovered peripheral on the same CoreBluetooth manager. +`device.boardSize` is `nil` when the advertised name does not contain a size. +The client updates it before invoking `onBoardInfo`. ## Commands @@ -65,6 +67,8 @@ client?.onBoardInfo = { info in client?.onFirmwareVersion = { version in print(version) } + +try await client?.requestBoardInfo(hour: 12, minute: 30, second: 0) ``` ## Images diff --git a/ios-sdk/README.zh-CN.md b/ios-sdk/README.zh-CN.md index b88f4fd..cb97e6c 100644 --- a/ios-sdk/README.zh-CN.md +++ b/ios-sdk/README.zh-CN.md @@ -42,6 +42,8 @@ scanner.start( Scanner 仅返回 C Core 识别的设备名。`makeClient(for:)` 会停止扫描,并使用发现 设备时的同一个 CoreBluetooth Manager 建立连接。 +广播名称不含尺寸时,`device.boardSize` 为 `nil`。触发 `onBoardInfo` 前, +Client 会用设备回报的板型更新该属性。 ## 控制命令 @@ -65,6 +67,8 @@ client?.onBoardInfo = { info in client?.onFirmwareVersion = { version in print(version) } + +try await client?.requestBoardInfo(hour: 12, minute: 30, second: 0) ``` ## 图片 diff --git a/ios-sdk/Sources/PixDot/PixDotClient.swift b/ios-sdk/Sources/PixDot/PixDotClient.swift index 10d2d88..abb92f6 100644 --- a/ios-sdk/Sources/PixDot/PixDotClient.swift +++ b/ios-sdk/Sources/PixDot/PixDotClient.swift @@ -51,6 +51,9 @@ public final class PixDotClient: NSObject, @unchecked Sendable { private static let writeTimeout: TimeInterval = 15 public let device: PixDotDevice + public var boardSize: PixDotBoardSize? { + device.boardSize + } private let central: CBCentralManager private let peripheral: CBPeripheral private var pendingServices = Set() @@ -456,6 +459,7 @@ public final class PixDotClient: NSObject, @unchecked Sendable { if let event = PixDotProtocol.parseDeviceEvent(data) { switch event { case .boardInfo(let info): + device.boardSize = info.boardSize onBoardInfo?(info) case .firmwareVersion(let version): onFirmwareVersion?(version) diff --git a/ios-sdk/Sources/PixDot/PixDotDeviceScanner.swift b/ios-sdk/Sources/PixDot/PixDotDeviceScanner.swift index 6f87e67..aca0db0 100644 --- a/ios-sdk/Sources/PixDot/PixDotDeviceScanner.swift +++ b/ios-sdk/Sources/PixDot/PixDotDeviceScanner.swift @@ -182,10 +182,7 @@ extension PixDotDeviceScanner: CBCentralManagerDelegate { return } seenIdentifiers.insert(peripheral.identifier) - let boardSize = PixDotProtocol.boardSize( - fromDeviceName: name, - fallback: .size52x52 - ) + let boardSize = PixDotProtocol.boardSize(fromDeviceName: name) let manufacturerData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data deviceHandler?( diff --git a/ios-sdk/Sources/PixDot/PixDotProtocol.swift b/ios-sdk/Sources/PixDot/PixDotProtocol.swift index 2c501af..4638cf4 100644 --- a/ios-sdk/Sources/PixDot/PixDotProtocol.swift +++ b/ios-sdk/Sources/PixDot/PixDotProtocol.swift @@ -10,9 +10,19 @@ public enum PixDotProtocol { name.withCString(pixdot_is_supported_device_name) } + public static func boardSize( + fromDeviceName name: String + ) -> PixDotBoardSize? { + var detected = PIXDOT_BOARD_52X52 + let found = name.withCString { + pixdot_try_board_size_from_device_name($0, &detected) + } + return found ? PixDotBoardSize(cValue: detected) : nil + } + public static func boardSize( fromDeviceName name: String, - fallback: PixDotBoardSize = .size52x52 + fallback: PixDotBoardSize ) -> PixDotBoardSize { name.withCString { PixDotBoardSize( diff --git a/ios-sdk/Sources/PixDot/PixDotTypes.swift b/ios-sdk/Sources/PixDot/PixDotTypes.swift index 36df808..3500a0d 100644 --- a/ios-sdk/Sources/PixDot/PixDotTypes.swift +++ b/ios-sdk/Sources/PixDot/PixDotTypes.swift @@ -113,7 +113,7 @@ public struct PixDotError: Error, LocalizedError { public final class PixDotDevice: Identifiable, @unchecked Sendable { public let id: UUID public let name: String - public let boardSize: PixDotBoardSize + public internal(set) var boardSize: PixDotBoardSize? public let signalStrength: Int public let manufacturerData: Data? @@ -124,7 +124,7 @@ public final class PixDotDevice: Identifiable, @unchecked Sendable { peripheral: CBPeripheral, central: CBCentralManager, name: String, - boardSize: PixDotBoardSize, + boardSize: PixDotBoardSize?, signalStrength: Int, manufacturerData: Data? ) { diff --git a/ios-sdk/Tests/PixDotConformance/main.swift b/ios-sdk/Tests/PixDotConformance/main.swift index b11e062..e98711f 100644 --- a/ios-sdk/Tests/PixDotConformance/main.swift +++ b/ios-sdk/Tests/PixDotConformance/main.swift @@ -92,6 +92,17 @@ do { PixDotProtocol.boardSize(fromDeviceName: "PDD_78*78") == .size78x78, "device board size" ) + try require( + PixDotProtocol.boardSize(fromDeviceName: "PDD_2E1155") == nil, + "opaque device name board size" + ) + try require( + PixDotProtocol.boardSize( + fromDeviceName: "PDD_2E1155", + fallback: .size32x32 + ) == .size32x32, + "device board size fallback" + ) try require( PixDotProtocol.crc32(Data("123456789".utf8)) == 0xcbf43926, "CRC-32" diff --git a/tests/native_protocol_test.c b/tests/native_protocol_test.c index 355ce62..1911dd1 100644 --- a/tests/native_protocol_test.c +++ b/tests/native_protocol_test.c @@ -95,9 +95,17 @@ static void check_vector( static void test_controls(void) { uint8_t storage[16]; pixdot_buffer packet = {storage, sizeof(storage), 0}; + pixdot_board_size detected; check( strcmp(pixdot_device_name_prefix(), "PDD_") == 0, "device name prefix"); + check( + pixdot_try_board_size_from_device_name("PDD_78*78", &detected) && + detected == PIXDOT_BOARD_78X78, + "detect board size from device name"); + check( + !pixdot_try_board_size_from_device_name("PDD_2E1155", &detected), + "opaque device name has no board size"); check( pixdot_board_size_from_device_name( "PDD_78*78", @@ -253,6 +261,7 @@ static void test_parse(void) { uint8_t scan[33] = {0}; pixdot_device_event event; pixdot_advertisement advertisement; + pixdot_board_size detected; size_t next_frame; check( @@ -280,6 +289,13 @@ static void test_parse(void) { scan[22] = 3; scan[23] = 127; scan[25] = 2; + check( + pixdot_try_board_size_from_advertisement( + scan, + sizeof(scan), + &detected) && + detected == PIXDOT_BOARD_78X78, + "detect advertisement board size"); check( pixdot_parse_advertisement( scan, @@ -292,6 +308,13 @@ static void test_parse(void) { check( advertisement.board_size == PIXDOT_BOARD_78X78, "advertisement board size"); + scan[25] = 255; + check( + !pixdot_try_board_size_from_advertisement( + scan, + sizeof(scan), + &detected), + "advertisement without board size stays unknown"); check( pixdot_advance_transfer( diff --git a/web-sdk/README.md b/web-sdk/README.md index b320ff8..48ba2ec 100644 --- a/web-sdk/README.md +++ b/web-sdk/README.md @@ -40,6 +40,18 @@ const client = await PixDotWebClient.request({ }); ``` +`client.boardSize` is initially `undefined`. Request board information after +connecting; the SDK updates it before invoking `onDeviceEvent`: + +```ts +const now = new Date(); +await client.requestBoardInfo( + now.getHours(), + now.getMinutes(), + now.getSeconds(), +); +``` + ## Commands ```ts @@ -79,7 +91,7 @@ Use encoded PNG bytes for 32×32 and 52×52 boards. Use exact row-major RGB888 data for 78×78 and 104×104 boards. `rgba8888ToRgb888` converts browser `ImageData.data` into RGB888. -The default GATT write size is 20 bytes. Set `maxWriteSize` only when the target -browser and board support a larger value. +The default GATT write size is 509 bytes, matching the supported boards' 512-byte +MTU. Set a smaller `maxWriteSize` only when the browser rejects that payload. Call `client.disconnect()` when the connection is no longer needed. diff --git a/web-sdk/README.zh-CN.md b/web-sdk/README.zh-CN.md index 629bfba..3c18079 100644 --- a/web-sdk/README.zh-CN.md +++ b/web-sdk/README.zh-CN.md @@ -38,6 +38,18 @@ const client = await PixDotWebClient.request({ }); ``` +`client.boardSize` 初始为 `undefined`。连接后请求板信息;触发 +`onDeviceEvent` 前,SDK 会更新该属性: + +```ts +const now = new Date(); +await client.requestBoardInfo( + now.getHours(), + now.getMinutes(), + now.getSeconds(), +); +``` + ## 命令 ```ts @@ -77,7 +89,7 @@ await client.sendRgbImage(rgb888, BoardSize.Size104x104, { 匹配的行优先 RGB888 数据。`rgba8888ToRgb888` 可将浏览器 `ImageData.data` 转为 RGB888。 -默认 GATT 写入分片为 20 字节。仅在目标浏览器和设备支持时通过 -`maxWriteSize` 设置更大的值。 +默认 GATT 写入分片为 509 字节,与受支持设备的 512 字节 MTU 匹配。仅在浏览器 +拒绝该载荷时设置更小的 `maxWriteSize`。 连接不再使用时调用 `client.disconnect()`。 diff --git a/web-sdk/src/client.ts b/web-sdk/src/client.ts index baa956a..f1e723d 100644 --- a/web-sdk/src/client.ts +++ b/web-sdk/src/client.ts @@ -68,8 +68,11 @@ export interface LiveTransferOptions extends TransferOptions { readonly brightness?: number; } +const DEFAULT_MAX_WRITE_SIZE = 509; + interface AcknowledgementWaiter { readonly promise: Promise; + start(): void; cancel(): void; } @@ -101,15 +104,19 @@ export class PixDotWebClient { PixDotWebClientOptions; private writeCharacteristic?: BluetoothRemoteGATTCharacteristic; private notifyCharacteristic?: BluetoothRemoteGATTCharacteristic; + private detectedBoardSize?: BoardSize; private activeAcknowledgement?: { accept(value: Acknowledgement): void; reject(error: PixDotWebError): void; - timer: ReturnType; + timer?: ReturnType; }; private busy = false; constructor(device: BluetoothDevice, options: PixDotWebClientOptions) { - if (!Number.isInteger(options.maxWriteSize ?? 20) || (options.maxWriteSize ?? 20) < 1) { + if ( + !Number.isInteger(options.maxWriteSize ?? DEFAULT_MAX_WRITE_SIZE) || + (options.maxWriteSize ?? DEFAULT_MAX_WRITE_SIZE) < 1 + ) { throw new RangeError("maxWriteSize must be a positive integer"); } if ( @@ -121,7 +128,7 @@ export class PixDotWebClient { this.device = device; this.options = { ...options, - maxWriteSize: options.maxWriteSize ?? 20, + maxWriteSize: options.maxWriteSize ?? DEFAULT_MAX_WRITE_SIZE, acknowledgementTimeoutMs: options.acknowledgementTimeoutMs ?? 8_000, }; this.device.addEventListener("gattserverdisconnected", this.handleDisconnected); @@ -131,6 +138,10 @@ export class PixDotWebClient { return this.device.gatt?.connected === true; } + get boardSize(): BoardSize | undefined { + return this.detectedBoardSize; + } + async connect(): Promise { if (this.connected && this.writeCharacteristic !== undefined) return; const gatt = this.device.gatt; @@ -303,6 +314,7 @@ export class PixDotWebClient { waiter.cancel(); throw cause; } + waiter.start(); const advance = await waiter.promise; whenStep: switch (advance.step) { case TransferStep.Complete: @@ -363,19 +375,9 @@ export class PixDotWebClient { frameIndex: number, ): AcknowledgementWaiter { let cancelled = false; - let resolvePromise: (value: TransferAdvance) => void = () => undefined; + let active: NonNullable; const promise = new Promise((resolve, reject) => { - resolvePromise = resolve; - const timer = setTimeout(() => { - this.activeAcknowledgement = undefined; - reject( - new PixDotWebError( - "timeout", - "The board did not acknowledge the protocol frame", - ), - ); - }, this.options.acknowledgementTimeoutMs); - this.activeAcknowledgement = { + active = { accept: (value) => { const advance = advanceTransfer( kind, @@ -384,24 +386,35 @@ export class PixDotWebClient { value, ); if (advance.step === TransferStep.Ignored) return; - clearTimeout(timer); + if (active.timer !== undefined) clearTimeout(active.timer); this.activeAcknowledgement = undefined; resolve(advance); }, reject, - timer, }; + this.activeAcknowledgement = active; }); + void promise.catch(() => undefined); return { promise, + start: () => { + if (cancelled || this.activeAcknowledgement !== active) return; + active.timer = setTimeout(() => { + if (this.activeAcknowledgement === active) { + this.activeAcknowledgement = undefined; + } + active.reject( + new PixDotWebError( + "timeout", + "The board did not acknowledge the protocol frame", + ), + ); + }, this.options.acknowledgementTimeoutMs); + }, cancel: () => { if (cancelled) return; cancelled = true; this.cancelAcknowledgement(); - resolvePromise({ - step: TransferStep.Ignored, - frameIndex, - }); }, }; } @@ -409,7 +422,7 @@ export class PixDotWebClient { private cancelAcknowledgement(error?: PixDotWebError): void { if (this.activeAcknowledgement === undefined) return; const active = this.activeAcknowledgement; - clearTimeout(active.timer); + if (active.timer !== undefined) clearTimeout(active.timer); this.activeAcknowledgement = undefined; if (error !== undefined) active.reject(error); } @@ -489,7 +502,12 @@ export class PixDotWebClient { ); this.onNotification?.(data); const deviceEvent = parseDeviceEvent(data); - if (deviceEvent !== undefined) this.onDeviceEvent?.(deviceEvent); + if (deviceEvent !== undefined) { + if (deviceEvent.type === "board-info") { + this.detectedBoardSize = deviceEvent.boardSize; + } + this.onDeviceEvent?.(deviceEvent); + } const acknowledgement = classifyAcknowledgement(data); if ( acknowledgement !== Acknowledgement.Unknown && diff --git a/web-sdk/test/client.test.mjs b/web-sdk/test/client.test.mjs index c547a36..f0c32cd 100644 --- a/web-sdk/test/client.test.mjs +++ b/web-sdk/test/client.test.mjs @@ -6,11 +6,13 @@ import { } from "../dist/index.js"; class FakeCharacteristic extends EventTarget { - constructor(properties) { + constructor(properties, writeDelayMs = 0) { super(); this.properties = properties; + this.writeDelayMs = writeDelayMs; this.writes = []; this.value = undefined; + this.onWrite = undefined; } async startNotifications() { @@ -18,11 +20,19 @@ class FakeCharacteristic extends EventTarget { } async writeValueWithoutResponse(value) { + if (this.writeDelayMs > 0) { + await new Promise((resolve) => setTimeout(resolve, this.writeDelayMs)); + } this.writes.push(new Uint8Array(value)); + this.onWrite?.(); } async writeValueWithResponse(value) { + if (this.writeDelayMs > 0) { + await new Promise((resolve) => setTimeout(resolve, this.writeDelayMs)); + } this.writes.push(new Uint8Array(value)); + this.onWrite?.(); } notify(value) { @@ -32,8 +42,16 @@ class FakeCharacteristic extends EventTarget { } } -function createClient() { - const write = new FakeCharacteristic({ writeWithoutResponse: true }); +function createClient({ + acknowledgementTimeoutMs = 100, + maxWriteSize = 3, + useDefaultMaxWriteSize = false, + writeDelayMs = 0, +} = {}) { + const write = new FakeCharacteristic( + { writeWithoutResponse: true }, + writeDelayMs, + ); const notify = new FakeCharacteristic({ notify: true }); const service = { async getCharacteristics() { @@ -57,8 +75,8 @@ function createClient() { return { client: new PixDotWebClient(device, { serviceUuid: "00001234-0000-1000-8000-00805f9b34fb", - maxWriteSize: 3, - acknowledgementTimeoutMs: 100, + ...(useDefaultMaxWriteSize ? {} : { maxWriteSize }), + acknowledgementTimeoutMs, }), write, notify, @@ -80,6 +98,28 @@ test("connects and fragments control frames", async () => { assert.equal(client.connected, false); }); +test("caches the board size reported by the device", async () => { + const { client, notify } = createClient(); + await client.connect(); + assert.equal(client.boardSize, undefined); + + let received; + let cachedDuringCallback; + client.onDeviceEvent = (event) => { + received = event; + cachedDuringCallback = client.boardSize; + }; + notify.notify(Uint8Array.of(8, 0, 1, 0x80, 3, 0, 0, 50)); + + assert.equal(client.boardSize, BoardSize.Size104x104); + assert.equal(cachedDuringCallback, BoardSize.Size104x104); + assert.deepEqual(received, { + type: "board-info", + boardSize: BoardSize.Size104x104, + lightLevel: 50, + }); +}); + test("waits for an image acknowledgement", async () => { const { client, notify } = createClient(); await client.connect(); @@ -97,3 +137,45 @@ test("waits for an image acknowledgement", async () => { assert.deepEqual(progress, [[0, 1], [1, 1]]); }); + +test("starts the acknowledgement timeout after writing the complete frame", async () => { + const { client, write, notify } = createClient({ + acknowledgementTimeoutMs: 20, + writeDelayMs: 10, + }); + await client.connect(); + write.onWrite = () => { + if (write.writes.length === 6) { + setTimeout(() => notify.notify(Uint8Array.of(5, 0, 2, 0, 3)), 1); + } + }; + + await client.sendPngImage( + Uint8Array.of(0x11, 0x22, 0x33), + BoardSize.Size52x52, + ); + + assert.equal(write.writes.length, 6); +}); + +test("uses 509-byte GATT writes by default", async () => { + const { client, write, notify } = createClient({ + useDefaultMaxWriteSize: true, + }); + await client.connect(); + write.onWrite = () => { + if (write.writes.length === 2) { + notify.notify(Uint8Array.of(5, 0, 2, 0, 3)); + } + }; + + await client.sendPngImage( + new Uint8Array(600), + BoardSize.Size52x52, + ); + + assert.equal(write.writes.length, 2); + assert.equal(write.writes[0].length, 509); + assert.ok(write.writes[1].length > 0); + assert.ok(write.writes[1].length <= 509); +});