allblue-hid 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,90 @@
1
+ # Local workspace data & isolated git worktrees
2
+ /.data/
3
+ /.worktrees/
4
+
5
+ # OS & Editor metadata
6
+ .DS_Store
7
+ Thumbs.db
8
+ *.swp
9
+ *.swo
10
+ *~
11
+ .idea/
12
+ .vscode/
13
+ *.iml
14
+
15
+ # Shared build & release staging
16
+ /dist/
17
+ /artifacts/
18
+
19
+ # Rust
20
+ /rust/Cargo.lock
21
+ **/target/
22
+
23
+ # C / C++
24
+ **/cmake-build-*/
25
+ *.o
26
+ *.obj
27
+ *.a
28
+ *.lib
29
+ *.so
30
+ *.so.*
31
+ *.dylib
32
+ *.dll
33
+ *.pdb
34
+ *.exp
35
+ *.xcframework/
36
+
37
+ # Dart / Flutter
38
+ **/.dart_tool/
39
+ **/.packages
40
+ **/build/
41
+ **/.flutter-plugins
42
+ **/.flutter-plugins-dependencies
43
+
44
+ # Go
45
+ **/vendor/
46
+ *.exe
47
+ *.test
48
+ *.out
49
+
50
+ # Python
51
+ **/__pycache__/
52
+ **/*.py[cod]
53
+ **/.venv/
54
+ **/venv/
55
+ **/*.egg-info/
56
+ **/.pytest_cache/
57
+ **/.mypy_cache/
58
+ **/.ruff_cache/
59
+
60
+ # TypeScript / JavaScript
61
+ **/node_modules/
62
+ **/.turbo/
63
+ *.tsbuildinfo
64
+ *.node
65
+
66
+ # JVM / Kotlin / Android
67
+ **/.gradle/
68
+ **/local.properties
69
+ *.apk
70
+ *.aab
71
+ *.aar
72
+ *.jar
73
+ !**/gradle/wrapper/gradle-wrapper.jar
74
+
75
+ # Zig
76
+ **/.zig-cache/
77
+ **/zig-cache/
78
+ **/zig-out/
79
+
80
+ # .NET / C#
81
+ **/[Bb]in/
82
+ **/[Oo]bj/
83
+ *.nupkg
84
+ *.snupkg
85
+ *.user
86
+
87
+ # Swift
88
+ **/.build/
89
+ **/.swiftpm/
90
+ **/DerivedData/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 fewensa
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is furnished
10
+ to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice (including the next
13
+ paragraph) shall be included in all copies or substantial portions of the
14
+ Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
18
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
19
+ OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
21
+ OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.5
2
+ Name: allblue-hid
3
+ Version: 0.1.0
4
+ Summary: Discrete HID report SDK for ALLBlue
5
+ Project-URL: Repository, https://github.com/fewensa/allblue
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.9
8
+ Requires-Dist: cffi>=1.16
9
+ Description-Content-Type: text/markdown
10
+
11
+ # ALLBlue HID
12
+
13
+ Use this standalone package to work with discrete input, output, and feature
14
+ reports. Report IDs are separate from payload bytes, including report ID zero.
15
+
16
+ ```python
17
+ from allblue_hid import ALLBlueHidDevice
18
+
19
+ devices = ALLBlueHidDevice.devices(filter=lambda info: info.usage_page == 0xff00)
20
+ if devices:
21
+ with ALLBlueHidDevice.open(devices[0]) as device:
22
+ with device.watch_input_reports() as reports:
23
+ device.write_output_report(2, b"ping")
24
+ report_id, data = next(reports)
25
+ ```
26
+
27
+ Input report and discovery watchers support sync and async iteration.
28
+ Use them with `with` or `async with`, or call `close()` when finished.
29
+ Each subscription retains up to 256 unconsumed events. Reading an input
30
+ report directly from the device is independent of every watcher.
31
+
32
+ ## Native library selection
33
+
34
+ Set `ALLBLUE_LIB_DIR` to a directory containing a release library or a
35
+ Cargo-built FFI library. To build offline from a source checkout, set
36
+ `ALLBLUE_BUILD_FROM_SOURCE=1` with the Rust dependencies cached.
37
+ Otherwise, the SDK uses its bundled library or a verified release cache.
38
+ `ALLBLUE_CACHE_DIR` overrides the cache location and `ALLBLUE_OFFLINE=1`
39
+ requires a warm cache. Downloads require a package release pin and are
40
+ verified before extraction. A wheel can be built with
41
+ `ALLBLUE_LIB_DIR=/path/to/libraries uv build --wheel` from this directory.
@@ -0,0 +1,31 @@
1
+ # ALLBlue HID
2
+
3
+ Use this standalone package to work with discrete input, output, and feature
4
+ reports. Report IDs are separate from payload bytes, including report ID zero.
5
+
6
+ ```python
7
+ from allblue_hid import ALLBlueHidDevice
8
+
9
+ devices = ALLBlueHidDevice.devices(filter=lambda info: info.usage_page == 0xff00)
10
+ if devices:
11
+ with ALLBlueHidDevice.open(devices[0]) as device:
12
+ with device.watch_input_reports() as reports:
13
+ device.write_output_report(2, b"ping")
14
+ report_id, data = next(reports)
15
+ ```
16
+
17
+ Input report and discovery watchers support sync and async iteration.
18
+ Use them with `with` or `async with`, or call `close()` when finished.
19
+ Each subscription retains up to 256 unconsumed events. Reading an input
20
+ report directly from the device is independent of every watcher.
21
+
22
+ ## Native library selection
23
+
24
+ Set `ALLBLUE_LIB_DIR` to a directory containing a release library or a
25
+ Cargo-built FFI library. To build offline from a source checkout, set
26
+ `ALLBLUE_BUILD_FROM_SOURCE=1` with the Rust dependencies cached.
27
+ Otherwise, the SDK uses its bundled library or a verified release cache.
28
+ `ALLBLUE_CACHE_DIR` overrides the cache location and `ALLBLUE_OFFLINE=1`
29
+ requires a warm cache. Downloads require a package release pin and are
30
+ verified before extraction. A wheel can be built with
31
+ `ALLBLUE_LIB_DIR=/path/to/libraries uv build --wheel` from this directory.
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.24"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "allblue-hid"
7
+ version = "0.1.0"
8
+ description = "Discrete HID report SDK for ALLBlue"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.9"
12
+ dependencies = ["cffi>=1.16"]
13
+
14
+ [project.urls]
15
+ Repository = "https://github.com/fewensa/allblue"
16
+
17
+ [tool.hatch.build.targets.wheel]
18
+ packages = ["src/allblue_hid"]
19
+
20
+ [tool.hatch.build.hooks.custom]
21
+ path = "src/allblue_hid/_loader.py"
22
+
23
+ [tool.mypy]
24
+ strict = true
@@ -0,0 +1,13 @@
1
+ from .device import (
2
+ ALLBlueHidDevice,
3
+ ALLBlueHidInfo,
4
+ HidDeviceWatcher,
5
+ HidReportWatcher,
6
+ )
7
+
8
+ __all__ = [
9
+ "ALLBlueHidDevice",
10
+ "ALLBlueHidInfo",
11
+ "HidDeviceWatcher",
12
+ "HidReportWatcher",
13
+ ]
@@ -0,0 +1,179 @@
1
+ """ABI declarations from the public C header."""
2
+ from importlib import import_module
3
+
4
+ ffi = import_module("cffi").FFI()
5
+ ffi.cdef("""
6
+ enum {
7
+ ALLBLUE_HID_OK = 0,
8
+ ALLBLUE_HID_ERR_INVALID_ARG = -1,
9
+ ALLBLUE_HID_ERR_NOT_FOUND = -2,
10
+ ALLBLUE_HID_ERR_PERMISSION = -3,
11
+ ALLBLUE_HID_ERR_TIMEOUT = -4,
12
+ ALLBLUE_HID_ERR_DISCONNECTED = -5,
13
+ ALLBLUE_HID_ERR_PACKET_TOO_BIG = -6,
14
+ ALLBLUE_HID_ERR_UNSUPPORTED = -7,
15
+ ALLBLUE_HID_ERR_BUSY = -8,
16
+ ALLBLUE_HID_ERR_IO = -9,
17
+ ALLBLUE_HID_ERR_INTERNAL = -10
18
+ };
19
+ enum {
20
+ ALLBLUE_HID_BUS_UNKNOWN = 0,
21
+ ALLBLUE_HID_BUS_USB = 1,
22
+ ALLBLUE_HID_BUS_BLUETOOTH = 2,
23
+ ALLBLUE_HID_BUS_BLE_HOGP = 3
24
+ };
25
+
26
+ typedef struct allblue_hid_device allblue_hid_device;
27
+
28
+ typedef struct allblue_hid_discover_watcher allblue_hid_discover_watcher;
29
+
30
+ typedef struct allblue_hid_discoverer allblue_hid_discoverer;
31
+
32
+ typedef struct allblue_hid_input_sink allblue_hid_input_sink;
33
+
34
+ typedef struct allblue_hid_watcher allblue_hid_watcher;
35
+
36
+ typedef int32_t allblue_hid_status_t;
37
+
38
+ typedef struct allblue_hid_input_sink allblue_hid_input_sink_t;
39
+
40
+ typedef struct allblue_hid_custom_vtable_t {
41
+ uint32_t struct_size;
42
+ void *user_data;
43
+ void (*bind)(void*, allblue_hid_input_sink_t*);
44
+ int32_t (*write_output)(void*, uint8_t, const uint8_t*, size_t, size_t*);
45
+ int32_t (*send_feature)(void*, uint8_t, const uint8_t*, size_t);
46
+ int32_t (*get_feature)(void*, uint8_t, uint8_t*, size_t, size_t*);
47
+ void (*destroy)(void*);
48
+ } allblue_hid_custom_vtable_t;
49
+
50
+ typedef struct allblue_hid_device allblue_hid_device_t;
51
+
52
+ typedef struct allblue_hid_info_t {
53
+ uint32_t struct_size;
54
+ const char *id;
55
+ const char *path;
56
+ uint16_t vid;
57
+ uint16_t pid;
58
+ uint16_t release_number;
59
+ uint16_t usage_page;
60
+ uint16_t usage;
61
+ int32_t bus_type;
62
+ const char *serial_number;
63
+ const char *manufacturer;
64
+ const char *product;
65
+ size_t max_input_report_len;
66
+ size_t max_output_report_len;
67
+ size_t max_feature_report_len;
68
+ } allblue_hid_info_t;
69
+
70
+ typedef uint8_t (*allblue_hid_filter_fn)(const struct allblue_hid_info_t*, void*);
71
+
72
+ typedef void (*allblue_hid_discover_fn)(const struct allblue_hid_info_t*, void*);
73
+
74
+ typedef struct allblue_hid_discoverer allblue_hid_discoverer_t;
75
+
76
+ typedef void (*allblue_hid_doorbell_fn)(void*);
77
+
78
+ typedef struct allblue_hid_discover_watcher allblue_hid_discover_watcher_t;
79
+
80
+ typedef void (*allblue_hid_watch_report_fn)(uint8_t, const uint8_t*, size_t, void*);
81
+
82
+ typedef struct allblue_hid_watcher allblue_hid_watcher_t;
83
+
84
+ const char *allblue_hid_last_error_message(void);
85
+
86
+ allblue_hid_status_t allblue_hid_open_custom(const struct allblue_hid_custom_vtable_t *vtable,
87
+ allblue_hid_device_t **out_dev);
88
+
89
+ allblue_hid_status_t allblue_hid_input_sink_push(allblue_hid_input_sink_t *sink,
90
+ uint8_t report_id,
91
+ const uint8_t *payload,
92
+ size_t len);
93
+
94
+ allblue_hid_status_t allblue_hid_input_sink_disconnect(allblue_hid_input_sink_t *sink);
95
+
96
+ void allblue_hid_input_sink_free(allblue_hid_input_sink_t *sink);
97
+
98
+ allblue_hid_status_t allblue_hid_open(const char *device_id_or_path,
99
+ allblue_hid_device_t **out_dev);
100
+
101
+ allblue_hid_status_t allblue_hid_open_android_fd(int32_t fd,
102
+ uint8_t interface_number,
103
+ allblue_hid_device_t **out_dev);
104
+
105
+ allblue_hid_status_t allblue_hid_close(allblue_hid_device_t *dev);
106
+
107
+ void allblue_hid_free(allblue_hid_device_t *dev);
108
+
109
+ allblue_hid_status_t allblue_hid_write_output_report(allblue_hid_device_t *dev,
110
+ uint8_t report_id,
111
+ const uint8_t *payload,
112
+ size_t len,
113
+ size_t *out_written);
114
+
115
+ allblue_hid_status_t allblue_hid_read_input_report(allblue_hid_device_t *dev,
116
+ uint8_t *out_report_id,
117
+ uint8_t *buf,
118
+ size_t cap,
119
+ int64_t timeout_ms,
120
+ size_t *out_len);
121
+
122
+ allblue_hid_status_t allblue_hid_clear_read_buffer(allblue_hid_device_t *dev);
123
+
124
+ allblue_hid_status_t allblue_hid_send_feature_report(allblue_hid_device_t *dev,
125
+ uint8_t report_id,
126
+ const uint8_t *payload,
127
+ size_t len);
128
+
129
+ allblue_hid_status_t allblue_hid_get_feature_report(allblue_hid_device_t *dev,
130
+ uint8_t report_id,
131
+ uint8_t *buf,
132
+ size_t cap,
133
+ size_t *out_len);
134
+
135
+ allblue_hid_status_t allblue_hid_discover(allblue_hid_filter_fn filter,
136
+ allblue_hid_discover_fn on_device,
137
+ void *user_data,
138
+ allblue_hid_discoverer_t **out);
139
+
140
+ void allblue_hid_discover_stop(allblue_hid_discoverer_t *p);
141
+
142
+ allblue_hid_status_t allblue_hid_discover_watcher_open(size_t queue_capacity,
143
+ allblue_hid_doorbell_fn on_readable,
144
+ void *user_data,
145
+ allblue_hid_discover_watcher_t **out);
146
+
147
+ allblue_hid_status_t allblue_hid_discover_watcher_try_next(allblue_hid_discover_watcher_t *p,
148
+ struct allblue_hid_info_t **out);
149
+
150
+ void allblue_hid_discover_watcher_close(allblue_hid_discover_watcher_t *p);
151
+
152
+ allblue_hid_status_t allblue_hid_devices(allblue_hid_filter_fn filter,
153
+ void *user_data,
154
+ struct allblue_hid_info_t **out_list,
155
+ size_t *out_count);
156
+
157
+ void allblue_hid_devices_free(struct allblue_hid_info_t *p, size_t count);
158
+
159
+ allblue_hid_status_t allblue_hid_watch_input_reports(allblue_hid_device_t *dev,
160
+ allblue_hid_watch_report_fn cb,
161
+ void *user_data,
162
+ uint64_t *out_watch_id);
163
+
164
+ allblue_hid_status_t allblue_hid_unwatch(allblue_hid_device_t *dev, uint64_t watch_id);
165
+
166
+ allblue_hid_status_t allblue_hid_watcher_open(allblue_hid_device_t *dev,
167
+ size_t queue_capacity,
168
+ allblue_hid_doorbell_fn on_readable,
169
+ void *user_data,
170
+ allblue_hid_watcher_t **out);
171
+
172
+ allblue_hid_status_t allblue_hid_watcher_try_read(allblue_hid_watcher_t *p,
173
+ uint8_t *out_report_id,
174
+ uint8_t *buf,
175
+ size_t cap,
176
+ size_t *out_len);
177
+
178
+ void allblue_hid_watcher_close(allblue_hid_watcher_t *p);
179
+ """)
@@ -0,0 +1,144 @@
1
+ """Locate the ABI library and bundle it when building a platform wheel."""
2
+ from __future__ import annotations
3
+
4
+ from functools import lru_cache
5
+ from importlib import import_module, util
6
+ import os
7
+ import re
8
+ from pathlib import Path
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ import sysconfig
13
+ from typing import Any
14
+
15
+ PACKAGE = "allblue-hid"
16
+ MODULE = PACKAGE.replace("-", "_")
17
+ VERSION = "0.1.0"
18
+
19
+
20
+ def _member() -> Path:
21
+ if sys.platform == "win32":
22
+ return Path("bin") / f"{MODULE}.dll"
23
+ suffix = "dylib" if sys.platform == "darwin" else "so"
24
+ return Path("lib") / f"lib{MODULE}.{suffix}"
25
+
26
+
27
+ def _reference_path() -> Path:
28
+ local = Path(__file__).with_name("_release.py")
29
+ if local.is_file():
30
+ return local
31
+ # In a checkout both distributions consume the repository implementation.
32
+ return Path(__file__).resolve().parents[4] / "scripts/allblue_resolver.py"
33
+
34
+
35
+ @lru_cache(maxsize=1)
36
+ def _reference() -> Any:
37
+ path = _reference_path()
38
+ spec = util.spec_from_file_location(f"{MODULE}._release", path)
39
+ if spec is None or spec.loader is None:
40
+ raise ImportError(f"Cannot load release resolver from {path}")
41
+ reference = util.module_from_spec(spec)
42
+ spec.loader.exec_module(reference)
43
+ return reference
44
+
45
+
46
+ def _from_directory(directory: Path, name: str) -> Path:
47
+ for candidate in (directory / name, directory / name.replace(".", "_ffi.", 1)):
48
+ if candidate.is_file():
49
+ return candidate.resolve()
50
+ raise FileNotFoundError(f"Missing {name} in {directory}")
51
+
52
+
53
+ def _from_source(cache: Path, name: str) -> Path:
54
+ for root in (*Path(__file__).resolve().parents, Path.cwd(), *Path.cwd().parents):
55
+ manifest = root / "rust/Cargo.toml"
56
+ if (root / f"rust/crates/{PACKAGE}-ffi/Cargo.toml").is_file() and manifest.is_file():
57
+ break
58
+ else:
59
+ raise FileNotFoundError("Building from source requires an ALLBlue source checkout")
60
+ cargo = shutil.which("cargo")
61
+ if cargo is None:
62
+ raise FileNotFoundError("Install the Rust toolchain and put cargo on PATH")
63
+ reference = _reference()
64
+ target = cache.resolve() / "from-source" / VERSION / reference.host_target()
65
+ with reference.locked(cache / ".lock"):
66
+ subprocess.run([cargo, "build", "--manifest-path", str(manifest), "--offline",
67
+ "--profile", "release-ffi", "-p", PACKAGE + "-ffi",
68
+ "--target-dir", str(target)], check=True,
69
+ env=dict(os.environ, CARGO_BUILD_JOBS="4"))
70
+ return _from_directory(target / "release-ffi", name)
71
+
72
+
73
+ def resolve() -> Path:
74
+ member = _member()
75
+ if directory := os.environ.get("ALLBLUE_LIB_DIR"):
76
+ return _from_directory(Path(directory), member.name)
77
+ reference = _reference()
78
+ cache = Path(reference.cache_dir())
79
+ if os.environ.get("ALLBLUE_BUILD_FROM_SOURCE", "").lower() in {"1", "true"}:
80
+ return _from_source(cache, member.name)
81
+ bundled = Path(__file__).with_name("_libs") / member.name
82
+ if bundled.is_file():
83
+ return bundled
84
+ target: str = reference.host_target()
85
+ dest = cache / f"v{VERSION}" / PACKAGE / target
86
+ if reference.verified(dest, member):
87
+ return dest / member
88
+ asset = reference.asset_name(PACKAGE, VERSION, target)
89
+ pins: dict[str, str] = import_module(f"{MODULE}._native_hashes").NATIVE_HASHES
90
+ if asset not in pins and os.environ.get("ALLBLUE_OFFLINE") != "1":
91
+ raise ValueError(f"No release SHA-256 pin for {asset}")
92
+ return Path(reference.resolve(VERSION, PACKAGE, target, pins.get(asset)))
93
+
94
+
95
+ @lru_cache(maxsize=1)
96
+ def native() -> Any:
97
+ ffi = import_module(f"{MODULE}._cdefs").ffi
98
+ library = ffi.dlopen(str(resolve()))
99
+ return library
100
+
101
+
102
+ def get_build_hook() -> Any:
103
+ from hatchling.builders.hooks.plugin.interface import BuildHookInterface
104
+
105
+ class NativeBuild(BuildHookInterface[Any]):
106
+ def initialize(self, version: str, build_data: dict[str, Any]) -> None:
107
+ included = build_data["force_include"]
108
+ root = Path(self.root)
109
+ license_file = root / "LICENSE"
110
+ if not license_file.is_file():
111
+ license_file = root.parents[1] / "LICENSE"
112
+ if self.target_name == "sdist":
113
+ included[str(license_file)] = "LICENSE"
114
+ included[str(_reference_path())] = f"src/{MODULE}/_release.py"
115
+ return
116
+ included[str(license_file)] = f"{MODULE}/LICENSE"
117
+ included[str(_reference_path())] = f"{MODULE}/_release.py"
118
+ platform_tag = os.environ.get("ALLBLUE_WHEEL_TAG")
119
+ directory = os.environ.get("ALLBLUE_LIB_DIR")
120
+ filename = os.environ.get("ALLBLUE_LIB_FILENAME")
121
+ if platform_tag and not re.fullmatch(r"[a-z0-9]+(?:_[a-z0-9]+)*", platform_tag):
122
+ raise ValueError(f"Invalid wheel platform tag: {platform_tag}")
123
+ if platform_tag and not directory:
124
+ raise ValueError("ALLBLUE_WHEEL_TAG requires ALLBLUE_LIB_DIR")
125
+ if filename:
126
+ if not directory or filename in (".", "..") or "/" in filename or "\\" in filename:
127
+ raise ValueError("ALLBLUE_LIB_FILENAME must name a file in ALLBLUE_LIB_DIR")
128
+ library = Path(directory).resolve() / filename
129
+ if not library.is_file():
130
+ raise FileNotFoundError(library)
131
+ else:
132
+ filename = _member().name
133
+ sys.path.insert(0, str(root / "src"))
134
+ try:
135
+ library = resolve()
136
+ finally:
137
+ sys.path.pop(0)
138
+ if not platform_tag:
139
+ platform_tag = sysconfig.get_platform().replace("-", "_").replace(".", "_")
140
+ build_data["tag"] = f"py3-none-{platform_tag}"
141
+ build_data["pure_python"] = False
142
+ included[str(library)] = f"{MODULE}/_libs/{filename}"
143
+
144
+ return NativeBuild
@@ -0,0 +1,11 @@
1
+ NATIVE_HASHES = {
2
+ "allblue-hid-v0.1.0-android-universal.aar": "29d5074d186a704f4c3f8f0dfb77f69b48cfdffc795f19c1b5a0c7d52fccbeff",
3
+ "allblue-hid-v0.1.0-apple-universal.xcframework.zip": "f5d1fd7259a0a56276d8a7f793962425f39a33c6db56be60568a19d469be616e",
4
+ "allblue-hid-v0.1.0-linux-aarch64-gnu.tar.gz": "e78a3b7365d4769fe84b3706fd367cfef41525640514e294ae7919d45a1be2f7",
5
+ "allblue-hid-v0.1.0-linux-armv7-gnueabihf.tar.gz": "63e9fd5e2d578b4510d095a0a59988213268efb83a5da8db6d6e4775d9f10690",
6
+ "allblue-hid-v0.1.0-linux-x86_64-gnu.tar.gz": "7b789ef7e2490660da1c6c98500dc300eeb1c5a2f5340181ab63c0cb601876cb",
7
+ "allblue-hid-v0.1.0-macos-universal.tar.gz": "d3cfc27e5a4e584a2af55cedae1b69ff2bf52050fae38a867d85aaed8c9fd579",
8
+ "allblue-hid-v0.1.0-windows-aarch64.zip": "c2cfe4c78c9e07837722ebaa067fede5b7174ffc447a414dacf8e91a0e417096",
9
+ "allblue-hid-v0.1.0-windows-i686.zip": "1735ff9c48c52042969f44943bf6dea126404461d005278889998af0e3b31f08",
10
+ "allblue-hid-v0.1.0-windows-x86_64.zip": "8a0e72a8111e5d821332163492049d6bb94f3785c11ea75eb6580159cc3132d1",
11
+ }
@@ -0,0 +1 @@
1
+ NATIVE_HASHES: dict[str, str]
@@ -0,0 +1,327 @@
1
+ """Reference implementation for pinned ALLBlue release archives and native libraries."""
2
+ from contextlib import contextmanager
3
+ import errno
4
+ import hashlib
5
+ import http.client
6
+ import ntpath
7
+ import os
8
+ from pathlib import Path, PurePosixPath, PureWindowsPath
9
+ import platform
10
+ import re
11
+ import shutil
12
+ import stat
13
+ import subprocess
14
+ import sys
15
+ import tarfile
16
+ import tempfile
17
+ import time
18
+ from urllib.error import HTTPError, URLError
19
+ from urllib.request import urlopen
20
+ import uuid
21
+ import zipfile
22
+
23
+
24
+ ROOT = Path(__file__).resolve().parents[1]
25
+ MIRROR = "https://github.com/fewensa/allblue/releases/download"
26
+ VERSION = re.compile(r"(?:0|[1-9][0-9]*)(?:\.(?:0|[1-9][0-9]*)){2}")
27
+ PACKAGES = ("allblue", "allblue-hid")
28
+ SUFFIXES = {
29
+ "apple-xcframework": "apple-universal.xcframework.zip",
30
+ "macos-universal": "macos-universal.tar.gz",
31
+ **{f"windows-{a}": f"windows-{a}.zip" for a in ("x86_64", "i686", "aarch64")},
32
+ **{f"linux-{a}": f"linux-{a}.tar.gz" for a in ("x86_64-gnu", "aarch64-gnu", "armv7-gnueabihf")},
33
+ "android-universal": "android-universal.aar",
34
+ "wasm32": "wasm32.tar.gz",
35
+ }
36
+
37
+
38
+ def asset_name(pkg, version, target):
39
+ if pkg not in PACKAGES or not VERSION.fullmatch(version):
40
+ raise ValueError(f"Invalid package or version: {pkg} {version}")
41
+ return f"{pkg}-v{version}-{SUFFIXES[target]}"
42
+
43
+
44
+ def layout(pkg, target):
45
+ """Return manifest path fields and the files required to exist in the archive."""
46
+ stem = pkg.replace("-", "_")
47
+ if target == "apple-xcframework":
48
+ bundle = "ALLBlue.xcframework" if pkg == "allblue" else "ALLBlueHid.xcframework"
49
+ return {"xcframework": bundle}, [f"{bundle}/Info.plist"]
50
+ if target == "android-universal":
51
+ libs = [f"jni/{abi}/lib{stem}.so" for abi in ("arm64-v8a", "armeabi-v7a", "x86_64", "x86")]
52
+ return {"shared_libs": libs}, libs
53
+ if target == "wasm32":
54
+ wasm = f"lib/{stem}_wasm.wasm"
55
+ return {"wasm": wasm}, [wasm]
56
+ if target.startswith("windows-"):
57
+ fields = {"shared_lib": f"bin/{stem}.dll", "import_lib": f"lib/{stem}.dll.lib",
58
+ "static_lib": f"lib/{stem}_static.lib"}
59
+ else:
60
+ ext = "dylib" if target == "macos-universal" else "so"
61
+ fields = {"shared_lib": f"lib/lib{stem}.{ext}", "static_lib": f"lib/lib{stem}.a"}
62
+ return {**fields, "header_dir": "include"}, [*fields.values(), f"include/allblue/{stem}.h"]
63
+
64
+
65
+ def sha256(path):
66
+ digest = hashlib.sha256()
67
+ with path.open("rb") as stream:
68
+ for chunk in iter(lambda: stream.read(65536), b""):
69
+ digest.update(chunk)
70
+ return digest.hexdigest()
71
+
72
+
73
+ def reserved_component(part):
74
+ if hasattr(ntpath, "isreserved"):
75
+ return ntpath.isreserved(part)
76
+ return PureWindowsPath(part).is_reserved()
77
+
78
+
79
+ def safe_path(name):
80
+ path = PurePosixPath(name)
81
+ if (path.is_absolute() or ".." in path.parts or "\\" in name
82
+ or any(":" in p or p.endswith((" ", ".")) or reserved_component(p)
83
+ or any(ord(c) < 32 for c in p) for p in path.parts)):
84
+ raise ValueError(f"Unsafe archive path: {name!r}")
85
+ return path
86
+
87
+
88
+ def inspect_archive(archive, target, pkg, destination=None):
89
+ """Only materialize regular members. Create internal symlinks last in a private directory."""
90
+ files, dirs, links = set(), set(), {}
91
+ seen = set()
92
+ is_tar = target.startswith("linux-") or target in ("macos-universal", "wasm32")
93
+ with (tarfile.open(archive, "r:gz") if is_tar else zipfile.ZipFile(archive)) as container:
94
+ for entry in container if is_tar else container.infolist():
95
+ name = safe_path(entry.name if is_tar else entry.orig_filename)
96
+ if is_tar:
97
+ directory, link, regular = entry.isdir(), entry.issym(), entry.isreg()
98
+ else:
99
+ mode = stat.S_IFMT(entry.external_attr >> 16)
100
+ directory, link = entry.is_dir(), mode == stat.S_IFLNK
101
+ regular = mode in (0, stat.S_IFREG)
102
+ if not name.parts and directory:
103
+ continue
104
+ key = name.as_posix().casefold()
105
+ if key in seen or not name.parts or name.parts[0].casefold() == ".complete":
106
+ raise ValueError(f"Duplicate or reserved archive path: {name}")
107
+ seen.add(key)
108
+ if directory:
109
+ dirs.add(name)
110
+ elif link:
111
+ if not is_tar and entry.file_size > 4096:
112
+ raise ValueError(f"Oversized symlink: {name}")
113
+ value = entry.linkname if is_tar else container.read(entry).decode()
114
+ links[name] = safe_path(value)
115
+ elif regular:
116
+ files.add(name)
117
+ if destination is not None:
118
+ output = destination / name
119
+ output.parent.mkdir(parents=True, exist_ok=True)
120
+ stream = container.extractfile(entry) if is_tar else container.open(entry)
121
+ with stream, output.open("xb") as writer:
122
+ shutil.copyfileobj(stream, writer)
123
+ else:
124
+ raise ValueError(f"Unsupported member type: {name}")
125
+ leaves = {str(p).casefold() for p in files | links.keys()}
126
+ if any(str(p).casefold() in leaves for n in files | dirs | links.keys() for p in n.parents):
127
+ raise ValueError("File or link used as an archive directory")
128
+ fields, required = layout(pkg, target)
129
+ if missing := set(map(PurePosixPath, required)) - files:
130
+ raise ValueError(f"Missing payload in {archive.name}: {sorted(map(str, missing))}")
131
+ if target == "apple-xcframework" and not any(p.name == "PrivacyInfo.xcprivacy" for p in files):
132
+ raise ValueError(f"Missing privacy manifest in {archive.name}")
133
+ if destination is not None:
134
+ for name in dirs:
135
+ (destination / name).mkdir(parents=True, exist_ok=True)
136
+ for name, value in links.items():
137
+ output = destination / name
138
+ output.parent.mkdir(parents=True, exist_ok=True)
139
+ output.symlink_to(str(value), target_is_directory=(output.parent / value).is_dir())
140
+ return fields
141
+
142
+
143
+ class OfflineCacheMissError(RuntimeError):
144
+ pass
145
+
146
+
147
+ class ChecksumMismatchError(RuntimeError):
148
+ pass
149
+
150
+
151
+ @contextmanager
152
+ def locked(path):
153
+ path.parent.mkdir(parents=True, exist_ok=True)
154
+ with path.open("a+b") as lock:
155
+ if os.name == "nt":
156
+ import msvcrt
157
+ lock.seek(0)
158
+ while True:
159
+ try:
160
+ msvcrt.locking(lock.fileno(), msvcrt.LK_LOCK, 1)
161
+ break
162
+ except OSError as exc:
163
+ if exc.errno not in (errno.EACCES, errno.EDEADLK):
164
+ raise
165
+ else:
166
+ import fcntl
167
+ fcntl.flock(lock, fcntl.LOCK_EX)
168
+ yield # Closing the file releases the OS lock, including on exceptions.
169
+
170
+
171
+ def host_target():
172
+ arch = platform.machine().lower()
173
+ arch = {"amd64": "x86_64", "arm64": "aarch64", "i386": "i686", "armv7l": "armv7"}.get(arch, arch)
174
+ if sys.platform == "darwin":
175
+ return "macos-universal"
176
+ if sys.platform == "win32":
177
+ return f"windows-{arch}"
178
+ if sys.platform.startswith("linux"):
179
+ return "linux-armv7-gnueabihf" if arch == "armv7" else f"linux-{arch}-gnu"
180
+ raise ValueError(f"Unsupported host: {sys.platform} {arch}")
181
+
182
+
183
+ def cache_dir():
184
+ if override := os.environ.get("ALLBLUE_CACHE_DIR"):
185
+ return Path(override)
186
+ if sys.platform == "darwin":
187
+ return Path.home() / "Library/Caches/allblue"
188
+ if os.name == "nt":
189
+ return Path(os.environ["LOCALAPPDATA"]) / "allblue/cache"
190
+ return Path.home() / ".cache/allblue"
191
+
192
+
193
+ def build_ffi(target_dir, triple=None, offline=False):
194
+ cargo = shutil.which("cargo")
195
+ if not cargo:
196
+ raise RuntimeError("Install the Rust toolchain and put cargo on PATH to build ALLBlue.")
197
+ command = [cargo, "build", "--manifest-path", str(ROOT / "rust/Cargo.toml"), "-p", "allblue-ffi",
198
+ "-p", "allblue-hid-ffi", "--profile", "release-ffi", "--target-dir", str(target_dir)]
199
+ if triple:
200
+ command.extend(["--target", triple])
201
+ if offline:
202
+ command.append("--offline")
203
+ env = dict(os.environ, CARGO_BUILD_JOBS="4")
204
+ subprocess.run(command, cwd=ROOT, env=env, check=True)
205
+ output = target_dir / (triple or "") / "release-ffi"
206
+ slim = ROOT / "scripts/slim-staticlib.sh"
207
+ for pkg in PACKAGES:
208
+ stem = pkg.replace("-", "_")
209
+ archive = output / f"lib{stem}_ffi.a"
210
+ if archive.is_file() and slim.exists() and (not triple or "linux" in triple or "apple" in triple):
211
+ args = [str(slim), "--crate", pkg, "--input", str(archive),
212
+ "--output", str(output / f"lib{stem}.a")]
213
+ subprocess.run(args + (["--target", triple] if triple else []), check=True, env=env)
214
+ return output
215
+
216
+
217
+ def source_library(cache, version, pkg, target, primary):
218
+ if target != host_target():
219
+ raise ValueError(f"Source resolver requires a host target, got {target}")
220
+ with locked(cache / ".lock"):
221
+ output = build_ffi(Path(os.environ.get("CARGO_TARGET_DIR", ROOT / "rust/target")).resolve(),
222
+ offline=True)
223
+ built = output / primary.name.replace(".", "_ffi.", 1)
224
+ if not built.is_file():
225
+ raise FileNotFoundError(f"Cargo did not produce the requested {pkg} library: {built}")
226
+ dest = cache / "from-source" / version / target
227
+ dest.mkdir(parents=True, exist_ok=True)
228
+ temp = dest / f"{primary.name}.{uuid.uuid4().hex}.tmp"
229
+ try:
230
+ shutil.copyfile(built, temp)
231
+ os.replace(temp, dest / primary.name)
232
+ finally:
233
+ temp.unlink(missing_ok=True)
234
+ return dest / primary.name
235
+
236
+
237
+ def verified(dest, primary):
238
+ try:
239
+ return (dest / ".complete").read_text("ascii").strip() == sha256(dest / primary)
240
+ except (OSError, UnicodeError):
241
+ return False
242
+
243
+
244
+ def download(url, archive):
245
+ for delay in (0, 0.5, 1.5):
246
+ time.sleep(delay)
247
+ try:
248
+ with urlopen(url, timeout=10) as response, archive.open("wb") as writer:
249
+ if isinstance(response, http.client.HTTPResponse) and response.fp is not None:
250
+ response.fp.raw._sock.settimeout(60)
251
+ shutil.copyfileobj(response, writer, 65536)
252
+ if isinstance(response, http.client.HTTPResponse) and response.length:
253
+ raise http.client.IncompleteRead(b"", response.length)
254
+ return
255
+ except HTTPError as exc:
256
+ exc.close()
257
+ if not 500 <= exc.code < 600 or delay == 1.5:
258
+ raise
259
+ except (URLError, ConnectionError, TimeoutError, http.client.IncompleteRead):
260
+ if delay == 1.5:
261
+ raise
262
+
263
+
264
+ def resolve(version, pkg, target, pinned_sha256):
265
+ """Return the host library path. A missing static pin selects the release checksum file."""
266
+ asset = asset_name(pkg, version, target)
267
+ fields, _ = layout(pkg, target)
268
+ if "shared_lib" not in fields:
269
+ raise ValueError(f"No desktop shared library for {target}")
270
+ primary = Path(fields["shared_lib"])
271
+ if override := os.environ.get("ALLBLUE_LIB_DIR"):
272
+ library = Path(override) / primary.name
273
+ if not library.is_file():
274
+ raise FileNotFoundError(f"ALLBLUE_LIB_DIR is missing {library}")
275
+ return library
276
+ cache = cache_dir()
277
+ if os.environ.get("ALLBLUE_BUILD_FROM_SOURCE", "").lower() in ("1", "true"):
278
+ return source_library(cache, version, pkg, target, primary)
279
+ dest = cache / f"v{version}" / pkg / target
280
+ if verified(dest, primary):
281
+ return dest / primary
282
+ with locked(cache / f"v{version}-{pkg}-{target}.lock"):
283
+ if verified(dest, primary):
284
+ return dest / primary
285
+ if os.environ.get("ALLBLUE_OFFLINE") == "1":
286
+ raise OfflineCacheMissError(f"No verified offline cache at {dest}")
287
+ staging = cache / "staging"
288
+ staging.mkdir(exist_ok=True)
289
+ nonce = f"{os.getpid()}.{uuid.uuid4().hex}"
290
+ archive = staging / f"{asset}.tmp.{nonce}"
291
+ mirror = os.environ.get("ALLBLUE_MIRROR_URL", MIRROR).rstrip("/")
292
+ try:
293
+ base = f"{mirror}/v{version}"
294
+ if pinned_sha256 is None:
295
+ download(f"{base}/SHA256SUMS.txt", archive)
296
+ matches = [line.partition(" ")[0] for line in archive.read_text("ascii").splitlines()
297
+ if line.partition(" ")[2] == asset]
298
+ if len(matches) != 1:
299
+ raise ChecksumMismatchError(f"Expected one checksum for {asset}")
300
+ pinned_sha256 = matches[0]
301
+ if not re.fullmatch("[0-9a-fA-F]{64}", pinned_sha256) or pinned_sha256 == "0"*64:
302
+ raise ChecksumMismatchError(f"Invalid SHA-256 for {asset}")
303
+ download(f"{base}/{asset}", archive)
304
+ if sha256(archive) != pinned_sha256.lower():
305
+ raise ChecksumMismatchError(f"Checksum mismatch for {asset}")
306
+ with tempfile.TemporaryDirectory(dir=staging, prefix=f"extract.{nonce}.") as folder:
307
+ extracted = Path(folder)
308
+ inspect_archive(archive, target, pkg, extracted)
309
+ with (extracted / ".complete").open("x", encoding="ascii") as marker:
310
+ marker.write(sha256(extracted / primary) + "\n")
311
+ marker.flush()
312
+ os.fsync(marker.fileno())
313
+ dest.parent.mkdir(parents=True, exist_ok=True)
314
+ if dest.exists():
315
+ shutil.rmtree(dest)
316
+ os.replace(extracted, dest)
317
+ finally:
318
+ archive.unlink(missing_ok=True)
319
+ return dest / primary
320
+
321
+
322
+ if __name__ == "__main__":
323
+ import argparse
324
+ parser = argparse.ArgumentParser(description="Build both FFI packages and slim host static archives.")
325
+ parser.add_argument("--target")
326
+ args = parser.parse_args()
327
+ build_ffi(Path(os.environ.get("CARGO_TARGET_DIR", ROOT / "rust/target")).resolve(), args.target)
@@ -0,0 +1,280 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from collections import deque
5
+ from threading import Condition
6
+ from typing import Any, Callable, Generic, TypeVar
7
+ from weakref import finalize
8
+
9
+ from dataclasses import dataclass
10
+ import math
11
+ from threading import RLock
12
+ from weakref import WeakSet
13
+
14
+ from ._cdefs import ffi
15
+ from ._loader import native
16
+
17
+ T = TypeVar("T")
18
+ W = TypeVar("W", bound="_Subscription[Any]")
19
+
20
+
21
+ class _Inbox(Generic[T]):
22
+ def __init__(self) -> None:
23
+ self.condition = Condition()
24
+ self.items: deque[T] = deque(maxlen=256)
25
+ self.closed = False
26
+ self.waiters: set[tuple[asyncio.AbstractEventLoop, asyncio.Event]] = set()
27
+
28
+ def _wake(self) -> None:
29
+ self.condition.notify_all()
30
+ for loop, event in self.waiters:
31
+ if not loop.is_closed():
32
+ loop.call_soon_threadsafe(event.set)
33
+ self.waiters.clear()
34
+
35
+ def push(self, value: T) -> None:
36
+ with self.condition:
37
+ if not self.closed:
38
+ self.items.append(value)
39
+ self._wake()
40
+
41
+ def finish(self) -> None:
42
+ with self.condition:
43
+ self.closed = True
44
+ self.items.clear()
45
+ self._wake()
46
+
47
+
48
+ class _Subscription(Generic[T]):
49
+ def __init__(self, inbox: _Inbox[T], stop: Callable[[], None], pins: tuple[Any, ...],
50
+ predicate: Callable[[T], bool] | None = None) -> None:
51
+ self._inbox = inbox
52
+ self._predicate = predicate
53
+ self._release = finalize(self, self._stop, inbox, stop, pins)
54
+
55
+ @staticmethod
56
+ def _stop(inbox: _Inbox[T], stop: Callable[[], None], pins: tuple[Any, ...]) -> None:
57
+ # The finalizer retains pins through the native callback drain.
58
+ try:
59
+ stop()
60
+ finally:
61
+ inbox.finish()
62
+
63
+ def close(self) -> None:
64
+ self._release()
65
+
66
+ def __enter__(self: W) -> W:
67
+ return self
68
+
69
+ def __exit__(self, *exc: object) -> None:
70
+ self.close()
71
+
72
+ async def __aenter__(self: W) -> W:
73
+ return self
74
+
75
+ async def __aexit__(self, *exc: object) -> None:
76
+ await asyncio.to_thread(self.close)
77
+
78
+ def __iter__(self: W) -> W:
79
+ return self
80
+
81
+ def __next__(self) -> T:
82
+ box = self._inbox
83
+ while True:
84
+ with box.condition:
85
+ box.condition.wait_for(lambda: box.closed or bool(box.items))
86
+ if box.closed:
87
+ raise StopIteration
88
+ value = box.items.popleft()
89
+ if self._predicate is None or self._predicate(value):
90
+ return value
91
+
92
+ def __aiter__(self: W) -> W:
93
+ return self
94
+
95
+ async def __anext__(self) -> T:
96
+ box = self._inbox
97
+ loop = asyncio.get_running_loop()
98
+ while True:
99
+ with box.condition:
100
+ if box.closed:
101
+ raise StopAsyncIteration
102
+ if box.items:
103
+ value = box.items.popleft()
104
+ event = None
105
+ else:
106
+ event = asyncio.Event()
107
+ box.waiters.add((loop, event))
108
+ if event is not None:
109
+ try:
110
+ await event.wait()
111
+ finally:
112
+ with box.condition:
113
+ box.waiters.discard((loop, event))
114
+ elif self._predicate is None or self._predicate(value):
115
+ return value
116
+
117
+
118
+
119
+ @dataclass(frozen=True)
120
+ class ALLBlueHidInfo:
121
+ id: str
122
+ path: str
123
+ vid: int = 0
124
+ pid: int = 0
125
+ release_number: int = 0
126
+ usage_page: int = 0
127
+ usage: int = 0
128
+ bus_type: int = 0
129
+ serial_number: str | None = None
130
+ manufacturer: str | None = None
131
+ product: str | None = None
132
+ max_input_report_len: int = 0
133
+ max_output_report_len: int = 0
134
+ max_feature_report_len: int = 0
135
+
136
+
137
+ class HidDeviceWatcher(_Subscription[ALLBlueHidInfo]):
138
+ """Receive HID discovery events."""
139
+
140
+
141
+ class HidReportWatcher(_Subscription[tuple[int, bytes]]):
142
+ """Receive report ID and payload pairs."""
143
+
144
+
145
+ def _check(status: int) -> None:
146
+ if status:
147
+ error = {-1: ValueError, -2: FileNotFoundError, -3: PermissionError,
148
+ -4: TimeoutError, -5: ConnectionError, -6: ValueError,
149
+ -7: NotImplementedError, -8: BlockingIOError}.get(status, OSError)
150
+ message = ffi.string(native().allblue_hid_last_error_message())
151
+ raise error(message.decode("utf-8", "replace"))
152
+
153
+
154
+ def _text(p: Any) -> str:
155
+ return bytes(ffi.string(p)).decode("utf-8") if p else ""
156
+
157
+
158
+ def _info(p: Any) -> ALLBlueHidInfo:
159
+ return ALLBlueHidInfo(_text(p.id), _text(p.path), p.vid, p.pid, p.release_number,
160
+ p.usage_page, p.usage, p.bus_type, _text(p.serial_number) or None,
161
+ _text(p.manufacturer) or None, _text(p.product) or None,
162
+ p.max_input_report_len, p.max_output_report_len, p.max_feature_report_len)
163
+
164
+
165
+ def _discovered(p: Any, ctx: Any) -> None:
166
+ ffi.from_handle(ctx).push(_info(p))
167
+
168
+
169
+ def _received(report_id: int, data: Any, length: int, ctx: Any) -> None:
170
+ ffi.from_handle(ctx).push((report_id, bytes(ffi.buffer(data, length))))
171
+
172
+
173
+ class ALLBlueHidDevice:
174
+ def __init__(self, pointer: Any) -> None:
175
+ self._lib = native()
176
+ self._ptr = ffi.gc(pointer, self._lib.allblue_hid_free)
177
+ self._lock = RLock()
178
+ self._watchers: WeakSet[HidReportWatcher] = WeakSet()
179
+
180
+ @staticmethod
181
+ def devices(filter: Callable[[ALLBlueHidInfo], bool] | None = None) -> list[ALLBlueHidInfo]:
182
+ lib = native()
183
+ out = ffi.new("allblue_hid_info_t **")
184
+ count = ffi.new("size_t *")
185
+ _check(lib.allblue_hid_devices(ffi.NULL, ffi.NULL, out, count))
186
+ try:
187
+ items = [_info(out[0][i]) for i in range(count[0])]
188
+ finally:
189
+ lib.allblue_hid_devices_free(out[0], count[0])
190
+ return items if filter is None else [item for item in items if filter(item)]
191
+
192
+ @staticmethod
193
+ def discover(filter: Callable[[ALLBlueHidInfo], bool] | None = None) -> HidDeviceWatcher:
194
+ lib = native()
195
+ box: _Inbox[ALLBlueHidInfo] = _Inbox()
196
+ ctx = ffi.new_handle(box)
197
+ cb = ffi.callback("allblue_hid_discover_fn", _discovered)
198
+ out = ffi.new("allblue_hid_discoverer_t **")
199
+ _check(lib.allblue_hid_discover(ffi.NULL, cb, ctx, out))
200
+ return HidDeviceWatcher(box, lambda: lib.allblue_hid_discover_stop(out[0]), (cb, ctx), filter)
201
+
202
+ @staticmethod
203
+ def open(info: ALLBlueHidInfo) -> ALLBlueHidDevice:
204
+ identifier = info.id or info.path
205
+ if "\0" in identifier:
206
+ raise ValueError("NUL in HID identifier")
207
+ out = ffi.new("allblue_hid_device_t **")
208
+ _check(native().allblue_hid_open(identifier.encode("utf-8"), out))
209
+ return ALLBlueHidDevice(out[0])
210
+
211
+ def _live(self) -> Any:
212
+ ptr = self._ptr
213
+ if ptr is None:
214
+ raise ConnectionError("HID device closed")
215
+ return ptr
216
+
217
+ def write_output_report(self, report_id: int, payload: bytes | bytearray | memoryview) -> int:
218
+ data = ffi.from_buffer("const uint8_t[]", payload)
219
+ count = ffi.new("size_t *")
220
+ _check(self._lib.allblue_hid_write_output_report(self._live(), report_id, data, len(data), count))
221
+ return int(count[0])
222
+
223
+ def clear_read_buffer(self) -> None:
224
+ _check(self._lib.allblue_hid_clear_read_buffer(self._live()))
225
+
226
+ def read_input_report(self, max_length: int = 64, timeout: float | None = 2.0) -> tuple[int, bytes]:
227
+ if timeout is not None and timeout < 0:
228
+ raise ValueError("Negative timeout")
229
+ ms = -1 if timeout is None else math.ceil(timeout * 1000)
230
+ data = ffi.new("uint8_t[]", max_length)
231
+ report_id = ffi.new("uint8_t *")
232
+ count = ffi.new("size_t *")
233
+ _check(self._lib.allblue_hid_read_input_report(self._live(), report_id, data, max_length, ms, count))
234
+ return report_id[0], bytes(ffi.buffer(data, count[0]))
235
+
236
+ def send_feature_report(self, report_id: int, payload: bytes | bytearray | memoryview) -> None:
237
+ data = ffi.from_buffer("const uint8_t[]", payload)
238
+ _check(self._lib.allblue_hid_send_feature_report(self._live(), report_id, data, len(data)))
239
+
240
+ def get_feature_report(self, report_id: int, max_length: int = 64) -> bytes:
241
+ dest = ffi.new("uint8_t[]", max_length)
242
+ count = ffi.new("size_t *")
243
+ _check(self._lib.allblue_hid_get_feature_report(self._live(), report_id, dest, max_length, count))
244
+ return bytes(ffi.buffer(dest, count[0]))
245
+
246
+ def watch_input_reports(self) -> HidReportWatcher:
247
+ box: _Inbox[tuple[int, bytes]] = _Inbox()
248
+ cb = ffi.callback("allblue_hid_watch_report_fn", _received)
249
+ ctx = ffi.new_handle(box)
250
+ watch_id = ffi.new("uint64_t *")
251
+ with self._lock:
252
+ ptr = self._live()
253
+ lib = self._lib
254
+ lock = self._lock
255
+ _check(lib.allblue_hid_watch_input_reports(ptr, cb, ctx, watch_id))
256
+
257
+ def stop() -> None:
258
+ with lock:
259
+ status = lib.allblue_hid_unwatch(ptr, watch_id[0])
260
+ # Disconnect may already have drained this subscription.
261
+ if status != -2:
262
+ _check(status)
263
+
264
+ watcher = HidReportWatcher(box, stop, (cb, ctx))
265
+ self._watchers.add(watcher)
266
+ return watcher
267
+
268
+ def close(self) -> None:
269
+ with self._lock:
270
+ if self._ptr is not None:
271
+ for watcher in list(self._watchers):
272
+ watcher.close()
273
+ _check(self._lib.allblue_hid_close(self._ptr))
274
+ self._ptr = None
275
+
276
+ def __enter__(self) -> ALLBlueHidDevice:
277
+ return self
278
+
279
+ def __exit__(self, *exc: object) -> None:
280
+ self.close()
File without changes
@@ -0,0 +1,113 @@
1
+ import asyncio
2
+ import gc
3
+
4
+ import pytest
5
+
6
+ from allblue_hid import ALLBlueHidDevice
7
+ from allblue_hid._cdefs import ffi
8
+ from allblue_hid._loader import native
9
+
10
+
11
+ @pytest.fixture
12
+ def device():
13
+ lib = native()
14
+ sinks = []
15
+ features = {}
16
+ table = ffi.new("allblue_hid_custom_vtable_t *")
17
+ table.struct_size = ffi.sizeof(table[0])
18
+
19
+ def output(ctx, report_id, data, length, count):
20
+ count[0] = length
21
+ return lib.allblue_hid_input_sink_push(sinks[0], report_id, data, length)
22
+
23
+ def send(ctx, report_id, data, length):
24
+ features[report_id] = bytes(ffi.buffer(data, length))
25
+ return 0
26
+
27
+ def get(ctx, report_id, data, length, count):
28
+ payload = features[report_id]
29
+ if len(payload) > length:
30
+ return -6
31
+ ffi.memmove(data, payload, len(payload))
32
+ count[0] = len(payload)
33
+ return 0
34
+
35
+ handlers = {"bind": lambda ctx, sink: sinks.append(sink),
36
+ "destroy": lambda ctx: lib.allblue_hid_input_sink_free(sinks.pop()),
37
+ "write_output": output, "send_feature": send, "get_feature": get}
38
+ pins = []
39
+ for name, handler in handlers.items():
40
+ cb = ffi.callback(ffi.typeof(getattr(table, name)), handler)
41
+ setattr(table, name, cb)
42
+ pins.append(cb)
43
+ out = ffi.new("allblue_hid_device_t **")
44
+ assert lib.allblue_hid_open_custom(table, out) == 0
45
+ # A traceback can retain the native handle past fixture teardown.
46
+ # Tie the custom vtable callbacks to the pointer given to the SDK.
47
+ pointer = ffi.gc(out[0], lambda _: pins.clear())
48
+ with ALLBlueHidDevice(pointer) as dev:
49
+ yield dev
50
+ assert not sinks
51
+
52
+
53
+ def test_clear_read_buffer(device):
54
+ device.write_output_report(1, b"old")
55
+ device.clear_read_buffer()
56
+ device.write_output_report(2, b"new")
57
+ assert device.read_input_report(timeout=0) == (2, b"new")
58
+
59
+
60
+ @pytest.mark.parametrize("report_id", [0, 2])
61
+ def test_report_round_trip(device, report_id):
62
+ async def run():
63
+ async with device.watch_input_reports() as reports:
64
+ with device.watch_input_reports() as sync:
65
+ for _ in range(3):
66
+ gc.collect()
67
+ data = bytes([0, report_id, 0xff])
68
+ assert device.write_output_report(report_id, memoryview(data)) == len(data)
69
+ with pytest.raises(ValueError):
70
+ device.read_input_report(max_length=1)
71
+ assert device.read_input_report() == (report_id, data)
72
+ assert await reports.__anext__() == (report_id, data)
73
+ assert next(sync) == (report_id, data)
74
+ device.send_feature_report(report_id, data)
75
+ assert device.get_feature_report(report_id) == data
76
+ device.write_output_report(report_id, b"")
77
+ assert await reports.__anext__() == (report_id, b"")
78
+ assert list(sync) == []
79
+ assert [x async for x in reports] == []
80
+
81
+ asyncio.run(asyncio.wait_for(run(), 5))
82
+
83
+
84
+ def test_discovery_copies_borrowed_fields(monkeypatch):
85
+ from allblue_hid import device as binding
86
+
87
+ addresses = []
88
+ stopped = []
89
+
90
+ class Discovery:
91
+ def allblue_hid_discover(self, predicate, cb, ctx, out):
92
+ addresses.extend(int(ffi.cast("uintptr_t", ptr)) for ptr in (cb, ctx))
93
+ return 0
94
+
95
+ def allblue_hid_discover_stop(self, handle):
96
+ gc.collect()
97
+ assert ffi.from_handle(ffi.cast("void *", addresses[1])) is not None
98
+ stopped.append(True)
99
+
100
+ api = Discovery()
101
+ monkeypatch.setattr(binding, "native", lambda: api)
102
+ with ALLBlueHidDevice.discover(filter=lambda info: info.vid == 42) as watcher:
103
+ gc.collect()
104
+ info = ffi.new("allblue_hid_info_t *")
105
+ name = ffi.new("char[]", b"sample")
106
+ info.id = info.path = name
107
+ info.vid = 42
108
+ ffi.cast("allblue_hid_discover_fn", addresses[0])(info, ffi.cast("void *", addresses[1]))
109
+ name[0] = b"x"
110
+ async def receive():
111
+ return await watcher.__anext__()
112
+ assert asyncio.run(asyncio.wait_for(receive(), 1)).path == "sample"
113
+ assert stopped == [True]