Skip to content
Open
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
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,25 @@ and the project follows [Semantic Versioning](https://semver.org/).

## [Unreleased]

### Added

- React to a receiver or cable arriving or leaving, and to a resume from sleep, as
soon as Windows reports it instead of at the next poll: a hidden window receives
the same device and power broadcasts the vendor tools use and coalesces a dock's
burst of interfaces into one refresh. The existing check every few seconds stays
as the fallback.
- A charging device at 100 % is now shown as fully charged: its ring stops breathing
and stays green, and the tooltip says so, translated in every language. A provider
with a real "charged" flag can set the same state below 100 %. Only a live reading
counts, never a greyed last known value.
- The last level kept for a sleeping mouse is never shown as charging or fully
charged, so a mouse that fell asleep on its cable no longer looks like it is still
charging (#109). Pulsar, Rapoo, ATK, Attack Shark R11, Dareu, Finalmouse, HyperX
and Lamzu mice mark that reading as asleep, and moving a sleeping Rapoo mouse now
re-reads it.
- `status.json` gains `full` and `asleep` and follows the tooltip: it no longer
reports a sleeping mouse as charging.

### Fixed

- Retry post-publication release and asset attestation verification when GitHub
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Support project via &nbsp;<a href="https://ko-fi.com/halobattery"><picture><sour
<img src="docs/readme/devices-light.svg" alt="Mouse at 100%, charging keyboard at 65%, headset at 25%, and controller at 10%" width="100%">
</picture>

- **Read the ring.** With a 20% alert threshold, 21–30% is amber and 20% or less is red. Above 30%, the ring follows the tray theme. With charging animation enabled, a known level pulses green. If the device reports charging without a percentage, a green arc rotates.
- **Read the ring.** With a 20% alert threshold, 21–30% is amber and 20% or less is red. Above 30%, the ring follows the tray theme. With charging animation enabled, a known level pulses green until the device is fully charged, then the ring stays steady green. If the device reports charging without a percentage, a green arc rotates.
- **Read the device directly.** Halo Battery checks a 2.4 GHz receiver, a USB cable or Windows Bluetooth. You can close the vendor’s software.
- **Set up each device.** Choose when each device needs attention. By default, alerts wait while a full-screen game is open.

Expand Down
2 changes: 1 addition & 1 deletion README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
<img src="docs/readme/devices-light.svg" alt="鼠标电量 100%,正在充电的键盘 65%,耳机 25%,手柄 10%" width="100%">
</picture>

- **看懂电量环。** 当提醒阈值设为 20% 时,21–30% 显示为琥珀色,20% 及以下显示为红色。高于 30% 时,圆环颜色随托盘主题变化。启用充电动画后,如果设备报告电量百分比,绿色圆环会呈呼吸效果;如果只报告正在充电,则会显示旋转的绿色圆弧。
- **看懂电量环。** 当提醒阈值设为 20% 时,21–30% 显示为琥珀色,20% 及以下显示为红色。高于 30% 时,圆环颜色随托盘主题变化。启用充电动画后,如果设备报告电量百分比,绿色圆环会呈呼吸效果,充满后保持常亮绿色;如果只报告正在充电,则会显示旋转的绿色圆弧。
- **直接读取设备。** Halo Battery 通过 2.4 GHz 接收器、USB 数据线或 Windows 蓝牙读取电量,无需运行厂商软件。
- **按设备设置。** 每台设备均可单独设置提醒阈值。默认在全屏游戏期间暂缓提醒。

Expand Down
10 changes: 6 additions & 4 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
- **Display scaling**: tray artwork is rendered at the taskbar's physical icon size and refreshed when its DPI changes, keeping the thin ring and pictograms sharp.
- **Colour**: follows the taskbar (white on a dark bar, black on a light one). With [MyDockFinder](https://store.steampowered.com/app/1787090/MyDockFinder/) running it follows its top menu bar instead. With a transparent taskbar (e.g. TranslucentTB) pick **Icon colour → White** or **Black**.
- **Amber**: close to the alert threshold. **Red**: at or below it.
- **Green**: charging. A known battery level breathes in brightness; an unknown level uses a rotating green arc over a steady neutral ring. Turning animation off in Settings leaves the arc still.
- **Translucent**: the mouse is asleep and keeps its last level for 5 minutes. A device that is switched off leaves the tray and comes back when it is switched on.
- **Green**: charging. A known battery level breathes in brightness until the device is fully charged, then the ring stays steady green; an unknown level uses a rotating green arc over a steady neutral ring. Turning animation off in Settings leaves the arc still.
- **Translucent**: the mouse is asleep and keeps its last level for 5 minutes. That kept level is never shown as charging or fully charged. A device that is switched off leaves the tray and comes back when it is switched on.

The low battery notification fires once, and again only after the device has been charged.

Expand Down Expand Up @@ -165,8 +165,10 @@ back, while the ring fades, slides and scales through native Composition animati
some games may stop seeing the controller until it is turned off and on.
The optional `%APPDATA%\HaloBattery\status.json` is written after every poll
for Rainmeter, Stream Deck and scripts. It includes device `name`, `level`,
`charging`, `online`, `kind`, `seconds_left` and tooltip `text`, plus `running`
and `updated_unix`. Turning the option off deletes the file.
`charging`, `full`, `asleep`, `online`, `kind`, `seconds_left` and tooltip
`text`, plus `running` and `updated_unix`. These follow the tooltip: a sleeping
mouse's kept level is never `charging` or `full`. Turning the option off
deletes the file.
- **About**: version, diagnostics, the data folder, the website, the Discord
community, the GitHub page, issue reporting, and authors and licenses for the
interface fonts, Lucide glyphs and downloaded icons.
Expand Down
295 changes: 295 additions & 0 deletions halo/device_events.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,295 @@
"""Instant notice of device arrivals, removals and resume from sleep.

The poll loop already compares a cheap USB signature every few seconds, so a
receiver plugged in or a mouse moved to its cable is noticed without waiting
for the whole poll interval, but only at the next check, and a resume from
sleep need not change that signature at all. This module listens to the same
Windows broadcasts the vendor tools use and wakes the poll loop at once:

* WM_DEVICECHANGE for USB device, HID and Bluetooth radio interfaces, and for
the generic DBT_DEVNODES_CHANGED which follows any child-device change;
* WM_POWERBROADCAST for resume from sleep.

Nothing is injected into other processes; the window is never shown. Events are
coalesced: a receiver exposes several interfaces and Windows sends one message
per node, so the callback runs once, 1.2 s after the last event (3 s after a
resume, when the devices need a moment before they answer). Windows only;
start() is a no-op elsewhere and returns False, and the signature check in the
app remains the fallback.
"""
from __future__ import annotations

import sys
import threading
from typing import Callable, Optional

WM_DEVICECHANGE = 0x0219
WM_POWERBROADCAST = 0x0218
WM_DESTROY = 0x0002
WM_QUIT = 0x0012

DBT_DEVICEARRIVAL = 0x8000
DBT_DEVICEREMOVECOMPLETE = 0x8004
DBT_DEVNODES_CHANGED = 0x0007
DBT_DEVTYP_DEVICEINTERFACE = 0x00000005

PBT_APMSUSPEND = 0x0004
PBT_APMRESUMESUSPEND = 0x0007
PBT_APMRESUMEAUTOMATIC = 0x0012

DEVICE_NOTIFY_WINDOW_HANDLE = 0x00000000

# Interface classes worth a notification: every HID collection, every USB
# device node (a receiver's audio/consumer interfaces included) and the
# Bluetooth radio itself (GUID_BTHPORT_DEVICE_INTERFACE in bthdef.h: a dongle
# plugged in, the radio turned on or off). Whether a paired device connecting is
# reported depends on its driver; the poll remains the fallback for that.
GUID_HID = "{4D1E55B2-F16F-11CF-88CB-001111000030}"
GUID_USB = "{A5DCBF10-6530-11D2-901F-00C04FB951ED}"
GUID_BTHPORT = "{0850302A-B344-4FDA-9BE9-90576B8D46F0}"
INTERFACES = (GUID_HID, GUID_USB, GUID_BTHPORT)

DEVICE_DELAY = 1.2 # s after the last device message
RESUME_DELAY = 3.0 # s after resume: devices need a moment to answer


def classify(message: int, wparam: int) -> Optional[str]:
"""The reason to poll for a window message, or None when it is not ours.

Kept pure so the mapping can be tested without a window or a device.
"""
if message == WM_POWERBROADCAST:
if wparam in (PBT_APMRESUMESUSPEND, PBT_APMRESUMEAUTOMATIC):
return "resume"
return None
if message == WM_DEVICECHANGE:
if wparam in (DBT_DEVICEARRIVAL, DBT_DEVICEREMOVECOMPLETE, DBT_DEVNODES_CHANGED):
return "device"
return None


def _user32_kernel32():
"""Private user32 and kernel32 handles with a prototype for every call made here.

`ctypes.windll` is shared with the rest of the app, so prototypes set on it would
change other modules' calls too; and a call without a prototype passes a 64-bit
handle as a 32-bit int (OverflowError, or a truncated handle).
"""
import ctypes
from ctypes import wintypes

user32 = ctypes.WinDLL("user32", use_last_error=True)
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
ptr, uint, dword, text, num = (ctypes.c_void_p, wintypes.UINT, wintypes.DWORD,
wintypes.LPCWSTR, ctypes.c_int)
prototypes = (
(user32.RegisterClassW, wintypes.ATOM, [ptr]),
(user32.UnregisterClassW, wintypes.BOOL, [text, ptr]),
(user32.CreateWindowExW, ptr, [dword, text, text, dword, num, num, num, num,
ptr, ptr, ptr, ptr]),
(user32.DestroyWindow, wintypes.BOOL, [ptr]),
(user32.DefWindowProcW, ptr, [ptr, uint, ptr, ptr]),
(user32.RegisterDeviceNotificationW, ptr, [ptr, ptr, dword]),
(user32.UnregisterDeviceNotification, wintypes.BOOL, [ptr]),
(user32.GetMessageW, wintypes.BOOL, [ptr, ptr, uint, uint]),
(user32.TranslateMessage, wintypes.BOOL, [ptr]),
(user32.DispatchMessageW, ctypes.c_ssize_t, [ptr]),
(user32.PostQuitMessage, None, [num]),
(user32.PostThreadMessageW, wintypes.BOOL,
[dword, uint, wintypes.WPARAM, wintypes.LPARAM]),
(kernel32.GetModuleHandleW, ptr, [text]),
(kernel32.GetCurrentThreadId, dword, []),
)
for fn, restype, argtypes in prototypes:
fn.restype = restype
fn.argtypes = argtypes
return user32, kernel32


class DeviceEventWatcher:
"""Sets a callback when a device arrives, leaves or the PC resumes.

`callback(reason)` runs on a short-lived timer thread, never inside the
window procedure: the poll thread may do native I/O, and an event storm (a
dock exposing six interfaces) must not run it once per node.
"""

def __init__(self, callback: Callable[[str], None],
*, device_delay: float = DEVICE_DELAY,
resume_delay: float = RESUME_DELAY):
self.callback = callback
self.device_delay = max(0.0, float(device_delay))
self.resume_delay = max(0.0, float(resume_delay))
self.count = 0
self._thread: Optional[threading.Thread] = None
self._thread_id = 0
self._hwnd = 0
self._ok = False
self._lock = threading.Lock()
self._generation = 0
self._reason = ""
self._timer: Optional[threading.Timer] = None
self._wndproc = None # keep the ctypes callback alive

# ---------------------------------------------------------------- public
def start(self) -> bool:
if sys.platform != "win32" or self._thread is not None:
return self._ok
ready = threading.Event()
self._thread = threading.Thread(target=self._run, args=(ready,), daemon=True,
name="device-events")
self._thread.start()
ready.wait(2.0)
return self._ok

def running(self) -> bool:
return self._ok and self._thread is not None and self._thread.is_alive()

def stop(self) -> None:
with self._lock:
self._generation += 1 # drop a pending debounce
timer, self._timer = self._timer, None
if timer is not None:
timer.cancel()
if self._thread_id:
try:
user32, _ = _user32_kernel32()
user32.PostThreadMessageW(self._thread_id, WM_QUIT, 0, 0)
except Exception:
pass

# ---------------------------------------------------------------- events
def _signal(self, reason: str) -> None:
with self._lock:
# A resume wins over the device messages it produces, and a pending
# device message is replaced rather than queued: one poll sees both.
if reason == "resume" or self._reason != "resume":
self._reason = reason
self.count += 1
self._generation += 1
generation = self._generation
delay = self.resume_delay if self._reason == "resume" else self.device_delay
old, self._timer = self._timer, None
if old is not None:
old.cancel()
timer = threading.Timer(delay, self._fire, args=(generation,))
timer.daemon = True
with self._lock:
if generation == self._generation:
self._timer = timer
timer.start()

def _fire(self, generation: int) -> None:
with self._lock:
if generation != self._generation:
return
reason, self._reason = self._reason, ""
self._timer = None
try:
self.callback(reason)
except Exception: # pragma: no cover - callback is app code
pass

# ---------------------------------------------------------------- window
def _run(self, ready: threading.Event) -> None:
import ctypes
from ctypes import wintypes

class GUID(ctypes.Structure):
_fields_ = [("Data1", wintypes.DWORD), ("Data2", wintypes.WORD),
("Data3", wintypes.WORD), ("Data4", ctypes.c_ubyte * 8)]

class DEV_BROADCAST_DEVICEINTERFACE(ctypes.Structure):
_fields_ = [("dbcc_size", wintypes.DWORD),
("dbcc_devicetype", wintypes.DWORD),
("dbcc_reserved", wintypes.DWORD),
("dbcc_classguid", GUID),
("dbcc_name", ctypes.c_wchar * 1)]

class WNDCLASSW(ctypes.Structure):
_fields_ = [("style", wintypes.UINT),
("lpfnWndProc", ctypes.c_void_p),
("cbClsExtra", ctypes.c_int),
("cbWndExtra", ctypes.c_int),
("hInstance", ctypes.c_void_p),
("hIcon", ctypes.c_void_p),
("hCursor", ctypes.c_void_p),
("hbrBackground", ctypes.c_void_p),
("lpszMenuName", wintypes.LPCWSTR),
("lpszClassName", wintypes.LPCWSTR)]

def guid(text: str) -> GUID:
import uuid
return GUID.from_buffer_copy(uuid.UUID(text).bytes_le)

user32, kernel32 = _user32_kernel32()
wndproc_type = ctypes.WINFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, wintypes.UINT,
ctypes.c_void_p, ctypes.c_void_p)

def on_message(hwnd, message, wparam, lparam):
try:
reason = classify(message, int(wparam or 0))
if reason:
self._signal(reason)
elif message == WM_DESTROY:
user32.PostQuitMessage(0)
except Exception:
pass
return user32.DefWindowProcW(hwnd, message, wparam, lparam)

self._wndproc = wndproc_type(on_message)
instance = kernel32.GetModuleHandleW(None)
class_name = "HaloBatteryDeviceEvents"
wc = WNDCLASSW()
wc.lpfnWndProc = ctypes.cast(self._wndproc, ctypes.c_void_p)
wc.hInstance = instance
wc.lpszClassName = class_name
atom = user32.RegisterClassW(ctypes.byref(wc))
if not atom:
ready.set()
return
hwnd = None
handles = []
try:
hwnd = user32.CreateWindowExW(0, class_name, "", 0, 0, 0, 0, 0,
None, None, instance, None)
if not hwnd:
ready.set()
return
self._hwnd = hwnd
for text in INTERFACES:
size = ctypes.sizeof(DEV_BROADCAST_DEVICEINTERFACE)
filt = DEV_BROADCAST_DEVICEINTERFACE()
filt.dbcc_size = size
filt.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE
filt.dbcc_classguid = guid(text)
h = user32.RegisterDeviceNotificationW(hwnd, ctypes.byref(filt),
DEVICE_NOTIFY_WINDOW_HANDLE)
if h:
handles.append(h)
self._thread_id = kernel32.GetCurrentThreadId()
self._ok = bool(handles)
ready.set()
if not handles:
return
msg = wintypes.MSG()
while user32.GetMessageW(ctypes.byref(msg), None, 0, 0) > 0:
user32.TranslateMessage(ctypes.byref(msg))
user32.DispatchMessageW(ctypes.byref(msg))
finally:
for h in handles:
try:
user32.UnregisterDeviceNotification(h)
except Exception:
pass
if hwnd:
try:
user32.DestroyWindow(hwnd)
except Exception:
pass
self._hwnd = 0
try:
user32.UnregisterClassW(class_name, instance)
except Exception:
pass
self._ok = False
1 change: 1 addition & 0 deletions halo/locales/en.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@
"state.no_link": "no link (off or asleep)",
"state.level": "{level}%",
"state.charging": "{state}, charging",
"state.fully_charged": "{state}, fully charged",
"state.asleep": "{state} (last known value, device asleep)",
"provider.ajazz": "AJAZZ mice",
"provider.akko_s9": "Akko Verge S9 Ultra headset",
Expand Down
1 change: 1 addition & 0 deletions halo/locales/es.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@
"state.no_link": "sin conexión (apagado o suspendido)",
"state.level": "{level}%",
"state.charging": "{state}, cargando",
"state.fully_charged": "{state}, carga completa",
"state.asleep": "{state} (último valor conocido, dispositivo suspendido)",
"provider.ajazz": "Ratones AJAZZ",
"provider.akko_s9": "Auriculares Akko Verge S9 Ultra",
Expand Down
1 change: 1 addition & 0 deletions halo/locales/fr.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@
"state.no_link": "aucune liaison (éteint ou en veille)",
"state.level": "{level} %",
"state.charging": "{state}, en charge",
"state.fully_charged": "{state}, chargé à 100 %",
"state.asleep": "{state} (dernière valeur connue, périphérique en veille)",
"provider.ajazz": "Souris AJAZZ",
"provider.akko_s9": "Casque Akko Verge S9 Ultra",
Expand Down
1 change: 1 addition & 0 deletions halo/locales/ja.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@
"state.no_link": "未接続(電源オフまたはスリープ)",
"state.level": "{level}%",
"state.charging": "{state}、充電中",
"state.fully_charged": "{state}、充電完了",
"state.asleep": "{state}(前回の残量、デバイスはスリープ中)",
"provider.ajazz": "AJAZZ マウス",
"provider.akko_s9": "Akko Verge S9 Ultra ヘッドセット",
Expand Down
Loading