Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 7 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,8 @@ Settings, then run `Logitech Mouse Battery`.
</p>

The script checks `PATH`, `/opt/homebrew/bin`, `/usr/local/bin`,
`$HOME/.local/bin`, and the repository's `target/release` and root directories,
in that order.
`$HOME/.local/bin`, and the repository's `target/release` directory, in that
order.

For a custom binary path, add this line to `mouse-battery.sh` before
`set -euo pipefail`:
Expand All @@ -106,10 +106,8 @@ export GBAT_BINARY="/path/to/gbat"

Setting this variable in Terminal only affects scripts launched from that shell.

Explicit paths take priority over the search above. The script checks
`GBAT_BINARY`, then the legacy variables `GPWBAT_BINARY` and
`GPW2_BATTERY_BINARY`, and uses the first non-empty value. That path must point
to an executable file.
`GBAT_BINARY` takes priority over the search above and must point to an
executable file.

## Build from source

Expand Down Expand Up @@ -163,10 +161,9 @@ headset. There is no device selector.

It reads `UNIFIED_BATTERY` at `0x1004` and falls back to `BATTERY_STATUS` at
`0x1000` when the unified feature is unavailable, does not answer, or returns an
incomplete response. Once a battery feature is found, HID access errors and
incomplete writes stop the read. During discovery, an interface that fails is
skipped; its error is reported only if no other interface finds the mouse or
reports it offline.
incomplete response. Once a battery feature is found, HID access errors stop the
read. During discovery, an interface that fails is skipped; its error is
reported only if no other interface finds the mouse or reports it offline.
If neither feature yields a battery status, the command reports an error
instead of inventing a `0%` reading.

Expand Down
6 changes: 3 additions & 3 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ gbat
<img src="assets/raycast-demo.webp" alt="gbat Raycast Script Command 演示" width="700">
</p>

脚本依次检查 `PATH`、`/opt/homebrew/bin`、`/usr/local/bin`、`$HOME/.local/bin`,以及仓库的 `target/release` 目录和根目录。
脚本依次检查 `PATH`、`/opt/homebrew/bin`、`/usr/local/bin`、`$HOME/.local/bin`,以及仓库的 `target/release` 目录。

如果可执行文件位于其他位置,在 `mouse-battery.sh` 的 `set -euo pipefail` 之前加入:

Expand All @@ -87,7 +87,7 @@ export GBAT_BINARY="/path/to/gbat"

在 Terminal 中设置这个变量,只会影响从该 Shell 启动的脚本。

指定路径的优先级高于上述搜索。脚本依次检查 `GBAT_BINARY`、旧变量 `GPWBAT_BINARY` 和 `GPW2_BATTERY_BINARY`,使用第一个非空值。该路径必须指向可执行文件。
`GBAT_BINARY` 的优先级高于上述搜索,且必须指向可执行文件。

## 从源码构建

Expand Down Expand Up @@ -131,7 +131,7 @@ xattr -dr com.apple.quarantine "$(brew --prefix gbat)"

`gbat` 以共享模式打开 Logitech HID++ 接口。它会检查接收器的设备索引 `1` 到 `6` 和 USB 直连索引 `0xFF`,先尝试 `1` 和 `0xFF`,再使用首个报告支持电池功能的接口及设备索引。它只按 Logitech 厂商 ID 筛选,连接多个 Logitech HID++ 设备时,可能读到另一只鼠标、键盘或耳机,且无法指定设备。

它优先读取 `0x1004` 的 `UNIFIED_BATTERY`。该功能不可用、未响应或返回不完整响应时,会回退到 `0x1000` 的 `BATTERY_STATUS`。找到电池功能后,HID 访问错误和写入不完整会直接终止读取。探测阶段某个接口出错时会跳过它,只有其他接口都没找到鼠标、也没有报告离线时,才返回该错误。如果两个功能都未返回电池状态,命令会报错,不会将读取失败显示为 `0%`。
它优先读取 `0x1004` 的 `UNIFIED_BATTERY`。该功能不可用、未响应或返回不完整响应时,会回退到 `0x1000` 的 `BATTERY_STATUS`。找到电池功能后,HID 访问错误会直接终止读取。探测阶段某个接口出错时会跳过它,只有其他接口都没找到鼠标、也没有报告离线时,才返回该错误。如果两个功能都未返回电池状态,命令会报错,不会将读取失败显示为 `0%`。

## 许可证

Expand Down
36 changes: 3 additions & 33 deletions docs/record-demo.sh
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,13 @@ printf 'Recording %s\n' "$version"
work_dir=$(mktemp -d "$project_root/target/record-demo.XXXXXX")
trap 'rm -r "$work_dir"' EXIT
trap 'exit 1' HUP INT TERM
frames="$work_dir/frames"
candidate="$work_dir/demo.gif"

# VHS 0.12.0 cancels its render context before starting FFmpeg. Keep its PNG
# frames and render separately. A temporary GIF output also makes VHS generate
# bar.png and mask.png; no tape output can overwrite the published GIF.
awk -v frames="$frames" -v video="$work_dir/vhs.gif" '
# Render to a temporary file so a failed recording keeps the published GIF.
awk -v output="$candidate" '
/^[[:space:]]*Output[[:space:]]/ {
if (!replaced) {
print "Output \"" video "\""
print "Output \"" frames "/\""
print "Output \"" output "\""
replaced = 1
}
next
Expand All @@ -42,32 +38,6 @@ awk -v frames="$frames" -v video="$work_dir/vhs.gif" '
' demo.tape > "$work_dir/demo.tape"
vhs "$work_dir/demo.tape"

# Match demo.tape: 1100x500, 30 fps, 24 px padding, a 30 px window bar,
# Catppuccin Mocha background, and the border mask generated by VHS.
ffmpeg -hide_banner -loglevel error -y \
-framerate 30 -start_number 1 -i "$frames/frame-text-%05d.png" \
-framerate 30 -start_number 1 -i "$frames/frame-cursor-%05d.png" \
-f lavfi -i 'color=#1e1e2e:s=1100x500:r=30' \
-framerate 30 -i "$frames/bar.png" \
-framerate 30 -i "$frames/mask.png" \
-filter_complex '
[0][1]overlay[merged];
[merged]scale=1052:422:force_original_aspect_ratio=1[scaled];
[scaled]fps=30,setpts=PTS/1.0[speed];
[speed]pad=1100:470:(ow-iw)/2:(oh-ih)/2:#1e1e2e[padded];
[padded]fillborders=left=24:right=24:top=24:bottom=24:mode=fixed:color=#1e1e2e[filled];
[3]loop=-1:size=1[loopbar];
[loopbar][filled]overlay=0:30:shortest=1[withbar];
[4]loop=-1:size=1[loopmask];
[withbar][loopmask]alphamerge=shortest=1[rounded];
[2]scale=1100:500[bg];
[bg][rounded]overlay=(W-w)/2:(H-h)/2:shortest=1[withbg];
[withbg]split[plt_a][plt_b];
[plt_a]palettegen=max_colors=256[plt];
[plt_b][plt]paletteuse[palette]
' \
-map '[palette]' "$candidate"

test -s "$candidate"
ffmpeg -hide_banner -loglevel error -xerror -i "$candidate" -f null -
cp "$candidate" "$project_root/assets/demo.gif"
Expand Down
12 changes: 5 additions & 7 deletions docs/recording.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,13 @@ The script builds with `--locked`, verifies a real battery read, and records
sets `GBAT_BINARY` to that same build, so all four commands use it. There is no
sample-output wrapper.

The recorder exports PNG frames with VHS, encodes them with FFmpeg, and checks
that the GIF can be decoded before replacing `assets/demo.gif`. Temporary files
are removed on exit. This avoids a VHS `0.12.0` issue where the recording context
is cancelled before rendering, leaving the existing GIF untouched despite a
successful exit. See the upstream [render call](https://github.com/charmbracelet/vhs/blob/v0.12.0/evaluator.go#L187).
The recorder renders to a temporary GIF and checks that FFmpeg can decode it
before replacing `assets/demo.gif`. Temporary files are removed on exit.

Use VHS `0.12.1` or later: `0.12.0` can exit successfully without rendering,
which leaves the existing GIF untouched.

The checked-in capture used VHS `0.12.1`, ttyd `1.7.7`, and FFmpeg `9.0.2`.
If you change the tape's dimensions, frame rate, padding, theme, or window bar,
update the matching FFmpeg settings in [`record-demo.sh`](record-demo.sh).

## Preserve the original Raycast animation

Expand Down
7 changes: 1 addition & 6 deletions raycast/mouse-battery.sh
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,6 @@ project_dir="${script_dir:h}"

if [[ -n "${GBAT_BINARY:-}" ]]; then
binary_path="$GBAT_BINARY"
elif [[ -n "${GPWBAT_BINARY:-}" ]]; then
binary_path="$GPWBAT_BINARY"
elif [[ -n "${GPW2_BATTERY_BINARY:-}" ]]; then
binary_path="$GPW2_BATTERY_BINARY"
elif binary_path="$(command -v gbat 2>/dev/null)" && [[ -x "$binary_path" ]]; then
:
else
Expand All @@ -26,8 +22,7 @@ else
"/opt/homebrew/bin/gbat" \
"/usr/local/bin/gbat" \
"$HOME/.local/bin/gbat" \
"$project_dir/target/release/gbat" \
"$project_dir/gbat"; do
"$project_dir/target/release/gbat"; do
if [[ -x "$candidate" ]]; then
binary_path="$candidate"
break
Expand Down
104 changes: 29 additions & 75 deletions src/hidpp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,6 @@ pub struct BatteryStatus {
#[derive(Debug)]
pub enum HidppError {
Hid(HidError),
ShortWrite {
expected: usize,
actual: usize,
},
/// A reply matched the request but is too short to decode. `match_report`
/// already checked the report ID, device index, feature index, and function
/// byte, and turned error reports into their own outcomes.
Expand All @@ -59,10 +55,6 @@ impl fmt::Display for HidppError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Hid(error) => write!(formatter, "HID access failed: {error}"),
Self::ShortWrite { expected, actual } => write!(
formatter,
"short HID++ write: expected {expected} bytes, wrote {actual}"
),
Self::ShortResponse { minimum, actual } => write!(
formatter,
"short HID++ response: expected at least {minimum} bytes, got {actual}"
Expand Down Expand Up @@ -141,14 +133,16 @@ enum BatteryFeature {

/// Report I/O and the monotonic timeline used by a request.
trait RequestIo {
fn write(&self, report: &[u8]) -> Result<usize, HidError>;
fn write(&self, report: &[u8]) -> Result<(), HidError>;
fn read_timeout(&self, buffer: &mut [u8], timeout_ms: i32) -> Result<usize, HidError>;
fn now(&self) -> Instant;
}

impl RequestIo for HidDevice {
fn write(&self, report: &[u8]) -> Result<usize, HidError> {
HidDevice::write(self, report)
// hidapi's macOS backend writes a report whole or fails, so the returned
// byte count carries no information.
fn write(&self, report: &[u8]) -> Result<(), HidError> {
HidDevice::write(self, report).map(drop)
}

fn read_timeout(&self, buffer: &mut [u8], timeout_ms: i32) -> Result<usize, HidError> {
Expand Down Expand Up @@ -206,17 +200,6 @@ fn request_timeout(io: &impl RequestIo, deadline: Instant) -> Duration {
.min(RESPONSE_TIMEOUT)
}

fn send_short(io: &impl RequestIo, report: [u8; 7]) -> Result<(), HidppError> {
let actual = io.write(&report)?;
if actual != report.len() {
return Err(HidppError::ShortWrite {
expected: report.len(),
actual,
});
}
Ok(())
}

/// The reply `report` gives to the request, or `None` if it answers something
/// else. A HID++ 2.0 reply echoes the request's function and software ID, so
/// matching that byte too rejects stale reports and replies meant for another
Expand Down Expand Up @@ -271,18 +254,15 @@ impl<Io: RequestIo> Device<'_, Io> {
) -> Result<Reply, HidppError> {
let function_byte = (function << 4) | SW_ID;
flush(self.io)?;
send_short(
self.io,
[
REPORT_ID_SHORT,
self.index,
feature_index,
function_byte,
payload[0],
payload[1],
payload[2],
],
)?;
self.io.write(&[
REPORT_ID_SHORT,
self.index,
feature_index,
function_byte,
payload[0],
payload[1],
payload[2],
])?;

let deadline = self.io.now() + timeout;
loop {
Expand Down Expand Up @@ -377,9 +357,7 @@ impl<Io: RequestIo> Device<'_, Io> {
Err(error @ HidppError::ShortResponse { .. }) => match query_legacy() {
Ok(Some(status)) => Ok(Some(status)),
Ok(None) | Err(HidppError::ShortResponse { .. }) => Err(error),
Err(legacy_error @ (HidppError::Hid(_) | HidppError::ShortWrite { .. })) => {
Err(legacy_error)
}
Err(legacy_error @ HidppError::Hid(_)) => Err(legacy_error),
},
Err(error) => Err(error),
}
Expand All @@ -401,18 +379,12 @@ fn candidate_interfaces(api: &HidApi) -> Vec<&hidapi::DeviceInfo> {
candidates
}

fn open_interface(api: &HidApi, info: &hidapi::DeviceInfo) -> Result<HidDevice, HidppError> {
let interface = api.open_path(info.path())?;
interface.set_blocking_mode(false)?;
Ok(interface)
}

/// Read the battery status through the first candidate HID interface and
/// device index that expose a battery feature.
pub fn read_battery(api: &HidApi) -> Result<Reading, HidppError> {
let interfaces = candidate_interfaces(api)
.into_iter()
.map(|info| move || open_interface(api, info));
.map(|info| move || api.open_path(info.path()).map_err(HidppError::Hid));
read_battery_from(interfaces, Instant::now)
}

Expand Down Expand Up @@ -552,7 +524,7 @@ mod tests {
},
Write {
report: Vec<u8>,
result: Result<usize, HidError>,
result: Result<(), HidError>,
advance: Duration,
},
}
Expand All @@ -574,7 +546,7 @@ mod tests {
fn write(report: &[u8]) -> Self {
Self::Write {
report: report.to_vec(),
result: Ok(report.len()),
result: Ok(()),
advance: Duration::ZERO,
}
}
Expand Down Expand Up @@ -651,7 +623,7 @@ mod tests {
}

impl RequestIo for ScriptedIo {
fn write(&self, report: &[u8]) -> Result<usize, HidError> {
fn write(&self, report: &[u8]) -> Result<(), HidError> {
let ScriptStep::Write {
report: expected,
result,
Expand Down Expand Up @@ -1259,17 +1231,11 @@ mod tests {
enum IoFailure {
FlushRead,
Write,
ShortWrite,
ResponseRead,
}

impl IoFailure {
const ALL: [Self; 4] = [
Self::FlushRead,
Self::Write,
Self::ShortWrite,
Self::ResponseRead,
];
const ALL: [Self; 3] = [Self::FlushRead, Self::Write, Self::ResponseRead];

/// The script for `request` up to and including this failure.
fn steps(self, request: &[u8]) -> Vec<ScriptStep> {
Expand All @@ -1278,37 +1244,25 @@ mod tests {
result: Err(HidError::InitializationError),
advance: Duration::ZERO,
};
let write = |result| ScriptStep::Write {
report: request.to_vec(),
result,
advance: Duration::ZERO,
};
match self {
Self::FlushRead => vec![failed_read(0)],
Self::Write => vec![
ScriptStep::flush(&[]),
write(Err(HidError::InitializationError)),
ScriptStep::Write {
report: request.to_vec(),
result: Err(HidError::InitializationError),
advance: Duration::ZERO,
},
],
Self::ShortWrite => vec![ScriptStep::flush(&[]), write(Ok(3))],
Self::ResponseRead => exchange(request, [failed_read(1_500)]),
}
}

fn assert_error(self, result: Result<Reading, HidppError>) {
match (self, result) {
(
Self::ShortWrite,
Err(HidppError::ShortWrite {
expected: 7,
actual: 3,
}),
)
| (
Self::FlushRead | Self::Write | Self::ResponseRead,
Err(HidppError::Hid(HidError::InitializationError)),
) => {}
(failure, result) => panic!("{failure:?} produced {result:?}"),
}
assert!(
matches!(result, Err(HidppError::Hid(HidError::InitializationError))),
"{self:?} produced {result:?}"
);
}
}

Expand Down
Loading