Compare commits

...

489 Commits

Author SHA1 Message Date
Peter F. Patel-Schneider a866de47fb udev: correctly re-raise access exception 2025-10-17 19:41:23 -04:00
NaviMen 632d4dd5a0 Update i18n.md
- Ukrainian: Олександр Афанасьєв
2025-10-17 19:40:48 -04:00
Peter F. Patel-Schneider f942dbec41 device: add special keys from Logitech 2025-10-16 20:57:15 -04:00
Олександр Афанасьєв 6fa8ec6b86 i18n: Add and complete Ukrainian translation (uk) 2025-10-16 20:54:12 -04:00
MistificaT0r 137dd6b2ff update Russian translation 2025-10-14 19:25:57 -04:00
Matthaiks bdb0e9589b Update Polish translation 2025-10-10 19:12:19 -04:00
Peter F. Patel-Schneider 0335dd003c release 1.1.15rc2 2025-10-10 09:19:31 -04:00
Peter F. Patel-Schneider 8bea0121cc release 1.1.15rc1 2025-10-10 09:19:31 -04:00
Peter F. Patel-Schneider 783bd5e4da device: fix bug with unknown tasks 2025-10-05 08:05:15 -04:00
ian-jeong 68514d83c1 fix: center labels and remove buggy entry resizing logic 2025-09-30 10:42:25 -04:00
ian-jeong 6409fc2832 fix: correct spelling of 'completion' in diversion_rules.py 2025-09-30 10:42:25 -04:00
Peter F. Patel-Schneider dc28ab61c2 device: add shape keys from Key POP Icon 2025-09-30 10:34:23 -04:00
Peter F. Patel-Schneider 94f4c3230b rules: Device and Action rule conditions match on codename and name 2025-09-30 10:23:50 -04:00
Rok Mandeljc 62aaeac595 GitHub CI: fix and re-enable macOS tests with python 3.13
Fix the `Failed to load shared library 'libglib-2.0.0.dylib' referenced
by the typelib` error by adding the common Homebrew's shared library
directory (i.e., `$(brew --prefix)/lib`) to the dyld library search path.
This ensures that all Homebrew-installed shared libraries are discoverable
via `dlopen()`-like loading mechanism. (Previously, only directory
with `libhidapi` shared library was explicitly added to search path).

Use `DYLD_FALLBACK_LIBRARY_PATH` instead of `DYLD_LIBRARY_PATH` to
register the Homebrew library directory as a fallback search path
rather than preferred/default one. In general, this should be
preferred way of modifying library search path with 3rd-party
installations, even though it probably bears no real difference in
this particular scenario.
2025-09-14 18:52:00 -04:00
Peter F. Patel-Schneider 694caf635e docs: give uninstallation file correct name 2025-09-08 13:28:39 -04:00
Stephen Kitt 924684b610 Apply uaccess rules on all actions other than remove
These actions now need to react to "change" uevents, not only "add"
uevents. The recommendation from
5a8b9fd49f/NEWS (L22)
is to apply them on all non-"remove" uevents, which is what is done
here.

See also https://bugs.debian.org/1112660

Signed-off-by: Stephen Kitt <steve@sk2.org>
2025-09-08 10:11:52 -04:00
Peter F. Patel-Schneider abc5a31c15 install: fix bug in apt install target 2025-09-08 09:55:21 -04:00
Salim B 3c11eff55a docs(metainfo): Add link to source repo
cf. https://docs.flathub.org/docs/for-app-authors/metainfo-guidelines#url
2025-09-08 09:54:36 -04:00
MattHag 001dce7ef5 GitHub CI: Disable latest Python tests on macOS
Related #2892
2025-09-08 09:52:51 -04:00
Nick 3f24d52f7a Update Swedish translation 2025-09-08 09:52:04 -04:00
MattHag 2a363a6388
Unsupported locale: Fall back to English (#2891)
* Unsupported locale: Fall back to English

For any locale that is not supported, automatically fall back to no
translation, so it is English.

Fixes #2889

* Update lib/solaar/i18n.py

---------

Co-authored-by: Peter F. Patel-Schneider <pfpschneider@gmail.com>
2025-09-08 09:44:45 -04:00
Peter F. Patel-Schneider bebadc219c
fixes battery setting when device is not available (#2890)
* device: fix battery setting when device is not available
2025-06-09 05:31:52 -04:00
Peter F. Patel-Schneider 694513832d
device: report symbolic names for pairing errors (#2886)
* device: report symbolic names for pairing errors

* testing: fix testing of notifications
2025-05-31 08:12:42 -04:00
Peter F. Patel-Schneider 1a9725f540 doc: update status of hid_parser 2025-05-21 11:52:31 -04:00
mattdale77 c7a54cf7ec Update installation.md
Fix link to the desktop file
2025-05-21 11:51:50 -04:00
Alban Browaeys 7066ec40c9
device: Fix listing hidpp10 devices - bytes vs string concatenation (#2856)
* Fix listing hidpp10 devices - bytes vs string concatenation

Fix error concatenating a bytes with a string.

Closes #2855.

Fixes: 5e0c85a6 receiver: Refactor extraction of serial and max. devices

* Update lib/logitech_receiver/receiver.py

---------

Co-authored-by: Peter F. Patel-Schneider <pfpschneider@gmail.com>
2025-04-22 08:47:26 -04:00
Peter F. Patel-Schneider abea1c4341 device: add present flag, unset when internal error occurs, set when notification appears 2025-04-22 08:45:55 -04:00
Peter F. Patel-Schneider 217b9360e6 device: pause setting up features when error occurs; use ADC message to signal connection and disconnection 2025-04-22 08:45:55 -04:00
Ágata Leuck 33a06ac834 docs: add G604 mouse details 2025-04-13 20:29:39 -04:00
Alban Browaeys 03cfa12852 Fix listing of hidpp10 peripherals
The Flag enum was applied the value method twice. remove the value
method call from the set_flag_bits in  device.py. There is no such value
call in receiver.py set_flag_bits in the same commit so I believe this
was a mistake.
With this fix the LX7 mouse is properly enumerated over a Logitech
C-BT44 Receiver (seen as EX100, compatible 27MHz FastRF protocol)

Close #2850.

Fixes: 72c9dfc5 Remove NamedInts: Convert NotificationFlag to flag
2025-04-07 10:29:41 -04:00
Alban Browaeys 41ba24eee2 Complete DEVICE_FEATURES to DeviceFeature transition for hidpp10 devices
Fixes solaar show.

Fixes: 378175f9 Remove NamedInts: Convert DeviceFeature to flag
2025-04-07 10:24:13 -04:00
Alban Browaeys ed596666ee Fix NOTIFICATION_FLAG to NotificationFlag transition leftovers
Fixes "solaar show" for hidpp10 device (or at least for 27MHz FastRF
hidpp10 peripherals).

Fixes: 72c9dfc5 Remove NamedInts: Convert NotificationFlag to flag
2025-04-07 10:24:13 -04:00
Alban Browaeys 16bd8126b6 Fix github workflow stopping all matrix jobs when one of them fails 2025-04-05 20:37:33 -04:00
Alban Browaeys 17150658bf Fix ubuntu github CI
python 3.13 brings pygobject >= 3.52.1 which requires libgirepository 2.0.
Add gobject-introspection has libgirepository-2.0-dev does not depends
on it and it is required by PyGObject.

Closes #2857.
2025-04-05 20:32:29 -04:00
Rolf Leggewie f0ad2692b8 Update index.md
improve the wording describing the limitations set by the differences between the devices
2025-03-30 20:50:23 -04:00
Rolf Leggewie d033a3c8fc Update index.md - add missing word 2025-03-30 20:50:23 -04:00
Peter F. Patel-Schneider 1613584c6a docs: python documentation appears to be broken so don't set it up 2025-03-29 09:35:33 -04:00
ml- ebf8493e72 docs: add information for MX Anywhere 3 for Business 2025-03-29 09:24:07 -04:00
Peter F. Patel-Schneider 7a5a67c394 docs: improve documentation on onboard profiles 2025-03-29 09:22:59 -04:00
Peter F. Patel-Schneider 3fcc75f892 settings: use correct LOD values for extended adjustable dpi 2025-03-25 10:52:56 -04:00
Matija Kljajić 7b28423572 docs(i18n): mention Serbian translation 2025-03-21 12:20:00 -04:00
Peter F. Patel-Schneider 198067519d settings: better support RGB Effects - not readable 2025-03-03 14:11:09 -05:00
Peter F. Patel-Schneider 94155dbbf1 cli: fix crash when asking for help about config 2025-03-03 14:09:22 -05:00
Peter F. Patel-Schneider 64943c90d9 ui: fix error when updating ChoiceControlBig box 2025-02-26 16:08:23 -05:00
Purvi Das 637e562699 Adding uninstallation docs 2025-02-22 15:31:05 -05:00
Peter F. Patel-Schneider 9b5e416755 receiver: Handle unknown power switch locations again
Ensure functionality via unit test.
2025-02-22 15:29:35 -05:00
Peter F. Patel-Schneider d8f321a5e9 ui: correctly handle selection of [empty] in rule editor 2025-02-11 17:37:21 -05:00
SeongWoo Chung df2df301e2
macOS: handle `HIDError` in `hidapi.hidapi_impl._match()` (#2804)
* Fix: handle `HIDError` in `hidapi.hidapi_impl._match()`
The `open_path()` function may raise `HIDError` but `_match()`, its caller, does not handle it, unlike other cases after opening the path. This affects to the device enumeration process in `hidapi.enumerate()`, causing some devices to be randomly undiscovered.

* hidapi: revert to independent checking of long and short HID++ features with an extensible refactor

* Refactor: too long line
2025-02-09 12:31:20 -05:00
Peter F. Patel-Schneider cefc502db9 ui: give ghost devices a path 2025-02-08 15:30:37 -05:00
Peter F. Patel-Schneider 7d4f787344 ui: guard against typeerror when setting the value of a control box 2025-02-04 10:22:28 -05:00
Peter F. Patel-Schneider e297f90e79 device: recover from errors in ping 2025-02-04 10:22:28 -05:00
Peter F. Patel-Schneider 20e20ce827 diversion: replace spaces by underscores when looking up features 2025-02-04 09:10:00 -05:00
DomHeadroom 90ab457ebe Rewrote string concatenation/format with f strings 2025-01-29 08:40:14 -05:00
daviddavid 297ccb9cc1 Fix logo not showing in about dialog box 2025-01-29 08:35:53 -05:00
Dominik 'Rathann' Mierzejewski d95068c3f5 make typing-extensions dependency mandatory
It's imported unconditionally in:
lib/solaar/ui/about/presenter.py:19
lib/logitech_receiver/hidpp10.py:22
lib/logitech_receiver/hidpp20.py:35

Fixes 469c04f (committed as part of #2428).
2025-01-10 17:00:03 -05:00
MattHag 3de575b697 Fix: Properly ignore unsupported locale
Generalize exception to catch anything locale error.

Related #2507
Fixes #2765
2025-01-10 16:58:17 -05:00
vulpes2 41e652609b hidapi: skip unsupported devices and handle exception on open 2025-01-02 17:18:39 -05:00
vulpes2 73ad98d5e4 Ignore macOS junk files and pipenv config 2025-01-02 17:18:39 -05:00
Peter F. Patel-Schneider b9557a46b6 docs: mention typing dependency 2025-01-02 15:05:12 -05:00
Peter F. Patel-Schneider 5a03433f86 tests: fix ui desktop notifications test 2025-01-02 15:04:41 -05:00
MattHag 81567a98df hidpp20: Remove dependency to NamedInts
Replace ButtonBehaviors and ButtonMappingTypes with IntEnum.

Related #2273
2025-01-02 11:06:04 -05:00
MattHag bd00cc97ad
Estimate accurate battery level for some rechargable devices (#2745)
* battery: Extract battery level estimation into function

Test battery level estimation with sharp edges based on predefined
steps. Rename variable for clarity and add type hints.

Related #2744

* battery: Interpolate battery level for some rechargeable devices in percent

Estimate remaining battery based on measured battery voltage. Use linear
interpolation to achieve a smooth line instead of 10 percent jumps.

Fixes #2744
2025-01-02 10:58:07 -05:00
Peter F. Patel-Schneider 3192fa1a34 testing: upgrade desktop notifications tests to take notifications availability into account 2025-01-02 10:47:53 -05:00
MattHag 9af67f0e1d Update tests to run on Python 3.13 2025-01-02 10:47:03 -05:00
MattHag 382e0b6797 solaar: Remove outdated logger enabled checks
Logger enabled checks clutter the code unnecessarily. The checks are
now handled in a custom logger class. Eventually they can be completely
removed in the future.

Related #2664
2025-01-02 09:26:31 -05:00
MattHag f5d80c30fa solaar/ui: Remove outdated logger enabled checks
Logger enabled checks clutter the code unnecessarily. The checks are
now handled in a custom logger class. Eventually they can be completely
removed in the future.

Related #2664
2025-01-02 09:26:31 -05:00
MattHag 636f736765 solaar/cli: Remove outdated logger enabled checks
Logger enabled checks clutter the code unnecessarily. The checks are
now handled in a custom logger class. Eventually they can be completely
removed in the future.

Related #2664
2025-01-02 09:26:31 -05:00
MattHag e9a58fb3e0 Introduce GTK signal types
Related #2273
2025-01-02 08:29:32 -05:00
MattHag ab52c4a7c0 Introduce error types
Related #2273
2025-01-02 08:29:32 -05:00
MattHag 3bf8a85866 hidapi: Remove outdated logger enabled checks
Logger enabled checks clutter the code unnecessarily. The checks are
now handled in a custom logger class. Eventually they can be completely
removed in the future.

Related #2664
2025-01-02 08:23:09 -05:00
MattHag d42524dec9 notification: Remove alias for SupportedFeature
Related #2273
2025-01-02 08:05:02 -05:00
MattHag 8894463f64 notification: Refactor process_device_notification
Simplify code and unify interfaces and type hints.

Related #2273
2025-01-02 08:05:02 -05:00
MattHag 15aaba2802 notification: Refactor process_receiver_notification
Remove repeated code pattern with generalized implementation. Aim
towards easy extension and code readability.

Related #2273
2025-01-02 08:05:02 -05:00
MattHag fa3a9bc5b3 notification: Refactor receiver event handling
Split processing of receiver notification into smaller functions.
Extract handler functions for every receiver notification for simple
maintenence and testability.

Related #2273
2025-01-02 08:05:02 -05:00
MattHag 33c057feff Introduce custom logger
Implement logger that internally checks if log level is enabled. Thus,
unnecessary log message computation costs are avoid, when logging is
disabled and logging code can be cut in half.

Related #2663
2025-01-02 07:56:46 -05:00
MattHag 810cda917a Refactor notifications
Add type hints and reasonable variable names.

Related #2711
2025-01-01 13:48:14 -05:00
MattHag 64ac437b7f Rename variable to full name notification
Related #2711
2025-01-01 13:48:14 -05:00
MattHag 207be464a5 Test notifications
Fixes #2711
2025-01-01 13:48:14 -05:00
MattHag f28a923d15 receiver: Test extraction of serial and max. devices
Related #2273
2025-01-01 12:52:33 -05:00
MattHag 5e0c85a6d7 receiver: Refactor extraction of serial and max. devices
Related #2273
2025-01-01 12:52:33 -05:00
MattHag 800d3498f4 Update release notes: Add Bluetooth macOS support with 1.15
Related #2729
2025-01-01 11:55:10 -05:00
MattHag 918b584b95 macOS: Fix int.from_bytes, int.to_bytes for show.py
Related #2729
2025-01-01 11:55:10 -05:00
MattHag 83c380f85b macOS: Remove udev rule warning
Warning about missing udev rules do not apply to macOS.

Related #2729
2025-01-01 11:55:10 -05:00
MattHag fd17e47382 macOS: Add support for Bluetooth devices
Use hidapi on macOS to communicate and configure Logitech peripherals
connected via Bluetooth. This brings macOS device support on the same
level as Linux. However, some rules might not be supported yet on macOS.

Tested with MX Keys and MX Master 3S.

Fixes #2729
2025-01-01 11:55:10 -05:00
cameronaw13 88787ab705 settings: add back and forward mouseclick actions 2025-01-01 11:46:05 -05:00
MattHag 1a3f4dab36 Speedup lookup of known receivers
Refactor get_receiver_info. Replacing data structure of known receivers
to avoid for loop, when an efficient dictionary lookup is possible.

Related #2273
2025-01-01 11:33:07 -05:00
MattHag 3186d880fc base: Refactor device filtering
Related #2273
2025-01-01 11:20:28 -05:00
MattHag 1e6af7fa7d base: Reorder private functions and variable definitions
Related #2273
2025-01-01 11:20:28 -05:00
MattHag 5d86c74df4 base: Turn filter_products_of_interest into a public function
Related #2273
2025-01-01 11:20:28 -05:00
MattHag 5cf7cbfd5d base: Improve tests of known receivers
Related #2273
2025-01-01 11:20:28 -05:00
some_developer 96364d2df3 Refactor InfoSubRegisters: Use IntEnum in favour of NamedInts 2025-01-01 10:46:04 -05:00
MattHag 378175f98f Remove NamedInts: Convert DeviceFeature to flag
Related #2273
2025-01-01 10:46:04 -05:00
MattHag 72c9dfc50c Remove NamedInts: Convert NotificationFlag to flag
Related #2273
2025-01-01 10:46:04 -05:00
MattHag 571cdb5f2d Prepare refactoring of NotificationFlag
Ensure behavior stays the same.

Related #2273
2025-01-01 10:46:04 -05:00
MattHag 5f5c7cdcce Fixes on top of refactoring 2025-01-01 10:46:04 -05:00
MattHag ad3916e1b8 Fix KeyFlag conversion 2025-01-01 10:46:04 -05:00
MattHag 6903eeefcd Remove NamedInts: Convert LedFormChoices to enum
Related #2273
2025-01-01 10:46:04 -05:00
MattHag c9d7d7234a charge status: Refactor to enum and move to module of use
The charge status is solely used in the hiddpp20 module, thus put it
into this module.

Related #2273
2025-01-01 10:46:04 -05:00
MattHag c34fd3c2b0 Remove NamedInts: Convert LedRampChoice to flag
Related #2273
2025-01-01 10:46:04 -05:00
MattHag b19c886426 Remove NamedInts: Convert HorizontalScroll to enum
Related #2273
2025-01-01 10:46:04 -05:00
MattHag 96c9cc2aa4 Remove NamedInts: Convert PowerSwitchLocation to flag
Related #2273
2025-01-01 10:46:04 -05:00
MattHag d27f7285e0 Remove NamedInts: Convert MappingFlag to flag
Related #2273
2025-01-01 10:46:04 -05:00
MattHag 5c736e9154 mapping flag: Move to module of use
The mapping flags are solely used in hiddpp20 module, thus put them into
this module.

Related #2273
2025-01-01 10:46:04 -05:00
MattHag 7c91d0b2db Remove NamedInts: Convert ActionId to enum
This data is not in use currently.

Related #2273
2025-01-01 10:46:04 -05:00
MattHag 5ca9c0a6ba Remove NamedInts: Convert Spec to enum
Related #2273
2025-01-01 10:46:04 -05:00
MattHag f54eeb7998 Remove NamedInts: Convert KeyFlag to Flag
Related #2273
2025-01-01 10:46:04 -05:00
MattHag 0bf7a78553 Add type hints
Related #2273
2025-01-01 10:46:04 -05:00
MattHag 267b0a723d key flags: Move to module of use
The key flags are solely used in hiddpp20 module, thus put them into the
module.

Related #2273
2025-01-01 10:46:04 -05:00
MattHag 5a9725ee17 Add type hints
Related #2273
2025-01-01 10:46:04 -05:00
MattHag 4c160d1723 Remove NamedInts: Convert Task to enum
Refactor code related to task and task ID.

Related #2273
2025-01-01 10:46:04 -05:00
MattHag b74e789715 Remove NamedInts: Convert Column to enum
Related #2273
2025-01-01 10:46:04 -05:00
MattHag 0d7fc46a81 settings: Add docstrings and type hint
Related #2273
2025-01-01 10:46:04 -05:00
MattHag 8bc42d20fb Enforce rules on RuleComponentUI subclasses
Enforce create_widgets and collect_values.

Related #2273
2025-01-01 10:46:04 -05:00
MattHag dd13993ff3 Simplify settings UI class
Classes shouldn't don't need to know about other settings classes.

Related #2273
2025-01-01 10:46:04 -05:00
MattHag cdaffce463 Refactor: Remove diversion alias
Related #2273
2025-01-01 10:46:04 -05:00
MattHag dfb4ccc93f type hints: Introduce settings protocol
Related #2273
2025-01-01 10:46:04 -05:00
MattHag 3636ed78bb Refactor: Convert Kind to IntEnum
Related #2273
2025-01-01 10:46:04 -05:00
MattHag 03de6fb276 Split up huge settings module
- Move validators into their own module.
- Convert Kind to IntEnum

Related #2273
2025-01-01 10:46:04 -05:00
Peter F. Patel-Schneider 789d35450c solaar: don't close temp file until after CLI call 2025-01-01 10:40:07 -05:00
MattHag 62e8aacd9f Remove Python 2 specific path handling
Related #2273
2025-01-01 10:18:44 -05:00
Nick 8eb0aec3e8 i18n: Swedish translations in .desktop files 2025-01-01 10:15:42 -05:00
MattHag 8a0fc13f23 Test arg parse 2025-01-01 10:14:10 -05:00
MattHag 41768d9616 Test receiver notification info 2025-01-01 10:14:10 -05:00
Nick a822b2f237 Update Swedish translation 2025-01-01 10:06:53 -05:00
Jan Fader dfafe15575 delete temp-file in case help-actions too 2025-01-01 10:04:44 -05:00
Jan Fader e6c833f635 delete tmpfile on close for cli 2025-01-01 10:04:44 -05:00
Peter F. Patel-Schneider 7e9babdc79 release 1.1.14 2025-01-01 09:42:39 -05:00
Nick 01d76bb0ed i18n: Swedish translations in .desktop files 2025-01-01 09:37:14 -05:00
Peter F. Patel-Schneider 3768354230 release 1.1.14rc4 2024-12-24 10:36:55 -05:00
Peter F. Patel-Schneider 87afc3659e cli: handle fake feature enums in show 2024-12-24 10:29:55 -05:00
Matthaiks 2e9aa64a2e Update Polish translation 2024-12-24 10:28:17 -05:00
Peter F. Patel-Schneider e945f797a2 release 1.1.14rc3 2024-12-23 10:57:24 -05:00
MattHag 73c88210f7 Fix battery entry in device
Enforce use of enum value.

Fixes #2700
Related #2273
2024-12-23 10:50:43 -05:00
Peter F. Patel-Schneider 510753ea67 release 1.1.14rc2 2024-12-23 10:40:49 -05:00
Peter F. Patel-Schneider c2a3bc7e55 release 1.1.14rc1 2024-12-23 10:40:49 -05:00
Nick b6f5f86c36 i18n: Swedish translations in .desktop files 2024-12-09 08:49:20 -05:00
Nick ba4fda00df Update Swedish translation 2024-12-09 06:39:04 -05:00
Nick 1fcedeee70 i18n: Swedish translations in .desktop files 2024-12-09 06:37:28 -05:00
Nick 2157fdb59c
po: Add translator to list (#2687)
* Add translator to list

* Update i18n.md

---------

Co-authored-by: Peter F. Patel-Schneider <pfpschneider@gmail.com>
2024-11-29 16:42:07 -05:00
Osman Karagöz c5f74953ce
po: Update tr.po (#2683) 2024-11-17 08:48:14 -05:00
Max Ammann ff6f7a8e22
settings: Add ratchet setting for smart shift enhanced devices (#2681)
* Add ratchet setting for smart shift enhanced devices

* Update lib/logitech_receiver/settings_templates.py

---------

Co-authored-by: Peter F. Patel-Schneider <pfpschneider@gmail.com>
2024-11-16 16:06:02 -05:00
Pierre Carru 8b0904ead0
receiver: fix BoltReceiver, Ex100Receiver __init__ (#2661) 2024-11-10 17:44:40 -05:00
Nick 9d5568f6e5
po: Update Swedish translation (#2671)
* Update Swedish translation

Small fixes

* Update sv.po

* Update sv.po

* Update sv.po
2024-11-09 12:17:06 -05:00
Nick ba4bbd0118
po: Update Swedish translation (#2670) 2024-11-08 15:48:35 -05:00
MattHag 862cef1f77 hidpp20_constants: Refactor Gesture into enum
Replace Gesture NamedInts with enum.

Related #2273
2024-11-03 14:41:07 -05:00
Romain Loutrel a19461b29d
refactor: replace ERROR NamedInts by IntEnum (#2645)
* refactoring(logitech_receiver/notifications): change to enums PairingError and BoltPairingError

* refactoring(logitech_receiver/notifications): change to enums PairingError and BoltPairingError (Fix pre-commit checks)

* refactor(logitech_receiver/base.py): create unit tests for ping function before replacing ERRORNamedInts by IntEnum

* refactor(logitech_receiver/base.py): create unit tests for request function before replacing ERROR NamedInts by IntEnum

* refactor(logitech_receiver/base.py): create unit tests for ping function before replacing ERRORNamedInts by IntEnum (add exclusion for macOS)

* refactor(logitech_receiver/base.py): create unit tests for ping function before replacing ERRORNamedInts by IntEnum (fix for python < 3.10)

* refactor(solaar/cli./probe.py): create unit tests for run function before replacing ERROR NamedInts by IntEnum (focusing on the call order when receiving errors)

* refactor(solaar/cli./probe.py): refactor register processing to handle short and long registers in a single loop structure for improved readability and reduced code duplication.

* refactor(logitech_receiver/hidpp10_constants.py): replace ERROR NamedInt by IntEnum.

* refactor(logitech_receiver/hidpp10_constants.py): distinguish hidpp10 and hidpp20 errors in the code for readibility.

* refactor(logitech_receiver/hidpp20_constants.py): replace ERROR NamedInt by IntEnum.

* refactor(logitech_receiver/hidpp20_constants.py): replace ERROR NamedInt by IntEnum. (fix problem with | operator when typing with python 3.8)

* feature(hide on startup option): Visual test (not binded yet) DRAFT

* refactor(solaar/cli./probe.py): create unit tests for run function before replacing ERROR NamedInts by IntEnum (focusing on the call order when receiving errors)

* refactor(solaar/cli./probe.py): refactor register processing to handle short and long registers in a single loop structure for improved readability and reduced code duplication.

* refactor(logitech_receiver/hidpp10_constants.py): replace ERROR NamedInt by IntEnum.

* refactor(logitech_receiver/hidpp20_constants.py): replace ERROR NamedInt by IntEnum.

* refactor(logitech_receiver/hidpp20_constants.py): replace ERROR NamedInt by IntEnum. (fix problem with | operator when typing with python 3.8)

* feature(hide on startup option): Visual test (not binded yet) DRAFT

* Merge: Refactor: hidpp20 to use enum

* Merge: Refactor: hidpp20 to use enum (fix test)

---------

Co-authored-by: some_developer <some.developper.44@gmail.com>
2024-11-02 10:17:50 -04:00
MattHag c90146df31
Refactor: hidpp20 to use enum (#2647)
* Remove duplicated Param definition

Use constants from hidpp20 constants

Related #2273

* hidpp20/Param: Refactor to use IntEnum

Related #2273

* hidpp20_constants: Refactor to use IntEnum

Related #2273
2024-11-02 08:33:58 -04:00
John Erling Blad 8518604155
i18n: Updated Norwegian Nynorsk (nn) (#2655)
Co-authored-by: John Erling Blad <jeblad@google.com>
2024-10-31 05:27:09 -04:00
John Erling Blad de033267fa i18n: Updated Norwegian Bokmål (nb) 2024-10-31 04:19:57 -04:00
John erling Blad 0d4fd4c537 i18n: Updated Norwegian Bokmål (nb) 2024-10-28 08:11:53 -04:00
MattHag 1afcfe4b57
refactor: use IntEnum for firmware and cidgroup constances
* Refactor: test_named_ints_flag_names

Shorten test and clarify behavior using binary numbers.

* Introduce plain flag_names function

This replicates the NamedInts functionality as plain function.

* Refactor FeatureFlag to use IntFlag

Replace NamedInts implementation with IntFlag enum and plain flag_names
function.

Related #2273

* Refactor FirmwareKind to use IntEnum

- Move general FirmwareKind to common module.
- Replace NamedInts implementation with IntEnum.
- Harden related HIDPP 1.0 get_firmware test.

Related #2273

* Refactor CID_GROUP, CID_GROUP_BIT to use IntEnum

Related #2273
2024-10-23 16:25:35 -04:00
Romain Loutrel 79ffbda903
change pairing error values to intenums
* refactoring(logitech_receiver/notifications): change to enums PairingError and BoltPairingError

* refactoring(logitech_receiver/notifications): change to enums PairingError and BoltPairingError (Fix pre-commit checks)

* refactor(logitech_receiver/base.py): create unit tests for ping function before replacing ERRORNamedInts by IntEnum

* refactor(logitech_receiver/base.py): create unit tests for request function before replacing ERROR NamedInts by IntEnum

* refactor(logitech_receiver/base.py): create unit tests for ping function before replacing ERRORNamedInts by IntEnum (add exclusion for macOS)

* refactor(logitech_receiver/base.py): create unit tests for ping function before replacing ERRORNamedInts by IntEnum (fix for python < 3.10)
2024-10-23 16:22:22 -04:00
Peter F. Patel-Schneider 2185a8390c ui: fix initialization bug for PackedRangeControl 2024-10-22 14:31:13 -04:00
rloutrel 0d12c6f229 notifications: Introduce unit tests 2024-10-20 12:57:00 -04:00
MattHag 0cd9c0c9b5 Refactor: Introduce Feature enum
Convert Feature NamedInts to SupportedFeature integer enum.

Related #2273
2024-10-14 07:28:09 -04:00
MattHag 11e7cbde69 Test Feature class
Related #2273
2024-10-14 07:28:09 -04:00
MattHag 06fd32b501 Test and refactor process_notification
Related #2273
2024-10-14 07:28:09 -04:00
MattHag badb76953d Test key_is_down
Related #2273
2024-10-14 07:28:09 -04:00
Peter F. Patel-Schneider a36973916c settings: check all bits for extended report rate 2024-10-13 20:46:21 -04:00
rloutrel 15659a1ee4 Fix copy-paste error while refactoring notifications.py 2024-10-11 13:23:55 -04:00
MattHag 194c385824 RuleComponentUI: Type hints methods 2024-10-11 07:42:38 -04:00
MattHag d1f9b9ca3d diversion_rules: Add type hints 2024-10-11 07:42:38 -04:00
MattHag 97d1e90ceb Fix signature of show
Fix diverged signature of RuleComponentUI subclasses.
2024-10-11 07:42:38 -04:00
MattHag 9f57955142 Action menu: Move context menu into own class
Reduce complexity of diversion dialog.
2024-10-11 07:42:38 -04:00
MattHag 0dec545bfd Fix rule saving command 2024-10-11 07:42:38 -04:00
MattHag 3277015ab6 diversion: Add type hints 2024-10-11 07:42:38 -04:00
MattHag 691e5878f9 Remove obsolete pytest fixture 2024-10-11 07:42:38 -04:00
MattHag bb559c0d7c base: Remove hard dependency on gi
Import gi solely for type checking.
2024-10-11 07:42:38 -04:00
MattHag 1f85ec01e7 base: Add more unit tests
Make internal functions private.
2024-10-11 07:42:38 -04:00
MattHag 58ddb0d6cd Introduce HIDAPI protocol
Improve type hints and names.
2024-10-11 07:42:38 -04:00
MattHag 46366b2430 Fix warnings from automatic code inspections
Warnings found by automatic code inspection and partially tackled
- Drop distuitls inf favour of setuptools
- Replace deprecated pyudev.Device.from_device_number
- Remove unnecessary brackets
- Avoid access to private variables etc.
- Shadows built-in name
- Line length >120 characters
- Not a module level variable
- Simplify clause
and more
2024-10-11 07:42:38 -04:00
MattHag 0f4d1aebcd ui/common: Introduce tests 2024-10-11 07:42:38 -04:00
MattHag 89233957dc settings: Add tests 2024-10-11 07:42:38 -04:00
MattHag c9e781e752 settings_template: Introduce State enum 2024-10-11 07:42:38 -04:00
MattHag 54aace050c Replace action strings with constants
Avoids spelling mistakes and helps readability.
2024-10-11 07:42:38 -04:00
MattHag cba3533869 Remove factory wrapper classes
A module level function is sufficient, no wrapper needed.
2024-10-11 07:42:38 -04:00
MattHag ef6b7dec2c receiver: Remove hard dependency on base
With this test all receiver tests are macOS compatible again. The low
level interface supports passing a fake API for unit tests.
2024-10-11 07:42:38 -04:00
MattHag 4e50e605a6 device: Remove hard dependency on base 2024-10-11 07:42:38 -04:00
MattHag 37e2ac80ba base: Add test for filter_products_of_interest 2024-10-11 07:42:38 -04:00
MattHag 614a5dc633 Add type hints and clean up 2024-10-11 07:42:38 -04:00
MattHag 1729189981 base: Add find_paired_node functions
Avoid direct access to hidapi and use the base module as low-level API
instead. This change replaces the remaining calls to find_paired_node
and find_paired_node_wpid by exposing them via base module.
2024-10-11 07:42:38 -04:00
MattHag 90c41dbe32 base: Add find_paired_node functions
Avoid the need for hidapi imports and add them to the base API module.
2024-10-11 07:42:38 -04:00
MattHag a7ad625023 Fix about dialog 2024-10-11 07:42:38 -04:00
MattHag 8d0672ac3c base_usb: Add external interface
Clean up, type hint and tests base_usb and related modules.
2024-10-11 07:42:38 -04:00
MattHag a75c4b9679 ui/about: Use Model-View-Presenter pattern for testability
Split model and view, and enable view mocks for unit tests without GDK.
2024-10-11 07:42:38 -04:00
MattHag 46fafa0e68 hidapi: Explicitly load hidapi/udev implementation
Linux uses udev, other platforms use the cross-platform hidapi
implementation. Remove implicit loading of hidapi in hidapi/__init__.py.
2024-10-11 07:42:38 -04:00
MattHag 99fc9c6fcb receiver: Remove hard dependency on hidapi 2024-10-11 07:42:38 -04:00
MattHag 615499dce2 device: Remove hard dependency on hidapi 2024-10-11 07:42:38 -04:00
MattHag 9907cb2875 Test coverage: Fix keysyms to be visible (#9)
Fix typo in package name.
2024-10-11 07:42:38 -04:00
MattHag 65d3b406c0 keysyms: Introduce tests for this package 2024-10-11 07:42:38 -04:00
MattHag b681aafaff keysymdef: Rename key symbols
Name the key symbol mapping different than the module itself.
2024-10-11 07:42:38 -04:00
MattHag 32fef49ff8 Upload test coverage reports solely after merging
Related #1097
2024-10-11 07:42:38 -04:00
Peter F. Patel-Schneider 4aada31b21 ui: augment pairing message for devices with multiple channels 2024-10-08 15:15:35 -04:00
MattHag 128ec43d70 solaar: Add type hints 2024-10-08 14:35:16 -04:00
MattHag 0481950324 base: Add type hints 2024-10-08 14:35:16 -04:00
MattHag aa354dc4c4 Replace global sw_id with function call
Add test for it.
2024-10-08 14:35:16 -04:00
MattHag 2442299539 base: Simplify receiver info retrieval
- Remove comments with unused receivers
- Simplify receiver hardcoded info
2024-10-08 14:35:16 -04:00
MattHag 2aa462532a settings_template: Prepare removal of desktop_notifications dependency
Related #2273
2024-10-08 14:35:16 -04:00
MattHag d5af19be8a Make ui/desktop_notifications testable
Introduce unit tests.

Related #2273
2024-10-08 14:35:16 -04:00
MattHag e8ef262433 Rename ui/notify module to desktop notifications
Related #2273
2024-10-08 14:35:16 -04:00
MattHag 912afff173 Make lr/desktop_notifications testable
Introduce unit tests.

Related #2273
2024-10-08 14:35:16 -04:00
MattHag 0f8ab61ddf Rename lr/notify module to desktop_notifications
Related #2273
2024-10-08 14:35:16 -04:00
MattHag c76b0ef36b Add code coverage badge
Related #1097
2024-10-08 14:35:16 -04:00
MattHag b1b9f01083 Setup reports and upload codecov
Create coverage.xml, upload it to GitHub CI and visualize with codecov.

Setup instruction:
- Install codecov for project
  https://github.com/settings/installations/55029514
- Add CODECOV_TOKEN in the GitHub CI project secrets

Related #1097
2024-10-08 14:35:16 -04:00
MattHag 454e1601bd Introduce test coverage threshold
Enforce a total coverage of 40% of the code.

Related #1097
2024-10-08 14:35:16 -04:00
MattHag c1bc39f99f Fix test coverage reporting
Related #1097
2024-10-08 14:35:16 -04:00
MattHag 26667afea4 Simplify setup with pathlib 2024-10-08 14:35:16 -04:00
MattHag 741c0861c2 Clarify that fake hidpp is used
This module shouldn't be necessary on the long run. Remove pieces from
it whenever possible.
2024-10-08 14:35:16 -04:00
MattHag 3c1aa35067 hidapi: Completely remove dependency on gi
Related #2480
2024-10-08 14:35:16 -04:00
MattHag 40033c0183 Introduce hid_parser tests
Add basic tests to cover the package.
2024-09-15 09:19:13 -04:00
MattHag 8fb087be14 logitech_receiver: Remove GDK dependency 2024-09-15 09:18:51 -04:00
MattHag ea0eb66f39 Refactor: Remove all GDK dependencies from hidapi package
The hidapi hardware layer must not know or depend on any UI libraries.
Removes all GDK dependencies from the hidapi packages, which makes
testing of these modules easier and removes unwanted cross-dependencies.

Related #2480
2024-09-15 09:18:51 -04:00
MattHag 70def31942 Refactor: Distinguish module from package
Adapt module names to easily distinguish them.

Related #2480
2024-09-15 09:18:51 -04:00
Peter F. Patel-Schneider fdd2c79950 settings: allow unkonwn keys in Key rule conditions 2024-08-28 10:40:23 -04:00
Peter F. Patel-Schneider ae39ac46ba docs: improve documentation for cli actions 2024-08-23 20:03:54 -04:00
Peter F. Patel-Schneider 4578f5f6f1 device: cycle sw_id to better guard against duplication of messages 2024-08-23 19:41:10 -04:00
Peter F. Patel-Schneider c07c30baef device: handle error return on root feature 2024-08-23 19:41:10 -04:00
MattHag af12f8df52 Remove incomplete developer docs
Auto generated code documentation is incomplete, remove it.

Related #2503
2024-08-23 18:44:52 -04:00
MattHag 48ff85ab94 Publish GitHub pages only on push to master
Avoid draft documentation from being published.
2024-08-23 18:44:14 -04:00
Peter F. Patel-Schneider 64a9aac0d5 docs: add information about Onboard Profiles overriding some settings 2024-08-10 10:42:28 -04:00
Peter F. Patel-Schneider ce197b7093 doc: add wording to README.md that Solaar is not a device driver 2024-07-24 07:19:24 -04:00
IskandarMa 7b797f40f7
i18n: Chinese translations in .desktop files (#2554)
* translation(v1.1.13): update solaar.pot; fix missing zh_CN translation; fix some mis-leading translation in zh_CN

* fix translation error

* i18n: zh_CN/zh_TW/zh_HK in .desktop files

---------

Co-authored-by: IskandarMa <zhenghe.mt@alibaba-inc.com>
2024-07-15 23:49:37 -04:00
MattHag 67829c5807
Clean up imports (#2537)
* Remove import as _ in solaar startup

Related #2273

* Remove import as _ in listener

Related #2273

* Remove import as _ in cli init

Related #2273

* Remove import as _ in gtk

Related #2273

* Remove import as _ in show

Related #2273

* Remove import as _ in tray

Related #2273

* Remove import as _ in profiles

Related #2273

* Remove import as _ in config

Related #2273

* Remove import as _ in config panel

Related #2273

* Remove import as _ in window

Related #2273

* Remove import as _ in pair

Related #2273

* Remove import as _ in pair window

Related #2273

* Remove import as _ in cli package

Related #2273

* Remove import as _ in ui package

Related #2273

* Remove commented out code

Related #2273

* Use constant for Logitech ID
2024-07-15 08:37:18 -04:00
Peter F. Patel-Schneider d9d67ed738 device: handle unknown device kinds 2024-07-02 10:59:16 -04:00
Peter F. Patel-Schneider 71d2a50cb4 docs: fix broken links to Solaar logo 2024-07-02 07:57:00 -04:00
IskandarMa 25b9ba70d2
po: Update zh_CN translation (#2541)
* translation(v1.1.13): update solaar.pot; fix missing zh_CN translation; fix some mis-leading translation in zh_CN

* fix translation error

---------

Co-authored-by: IskandarMa <zhenghe.mt@alibaba-inc.com>
2024-07-01 08:04:34 -04:00
MattHag 59b30706b8
docs: Use mkdocs for public documentation (#2527)
* Add mkdocs config

Build and debug docs locally:
mkdocs serve

* Add mkdocs config

* Introduce GitHub action for mkdocs

* Delete outdated doc files

* Generate Python documentation

* Clean up docs

- Remove ToDos from public docs
2024-07-01 08:03:50 -04:00
MattHag f40a5cc7a9
Clean up setup.py (#2536)
- Indent description
- Remove commented code

Related #2273
2024-06-29 15:23:38 -04:00
proletarius101 6d4cf80c89
docs: dead links in the AppStream file (#2539) 2024-06-29 15:22:25 -04:00
Anderson Silva 8ab8cb0225
docs: Update about.py (#2535)
Update copyright date in about page to reflect current year (2024)

Follow-up to #2074
2024-06-23 17:56:52 -04:00
Peter F. Patel-Schneider 3aa064b40f settings: finish change to new constants 2024-06-13 10:01:50 -04:00
Peter F. Patel-Schneider db93e9ab10 hidapi: remove check on driver 2024-06-13 07:44:47 -04:00
Peter F. Patel-Schneider a7784b40ab cli: finish change to show.py for new constants 2024-06-13 05:54:36 -04:00
MattHag 86b55b9c25 Introduce Enum BusID
Distinguishes Bluetooth and USB devices.
2024-06-03 08:37:02 -04:00
MattHag 7f5e156fa1 Introduce constant for Logitech vendor ID
The Vendor ID for Logitech is 0x46D = 1133.
2024-06-03 08:37:02 -04:00
MattHag d67466298b Introduce Enum for notification types 2024-06-03 08:37:02 -04:00
MattHag 9726b93a78 Improve base module
Use clearer names and type hints.
2024-06-03 08:37:02 -04:00
MattHag e316ed1bc2 Remove unnecessary receiver info 'hid_driver'
The same constant is used everywhere.
2024-06-03 08:37:02 -04:00
MattHag a5ded24057 Convert HIDPPNotification to dataclass
Replaces the very last namedtuple.
2024-06-03 08:37:02 -04:00
Peter F. Patel-Schneider 2113e63a75 device: be defensive when converting battery status to string 2024-06-03 08:33:11 -04:00
MattHag 104556e7a3 Automatically detect packages in /lib
Automate handling of internal packages.
2024-06-02 10:42:57 -04:00
MattHag be83dac209
hid: Convert definition of HID registers to enum
* Refactor HID Register definitions

Use enums for distinct type hints, easy discovery of registers.
Make constants uppercase and benefit from enum auto-completion.

Related #2273

* Improve type hints: Registers
2024-06-02 10:34:00 -04:00
MattHag c23ebcd267 Use double quotes for module level docstrings
Make module level docstrings distinguishable from license text.

Related #2273
2024-06-02 09:54:21 -04:00
MattHag 5a63e44d58 Remove empty comment lines
Remove hashtags solely used for structuring.

Related #2273
2024-06-02 09:54:21 -04:00
MattHag 244d0ee88a
solaar: clean up locale code
Usage example for German:
LC_ALL=de_DE.UTF-8 solaar

Related #2507
2024-06-01 12:09:55 -04:00
Peter F. Patel-Schneider 089b85676f docs: update built-in rules 2024-06-01 11:59:57 -04:00
MattHag cece723ea4
docs: Improve rules documentation
- Page heading
- Fix heading levels
- Improve some names
2024-05-27 12:50:42 -04:00
MattHag c29231bc6b
refactor: Creation of devices (#2493)
* Refine interfaces for testability

* Reenable fixed device tests
2024-05-27 11:58:16 -04:00
MattHag faf27ca323
docs: Add headings to structure rules.md
Allow users to find relevant information without reading a
long wall of text.
2024-05-27 09:55:41 -04:00
MattHag 815dce07be Unify imports in logitech package
Related #2273
2024-05-23 16:42:18 -04:00
Peter F. Patel-Schneider 90b0db6c3b device: don't ping device when getting name or codename 2024-05-22 21:22:08 -04:00
Matthias Hagmann c9dc232951 Refactor: Use dataclasses and enums
Replace unnecessary NamedInts in favour of default data types.
Simplify interfaces by reducing possible input from strings to members
of an enum.
2024-05-22 21:14:41 -04:00
Matthias Hagmann 469c04faaf Introduce Device protocol and type hints 2024-05-22 21:14:41 -04:00
Matthias Hagmann 675cd6ee34 Add typing_extensions dependency 2024-05-22 21:14:41 -04:00
Matthias Hagmann 193dbfda21 hidpp10: Move independent functions to module level 2024-05-22 21:14:41 -04:00
Matthias Hagmann 7d171b1d09 Refactor: Use dataclasses and enums
Replace NamedTuples with more flexible dataclass, which also support
type hints. Introduce enums to replace constant strings, which need to
be kept in sync. Also enhances interfaces by limiting it to the enum
values. Remove unused variables.
2024-05-22 21:14:41 -04:00
MattHag 500b9998c5
Fix macOS compatibility and reenable CI tests
* Fix CI for macOS

* Fix error message for missing hidapi

* Skip some device and receiver tests on macOS

Tests fail on macOS, enable them when unit tests are
refined to only test the module without dependencies.

* Safe guard dbus import
2024-05-22 18:45:40 -04:00
MattHag a9ce033cc8
docs: Update README.md
Related #2485
2024-05-16 17:48:33 -04:00
MattHag 9882d99125 docs: Add high-level graph of components
Gives an overview of the main components of Solaar and
their connections.
2024-05-16 15:59:41 -04:00
MattHag d0a3e474c7
hidapi: Unify imports in hidapi package (#2487)
Remove all 'import xyz as _xyz' and favor import of module name to
get more context in the code.

Related #2273
2024-05-16 15:58:22 -04:00
MattHag f15a50b4b2 docs: Move screenshots into dedicated folder
Clean up docs folder.
2024-05-16 15:55:44 -04:00
david_david 9d2cedbefe
po: Update French translation (for release 1.1.13)
- by David Geiger david.david@mageialinux-online.org
2024-05-12 09:58:51 -04:00
MattHag b321167304
Drop support for end-of-life Python 3.7
* Drop support for end-of-life Python 3.7

* Remove handling of code for Python 3.7 and older
2024-05-11 11:48:32 -04:00
Peter F. Patel-Schneider ea77335ecf release 1.1.13 2024-05-11 11:35:41 -04:00
MistificaT0r bfc06502c1
po: update Russian translation 2024-05-09 06:06:59 -04:00
Matthaiks 413d449188
po: Update Polish translation 2024-05-08 16:32:22 -04:00
Peter F. Patel-Schneider f30999a96a release 1.1.13rc1 2024-05-08 14:37:55 -04:00
Peter F. Patel-Schneider 6c11f4e480 solaar: fix bug in suspend and resume callback 2024-05-08 08:05:00 -04:00
Peter F. Patel-Schneider 1dfc4bdb1c settings: add choices universe for backlight setting 2024-05-08 08:05:00 -04:00
MattHag 20d34025d8 diversion: Add unit tests 2024-05-05 10:43:39 -04:00
MattHag 1d5b61fbf2 diversion: Simplify and type hint
- Make static method an easy testable function.
- Fix variable name clashes
2024-05-05 10:43:39 -04:00
Peter F. Patel-Schneider 3ffa4e30f1 settings: get and use current host number for K375sFnSwap because of bug in firmware of MX Keys S 2024-05-04 04:46:27 -04:00
Peter F. Patel-Schneider b4811f602d ui: fix bug with logo in about window 2024-05-04 04:46:27 -04:00
Peter F. Patel-Schneider 37aa0963da solaar: don't ping device just to get logging information 2024-05-04 04:46:27 -04:00
Peter F. Patel-Schneider da1cb53c1b settings: optimize write for per-key lighting 2024-05-03 11:54:24 -04:00
Peter F. Patel-Schneider e5967edc66 settings: add and initialize per-key lighting to a special no-change value 2024-05-03 11:54:24 -04:00
MattHag 704a87696f
hidapi: Remove Python 2 compatibility (#2460)
Related #2273
2024-04-30 08:19:50 -04:00
david_david 74e126e015
po: Update French translation (for release 1.1.12) (#2458)
- by David Geiger <david.david@mageialinux-online.org>
2024-04-28 06:59:34 -04:00
MattHag 959dd2a35b
Refactor rule loading for testability (#2456)
rules: Introduce tests for YAML rule loading functionality.
2024-04-27 17:56:27 -04:00
Peter F. Patel-Schneider 22a59b6b0b release 1.1.12 2024-04-27 17:51:04 -04:00
Peter Dave Hello 39e51fa8ff po: Update zh_TW Traditional Chinese translation 2024-04-27 17:47:38 -04:00
Peter F. Patel-Schneider 3160e3b3d6 release 1.1.12rc2 2024-04-22 12:13:46 -04:00
Peter F. Patel-Schneider 932bc5cb0e device: check for existences of keys file before opening 2024-04-21 17:37:10 -04:00
MistificaT0r 4225fce8d7
po: update Russion translation and have all strings translated
* update Russian translation

* Fixed translation display in GUI

* fix checks / Fixed translation display in GUI
2024-04-21 11:36:39 -04:00
MistificaT0r 2adeb2672a
po: update Russian translation (#2443) 2024-04-20 20:27:01 -04:00
Peter F. Patel-Schneider a5a0d7e80e dist: add included hid_parser to packages installed 2024-04-20 14:06:41 -04:00
Matthaiks 99f0d62aa0
po: Update Polish translation (#2439) 2024-04-20 06:24:23 -04:00
Peter F. Patel-Schneider cf038fd982 settings: improve label and description for LED zone settings 2024-04-19 16:05:29 -04:00
Peter F. Patel-Schneider 7bef5c046c settings: add message about Onboard Profiles to LED Zone settings 2024-04-19 16:05:29 -04:00
Peter F. Patel-Schneider c4e2a5683a device: initialize device registers to empty list 2024-04-19 16:05:29 -04:00
Matthaiks 8fbd643110
po: Update Polish translation (#2435) 2024-04-19 07:36:44 -04:00
Peter F. Patel-Schneider 7550d6b88c release 1.1.12rc1 2024-04-19 04:02:49 -04:00
Peter F. Patel-Schneider 08c748c593 release 1.1.12rc1 2024-04-19 03:54:54 -04:00
Peter F. Patel-Schneider e667d41c7b solaar: use bluez dbus signals to disconnect and connect bluetooth devices 2024-04-18 20:32:40 -04:00
Peter F. Patel-Schneider d7ce636917 device: handle a different signal for onboard profiles directory in ROM 2024-04-15 14:40:50 -04:00
Peter F. Patel-Schneider 86bab897d1 receiver: introduce small delay in getting pairing information to let receiver settle after pairing 2024-04-15 14:40:50 -04:00
Peter F. Patel-Schneider 1eb1d4b198 tests: extend tests for device.py 2024-04-13 18:38:44 -04:00
Peter F. Patel-Schneider b616419f72 device: fix bug found in testing 2024-04-13 18:38:44 -04:00
Peter F. Patel-Schneider c7195881e3 tests: expand tests for device.py 2024-04-13 18:38:44 -04:00
Peter F. Patel-Schneider 269e970aa6 device: fix small bugs uncovered by testing 2024-04-13 18:38:44 -04:00
Peter F. Patel-Schneider 9bb2a1ff5c tests: expand tests for settings_templates 2024-04-13 18:38:44 -04:00
Peter F. Patel-Schneider c7a2f1698b tests: extend testing of hidpp20 2024-04-13 18:38:44 -04:00
Peter F. Patel-Schneider d6499808f9 device: fix bugs in onboard profiles found during testing 2024-04-13 18:38:44 -04:00
Peter F. Patel-Schneider c283da27df tests: extend testing of hidpp20 2024-04-13 18:38:44 -04:00
Peter F. Patel-Schneider 3855409605 device: fix bugs in hidpp20 found during testing 2024-04-13 18:38:44 -04:00
Peter F. Patel-Schneider 6c67789bad tests: extend device testing 2024-04-13 18:38:44 -04:00
Peter F. Patel-Schneider d12575b47d tests: test GESTURES settings 2024-04-13 18:38:44 -04:00
Peter F. Patel-Schneider e64eec18e9 tests: extend testing of hidpp20 2024-04-13 18:38:44 -04:00
Karachalios Stagkas Athanasios Nektarios 091822185f Updated Greek Translation 2024-04-12 17:29:00 -04:00
Peter F. Patel-Schneider 157a2601d9 doc: add information about bad interaction between Bluez 5.73 and Solaar 2024-04-10 10:55:40 -04:00
Peter F. Patel-Schneider b43cdace79 tests: expand tests for settings_templates 2024-04-09 10:31:06 -04:00
Peter F. Patel-Schneider 8de3a1d2e2 device: better support for extended ajustable dpi 2024-04-09 10:31:06 -04:00
Peter F. Patel-Schneider ab94f1be07 device: limited support for extended adjustable dpi 2024-04-09 10:31:06 -04:00
Peter F. Patel-Schneider c70e8b54bf tests: remove unused code 2024-03-27 18:02:55 -04:00
Peter F. Patel-Schneider 12f3f2e856 tests: adjust imports to always import installed version 2024-03-27 18:02:55 -04:00
Peter F. Patel-Schneider cb16a46b93 tests: test more settings 2024-03-27 11:15:15 -04:00
Peter F. Patel-Schneider afe04b9804 settings: remove unused code and fix but in EQUALIZER setting 2024-03-27 11:15:15 -04:00
Peter F. Patel-Schneider f38fbcf949 settings: provide symbolic names for per-key lighting keys 2024-03-27 11:15:15 -04:00
Peter F. Patel-Schneider 4d0f93b35c tests: improve infrastructure for testing setting_templates 2024-03-27 11:15:15 -04:00
Peter F. Patel-Schneider 1ed5f765e3 settings: implement and test per-key lighting 2024-03-27 11:15:15 -04:00
Peter F. Patel-Schneider 04a818f215 tests: check for Gtk initialization and don't run tests that depend on it 2024-03-25 09:13:22 -04:00
Peter F. Patel-Schneider 41aacefa5e tests: test GUI pair_window 2024-03-25 09:13:22 -04:00
Peter F. Patel-Schneider bd437b548b ui: refactor pair_window 2024-03-25 09:13:22 -04:00
Peter F. Patel-Schneider 7d868425e7 tests: fix tests for RBG effects 2024-03-24 15:44:15 -04:00
Peter F. Patel-Schneider 8ee291c144 settings: add in bit telling RGB effects changes to change ROM 2024-03-24 15:44:15 -04:00
Peter F. Patel-Schneider 97d214f667 ui: handle situation when read of a setting fails 2024-03-24 15:44:15 -04:00
Peter F. Patel-Schneider 1a874c39d7 settings: permit continuing when a read during pushing fails 2024-03-24 15:44:15 -04:00
Peter F. Patel-Schneider dbd9fcfca6 tests: add tests for RGB EFFECTS settings 2024-03-24 15:44:15 -04:00
Peter F. Patel-Schneider e202e904b4 settings: add settings for RGB EFFECTS feature 2024-03-24 15:44:15 -04:00
Peter F. Patel-Schneider c8288a6b69 settings: fix bug in LEDZoneSetting when effect is not implemented 2024-03-24 15:44:15 -04:00
Peter F. Patel-Schneider c81809bd39 device: add RGB EFFECTS feature version of LED COLOR EFFECTS data 2024-03-24 15:44:15 -04:00
Peter F. Patel-Schneider 89b7fb6ef3 tests: add tests for LEDEffect structures in hidpp20 2024-03-24 15:44:15 -04:00
Peter F. Patel-Schneider 490493d7a3 device: handle BRIGHTNESS CONTROL notifications 2024-03-24 15:44:15 -04:00
Peter F. Patel-Schneider 3876f07d57 settings: implement and test BRIGHTNESS_CONTROL 2024-03-24 15:44:15 -04:00
Peter F. Patel-Schneider a5f1dd09a2 tests: expand tests for settings_templates 2024-03-24 07:02:39 -04:00
Peter F. Patel-Schneider 4fd75a64ff settings: fix small bugs found from testing 2024-03-24 07:02:39 -04:00
Matthias Hagmann 6f613b17c7 refactor: Manually improve f-string formatting 2024-03-24 07:01:56 -04:00
Matthias Hagmann 4e6361429e refactor: Use f-strings for more exceptions and log message
Semi manually convert remaining strings with no translation to f-string.
2024-03-24 07:01:56 -04:00
Peter F. Patel-Schneider d1d3d71091 settings: patch to make python 3.7 happy 2024-03-23 10:11:30 -04:00
Peter F. Patel-Schneider e9297cf8d8 tests: expand tests for settings_templates 2024-03-23 10:11:30 -04:00
Peter F. Patel-Schneider 88ac4c9f89 tests: use new test methods in test_hidpp20_simple 2024-03-23 10:11:30 -04:00
Peter F. Patel-Schneider 5e351399f5 tests: add tests for setting_templates 2024-03-23 10:11:30 -04:00
Peter F. Patel-Schneider 17bbc9c4ea settings: simple change to improve testability 2024-03-23 10:11:30 -04:00
Peter F. Patel-Schneider 47ba1402ed device: use feature_request from the device everywhere in hidpp20 2024-03-23 10:11:30 -04:00
Peter F. Patel-Schneider 7d6428a03b settings: fix bug in backlight 2 durations 2024-03-23 10:11:30 -04:00
Peter F. Patel-Schneider 07c0d35f80 tests: fix finding paired node in test_device 2024-03-23 08:26:12 -04:00
Peter F. Patel-Schneider 10e3f844dd tests: use hidpp module in several test modules 2024-03-23 08:26:12 -04:00
Peter F. Patel-Schneider ebc76bca24 tests: add tests for logitech_receiver device 2024-03-23 08:26:12 -04:00
Peter F. Patel-Schneider 50c8013cb1 ui: reduce deprecation warnings in ui 2024-03-19 09:07:21 -04:00
Peter F. Patel-Schneider c617988788 hidapi: remove deprecation warnings 2024-03-19 09:07:21 -04:00
Peter F. Patel-Schneider 871322bf68 tests: improve coverage of receiver.py 2024-03-16 16:24:33 -04:00
Peter F. Patel-Schneider 480badbe8c device: align init methods for all receiver classes 2024-03-16 16:24:33 -04:00
Peter F. Patel-Schneider e0047024a5 tests: use 3.7 type hint 2024-03-16 16:20:39 -04:00
Peter F. Patel-Schneider 6164317a64 tests: improve hidpp20 coverage 2024-03-16 16:20:39 -04:00
Peter F. Patel-Schneider 8de3866696 tests: fully cover hidpp10 2024-03-16 16:20:39 -04:00
Peter F. Patel-Schneider dcd72b0178 device: fix bug in hidpp10 get_device_features 2024-03-16 16:20:39 -04:00
Matthias Hagmann c6adf94e5d refactor: Use dataclass for TestByte
Related #2378
2024-03-14 17:15:10 -04:00
Matthias Hagmann 2f6e3e21ec refactor: Split diversion rules into smaller modules
Put rule conditions and actions into their into module

Related #2378
2024-03-14 17:15:10 -04:00
Matthias Hagmann 4e7356385d refactor: Make _populate_model a function
Related #2378
2024-03-14 17:15:10 -04:00
Peter F. Patel-Schneider 154dd7017f rules: allow sub-second delays in Later 2024-03-14 17:08:47 -04:00
Peter F. Patel-Schneider 4e4275c281 device: remove unreachable code 2024-03-14 17:08:47 -04:00
Peter F. Patel-Schneider d76eed85f6 device: fix bug in setting configuration cookie due to bad documentation 2024-03-14 17:06:17 -04:00
Ferdina Kusumah 84524bec3e Add new end line 2024-03-14 12:44:36 -04:00
Ferdina Kusumah a0e475c057 Add solaar pot generation 2024-03-14 12:44:36 -04:00
Ferdina Kusumah a02b1065ac Add indonesian translations 2024-03-14 12:44:36 -04:00
Peter F. Patel-Schneider d5bdf2b0f5 tests: complete testing of common 2024-03-13 16:08:16 -04:00
Peter F. Patel-Schneider 54ee78ee25 tests: start coverage of complex structures in hidpp20 2024-03-13 16:08:16 -04:00
Peter F. Patel-Schneider 4632c46e30 tests: expand coverage of hidpp20 2024-03-13 16:08:16 -04:00
Peter F. Patel-Schneider 03a5ca3d49 tests: expand coverage of common 2024-03-13 16:08:16 -04:00
Matthias Hagmann 5b09ace1f5 ruff: Apply single line import format
# Usage
pre-commit run --all-files

Related #2295
2024-03-13 15:41:21 -04:00
Matthias Hagmann 66d31885e4 ruff: Force single line imports
This makes commits easier to compare.

Related #2295
2024-03-13 15:41:21 -04:00
Matthias Hagmann e92f1a8a0b Automatically upgrade strings to f-string
Used flynt to convert strings to f-strings, where safely possible.

Usage:
flynt .

Related #2372
2024-03-13 11:02:50 -04:00
Peter F. Patel-Schneider 97ddee1929 docs: document battery-icons=solaar option 2024-03-13 08:50:28 -04:00
Peter F. Patel-Schneider b957217ea8 receiver: delay device sending first messages 2024-03-13 08:34:28 -04:00
Peter F. Patel-Schneider 4a89a79a4d device: remove checks for status attributes 2024-03-12 13:11:49 -04:00
Peter F. Patel-Schneider dfd3d10c2e device: optimize some functions in FeaturesArray 2024-03-12 12:21:17 -04:00
Peter F. Patel-Schneider 0b599194d1 device: fix bug in creating features array 2024-03-11 15:20:39 -04:00
Peter F. Patel-Schneider f3ff61cfc1 cli: fix bug in building battery line in show 2024-03-11 15:20:39 -04:00
MattHag 704d591448
ui: refactor diversion_rules
* refactor: Create close dialog in its own function

Related #2378

* refactor: Create selected rule edit panel in module level function

Related #2378

* refactor: Remove commented code

Related #2378

* refactor: Use Gdk constant for right click button comparison

Related #2378

* refactor: Make _menu_do_copy a function

Related #2378
2024-03-11 10:19:20 -04:00
Peter F. Patel-Schneider 569f829a63 ui: fix bug in determining tray icon 2024-03-11 08:23:27 -04:00
Peter F. Patel-Schneider 24223e77c7 device: fix bug in getting friendly name 2024-03-11 08:23:27 -04:00
Peter F. Patel-Schneider 9c5ba6445e device: remove status from Device and Receiver 2024-03-11 08:23:27 -04:00
Peter F. Patel-Schneider a1418cd834 device: move changed method from status to Device and Receiver 2024-03-11 08:23:27 -04:00
Peter F. Patel-Schneider 1fe2eab1a4 device: move link_encrypted from status to Device 2024-03-11 08:23:27 -04:00
Peter F. Patel-Schneider 15d425c365 device: move battery information from status to Device 2024-03-11 08:23:27 -04:00
Peter F. Patel-Schneider 0805ecb511 device: move status string function to Device and Receiver 2024-03-11 08:23:27 -04:00
Peter F. Patel-Schneider 87285faf7f receiver: move pairing status to new dataclass attached to receiver 2024-03-11 08:23:27 -04:00
MattHag 0d225f6cb1
test: Test base product information
* test: Test base product information

Related #1097

* Fix dependencies for gi
2024-03-10 10:11:02 -04:00
Matthias Hagmann e226b76b8b Disable macOS tests until GitHub CI dependencies are fixed
Related #1097
2024-03-10 09:20:39 -04:00
Matthias Hagmann cc7194fe3d Extend Ubuntu dependencies for GitHub CI
Related #1097
2024-03-10 09:20:39 -04:00
Matthias Hagmann 7ec3eddccc test: Extract get_kind_from_index function and test it
Pull get_kind_from_index from class to module level and add tests.

Related #1097
2024-03-10 09:20:39 -04:00
Peter F. Patel-Schneider c23c6b7124 docs: update EX100 information 2024-03-09 10:36:40 -05:00
Peter F. Patel-Schneider 523628926b device: use Python 3.7 type hints 2024-03-09 10:36:40 -05:00
Peter F. Patel-Schneider 135c8b8cb9 device: use status attribute for error 2024-03-09 10:36:40 -05:00
Peter F. Patel-Schneider 8154cd759f device: use status attribute for notification_flags 2024-03-09 10:36:40 -05:00
Peter F. Patel-Schneider 6b3f09aa5d device: use status attribute for link_encrypted 2024-03-09 10:36:40 -05:00
Peter F. Patel-Schneider 9121169f91 ui: use Battery object in GUI 2024-03-09 10:36:40 -05:00
Peter F. Patel-Schneider 64d8cad81a device: change status battery fields to Battery objects 2024-03-09 10:36:40 -05:00
Peter F. Patel-Schneider 3916c189be receiver: move more method code to subclasses 2024-03-08 15:39:12 -05:00
Matthias Hagmann 4eb5a83326 receiver: create subclasses of receiver for different variants
Related #2350
2024-03-08 15:39:12 -05:00
Peter F. Patel-Schneider a90a367609 docs: add requirement for CONFIG_HIDRAW 2024-03-07 16:32:41 -05:00
Peter F. Patel-Schneider 15ed26887b tests: tests for a few simple hidpp20 functions 2024-03-05 15:27:07 -05:00
Peter F. Patel-Schneider a2bf51386a tests: add yaml test for led setting 2024-03-05 15:27:07 -05:00
Peter F. Patel-Schneider c3e988a03a tests: simple tests for hidpp20 profiles and lighting 2024-03-05 15:27:07 -05:00
Swapnil Devesh 5ee1c6df30
ui: fix app name casing in UI
* Fix app name casing in UI

* Linter fixes

* Only use NAME variable

* FIx linter errors
2024-03-05 12:08:56 -05:00
Peter F. Patel-Schneider 51ef2a7fe2 device: add missing receiver type for Lightspeed receivers 2024-03-03 15:14:20 -05:00
Peter F. Patel-Schneider de8fe3685d device: add new device types 2024-03-03 15:14:20 -05:00
Matthias Hagmann c3b6802373 refactor: Get receiver product info before instantiation
Related #2350
2024-03-03 10:38:46 -05:00
Matthias Hagmann 8f6e8eef4c Refactor: Move Device instantiation to factory class
Related #2273
2024-03-03 09:32:42 -05:00
Matthias Hagmann 51e44052b0 Refactor: Move Receiver instantiation to factory class
Related #2350
2024-03-03 09:32:42 -05:00
Matthias Hagmann 5edf5e7419 Simplify name of license file
Related #2273
2024-03-02 18:15:56 -05:00
Matthias Hagmann 85af0fc667 Rename changelog.md to all capitals
The basic files in root often use all capitals, as is already used for
readme and manifest.

Related #2273
2024-03-02 18:15:56 -05:00
Matthias Hagmann 79f7c5ef77 Update .gitignore
Related #2273
2024-03-02 18:15:56 -05:00
Matthias Hagmann f11af99cf3 Remove unused .gitmodules
Related #2273
2024-03-02 18:15:56 -05:00
Matthias Hagmann 7d127ff068 fix: Use exception from exception module 2024-03-02 12:25:13 -05:00
Matthias Hagmann fb9dbb9c39 update: Replace legacy logger.warn with logger.warning
Related #1097
2024-03-02 10:56:41 -05:00
Matthias Hagmann d4702f0bf0 cleanup: Remove duplicated code to read register
Related #1097
2024-03-02 10:56:41 -05:00
Matthias Hagmann a29f2b8614 tests: Add hidpp10 tests
Related #1097
2024-03-02 10:56:41 -05:00
Matthias Hagmann 9c76a6c5ba refactor: Introduce Hidpp20 class
Related #1097
2024-03-02 10:56:41 -05:00
Matthias Hagmann 85149a809e refactor: Introduce Hidpp10 class
Related #1097
2024-03-02 10:56:41 -05:00
MattHag 574a95da50
cleanup: Remove unnecessary calls of del
Related #2273
2024-03-02 10:48:06 -05:00
Peter F. Patel-Schneider ad0f9ec712 settings: fix bug when reading BACKLIGHT setting from device 2024-03-02 09:22:57 -05:00
Matthias Hagmann 7ef3059b69 clean up: Remove editor specific marks
Related #2273
2024-02-29 10:10:46 -05:00
Matthias Hagmann e53b5380a3 fix: Replace invalid hidpp20 usage
Related #1097
2024-02-28 17:41:46 -05:00
Matthias Hagmann c3b01bffae fix: Replace invalid hidpp10 usage
Related #1097
2024-02-28 17:41:46 -05:00
Peter F. Patel-Schneider 6939fb7196 solaar: use only timer thread to save config.yaml 2024-02-27 14:47:03 -05:00
Peter F. Patel-Schneider e3b25840fd docs: improve README.md 2024-02-27 14:47:03 -05:00
Anton Soroko 1033921d7c
doc: Add link to Debian package to README.md
* Add link to Debian package to README.md

Add link to Debian package and mention its maintainer.
Also i removed mention about ubuntu version since they always changes b/c of "end of life/support". And i removed mention about kububntu since there are many other flavours of ubuntu like xubuntu.

* Update README.md

Co-authored-by: Peter F. Patel-Schneider <pfpschneider@gmail.com>

---------

Co-authored-by: Peter F. Patel-Schneider <pfpschneider@gmail.com>
2024-02-27 06:06:47 -05:00
Peter F. Patel-Schneider 1adc8ad688 docs: adjust image placing in README 2024-02-26 17:46:18 -05:00
Peter F. Patel-Schneider cebc5a3f57 docs: adjust image size in README 2024-02-26 17:38:54 -05:00
Peter F. Patel-Schneider f6003af99a docs: improve README 2024-02-26 17:29:46 -05:00
Peter F. Patel-Schneider 6805a57b94 hid: copy newer version of hid_parser into Solaar codebase 2024-02-26 14:19:16 -05:00
Peter F. Patel-Schneider 8ae86acd65 ui: fix bug when displaying receiver notification flags 2024-02-26 10:55:14 -05:00
Peter F. Patel-Schneider 67be689866 device: reorder code in settings 2024-02-25 07:23:03 -05:00
Peter F. Patel-Schneider e8dadcd5c2 doc: update installation documentation 2024-02-23 13:30:52 -05:00
Peter F. Patel-Schneider 069f96fe48 hidapi: make hid_parser optional, but add it to setup 2024-02-23 13:30:52 -05:00
Peter F. Patel-Schneider 20c4d64d17 device: add missing license blocks 2024-02-23 11:37:23 -05:00
Peter F. Patel-Schneider b7afc410ba device: clean up listener and notifications code 2024-02-23 11:37:23 -05:00
Peter F. Patel-Schneider 14f19ceaaf solaar: cleanup listener code 2024-02-23 11:37:23 -05:00
Peter F. Patel-Schneider 8744506259 solaar: add locks to prevent multiple persisters for device 2024-02-23 08:40:16 -05:00
Peter F. Patel-Schneider 3954bbd111 solaar: clean up configuration code 2024-02-23 08:40:16 -05:00
Peter F. Patel-Schneider ce2de71b1b device: clean up device and receiver code 2024-02-22 09:57:02 -05:00
Peter F. Patel-Schneider 646ef2f596 device: move battery constants common to HID++ 1.0 and 2.0 to common 2024-02-22 09:57:02 -05:00
Peter F. Patel-Schneider 24ae9bacaa device: move mapping of device kind into hidpp20 2024-02-22 09:57:02 -05:00
Peter F. Patel-Schneider 4b33c119f6 device: move pairing information gathering to receiver 2024-02-22 09:57:02 -05:00
Peter F. Patel-Schneider 9228fa1da0 docs: update contributors 2024-02-22 09:46:21 -05:00
Peter F. Patel-Schneider fc8628c9c5 solaar: fix debugging levels 2024-02-21 16:06:22 -05:00
Peter F. Patel-Schneider 353c2dfb2f device: expand allowable profile numbers 2024-02-21 16:06:22 -05:00
Peter F. Patel-Schneider 8e44c08139 device: clean up __init__ in logitech_receiver 2024-02-21 16:06:22 -05:00
Peter F. Patel-Schneider 767a729598 dist: modify pre-commit args to make ruff change files 2024-02-21 16:06:22 -05:00
Peter F. Patel-Schneider 68b62a9ee4 device: fix bug in hidpp20 get host names 2024-02-21 16:04:32 -05:00
Peter F. Patel-Schneider af7806ed00 device: fix typo 2024-02-21 16:04:32 -05:00
Matthias Hagmann 04e709b00a Remove yapf exclusions
Related #2295
2024-02-20 15:41:10 -05:00
Matthias Hagmann eb937fcc3a Manually fix linter issues
Related #2295
2024-02-20 15:41:10 -05:00
Matthias Hagmann 7774569971 Apply ruff format
Run ruff auto formatting using:
ruff format .

Related #2295
2024-02-20 15:41:10 -05:00
Matthias Hagmann 35f63edcd8 Makefile: Add command for formatting and linting
Format code:
make format

Lint code (automatically fixing issues when possible):
make lint

Related #2295
2024-02-20 15:41:10 -05:00
Matthias Hagmann fb6285606d Introduce ruff formatter and linter
Replace yapf, isort and flake8 with much faster ruff formatter. Remove
conflicting rule and switch to double quotes for strings.

Install:
pip install ."[dev]"
pre-commit install

Run pre-commit hooks:
pre-commit run -a

Related #2295
2024-02-20 15:41:10 -05:00
Peter F. Patel-Schneider ce00a78e7f rules: fix bug in Set action 2024-02-20 11:16:40 -05:00
Peter F. Patel-Schneider 3f692c0fe2 device: add notify module to logitech_receiver 2024-02-20 08:35:19 -05:00
Peter F. Patel-Schneider 6f633efac5 ui: implement setting_changed callback and pass in to new devices and receivers 2024-02-20 06:19:23 -05:00
Peter F. Patel-Schneider ed248c62b9 device: add callback to call when changing a setting 2024-02-20 06:19:23 -05:00
Peter F. Patel-Schneider 476f41f8ae logitech_receiver: style fixes 2024-02-20 05:58:33 -05:00
Matthias Hagmann 5f487dd3b2 logitech_receiver: Move hidpp20 constants into new module
Related #1097
2024-02-20 05:58:33 -05:00
Matthias Hagmann 2fcab65486 logitech_receiver: Move hidpp10 constants into new module
Related #1097
2024-02-20 05:58:33 -05:00
Matthias Hagmann e8fdbeee8e logitech_receiver: Move exceptions into own module
Related #1097
2024-02-20 05:58:33 -05:00
Peter F. Patel-Schneider fa9494435b device: streamline status code 2024-02-19 09:18:08 -05:00
Peter F. Patel-Schneider 50ddb54466 hidapi: upgrade debugging in udev 2024-02-19 09:16:56 -05:00
MattHag ad110498a6
dist: Fix deprecated GitHub actions
* Show pytest coverage in GitHub CI tests

Related #1097

* Extend Makefile with installation and test targets

Refactor setup steps to unify commands between Linux and macOS.
Move bash commands into Makefile for consistency and enable local
execution of GitHub CI commands corresponding Makefile targets.

Install on Ubuntu:
make install_ubuntu

Install on Ubuntu for development:
make install_ubuntu PIP_ARGS=."[test]"

Fixes #2303

* Improve name of GitHub test actions

Related #2303

* Upgrade GitHub actions to Node.js 20

Replaces deprecated Node.js 16 actions.

Related #2256, #2284
2024-02-18 08:30:31 -05:00
MattHag 9617cb88df
dist: extend makefile and tests
* Show pytest coverage in GitHub CI tests

Related #1097

* Extend Makefile with installation and test targets

Refactor setup steps to unify commands between Linux and macOS.
Move bash commands into Makefile for consistency and enable local
execution of GitHub CI commands corresponding Makefile targets.

Install on Ubuntu:
make install_ubuntu

Install on Ubuntu for development:
make install_ubuntu PIP_ARGS=."[test]"

Fixes #2303

* Improve name of GitHub test actions

Related #2303
2024-02-18 08:29:29 -05:00
Peter F. Patel-Schneider 20a76fb4d3 device: improve features array 2024-02-18 08:21:09 -05:00
Peter F. Patel-Schneider ab9e06829a ui: move ui_async to common.py 2024-02-18 08:09:34 -05:00
MattHag afdfcb0d2c
tests: Show pytest coverage in GitHub CI tests
Related #1097
2024-02-18 07:40:09 -05:00
Peter F. Patel-Schneider 12de240949 device: improve imports in logitech_receiver
device: move imports of ui modules to beginning of files

logitech_receiver: remove imports from __init__.py
2024-02-18 06:21:35 -05:00
Peter F. Patel-Schneider d1c899d6da solaar: improve imports and guard Gtk, etc imports with correct version
solaar: move imports to top of files

solaar: move more imports to top of files

solaar: guard Gtk, etc imports with correct version
2024-02-18 06:21:35 -05:00
Peter F. Patel-Schneider 17e6463950 ui: improve imports in ui
ui: move imports in about.py to top of file

ui: move imports to top of notify.py

ui: move imports to top of window.py

ui: reorder imports at beginning of __init__.py

ui: move imports to top of tray.py

ui: move common code out of __init__.py to common.py

ui: move imports to top of __init___.py
2024-02-18 06:21:35 -05:00
Peter F. Patel-Schneider ad6e3dc80e cli: move imports in __init__.py to top of file 2024-02-18 06:21:35 -05:00
Peter F. Patel-Schneider 31d795fcb8 device: improve imports in logitech_receiver
device: move some imports to top of modules

device: break up imports loop with device descriptors

device: break up imports loop by moving a function from notifications.py to setting_templates.py

device: break import loop between device.py and diversion.py by using device to access method
2024-02-18 06:21:35 -05:00
MattHag 008d3df50b
tests: Add tests of common module
Introduces unit tests for Solaar.

Related #1097
2024-02-18 06:10:53 -05:00
Peter F. Patel-Schneider 47f94a6a79 release 1.1.11 2024-02-18 05:59:47 -05:00
proletarius101 3dcc1eb800
dist: Add the <developer/> tag in the metainfo
Flathub requires this tag: https://docs.flathub.org/docs/for-app-authors/metainfo-guidelines/#name-summary-and-developer-name.

The format of this tag is defined in https://www.freedesktop.org/software/appstream/docs/chap-Metadata.html#tag-developer.
2024-02-18 05:49:49 -05:00
Peter F. Patel-Schneider a3ff536c90 dist: correctly find light icons 2024-02-15 10:42:26 -05:00
Peter F. Patel-Schneider 8dcb85ddb7 release 1.1.11rc4 2024-02-15 08:59:32 -05:00
Peter F. Patel-Schneider 8facd0cf68 dist: rename light icons and install them in correct place 2024-02-15 08:51:36 -05:00
MattHag e6191296e0
macos: Remove dbus from macos dependencies
Related #2284
2024-02-14 19:27:06 -05:00
MattHag b516b12920
Setup macOS tests using GitHub action (#2284)
Related #1244
2024-02-14 13:40:25 -05:00
Peter F. Patel-Schneider 1f954cd42e release 1.1.11rc3 2024-02-14 12:21:49 -05:00
Peter F. Patel-Schneider fb5b7e0582 ui: better checking for setting in record_setting 2024-02-13 04:01:19 -05:00
Matthaiks 745374e221
po: Update Polish translation (#2275) 2024-02-13 03:29:26 -05:00
Matthias Hagmann ca24a93005 Fix invalid func name set logo name
Related #2254, #2276
2024-02-13 03:28:51 -05:00
179 changed files with 45150 additions and 28664 deletions

22
.coveragerc Normal file
View File

@ -0,0 +1,22 @@
[run]
branch = True
source =
hid_parser
hidapi
keysyms
logitech_receiver
solaar
omit =
*/tests/*
*/setup.py
*/__main__.py
[report]
exclude_lines =
pragma: no cover
if __name__ == '__main__':
if typing.TYPE_CHECKING
fail_under = 40

View File

@ -7,10 +7,10 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Set up Python - name: Set up Python
uses: actions/setup-python@v4.3.0 uses: actions/setup-python@v5
- name: Run pre-commit - name: Run pre-commit
uses: pre-commit/action@v3.0.0 uses: pre-commit/action@v3.0.0

52
.github/workflows/gh-pages.yml vendored Normal file
View File

@ -0,0 +1,52 @@
name: Deploy to GitHub Pages
on:
push:
branches:
- master
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: 'pages'
cancel-in-progress: false
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Install dependencies
run: |
pip install mkdocs mkdocs-rtd-dropdown mkdocs-mermaid2-plugin mkdocstrings[python]
- name: Build and deploy
run: |
mkdocs build
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: 'site'
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: build
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4

View File

@ -3,31 +3,88 @@ name: tests
on: [push, pull_request] on: [push, pull_request]
jobs: jobs:
build: ubuntu-tests:
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy: strategy:
matrix: matrix:
python-version: [3.7, 3.12] python-version: [3.8, 3.13]
fail-fast: false
steps: steps:
- uses: actions/checkout@v3 - name: Checkout
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }} - name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4.3.0 uses: actions/setup-python@v5
with: with:
python-version: ${{ matrix.python-version }} python-version: ${{ matrix.python-version }}
- name: Install Ubuntu dependencies - name: Install Ubuntu dependencies for python 3.8
if: matrix.python-version == '3.8'
run: | run: |
sudo apt update make install_apt
sudo apt install libdbus-1-dev libglib2.0-dev
- name: Install Ubuntu dependencies for python 3.13
if: matrix.python-version == '3.13'
run: |
make install_apt_python3.13
- name: Install Python dependencies - name: Install Python dependencies
run: | run: |
python -m pip install --upgrade pip make install_pip PIP_ARGS='.["test"]'
pip install -e .[test]
- name: Run tests - name: Run tests on Ubuntu
run: | run: |
pytest make test
- name: Upload coverage to Codecov
if: github.ref == 'refs/heads/master'
uses: codecov/codecov-action@v4.5.0
with:
directory: ./coverage/reports/
env_vars: OS, PYTHON
files: ./coverage.xml
flags: unittests
name: codecov-umbrella
token: ${{ secrets.CODECOV_TOKEN }}
macos-tests:
runs-on: macos-latest
strategy:
matrix:
python-version: [3.8, 3.13]
fail-fast: false
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Set up macOS dependencies
run: |
make install_brew
- name: Add Homebrew's library directory to dyld search path
run: |
echo "DYLD_FALLBACK_LIBRARY_PATH=$(brew --prefix)/lib:$DYLD_FALLBACK_LIBRARY_PATH" >> $GITHUB_ENV
- name: Install Python dependencies
run: |
make install_pip PIP_ARGS='.["test"]'
- name: Run tests on macOS
run: |
pytest --cov --cov-report=xml
- name: Upload coverage to Codecov
if: github.ref == 'refs/heads/master'
uses: codecov/codecov-action@v4.5.0
with:
directory: ./coverage/reports/
env_vars: OS, PYTHON
files: ./coverage.xml
flags: unittests
name: codecov-umbrella
token: ${{ secrets.CODECOV_TOKEN }}

11
.gitignore vendored
View File

@ -13,8 +13,19 @@ __pycache__/
/deb_dist/ /deb_dist/
/MANIFEST /MANIFEST
.coverage
/htmlcov/
/docs/captures/ /docs/captures/
/share/logitech_icons/ /share/logitech_icons/
/share/locale/ /share/locale/
/po/*.po~ /po/*.po~
/.idea/
.DS_Store
._*
Pipfile
Pipfile.lock

View File

@ -8,19 +8,13 @@ repos:
- id: check-yaml - id: check-yaml
- id: check-toml - id: check-toml
- id: debug-statements - id: debug-statements
- id: double-quote-string-fixer
- id: end-of-file-fixer - id: end-of-file-fixer
- id: trailing-whitespace - id: trailing-whitespace
- repo: https://github.com/pre-commit/mirrors-yapf - repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.32.0 rev: v0.2.2
hooks: hooks:
- id: yapf - id: ruff
- repo: https://github.com/pre-commit/mirrors-isort name: ruff lint
rev: v5.10.1 args: [--fix, --exit-non-zero-on-fix]
hooks: - id: ruff-format
- id: isort name: ruff format
- repo: https://github.com/PyCQA/flake8
rev: 6.0.0
hooks:
- id: flake8
additional_dependencies: ['flake8-bugbear']

View File

@ -1,5 +1,248 @@
# 1.1.11rc2 # 1.1.15rc1
* Center labels and remove buggy entry resizing logic
* Add shape keys from Key POP Icon
* Device and Action rule conditions match on codename and name
* Fix listing hidpp10 devices - bytes vs string concatenation (#2856)
* Add present flag, unset when internal error occurs, set when notification appears
* Pause setting up features when error occurs; use ADC message to signal connection and disconnection
* Fix listing of hidpp10 peripherals
* Complete DEVICE_FEATURES to DeviceFeature transition for hidpp10 devices
* Fix NOTIFICATION_FLAG to NotificationFlag transition leftovers
* Fix github workflow stopping all matrix jobs when one of them fails
* Fix ubuntu github CI
* Update index.md
* Python documentation appears to be broken so don't set it up
* Improve documentation on onboard profiles
* Use correct LOD values for extended adjustable dpi
* Better support RGB Effects - not readable
* Fix crash when asking for help about config
* Fix error when updating ChoiceControlBig box
* Add uninstallation docs
* Handle unknown power switch locations again
* Correctly handle selection of [empty] in rule editor
* Handle `HIDError` in `hidapi.hidapi_impl._match()` (#2804)
* Give ghost devices a path
* Guard against typeerror when setting the value of a control box
* Recover from errors in ping
* Replace spaces by underscores when looking up features
* Rewrote string concatenation/format with f strings
* Fix logo not showing in about dialog box
* Make typing-extensions dependency mandatory
* Properly ignore unsupported locale
* hidapi: skip unsupported devices and handle exception on open
* Ignore macOS junk files and pipenv config
* Fix ui desktop notifications test
* hidpp20: Remove dependency to NamedInts
* Estimate accurate battery level for some rechargable devices (#2745)
* Upgrade desktop notifications tests to take notifications availability into account
* Update tests to run on Python 3.13
* Remove outdated logger enabled checks
* Introduce GTK signal types
* Introduce error types
* Remove alias for SupportedFeature
* Refactor process_device_notification
* Refactor process_receiver_notification
* Refactor receiver event handling
* Introduce custom logger
* Refactor notifications
* Rename variable to full name notification
* Test notifications
* Test extraction of serial and max. devices
* Refactor extraction of serial and max. devices
* macOS: Fix int.from_bytes, int.to_bytes for show.py
* macOS: Remove udev rule warning
* macOS: Add support for Bluetooth devices
* Add back and forward mouseclick actions
* Speedup lookup of known receivers
* Refactor device filtering
* Reorder private functions and variable definitions
* Turn filter_products_of_interest into a public function
* Improve tests of known receivers
* Refactor: Remove NamedInts and move enums where used
* Add docstrings and type hints
* Enforce rules on RuleComponentUI subclasses
* Simplify settings UI class
* Remove diversion alias
* Refactor: Convert Kind to IntEnum
* Split up huge settings module
* Remove Python 2 specific path handling
* Delete logging temp file on exit
* Update Swedish translation
# 1.1.14
* Handle fake feature enums in show
* Fix battery entries in config.yaml
* Add ratchet setting for smart shift enhanced devices
* Refactor Gesture into enum
* Replace ERROR NamedInts by IntEnum (#2645)
* Refactor hidpp20 to use enum
* Update Polish, Swedish, Norwegian Nynorsk (nn), and Norwegian Bokmål (nb) translations
* Use IntEnum for firmware and cidgroup constances
* Change pairing error values to intenums
* Fix initialization bug for PackedRangeControl
* Add tests for feature class, process_notification, and key_is_down
* Check all bits for extended report rate
* Add type hints
* Improve about dialog
* Reduce dependencies
* Refactor code
* Improve testing
* Allow unknown keys in Key rule conditions
* Improve documentation for cli actions
* Cycle sw_id to better guard against duplication of messages
* Handle error return on root feature
* Clean up documentation
* Improve github interactions
* Add information about Onboard Profiles overriding some settings
* Add wording to README.md that Solaar is not a device driver
* Clean up imports
* Handle unknown device kinds
* Fix broken links to Solaar logo
* Use mkdocs for public documentation
* Clean up setup.py
* Remove Dead links in the AppStream file
* Update about.py
* Remove check on driver
* Improve base module
* Remove unnecessary receiver info 'hid_driver'
* Convert HIDPPNotification to dataclass
* Be defensive when converting battery status to string
* Automatically detect packages in /lib
* Clean up locale code
* Improve rules documentation
* Refactor creation of devices
* Add headings to structure rules.md
* Unify imports in logitech package
* Don't ping device when getting name or codename
* Use dataclasses and enums where useful
* Introduce Device protocol and type hints
* Add typing_extensions dependency
* Move hidpp10 independent functions to module level
* Fix macOS compatibility and reenable CI tests
* Unify imports in hidapi package
* Move screenshots into dedicated folder and add high-level graph of components
* Update French and Chinese translations
* Drop support for end-of-life Python 3.7
# 1.1.13
* Update Polish and Russian translations.
* Fix bug in suspend and resume callback
* Add choices universe for backlight setting
* Add simplify diversion.py and add unit tests
* Get and use current host number for K375sFnSwap because of bug in firmware of MX Keys S
* Fix bug with logo in about window
* Don't ping device just to get logging information
* Optimize write for per-key lighting
* Add and initialize per-key lighting to a special no-change value
* Remove some Python 2 compatibility code
* Update French translation
* Refactor rule loading for testability
# 1.1.12
* Check for existence of keys file before opening
* Perform translation for all translatable strings.
* Add included hid_parser to packages installed
* Improve label and description for LED zone settings
* Add message about Onboard Profiles to LED Zone settings
* Initialize device registers to empty list
* Use bluez dbus signals to disconnect and connect bluetooth devices
* Handle a different signal for onboard profiles directory in ROM
* Introduce small delay in getting pairing information to let receiver settle after pairing
* Improve testing for settings_templates, settings, hidpp20, and device and fix small bugs found
* Add extended adjustable DPI setting
* Improve and extend infrastructure for testing setting_templates
* Update Greek, Polish, Russian, and Traditional Chinese translations
* Implement and test per-key lighting
* Refactor and test pair_window in GUI
* Handle situation when read of a setting fails in GUI
* Permit continuing when a read during pushing fails
* Fix bug in LEDZoneSetting when effect is not implemented
* Add tests for LEDEffect structures in hidpp20
* Handle BRIGHTNESS_CONTROL notifications
* Add settings for BRIGHTNESS_CONTROL and RGB_EFFECTS features
* Fix small bugs found from testing in settings
* Use f-strings for more exceptions and log message
* Tests for setting_templates
* Simple change in settings to improve testability
* Use feature_request from the device everywhere in hidpp20
* Fix bug in backlight 2 durations
* Replace deprecated code constructs
* Set up test data and classes to help test HID++ interactions
* Use pytest to test code for logitech_receiver modules
* Align init methods for all receiver classes
* Start refactoring of code base
* Allow sub-second delays in Later
* Fix bug in setting configuration cookie due to bad documentation
* Use ruff for code styling and linting
* Upgrade string formating to f-string
* Document battery-icons=solaar option
* Tell devices to delay device sending first messages until configuration is done
* Optimize some functions in FeaturesArray
* Fix bug in creating features array
* Fix bug in building battery line in show
* Refactor diversion_rules
* Fix bug in determining tray icon
* Fix bug in getting friendly name
* Move status information to Device and Receiver objects
* Add tests for get_kind_from_index and base product information
* Update EX100 documentation
* Use object attributes instead of dictionary in status objects
* Create subclasses of receiver for different variants
* Add requirement for CONFIG_HIDRAW to documentation
* Add some low-level tests for some hidpp20 functions, profiles, and lighting and some hidpp10 tests
* Fix app name casing in UI
* Add missing receiver type for Lightspeed receivers
* Add new device types
* Refactor device and receiver instantiation
* Simplify naming of distribution files
* Clean up some logging code
* Remove duplicated code to read register
* Introduce Hidpp20 and Hidpp10 class
* Remove unnecessary calls of del
* Fix bug when reading BACKLIGHT setting from device
* Replace invalid hidpp10 and hidpp20 usages
* Use only timer thread to save config.yaml
* Improve README
* Copy newer version of hid_parser
* Reorder code in settings
* Update installation documentation
* Add missing license blocks
* Clean up listener and notifications code
* Add locks to prevent multiple persisters for device
* Clean up configuration, device, and receiver code
* Move battery constants common to HID++ 1.0 and 2.0 to common
* Move mapping of device kind into hidpp20
* Move pairing information gathering to receiver
* update contributors
* Expand allowable profile numbers
* Clean up __init__ in logitech_receiver
* Modify pre-commit args to make ruff change files
* Fix bug in hidpp20 get host names
* Use ruff for formatting and linting
* Fix bug in rule Set action
* Add notify module to logitech_receiver
* Implement setting_changed callback and pass in to new devices and receivers
* Add callback to call when changing a setting
* Move exceptions, hidpp20 and hidpp10 constants into new modules
* Streamline status code
* Upgrade debugging in udev
* Fix deprecated GitHub actions
* Extend makefile and tests
* Improve features array
* Move ui_async to common.py
* Improve module imports
* Add tests of common module
# 1.1.11
* Rename light icons and install them in correct place
* Setup macOS tests using GitHub action (#2284)
* Better checking for setting in record_setting
* Fix invalid func name set logo name
* Simplify installation of udev rules * Simplify installation of udev rules
* Add document on implementation * Add document on implementation
* Tidy up scrolling appearance in configuration panel * Tidy up scrolling appearance in configuration panel

View File

@ -1,3 +1,3 @@
include COPYRIGHT COPYING README.md ChangeLog.md lib/solaar/version lib/solaar/commit include COPYRIGHT LICENSE.txt README.md CHANGELOG.md lib/solaar/version lib/solaar/commit
recursive-include rules.d * recursive-include rules.d *
recursive-include share/locale * recursive-include share/locale *

View File

@ -3,19 +3,72 @@ UDEV_RULES_SOURCE := rules.d/$(UDEV_RULE_FILE)
UDEV_RULES_SOURCE_UINPUT := rules.d-uinput/$(UDEV_RULE_FILE) UDEV_RULES_SOURCE_UINPUT := rules.d-uinput/$(UDEV_RULE_FILE)
UDEV_RULES_DEST := /etc/udev/rules.d/ UDEV_RULES_DEST := /etc/udev/rules.d/
.PHONY: install_udev install_udev_uinput uninstall_udev PIP_ARGS ?= .
.PHONY: install_ubuntu install_macos
.PHONY: install_apt install_brew install_pip
.PHONY: install_udev install_udev_uinput reload_udev uninstall_udev
.PHONY: format lint test
install_ubuntu: install_apt install_udev_uinput install_pip
install_macos: install_brew install_pip
install_apt:
@echo "Installing Solaar dependencies via apt"
sudo apt update
sudo apt install libdbus-1-dev libglib2.0-dev libgtk-3-dev libgirepository1.0-dev
install_apt_python3.13:
@echo "Installing Solaar dependencies via apt"
sudo apt update
sudo apt install libdbus-1-dev libglib2.0-dev libgtk-3-dev libgirepository-2.0-dev gobject-introspection
install_dnf:
@echo "Installing Solaar dependencies via dn"
sudo dnf install gtk3 python3-gobject python3-dbus python3-pyudev python3-psutil python3-xlib python3-yaml
install_brew:
@echo "Installing Solaar dependencies via brew"
brew update
brew install hidapi gtk+3 pygobject3 gobject-introspection
install_pip:
@echo "Installing Solaar via pip"
python -m pip install --upgrade pip
pip install $(PIP_ARGS)
install_pipx:
@echo "Installing Solaar via pipx"
pipx install --system-site-packages $(PIP_ARGS)
install_udev: install_udev:
@echo "Copying Solaar udev rule to $(UDEV_RULES_DEST)" @echo "Copying Solaar udev rule to $(UDEV_RULES_DEST)"
sudo cp $(UDEV_RULES_SOURCE) $(UDEV_RULES_DEST) sudo cp $(UDEV_RULES_SOURCE) $(UDEV_RULES_DEST)
sudo udevadm control --reload-rules make reload_udev
install_udev_uinput: install_udev_uinput:
@echo "Copying Solaar udev rule (uinput) to $(UDEV_RULES_DEST)" @echo "Copying Solaar udev rule (uinput) to $(UDEV_RULES_DEST)"
sudo cp $(UDEV_RULES_SOURCE_UINPUT) $(UDEV_RULES_DEST) sudo cp $(UDEV_RULES_SOURCE_UINPUT) $(UDEV_RULES_DEST)
make reload_udev
reload_udev:
@echo "Reloading udev rules"
sudo udevadm control --reload-rules sudo udevadm control --reload-rules
uninstall_udev: uninstall_udev:
@echo "Removing Solaar udev rules from $(UDEV_RULES_DEST)" @echo "Removing Solaar udev rules from $(UDEV_RULES_DEST)"
sudo rm -f $(UDEV_RULES_DEST)/$(UDEV_RULE_FILE) sudo rm -f $(UDEV_RULES_DEST)/$(UDEV_RULE_FILE)
sudo udevadm control --reload-rules make reload_udev
format:
@echo "Formatting Solaar code"
ruff format .
lint:
@echo "Linting Solaar code"
ruff check . --fix
test:
@echo "Running Solaar tests"
pytest --cov --cov-report=xml

View File

@ -1 +0,0 @@
docs/index.md

67
README.md Normal file
View File

@ -0,0 +1,67 @@
# <img src="https://pwr-solaar.github.io/Solaar/img/solaar.svg" width="60px"/> Solaar
Solaar is a Linux manager for many Logitech keyboards, mice, and other devices
that connect wirelessly to a Unifying, Bolt, Lightspeed or Nano receiver
as well as many Logitech devices that connect via a USB cable or Bluetooth.
Solaar is not a device driver and responds only to special messages from devices
that are otherwise ignored by the Linux input system.
<a href="https://pwr-solaar.github.io/Solaar/index">More Information</a> -
<a href="https://pwr-solaar.github.io/Solaar/usage">Usage</a> -
<a href="https://pwr-solaar.github.io/Solaar/capabilities">Capabilities</a> -
<a href="https://pwr-solaar.github.io/Solaar/rules">Rules</a> -
<a href="https://pwr-solaar.github.io/Solaar/installation">Manual Installation</a>
[![codecov](https://codecov.io/gh/pwr-Solaar/Solaar/graph/badge.svg?token=D7YWFEWID6)](https://codecov.io/gh/pwr-Solaar/Solaar)
[![License: GPL v2](https://img.shields.io/badge/License-GPL%20v2+-blue.svg)](../LICENSE.txt)
<p align="center">
<img src="https://pwr-solaar.github.io/Solaar/screenshots/Solaar-main-window-multiple.png" width="54%"/>
&#160;
<img src="https://pwr-solaar.github.io/Solaar/screenshots/Solaar-main-window-receiver.png" width="43%"/>
</p>
<p align="center">
<img src="https://pwr-solaar.github.io/Solaar/screenshots/Solaar-main-window-back-divert.png" width="49%"/>
&#160;
<img src="https://pwr-solaar.github.io/Solaar/screenshots/Solaar-rule-editor.png" width="48%"/>
</p>
Solaar supports:
- pairing/unpairing of devices with receivers
- configuring device settings
- custom button configuration
- running rules in response to special messages from devices
For more information see
<a href="https://pwr-solaar.github.io/Solaar/index">the main Solaar documentation page.</a> -
## Installation Packages
Up-to-date prebuilt packages are available for some Linux distros
(e.g., Fedora) in their standard repositories.
If a recent version of Solaar is not
available from the standard repositories for your distribution, you can try
one of these packages:
- Arch solaar package in the [extra repository][arch]
- Ubuntu/Kubuntu package in [Solaar stable ppa][ppa stable]
- NixOS Flake package in [Svenum/Solaar-Flake][nix flake]
Solaar is available from some other repositories
but may be several versions behind the current version:
- a [Debian package][debian], courtesy of Stephen Kitt
- a Ubuntu package is available from [universe repository][ubuntu universe repository]
- a [Gentoo package][gentoo], courtesy of Carlos Silva and Tim Harder
- a [Mageia package][mageia], courtesy of David Geiger
[ppa stable]: https://launchpad.net/~solaar-unifying/+archive/ubuntu/stable
[arch]: https://www.archlinux.org/packages/extra/any/solaar/
[gentoo]: https://packages.gentoo.org/packages/app-misc/solaar
[mageia]: http://mageia.madb.org/package/show/release/cauldron/application/0/name/solaar
[ubuntu universe repository]: http://packages.ubuntu.com/search?keywords=solaar&searchon=names&suite=all&section=all
[nix flake]: https://github.com/Svenum/Solaar-Flake
[debian]: https://packages.debian.org/search?keywords=solaar&searchon=names&suite=all&section=all

View File

@ -8,7 +8,7 @@ candidates (ex. `1.0.0rc1`). Release candidates must have a `rcX` suffix.
Release routine: Release routine:
- Update version in `lib/solaar/version` - Update version in `lib/solaar/version`
- Add release changes to `ChangeLog.md` - Add release changes to `CHANGELOG.md`
- Add release information to `share/solaar/io.github.pwr_solaar.solaar.metainfo.xml` - Add release information to `share/solaar/io.github.pwr_solaar.solaar.metainfo.xml`
- Create a commit that starts with `release VERSION` - Create a commit that starts with `release VERSION`
- Push commit to Solaar repository - Push commit to Solaar repository

View File

@ -1,6 +1,33 @@
# Notes on Major Changes in Releases # Notes on Major Changes in Releases
## Version 1.1.11rc2 ## Version 1.1.15
* Device and Action rule conditions match on device codename and name
* Solaar supports configuration of Bluetooth devices on macOS.
## Version 1.1.13
* Solaar will drop support for Python 3.7 immediately after version 1.1.13.
* Version 1.1.12 does not push settings to many devices after a resume resulting in the device reverting to its default behaviour. This is fixed in 1.1.13.
## Version 1.1.12
* Solaar now processes DBus disconnection and connection messages from Bluez and re-initializes devices when they reconnect, to handle to a change introduced in Bluez 5.73. The HID++ driver does not re-initialize devices, which causes problems with smooth scrolling. Until the issue is resolved having Scroll Wheel Resolution set to true (and not ignored) may be helpful.
* The credits for translations have not been kept up to date. Translators who are not listed can update docs/i18n.ml and lib/solaar/ui/about.py.
* Solaar now has settings for features BRIGHTNESS_CONTROL, RGB_EFFECTS, and PER_KEY_LIGHTING features. The names of keys in the Per-key Lighting setting are for the standard US keyboard. Users who wish to modify these names should look at the section Keyboard Key Names and Locations in `https://pwr-solaar.github.io/Solaar/capabilities`
* A unit test test suite is being constructed using pytest.
* The Solaar code for communicating with receivers and devices has been significantly modified to improve testability and organization. Errors may have been introduced for uncommon hardware.
* The Later rule action uses precision timing for delays of less than one second.
* Solaar now indentifies supported devices by whether they support the HID protocols that Solaar needs. If a device does not show up at all when running Solaar, it almost certainly cannot be supported by Solaar.
## Version 1.1.11
* Solaar can dump device profiles in YAMLfor devices that support profiles and load profiles back from an edited file. See [the capabilities page](https://pwr-solaar.github.io/Solaar/capabilities) for more information. * Solaar can dump device profiles in YAMLfor devices that support profiles and load profiles back from an edited file. See [the capabilities page](https://pwr-solaar.github.io/Solaar/capabilities) for more information.

View File

@ -21,35 +21,22 @@
def init_paths(): def init_paths():
"""Make the app work in the source tree.""" """Make the app work in the source tree."""
import os.path as _path import os.path
import sys import sys
# Python 2 need conversion from utf-8 filenames root = os.path.join(os.path.realpath(sys.path[0]), "..")
# Python 3 might have problems converting back to UTF-8 in case of Unicode surrogates prefix = os.path.normpath(root)
try: src_lib = os.path.join(prefix, "lib")
decoded_path = sys.path[0] share_lib = os.path.join(prefix, "share", "solaar", "lib")
sys.path[0].encode(sys.getfilesystemencoding())
except UnicodeError:
sys.stderr.write(
'ERROR: Solaar cannot recognize encoding of filesystem path, '
'this may happen because non UTF-8 characters in the pathname.\n'
)
sys.exit(1)
prefix = _path.normpath(_path.join(_path.realpath(decoded_path), '..'))
src_lib = _path.join(prefix, 'lib')
share_lib = _path.join(prefix, 'share', 'solaar', 'lib')
for location in src_lib, share_lib: for location in src_lib, share_lib:
init_py = _path.join(location, 'solaar', '__init__.py') init_py = os.path.join(location, "solaar", "__init__.py")
# print ("sys.path[0]: checking", init_py) if os.path.exists(init_py):
if _path.exists(init_py):
# print ("sys.path[0]: found", location, "replacing", sys.path[0])
sys.path[0] = location sys.path[0] = location
break break
if __name__ == '__main__': if __name__ == "__main__":
init_paths() init_paths()
import solaar.gtk import solaar.gtk
solaar.gtk.main() solaar.gtk.main()

View File

@ -1,9 +0,0 @@
title: Solaar
description: Linux Device Manager for Logitech Unifying Receivers and Devices.
tagline: Linux Device Manager for Logitech Unifying Receivers and Devices.
owner: pwr-Solaar
owner_url: https://github.com/pwr-Solaar
repository: pwr-Solaar/Solaar
show_downloads: false
encoding: utf-8
theme: jekyll-theme-slate

View File

@ -1,53 +0,0 @@
<!DOCTYPE html>
<html lang="{{ site.lang | default: "en-US" }}">
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,maximum-scale=2">
<link rel="stylesheet" type="text/css" media="screen" href="{{ '/assets/css/style.css?v=' | append: site.github.build_revision | relative_url }}">
<link rel="icon" type="image/png" href="{{ site.baseurl }}/assets/favicon.png" />
{% seo %}
</head>
<body>
<!-- HEADER -->
<div id="header_wrap" class="outer">
<header class="inner">
{% if site.github.is_project_page %}
<a id="forkme_banner" href="{{ site.github.repository_url }}">View on GitHub</a>
{% endif %}
<h1 id="project_title">
<img src="{{ site.baseurl }}/assets/solaar.svg" style="margin-bottom: -10px; width: 48px; height: 48px; border: 0; box-shadow: none;" />
{{ site.title | default: site.github.repository_name }}</h1>
<h2 id="project_tagline">{{ site.description | default: site.github.project_tagline }}</h2>
{% if site.show_downloads %}
<section id="downloads">
<a class="zip_download_link" href="{{ site.github.zip_url }}">Download this project as a .zip file</a>
<a class="tar_download_link" href="{{ site.github.tar_url }}">Download this project as a tar.gz file</a>
</section>
{% endif %}
</header>
</div>
<!-- MAIN CONTENT -->
<div id="main_content_wrap" class="outer">
<section id="main_content" class="inner">
{{ content }}
</section>
</div>
<!-- FOOTER -->
<div id="footer_wrap" class="outer">
<footer class="inner">
{% if site.github.is_project_page %}
<p class="copyright">{{ site.title | default: site.github.repository_name }} maintained by <a href="{{ site.github.owner_url }}">{{ site.github.owner_name }}</a></p>
{% endif %}
<p>Published with <a href="https://pages.github.com">GitHub Pages</a></p>
</footer>
</div>
</body>
</html>

View File

@ -1,47 +0,0 @@
<!DOCTYPE html>
<html lang="{{ site.lang | default: "en-US" }}">
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,maximum-scale=2">
<link rel="stylesheet" type="text/css" media="screen" href="{{ '/assets/css/style.css?v=' | append: site.github.build_revision | relative_url }}">
<link rel="icon" type="image/png" href="{{ site.baseurl }}/assets/favicon.png" />
{% seo %}
</head>
<body>
<!-- HEADER -->
<div id="header_wrap" class="outer">
<header class="inner">
{% if site.github.is_project_page %}
<a id="forkme_banner" href="{{ site.github.repository_url }}">View on GitHub</a>
{% endif %}
<h1 id="project_title">
<a href="{{ site.baseurl }}" style="color: #fff;">
<img src="{{ site.baseurl }}/assets/solaar.svg" style="margin-bottom: -10px; width: 48px; height: 48px; border: 0; box-shadow: none;" />
{{ site.title | default: site.github.repository_name }}</h1>
</a>
</header>
</div>
<!-- MAIN CONTENT -->
<div id="main_content_wrap" class="outer">
<section id="main_content" class="inner">
{{ content }}
</section>
</div>
<!-- FOOTER -->
<div id="footer_wrap" class="outer">
<footer class="inner">
{% if site.github.is_project_page %}
<p class="copyright">{{ site.title | default: site.github.repository_name }} maintained by <a href="{{ site.github.owner_url }}">{{ site.github.owner_name }}</a></p>
{% endif %}
<p>Published with <a href="https://pages.github.com">GitHub Pages</a></p>
</footer>
</div>
</body>
</html>

View File

@ -51,7 +51,7 @@ connect via a USB cable or via bluetooth can be determined by their USB or
Bluetooth product ID. Bluetooth product ID.
# Pairing and Unpairing ## Pairing and Unpairing
Solaar is able to pair and unpair devices with Solaar is able to pair and unpair devices with
receivers as supported by the device and receiver. receivers as supported by the device and receiver.
@ -80,7 +80,7 @@ that they were bought with.
## Device Settings ## Device Settings
Solaar can display quite a few changeable settings of receivers and devices. Solaar can display quite a few changeable settings of receivers and devices.
For a list of HID++ features and their support see [the features page](features). For a list of HID++ features and their support see [the features page](features.md).
Solaar does not do much beyond using the HID++ protocol to change the Solaar does not do much beyond using the HID++ protocol to change the
behavior of receivers and devices via changing their settings. behavior of receivers and devices via changing their settings.
@ -174,13 +174,25 @@ is sent to the Solaar rule system so that rules can detect these notifications.
For more information on Mouse Gestures rule conditions see For more information on Mouse Gestures rule conditions see
[the rules page](https://pwr-solaar.github.io/Solaar/rules). [the rules page](https://pwr-solaar.github.io/Solaar/rules).
### Device Profiles ### Keyboard Key Names and Locations
Some mice store one or more profiles, which control aspects of the behavior of the device. Solaar uses the standard Logitech names for keyboard keys. Some Logitech keyboards have different icons on some of their keys and have different functionality than suggested by these names.
Profiles can control the rate at which the mouse reports movement, the resolution of the the movement reports, what the mouse buttons do, and its LED effects. Solaar can dump the entire set of profiles into a YAML file can load an entire set of profiles from a file. Users can edit the file to effect changes to the profiles. Solaar has a setting that switches between profiles or disables all profiles. When switching between profiles or using a button to change resolution Solaar keeps track of the changes in the settings for these features. Solaar is uses the standard US keyboard layout. This currently only matters for the `Per-key Lighting` setting. Users who want to have the key names for this setting reflect the keyboard layout that they use can create and edit `~/.config/solaar/keys.yaml` which contains a YAML dictionary of key names and locations. For example, switching the `Y` and `Z` keys can be done as:
When profiles are active changes cannot be made to the Report Rate setting. Changes can be made to the Sensitivity setting and to LED settings. To keep the profile values make these setting ignored. Z: 25
Y: 26
This is an experimental feature and may be modified or even eliminated.
### Onboard Profiles
Some mice store one or more profiles onboard. An onboard profile controls certain aspects of the behavior of the mouse, including the rate at which the mouse reports movement, the resolution of the the movement reports, what the mouse buttons do, LED effects, and maybe more. Solaar has a setting that switches between profiles or disables all profiles.
When an onboard profile is active it may not be possible to change the aspects that the profile controls. This is often seen for the Report Rate setting. For some devices it is possible to make changes to the Sensitivity setting and to LED settings. These changes are likely to only be temporary and may be overridden when the device reconnects or when Solaar is restarted. This is in keeping with the intent of Onboard Profiles as controlling the device behavior. To make the changes to these settings permanent it is necessary to disable onboard profiles. Alternatively, multiple profiles can be set up as described below and these settings controlled by switching between the profiles.
Solaar can dump the entire set of profiles into a YAML file and can load the entire set of profiles from a file. Users can edit the file to effect changes to the profiles.
A profile file has some bookkeeping information, including profile version and the name of the device, and a sequence of profiles. A profile file has some bookkeeping information, including profile version and the name of the device, and a sequence of profiles.
@ -235,7 +247,7 @@ See USB_HID_KEYCODES and HID_CONSUMERCODES in lib/logitech_receiver/special_keys
Buttons can also execute macros but Solaar does not provide any support for macros. Buttons can also execute macros but Solaar does not provide any support for macros.
Lighting information is a sequence of lighting effects, with the first for the logo LEDs and the second for the side LEDs. Lighting information is a sequence of lighting effects, with the first usually for the logo LEDs and the second usually for the side LEDs.
The fields possible in an effect are: The fields possible in an effect are:
- ID: The kind of effect: - ID: The kind of effect:

View File

@ -11,72 +11,26 @@ Solaar supports most Logitech Nano, Unifying, and Bolt receivers.
Solaar supports some Lightspeed receivers. Solaar supports some Lightspeed receivers.
See the receiver table below for the list of currently supported receivers. See the receiver table below for the list of currently supported receivers.
Solaar supports most recent and many older Logitech devices Solaar supports all Logitech devices (keyboards, mice, trackballs, touchpads, and headsets)
(keyboards, mice, trackballs, touchpads, and headsets)
that can connect to supported receivers. that can connect to supported receivers.
Solaar supports many recent Logitech devices that can connect via a USB cable, Solaar supports all Logitech devices that can connect via a USB cable or via Bluetooth,
but some such Logitech devices are not suited for use in Solaar because they do not use the HID++ protocol. as long as the device uses the HID++ protocol.
One example is the MX518 Gaming Mouse.
Solaar supports most recent Logitech devices that can connect via Bluetooth.
The best way to determine whether Solaar supports a device is to run Solaar while the device is connected. The best way to determine whether Solaar supports a device is to run Solaar while the device is connected.
If the device is supported, it will show up in the Solaar main window. If the device is supported, it will show up in the Solaar main window.
If it is not, and there is no issue about the device in the Solaar GitHub repository,
open an enhancement issue requesting that it be supported.
The directory <https://github.com/pwr-Solaar/Solaar/tree/master/docs/devices> contains edited output The directory <https://github.com/pwr-Solaar/Solaar/tree/master/docs/devices> contains edited output
of `solaar show` on many devices and can be used to see what Solaar can do with the device. of `solaar show` on many devices and can be used to see what Solaar can do with the device.
## Adding new devices ## Supporting old devices
Most new HID++ devices do not need to be known to Solaar to work. Some old Logitech devices use an old version of HID++.
You should be able to just run Solaar and the device will show up. For Solaar to support these devices well, Solaar needs some information about them.
If your device does not show up, If you have an old Logitech device that shows up in Solaar but has no settings
either it doesn't use HID++ or the interface it uses isn't the one Solaar normally uses. and you feel that Solaar should be able to do more with the device you can
To start the process of support for a Logitech device open an enhancement issue for Solaar and open an enhancement request for Solaar to better support the device.
follow these steps:
1. Make sure the receiver or device is connected and active.
2. Look at the output of `grep -H . /sys/class/hidraw/hidraw*/device/uevent` to find
where information about the device is kept.
You are looking for a line like `/sys/class/hidraw/hidrawN/device/uevent:HID_NAME=<NAME>`
where \<NAME\> is the name of your receiver or device.
N is the current HID raw number of your receiver or device.
3. Provide the contents of the file `/sys/class/hidraw/hidrawN/device/uevent` where N was found
above.
4. Also attach the contents of the file `/sys/class/hidraw/hidrawN/device/report_descriptor`
to the enhancement request.
You will have to copy the contents to a file with txt extension before attaching it.
Or, better, install hidrd-convert and attach the output of
`hidrd-convert -o spec /sys/class/hidraw/hidrawN/device/report_descriptor`
(To install hidrd on Fedora use `sudo dnf install hidrd`.)
5. If your device or receiver connects via USB, look at the output of `lsusb`
to find the ID of the device or receiver and also provide the output of
`lsusb -vv -d xxxx:yyyy` where xxxx:yyyy is the ID of the device or receiver.
If your device can connect in multiple ways - via a receiver, via USB (not just charging via a USB cable),
via Bluetooth - do this for each way it can connect.
### Adding information about a new device to the Solaar code
The _D function in `../lib/logitech_receiver/descriptors.py` makes a device known to Solaar.
The usual arguments to the _D function are the device's long name, its short name
(codename), and its HID++ protocol version.
Devices that use HID++ 1.0 need a tuple of known registers (registers) and settings (settings).
Settings can be provided for Devices that use HID++ 2.0 or later,
but Solaar can determine these from the device.
If the device can connect to a receiver, provide its wireless product ID (wpid),
If the device can connect via Bluetooth, provide its Bluetooth product ID (btid).
If the device can connect via a USB cable, provide its USB product ID (usbid),
and the interface it uses to send and receiver HID++ messages (interface - default 2).
The use of a non-default USB interface is the main reason for requiring information about
modern devices to be added to Solaar.
## Adding new receivers ## Adding new receivers
@ -129,7 +83,7 @@ a subset of the HID++ 1.0 protocol. Only hardware pairing is supported.
## Supported Devices ## Supported Devices (Historical Interest Only)
The device tables below provide a list of some of the devices that Solaar supports, The device tables below provide a list of some of the devices that Solaar supports,
giving their product name, WPID product number, and HID++ protocol information. giving their product name, WPID product number, and HID++ protocol information.
@ -255,6 +209,7 @@ so what is important for support is the USB WPID or Bluetooth model ID.
| Device | WPID | HID++ | | Device | WPID | HID++ |
|------------------------------|------|-------| |------------------------------|------|-------|
| G604 Wireless Gaming Mouse | 4085 | 4.2 |
| PRO X Superlight Wireless | 4093 | 4.2 | | PRO X Superlight Wireless | 4093 | 4.2 |
### Trackballs (Unifying) ### Trackballs (Unifying)

View File

@ -1,11 +1,35 @@
./bin/solaar probe solaar version 1.1.11-80-gdea496f
EX100 Receiver 27 Mhz EX100 Receiver 27 Mhz
Device path : /dev/hidraw3 Device path : /dev/hidraw2
USB id : 046d:C517 USB id : 046d:C517
Serial : None Serial : None
Has 1 paired device(s) out of a maximum of 4. Has 2 paired device(s) out of a maximum of 4.
Notifications: wireless (0x000100) Notifications: wireless (0x000100)
1: Wireless Mouse EX100
Device path : /dev/hidraw3
WPID : 003F
Codename : EX100m
Kind : mouse
Protocol : HID++ 1.0
Serial number:
The power switch is located on the (unknown).
Notifications: roller V, mouse extra buttons, battery status, roller H (0x3C0000).
Battery: good, discharging.
3: Wireless Keyboard EX100
Device path : /dev/hidraw6
WPID : 0065
Codename : EX100
Kind : keyboard
Protocol : HID++ 1.0
Serial number:
The power switch is located on the (unknown).
Notifications: keyboard multimedia raw, battery status (0x110000).
Battery: good, discharging.
Register Dump Register Dump
Notifications 0x00: 0x000100 Notifications 0x00: 0x000100
Connection State 0x02: 0x000100 Connection State 0x02: 0x000100

View File

@ -1,18 +1,18 @@
Solaar version 1.1.7 solaar version 1.1.12rc1
1: G502 Gaming Mouse 1: G502 Gaming Mouse
Device path : /dev/hidraw4 Device path : /dev/hidraw20
WPID : 407F WPID : 407F
Codename : G502 Codename : G502
Kind : mouse Kind : mouse
Protocol : HID++ 4.2 Protocol : HID++ 4.2
Polling rate : 1 ms (1000Hz) Report Rate : 1ms
Serial number: 1F2DBC7E Serial number: DDDAADBC
Model ID: 407FC08D0000 Model ID: 407FC08D0000
Unit ID: 1F2DBC7E Unit ID: DDDAADBC
Bootloader: BOT 92.00.B0008 1: BOT 92.00.B0008
Firmware: MPM 17.00.B0008 0: MPM 17.00.B0008
Other: 3:
The power switch is located on the base. The power switch is located on the base.
Supports 30 HID++ 2.0 features: Supports 30 HID++ 2.0 features:
0: ROOT {0000} V0 0: ROOT {0000} V0
@ -21,28 +21,34 @@ Solaar version 1.1.7
Firmware: Bootloader BOT 92.00.B0008 AAEF21F1FA5F Firmware: Bootloader BOT 92.00.B0008 AAEF21F1FA5F
Firmware: Firmware MPM 17.00.B0008 407F21F1FA5F Firmware: Firmware MPM 17.00.B0008 407F21F1FA5F
Firmware: Other Firmware: Other
Unit ID: 1F2DBC7E Model ID: 407FC08D0000 Transport IDs: {'wpid': '407F', 'usbid': 'C08D'} Unit ID: DDDAADBC Model ID: 407FC08D0000 Transport IDs: {'wpid': '407F', 'usbid': 'C08D'}
3: DEVICE NAME {0005} V0 3: DEVICE NAME {0005} V0
Name: G502 LIGHTSPEED Wireless Gaming Mouse Name: G502 LIGHTSPEED Wireless Gaming Mouse
Kind: mouse Kind: mouse
4: WIRELESS DEVICE STATUS {1D4B} V0 4: WIRELESS DEVICE STATUS {1D4B} V0
5: RESET {0020} V0 5: CONFIG CHANGE {0020} V0
Configuration: 11000000000000000000000000000000
6: BATTERY VOLTAGE {1001} V2 6: BATTERY VOLTAGE {1001} V2
Battery: 70% 3978mV , discharging. Battery: 90% 4166mV , discharging.
7: COLOR LED EFFECTS {8070} V4 7: COLOR LED EFFECTS {8070} V4
LED Control (saved): Device
LED Control : Device
LEDs Primary (saved): !LEDEffectSetting {ID: 1, color: 16711680, intensity: 0, period: 100, ramp: 0, speed: 0}
LEDs Primary : None
LEDs Logo : None
8: LED CONTROL {1300} V0 8: LED CONTROL {1300} V0
9: ONBOARD PROFILES {8100} V0 9: ONBOARD PROFILES {8100} V0
Device Mode: On-Board Device Mode: On-Board
Onboard Profiles (saved): Enable Onboard Profiles (saved): Profile 1
Onboard Profiles : Enable Onboard Profiles : Profile 1
10: MOUSE BUTTON SPY {8110} V0 10: MOUSE BUTTON SPY {8110} V0
11: REPORT RATE {8060} V0 11: REPORT RATE {8060} V0
Polling Rate (ms): 1 Report Rate: 1ms
Polling Rate (ms) (saved): 1 Report Rate (saved): 1ms
Polling Rate (ms) : 1 Report Rate : 1ms
12: ADJUSTABLE DPI {2201} V1 12: ADJUSTABLE DPI {2201} V1
Sensitivity (DPI) (saved): 800 Sensitivity (DPI) (saved): 900
Sensitivity (DPI) : 800 Sensitivity (DPI) : 900
13: DEVICE RESET {1802} V0 internal, hidden 13: DEVICE RESET {1802} V0 internal, hidden
14: unknown:1803 {1803} V0 internal, hidden 14: unknown:1803 {1803} V0 internal, hidden
15: OOBSTATE {1805} V0 internal, hidden 15: OOBSTATE {1805} V0 internal, hidden
@ -63,12 +69,12 @@ Solaar version 1.1.7
Multiplier: 8 Multiplier: 8
Has invert: Normal wheel motion Has invert: Normal wheel motion
Has ratchet switch: Normal wheel mode Has ratchet switch: Normal wheel mode
Low resolution mode High resolution mode
HID notification HID notification
Scroll Wheel Direction (saved): False Scroll Wheel Direction (saved): False
Scroll Wheel Direction : False Scroll Wheel Direction : False
Scroll Wheel Resolution (saved): False Scroll Wheel Resolution (saved): True
Scroll Wheel Resolution : False Scroll Wheel Resolution : True
Scroll Wheel Diversion (saved): False Scroll Wheel Diversion (saved): False
Scroll Wheel Diversion : False Scroll Wheel Diversion : False
Battery: 70% 3978mV , discharging. Battery: 90% 4166mV , discharging.

View File

@ -0,0 +1,84 @@
solaar version 03cfa128
1: G604 Wireless Gaming Mouse
Device path : /dev/hidraw6
WPID : 4085
Codename : G604
Kind : mouse
Protocol : HID++ 4.2
Report Rate : 1ms
Serial number: XXXXXXXX
Model ID: B02440850000
Unit ID: XXXXXXXX
1: BL1 04.01.B0014
0: MPM 21.01.B0014
3:
The power switch is located on the base.
Supports 33 HID++ 2.0 features:
0: ROOT {0000} V0
1: FEATURE SET {0001} V0
2: DEVICE FW VERSION {0003} V2
Firmware: 1 BL1 04.01.B0014 0000B01B3067
Firmware: 0 MPM 21.01.B0014 4085B01B3067
Firmware: 3
Unit ID: XXXXXXXX Model ID: B02440850000 Transport IDs: {'btleid': 'B024', 'wpid': '4085'}
3: DEVICE NAME {0005} V0
Name: G604 Wireless Gaming Mouse
Kind: mouse
4: WIRELESS DEVICE STATUS {1D4B} V0
5: CONFIG CHANGE {0020} V0
Configuration: 00000000000000000000000000000000
6: BATTERY STATUS {1000} V0
Battery: 30%, BatteryStatus.DISCHARGING, next level 15%.
7: COLOR LED EFFECTS {8070} V4
LED Control (saved): Device
LED Control : Device
LEDs Primary : None
8: LED CONTROL {1300} V0
9: ONBOARD PROFILES {8100} V0
Device Mode: On-Board
Onboard Profiles (saved): Profile 1
Onboard Profiles : Profile 1
10: MOUSE BUTTON SPY {8110} V0
11: REPORT RATE {8060} V0
Report Rate: 1ms
Report Rate (saved): 1ms
Report Rate : 1ms
12: ADJUSTABLE DPI {2201} V1
Sensitivity (DPI) (saved): 800
Sensitivity (DPI) : 800
13: DFUCONTROL SIGNED {00C2} V0
14: DEVICE RESET {1802} V0
15: unknown:1803 {0318} V0 internal, hidden
16: OOBSTATE {1805} V0
17: CONFIG DEVICE PROPS {1806} V4
18: unknown:1813 {1318} V0 internal, hidden
19: unknown:1830 {3018} V0 internal, hidden
20: unknown:1890 {9018} V0 internal, hidden
21: unknown:1891 {9118} V0 internal, hidden
22: unknown:1861 {6118} V0 internal, hidden
23: unknown:1801 {0118} V0 internal, hidden
24: unknown:18B1 {B118} V0 internal, hidden
25: unknown:1DF3 {F31D} V0 internal, hidden
26: unknown:1E00 {001E} V0 hidden
27: unknown:1EB0 {B01E} V0 internal, hidden
28: unknown:1E22 {221E} V0 internal, hidden
29: HIRES WHEEL {2121} V0
Multiplier: 8
Has invert: Normal wheel motion
Has ratchet switch: Normal wheel mode
High resolution mode
HID notification
Scroll Wheel Direction (saved): False
Scroll Wheel Direction : False
Scroll Wheel Resolution (saved): True
Scroll Wheel Resolution : True
Scroll Wheel Diversion (saved): False
Scroll Wheel Diversion : False
30: unknown:18C0 {C018} V0 internal, hidden
31: CHANGE HOST {1814} V1
Change Host : 1:host1
32: HOSTS INFO {1815} V1
Host 0 (unpaired): host1
Host 1 (paired):
Battery: 30%, BatteryStatus.DISCHARGING, next level 15%.

View File

@ -0,0 +1,42 @@
solaar version 1.1.11
G733 Gaming Headset
Device path : /dev/hidraw3
USB id : 046d:0AFE
Codename : G733 Headset New
Kind : headset
Protocol : HID++ 4.2
Serial number:
Model ID: 0AFE00000000
Unit ID: FFFFFFFF
Firmware: U2 00.06
Supports 9 HID++ 2.0 features:
0: ROOT {0000} V0
1: FEATURE SET {0001} V0
2: DEVICE FW VERSION {0003} V2
Firmware: Firmware U2 00.06 0AFE
Unit ID: FFFFFFFF Model ID: 0AFE00000000 Transport IDs: {'usbid': '0AFE'}
3: DEVICE NAME {0005} V0
Name: G733 Gaming Headset
Kind: None
4: COLOR LED EFFECTS {8070} V3
LED Control (saved): Device
LED Control : Device
LEDs Logo (saved): !LEDEffectSetting {ID: 0x0}
LEDs Logo : !LEDEffectSetting {ID: 0}
LEDs Primary (saved): !LEDEffectSetting {ID: 0x1, color: 0x0, ramp: 0x0}
LEDs Primary : !LEDEffectSetting {ID: 1, color: 0x10000, ramp: 0x0}
5: GKEY {8010} V0
Divert G and M Keys (saved): False
Divert G and M Keys : False
6: EQUALIZER {8310} V1
Equalizer (saved): {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}
Equalizer : {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}
7: SIDETONE {8300} V0
Sidetone (saved): 0
Sidetone : 0
8: ADC MEASUREMENT {1F20} V4
Battery: 60% 3867mV , discharging.
Power Management (saved): 0
Power Management : 0
Battery: 60% 3867mV , discharging.

View File

@ -1,15 +1,4 @@
solaar version 1.1.10-22-g0b271eb solaar version 1.1.12rc1
Récepteur Lightspeed
Device path : /dev/hidraw10
USB id : 046d:C547
Serial : 033DFAF7
Firmware : 04.02.B0009
Bootloader : 02.09
Other : B4.DA
Has 1 paired device(s) out of a maximum of 2.
Notifications: wireless, software present (0x000900)
Device activity counters: 1=78
1: G915 WIRELESS RGB MECHANICAL GAMING KEYBOARD 1: G915 WIRELESS RGB MECHANICAL GAMING KEYBOARD
Device path : None Device path : None
@ -17,67 +6,78 @@ Récepteur Lightspeed
Codename : G915 KEYBOARD Codename : G915 KEYBOARD
Kind : keyboard Kind : keyboard
Protocol : HID++ 4.2 Protocol : HID++ 4.2
Polling rate : 1 ms (1000Hz) Report Rate : 1ms
Serial number: 8816D0DF Serial number: A502B0E1
Model ID: B354407CC33E Model ID: B354407CC33E
Unit ID: 8816D0DF Unit ID: A502B0E1
Bootloader: BOT 77.03.B0041 1: BOT 77.02.B0039
Other: 3:
Firmware: MPK 09.04.B0042 0: MPK 09.03.B0041
Other: 3:
Other: 3:
The power switch is located on the top left corner. The power switch is located on the top left corner.
Supports 38 HID++ 2.0 features: Supports 38 HID++ 2.0 features:
0: ROOT {0000} V0 0: ROOT {0000} V0
1: FEATURE SET {0001} V0 1: FEATURE SET {0001} V0
2: DEVICE FW VERSION {0003} V4 2: DEVICE FW VERSION {0003} V4
Firmware: Bootloader BOT 77.03.B0041 00003791543D Firmware: Bootloader BOT 77.02.B0039 0000EC44D534
Firmware: Other Firmware: Other
Firmware: Firmware MPK 09.04.B0042 407C8A23A76B Firmware: Firmware MPK 09.03.B0041 407C3791543D
Firmware: Other Firmware: Other
Firmware: Other Firmware: Other
Unit ID: 8816D0DF Model ID: B354407CC33E Transport IDs: {'btleid': 'B354', 'wpid': '407C', 'usbid': 'C33E'} Unit ID: A502B0E1 Model ID: B354407CC33E Transport IDs: {'btleid': 'B354', 'wpid': '407C', 'usbid': 'C33E'}
3: DEVICE NAME {0005} V0 3: DEVICE NAME {0005} V0
Name: G915 WIRELESS RGB MECHANICAL GAMING KEYBOARD Name: G915 WIRELESS RGB MECHANICAL GAMING KEYBOARD
Kind: keyboard Kind: keyboard
4: WIRELESS DEVICE STATUS {1D4B} V0 4: WIRELESS DEVICE STATUS {1D4B} V0
5: CONFIG CHANGE {0020} V0 5: CONFIG CHANGE {0020} V0
Configuration: 11000000000000000000000000000000
6: DEVICE FRIENDLY NAME {0007} V0 6: DEVICE FRIENDLY NAME {0007} V0
Friendly Name: G915 KEYBOARD Friendly Name: G915 KEYBOARD<EFBFBD>
7: BATTERY VOLTAGE {1001} V3 7: BATTERY VOLTAGE {1001} V3
Battery: 80% 4042mV , discharging. Battery: 80% 3998mV , discharging.
8: CHANGE HOST {1814} V1 8: CHANGE HOST {1814} V1
Changer d'hôte : 1:stagcrown Change Host : 1:Yon
9: HOSTS INFO {1815} V1 9: HOSTS INFO {1815} V1
Host 0 (paired): stagcrown Host 0 (paired): Yon
Host 1 (paired): Host 1 (paired):
10: RGB EFFECTS {8071} V0 10: RGB EFFECTS {8071} V0
RGB Control (saved): Device
RGB Control : Device
LEDs Logo (saved): !LEDEffectSetting {ID: 1, color: 11546720, intensity: 0, period: 100, ramp: 0, speed: 0}
LEDs Logo : HID++ error {'number': 1, 'request': 2799, 'error': 7, 'params': b'\x00'}
LEDs Primary (saved): !LEDEffectSetting {ID: 1, color: 16776960, intensity: 0, period: 100, ramp: 0, speed: 0}
LEDs Primary : HID++ error {'number': 1, 'request': 2796, 'error': 7, 'params': b'\x01'}
11: PER KEY LIGHTING V2 {8081} V2 11: PER KEY LIGHTING V2 {8081} V2
Per-key Lighting (saved): {A:white, B:red, C:white, D:white, E:white, F:white, G:white, H:white, I:white, J:white, K:white, L:white, M:white, N:white, O:white, P:white, Q:white, R:white, S:white, T:white, U:white, V:white, W:white, X:white, Y:white, Z:white, 1:white, 2:white, 3:white, 4:white, 5:white, 6:white, 7:white, 8:white, 9:white, 0:white, ENTER:white, ESC:white, BACKSPACE:white, TAB:white, SPACE:white, -:white, =:white, [:white, \:white, KEY 46:white, ~:white, ;:white, ':white, `:white, ,:white, .:white, /:white, CAPS LOCK:white, F1:white, F2:white, F3:white, F4:white, F5:white, F6:white, F7:white, F8:white, F9:white, F10:white, F11:white, F12:white, PRINT:white, SCROLL LOCK:white, PASTE:white, INSERT:white, HOME:white, PAGE UP:white, DELETE:white, END:white, PAGE DOWN:white, RIGHT:white, LEFT:white, DOWN:white, UP:white, NUMLOCK:white, KEYPAD /:white, KEYPAD *:white, KEYPAD -:white, KEYPAD +:white, KEYPAD ENTER:white, KEYPAD 1:white, KEYPAD 2:white, KEYPAD 3:white, KEYPAD 4:white, KEYPAD 5:white, KEYPAD 6:white, KEYPAD 7:white, KEYPAD 8:white, KEYPAD 9:white, KEYPAD 0:white, KEYPAD .:white, KEY 97:white, COMPOSE:white, POWER:white, KEY 100:white, KEY 101:white, KEY 102:white, KEY 103:white, LEFT CTRL:white, LEFT SHIFT:white, LEFT ALT:white, LEFT WINDOWS:white, RIGHT CTRL:white, RIGHT SHIFT:white, RIGHT ALTGR:white, RIGHT WINDOWS:white, BRIGHTNESS:white, PAUSE:white, MUTE:white, NEXT:white, PREVIOUS:white, G1:white, G2:white, G3:white, G4:white, G5:white, LOGO:white}
Per-key Lighting : {A:white, B:white, C:white, D:white, E:white, F:white, G:white, H:white, I:white, J:white, K:white, L:white, M:white, N:white, O:white, P:white, Q:white, R:white, S:white, T:white, U:white, V:white, W:white, X:white, Y:white, Z:white, 1:white, 2:white, 3:white, 4:white, 5:white, 6:white, 7:white, 8:white, 9:white, 0:white, ENTER:white, ESC:white, BACKSPACE:white, TAB:white, SPACE:white, -:white, =:white, [:white, \:white, KEY 46:white, ~:white, ;:white, ':white, `:white, ,:white, .:white, /:white, CAPS LOCK:white, F1:white, F2:white, F3:white, F4:white, F5:white, F6:white, F7:white, F8:white, F9:white, F10:white, F11:white, F12:white, PRINT:white, SCROLL LOCK:white, PASTE:white, INSERT:white, HOME:white, PAGE UP:white, DELETE:white, END:white, PAGE DOWN:white, RIGHT:white, LEFT:white, DOWN:white, UP:white, NUMLOCK:white, KEYPAD /:white, KEYPAD *:white, KEYPAD -:white, KEYPAD +:white, KEYPAD ENTER:white, KEYPAD 1:white, KEYPAD 2:white, KEYPAD 3:white, KEYPAD 4:white, KEYPAD 5:white, KEYPAD 6:white, KEYPAD 7:white, KEYPAD 8:white, KEYPAD 9:white, KEYPAD 0:white, KEYPAD .:white, KEY 97:white, COMPOSE:white, POWER:white, KEY 100:white, KEY 101:white, KEY 102:white, KEY 103:white, LEFT CTRL:white, LEFT SHIFT:white, LEFT ALT:white, LEFT WINDOWS:white, RIGHT CTRL:white, RIGHT SHIFT:white, RIGHT ALTGR:white, RIGHT WINDOWS:white, BRIGHTNESS:white, PAUSE:white, MUTE:white, NEXT:white, PREVIOUS:white, G1:white, G2:white, G3:white, G4:white, G5:white, LOGO:white}
12: REPROG CONTROLS V4 {1B04} V4 12: REPROG CONTROLS V4 {1B04} V4
Interception des boutons/touches (saved): {Host Switch Channel 1:Interception, Host Switch Channel 2:Interception} Key/Button Diversion (saved): {Host Switch Channel 1:Regular, Host Switch Channel 2:Regular}
Interception des boutons/touches : {Host Switch Channel 1:Interception, Host Switch Channel 2:Interception} Key/Button Diversion : {Host Switch Channel 1:Regular, Host Switch Channel 2:Regular}
13: REPORT HID USAGE {1BC0} V1 13: REPORT HID USAGE {1BC0} V1
14: ENCRYPTION {4100} V0 14: ENCRYPTION {4100} V0
15: KEYBOARD DISABLE BY USAGE {4522} V0 15: KEYBOARD DISABLE BY USAGE {4522} V0
16: KEYBOARD LAYOUT 2 {4540} V0 16: KEYBOARD LAYOUT 2 {4540} V0
17: GKEY {8010} V0 17: GKEY {8010} V0
Définir les touches G (saved): True Divert G and M Keys (saved): False
Définir les touches G : False Divert G and M Keys : False
18: MKEYS {8020} V0 18: MKEYS {8020} V0
LEDs de touche M (saved): {M1:True, M2:True, M3:True} M-Key LEDs (saved): {M1:False, M2:False, M3:False}
LEDs de touche M : {M1:False, M2:False, M3:False} M-Key LEDs : {M1:False, M2:False, M3:False}
19: MR {8030} V0 19: MR {8030} V0
LED de touche MR (saved): True MR-Key LED (saved): False
LED de touche MR : False MR-Key LED : False
20: BRIGHTNESS CONTROL {8040} V0 20: BRIGHTNESS CONTROL {8040} V0
Brightness Control (saved): 12
Brightness Control : 12
21: ONBOARD PROFILES {8100} V0 21: ONBOARD PROFILES {8100} V0
Device Mode: On-Board Device Mode: Host
Profils embarqués (saved): Enable Onboard Profiles (saved): Disabled
Profils embarqués : Enable Onboard Profiles : Disabled
22: REPORT RATE {8060} V0 22: REPORT RATE {8060} V0
Polling Rate (ms): 1 Report Rate: 1ms
Taux de scrutation (ms) (saved): 1 Report Rate (saved): 1ms
Taux de scrutation (ms) : 1 Report Rate : 1ms
23: DFUCONTROL SIGNED {00C2} V0 23: DFUCONTROL SIGNED {00C2} V0
24: DFU {00D0} V3 24: DFU {00D0} V3
25: DEVICE RESET {1802} V0 internal, hidden 25: DEVICE RESET {1802} V0 internal, hidden
@ -86,8 +86,8 @@ Récepteur Lightspeed
28: unknown:1813 {1813} V0 internal, hidden 28: unknown:1813 {1813} V0 internal, hidden
29: OOBSTATE {1805} V0 internal, hidden 29: OOBSTATE {1805} V0 internal, hidden
30: unknown:1830 {1830} V0 internal, hidden 30: unknown:1830 {1830} V0 internal, hidden
31: unknown:1890 {1890} V9 internal, hidden 31: unknown:1890 {1890} V5 internal, hidden
32: unknown:1891 {1891} V9 internal, hidden 32: unknown:1891 {1891} V5 internal, hidden
33: unknown:18A1 {18A1} V0 internal, hidden 33: unknown:18A1 {18A1} V0 internal, hidden
34: unknown:1E00 {1E00} V0 hidden 34: unknown:1E00 {1E00} V0 hidden
35: unknown:1EB0 {1EB0} V0 internal, hidden 35: unknown:1EB0 {1EB0} V0 internal, hidden
@ -96,8 +96,8 @@ Récepteur Lightspeed
Has 2 reprogrammable keys: Has 2 reprogrammable keys:
0: Host Switch Channel 1 , default: HostSwitch Channel 1 => HostSwitch Channel 1 0: Host Switch Channel 1 , default: HostSwitch Channel 1 => HostSwitch Channel 1
divertable, persistently divertable, pos:1, group:0, group mask:empty divertable, persistently divertable, pos:1, group:0, group mask:empty
reporting: diverted reporting: default
1: Host Switch Channel 2 , default: HostSwitch Channel 2 => HostSwitch Channel 2 1: Host Switch Channel 2 , default: HostSwitch Channel 2 => HostSwitch Channel 2
divertable, persistently divertable, pos:2, group:0, group mask:empty divertable, persistently divertable, pos:2, group:0, group mask:empty
reporting: diverted reporting: default
Battery: 80% 4042mV , discharging. Battery: 80% 3998mV , discharging.

View File

@ -0,0 +1,100 @@
solaar version 1.1.14
1: MX Anywhere 3 for Business
Device path : None
WPID : B02D
Codename : MX Anywhere 3
Kind : mouse
Protocol : HID++ 4.5
Serial number: 00000000
Model ID: B02D00000000
Unit ID: 00000000
1: BL1 36.01.B0011
0: RBM 15.01.B0011
3:
The power switch is located on the (unknown).
Supports 35 HID++ 2.0 features:
0: ROOT {0000} V0
1: FEATURE SET {0001} V0
2: DEVICE FW VERSION {0003} V4
Firmware: 1 BL1 36.01.B0011 B02D1EEFD8F8
Firmware: 0 RBM 15.01.B0011 B02D1EEFD8F8
Firmware: 3
Unit ID: 00000000 Model ID: B02D00000000 Transport IDs: {'btleid': 'B02D'}
3: DEVICE NAME {0005} V0
Name: MX Anywhere 3 for Business
Kind: mouse
4: WIRELESS DEVICE STATUS {1D4B} V0
5: CONFIG CHANGE {0020} V0
Configuration: 11000000000000000000000000000000
6: CRYPTO ID {0021} V1
7: DEVICE FRIENDLY NAME {0007} V0
Friendly Name: MX Anywhere 3B
8: UNIFIED BATTERY {1004} V3
Battery: 75%, 0.
9: REPROG CONTROLS V4 {1B04} V5
Key/Button Actions : {Left Button:Left Click, Right Button:Right Click, Middle Button:Mouse Middle Button, Back Button:Mouse Back Button, Forward Button:Mouse Forward Button, Smart Shift:Smart Shift}
Key/Button Diversion : {Middle Button:Regular, Back Button:Regular, Forward Button:Regular, Smart Shift:Diverted}
10: CHANGE HOST {1814} V1
Change Host : 2:archlinux
11: HOSTS INFO {1815} V2
Host 0 (paired): archlinux
Host 1 (paired): archlinux
Host 2 (unpaired):
12: XY STATS {2250} V1
13: ADJUSTABLE DPI {2201} V2
Sensitivity (DPI) : 1000
14: SMART SHIFT ENHANCED {2111} V0
Scroll Wheel Ratcheted : Ratcheted
Scroll Wheel Ratchet Speed : 15
15: HIRES WHEEL {2121} V1
Multiplier: 15
Has invert: Normal wheel motion
Has ratchet switch: Normal wheel mode
Low resolution mode
HID notification
Scroll Wheel Direction : False
Scroll Wheel Resolution : False
Scroll Wheel Diversion : False
16: WHEEL STATS {2251} V0
17: DFUCONTROL {00C3} V0
18: DEVICE RESET {1802} V0 internal, hidden, unknown:000010
19: unknown:1803 {1803} V0 internal, hidden, unknown:000010
20: CONFIG DEVICE PROPS {1806} V8 internal, hidden, unknown:000010
21: unknown:1816 {1816} V0 internal, hidden, unknown:000010
22: OOBSTATE {1805} V0 internal, hidden
23: unknown:1830 {1830} V0 internal, hidden, unknown:000010
24: unknown:1891 {1891} V7 internal, hidden, unknown:000008
25: unknown:18A1 {18A1} V0 internal, hidden, unknown:000010
26: unknown:1E00 {1E00} V0 hidden
27: unknown:1E02 {1E02} V0 internal, hidden
28: unknown:1602 {1602} V0
29: unknown:1EB0 {1EB0} V0 internal, hidden, unknown:000010
30: unknown:1861 {1861} V1 internal, hidden, unknown:000010
31: unknown:9300 {9300} V1 internal, hidden, unknown:000010
32: unknown:9001 {9001} V0 internal, hidden, unknown:000010
33: unknown:1E22 {1E22} V0 internal, hidden, unknown:000010
34: unknown:9205 {9205} V0 internal, hidden, unknown:000010
Has 7 reprogrammable keys:
0: Left Button , default: Left Click => Left Click
mse, analytics key events, pos:0, group:1, group mask:g1
reporting: default
1: Right Button , default: Right Click => Right Click
mse, analytics key events, pos:0, group:1, group mask:g1
reporting: default
2: Middle Button , default: Mouse Middle Button => Mouse Middle Button
mse, reprogrammable, divertable, raw XY, analytics key events, pos:0, group:2, group mask:g1,g2
reporting: default
3: Back Button , default: Mouse Back Button => Mouse Back Button
mse, reprogrammable, divertable, raw XY, analytics key events, unknown:000800, pos:0, group:2, group mask:g1,g2
reporting: default
4: Forward Button , default: Mouse Forward Button => Mouse Forward Button
mse, reprogrammable, divertable, raw XY, analytics key events, unknown:000800, pos:0, group:2, group mask:g1,g2
reporting: default
5: Smart Shift , default: Smart Shift => Smart Shift
mse, reprogrammable, divertable, raw XY, analytics key events, pos:0, group:2, group mask:g1,g2
reporting: diverted, raw XY diverted
6: Virtual Gesture Button , default: Virtual Gesture Button => Virtual Gesture Button
divertable, virtual, raw XY, force raw XY, pos:0, group:3, group mask:empty
reporting: default
Battery: 75%, 0.

View File

@ -39,15 +39,15 @@ Receiver
Battery: 96%, discharging. Battery: 96%, discharging.
7: XY STATS {2250} V1 7: XY STATS {2250} V1
8: WHEEL STATS {2251} V0 8: WHEEL STATS {2251} V0
9: unknown:2202 {2202} V0 9: unknown:2202 {2202} V0 EXTENDED_ADJUSTABLE_DPI
10: MODE STATUS {8090} V2 10: MODE STATUS {8090} V2
11: unknown:8061 {8061} V0 11: unknown:8061 {8061} V0 EXTENDED_ADJUSTABLE_REPORT_RATE
12: ONBOARD PROFILES {8100} V0 12: ONBOARD PROFILES {8100} V0
Device Mode: On-Board Device Mode: On-Board
Onboard Profiles (saved): Enable Onboard Profiles (saved): Enable
Onboard Profiles : Enable Onboard Profiles : Enable
13: MOUSE BUTTON SPY {8110} V0 13: MOUSE BUTTON SPY {8110} V0
14: unknown:1500 {1500} V0 14: unknown:1500 {1500} V0 FORCE_PAIRING
15: unknown:1801 {1801} V0 internal, hidden, unknown:000010 15: unknown:1801 {1801} V0 internal, hidden, unknown:000010
16: DEVICE RESET {1802} V0 internal, hidden, unknown:000010 16: DEVICE RESET {1802} V0 internal, hidden, unknown:000010
17: unknown:1803 {1803} V0 internal, hidden, unknown:000010 17: unknown:1803 {1803} V0 internal, hidden, unknown:000010

View File

@ -0,0 +1,64 @@
solaar show
rules cannot access modifier keys in Wayland, accessing process only works on GNOME with Solaar Gnome extension installed
solaar version 1.1.14-2
Unifying Receiver
Device path : /dev/hidraw1
USB id : 046d:C52B
Serial : EC219AC2
C Pending : ff
0 : 12.11.B0032
1 : 04.16
3 : AA.AA
Has 2 paired device(s) out of a maximum of 6.
Notifications: wireless (0x000100)
Device activity counters: 1=195, 2=74
1: Wireless Mouse M175
Device path : /dev/hidraw2
WPID : 4008
Codename : M175
Kind : mouse
Protocol : HID++ 2.0
Report Rate : 8ms
Serial number: 16E46E8C
Model ID: 000000000000
Unit ID: 00000000
0: RQM 40.00.B0016
The power switch is located on the base.
Supports 21 HID++ 2.0 features:
0: ROOT {0000} V0
1: FEATURE SET {0001} V0
2: DEVICE FW VERSION {0003} V0
Firmware: 0 RQM 40.00.B0016 4008
Unit ID: 00000000 Model ID: 000000000000 Transport IDs: {}
3: DEVICE NAME {0005} V0
Name: Wireless Mouse M185
Kind: mouse
4: BATTERY STATUS {1000} V0
Battery: 70%, 0, next level 5%.
5: unknown:1830 {1830} V0 internal, hidden
6: unknown:1850 {1850} V0 internal, hidden
7: unknown:1860 {1860} V0 internal, hidden
8: unknown:1890 {1890} V0 internal, hidden
9: unknown:18A0 {18A0} V0 internal, hidden
10: unknown:18C0 {18C0} V0 internal, hidden
11: WIRELESS DEVICE STATUS {1D4B} V0
12: unknown:1DF3 {1DF3} V0 internal, hidden
13: REPROG CONTROLS {1B00} V0
14: REMAINING PAIRING {1DF0} V0 hidden
Remaining Pairings: 117
15: unknown:1E00 {1E00} V0 hidden
16: unknown:1E80 {1E80} V0 internal, hidden
17: unknown:1E90 {1E90} V0 internal, hidden
18: unknown:1F03 {1F03} V0 internal, hidden
19: VERTICAL SCROLLING {2100} V0
Roller type: standard
Ratchet per turn: 24
Scroll lines: 0
20: MOUSE POINTER {2200} V0
DPI: 1000
Acceleration: low
Override OS ballistics
No vertical tuning, standard mice
Battery: 70%, 0, next level 5%.

View File

@ -39,8 +39,8 @@ Feature | ID | Status | Notes
`CONFIG_DEVICE_PROPS` | `0x1806` | Unsupported | `CONFIG_DEVICE_PROPS` | `0x1806` | Unsupported |
`CHANGE_HOST` | `0x1814` | Supported | `ChangeHost` `CHANGE_HOST` | `0x1814` | Supported | `ChangeHost`
`HOSTS_INFO` | `0x1815` | Partial Support | `get_host_names`, partial listing only `HOSTS_INFO` | `0x1815` | Partial Support | `get_host_names`, partial listing only
`BACKLIGHT` | `0x1981` | Unsupported | `BACKLIGHT` | `0x1981` | Supported | `Backlight`
`BACKLIGHT2` | `0x1982` | Supported | `Backlight2` `BACKLIGHT2` | `0x1982` | Supported | `Backlight2`, ...
`BACKLIGHT3` | `0x1983` | Unsupported | `BACKLIGHT3` | `0x1983` | Unsupported |
`PRESENTER_CONTROL` | `0x1A00` | Unsupported | `PRESENTER_CONTROL` | `0x1A00` | Unsupported |
`SENSOR_3D` | `0x1A01` | Unsupported | `SENSOR_3D` | `0x1A01` | Unsupported |
@ -54,7 +54,7 @@ Feature | ID | Status | Notes
`WIRELESS_DEVICE_STATUS` | `0x1D4B` | Read only | status reporting from device `WIRELESS_DEVICE_STATUS` | `0x1D4B` | Read only | status reporting from device
`REMAINING_PAIRING` | `0x1DF0` | Unsupported | `REMAINING_PAIRING` | `0x1DF0` | Unsupported |
`FIRMWARE_PROPERTIES` | `0x1F1F` | Unsupported | `FIRMWARE_PROPERTIES` | `0x1F1F` | Unsupported |
`ADC_MEASUREMENT` | `0x1F20` | Unsupported | `ADC_MEASUREMENT` | `0x1F20` | Supported | `ADCPower`
`LEFT_RIGHT_SWAP` | `0x2001` | Unsupported | `LEFT_RIGHT_SWAP` | `0x2001` | Unsupported |
`SWAP_BUTTON_CANCEL` | `0x2005` | Unsupported | `SWAP_BUTTON_CANCEL` | `0x2005` | Unsupported |
`POINTER_AXIS_ORIENTATION` | `0x2006` | Unsupported | `POINTER_AXIS_ORIENTATION` | `0x2006` | Unsupported |
@ -97,22 +97,22 @@ Feature | ID | Status | Notes
`GESTURE` | `0x6500` | Unsupported | `GESTURE` | `0x6500` | Unsupported |
`GESTURE_2` | `0x6501` | Partial Support | `Gesture2Gestures`, `Gesture2Params` `GESTURE_2` | `0x6501` | Partial Support | `Gesture2Gestures`, `Gesture2Params`
`GKEY` | `0x8010` | Partial Support | `DivertGkeys` `GKEY` | `0x8010` | Partial Support | `DivertGkeys`
`MKEYS` | `0x8020` | Unsupported | `MKEYS` | `0x8020` | Supported | `MkeyLEDs`
`MR` | `0x8030` | Unsupported | `MR` | `0x8030` | Supported | `MRKeyLED`
`BRIGHTNESS_CONTROL` | `0x8040` | Unsupported | `BRIGHTNESS_CONTROL` | `0x8040` | Supported | `BrightnessControl`
`REPORT_RATE` | `0x8060` | Supported | `ReportRate` `REPORT_RATE` | `0x8060` | Supported | `ReportRate`
`COLOR_LED_EFFECTS` | `0x8070` | Unsupported | `COLOR_LED_EFFECTS` | `0x8070` | Supported | `LEDControl`, `LEDZoneSetting`
`RGB_EFFECTS` | `0X8071` | Unsupported | `RGB_EFFECTS` | `0X8071` | Supported | `RGBControl`, `RGBEffectSetting`
`PER_KEY_LIGHTING` | `0x8080` | Unsupported | `PER_KEY_LIGHTING` | `0x8080` | Unsupported |
`PER_KEY_LIGHTING_V2` | `0x8081` | Unsupported | `PER_KEY_LIGHTING_V2` | `0x8081` | Supported | `PerKeyLighting`
`MODE_STATUS` | `0x8090` | Unsupported | `MODE_STATUS` | `0x8090` | Unsupported |
`ONBOARD_PROFILES` | `0x8100` | Unsupported | `ONBOARD_PROFILES` | `0x8100` | Supported |
`MOUSE_BUTTON_SPY` | `0x8110` | Unsupported | `MOUSE_BUTTON_SPY` | `0x8110` | Unsupported |
`LATENCY_MONITORING` | `0x8111` | Unsupported | `LATENCY_MONITORING` | `0x8111` | Unsupported |
`GAMING_ATTACHMENTS` | `0x8120` | Unsupported | `GAMING_ATTACHMENTS` | `0x8120` | Unsupported |
`FORCE_FEEDBACK` | `0x8123` | Unsupported | `FORCE_FEEDBACK` | `0x8123` | Unsupported |
`SIDETONE` | `0x8300` | Unsupported | `SIDETONE` | `0x8300` | Supported | `Sidetone`
`EQUALIZER` | `0x8310` | Unsupported | `EQUALIZER` | `0x8310` | Supported | `Equalizer`
`HEADSET_OUT` | `0x8320` | Unsupported | `HEADSET_OUT` | `0x8320` | Unsupported |
A “read only” note means the feature is a read-only feature. A “read only” note means the feature is a read-only feature.

View File

@ -43,16 +43,31 @@ a translation.
Some of the languages Solaar has been translated to are listed below. A full list of available translations can be obtained by checking the `/po` folder for translation files. Some of the languages Solaar has been translated to are listed below. A full list of available translations can be obtained by checking the `/po` folder for translation files.
- Chinese (Simplified): [Rongrong][Rongronggg9] - Chinese (Simplified): [Rongrong][Rongronggg9]
- Français: [Papoteur][papoteur], [David Geiger][david-geiger], - Chinese (Taiwan): Peter Dave Hello
[Damien Lallement][damsweb] - Czech: Marián Kyral
- Italiano: [Michele Olivo][micheleolivo] - Croatian: gogo
- Danish: John Erling Blad
- Dutch: Heimen Stoffels
- Français: [Papoteur][papoteur], [David Geiger][david-geiger], [Damien Lallement][damsweb]
- Finnish: Tomi Leppänen
- German: Daniel Frost
- Greek: Vangelis Skarmoutsos
- Indonesia: [Ferdina Kusumah][feku]
- Italiano: [Michele Olivo][micheleolivo], Lorenzo
- Japanese: Ryunosuke Toda
- Norsk (Bokmål): [John Erling Blad][jeblad] - Norsk (Bokmål): [John Erling Blad][jeblad]
- Polski: [Adrian Piotrowicz][nexces] - Norsk (Nynorsk): [John Erling Blad][jeblad]
- Portuguese-BR: [Drovetto][drovetto], [Josenivaldo Benito Jr.][jrbenito] - Polski: [Adrian Piotrowicz][nexces], Matthaiks
- Portuguese: Américo Monteiro
- Portuguese-BR: [Drovetto][drovetto], [Josenivaldo Benito Jr.][jrbenito], Vinícius
- Română: Daniel Pavel - Română: Daniel Pavel
- Russian: [Dimitriy Ryazantcev][DJm00n] - Russian: [Dimitriy Ryazantcev][DJm00n], Anton Soroko
- Serbian: [Renato Kaurić][renatoka]
- Slovak: [Jose Riha][jose1711] - Slovak: [Jose Riha][jose1711]
- Svensk: [Daniel Zippert][zipperten], Emelie Snecker - Spanish, Castilian: Jose Luis Tirado
- Swedish: John Erling Blad, [Daniel Zippert][zipperten], Emelie Snecker, Jonatan Nyberg
- Turkish: Osman Karagöz
- Ukrainian: Олександр Афанасьєв
[Rongronggg9]: https://github.com/Rongronggg9 [Rongronggg9]: https://github.com/Rongronggg9
[papoteur]: https://github.com/papoteur [papoteur]: https://github.com/papoteur
@ -66,3 +81,5 @@ Some of the languages Solaar has been translated to are listed below. A full lis
[drovetto]: https://github.com/drovetto [drovetto]: https://github.com/drovetto
[jrbenito]: https://github.com/jrbenito [jrbenito]: https://github.com/jrbenito
[jeblad]: https://github.com/jeblad [jeblad]: https://github.com/jeblad
[feku]: https://github.com/FerdinaKusumah
[renatoka]: https://github.com/renatoka

View File

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

BIN
docs/img/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

Before

Width:  |  Height:  |  Size: 3.7 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

View File

@ -3,12 +3,40 @@ title: Solaar Implementation
layout: page layout: page
--- ---
TODO: improve the callback mechanism(s) to support the explicit calls of the UI
# Solaar Implementation # Solaar Implementation
Solaar has three main components: code mostly about receivers and devices, code for the command line interface, and code for the graphical user interface. Solaar has three main components: code mostly about receivers and devices, code for the command line interface, and code for the graphical user interface.
The following graph shows the main components of Solaar and how they interact.
```mermaid
graph TD
subgraph User interface
U[UI]
C[CLI]
end
subgraph Core
U --> S{Solaar}
C --> S
S --> L[Logitech receiver]
L --> R[Receiver]
L --> D[Device]
S --> B[dbus]
end
subgraph Hardware interface
R --> A
D --> A
A[hidapi]--> P[hid parser]
end
subgraph Peripherals
P <-.-> M[Logitech mouse]
P <-.-> K[Logitech keyboard]
end
```
## Receivers and Devices ## Receivers and Devices
The code in `logitech_receiver` is responsible for creating and maintaining receiver (`receiver/Receiver`) and device (`device/Device`) objects for each device on the computer that uses the Logitech HID++ protocol. These objects are discovered in Linux by interacting with the Linux `udev` system using code in `hidapi`. The code in `logitech_receiver` is responsible for creating and maintaining receiver (`receiver/Receiver`) and device (`device/Device`) objects for each device on the computer that uses the Logitech HID++ protocol. These objects are discovered in Linux by interacting with the Linux `udev` system using code in `hidapi`.
@ -40,9 +68,9 @@ Many devices allow reprogramming some keys or buttons. One the main reasons for
Many pointing devices provide a facility for recognizing gestures and sending an HID message for the gesture. The `Gesture` class stores inforation for one gesture and the `Gestures` class stores information for all the gestures on a device. Functions in the Device class request `KeysArray` information and store it on devices. Functions in the Device class request `Gestures` information for a device when appropriate and store it on the device. Many pointing devices provide a facility for recognizing gestures and sending an HID message for the gesture. The `Gesture` class stores inforation for one gesture and the `Gestures` class stores information for all the gestures on a device. Functions in the Device class request `KeysArray` information and store it on devices. Functions in the Device class request `Gestures` information for a device when appropriate and store it on the device.
Many gaming devices provide an interface to controlling their LEDs by zone. The `LEDEffectSetting` class stores the current state of one zone of LEDs. This information can come directly from an LED feature but is also part of device profiles so this class provides a byte string interface. Solaar stores this information in YAML so this class provides a YAML interface. The `LEDEffectsInfo` class stores information about what LED zones are on a device and what effects they can perform and provides a method that builds an object by querying a device. Many gaming devices provide an interface to controlling their LEDs by zone. The `LEDEffectSetting` class stores the current state of one zone of LEDs. This information can come directly from an LED feature but is also part of Onboard Profiles so this class provides a byte string interface. Solaar stores this information in YAML so this class provides a YAML interface. The `LEDEffectsInfo` class stores information about what LED zones are on a device and what effects they can perform and provides a method that builds an object by querying a device.
Many gaming devices can be controlled by selecting one of their profiles. A profile sets up the rate at which the device reports movement, a set of sensitivites of its movement detector, a set of actions to be performed by mouse buttons or G and M keys, and effects for up to two LED zones. The `Button` class stores information about a button or key action. The `OnboardProfile` class stores a single profile, using the `LEDEffectSetting` and `Button` classes. Because retrieving and changing a profile is complex, this class provides a byte string interface. Because Solaar dumps profiles from devices as YAML documents and loads them into devices from YAML documents, this class provides a YAML interface. The `OnboardProfiles` class class stores the entire profiles information for a device. It provides an interface to construct an `OnboardProfiles` object by querying a device. Many gaming devices can be controlled by selecting one of their Onboard Profiles. An Onboard Profile sets up the rate at which the device reports movement, a set of sensitivites of its movement detector, a set of actions to be performed by mouse buttons or G and M keys, and effects for up to two LED zones. The `Button` class stores information about a button or key action. The `OnboardProfile` class stores a single profile, using the `LEDEffectSetting` and `Button` classes. Because retrieving and changing a profile is complex, this class provides a byte string interface. Because Solaar dumps profiles from devices as YAML documents and loads them into devices from YAML documents, this class provides a YAML interface. The `OnboardProfiles` class class stores the entire profiles information for a device. It provides an interface to construct an `OnboardProfiles` object by querying a device.
Because Solaar dumps profiles from devices as YAML documents and loads them into devices from YAML documents, these classes also provide a YAML interface. Because Solaar dumps profiles from devices as YAML documents and loads them into devices from YAML documents, these classes also provide a YAML interface.
#### HID++ 1.0 #### HID++ 1.0
@ -58,8 +86,6 @@ The module `descriptors` sets up information on device models for which Solaar n
The module `base_usb` sets up information for most of the receiver models that Solaar supports, including USB id, USB interface used for HID++ messages, what kind of receiver model it is, and some capabilities of the receiver model. Solaar can now support other receivers as long as they are not too unusual. The module lso sets up lists of device models by USB ID and Bluetooth ID and provides a function to determine whether a USB ID or Bluetooth ID is an HID++ device model The module `base_usb` sets up information for most of the receiver models that Solaar supports, including USB id, USB interface used for HID++ messages, what kind of receiver model it is, and some capabilities of the receiver model. Solaar can now support other receivers as long as they are not too unusual. The module lso sets up lists of device models by USB ID and Bluetooth ID and provides a function to determine whether a USB ID or Bluetooth ID is an HID++ device model
TODO? Move some information down to descriptors?
The module `base` provides functions that call discovery to enumerate all current receivers and devices and to set up a callback for when new receivers or devices are discovered. It provides functions to open and close I/O channels to receivers and devices, write HID++ messages to receivers and devices, and read HID++ messages from receivers and devices. It provides a function to turn an HID++ message into a notification. The module `base` provides functions that call discovery to enumerate all current receivers and devices and to set up a callback for when new receivers or devices are discovered. It provides functions to open and close I/O channels to receivers and devices, write HID++ messages to receivers and devices, and read HID++ messages from receivers and devices. It provides a function to turn an HID++ message into a notification.
The module provides a function to send an HID++ message to a receiver or device, constructing the message from parameters to the function, and optionally waiting for and returning a response. The function checks messages from the receiver or device, only terminating at timeout or when a message that appears to be the response is seen. Other messages are turned into notifications if appropriate and ignoreed otherwise. A separate function sends a ping message and waits for a reply to the ping. The module provides a function to send an HID++ message to a receiver or device, constructing the message from parameters to the function, and optionally waiting for and returning a response. The function checks messages from the receiver or device, only terminating at timeout or when a message that appears to be the response is seen. Other messages are turned into notifications if appropriate and ignoreed otherwise. A separate function sends a ping message and waits for a reply to the ping.
@ -79,8 +105,6 @@ After this processing HID++ 2.0 notifications are sent to the `diversion` module
The `status` module provides the `DeviceStatus` class to record the battery status of a device. It also provides an interface to signal changes to the connection status of the device that can invoke a callback. This callback is used to update the Solaar user interface when the status changes. The `status` module provides the `DeviceStatus` class to record the battery status of a device. It also provides an interface to signal changes to the connection status of the device that can invoke a callback. This callback is used to update the Solaar user interface when the status changes.
TODO: check why solaar/listener.py sets the callback multiple times
### Settings ### Settings
@ -123,10 +147,6 @@ The Solaar GUI takes these settings and constructs an interface for displaying a
This setup allows for very quick implementation of simple settings but it bypasses the data stored in a device object. This setup allows for very quick implementation of simple settings but it bypasses the data stored in a device object.
TODO: Refactor settings so that they always use data stored in device objects. Set up code to create a device data as easily as simple settings are creates. Set up code to use this to create a setting object for the Solaar GUI. Use callbacks to control GUI redisplay whenever the device data changes.
### Solaar Rules ### Solaar Rules
@ -143,8 +163,6 @@ The module `common.py` provides utility functions, structures, and classes.
`FirmwareInfo` provides information about device firmware. `FirmwareInfo` provides information about device firmware.
`BATTERY_APPROX` provides named integers used for approximate battery levels of devices. `BATTERY_APPROX` provides named integers used for approximate battery levels of devices.
TODO: Move a couple of things from hidpp20 to here.
`i18n.py` provides a few strings that need translations and might not otherwise be visible to translation software. `i18n.py` provides a few strings that need translations and might not otherwise be visible to translation software.
`special_keys.py` provides named integers for various collections of key codes and colors. `special_keys.py` provides named integers for various collections of key codes and colors.
@ -162,8 +180,6 @@ Device and receiver discovery is performed when Solaar starts. While the Solaar
This code is also responsible for actual writing data to devices and receivers and reading data from them. This code is also responsible for actual writing data to devices and receivers and reading data from them.
TOD: Is this actually the case?
## Solaar ## Solaar

View File

@ -17,7 +17,7 @@ Solaar runs as a regular user process, albeit with direct access to the Linux in
that lets it directly communicate with the Logitech devices it manages using special that lets it directly communicate with the Logitech devices it manages using special
Logitech-proprietary (HID++) commands. Logitech-proprietary (HID++) commands.
Each Logitech device implements a different subset of these commands. Each Logitech device implements a different subset of these commands.
Solaar is thus only able to make the changes to devices that devices implement. Solaar is thus only able to make the changes that a particular device supports.
Solaar is not a device driver and does not process normal input from devices. Solaar is not a device driver and does not process normal input from devices.
It is thus unable to fix problems that arise from incorrect handling of It is thus unable to fix problems that arise from incorrect handling of
@ -46,8 +46,8 @@ and for more information on its capabilities see
Solaar's GUI normally uses an icon in the system tray and starts with its main window visible. Solaar's GUI normally uses an icon in the system tray and starts with its main window visible.
This aspect of Solaar depends on having an active system tray, which is not the default This aspect of Solaar depends on having an active system tray, which is not the default
situation for recent versions of Gnome. For information on to set up a system tray under Gnome see situation for recent versions of Gnome. For information on how to set up a system tray under
[the capabilities page](https://pwr-solaar.github.io/Solaar/capabilities). Gnome see [the capabilities page](https://pwr-solaar.github.io/Solaar/capabilities).
Solaar's GUI can be started in several ways Solaar's GUI can be started in several ways
@ -75,7 +75,7 @@ Please report such experiences by creating an issue in
Solaar will detect all devices paired with supported Unifying, Bolt, Lightspeed, or Nano Solaar will detect all devices paired with supported Unifying, Bolt, Lightspeed, or Nano
receivers, and at the very least display some basic information about them. receivers, and at the very least display some basic information about them.
Solaar will detect some Logitech devices that connect via a USB cable or Bluetooth. Solaar will detect many Logitech devices that connect via a USB cable or Bluetooth.
Solaar can pair and unpair a Logitech device showing the Unifying logo Solaar can pair and unpair a Logitech device showing the Unifying logo
(Solaar's version of the [logo][logo]) (Solaar's version of the [logo][logo])
@ -95,7 +95,7 @@ which is done using the usual Bluetooth mechanisms.
For a partial list of supported devices For a partial list of supported devices
and their features, see [the devices page](https://pwr-solaar.github.io/Solaar/devices). and their features, see [the devices page](https://pwr-solaar.github.io/Solaar/devices).
[logo]: https://pwr-solaar.github.io/Solaar/assets/solaar.svg [logo]: https://pwr-solaar.github.io/Solaar/img/solaar.svg
## Prebuilt packages ## Prebuilt packages
@ -106,12 +106,11 @@ available from the standard repositories for your distribution, you can try
one of these packages. one of these packages.
- Arch solaar package in the [extra repository][arch] - Arch solaar package in the [extra repository][arch]
- Ubuntu/Kubuntu stable packages: use the [Solaar stable ppa][ppa2], courtesy of [gogo][ppa4] - Ubuntu/Kubuntu package in [Solaar stable ppa][ppa2]
- Ubuntu/Kubuntu git build packages: use the [Solaar git ppa][ppa1], courtesy of [gogo][ppa4] - NixOS Flake package in [Svenum/Solaar-Flake][nix flake]
- NixOS Flake: see [Svenum/Solaar-Flake][nix flake]
Solaar is available from some other repositories Solaar is available from some other repositories
but they are several versions behind the current version. but they may be several versions behind the current version.
- for Ubuntu/Kubuntu 16.04+: the solaar package from [universe repository][universe repository] - for Ubuntu/Kubuntu 16.04+: the solaar package from [universe repository][universe repository]
- a [Gentoo package][gentoo], courtesy of Carlos Silva and Tim Harder - a [Gentoo package][gentoo], courtesy of Carlos Silva and Tim Harder
@ -121,8 +120,6 @@ Solaar uses a standard system tray implementation; solaar-gnome3 is no longer re
[ppa4]: https://launchpad.net/~trebelnik-stefina [ppa4]: https://launchpad.net/~trebelnik-stefina
[ppa2]: https://launchpad.net/~solaar-unifying/+archive/ubuntu/stable [ppa2]: https://launchpad.net/~solaar-unifying/+archive/ubuntu/stable
[ppa1]: https://launchpad.net/~solaar-unifying/+archive/ubuntu/ppa
[ppa]: http://launchpad.net/~daniel.pavel/+archive/solaar
[arch]: https://www.archlinux.org/packages/extra/any/solaar/ [arch]: https://www.archlinux.org/packages/extra/any/solaar/
[gentoo]: https://packages.gentoo.org/packages/app-misc/solaar [gentoo]: https://packages.gentoo.org/packages/app-misc/solaar
[mageia]: http://mageia.madb.org/package/show/release/cauldron/application/0/name/solaar [mageia]: http://mageia.madb.org/package/show/release/cauldron/application/0/name/solaar
@ -136,17 +133,26 @@ for the step-by-step procedure for manual installation.
## Known Issues ## Known Issues
- Solaar expects that it has exclusive control over settings that are not ignored. - Onboard Profiles, when active, can prevent changes to other settings, such as Polling Rate, DPI, and various LED settings. Which settings are affected depends on the device. To make changes to affected settings, disable Onboard Profiles. If Onboard Profiles are later enabled the affected settings may change to the value in the profile.
Running other programs that modify these settings, such as logiops,
will likely result in unexpected device behavior. - Solaar version 1.1.12 has a bug resulting in devices remaining in their default configuration after a system resume. This is fixed in 1.1.13.
- Bluez 5.73 does not remove Bluetooth devices when they disconnect.
Solaar 1.1.12 processes the DBus disconnection and connection messages from Bluez and does re-initialize devices when they reconnect.
The HID++ driver does not re-initialize devices, which causes problems with smooth scrolling.
Until the problem is resolved having Scroll Wheel Resolution set to true (and not ignored) may be helpful.
- The Linux HID++ driver modifies the Scroll Wheel Resolution setting to - The Linux HID++ driver modifies the Scroll Wheel Resolution setting to
implement smooth scrolling. If Solaar later changes this setting, scrolling implement smooth scrolling. If Solaar changes this setting, scrolling
can be either very fast or very slow. To fix this problem can be either very fast or very slow. To fix this problem
click on the icon at the right edge of the setting to set it to click on the icon at the right edge of the setting to set it to
"Ignore this setting", which is the default for new devices. "Ignore this setting", which is the default for new devices.
The mouse has to be reset (e.g., by turning it off and on again) before this fix will take effect. The mouse has to be reset (e.g., by turning it off and on again) before this fix will take effect.
- Solaar expects that it has exclusive control over settings that are not ignored.
Running other programs that modify these settings, such as logiops,
will likely result in unexpected device behavior.
- The driver also sets the scrolling direction to its normal setting when implementing smooth scrolling. - The driver also sets the scrolling direction to its normal setting when implementing smooth scrolling.
This can interfere with the Scroll Wheel Direction setting, requiring flipping this setting back and forth This can interfere with the Scroll Wheel Direction setting, requiring flipping this setting back and forth
to restore reversed scrolling. to restore reversed scrolling.
@ -155,9 +161,6 @@ for the step-by-step procedure for manual installation.
resulting in responses being sent back that look like other messages. For some devices this causes resulting in responses being sent back that look like other messages. For some devices this causes
Solaar to report incorrect battery levels. Solaar to report incorrect battery levels.
- If the Python hid-parser package is not available, Solaar will not recognize some devices.
Use pip to install hid-parser.
- Solaar normally uses icon names for its icons, which in some system tray implementations - Solaar normally uses icon names for its icons, which in some system tray implementations
results in missing or wrong-sized icons. results in missing or wrong-sized icons.
The `--tray-icon-size` option forces Solaar to use icon files of appropriate size The `--tray-icon-size` option forces Solaar to use icon files of appropriate size
@ -169,11 +172,6 @@ for the step-by-step procedure for manual installation.
in some system tray implementations. Changing to a different theme may help. in some system tray implementations. Changing to a different theme may help.
The `--battery-icons=symbolic` option can be used to force symbolic icons. The `--battery-icons=symbolic` option can be used to force symbolic icons.
- Many gaming mice and keyboards have the ONBOARD PROFILES feature.
This feature can override other features, including polling rate and key lighting.
To make the Polling Rate and M-Key LEDs settings effective, the Onboard Profiles setting has to be disabled.
This may have other effects, such as turning off backlighting.
- Solaar will try to use uinput to simulate input from rules under Wayland or if Xtest is not available - Solaar will try to use uinput to simulate input from rules under Wayland or if Xtest is not available
but this needs write permission on /dev/uinput. but this needs write permission on /dev/uinput.
For more information see [the rules page](https://pwr-solaar.github.io/Solaar/rules). For more information see [the rules page](https://pwr-solaar.github.io/Solaar/rules).
@ -189,6 +187,11 @@ for the step-by-step procedure for manual installation.
realize that the key was newly depressed. For this reason Solaar rules that can change hosts should realize that the key was newly depressed. For this reason Solaar rules that can change hosts should
trigger on key releasing. trigger on key releasing.
## License
This software is distributed under the terms of the
[GNU Public License, v2](LICENSE.txt), or later.
## Contributing to Solaar ## Contributing to Solaar
Contributions to Solaar are very welcome. Contributions to Solaar are very welcome.
@ -201,28 +204,21 @@ If you find a bug, please check first if it has already been reported. If yes, p
If you want to add a new feature to Solaar, feel free to open a feature request issue to discuss your proposal. If you want to add a new feature to Solaar, feel free to open a feature request issue to discuss your proposal.
There are also usually several open issues for enhancements that have already been requested. There are also usually several open issues for enhancements that have already been requested.
## Contributors
## License
This software is distributed under the terms of the
[GNU Public License, v2](COPYING).
## Thanks
This project began as a third-hand clone of [Noah K. Tilton](https://github.com/noah)'s This project began as a third-hand clone of [Noah K. Tilton](https://github.com/noah)'s
logitech-solar-k750 project on GitHub (no longer available). It was developed logitech-solar-k750 project on GitHub (no longer available). It was developed
further thanks to the diggings in Logitech's HID++ protocol done by many other further thanks to the contributions of many other people, including:
people:
- [Julien Danjou](http://julien.danjou.info/blog/2012/logitech-k750-linux-support), - [Daniel Pavel](https://github.com/pwr)
who also provided some internal - [Filipe Lains](https://github.com/FFY00)
[Logitech documentation](http://julien.danjou.info/blog/2012/logitech-unifying-upower) - [Peter Wu](https://github.com/Lekensteyn), who also did some [reverse engineering on pairing](https://lekensteyn.nl/logitech-unifying.html)
- Julien Danjou
- [Lars-Dominik Braun](http://6xq.net/git/lars/lshidpp.git) - [Lars-Dominik Braun](http://6xq.net/git/lars/lshidpp.git)
- [Alexander Hofbauer](http://derhofbauer.at/blog/blog/2012/08/28/logitech-performance-mx) - [Alexander Hofbauer](http://derhofbauer.at/blog/blog/2012/08/28/logitech-performance-mx)
- [Clach04](http://bitbucket.org/clach04/logitech-unifying-receiver-tools) - [Clach04](https://github.com/clach04)
- [Peter Wu](https://lekensteyn.nl/logitech-unifying.html) - [Peter F. Patel-Schneider](https://github.com/pfps)
- [Nestor Lopez Casado](http://drive.google.com/folderview?id=0BxbRzx7vEV7eWmgwazJ3NUFfQ28)
provided some more Logitech specifications for the HID++ protocol
Also, thanks to Douglas Wagner, Julien Gascard, and Peter Wu for helping with Thanks go to Nestor Lopez Casado, who
application testing and supporting new devices. provided [public Logitech specifications for the HID++ protocol](http://drive.google.com/folderview?id=0BxbRzx7vEV7eWmgwazJ3NUFfQ28).
Also, thanks to Douglas Wagner, Julien Gascard, and others for helping with application testing and supporting new devices.

View File

@ -7,58 +7,73 @@ layout: page
An easy way to install the most recent release version of Solaar is from the PyPI repository. An easy way to install the most recent release version of Solaar is from the PyPI repository.
First install pip, and then run First install pip, and then run
`pip install --user solaar`. `pip install --user solaar` or `pipx install --system-site-packages solaar` or
If you are using pipx add the `--system-site-packages` flag. If you are using pipx add the `` flag.
This will not install the Solaar udev rule, which you will need to install manually by copying This will not install the Solaar udev rule, which you will need to install manually by copying
`~/.local/lib/udev/rules.d/42-logitech-unify-permissions.rules` `~/.local/lib/udev/rules.d/42-logitech-unify-permissions.rules`
to `/etc/udev/rules.d` as root. to `/etc/udev/rules.d` as root.
If you want Solaar rules to simulate input you will have to instead install Solaar's uinput udev rule
from the GitHub repository.
## macOS support ## Installing in macOS
Solaar has limited support for macOS. You can use it to pair devices and configure settings Solaar has limited support for macOS. You can use it to pair devices and configure settings
but the rule system and diversion will not work. but the rule system and diversion will not work.
After installing Solaar via pip use homebrew to install the hidapi library: After installing Solaar via pip use homebrew to install the needed libraries:
``` ```
brew install hidapi brew update
``` brew install hidapi gtk+3 pygobject3
If you only want to use the CLI that's all that is needed. To use the GUI you need to also
install GTK and its python bindings:
```
brew install gtk+3 pygobject3
``` ```
# Manual installation from GitHub # Installating from GitHub
## Downloading ## Downloading
Clone Solaar from GitHub by `git clone https://github.com/pwr-Solaar/Solaar.git`. Clone Solaar from GitHub by `git clone https://github.com/pwr-Solaar/Solaar.git`.
## Installing using the Makefile
Solaar has a makefile that can be used to easily install Solaar after cloning the repository.
First, install the needed system packages by `make install_apt`
or `make install_dnf` or `make install_brew`.
These might not install all needed packages in older versions of your distribution.
Next, install the Solaar rule via `make install_udev`.
If you are using Wayland instead of X11 you may want to instead `make install_udev_uinput`
so that Solaar rules can simulate input in Wayland.
Finally, install Solaar via `make install_pip` or `make install_pipx`.
Parts of the installation process require sudo privileges so you may be asked for your password.
## Running from the download directory
To run Solaar from the download directory, just cd to there and run `bin/solaar` for the GUI
or `bin/solaar <command> <arguments>` for the CLI.
## Requirements for Solaar ## Requirements for Solaar
If you have previously successfully installed a recent version of Solaar from a repository This is only relevant if you have problems with the easier methods above.
you should be able to skip this section.
Solaar needs a reasonably new kernel with kernel modules `hid-logitech-dj` Solaar needs a reasonably new kernel with kernel modules `hid-logitech-dj` and `hid-logitech-hidpp` loaded.
and `hid-logitech-hidpp` loaded. The kernel option CONFIG_HIDRAW also needs to be enabled.
Most of Solaar should work fine with any kernel more recent than 5.2, Most of Solaar should work fine with any kernel more recent than 5.2,
but newer kernels might be needed for some devices to be correctly recognized and handled. but newer kernels might be needed for some devices to be correctly recognized and handled.
The `udev` package must be installed and its daemon running. The `udev` package must be installed and its daemon running.
Solaar requires Python 3.7+ and requires several packages to be installed. Solaar requires Python 3.7+ and requires several packages to be installed.
If you are running the system version of Python you should have the If you are running the system version of Python you should have the
`python3-pyudev`, `python3-psutil`, `python3-xlib`, `python3-evdev`, `python3-typing-extensions`, `dbus-python`, `python3-pyudev`, `python3-psutil`, `python3-xlib`, `python3-evdev`, `python3-typing-extensions`, `dbus-python`
and `python3-yaml` or `python3-pyyaml` packages installed. or `python3-dbus`, and `python3-yaml` or `python3-pyyaml` packages installed.
To run the GUI Solaar also requires Gtk3 and its GObject introspection bindings. To run the GUI Solaar also requires Gtk3 and its GObject introspection bindings.
If you are running the system version of Python If you are running the system version of Python in Debian/Ubuntu you should have the
in Debian/Ubuntu you should have the
`python3-gi` and `gir1.2-gtk-3.0` packages installed. `python3-gi` and `gir1.2-gtk-3.0` packages installed.
In Fedora you need `gtk3` and `python3-gobject`. In Fedora you need `gtk3` and `python3-gobject`.
You may have to install `gcc` and the Python development package (`python3-dev` or `python3-devel`, You may have to install `gcc` and the Python development package (`python3-dev` or `python3-devel`,
depending on your distribution). depending on your distribution).
Other system packages may be required depending on your distribution, such as `python-gobject-common-devel`. Other system packages may be required depending on your distribution, such as `python-gobject-common-devel` and `python-typing-extensions'.
Although the Solaar CLI does not require Gtk3, Although the Solaar CLI does not require Gtk3,
`solaar config` does use Gtk3 capabilities to determine whether the Solaar GUI is running `solaar config` does use Gtk3 capabilities to determine whether the Solaar GUI is running
and thus should tell the Solaar GUI to update its information about settings and thus should tell the Solaar GUI to update its information about settings
@ -77,10 +92,11 @@ If desktop notifications bindings are also installed
(`gir1.2-notify-0.7` for Debian/Ubuntu), (`gir1.2-notify-0.7` for Debian/Ubuntu),
you will also see desktop notifications when devices come online and go offline. you will also see desktop notifications when devices come online and go offline.
If the `hid_parser` Python package is available, Solaar parses HID report descriptors Solaar includes its own version of `hid_parser` because the version that is in PyPi
and can control more HID++ devices that do not use a receiver. (at https://pypi.org/project/hid-parser/) does not have some changes that are in
This package may not be available in some distributions but can be installed using pip https://github.com/usb-tools/python-hid-parser and are needed for some devices.
via `pip install --user hid-parser`. Do not use pip to install hid_parser!
Some distributions (e.g., Fedora) may separately package this code.
If the `gitinfo` Python package is available, Solaar shows better information If the `gitinfo` Python package is available, Solaar shows better information
about which version of Solaar is running. about which version of Solaar is running.
@ -97,78 +113,25 @@ which requires installation of the X11 development package.
Solaar will run under Wayland but some parts of Solaar rules will not work. Solaar will run under Wayland but some parts of Solaar rules will not work.
For more information see [the rules page](https://pwr-solaar.github.io/Solaar/rules). For more information see [the rules page](https://pwr-solaar.github.io/Solaar/rules).
### Installing Solaar's udev rule ## Installing Solaar's udev rule manually
Solaar needs to write to HID devices and receivers. You can install Solaar's udev rule manually by copying the file
To achieve this without Solaar running as root, which is not recommended, requires a udev rule. Run `make install_udev` in Solaar's root folder to `rules.d/42-logitech-unify-permissions.rules`
install Solaar's regular udev rule and put it into effect. You need sudo privileges to do this and will be asked for your password. If you are using Wayland instead of X11 you may want to instead `make install_udev_uinput` so that Solaar rules can simulate input in Wayland. as root from the Solaar repository to `/etc/udev/rules.d`.
In Wayland you may want to instead copy
`rules.d-uinput/42-logitech-unify-permissions.rules`.
Let udev reload its rules by running `sudo udevadm control --reload-rules`.
<details> # Solaar in other languages
<summary>Manual steps</summary>
You can install this rule manually by copying the file
[`rules.d/42-logitech-unify-permissions.rules`](/rules.d/42-logitech-unify-permissions.rules) as root from Solaar repo
to `/etc/udev/rules.d`.
Let udev reload its rules by running
`sudo udevadm control --reload-rules`.
</details>
Then disconnect your Logitech receivers and any USB- or Bluetooth-connected Logitech devices and
re-connect them for the udev rule to take effect. Alternatively, you can just reboot your computer.
## Running from the download directory
To run Solaar from the download directory, first install the Solaar udev rule if necessary.
Then cd to the solaar directory and run `bin/solaar` for the GUI
or `bin/solaar <command> <arguments>` for the CLI.
Do not run Solaar as root, as you may encounter problems with X11 integration and with the system tray.
## Installing Solaar from the download directory using Pip
Python programs are usually installed using [pip][pip].
The pip instructions for Solaar are in `setup.py`, the standard place to put such instructions.
To install Solaar for yourself only run
`pip install --user '.[report-descriptor,git-commit]'`
from the download directory.
This tells pip to install Solaar into your `~/.local` directory, but does not install Solaar's udev rule.
(See above for installing the udev rule.)
Once the udev rule has been installed you can then run Solaar as `~/.local/bin/solaar`.
Installing Python programs to system directories using pip is generally frowned on both
because this runs arbitrary code as root and because this can override existing python libraries
that other users or even the system depend on. If you want to install Solaar to /usr/local run
`sudo bash -c 'umask 022 ; pip install .'` in the solaar directory.
(The umask is needed so that the created files and directories can be read and executed by everyone.)
Then Solaar can be run as `/usr/local/bin/solaar`.
You will also have to install the udev rule.
[pip]: https://en.wikipedia.org/wiki/Pip_(package_manager)
## Solaar in other languages
If you want to have Solaar's user messages in some other language you need to run If you want to have Solaar's user messages in some other language you need to run
`tools/po-compile.sh` to create the translation files before running or installing Solaar `tools/po-compile.sh` to create the translation files before running or installing Solaar
and set the LANGUAGE environment variable appropriately when running Solaar. and set the LANGUAGE environment variable appropriately when running Solaar.
# Setting up Solaar's icons
Solaar uses a number of custom icons, which have to be installed in a place where GTK can access them.
If Solaar has never been installed, and only run from the download directory then Solaar will not be able to find the icons.
If Solaar has only been installed for a user (e.g., via pip) then Solaar will be able to find the icons,
but they may not show up in the system tray.
One solution is to install a version of Solaar on a system-wide basis.
A more-recent version of Solaar can then be installed for a user or Solaar can be run out of the download directory.
Another solution is to copy the Solaar custom icons from `share/solaar/icons` to a place they can be found by GTK,
likely `/usr/share/icons/hicolor/scalable/apps`.
# Running Solaar at Startup # Running Solaar at Startup
Distributions can cause Solaar can be run automatically at user login by installing a desktop file at Distributions can cause Solaar can be run automatically at user login by installing a desktop file at
`/etc/xdg/autostart/solaar.desktop`. An example of this file content can be seen in the repository at `/etc/xdg/autostart/solaar.desktop`. An example of this file content can be seen in the repository at
[`share/autostart/solaar.desktop`](/share/autostart/solaar.desktop). [`share/autostart/solaar.desktop`](https://github.com/pwr-Solaar/Solaar/blob/master/share/autostart/solaar.desktop).
If you install Solaar yourself you may need to create or modify this file or install a startup file under your home directory. If you install Solaar yourself you may need to create or modify this file or install a startup file under your home directory.

View File

@ -3,11 +3,10 @@ title: Rule Processing of HID++ Notifications
layout: page layout: page
--- ---
# Rule Processing of HID++ Notifications
Creating and editing most rules can be done in the Solaar GUI, by pressing the 'Rule Editor' button in the Creating and editing most rules can be done in the Solaar GUI, by pressing the 'Rule Editor' button in the
Solaar main window. Solaar main window.
Rule processing is an experimental feature. Significant changes might be made in response to problems.
Note that rule processing only fully works under X11. Note that rule processing only fully works under X11.
When running under Wayland with X11 libraries loaded some features will not be available. When running under Wayland with X11 libraries loaded some features will not be available.
When running under Wayland without X11 libraries loaded even more features will not be available. When running under Wayland without X11 libraries loaded even more features will not be available.
@ -24,7 +23,8 @@ You may have to reboot your system for the write permission to be set up.
Another way to get write access to /dev/uinput is to run `sudo setfacl -m u:${USER}:rw /dev/uinput` Another way to get write access to /dev/uinput is to run `sudo setfacl -m u:${USER}:rw /dev/uinput`
but this needs to be done every time the system is rebooted. but this needs to be done every time the system is rebooted.
Logitech devices that use HID++ version 2.0 or greater produce feature-based ## HID++ notifications and diversion
Logitech devices that use HID++ version 2.0 or greater, produce feature-based
notifications that Solaar can process using a simple rule language. For notifications that Solaar can process using a simple rule language. For
example, using rules Solaar can emulate an `XF86_MonBrightnessDown` key tap example, using rules Solaar can emulate an `XF86_MonBrightnessDown` key tap
in response to the pressing of the `Brightness Down` key on Craft keyboards, in response to the pressing of the `Brightness Down` key on Craft keyboards,
@ -34,7 +34,7 @@ Windows mode.
Solaar's rules only trigger on HID++ notifications so device actions that Solaar's rules only trigger on HID++ notifications so device actions that
normally produce HID output have to be first be set (diverted) to normally produce HID output have to be first be set (diverted) to
produce HID++ notifications instead of their normal behavior. produce HID++ notifications instead of their normal behavior.
Currently Solaar can divert some mouse scroll wheels, some Currently, Solaar can divert some mouse scroll wheels, some
mouse thumb wheels, the crown of Craft keyboards, and some keys and buttons. mouse thumb wheels, the crown of Craft keyboards, and some keys and buttons.
If the scroll wheel, thumb wheel, crown, key, or button is If the scroll wheel, thumb wheel, crown, key, or button is
not diverted by setting the appropriate setting then no HID++ notification is not diverted by setting the appropriate setting then no HID++ notification is
@ -42,6 +42,7 @@ generated and rules will not be triggered by manipulating the wheel, crown, key,
Look for `HID++` or `Diversion` settings to see what Look for `HID++` or `Diversion` settings to see what
diversion can be done with your devices. diversion can be done with your devices.
### Show notifications
Running Solaar with the `-ddd` Running Solaar with the `-ddd`
option will show information about notifications, including their feature option will show information about notifications, including their feature
name, report number, and data. name, report number, and data.
@ -57,35 +58,44 @@ processed for the notification.
Rules are evaluated by evaluating each of their components in order. The Rules are evaluated by evaluating each of their components in order. The
evaluation of a rule is terminated early if a condition component evaluates evaluation of a rule is terminated early if a condition component evaluates
to false or the last evaluated sub-component of a component is an action. A to false or the last evaluated subcomponent of a component is an action. A
rule is false if its last evaluated component evaluates to a false value. rule is false if its last evaluated component evaluates to false.
## Conditions
### Not
`Not` conditions take a single component and are true if their component `Not` conditions take a single component and are true if their component
evaluates to a false value. evaluates to a false value.
### Or
`Or` conditions take a sequence of components and are evaluated by `Or` conditions take a sequence of components and are evaluated by
evaluating each of their components in order. evaluating each of their components in order.
An Or condition is terminated early if a component evaluates to true or the An Or condition is terminated early if a component evaluates to true or the
last evaluated sub-component of a component is an action. last evaluated subcomponent of a component is an action.
A Or condition is true if its last evaluated component evaluates to a true A Or condition is true if its last evaluated component evaluates to a true
value. `And` conditions take a sequence of components which are evaluated the same value. `And` conditions take a sequence of components which are evaluated the same
as rules. as rules.
### Feature
`Feature` conditions are true if the name of the feature of the current `Feature` conditions are true if the name of the feature of the current
notification is their string argument. notification is their string argument.
`Report` conditions are true if the report number in the current `Report` conditions are true if the report number in the current
notification is their integer argument. notification is their integer argument.
### Key
`Key` conditions are true if the Logitech name of the current **diverted** key or button being pressed is their `Key` conditions are true if the Logitech name of the current **diverted** key or button being pressed is their
string argument. Alternatively, if the argument is a list `[name, action]` where `action` string argument. Alternatively, if the argument is a list `[name, action]` where `action`
is either `'pressed'` or `'released'`, the key down or key up events of `name` argument are is either `'pressed'` or `'released'`, the key down or key up events of `name` argument are
matched, respectively. Logitech key and button names are shown in the `Key/Button Diversion` matched, respectively. Logitech key and button names are shown in the `Key/Button Diversion`
setting. These names are also shown in the output of `solaar show` in the 'reprogrammable keys' setting. These names are also shown in the output of `solaar show` in the 'Reprogrammable keys'
section. Only keys or buttons that have 'divertable' in their report can be diverted. section. Only keys or buttons that have 'Divertable' in their report can be diverted.
Some keyboards have Gn, Mn, or MR keys, which are diverted using the 'Divert G Keys' setting. Some keyboards have 'Gn', 'Mn', or 'MR' keys, which are diverted using the 'Divert G Keys' setting.
### Key is down
`KeyIsDown` conditions are true if the **diverted** key or button that is their string argument is currently down. `KeyIsDown` conditions are true if the **diverted** key or button that is their string argument is currently down.
Note that this only works for **diverted** keys or buttons, including diverted Gn, Mn, and MR keys. Note that this only works for **diverted** keys or buttons, including diverted Gn, Mn, and MR keys.
### Key and button diversion
Solaar can also create special notifications in response to mouse movements on some mice. Solaar can also create special notifications in response to mouse movements on some mice.
Setting `Key/Button Diversion` for a key or button to Mouse Gestures causes the key or button to create a `Mouse Gesture` Setting `Key/Button Diversion` for a key or button to Mouse Gestures causes the key or button to create a `Mouse Gesture`
notification for the period that the key or button is depressed. notification for the period that the key or button is depressed.
@ -95,6 +105,7 @@ Pressing a diverted key creates a key event.
When the key is released the sequence of events is sent as a synthetic notification When the key is released the sequence of events is sent as a synthetic notification
that can be matched with `Mouse Gesture` conditions. that can be matched with `Mouse Gesture` conditions.
### Mouse gestures
`Mouse Gesture` conditions are true if the actions (mouse movements and diverted key presses) taken while a mouse gestures button is held down match the arguments of the condition. `Mouse Gesture` conditions are true if the actions (mouse movements and diverted key presses) taken while a mouse gestures button is held down match the arguments of the condition.
Mouse gestures buttons can be set using the 'Key/Button Diversion' setting, by changing the value to `Mouse Gestures`. Mouse gestures buttons can be set using the 'Key/Button Diversion' setting, by changing the value to `Mouse Gestures`.
The arguments of a Mouse Gesture condition can be a direction, i.e., `Mouse Up`, `Mouse Down`, `Mouse Left`, `Mouse Right`, `Mouse Up-Left`, `Mouse Up-Right`, `Mouse Down-Left`, or `Mouse Down-Right`, or the Logitech name of a key. The arguments of a Mouse Gesture condition can be a direction, i.e., `Mouse Up`, `Mouse Down`, `Mouse Left`, `Mouse Right`, `Mouse Up-Left`, `Mouse Up-Right`, `Mouse Down-Left`, or `Mouse Down-Right`, or the Logitech name of a key.
@ -104,24 +115,32 @@ The condition `Smart Shift` -> `Mouse Down` -> `Back Button` would match pressin
Directions and buttons can be mixed and chained together however you like. Directions and buttons can be mixed and chained together however you like.
It's possible to create a `No-op` gesture by clicking 'Delete' on the initial Action when you first create the rule. This gesture will trigger when you simply click a Mouse Gestures button. It's possible to create a `No-op` gesture by clicking 'Delete' on the initial Action when you first create the rule. This gesture will trigger when you simply click a Mouse Gestures button.
### Key modifiers
`Modifiers` conditions take either a string or a sequence of strings, which `Modifiers` conditions take either a string or a sequence of strings, which
can only be `Shift`, `Control`, `Alt`, and `Super`. can only be `Shift`, `Control`, `Alt`, and `Super`.
Modifiers conditions are true if their argument is the current keyboard Modifiers conditions are true if their argument is the current keyboard
modifiers. modifiers.
### Process focused
`Process` conditions are true if the process for the focused input window `Process` conditions are true if the process for the focused input window
or the window's Window manager class or instance name starts with their string argument. or the window's Window manager class or instance name starts with their string argument.
### Window under cursor
`MouseProcess` conditions are true if the process for the window under the mouse `MouseProcess` conditions are true if the process for the window under the mouse
or the window's Window manager class or instance name starts with their string argument. or the window's Window manager class or instance name starts with their string argument.
### Device notification and device active
`Device` conditions are true if a particular device originated the notification. `Device` conditions are true if a particular device originated the notification.
`Active` conditions are true if a particular device is active. `Active` conditions are true if a particular device is active.
`Device` and `Active` conditions take one argument, which is the serial number or unit ID of a device, `Device` and `Active` conditions take one argument, which is the serial number or unit ID of a device,
as shown in Solaar's detail pane. as shown in Solaar's detail pane, or either of its names, as shown by Solaar.
Some older devices do not have a useful serial number or unit ID and so cannot be tested for by these conditions. Some older devices do not have a useful serial number or unit ID and so cannot
distinguished from other devices with the same names.
`Host' conditions are true if the computers hostname starts with the condition's argument. ### Host
`Host` conditions are true if the computers hostname starts with the condition's argument.
### Solaar device setting
`Setting` conditions check the value of a Solaar setting on a device. `Setting` conditions check the value of a Solaar setting on a device.
`Setting` conditions take three or four arguments, depending on the setting: `Setting` conditions take three or four arguments, depending on the setting:
the Serial number or Unit ID of a device, as shown in Solaar's detail pane, the Serial number or Unit ID of a device, as shown in Solaar's detail pane,
@ -147,16 +166,17 @@ For settings that use gestures as an argument the internal name of the gesture i
which can be found in the GESTURE2_GESTURES_LABELS structure in lib/logitech_receiver/settings_templates. which can be found in the GESTURE2_GESTURES_LABELS structure in lib/logitech_receiver/settings_templates.
For boolean settings '~' can be used to toggle the setting. For boolean settings '~' can be used to toggle the setting.
### Test and TestBytes
`Test` and `TestBytes` conditions are true if their test evaluates to true on the feature, `Test` and `TestBytes` conditions are true if their test evaluates to true on the feature,
report, and data of the current notification. report and data of the current notification.
`TestBytes` conditions can return a number instead of a boolean. `TestBytes` conditions can return a number instead of a boolean.
`TestBytes` conditions consist of a sequence of three or four integers and use the first `TestBytes` conditions consist of a sequence of three or four integers and use the first
two to select bytes of the notification data. two to select bytes of the notification data.
Writing this kind of test condition is not trivial. Writing this kind of test condition is not trivial.
Three-element `TestBytes` conditions are true if the selected bytes bit-wise anded Three-element `TestBytes` conditions are true if the selected bytes bit-wise AND
with its third element is non-zero. with its third element is non-zero.
The value of these test conditions is the result of the and. The value of these test conditions is the result of the AND.
Four-element `TestBytes` conditions are true if the selected bytes form a signed Four-element `TestBytes` conditions are true if the selected bytes form a signed
integer between the third and fourth elements. integer between the third and fourth elements.
The value of these conditions is the signed value of the selected bytes The value of these conditions is the signed value of the selected bytes
@ -184,10 +204,13 @@ This displacement is reset when the thumb wheel is inactive.
With a parameter the test is only true if the current thumb wheel displacement is greater than the parameter. With a parameter the test is only true if the current thumb wheel displacement is greater than the parameter.
The displacement is then lessened by the amount of the parameter. The displacement is then lessened by the amount of the parameter.
## Actions
### Key press
A `KeyPress` action takes either the name of an X11 key symbol, such as "a", A `KeyPress` action takes either the name of an X11 key symbol, such as "a",
a list of X11 key symbols, such as "a" or "Control+a", a list of X11 key symbols, such as "a" or "CTRL + A",
or a two-element list with the first element as above or a two-element list with the first element as above
and the second element one of 'click', 'depress', or 'release' and the second element one of `'click'`, `'depress'`, or `'release'`
and executes key actions on a simulated keyboard to produce these symbols. and executes key actions on a simulated keyboard to produce these symbols.
Use separate `KeyPress` actions for multiple characters, Use separate `KeyPress` actions for multiple characters,
i.e., don't use a single `KeyPress` like 'a+b'. i.e., don't use a single `KeyPress` like 'a+b'.
@ -215,38 +238,42 @@ simulate inputting a key symbol.
Unfortunately, this determination can go wrong in several ways and is more likely Unfortunately, this determination can go wrong in several ways and is more likely
to go wrong under Wayland than under X11. to go wrong under Wayland than under X11.
### Mouse scroll
A `MouseScroll` action takes a sequence of two numbers and simulates a horizontal and vertical mouse scroll of these amounts. A `MouseScroll` action takes a sequence of two numbers and simulates a horizontal and vertical mouse scroll of these amounts.
If the previous condition in the parent rule returns a number the scroll amounts are multiplied by this number. If the previous condition in the parent rule returns a number the scroll amounts are multiplied by this number.
### Mouse click
A `MouseClick` action takes a mouse button name (`left`, `middle` or `right`) and a positive number or 'click', 'depress', or 'release'. A `MouseClick` action takes a mouse button name (`left`, `middle` or `right`) and a positive number or 'click', 'depress', or 'release'.
The action simulates that number of clicks of the specified button or just one click, depress, or release of the button. The action simulates that number of clicks of the specified button or just one click, depress, or release of the button.
A `MouseClick` action takes a mouse button name (`left`, `middle` or `right`) and a positive number, and simulates that number of clicks of the specified button. A `MouseClick` action takes a mouse button name (`left`, `middle` or `right`) and a positive number, and simulates that number of clicks of the specified button.
An `Execute` action takes a program and arguments and executes it asynchronously. An `Execute` action takes a program and arguments and executes it asynchronously.
### Set setting
A `Set` action changes a Solaar setting for a device, provided that the device is on-line. A `Set` action changes a Solaar setting for a device, provided that the device is on-line.
`Set` actions take three or four arguments, depending on the setting. `Set` actions take three or four arguments, depending on the setting.
The first two are the Serial number or Unit ID of a device, as shown in Solaar's detail pane, The first two are the Serial number or Unit ID of a device, as shown in Solaar's detail pane,
or null for the device that initiated rule processing; and or null for the device that initiated rule processing; and
the internal name of a setting (which can be found from solaar config \<device\>). the internal name of a setting (which can be found from `solaar config <device>`).
Simple settings take one extra argument, the value to set the setting to. Simple settings take one extra argument, the value to set the setting to.
For boolean settings '~' can be used to toggle the setting. For boolean settings `~` can be used to toggle the setting.
Other simple settings take two extra arguments, a key indicating which sub-setting to set and the value to set it to. Other simple settings take two extra arguments, a key indicating which sub-setting to set and the value to set it to.
For settings that use gestures as an argument the internal name of the gesture is used, For settings that use gestures as an argument the internal name of the gesture is used,
which can be found in the GESTURE2_GESTURES_LABELS structure in lib/logitech_receiver/settings_templates. which can be found in the GESTURE2_GESTURES_LABELS structure in `lib/logitech_receiver/settings_templates`.
All settings are supported. All settings are supported.
### Later
A `Later` action executes rule components later. A `Later` action executes rule components later.
`Later` actions take an integer delay in seconds between 1 and 100 followed by zero or more rule components that will be executed later. `Later` actions take an integer delay in seconds between 1 and 100 followed by zero or more rule components that will be executed later.
Processing of the rest of the rule continues immediately. Processing of the rest of the rule continues immediately.
Solaar has several built-in rules, which are run after user-created rules and so can be overridden by user-created rules. ## Built-in Rules
One rule turns
Solaar has a built-in rule, which is run after user-created rules and so can be overridden by user-created rules.
This rule turns
`Brightness Down` key press notifications into `XF86_MonBrightnessDown` key taps `Brightness Down` key press notifications into `XF86_MonBrightnessDown` key taps
and `Brightness Up` key press notifications into `XF86_MonBrightnessUp` key taps. and `Brightness Up` key press notifications into `XF86_MonBrightnessUp` key taps.
Another rule makes Craft crown ratchet movements move between tabs when the crown is pressed
and up and down otherwise. ## Example Solaar Rule File
A third rule turns Craft crown ratchet movements into `XF86_AudioNext` or `XF86_AudioPrev` key taps when the crown is pressed and `XF86_AudioRaiseVolume` or `XF86_AudioLowerVolume` otherwise.
A fourth rule doubles the speed of `THUMB WHEEL` movements unless the `Control` modifier is on.
All of these rules are only active if the key or feature is diverted, of course.
Solaar reads rules from a YAML configuration file (normally `~/.config/solaar/rules.yaml`). Solaar reads rules from a YAML configuration file (normally `~/.config/solaar/rules.yaml`).
This file contains zero or more documents, each a rule. This file contains zero or more documents, each a rule.
@ -294,10 +321,11 @@ Here is a file with six rules:
... ...
``` ```
## Button diversion example
Here is an example showing how to divert the Back Button on an MX Master 3 so that pressing Here is an example showing how to divert the Back Button on an MX Master 3 so that pressing
the button will initiate rule processing and a rule that triggers on this notification and the button will initiate rule processing and a rule that triggers on this notification and
switches the mouse to host 3 after popping up a simple notification. switches the mouse to host 3 after popping up a simple notification.
![Solaar-divert-back](Solaar-main-window-back-divert.png) ![Solaar-divert-back](screenshots/Solaar-main-window-back-divert.png)
![Solaar-rule-back-host](Solaar-rule-editor.png) ![Solaar-rule-back-host](screenshots/Solaar-rule-editor.png)

View File

Before

Width:  |  Height:  |  Size: 152 KiB

After

Width:  |  Height:  |  Size: 152 KiB

View File

Before

Width:  |  Height:  |  Size: 94 KiB

After

Width:  |  Height:  |  Size: 94 KiB

View File

Before

Width:  |  Height:  |  Size: 70 KiB

After

Width:  |  Height:  |  Size: 70 KiB

View File

Before

Width:  |  Height:  |  Size: 67 KiB

After

Width:  |  Height:  |  Size: 67 KiB

View File

Before

Width:  |  Height:  |  Size: 135 KiB

After

Width:  |  Height:  |  Size: 135 KiB

View File

Before

Width:  |  Height:  |  Size: 69 KiB

After

Width:  |  Height:  |  Size: 69 KiB

View File

Before

Width:  |  Height:  |  Size: 61 KiB

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

View File

Before

Width:  |  Height:  |  Size: 57 KiB

After

Width:  |  Height:  |  Size: 57 KiB

View File

Before

Width:  |  Height:  |  Size: 141 KiB

After

Width:  |  Height:  |  Size: 141 KiB

40
docs/uninstallation.md Normal file
View File

@ -0,0 +1,40 @@
---
title: Uninstalling Solaar
layout: page
---
# Uninstalling Solaar
## Uninstalling from Debian systems
If you installed Solaar using `apt`, you can remove it by running:
```bash
sudo apt remove --purge solaar
```
## Uninstalling from GitHub
If you cloned and installed Solaar from GitHub manually, navigate to the cloned directory and run:
```bash
sudo make uninstall
```
## Removing Configuration Files
Solaar may leave behind configuration files in your home directory. To delete them, run:
```bash
rm -rf ~/.config/solaar
```
## Verifying Uninstallation
To confirm that Solaar is fully removed, try running:
```bash
which solaar
```
If no output is returned, Solaar has been successfully uninstalled.

View File

@ -22,7 +22,7 @@ The following is an image of the Solaar menu and the icon (the battery
symbol is in the system tray at the left of the image). The icon can symbol is in the system tray at the left of the image). The icon can
also be other battery icons or versions of the Logitech Unifying icon. also be other battery icons or versions of the Logitech Unifying icon.
![Solaar-menu](Solaar-menu.png) ![Solaar-menu](screenshots/Solaar-menu.png)
Clicking on “Quit” in the Solaar menu terminates the program. Clicking on “Quit” in the Solaar menu terminates the program.
Clicking on “About Solaar” pops up a window with further information about Solaar. Clicking on “About Solaar” pops up a window with further information about Solaar.
@ -32,10 +32,13 @@ Clicking on “About Solaar” pops up a window with further information about S
There are several options that affect how the Solaar GUI behaves: There are several options that affect how the Solaar GUI behaves:
* `--help` shows a help message and then quits * `--help` shows a help message and then quits
* `--version` shows the version of Solaar and then quits
* `--window=show` starts Solaar with the main window showing * `--window=show` starts Solaar with the main window showing
* `--window=hide` starts Solaar with the main window not showing * `--window=hide` starts Solaar with the main window not showing
* `--window=only` starts Solaar with no system tray icon and the main window showing * `--window=only` starts Solaar with no system tray icon and the main window showing
* `--battery-icons=regular` uses regular icons for battery levels
* `--battery-icons=symbolic` uses symbolic icons for battery levels * `--battery-icons=symbolic` uses symbolic icons for battery levels
* `--battery-icons=solaar` uses only the Solaar icon in the system tray
## Solaar main window ## Solaar main window
@ -61,7 +64,7 @@ To pair with a Bolt receiver you have to type a passcode followed by enter
or click the left and right buttons in the correct sequence followed by or click the left and right buttons in the correct sequence followed by
clicking both buttons simultaneously. clicking both buttons simultaneously.
![Solaar-main-window-receiver](Solaar-main-window-receiver.png) ![Solaar-main-window-receiver](screenshots/Solaar-main-window-receiver.png)
When a device is selected you can unpair the device if your receiver supports When a device is selected you can unpair the device if your receiver supports
unpairing. To unpair the device, just click on the “Unpair” button and unpairing. To unpair the device, just click on the “Unpair” button and
@ -90,26 +93,26 @@ You can also see and change the settings of devices.
Changing settings is performed by clicking on buttons, Changing settings is performed by clicking on buttons,
moving sliders, or selecting from alternatives. moving sliders, or selecting from alternatives.
![Solaar-main-window-keyboard](Solaar-main-window-keyboard.png) ![Solaar-main-window-keyboard](screenshots/Solaar-main-window-keyboard.png)
![Solaar-main-window-mouse](Solaar-main-window-mouse.png) ![Solaar-main-window-mouse](screenshots/Solaar-main-window-mouse.png)
Device settings now have a clickable icon that determines whether the Device settings now have a clickable icon that determines whether the
setting can be changed and whether the setting is ignored. setting can be changed and whether the setting is ignored.
![Solaar-divert-back](Solaar-main-window-back-divert.png) ![Solaar-divert-back](screenshots/Solaar-main-window-back-divert.png)
If the selected device that is paired with a receiver is powered down or If the selected device that is paired with a receiver is powered down or
otherwise disconnected its settings cannot be changed otherwise disconnected its settings cannot be changed
but it still can be unpaired if its receiver allows unpairing. but it still can be unpaired if its receiver allows unpairing.
![Solaar-main-window-offline](Solaar-main-window-offline.png) ![Solaar-main-window-offline](screenshots/Solaar-main-window-offline.png)
If a device is paired with a receiver but directly connected via USB or Bluetooth If a device is paired with a receiver but directly connected via USB or Bluetooth
the receiver pairing will show up as well as the direct connection. the receiver pairing will show up as well as the direct connection.
The device can only be manipulated using the direct connection. The device can only be manipulated using the direct connection.
![Solaar-main-window-multiple](Solaar-main-window-multiple.png) ![Solaar-main-window-multiple](screenshots/Solaar-main-window-multiple.png)
#### Remapping key and button actions #### Remapping key and button actions
@ -124,7 +127,7 @@ action is always the one shown first in the list. As with all settings,
Solaar will remember past action settings and restore them on the device Solaar will remember past action settings and restore them on the device
from then on. from then on.
![Solaar-main-window-actions](Solaar-main-window-button-actions.png) ![Solaar-main-window-actions](screenshots/Solaar-main-window-button-actions.png)
The names of the keys, buttons, and actions are mostly taken from Logitech The names of the keys, buttons, and actions are mostly taken from Logitech
documentation and may not be completely obvious. documentation and may not be completely obvious.
@ -133,9 +136,9 @@ It is possible to end up with an unusable system, for example by having no
way to do a mouse left click, so exercise caution when remapping keys or way to do a mouse left click, so exercise caution when remapping keys or
buttons that are needed to operate your system. buttons that are needed to operate your system.
## Solaar command line interface ## Solaar command-line interface
Solaar also has a command line interface that can do most of what can be Solaar also has a command-line interface that can do most of what can be
done using the main window. For more information on the done using the main window. For more information on the
command line interface, run `solaar --help` to see the commands and command line interface, run `solaar --help` to see the commands and
then `solaar <command> --help` to see the arguments to any of the commands. then `solaar <command> --help` to see the arguments to any of the commands.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 96 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 432 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 230 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

1052
lib/hid_parser/__init__.py Normal file

File diff suppressed because it is too large Load Diff

1086
lib/hid_parser/data.py Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,49 +0,0 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Generic Human Interface Device API."""
import platform as _platform
if _platform.system() in ('Darwin', 'Windows'):
from hidapi.hidapi import close # noqa: F401
from hidapi.hidapi import enumerate # noqa: F401
from hidapi.hidapi import find_paired_node # noqa: F401
from hidapi.hidapi import find_paired_node_wpid # noqa: F401
from hidapi.hidapi import get_manufacturer # noqa: F401
from hidapi.hidapi import get_product # noqa: F401
from hidapi.hidapi import get_serial # noqa: F401
from hidapi.hidapi import monitor_glib # noqa: F401
from hidapi.hidapi import open # noqa: F401
from hidapi.hidapi import open_path # noqa: F401
from hidapi.hidapi import read # noqa: F401
from hidapi.hidapi import write # noqa: F401
else:
from hidapi.udev import close # noqa: F401
from hidapi.udev import enumerate # noqa: F401
from hidapi.udev import find_paired_node # noqa: F401
from hidapi.udev import find_paired_node_wpid # noqa: F401
from hidapi.udev import get_manufacturer # noqa: F401
from hidapi.udev import get_product # noqa: F401
from hidapi.udev import get_serial # noqa: F401
from hidapi.udev import monitor_glib # noqa: F401
from hidapi.udev import open # noqa: F401
from hidapi.udev import open_path # noqa: F401
from hidapi.udev import read # noqa: F401
from hidapi.udev import write # noqa: F401
__version__ = '0.9'

20
lib/hidapi/common.py Normal file
View File

@ -0,0 +1,20 @@
from __future__ import annotations
import dataclasses
@dataclasses.dataclass
class DeviceInfo:
path: str
bus_id: str | None
vendor_id: str
product_id: str
interface: str | None
driver: str | None
manufacturer: str | None
product: str | None
serial: str | None
release: str | None
isDevice: bool
hidpp_short: str | None
hidpp_long: str | None

View File

@ -1,5 +1,3 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
@ -24,46 +22,47 @@ See https://github.com/libusb/hidapi for how to obtain binaries.
Parts of this code are adapted from https://github.com/apmorton/pyhidapi Parts of this code are adapted from https://github.com/apmorton/pyhidapi
which is MIT licensed. which is MIT licensed.
""" """
from __future__ import annotations
import atexit import atexit
import ctypes import ctypes
import logging import logging
import platform as _platform import platform
import typing
from collections import namedtuple
from threading import Thread from threading import Thread
from time import sleep from time import sleep
from typing import Any
from typing import Callable
from hidapi.common import DeviceInfo
if typing.TYPE_CHECKING:
import gi
gi.require_version("Gdk", "3.0")
from gi.repository import GLib # NOQA: E402
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
native_implementation = 'hidapi' ACTION_ADD = "add"
ACTION_REMOVE = "remove"
# Device info as expected by Solaar
DeviceInfo = namedtuple(
'DeviceInfo', [
'path',
'bus_id',
'vendor_id',
'product_id',
'interface',
'driver',
'manufacturer',
'product',
'serial',
'release',
'isDevice',
'hidpp_short',
'hidpp_long',
]
)
del namedtuple
# Global handle to hidapi # Global handle to hidapi
_hidapi = None _hidapi = None
# hidapi binary names for various platforms # hidapi binary names for various platforms
_library_paths = ( _library_paths = (
'libhidapi-hidraw.so', 'libhidapi-hidraw.so.0', 'libhidapi-libusb.so', 'libhidapi-libusb.so.0', "libhidapi-hidraw.so",
'libhidapi-iohidmanager.so', 'libhidapi-iohidmanager.so.0', 'libhidapi.dylib', 'hidapi.dll', 'libhidapi-0.dll' "libhidapi-hidraw.so.0",
"libhidapi-libusb.so",
"libhidapi-libusb.so.0",
"libhidapi-iohidmanager.so",
"libhidapi-iohidmanager.so.0",
"libhidapi.dylib",
"hidapi.dll",
"libhidapi-0.dll",
) )
for lib in _library_paths: for lib in _library_paths:
@ -73,15 +72,15 @@ for lib in _library_paths:
except OSError: except OSError:
pass pass
else: else:
raise ImportError(f"Unable to load hdiapi library, tried: {' '.join(_library_paths)}") raise ImportError(f"Unable to load hidapi library, tried: {' '.join(_library_paths)}")
# Retrieve version of hdiapi library # Retrieve version of hdiapi library
class _cHidApiVersion(ctypes.Structure): class _cHidApiVersion(ctypes.Structure):
_fields_ = [ _fields_ = [
('major', ctypes.c_int), ("major", ctypes.c_int),
('minor', ctypes.c_int), ("minor", ctypes.c_int),
('patch', ctypes.c_int), ("patch", ctypes.c_int),
] ]
@ -92,28 +91,27 @@ _hid_version = _hidapi.hid_version()
# Construct device info struct based on API version # Construct device info struct based on API version
class _cDeviceInfo(ctypes.Structure): class _cDeviceInfo(ctypes.Structure):
def as_dict(self): def as_dict(self):
return {name: getattr(self, name) for name, _t in self._fields_ if name != 'next'} return {name: getattr(self, name) for name, _t in self._fields_ if name != "next"}
# Low level hdiapi device info struct # Low level hdiapi device info struct
# See https://github.com/libusb/hidapi/blob/master/hidapi/hidapi.h#L143 # See https://github.com/libusb/hidapi/blob/master/hidapi/hidapi.h#L143
_cDeviceInfo_fields = [ _cDeviceInfo_fields = [
('path', ctypes.c_char_p), ("path", ctypes.c_char_p),
('vendor_id', ctypes.c_ushort), ("vendor_id", ctypes.c_ushort),
('product_id', ctypes.c_ushort), ("product_id", ctypes.c_ushort),
('serial_number', ctypes.c_wchar_p), ("serial_number", ctypes.c_wchar_p),
('release_number', ctypes.c_ushort), ("release_number", ctypes.c_ushort),
('manufacturer_string', ctypes.c_wchar_p), ("manufacturer_string", ctypes.c_wchar_p),
('product_string', ctypes.c_wchar_p), ("product_string", ctypes.c_wchar_p),
('usage_page', ctypes.c_ushort), ("usage_page", ctypes.c_ushort),
('usage', ctypes.c_ushort), ("usage", ctypes.c_ushort),
('interface_number', ctypes.c_int), ("interface_number", ctypes.c_int),
('next', ctypes.POINTER(_cDeviceInfo)), ("next", ctypes.POINTER(_cDeviceInfo)),
] ]
if _hid_version.contents.major >= 0 and _hid_version.contents.minor >= 13: if _hid_version.contents.major >= 0 and _hid_version.contents.minor >= 13:
_cDeviceInfo_fields.append(('bus_type', ctypes.c_int)) _cDeviceInfo_fields.append(("bus_type", ctypes.c_int))
_cDeviceInfo._fields_ = _cDeviceInfo_fields _cDeviceInfo._fields_ = _cDeviceInfo_fields
# Set up hidapi functions # Set up hidapi functions
@ -163,7 +161,7 @@ atexit.register(_hidapi.hid_exit)
# Solaar opens the same device more than once which will fail unless we # Solaar opens the same device more than once which will fail unless we
# allow non-exclusive opening. On windows opening with shared access is # allow non-exclusive opening. On windows opening with shared access is
# the default, for macOS we need to set it explicitly. # the default, for macOS we need to set it explicitly.
if _platform.system() == 'Darwin': if platform.system() == "Darwin":
_hidapi.hid_darwin_set_open_exclusive.argtypes = [ctypes.c_int] _hidapi.hid_darwin_set_open_exclusive.argtypes = [ctypes.c_int]
_hidapi.hid_darwin_set_open_exclusive.restype = None _hidapi.hid_darwin_set_open_exclusive.restype = None
_hidapi.hid_darwin_set_open_exclusive(0) _hidapi.hid_darwin_set_open_exclusive(0)
@ -183,19 +181,12 @@ def _enumerate_devices():
p = p.contents.next p = p.contents.next
_hidapi.hid_free_enumeration(c_devices) _hidapi.hid_free_enumeration(c_devices)
keyboard_or_mouse = {d['path'] for d in devices if d['usage_page'] == 1 and d['usage'] in (6, 2)}
unique_devices = {} unique_devices = {}
for device in devices: for device in devices:
# On macOS we cannot access keyboard or mouse devices without special permissions. Since
# we don't need them anyway we remove them so opening them doesn't cause errors later.
if device['path'] in keyboard_or_mouse:
# print(f"Ignoring keyboard or mouse device: {device}")
continue
# hidapi returns separate entries for each usage page of a device. # hidapi returns separate entries for each usage page of a device.
# Deduplicate by path to only keep one device entry. # Deduplicate by path to only keep one device entry.
if device['path'] not in unique_devices: if device["path"] not in unique_devices:
unique_devices[device['path']] = device unique_devices[device["path"]] = device
unique_devices = unique_devices.values() unique_devices = unique_devices.values()
# print("Unique devices:\n" + '\n'.join([f"{dev}" for dev in unique_devices])) # print("Unique devices:\n" + '\n'.join([f"{dev}" for dev in unique_devices]))
@ -204,10 +195,10 @@ def _enumerate_devices():
# Use a separate thread to check if devices have been removed or connected # Use a separate thread to check if devices have been removed or connected
class _DeviceMonitor(Thread): class _DeviceMonitor(Thread):
def __init__(self, device_callback, polling_delay=5.0): def __init__(self, device_callback, polling_delay=5.0):
self.device_callback = device_callback self.device_callback = device_callback
self.polling_delay = polling_delay self.polling_delay = polling_delay
self.prev_devices = None
# daemon threads are automatically killed when main thread exits # daemon threads are automatically killed when main thread exits
super().__init__(daemon=True) super().__init__(daemon=True)
@ -220,118 +211,167 @@ class _DeviceMonitor(Thread):
current_devices = {tuple(dev.items()): dev for dev in _enumerate_devices()} current_devices = {tuple(dev.items()): dev for dev in _enumerate_devices()}
for key, device in self.prev_devices.items(): for key, device in self.prev_devices.items():
if key not in current_devices: if key not in current_devices:
self.device_callback('remove', device) self.device_callback(ACTION_REMOVE, device)
for key, device in current_devices.items(): for key, device in current_devices.items():
if key not in self.prev_devices: if key not in self.prev_devices:
self.device_callback('add', device) self.device_callback(ACTION_ADD, device)
self.prev_devices = current_devices self.prev_devices = current_devices
sleep(self.polling_delay) sleep(self.polling_delay)
# The filterfn is used to determine whether this is a device of interest to Solaar. def _match(
# It is given the bus id, vendor id, and product id and returns a dictionary action: str,
# with the required hid_driver and usb_interface and whether this is a receiver or device. device: dict[str, Any],
def _match(action, device, filterfn): filter_func: Callable[[int, int, int, bool, bool], dict[str, Any]],
vid = device['vendor_id'] ):
pid = device['product_id'] """
The filter_func is used to determine whether this is a device of
interest to Solaar. It is given the bus id, vendor id, and product
id and returns a dictionary with the required hid_driver and
usb_interface and whether this is a receiver or device.
"""
vid = device["vendor_id"]
pid = device["product_id"]
hid_bus_type = device["bus_type"]
# Translate hidapi bus_type to the bus_id values Solaar expects # Translate hidapi bus_type to the bus_id values Solaar expects
if device.get('bus_type') == 0x01: if device.get("bus_type") == 0x01:
bus_id = 0x03 # USB bus_id = 0x03 # USB
elif device.get('bus_type') == 0x02: elif device.get("bus_type") == 0x02:
bus_id = 0x05 # Bluetooth bus_id = 0x05 # Bluetooth
else: else:
bus_id = None bus_id = None
logger.info(f"Device {device['path']} has an unsupported bus type {hid_bus_type:02X}")
return None
# Skip unlikely devices with all-zero VID PID or unsupported bus IDs
if vid == 0 and pid == 0:
logger.info(f"Device {device['path']} has all-zero VID and PID")
logger.info(f"Skipping unlikely device {device['path']} ({bus_id}/{vid:04X}/{pid:04X})")
return None
# Check for hidpp support # Check for hidpp support
device['hidpp_short'] = False device["hidpp_short"] = False
device['hidpp_long'] = False device["hidpp_long"] = False
device_handle = None device_handle = None
try:
device_handle = open_path(device['path']) def check_hidpp_short():
report = get_input_report(device_handle, 0x10, 32) report = _get_input_report(device_handle, 0x10, 32)
if len(report) == 1 + 6 and report[0] == 0x10: if len(report) == 1 + 6 and report[0] == 0x10:
device['hidpp_short'] = True device["hidpp_short"] = True
report = get_input_report(device_handle, 0x11, 32)
def check_hidpp_long():
report = _get_input_report(device_handle, 0x11, 32)
if len(report) == 1 + 19 and report[0] == 0x11: if len(report) == 1 + 19 and report[0] == 0x11:
device['hidpp_long'] = True device["hidpp_long"] = True
except HIDError as e: # noqa: F841
if logger.isEnabledFor(logging.INFO): try:
device_handle = open_path(device["path"])
for check_func in (check_hidpp_short, check_hidpp_long):
try:
check_func()
except HIDError as e:
logger.info(
f"Error while {check_func.__name__}"
f"on device {device['path']} ({bus_id}/{vid:04X}/{pid:04X}) for hidpp check: {e}"
)
except HIDError as e:
logger.info(f"Error opening device {device['path']} ({bus_id}/{vid:04X}/{pid:04X}) for hidpp check: {e}") logger.info(f"Error opening device {device['path']} ({bus_id}/{vid:04X}/{pid:04X}) for hidpp check: {e}")
finally: finally:
if device_handle: if device_handle:
close(device_handle) close(device_handle)
if logger.isEnabledFor(logging.INFO):
logger.info( logger.info(
'Found device BID %s VID %04X PID %04X HID++ %s %s', bus_id, vid, pid, device['hidpp_short'], device['hidpp_long'] "Found device BID %s VID %04X PID %04X HID++ SHORT %s LONG %s",
bus_id,
vid,
pid,
device["hidpp_short"],
device["hidpp_long"],
) )
if not device['hidpp_short'] and not device['hidpp_long']: if not device["hidpp_short"] and not device["hidpp_long"]:
return None return None
filter = filterfn(bus_id, vid, pid, device['hidpp_short'], device['hidpp_long']) filtered_result = filter_func(bus_id, vid, pid, device["hidpp_short"], device["hidpp_long"])
if not filter: if not filtered_result:
return return
isDevice = filter.get('isDevice') is_device = filtered_result.get("isDevice")
if action == 'add': if action == ACTION_ADD:
d_info = DeviceInfo( d_info = DeviceInfo(
path=device['path'].decode(), path=device["path"].decode(),
bus_id=bus_id, bus_id=bus_id,
vendor_id=f'{vid:04X}', vendor_id=f"{vid:04X}", # noqa
product_id=f'{pid:04X}', product_id=f"{pid:04X}", # noqa
interface=None, interface=None,
driver=None, driver=None,
manufacturer=device['manufacturer_string'], manufacturer=device["manufacturer_string"],
product=device['product_string'], product=device["product_string"],
serial=device['serial_number'], serial=device["serial_number"],
release=device['release_number'], release=device["release_number"],
isDevice=isDevice, isDevice=is_device,
hidpp_short=device['hidpp_short'], hidpp_short=device["hidpp_short"],
hidpp_long=device['hidpp_long'], hidpp_long=device["hidpp_long"],
) )
return d_info return d_info
elif action == 'remove': elif action == ACTION_REMOVE:
d_info = DeviceInfo( d_info = DeviceInfo(
path=device['path'].decode(), path=device["path"].decode(),
bus_id=None, bus_id=None,
vendor_id=f'{vid:04X}', vendor_id=f"{vid:04X}", # noqa
product_id=f'{pid:04X}', product_id=f"{pid:04X}", # noqa
interface=None, interface=None,
driver=None, driver=None,
manufacturer=None, manufacturer=None,
product=None, product=None,
serial=None, serial=None,
release=None, release=None,
isDevice=isDevice, isDevice=is_device,
hidpp_short=None, hidpp_short=None,
hidpp_long=None, hidpp_long=None,
) )
return d_info return d_info
logger.info(f"Finished checking HIDPP support for device {device['path']} ({bus_id}/{vid:04X}/{pid:04X})")
def find_paired_node(receiver_path, index, timeout):
def find_paired_node(receiver_path: str, index: int, timeout: int):
"""Find the node of a device paired with a receiver""" """Find the node of a device paired with a receiver"""
return None return None
def find_paired_node_wpid(receiver_path, index): def find_paired_node_wpid(receiver_path: str, index: int):
"""Find the node of a device paired with a receiver, get wpid from udev""" """Find the node of a device paired with a receiver, get wpid from udev"""
return None return None
def monitor_glib(callback, filterfn): def monitor_glib(
from gi.repository import GLib glib: GLib,
callback: Callable,
filter_func: Callable[[int, int, int, bool, bool], dict[str, Any]],
) -> None:
"""Monitor GLib.
def device_callback(action, device): Parameters
# print(f"device_callback({action}): {device}") ----------
if action == 'add': glib
d_info = _match(action, device, filterfn) GLib instance.
callback
Called when device found.
filter_func
Filter devices callback.
"""
def device_callback(action: str, device):
if action == ACTION_ADD:
d_info = _match(action, device, filter_func)
if d_info: if d_info:
GLib.idle_add(callback, action, d_info) glib.idle_add(callback, action, d_info)
elif action == 'remove': elif action == ACTION_REMOVE:
# Removed devices will be detected by Solaar directly # Removed devices will be detected by Solaar directly
pass pass
@ -339,7 +379,7 @@ def monitor_glib(callback, filterfn):
monitor.start() monitor.start()
def enumerate(filterfn): def enumerate(filter_func) -> DeviceInfo:
"""Enumerate the HID Devices. """Enumerate the HID Devices.
List all the HID devices attached to the system, optionally filtering by List all the HID devices attached to the system, optionally filtering by
@ -348,7 +388,7 @@ def enumerate(filterfn):
:returns: a list of matching ``DeviceInfo`` tuples. :returns: a list of matching ``DeviceInfo`` tuples.
""" """
for device in _enumerate_devices(): for device in _enumerate_devices():
d_info = _match('add', device, filterfn) d_info = _match(ACTION_ADD, device, filter_func)
if d_info: if d_info:
yield d_info yield d_info
@ -369,7 +409,7 @@ def open(vendor_id, product_id, serial=None):
return device_handle return device_handle
def open_path(device_path): def open_path(device_path: str) -> int:
"""Open a HID device by its path name. """Open a HID device by its path name.
:param device_path: the path of a ``DeviceInfo`` tuple returned by enumerate(). :param device_path: the path of a ``DeviceInfo`` tuple returned by enumerate().
@ -385,7 +425,7 @@ def open_path(device_path):
return device_handle return device_handle
def close(device_handle): def close(device_handle) -> None:
"""Close a HID device. """Close a HID device.
:param device_handle: a device handle returned by open() or open_path(). :param device_handle: a device handle returned by open() or open_path().
@ -394,7 +434,7 @@ def close(device_handle):
_hidapi.hid_close(device_handle) _hidapi.hid_close(device_handle)
def write(device_handle, data): def write(device_handle: int, data: bytes) -> int:
"""Write an Output report to a HID device. """Write an Output report to a HID device.
:param device_handle: a device handle returned by open() or open_path(). :param device_handle: a device handle returned by open() or open_path().
@ -451,12 +491,11 @@ def read(device_handle, bytes_count, timeout_ms=None):
if bytes_read < 0: if bytes_read < 0:
raise HIDError(_hidapi.hid_error(device_handle)) raise HIDError(_hidapi.hid_error(device_handle))
return None
return data.raw[:bytes_read] return data.raw[:bytes_read]
def get_input_report(device_handle, report_id, size): def _get_input_report(device_handle, report_id, size):
assert device_handle assert device_handle
data = ctypes.create_string_buffer(size) data = ctypes.create_string_buffer(size)
data[0] = bytearray((report_id,)) data[0] = bytearray((report_id,))
@ -471,7 +510,7 @@ def _readstring(device_handle, func, max_length=255):
buf = ctypes.create_unicode_buffer(max_length) buf = ctypes.create_unicode_buffer(max_length)
ret = func(device_handle, buf, max_length) ret = func(device_handle, buf, max_length)
if ret < 0: if ret < 0:
raise HIDError('Error reading device property') raise HIDError("Error reading device property")
return buf.value return buf.value

View File

@ -1,5 +1,3 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
@ -16,47 +14,46 @@
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import argparse
import os import os
import os.path
import platform
import readline
import sys import sys
import time import time
from binascii import hexlify, unhexlify from binascii import hexlify
from select import select as _select from binascii import unhexlify
from select import select
from threading import Lock from threading import Lock
from threading import Thread
import hidapi as _hid if platform.system() == "Linux":
import hidapi.udev_impl as hidapi
else:
import hidapi.hidapi_impl as hidapi
# LOGITECH_VENDOR_ID = 0x046D
#
#
try:
read_packet = raw_input
except NameError:
# Python 3 equivalent of raw_input
read_packet = input
interactive = os.isatty(0) interactive = os.isatty(0)
prompt = '?? Input: ' if interactive else '' prompt = "?? Input: " if interactive else ""
start_time = time.time() start_time = time.time()
strhex = lambda d: hexlify(d).decode('ascii').upper()
# def strhex(d):
# return hexlify(d).decode("ascii").upper()
#
print_lock = Lock() print_lock = Lock()
del Lock
def _print(marker, data, scroll=False): def _print(marker, data, scroll=False):
t = time.time() - start_time t = time.time() - start_time
if isinstance(data, str): if isinstance(data, str):
s = marker + ' ' + data s = f"{marker} {data}"
else: else:
hexs = strhex(data) hexs = strhex(data)
s = '%s (% 8.3f) [%s %s %s %s] %s' % (marker, t, hexs[0:2], hexs[2:4], hexs[4:8], hexs[8:], repr(data)) s = "%s (% 8.3f) [%s %s %s %s] %s" % (marker, t, hexs[0:2], hexs[2:4], hexs[4:8], hexs[8:], repr(data))
with print_lock: with print_lock:
# allow only one thread at a time to write to the console, otherwise # allow only one thread at a time to write to the console, otherwise
@ -65,18 +62,18 @@ def _print(marker, data, scroll=False):
if interactive and scroll: if interactive and scroll:
# scroll the entire screen above the current line up by 1 line # scroll the entire screen above the current line up by 1 line
sys.stdout.write( sys.stdout.write(
'\033[s' # save cursor position "\033[s" # save cursor position
'\033[S' # scroll up "\033[S" # scroll up
'\033[A' # cursor up "\033[A" # cursor up
'\033[L' # insert 1 line "\033[L" # insert 1 line
'\033[G' "\033[G"
) # move cursor to column 1 ) # move cursor to column 1
sys.stdout.write(s) sys.stdout.write(s)
if interactive and scroll: if interactive and scroll:
# restore cursor position # restore cursor position
sys.stdout.write('\033[u') sys.stdout.write("\033[u")
else: else:
sys.stdout.write('\n') sys.stdout.write("\n")
# flush stdout manually... # flush stdout manually...
# because trying to open stdin/out unbuffered programmatically # because trying to open stdin/out unbuffered programmatically
@ -85,106 +82,99 @@ def _print(marker, data, scroll=False):
def _error(text, scroll=False): def _error(text, scroll=False):
_print('!!', text, scroll) _print("!!", text, scroll)
def _continuous_read(handle, timeout=2000): def _continuous_read(handle, timeout=2000):
while True: while True:
try: try:
reply = _hid.read(handle, 128, timeout) reply = hidapi.read(handle, 128, timeout)
except OSError as e: except OSError as e:
_error('Read failed, aborting: ' + str(e), True) _error(f"Read failed, aborting: {str(e)}", True)
break break
assert reply is not None assert reply is not None
if reply: if reply:
_print('>>', reply, True) _print(">>", reply, True)
def _validate_input(line, hidpp=False): def _validate_input(line, hidpp=False):
try: try:
data = unhexlify(line.encode('ascii')) data = unhexlify(line.encode("ascii"))
except Exception as e: except Exception as e:
_error('Invalid input: ' + str(e)) _error(f"Invalid input: {str(e)}")
return None return None
if hidpp: if hidpp:
if len(data) < 4: if len(data) < 4:
_error('Invalid HID++ request: need at least 4 bytes') _error("Invalid HID++ request: need at least 4 bytes")
return None return None
if data[:1] not in b'\x10\x11': if data[:1] not in b"\x10\x11":
_error('Invalid HID++ request: first byte must be 0x10 or 0x11') _error("Invalid HID++ request: first byte must be 0x10 or 0x11")
return None return None
if data[1:2] not in b'\xFF\x00\x01\x02\x03\x04\x05\x06\x07': if data[1:2] not in b"\xff\x00\x01\x02\x03\x04\x05\x06\x07":
_error('Invalid HID++ request: second byte must be 0xFF or one of 0x00..0x07') _error("Invalid HID++ request: second byte must be 0xFF or one of 0x00..0x07")
return None return None
if data[:1] == b'\x10': if data[:1] == b"\x10":
if len(data) > 7: if len(data) > 7:
_error('Invalid HID++ request: maximum length of a 0x10 request is 7 bytes') _error("Invalid HID++ request: maximum length of a 0x10 request is 7 bytes")
return None return None
while len(data) < 7: while len(data) < 7:
data = (data + b'\x00' * 7)[:7] data = (data + b"\x00" * 7)[:7]
elif data[:1] == b'\x11': elif data[:1] == b"\x11":
if len(data) > 20: if len(data) > 20:
_error('Invalid HID++ request: maximum length of a 0x11 request is 20 bytes') _error("Invalid HID++ request: maximum length of a 0x11 request is 20 bytes")
return None return None
while len(data) < 20: while len(data) < 20:
data = (data + b'\x00' * 20)[:20] data = (data + b"\x00" * 20)[:20]
return data return data
def _open(args): def _open(args):
def matchfn(bid, vid, pid, _a, _b): def matchfn(bid, vid, pid, _a, _b):
if vid == 0x046d: if vid == LOGITECH_VENDOR_ID:
return {'vid': 0x046d} return {"vid": vid}
device = args.device device = args.device
if args.hidpp and not device: if args.hidpp and not device:
for d in _hid.enumerate(matchfn): for d in hidapi.enumerate(matchfn):
if d.driver == 'logitech-djreceiver': if d.driver == "logitech-djreceiver":
device = d.path device = d.path
break break
if not device: if not device:
sys.exit('!! No HID++ receiver found.') sys.exit("!! No HID++ receiver found.")
if not device: if not device:
sys.exit('!! Device path required.') sys.exit("!! Device path required.")
print('.. Opening device', device) print(".. Opening device", device)
handle = _hid.open_path(device) handle = hidapi.open_path(device)
if not handle: if not handle:
sys.exit('!! Failed to open %s, aborting.' % device) sys.exit(f"!! Failed to open {device}, aborting.")
print( print(
'.. Opened handle %r, vendor %r product %r serial %r.' % ".. Opened handle %r, vendor %r product %r serial %r."
(handle, _hid.get_manufacturer(handle), _hid.get_product(handle), _hid.get_serial(handle)) % (handle, hidapi.get_manufacturer(handle), hidapi.get_product(handle), hidapi.get_serial(handle))
) )
if args.hidpp: if args.hidpp:
if _hid.get_manufacturer(handle) is not None and _hid.get_manufacturer(handle) != b'Logitech': if hidapi.get_manufacturer(handle) is not None and hidapi.get_manufacturer(handle) != b"Logitech":
sys.exit('!! Only Logitech devices support the HID++ protocol.') sys.exit("!! Only Logitech devices support the HID++ protocol.")
print('.. HID++ validation enabled.') print(".. HID++ validation enabled.")
else: else:
if (_hid.get_manufacturer(handle) == b'Logitech' and b'Receiver' in _hid.get_product(handle)): if hidapi.get_manufacturer(handle) == b"Logitech" and b"Receiver" in hidapi.get_product(handle):
args.hidpp = True args.hidpp = True
print('.. Logitech receiver detected, HID++ validation enabled.') print(".. Logitech receiver detected, HID++ validation enabled.")
return handle return handle
#
#
#
def _parse_arguments(): def _parse_arguments():
import argparse
arg_parser = argparse.ArgumentParser() arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--history', help='history file (default ~/.hidconsole-history)') arg_parser.add_argument("--history", help="history file (default ~/.hidconsole-history)")
arg_parser.add_argument('--hidpp', action='store_true', help='ensure input data is a valid HID++ request') arg_parser.add_argument("--hidpp", action="store_true", help="ensure input data is a valid HID++ request")
arg_parser.add_argument( arg_parser.add_argument(
'device', "device",
nargs='?', nargs="?",
help='linux device to connect to (/dev/hidrawX); ' help="linux device to connect to (/dev/hidrawX); "
'may be omitted if --hidpp is given, in which case it looks for the first Logitech receiver' "may be omitted if --hidpp is given, in which case it looks for the first Logitech receiver",
) )
return arg_parser.parse_args() return arg_parser.parse_args()
@ -194,12 +184,10 @@ def main():
handle = _open(args) handle = _open(args)
if interactive: if interactive:
print('.. Press ^C/^D to exit, or type hex bytes to write to the device.') print(".. Press ^C/^D to exit, or type hex bytes to write to the device.")
import readline
if args.history is None: if args.history is None:
import os.path args.history = os.path.join(os.path.expanduser("~"), ".hidconsole-history")
args.history = os.path.join(os.path.expanduser('~'), '.hidconsole-history')
try: try:
readline.read_history_file(args.history) readline.read_history_file(args.history)
except Exception: except Exception:
@ -207,18 +195,17 @@ def main():
pass pass
try: try:
from threading import Thread
t = Thread(target=_continuous_read, args=(handle,)) t = Thread(target=_continuous_read, args=(handle,))
t.daemon = True t.daemon = True
t.start() t.start()
if interactive: if interactive:
# move the cursor at the bottom of the screen # move the cursor at the bottom of the screen
sys.stdout.write('\033[300B') # move cusor at most 300 lines down, don't scroll sys.stdout.write("\033[300B") # move cusor at most 300 lines down, don't scroll
while t.is_alive(): while t.is_alive():
line = read_packet(prompt) line = input(prompt)
line = line.strip().replace(' ', '') line = line.strip().replace(" ", "")
# print ("line", line) # print ("line", line)
if not line: if not line:
continue continue
@ -227,12 +214,12 @@ def main():
if data is None: if data is None:
continue continue
_print('<<', data) _print("<<", data)
_hid.write(handle, data) hidapi.write(handle, data)
# wait for some kind of reply # wait for some kind of reply
if args.hidpp and not interactive: if args.hidpp and not interactive:
rlist, wlist, xlist = _select([handle], [], [], 1) rlist, wlist, xlist = select([handle], [], [], 1)
if data[1:2] == b'\xFF': if data[1:2] == b"\xff":
# the receiver will reply very fast, in a few milliseconds # the receiver will reply very fast, in a few milliseconds
time.sleep(0.010) time.sleep(0.010)
else: else:
@ -240,16 +227,16 @@ def main():
time.sleep(0.700) time.sleep(0.700)
except EOFError: except EOFError:
if interactive: if interactive:
print('') print("")
else: else:
time.sleep(1) time.sleep(1)
finally: finally:
print('.. Closing handle %r' % handle) print(f".. Closing handle {handle!r}")
_hid.close(handle) hidapi.close(handle)
if interactive: if interactive:
readline.write_history_file(args.history) readline.write_history_file(args.history)
if __name__ == '__main__': if __name__ == "__main__":
main() main()

View File

@ -1,5 +1,3 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
@ -15,6 +13,7 @@
## You should have received a copy of the GNU General Public License along ## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Generic Human Interface Device API. """Generic Human Interface Device API.
It is currently a partial pure-Python implementation of the native HID API It is currently a partial pure-Python implementation of the native HID API
@ -24,46 +23,37 @@ The docstrings are mostly copied from the hidapi API header, with changes where
necessary. necessary.
""" """
import errno as _errno from __future__ import annotations
import errno
import logging import logging
import os as _os import os
import warnings as _warnings import typing
import warnings
# the tuple object we'll expose when enumerating devices # the tuple object we'll expose when enumerating devices
from collections import namedtuple from select import select
from select import select as _select
from time import sleep from time import sleep
from time import time as _timestamp from time import time
from typing import Callable
from pyudev import Context as _Context import pyudev
from pyudev import Device as _Device
from pyudev import DeviceNotFoundError from hidapi.common import DeviceInfo
from pyudev import Devices as _Devices
from pyudev import Monitor as _Monitor if typing.TYPE_CHECKING:
import gi
gi.require_version("Gdk", "3.0")
from gi.repository import GLib # NOQA: E402
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
native_implementation = 'udev'
fileopen = open fileopen = open
DeviceInfo = namedtuple( ACTION_ADD = "add"
'DeviceInfo', [ ACTION_REMOVE = "remove"
'path',
'bus_id',
'vendor_id',
'product_id',
'interface',
'driver',
'manufacturer',
'product',
'serial',
'release',
'isDevice',
'hidpp_short',
'hidpp_long',
]
)
del namedtuple
# #
# exposed API # exposed API
@ -89,31 +79,34 @@ def exit():
return True return True
# The filterfn is used to determine whether this is a device of interest to Solaar. def _match(action: str, device, filter_func: typing.Callable[[int, int, int, bool, bool], dict[str, typing.Any]]):
# It is given the bus id, vendor id, and product id and returns a dictionary """
# with the required hid_driver and usb_interface and whether this is a receiver or device.
def _match(action, device, filterfn): The filter_func is used to determine whether this is a device of
hid_device = device.find_parent('hid') interest to Solaar. It is given the bus id, vendor id, and product
if not hid_device: # only HID devices are of interest to Solaar id and returns a dictionary with the required hid_driver and
usb_interface and whether this is a receiver or device."""
logger.debug(f"Dbus event {action} {device}")
hid_device = device.find_parent("hid")
if hid_device is None: # only HID devices are of interest to Solaar
return return
hid_id = hid_device.get('HID_ID') hid_id = hid_device.properties.get("HID_ID")
if not hid_id: if not hid_id:
return # there are reports that sometimes the id isn't set up right so be defensive return # there are reports that sometimes the id isn't set up right so be defensive
bid, vid, pid = hid_id.split(':') bid, vid, pid = hid_id.split(":")
hid_hid_device = hid_device.find_parent('hid') hid_hid_device = hid_device.find_parent("hid")
if hid_hid_device: if hid_hid_device is not None:
return # these are devices connected through a receiver so don't pick them up here return # these are devices connected through a receiver so don't pick them up here
try: # if report descriptor does not indicate HID++ capabilities then this device is not of interest to Solaar try: # if report descriptor does not indicate HID++ capabilities then this device is not of interest to Solaar
from hid_parser import ReportDescriptor as _ReportDescriptor from hid_parser import ReportDescriptor
# from hid_parser import Usage as _Usage
hidpp_short = hidpp_long = False hidpp_short = hidpp_long = False
devfile = '/sys' + hid_device.get('DEVPATH') + '/report_descriptor' devfile = "/sys" + hid_device.properties.get("DEVPATH") + "/report_descriptor"
with fileopen(devfile, 'rb') as fd: with fileopen(devfile, "rb") as fd:
with _warnings.catch_warnings(): with warnings.catch_warnings():
_warnings.simplefilter('ignore') warnings.simplefilter("ignore")
rd = _ReportDescriptor(fd.read()) rd = ReportDescriptor(fd.read())
hidpp_short = 0x10 in rd.input_report_ids and 6 * 8 == int(rd.get_input_report_size(0x10)) hidpp_short = 0x10 in rd.input_report_ids and 6 * 8 == int(rd.get_input_report_size(0x10))
# and _Usage(0xFF00, 0x0001) in rd.get_input_items(0x10)[0].usages # be more permissive # and _Usage(0xFF00, 0x0001) in rd.get_input_items(0x10)[0].usages # be more permissive
hidpp_long = 0x11 in rd.input_report_ids and 19 * 8 == int(rd.get_input_report_size(0x11)) hidpp_long = 0x11 in rd.input_report_ids and 19 * 8 == int(rd.get_input_report_size(0x11))
@ -121,39 +114,42 @@ def _match(action, device, filterfn):
if not hidpp_short and not hidpp_long: if not hidpp_short and not hidpp_long:
return return
except Exception as e: # if can't process report descriptor fall back to old scheme except Exception as e: # if can't process report descriptor fall back to old scheme
hidpp_short = hidpp_long = None hidpp_short = None
logger.warning( hidpp_long = None
'Report Descriptor not processed for DEVICE %s BID %s VID %s PID %s: %s', device.device_node, bid, vid, pid, e logger.info(
"Report Descriptor not processed for DEVICE %s BID %s VID %s PID %s: %s",
device.device_node,
bid,
vid,
pid,
e,
) )
filter = filterfn(int(bid, 16), int(vid, 16), int(pid, 16), hidpp_short, hidpp_long) filtered_result = filter_func(int(bid, 16), int(vid, 16), int(pid, 16), hidpp_short, hidpp_long)
if not filter: if not filtered_result:
return return
hid_driver = filter.get('hid_driver') interface_number = filtered_result.get("usb_interface")
interface_number = filter.get('usb_interface') isDevice = filtered_result.get("isDevice")
isDevice = filter.get('isDevice')
if action == 'add': if action == ACTION_ADD:
hid_driver_name = hid_device.get('DRIVER') hid_driver_name = hid_device.properties.get("DRIVER")
# print ("** found hid", action, device, "hid:", hid_device, hid_driver_name) intf_device = device.find_parent("usb", "usb_interface")
if hid_driver: usb_interface = None if intf_device is None else intf_device.attributes.asint("bInterfaceNumber")
if isinstance(hid_driver, tuple):
if hid_driver_name not in hid_driver:
return
elif hid_driver_name != hid_driver:
return
intf_device = device.find_parent('usb', 'usb_interface')
usb_interface = None if intf_device is None else intf_device.attributes.asint('bInterfaceNumber')
# print('*** usb interface', action, device, 'usb_interface:', intf_device, usb_interface, interface_number) # print('*** usb interface', action, device, 'usb_interface:', intf_device, usb_interface, interface_number)
if logger.isEnabledFor(logging.INFO):
logger.info( logger.info(
'Found device %s BID %s VID %s PID %s HID++ %s %s USB %s %s', device.device_node, bid, vid, pid, hidpp_short, "Found device %s BID %s VID %s PID %s HID++ %s %s USB %s %s",
hidpp_long, usb_interface, interface_number device.device_node,
bid,
vid,
pid,
hidpp_short,
hidpp_long,
usb_interface,
interface_number,
) )
if not (hidpp_short or hidpp_long or interface_number is None or interface_number == usb_interface): if not (hidpp_short or hidpp_long or interface_number is None or interface_number == usb_interface):
return return
attrs = intf_device.attributes if intf_device else None attrs = intf_device.attributes if intf_device is not None else None
d_info = DeviceInfo( d_info = DeviceInfo(
path=device.device_node, path=device.device_node,
@ -162,19 +158,17 @@ def _match(action, device, filterfn):
product_id=pid[-4:], product_id=pid[-4:],
interface=usb_interface, interface=usb_interface,
driver=hid_driver_name, driver=hid_driver_name,
manufacturer=attrs.get('manufacturer') if attrs else None, manufacturer=attrs.get("manufacturer") if attrs else None,
product=attrs.get('product') if attrs else None, product=attrs.get("product") if attrs else None,
serial=hid_device.get('HID_UNIQ'), serial=hid_device.properties.get("HID_UNIQ"),
release=attrs.get('bcdDevice') if attrs else None, release=attrs.get("bcdDevice") if attrs else None,
isDevice=isDevice, isDevice=isDevice,
hidpp_short=hidpp_short, hidpp_short=hidpp_short,
hidpp_long=hidpp_long, hidpp_long=hidpp_long,
) )
return d_info return d_info
elif action == 'remove': elif action == ACTION_REMOVE:
# print (dict(device), dict(usb_device))
d_info = DeviceInfo( d_info = DeviceInfo(
path=device.device_node, path=device.device_node,
bus_id=None, bus_id=None,
@ -193,41 +187,41 @@ def _match(action, device, filterfn):
return d_info return d_info
def find_paired_node(receiver_path, index, timeout): def find_paired_node(receiver_path: str, index: int, timeout: int):
"""Find the node of a device paired with a receiver""" """Find the node of a device paired with a receiver"""
context = _Context() context = pyudev.Context()
receiver_phys = _Devices.from_device_file(context, receiver_path).find_parent('hid').get('HID_PHYS') receiver_phys = pyudev.Devices.from_device_file(context, receiver_path).find_parent("hid").get("HID_PHYS")
if not receiver_phys: if not receiver_phys:
return None return None
phys = f'{receiver_phys}:{index}' # noqa: E231 phys = f"{receiver_phys}:{index}" # noqa: E231
timeout += _timestamp() timeout += time()
delta = _timestamp() delta = time()
while delta < timeout: while delta < timeout:
for dev in context.list_devices(subsystem='hidraw'): for dev in context.list_devices(subsystem="hidraw"):
dev_phys = dev.find_parent('hid').get('HID_PHYS') dev_phys = dev.find_parent("hid").get("HID_PHYS")
if dev_phys and dev_phys == phys: if dev_phys and dev_phys == phys:
return dev.device_node return dev.device_node
delta = _timestamp() delta = time()
return None return None
def find_paired_node_wpid(receiver_path, index): def find_paired_node_wpid(receiver_path: str, index: int):
"""Find the node of a device paired with a receiver, get wpid from udev""" """Find the node of a device paired with a receiver, get wpid from udev"""
context = _Context() context = pyudev.Context()
receiver_phys = _Devices.from_device_file(context, receiver_path).find_parent('hid').get('HID_PHYS') receiver_phys = pyudev.Devices.from_device_file(context, receiver_path).find_parent("hid").get("HID_PHYS")
if not receiver_phys: if not receiver_phys:
return None return None
phys = f'{receiver_phys}:{index}' # noqa: E231 phys = f"{receiver_phys}:{index}" # noqa: E231
for dev in context.list_devices(subsystem='hidraw'): for dev in context.list_devices(subsystem="hidraw"):
dev_phys = dev.find_parent('hid').get('HID_PHYS') dev_phys = dev.find_parent("hid").get("HID_PHYS")
if dev_phys and dev_phys == phys: if dev_phys and dev_phys == phys:
# get hid id like 0003:0000046D:00000065 # get hid id like 0003:0000046D:00000065
hid_id = dev.find_parent('hid').get('HID_ID') hid_id = dev.find_parent("hid").get("HID_ID")
# get wpid - last 4 symbols # get wpid - last 4 symbols
udev_wpid = hid_id[-4:] udev_wpid = hid_id[-4:]
return udev_wpid return udev_wpid
@ -235,55 +229,48 @@ def find_paired_node_wpid(receiver_path, index):
return None return None
def monitor_glib(callback, filterfn): def monitor_glib(glib: GLib, callback: Callable, filter_func: Callable):
from gi.repository import GLib """Monitor GLib.
c = _Context() Parameters
----------
glib
GLib instance.
"""
c = pyudev.Context()
m = pyudev.Monitor.from_netlink(c)
m.filter_by(subsystem="hidraw")
# already existing devices def _process_udev_event(monitor, condition, cb, filter_func):
# for device in c.list_devices(subsystem='hidraw'): if condition == glib.IO_IN:
# # print (device, dict(device), dict(device.attributes))
# for filter in device_filters:
# d_info = _match('add', device, *filter)
# if d_info:
# GLib.idle_add(callback, 'add', d_info)
# break
m = _Monitor.from_netlink(c)
m.filter_by(subsystem='hidraw')
def _process_udev_event(monitor, condition, cb, filterfn):
if condition == GLib.IO_IN:
event = monitor.receive_device() event = monitor.receive_device()
if event: if event:
action, device = event action, device = event
# print ("***", action, device) # print ("***", action, device)
if action == 'add': if action == ACTION_ADD:
d_info = _match(action, device, filterfn) d_info = _match(action, device, filter_func)
if d_info: if d_info:
GLib.idle_add(cb, action, d_info) glib.idle_add(cb, action, d_info)
elif action == 'remove': elif action == ACTION_REMOVE:
# the GLib notification does _not_ match! # the GLib notification does _not_ match!
pass pass
return True return True
try: try:
# io_add_watch_full may not be available... # io_add_watch_full may not be available...
GLib.io_add_watch_full(m, GLib.PRIORITY_LOW, GLib.IO_IN, _process_udev_event, callback, filterfn) glib.io_add_watch_full(m, glib.PRIORITY_LOW, glib.IO_IN, _process_udev_event, callback, filter_func)
# print ("did io_add_watch_full")
except AttributeError: except AttributeError:
try: try:
# and the priority parameter appeared later in the API # and the priority parameter appeared later in the API
GLib.io_add_watch(m, GLib.PRIORITY_LOW, GLib.IO_IN, _process_udev_event, callback, filterfn) glib.io_add_watch(m, glib.PRIORITY_LOW, glib.IO_IN, _process_udev_event, callback, filter_func)
# print ("did io_add_watch with priority")
except Exception: except Exception:
GLib.io_add_watch(m, GLib.IO_IN, _process_udev_event, callback, filterfn) glib.io_add_watch(m, glib.IO_IN, _process_udev_event, callback, filter_func)
# print ("did io_add_watch")
logger.debug("Starting dbus monitoring")
m.start() m.start()
def enumerate(filterfn): def enumerate(filter_func: typing.Callable[[int, int, int, bool, bool], dict[str, typing.Any]]):
"""Enumerate the HID Devices. """Enumerate the HID Devices.
List all the HID devices attached to the system, optionally filtering by List all the HID devices attached to the system, optionally filtering by
@ -292,8 +279,9 @@ def enumerate(filterfn):
:returns: a list of matching ``DeviceInfo`` tuples. :returns: a list of matching ``DeviceInfo`` tuples.
""" """
for dev in _Context().list_devices(subsystem='hidraw'): logger.debug("Starting dbus enumeration")
dev_info = _match('add', dev, filterfn) for dev in pyudev.Context().list_devices(subsystem="hidraw"):
dev_info = _match(ACTION_ADD, dev, filter_func)
if dev_info: if dev_info:
yield dev_info yield dev_info
@ -322,29 +310,29 @@ def open_path(device_path):
:returns: an opaque device handle, or ``None``. :returns: an opaque device handle, or ``None``.
""" """
assert device_path assert device_path
assert device_path.startswith('/dev/hidraw') assert device_path.startswith("/dev/hidraw")
logger.info('OPEN PATH %s', device_path) logger.info("OPEN PATH %s", device_path)
retrycount = 0 retrycount = 0
while (retrycount < 3): while retrycount < 3:
retrycount += 1 retrycount += 1
try: try:
return _os.open(device_path, _os.O_RDWR | _os.O_SYNC) return os.open(device_path, os.O_RDWR | os.O_SYNC)
except OSError as e: except OSError as e:
logger.info('OPEN PATH FAILED %s ERROR %s %s', device_path, e.errno, e) logger.info("OPEN PATH FAILED %s ERROR %s %s", device_path, e.errno, e)
if e.errno == _errno.EACCES: if e.errno == errno.EACCES:
sleep(0.1) sleep(0.1)
else: else:
raise raise e
def close(device_handle): def close(device_handle) -> None:
"""Close a HID device. """Close a HID device.
:param device_handle: a device handle returned by open() or open_path(). :param device_handle: a device handle returned by open() or open_path().
""" """
assert device_handle assert device_handle
_os.close(device_handle) os.close(device_handle)
def write(device_handle, data): def write(device_handle, data):
@ -373,17 +361,17 @@ def write(device_handle, data):
assert isinstance(data, bytes), (repr(data), type(data)) assert isinstance(data, bytes), (repr(data), type(data))
retrycount = 0 retrycount = 0
bytes_written = 0 bytes_written = 0
while (retrycount < 3): while retrycount < 3:
try: try:
retrycount += 1 retrycount += 1
bytes_written = _os.write(device_handle, data) bytes_written = os.write(device_handle, data)
except OSError as e: except OSError as e:
if e.errno == _errno.EPIPE: if e.errno == errno.EPIPE:
sleep(0.1) sleep(0.1)
else: else:
break break
if bytes_written != len(data): if bytes_written != len(data):
raise OSError(_errno.EIO, 'written %d bytes out of expected %d' % (bytes_written, len(data))) raise OSError(errno.EIO, f"written {int(bytes_written)} bytes out of expected {len(data)}")
def read(device_handle, bytes_count, timeout_ms=-1): def read(device_handle, bytes_count, timeout_ms=-1):
@ -404,26 +392,26 @@ def read(device_handle, bytes_count, timeout_ms=-1):
""" """
assert device_handle assert device_handle
timeout = None if timeout_ms < 0 else timeout_ms / 1000.0 timeout = None if timeout_ms < 0 else timeout_ms / 1000.0
rlist, wlist, xlist = _select([device_handle], [], [device_handle], timeout) rlist, wlist, xlist = select([device_handle], [], [device_handle], timeout)
if xlist: if xlist:
assert xlist == [device_handle] assert xlist == [device_handle]
raise OSError(_errno.EIO, 'exception on file descriptor %d' % device_handle) raise OSError(errno.EIO, f"exception on file descriptor {int(device_handle)}")
if rlist: if rlist:
assert rlist == [device_handle] assert rlist == [device_handle]
data = _os.read(device_handle, bytes_count) data = os.read(device_handle, bytes_count)
assert data is not None assert data is not None
assert isinstance(data, bytes), (repr(data), type(data)) assert isinstance(data, bytes), (repr(data), type(data))
return data return data
else: else:
return b'' return b""
_DEVICE_STRINGS = { _DEVICE_STRINGS = {
0: 'manufacturer', 0: "manufacturer",
1: 'product', 1: "product",
2: 'serial', 2: "serial",
} }
@ -468,22 +456,22 @@ def get_indexed_string(device_handle, index):
return None return None
assert device_handle assert device_handle
stat = _os.fstat(device_handle) stat = os.fstat(device_handle)
try: try:
dev = _Device.from_device_number(_Context(), 'char', stat.st_rdev) dev = pyudev.Devices.from_device_number(pyudev.Context(), "char", stat.st_rdev)
except (DeviceNotFoundError, ValueError): except (pyudev.DeviceNotFoundError, ValueError):
return None return None
hid_dev = dev.find_parent('hid') hid_dev = dev.find_parent("hid")
if hid_dev: if hid_dev:
assert 'HID_ID' in hid_dev assert "HID_ID" in hid_dev
bus, _ignore, _ignore = hid_dev['HID_ID'].split(':') bus, _ignore, _ignore = hid_dev["HID_ID"].split(":")
if bus == '0003': # USB if bus == "0003": # USB
usb_dev = dev.find_parent('usb', 'usb_device') usb_dev = dev.find_parent("usb", "usb_device")
assert usb_dev assert usb_dev
return usb_dev.attributes.get(key) return usb_dev.attributes.get(key)
elif bus == '0005': # BLUETOOTH elif bus == "0005": # BLUETOOTH
# TODO # TODO
pass pass

View File

@ -1,43 +1,39 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Extract key symbol encodings from X11 header files."""
from pathlib import Path from pathlib import Path
from pprint import pprint from pprint import pprint
from re import findall from re import findall
from subprocess import run from subprocess import run
from tempfile import TemporaryDirectory from tempfile import TemporaryDirectory
repo = 'https://github.com/freedesktop/xorg-proto-x11proto.git' repo = "https://gitlab.freedesktop.org/xorg/proto/xorgproto.git"
xx = 'https://gitlab.freedesktop.org/xorg/proto/xorgproto/-/tree/master/include/X11/' pattern = r"#define XK_(\w+)\s+0x(\w+)(?:\s+/\*\s+U\+(\w+))?"
repo = 'https://gitlab.freedesktop.org/xorg/proto/xorgproto.git' xf86pattern = r"#define XF86XK_(\w+)\s+0x(\w+)(?:\s+/\*\s+U\+(\w+))?"
pattern = r'#define XK_(\w+)\s+0x(\w+)(?:\s+/\*\s+U\+(\w+))?'
xf86pattern = r'#define XF86XK_(\w+)\s+0x(\w+)(?:\s+/\*\s+U\+(\w+))?'
def main(): def main():
keysymdef = {} keysymdef = {}
keysym_files = [
("include/X11/keysymdef.h", pattern, ""),
("include/X11/XF86keysym.h", xf86pattern, "XF86_"),
]
with TemporaryDirectory() as temp: with TemporaryDirectory() as temp:
run(['git', 'clone', repo, '.'], cwd=temp) run(["git", "clone", repo, "."], cwd=temp)
# text = Path(temp, 'keysymdef.h').read_text()
text = Path(temp, 'include/X11/keysymdef.h').read_text()
for name, sym, uni in findall(pattern, text):
sym = int(sym, 16)
uni = int(uni, 16) if uni else None
if keysymdef.get(name, None):
print('KEY DUP', name)
keysymdef[name] = sym
# text = Path(temp, 'keysymdef.h').read_text()
text = Path(temp, 'include/X11/XF86keysym.h').read_text()
for name, sym, uni in findall(xf86pattern, text):
sym = int(sym, 16)
uni = int(uni, 16) if uni else None
if keysymdef.get('XF86_' + name, None):
print('KEY DUP', 'XF86_' + name)
keysymdef['XF86_' + name] = sym
with open('keysymdef.py', 'w') as f: for filename, extraction_pattern, prefix in keysym_files:
f.write('# flake8: noqa\nkeysymdef = \\\n') text = Path(temp, filename).read_text()
for name, sym, _ in findall(extraction_pattern, text):
sym = int(sym, 16)
if keysymdef.get(f"{prefix}{name}", None):
print(f"KEY DUP {prefix}{name}")
keysymdef[f"{prefix}{name}"] = sym
with open("keysymdef.py", "w") as f:
f.write("# flake8: noqa\nkey_symbols = \\\n")
pprint(keysymdef, f) pprint(keysymdef, f)
if __name__ == '__main__': if __name__ == "__main__":
main() main()

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,3 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
@ -15,34 +13,12 @@
## You should have received a copy of the GNU General Public License along ## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Low-level interface for devices connected through a Logitech Universal """Low-level interface for devices using Logitech HID++ protocol.
Receiver (UR).
Uses the HID api exposed through hidapi.py, a Python thin layer over a native Uses the HID api exposed through hidapi_impl.py, a Python thin layer over a native
implementation. implementation.
Incomplete. Based on a bit of documentation, trial-and-error, and guesswork.
References:
http://julien.danjou.info/blog/2012/logitech-k750-linux-support
http://6xq.net/git/lars/lshidpp.git/plain/doc/
""" """
import logging import logging
from . import listener, status # noqa: F401
from .base import DeviceUnreachable, NoReceiver, NoSuchDevice # noqa: F401
from .common import strhex # noqa: F401
from .device import Device # noqa: F401
from .hidpp20 import FeatureCallError, FeatureNotSupported # noqa: F401
from .receiver import Receiver # noqa: F401
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
logger.setLevel(logging.root.level)
# if logging.root.level > logging.DEBUG:
# logger.addHandler(logging.NullHandler())
# logger.propagate = 0
del logging
__version__ = '0.9'

View File

@ -1,5 +1,3 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
@ -16,35 +14,80 @@
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# Base low-level functions used by the API proper. """Base low-level functions as API for upper layers."""
# Unlikely to be used directly unless you're expanding the API.
from __future__ import annotations
import dataclasses
import logging import logging
import threading as _threading import platform
import struct
import threading
import typing
from collections import namedtuple
from contextlib import contextmanager from contextlib import contextmanager
from random import getrandbits as _random_bits from random import getrandbits
from struct import pack as _pack from time import time
from time import time as _timestamp from typing import Any
from typing import Callable
import hidapi as _hid from . import base_usb
from . import common
from . import descriptors
from . import exceptions
from .common import LOGITECH_VENDOR_ID
from .common import BusID
from .hidpp10_constants import ErrorCode as Hidpp10ErrorCode
from .hidpp20_constants import ErrorCode as Hidpp20ErrorCode
from . import hidpp10 as _hidpp10 if typing.TYPE_CHECKING:
from . import hidpp20 as _hidpp20 import gi
from .base_usb import ALL as _RECEIVER_USB_IDS
from .base_usb import DEVICES as _DEVICE_IDS from hidapi.common import DeviceInfo
from .base_usb import other_device_check as _other_device_check
from .common import KwException as _KwException gi.require_version("Gdk", "3.0")
from .common import strhex as _strhex from gi.repository import GLib # NOQA: E402
if platform.system() == "Linux":
import hidapi.udev_impl as hidapi
else:
import hidapi.hidapi_impl as hidapi
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
#
#
#
_SHORT_MESSAGE_SIZE = 7 class HIDProtocol(typing.Protocol):
def find_paired_node_wpid(self, receiver_path: str, index: int):
...
def find_paired_node(self, receiver_path: str, index: int, timeout: int):
...
def open(self, vendor_id, product_id, serial=None):
...
def open_path(self, path) -> int:
...
def enumerate(self, filter_func: Callable[[int, int, int, bool, bool], dict[str, typing.Any]]) -> DeviceInfo:
...
def monitor_glib(
self, glib: GLib, callback: Callable, filter_func: Callable[[int, int, int, bool, bool], dict[str, typing.Any]]
) -> None:
...
def read(self, device_handle, bytes_count, timeout_ms):
...
def write(self, device_handle: int, data: bytes) -> int:
...
def close(self, device_handle) -> None:
...
SHORT_MESSAGE_SIZE = 7
_LONG_MESSAGE_SIZE = 20 _LONG_MESSAGE_SIZE = 20
_MEDIUM_MESSAGE_SIZE = 15 _MEDIUM_MESSAGE_SIZE = 15
_MAX_READ_SIZE = 32 _MAX_READ_SIZE = 32
@ -53,13 +96,7 @@ HIDPP_SHORT_MESSAGE_ID = 0x10
HIDPP_LONG_MESSAGE_ID = 0x11 HIDPP_LONG_MESSAGE_ID = 0x11
DJ_MESSAGE_ID = 0x20 DJ_MESSAGE_ID = 0x20
# mapping from report_id to message length
report_lengths = {
HIDPP_SHORT_MESSAGE_ID: _SHORT_MESSAGE_SIZE,
HIDPP_LONG_MESSAGE_ID: _LONG_MESSAGE_SIZE,
DJ_MESSAGE_ID: _MEDIUM_MESSAGE_SIZE,
0x21: _MAX_READ_SIZE
}
"""Default timeout on read (in seconds).""" """Default timeout on read (in seconds)."""
DEFAULT_TIMEOUT = 4 DEFAULT_TIMEOUT = 4
# the receiver itself should reply very fast, within 500ms # the receiver itself should reply very fast, within 500ms
@ -69,84 +106,156 @@ _DEVICE_REQUEST_TIMEOUT = DEFAULT_TIMEOUT
# when pinging, be extra patient (no longer) # when pinging, be extra patient (no longer)
_PING_TIMEOUT = DEFAULT_TIMEOUT _PING_TIMEOUT = DEFAULT_TIMEOUT
# hidapi = typing.cast(HIDProtocol, hidapi)
# Exceptions that may be raised by this API.
# request_lock = threading.Lock() # serialize all requests
handles_lock = {}
class NoReceiver(_KwException): @dataclasses.dataclass
"""Raised when trying to talk through a previously open handle, when the class HIDPPNotification:
receiver is no longer available. Should only happen if the receiver is report_id: int
physically disconnected from the machine, or its kernel driver module is devnumber: int
unloaded.""" sub_id: int
pass address: int
data: bytes
def __str__(self):
text_as_hex = common.strhex(self.data)
return f"Notification({self.report_id:02x},{self.devnumber},{self.sub_id:02X},{self.address:02X},{text_as_hex})"
class NoSuchDevice(_KwException): def _usb_device(product_id: int, usb_interface: int) -> dict[str, Any]:
"""Raised when trying to reach a device number not paired to the receiver.""" return {
pass "vendor_id": LOGITECH_VENDOR_ID,
"product_id": product_id,
"bus_id": BusID.USB,
"usb_interface": usb_interface,
"isDevice": True,
}
class DeviceUnreachable(_KwException): def _bluetooth_device(product_id: int) -> dict[str, Any]:
"""Raised when a request is made to an unreachable (turned off) device.""" return {"vendor_id": LOGITECH_VENDOR_ID, "product_id": product_id, "bus_id": BusID.BLUETOOTH, "isDevice": True}
pass
# KNOWN_DEVICE_IDS = []
#
# for _ignore, d in descriptors.DEVICES.items():
if d.usbid:
usb_interface = d.interface if d.interface else 2
KNOWN_DEVICE_IDS.append(_usb_device(d.usbid, usb_interface))
if d.btid:
KNOWN_DEVICE_IDS.append(_bluetooth_device(d.btid))
def match(record, bus_id, vendor_id, product_id): def product_information(usb_id: int) -> dict[str, Any]:
return ((record.get('bus_id') is None or record.get('bus_id') == bus_id) """Returns hardcoded information from USB receiver."""
and (record.get('vendor_id') is None or record.get('vendor_id') == vendor_id) return base_usb.get_receiver_info(usb_id)
and (record.get('product_id') is None or record.get('product_id') == product_id))
def filter_receivers(bus_id, vendor_id, product_id, hidpp_short=False, hidpp_long=False):
"""Check that this product is a Logitech receiver and if so return the receiver record for further checking"""
for record in _RECEIVER_USB_IDS: # known receivers
if match(record, bus_id, vendor_id, product_id):
return record
if vendor_id == 0x046D and 0xC500 <= product_id <= 0xC5FF: # unknown receiver
return {'vendor_id': vendor_id, 'product_id': product_id, 'bus_id': bus_id, 'isDevice': False}
def receivers(): def receivers():
"""Enumerate all the receivers attached to the machine.""" """Enumerate all the receivers attached to the machine."""
yield from _hid.enumerate(filter_receivers) yield from hidapi.enumerate(get_known_receiver_info)
def filter(bus_id, vendor_id, product_id, hidpp_short=False, hidpp_long=False): def filter_products_of_interest(
bus_id: int, vendor_id: int, product_id: int, hidpp_short: bool = False, hidpp_long: bool = False
) -> dict[str, Any] | None:
"""Check that this product is of interest and if so return the device record for further checking""" """Check that this product is of interest and if so return the device record for further checking"""
record = filter_receivers(bus_id, vendor_id, product_id, hidpp_short, hidpp_long)
if record: # known or unknown receiver recv = get_known_receiver_info(bus_id, vendor_id, product_id, hidpp_short, hidpp_long)
if recv: # known or unknown receiver
return recv
device = get_known_device_info(bus_id, vendor_id, product_id)
if device:
return device
if hidpp_short or hidpp_long:
return get_unknown_hid_device_info(bus_id, vendor_id, product_id)
if hidpp_short is None and hidpp_long is None:
return get_unknown_logitech_device_info(bus_id, vendor_id, product_id)
return None
def get_known_device_info(bus_id: int, vendor_id: int, product_id: int) -> dict[str, Any]:
for recv in KNOWN_DEVICE_IDS:
if _match_device(recv, bus_id, vendor_id, product_id):
return recv
def get_unknown_hid_device_info(bus_id: int, vendor_id: int, product_id: int) -> dict[str, Any]:
return {"vendor_id": vendor_id, "product_id": product_id, "bus_id": bus_id, "isDevice": True}
def get_unknown_logitech_device_info(bus_id: int, vendor_id: int, product_id: int) -> dict[str, Any] | None:
"""Get info from unknown device in Logitech product range.
Check whether product is a Logitech USB-connected or Bluetooth
device based on bus, vendor, and product ID. This allows Solaar to
support receiverless HID++ 2.0 devices that it knows nothing about.
"""
if vendor_id != LOGITECH_VENDOR_ID:
return None
if bus_id == BusID.USB.value and (0xC07D <= product_id <= 0xC094 or 0xC32B <= product_id <= 0xC344):
device_info = _usb_device(product_id, 2)
return device_info
elif bus_id == BusID.BLUETOOTH.value and (0xB012 <= product_id <= 0xB0FF or 0xB317 <= product_id <= 0xB3FF):
device_info = _bluetooth_device(product_id)
return device_info
return None
def _match_device(record: dict[str, Any], bus_id: int, vendor_id: int, product_id: int):
return (
(record.get("bus_id") is None or record.get("bus_id") == bus_id)
and (record.get("vendor_id") is None or record.get("vendor_id") == vendor_id)
and (record.get("product_id") is None or record.get("product_id") == product_id)
)
def get_known_receiver_info(
bus_id: int, vendor_id: int, product_id: int, _hidpp_short: bool = False, _hidpp_long: bool = False
) -> dict[str, Any]:
"""Check that this product is a Logitech receiver and return it.
Filters based on bus_id, vendor_id and product_id.
If so return the receiver record for further checking.
"""
try:
record = base_usb.get_receiver_info(product_id)
if _match_device(record, bus_id, vendor_id, product_id):
return record return record
for record in _DEVICE_IDS: # known devices except ValueError:
if match(record, bus_id, vendor_id, product_id): pass
return record
if hidpp_short or hidpp_long: # unknown devices that use HID++ if vendor_id == LOGITECH_VENDOR_ID and 0xC500 <= product_id <= 0xC5FF: # unknown receiver
return {'vendor_id': vendor_id, 'product_id': product_id, 'bus_id': bus_id, 'isDevice': True} return {"vendor_id": vendor_id, "product_id": product_id, "bus_id": bus_id, "isDevice": False}
elif hidpp_short is None and hidpp_long is None: # unknown devices in correct range of IDs return None
return _other_device_check(bus_id, vendor_id, product_id)
def receivers_and_devices(): def receivers_and_devices():
"""Enumerate all the receivers and devices directly attached to the machine.""" """Enumerate all the receivers and devices directly attached to the machine."""
yield from _hid.enumerate(filter) yield from hidapi.enumerate(filter_products_of_interest)
def notify_on_receivers_glib(callback): def notify_on_receivers_glib(glib: GLib, callback: Callable):
"""Watch for matching devices and notifies the callback on the GLib thread.""" """Watch for matching devices and notifies the callback on the GLib thread.
return _hid.monitor_glib(callback, filter)
Parameters
----------
glib
GLib instance.
"""
return hidapi.monitor_glib(glib, callback, filter_products_of_interest)
# def open_path(path) -> int:
#
#
def open_path(path):
"""Checks if the given Linux device path points to the right UR device. """Checks if the given Linux device path points to the right UR device.
:param path: the Linux device path. :param path: the Linux device path.
@ -159,7 +268,7 @@ def open_path(path):
:returns: an open receiver handle if this is the right Linux device, or :returns: an open receiver handle if this is the right Linux device, or
``None``. ``None``.
""" """
return _hid.open_path(path) return hidapi.open_path(path)
def open(): def open():
@ -178,13 +287,11 @@ def close(handle):
if handle: if handle:
try: try:
if isinstance(handle, int): if isinstance(handle, int):
_hid.close(handle) hidapi.close(handle)
else: else:
handle.close() handle.close()
# logger.info("closed receiver handle %r", handle)
return True return True
except Exception: except Exception:
# logger.exception("closing receiver handle %r", handle)
pass pass
return False return False
@ -207,19 +314,26 @@ def write(handle, devnumber, data, long_message=False):
assert data is not None assert data is not None
assert isinstance(data, bytes), (repr(data), type(data)) assert isinstance(data, bytes), (repr(data), type(data))
if long_message or len(data) > _SHORT_MESSAGE_SIZE - 2 or data[:1] == b'\x82': if long_message or len(data) > SHORT_MESSAGE_SIZE - 2 or data[:1] == b"\x82":
wdata = _pack('!BB18s', HIDPP_LONG_MESSAGE_ID, devnumber, data) wdata = struct.pack("!BB18s", HIDPP_LONG_MESSAGE_ID, devnumber, data)
else: else:
wdata = _pack('!BB5s', HIDPP_SHORT_MESSAGE_ID, devnumber, data) wdata = struct.pack("!BB5s", HIDPP_SHORT_MESSAGE_ID, devnumber, data)
if logger.isEnabledFor(logging.DEBUG): if logger.isEnabledFor(logging.DEBUG):
logger.debug('(%s) <= w[%02X %02X %s %s]', handle, ord(wdata[:1]), devnumber, _strhex(wdata[2:4]), _strhex(wdata[4:])) logger.debug(
"(%s) <= w[%02X %02X %s %s]",
handle,
ord(wdata[:1]),
devnumber,
common.strhex(wdata[2:4]),
common.strhex(wdata[4:]),
)
try: try:
_hid.write(int(handle), wdata) hidapi.write(int(handle), wdata)
except Exception as reason: except Exception as reason:
logger.error('write failed, assuming handle %r no longer available', handle) logger.error("write failed, assuming handle %r no longer available", handle)
close(handle) close(handle)
raise NoReceiver(reason=reason) raise exceptions.NoReceiver(reason=reason) from reason
def read(handle, timeout=DEFAULT_TIMEOUT): def read(handle, timeout=DEFAULT_TIMEOUT):
@ -240,19 +354,31 @@ def read(handle, timeout=DEFAULT_TIMEOUT):
return reply return reply
# sanity checks on message report id and size def _is_relevant_message(data: bytes) -> bool:
def check_message(data): """Checks if given id is a HID++ or DJ message.
Applies sanity checks on message report ID and message size.
"""
assert isinstance(data, bytes), (repr(data), type(data)) assert isinstance(data, bytes), (repr(data), type(data))
# mapping from report_id to message length
report_lengths = {
HIDPP_SHORT_MESSAGE_ID: SHORT_MESSAGE_SIZE,
HIDPP_LONG_MESSAGE_ID: _LONG_MESSAGE_SIZE,
DJ_MESSAGE_ID: _MEDIUM_MESSAGE_SIZE,
0x21: _MAX_READ_SIZE,
}
report_id = ord(data[:1]) report_id = ord(data[:1])
if report_id in report_lengths: # is this an HID++ or DJ message? if report_id in report_lengths:
if report_lengths.get(report_id) == len(data): if report_lengths.get(report_id) == len(data):
return True return True
else: else:
logger.warning('unexpected message size: report_id %02X message %s' % (report_id, _strhex(data))) logger.warning(f"unexpected message size: report_id {report_id:02X} message {common.strhex(data)}")
return False return False
def _read(handle, timeout): def _read(handle, timeout) -> tuple[int, int, bytes]:
"""Read an incoming packet from the receiver. """Read an incoming packet from the receiver.
:returns: a tuple of (report_id, devnumber, data), or `None`. :returns: a tuple of (report_id, devnumber, data), or `None`.
@ -264,106 +390,72 @@ def _read(handle, timeout):
try: try:
# convert timeout to milliseconds, the hidapi expects it # convert timeout to milliseconds, the hidapi expects it
timeout = int(timeout * 1000) timeout = int(timeout * 1000)
data = _hid.read(int(handle), _MAX_READ_SIZE, timeout) data = hidapi.read(int(handle), _MAX_READ_SIZE, timeout)
except Exception as reason: except Exception as reason:
logger.warning('read failed, assuming handle %r no longer available', handle) logger.warning("read failed, assuming handle %r no longer available", handle)
close(handle) close(handle)
raise NoReceiver(reason=reason) raise exceptions.NoReceiver(reason=reason) from reason
if data and check_message(data): # ignore messages that fail check if data and _is_relevant_message(data): # ignore messages that fail check
report_id = ord(data[:1]) report_id = ord(data[:1])
devnumber = ord(data[1:2]) devnumber = ord(data[1:2])
if logger.isEnabledFor(logging.DEBUG if logger.isEnabledFor(logging.DEBUG) and (
) and (report_id != DJ_MESSAGE_ID or ord(data[2:3]) > 0x10): # ignore DJ input messages report_id != DJ_MESSAGE_ID or ord(data[2:3]) > 0x10
logger.debug('(%s) => r[%02X %02X %s %s]', handle, report_id, devnumber, _strhex(data[2:4]), _strhex(data[4:])) ): # ignore DJ input messages
logger.debug(
"(%s) => r[%02X %02X %s %s]",
handle,
report_id,
devnumber,
common.strhex(data[2:4]),
common.strhex(data[4:]),
)
return report_id, devnumber, data[2:] return report_id, devnumber, data[2:]
# def make_notification(report_id: int, devnumber: int, data: bytes) -> HIDPPNotification | None:
#
#
def _skip_incoming(handle, ihandle, notifications_hook):
"""Read anything already in the input buffer.
Used by request() and ping() before their write.
"""
while True:
try:
# read whatever is already in the buffer, if any
data = _hid.read(ihandle, _MAX_READ_SIZE, 0)
except Exception as reason:
logger.error('read failed, assuming receiver %s no longer available', handle)
close(handle)
raise NoReceiver(reason=reason)
if data:
if check_message(data): # only process messages that pass check
# report_id = ord(data[:1])
if notifications_hook:
n = make_notification(ord(data[:1]), ord(data[1:2]), data[2:])
if n:
notifications_hook(n)
else:
# nothing in the input buffer, we're done
return
def make_notification(report_id, devnumber, data):
"""Guess if this is a notification (and not just a request reply), and """Guess if this is a notification (and not just a request reply), and
return a Notification tuple if it is.""" return a Notification if it is."""
sub_id = ord(data[:1]) sub_id = ord(data[:1])
if sub_id & 0x80 == 0x80: if sub_id & 0x80 == 0x80:
# this is either a HID++1.0 register r/w, or an error reply # this is either a HID++1.0 register r/w, or an error reply
return return None
# DJ input records are not notifications # DJ input records are not notifications
if report_id == DJ_MESSAGE_ID and (sub_id < 0x10): if report_id == DJ_MESSAGE_ID and (sub_id < 0x10):
return return None
address = ord(data[1:2]) address = ord(data[1:2])
if sub_id == 0x00 and (address & 0x0F == 0x00): if sub_id == 0x00 and (address & 0x0F == 0x00):
# this is a no-op notification - don't do anything with it # this is a no-op notification - don't do anything with it
return return None
if ( if (
# standard HID++ 1.0 notification, SubId may be 0x40 - 0x7F # standard HID++ 1.0 notification, SubId may be 0x40 - 0x7F
(sub_id >= 0x40) or # noqa: E131 (sub_id >= 0x40) # noqa: E131
or
# custom HID++1.0 battery events, where SubId is 0x07/0x0D # custom HID++1.0 battery events, where SubId is 0x07/0x0D
(sub_id in (0x07, 0x0D) and len(data) == 5 and data[4:5] == b'\x00') or (sub_id in (0x07, 0x0D) and len(data) == 5 and data[4:5] == b"\x00")
or
# custom HID++1.0 illumination event, where SubId is 0x17 # custom HID++1.0 illumination event, where SubId is 0x17
(sub_id == 0x17 and len(data) == 5) or (sub_id == 0x17 and len(data) == 5)
or
# HID++ 2.0 feature notifications have the SoftwareID 0 # HID++ 2.0 feature notifications have the SoftwareID 0
(address & 0x0F == 0x00) (address & 0x0F == 0x00)
): # noqa: E129 ): # noqa: E129
return _HIDPP_Notification(report_id, devnumber, sub_id, address, data[2:]) return HIDPPNotification(report_id, devnumber, sub_id, address, data[2:])
return None
_HIDPP_Notification = namedtuple('_HIDPP_Notification', ('report_id', 'devnumber', 'sub_id', 'address', 'data'))
_HIDPP_Notification.__str__ = lambda self: 'Notification(%02x,%d,%02X,%02X,%s)' % (
self.report_id, self.devnumber, self.sub_id, self.address, _strhex(self.data)
)
del namedtuple
#
#
#
request_lock = _threading.Lock() # serialize all requests
handles_lock = {}
def handle_lock(handle): def handle_lock(handle):
with request_lock: with request_lock:
if handles_lock.get(handle) is None: if handles_lock.get(handle) is None:
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
logger.info('New lock %s', repr(handle)) logger.info("New lock %s", repr(handle))
handles_lock[handle] = _threading.Lock() # Serialize requests on the handle handles_lock[handle] = threading.Lock() # Serialize requests on the handle
return handles_lock[handle] return handles_lock[handle]
@ -373,15 +465,37 @@ def acquire_timeout(lock, handle, timeout):
result = lock.acquire(timeout=timeout) result = lock.acquire(timeout=timeout)
try: try:
if not result: if not result:
logger.error('lock on handle %d not acquired, probably due to timeout', int(handle)) logger.error("lock on handle %d not acquired, probably due to timeout", int(handle))
yield result yield result
finally: finally:
if result: if result:
lock.release() lock.release()
def find_paired_node(receiver_path: str, index: int, timeout: int):
"""Find the node of a device paired with a receiver."""
return hidapi.find_paired_node(receiver_path, index, timeout)
def find_paired_node_wpid(receiver_path: str, index: int):
"""Find the node of a device paired with a receiver.
Get wpid from udev.
"""
return hidapi.find_paired_node_wpid(receiver_path, index)
# a very few requests (e.g., host switching) do not expect a reply, but use no_reply=True with extreme caution # a very few requests (e.g., host switching) do not expect a reply, but use no_reply=True with extreme caution
def request(handle, devnumber, request_id, *params, no_reply=False, return_error=False, long_message=False, protocol=1.0): def request(
handle,
devnumber,
request_id: int,
*params,
no_reply: bool = False,
return_error: bool = False,
long_message: bool = False,
protocol: float = 1.0,
):
"""Makes a feature call to a device and waits for a matching reply. """Makes a feature call to a device and waits for a matching reply.
:param handle: an open UR handle. :param handle: an open UR handle.
:param devnumber: attached device number. :param devnumber: attached device number.
@ -389,19 +503,14 @@ def request(handle, devnumber, request_id, *params, no_reply=False, return_error
:param params: parameters for the feature call, 3 to 16 bytes. :param params: parameters for the feature call, 3 to 16 bytes.
:returns: the reply data, or ``None`` if some error occurred. or no reply expected :returns: the reply data, or ``None`` if some error occurred. or no reply expected
""" """
with acquire_timeout(handle_lock(handle), handle, 10.0):
# import inspect as _inspect
# print ('\n '.join(str(s) for s in _inspect.stack()))
with acquire_timeout(handle_lock(handle), handle, 10.):
assert isinstance(request_id, int) assert isinstance(request_id, int)
if (devnumber != 0xFF or protocol >= 2.0) and request_id < 0x8000: if (devnumber != 0xFF or protocol >= 2.0) and request_id < 0x8000:
# For HID++ 2.0 feature requests, randomize the SoftwareId to make it # Always set the most significant bit (8) in SoftwareId,
# easier to recognize the reply for this request. also, always set the # to make notifications easier to distinguish from request replies.
# most significant bit (8) in SoftwareId, to make notifications easier
# to distinguish from request replies.
# This only applies to peripheral requests, ofc. # This only applies to peripheral requests, ofc.
request_id = (request_id & 0xFFF0) | 0x08 | _random_bits(3) sw_id = _get_next_sw_id()
request_id = (request_id & 0xFFF0) | sw_id # was 0x08 | getrandbits(3)
timeout = _RECEIVER_REQUEST_TIMEOUT if devnumber == 0xFF else _DEVICE_REQUEST_TIMEOUT timeout = _RECEIVER_REQUEST_TIMEOUT if devnumber == 0xFF else _DEVICE_REQUEST_TIMEOUT
# be extra patient on long register read # be extra patient on long register read
@ -409,19 +518,17 @@ def request(handle, devnumber, request_id, *params, no_reply=False, return_error
timeout *= 2 timeout *= 2
if params: if params:
params = b''.join(_pack('B', p) if isinstance(p, int) else p for p in params) params = b"".join(struct.pack("B", p) if isinstance(p, int) else p for p in params)
else: else:
params = b'' params = b""
# if logger.isEnabledFor(logging.DEBUG): request_data = struct.pack("!H", request_id) + params
# logger.debug("(%s) device %d request_id {%04X} params [%s]", handle, devnumber, request_id, _strhex(params))
request_data = _pack('!H', request_id) + params
ihandle = int(handle) ihandle = int(handle)
notifications_hook = getattr(handle, 'notifications_hook', None) notifications_hook = getattr(handle, "notifications_hook", None)
try: try:
_skip_incoming(handle, ihandle, notifications_hook) _read_input_buffer(handle, ihandle, notifications_hook)
except NoReceiver: except exceptions.NoReceiver:
logger.warning('device or receiver disconnected') logger.warning("device or receiver disconnected")
return None return None
write(ihandle, devnumber, request_data, long_message) write(ihandle, devnumber, request_data, long_message)
@ -429,33 +536,48 @@ def request(handle, devnumber, request_id, *params, no_reply=False, return_error
return None return None
# we consider timeout from this point # we consider timeout from this point
request_started = _timestamp() request_started = time()
delta = 0 delta = 0
while delta < timeout: while delta < timeout:
reply = _read(handle, timeout) reply = _read(handle, timeout)
if reply: if reply:
report_id, reply_devnumber, reply_data = reply report_id, reply_devnumber, reply_data = reply
if reply_devnumber == devnumber or reply_devnumber == devnumber ^ 0xff: # BT device returning 0x00 if reply_devnumber == devnumber or reply_devnumber == devnumber ^ 0xFF: # BT device returning 0x00
if report_id == HIDPP_SHORT_MESSAGE_ID and reply_data[:1] == b'\x8F' and reply_data[1:3] == request_data[:2 if (
]: report_id == HIDPP_SHORT_MESSAGE_ID
and reply_data[:1] == b"\x8f"
and reply_data[1:3] == request_data[:2]
):
error = ord(reply_data[3:4]) error = ord(reply_data[3:4])
if logger.isEnabledFor(logging.DEBUG): if logger.isEnabledFor(logging.DEBUG):
logger.debug( logger.debug(
'(%s) device 0x%02X error on request {%04X}: %d = %s', handle, devnumber, request_id, error, "(%s) device 0x%02X error on request {%04X}: %d = %s",
_hidpp10.ERROR[error] handle,
devnumber,
request_id,
error,
Hidpp10ErrorCode(error),
) )
return _hidpp10.ERROR[error] if return_error else None return Hidpp10ErrorCode(error) if return_error else None
if reply_data[:1] == b'\xFF' and reply_data[1:3] == request_data[:2]: if reply_data[:1] == b"\xff" and reply_data[1:3] == request_data[:2]:
# a HID++ 2.0 feature call returned with an error # a HID++ 2.0 feature call returned with an error
error = ord(reply_data[3:4]) error = ord(reply_data[3:4])
logger.error( logger.error(
'(%s) device %d error on feature request {%04X}: %d = %s', handle, devnumber, request_id, error, "(%s) device %d error on feature request {%04X}: %d = %s",
_hidpp20.ERROR[error] handle,
devnumber,
request_id,
error,
Hidpp20ErrorCode(error),
)
raise exceptions.FeatureCallError(
number=devnumber,
request=request_id,
error=error,
params=params,
) )
raise _hidpp20.FeatureCallError(number=devnumber, request=request_id, error=error, params=params)
if reply_data[:2] == request_data[:2]: if reply_data[:2] == request_data[:2]:
if devnumber == 0xFF: if devnumber == 0xFF:
@ -473,78 +595,119 @@ def request(handle, devnumber, request_id, *params, no_reply=False, return_error
else: else:
# a reply was received, but did not match our request in any way # a reply was received, but did not match our request in any way
# reset the timeout starting point # reset the timeout starting point
request_started = _timestamp() request_started = time()
if notifications_hook: if notifications_hook:
n = make_notification(report_id, reply_devnumber, reply_data) n = make_notification(report_id, reply_devnumber, reply_data)
if n: if n:
notifications_hook(n) notifications_hook(n)
# elif logger.isEnabledFor(logging.DEBUG): delta = time() - request_started
# logger.debug("(%s) ignoring reply %02X [%s]", handle, reply_devnumber, _strhex(reply_data))
# elif logger.isEnabledFor(logging.DEBUG):
# logger.debug("(%s) ignoring reply %02X [%s]", handle, reply_devnumber, _strhex(reply_data))
delta = _timestamp() - request_started
# if logger.isEnabledFor(logging.DEBUG):
# logger.debug("(%s) still waiting for reply, delta %f", handle, delta)
logger.warning( logger.warning(
'timeout (%0.2f/%0.2f) on device %d request {%04X} params [%s]', delta, timeout, devnumber, request_id, "timeout (%0.2f/%0.2f) on device %d request {%04X} params [%s]",
_strhex(params) delta,
timeout,
devnumber,
request_id,
common.strhex(params),
) )
# raise DeviceUnreachable(number=devnumber, request=request_id) # raise DeviceUnreachable(number=devnumber, request=request_id)
def ping(handle, devnumber, long_message=False): def ping(handle, devnumber, long_message: bool = False):
"""Check if a device is connected to the receiver. """Check if a device is connected to the receiver.
:returns: The HID protocol supported by the device, as a floating point number, if the device is active. :returns: The HID protocol supported by the device, as a floating point number, if the device is active.
""" """
if logger.isEnabledFor(logging.DEBUG): if logger.isEnabledFor(logging.DEBUG):
logger.debug('(%s) pinging device %d', handle, devnumber) logger.debug("(%s) pinging device %d", handle, devnumber)
with acquire_timeout(handle_lock(handle), handle, 10.): with acquire_timeout(handle_lock(handle), handle, 10.0):
notifications_hook = getattr(handle, 'notifications_hook', None) notifications_hook = getattr(handle, "notifications_hook", None)
try: try:
_skip_incoming(handle, int(handle), notifications_hook) _read_input_buffer(handle, int(handle), notifications_hook)
except NoReceiver: except exceptions.NoReceiver:
logger.warning('device or receiver disconnected') logger.warning("device or receiver disconnected")
return return
# randomize the SoftwareId and mark byte to be able to identify the ping # randomize the mark byte to be able to identify the ping reply
# reply, and set most significant (0x8) bit in SoftwareId so that the reply sw_id = _get_next_sw_id()
# is always distinguishable from notifications request_id = 0x0010 | sw_id # was 0x0018 | getrandbits(3)
request_id = 0x0018 | _random_bits(3) request_data = struct.pack("!HBBB", request_id, 0, 0, getrandbits(8))
request_data = _pack('!HBBB', request_id, 0, 0, _random_bits(8))
write(int(handle), devnumber, request_data, long_message) write(int(handle), devnumber, request_data, long_message)
request_started = _timestamp() # we consider timeout from this point request_started = time() # we consider timeout from this point
delta = 0 delta = 0
while delta < _PING_TIMEOUT: while delta < _PING_TIMEOUT:
reply = _read(handle, _PING_TIMEOUT) reply = _read(handle, _PING_TIMEOUT)
if reply: if reply:
report_id, reply_devnumber, reply_data = reply report_id, reply_devnumber, reply_data = reply
if reply_devnumber == devnumber or reply_devnumber == devnumber ^ 0xff: # BT device returning 0x00 if reply_devnumber == devnumber or reply_devnumber == devnumber ^ 0xFF: # BT device returning 0x00
if reply_data[:2] == request_data[:2] and reply_data[4:5] == request_data[-1:]: if reply_data[:2] == request_data[:2] and reply_data[4:5] == request_data[-1:]:
# HID++ 2.0+ device, currently connected # HID++ 2.0+ device, currently connected
return ord(reply_data[2:3]) + ord(reply_data[3:4]) / 10.0 return ord(reply_data[2:3]) + ord(reply_data[3:4]) / 10.0
if report_id == HIDPP_SHORT_MESSAGE_ID and reply_data[:1] == b'\x8F' and \ if (
reply_data[1:3] == request_data[:2]: # error response report_id == HIDPP_SHORT_MESSAGE_ID
and reply_data[:1] == b"\x8f"
and reply_data[1:3] == request_data[:2]
): # error response
error = ord(reply_data[3:4]) error = ord(reply_data[3:4])
if error == _hidpp10.ERROR.invalid_SubID__command: # a valid reply from a HID++ 1.0 device if error == Hidpp10ErrorCode.INVALID_SUB_ID_COMMAND:
# a valid reply from a HID++ 1.0 device
return 1.0 return 1.0
if error == _hidpp10.ERROR.resource_error or error == _hidpp10.ERROR.connection_request_failed: if error in [Hidpp10ErrorCode.RESOURCE_ERROR, Hidpp10ErrorCode.CONNECTION_REQUEST_FAILED]:
return # device unreachable return # device unreachable
if error == _hidpp10.ERROR.unknown_device: # no paired device with that number if error == Hidpp10ErrorCode.UNKNOWN_DEVICE: # no paired device with that number
logger.error('(%s) device %d error on ping request: unknown device', handle, devnumber) logger.error("(%s) device %d error on ping request: unknown device", handle, devnumber)
raise NoSuchDevice(number=devnumber, request=request_id) raise exceptions.NoSuchDevice(number=devnumber, request=request_id)
if notifications_hook: if notifications_hook:
n = make_notification(report_id, reply_devnumber, reply_data) n = make_notification(report_id, reply_devnumber, reply_data)
if n: if n:
notifications_hook(n) notifications_hook(n)
# elif logger.isEnabledFor(logging.DEBUG):
# logger.debug("(%s) ignoring reply %02X [%s]", handle, reply_devnumber, _strhex(reply_data))
delta = _timestamp() - request_started delta = time() - request_started
logger.warning('(%s) timeout (%0.2f/%0.2f) on device %d ping', handle, delta, _PING_TIMEOUT, devnumber) logger.warning("(%s) timeout (%0.2f/%0.2f) on device %d ping", handle, delta, _PING_TIMEOUT, devnumber)
def _read_input_buffer(handle, ihandle, notifications_hook):
"""Consume anything already in the input buffer.
Used by request() and ping() before their write.
"""
while True:
try:
# read whatever is already in the buffer, if any
data = hidapi.read(ihandle, _MAX_READ_SIZE, 0)
except Exception as reason:
logger.error("read failed, assuming receiver %s no longer available", handle)
close(handle)
raise exceptions.NoReceiver(reason=reason) from reason
if data:
if _is_relevant_message(data): # only process messages that pass check
# report_id = ord(data[:1])
if notifications_hook:
n = make_notification(ord(data[:1]), ord(data[1:2]), data[2:])
if n:
notifications_hook(n)
else:
# nothing in the input buffer, we're done
return
def _get_next_sw_id() -> int:
"""Returns 'random' software ID to separate replies from different devices.
Cycle the HID++ 2.0 software ID from 0x2 to 0xF to separate
results and notifications.
"""
if not hasattr(_get_next_sw_id, "software_id"):
_get_next_sw_id.software_id = 0xF
if _get_next_sw_id.software_id < 0xF:
_get_next_sw_id.software_id += 1
else:
_get_next_sw_id.software_id = 2
return _get_next_sw_id.software_id

View File

@ -1,5 +1,3 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
@ -16,235 +14,222 @@
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
## According to Logitech, they use the following product IDs (as of September 2020) """Collection of known Logitech product IDs.
## USB product IDs for receivers: 0xC526 - 0xC5xx
## Wireless PIDs for hidpp10 devices: 0x2006 - 0x2019
## Wireless PIDs for hidpp20 devices: 0x4002 - 0x4097, 0x4101 - 0x4102
## USB product IDs for hidpp20 devices: 0xC07D - 0xC094, 0xC32B - 0xC344
## Bluetooth product IDs (for hidpp20 devices): 0xB012 - 0xB0xx, 0xB32A - 0xB3xx
# USB ids of Logitech wireless receivers. According to Logitech, they use the following product IDs (as of September 2020)
# Only receivers supporting the HID++ protocol can go in here. USB product IDs for receivers: 0xC526 - 0xC5xx
Wireless PIDs for hidpp10 devices: 0x2006 - 0x2019
Wireless PIDs for hidpp20 devices: 0x4002 - 0x4097, 0x4101 - 0x4102
USB product IDs for hidpp20 devices: 0xC07D - 0xC094, 0xC32B - 0xC344
Bluetooth product IDs (for hidpp20 devices): 0xB012 - 0xB0xx, 0xB32A - 0xB3xx
from .descriptors import DEVICES as _DEVICES USB ids of Logitech wireless receivers.
from .i18n import _ Only receivers supporting the HID++ protocol can go in here.
"""
# max_devices is only used for receivers that do not support reading from _R.receiver_info offset 0x03, default to 1 from __future__ import annotations
# may_unpair is only used for receivers that do not support reading from _R.receiver_info offset 0x03, default to False
# unpair is for receivers that do support reading from _R.receiver_info offset 0x03, no default
## should this last be changed so that may_unpair is used for all receivers? writing to _R.receiver_pairing doesn't seem right
# re_pairs determines whether a receiver pairs by replacing existing pairings, default to False
## currently only one receiver is so marked - should there be more?
_DRIVER = ('hid-generic', 'generic-usb', 'logitech-djreceiver') from typing import Any
_bolt_receiver = lambda product_id: { from solaar.i18n import _
'vendor_id': 0x046d,
'product_id': product_id, # max_devices is only used for receivers that do not support reading from Registers.RECEIVER_INFO offset 0x03, default
'usb_interface': 2, # to 1.
'hid_driver': _DRIVER, # noqa: F821 # may_unpair is only used for receivers that do not support reading from Registers.RECEIVER_INFO offset 0x03,
'name': _('Bolt Receiver'), # default to False.
'receiver_kind': 'bolt', # unpair is for receivers that do support reading from Registers.RECEIVER_INFO offset 0x03, no default.
'max_devices': 6, ## should this last be changed so that may_unpair is used for all receivers? writing to Registers.RECEIVER_PAIRING
'may_unpair': True ## doesn't seem right
LOGITECH_VENDOR_ID = 0x046D
def _bolt_receiver(product_id: int) -> dict:
return {
"vendor_id": LOGITECH_VENDOR_ID,
"product_id": product_id,
"usb_interface": 2,
"name": _("Bolt Receiver"),
"receiver_kind": "bolt",
"max_devices": 6,
"may_unpair": True,
} }
_unifying_receiver = lambda product_id: {
'vendor_id': 0x046d, def _unifying_receiver(product_id: int) -> dict:
'product_id': product_id, return {
'usb_interface': 2, "vendor_id": LOGITECH_VENDOR_ID,
'hid_driver': _DRIVER, # noqa: F821 "product_id": product_id,
'name': _('Unifying Receiver'), "usb_interface": 2,
'receiver_kind': 'unifying', "name": _("Unifying Receiver"),
'may_unpair': True "receiver_kind": "unifying",
"may_unpair": True,
} }
_nano_receiver = lambda product_id: {
'vendor_id': 0x046d, def _nano_receiver(product_id: int) -> dict:
'product_id': product_id, return {
'usb_interface': 1, "vendor_id": LOGITECH_VENDOR_ID,
'hid_driver': _DRIVER, # noqa: F821 "product_id": product_id,
'name': _('Nano Receiver'), "usb_interface": 1,
'receiver_kind': 'nano', "name": _("Nano Receiver"),
'may_unpair': False, "receiver_kind": "nano",
're_pairs': True "may_unpair": False,
"re_pairs": True,
} }
_nano_receiver_no_unpair = lambda product_id: {
'vendor_id': 0x046d, def _nano_receiver_no_unpair(product_id: int) -> dict:
'product_id': product_id, return {
'usb_interface': 1, "vendor_id": LOGITECH_VENDOR_ID,
'hid_driver': _DRIVER, # noqa: F821 "product_id": product_id,
'name': _('Nano Receiver'), "usb_interface": 1,
'receiver_kind': 'nano', "name": _("Nano Receiver"),
'may_unpair': False, "receiver_kind": "nano",
'unpair': False, "may_unpair": False,
're_pairs': True "unpair": False,
"re_pairs": True,
} }
_nano_receiver_max2 = lambda product_id: {
'vendor_id': 0x046d, def _nano_receiver_max2(product_id: int) -> dict:
'product_id': product_id, return {
'usb_interface': 1, "vendor_id": LOGITECH_VENDOR_ID,
'hid_driver': _DRIVER, # noqa: F821 "product_id": product_id,
'name': _('Nano Receiver'), "usb_interface": 1,
'receiver_kind': 'nano', "name": _("Nano Receiver"),
'max_devices': 2, "receiver_kind": "nano",
'may_unpair': False, "max_devices": 2,
're_pairs': True "may_unpair": False,
"re_pairs": True,
} }
_nano_receiver_maxn = lambda product_id, max: {
'vendor_id': 0x046d, def _lenovo_receiver(product_id: int) -> dict:
'product_id': product_id, return {
'usb_interface': 1, "vendor_id": 6127,
'hid_driver': _DRIVER, # noqa: F821 "product_id": product_id,
'name': _('Nano Receiver'), "usb_interface": 1,
'receiver_kind': 'nano', "name": _("Nano Receiver"),
'max_devices': max, "receiver_kind": "nano",
'may_unpair': False, "may_unpair": False,
're_pairs': True
} }
_lenovo_receiver = lambda product_id: {
'vendor_id': 0x17ef, def _lightspeed_receiver(product_id: int) -> dict:
'product_id': product_id, return {
'usb_interface': 1, "vendor_id": LOGITECH_VENDOR_ID,
'hid_driver': _DRIVER, # noqa: F821 "product_id": product_id,
'name': _('Nano Receiver'), "usb_interface": 2,
'receiver_kind': 'nano', "receiver_kind": "lightspeed",
'may_unpair': False "name": _("Lightspeed Receiver"),
"may_unpair": False,
} }
_lightspeed_receiver = lambda product_id: {
'vendor_id': 0x046d, def _ex100_receiver(product_id: int) -> dict:
'product_id': product_id, return {
'usb_interface': 2, "vendor_id": LOGITECH_VENDOR_ID,
'hid_driver': _DRIVER, # noqa: F821 "product_id": product_id,
'name': _('Lightspeed Receiver'), "usb_interface": 1,
'may_unpair': False "name": _("EX100 Receiver 27 Mhz"),
"receiver_kind": "27Mhz",
"max_devices": 4,
"may_unpair": False,
"re_pairs": True,
} }
_ex100_receiver = lambda product_id: {
'vendor_id': 0x046d,
'product_id': product_id,
'usb_interface': 1,
'hid_driver': _DRIVER, # noqa: F821
'name': _('EX100 Receiver 27 Mhz'),
'receiver_kind': '27Mhz',
'max_devices': 4,
'may_unpair': False,
're_pairs': True
}
# Receivers added here should also be listed in # Receivers added here should also be listed in
# share/solaar/io.github.pwr_solaar.solaar.metainfo.xml # share/solaar/io.github.pwr_solaar.solaar.meta-info.xml
# Look in https://github.com/torvalds/linux/blob/master/drivers/hid/hid-ids.h # Look in https://github.com/torvalds/linux/blob/master/drivers/hid/hid-ids.h
# Bolt receivers (marked with the yellow lightning bolt logo) # Bolt receivers (marked with the yellow lightning bolt logo)
BOLT_RECEIVER_C548 = _bolt_receiver(0xc548) BOLT_RECEIVER_C548 = _bolt_receiver(0xC548)
# standard Unifying receivers (marked with the orange Unifying logo) # standard Unifying receivers (marked with the orange Unifying logo)
UNIFYING_RECEIVER_C52B = _unifying_receiver(0xc52b) UNIFYING_RECEIVER_C52B = _unifying_receiver(0xC52B)
UNIFYING_RECEIVER_C532 = _unifying_receiver(0xc532) UNIFYING_RECEIVER_C532 = _unifying_receiver(0xC532)
# Nano receivers (usually sold with low-end devices) # Nano receivers (usually sold with low-end devices)
NANO_RECEIVER_ADVANCED = _nano_receiver_no_unpair(0xc52f) NANO_RECEIVER_ADVANCED = _nano_receiver_no_unpair(0xC52F)
NANO_RECEIVER_C518 = _nano_receiver(0xc518) NANO_RECEIVER_C518 = _nano_receiver(0xC518)
NANO_RECEIVER_C51A = _nano_receiver(0xc51a) NANO_RECEIVER_C51A = _nano_receiver(0xC51A)
NANO_RECEIVER_C51B = _nano_receiver(0xc51b) NANO_RECEIVER_C51B = _nano_receiver(0xC51B)
NANO_RECEIVER_C521 = _nano_receiver(0xc521) NANO_RECEIVER_C521 = _nano_receiver(0xC521)
NANO_RECEIVER_C525 = _nano_receiver(0xc525) NANO_RECEIVER_C525 = _nano_receiver(0xC525)
NANO_RECEIVER_C526 = _nano_receiver(0xc526) NANO_RECEIVER_C526 = _nano_receiver(0xC526)
NANO_RECEIVER_C52E = _nano_receiver_no_unpair(0xc52e) NANO_RECEIVER_C52E = _nano_receiver_no_unpair(0xC52E)
NANO_RECEIVER_C531 = _nano_receiver(0xc531) NANO_RECEIVER_C531 = _nano_receiver(0xC531)
NANO_RECEIVER_C534 = _nano_receiver_max2(0xc534) NANO_RECEIVER_C534 = _nano_receiver_max2(0xC534)
NANO_RECEIVER_C535 = _nano_receiver(0xc535) # branded as Dell NANO_RECEIVER_C535 = _nano_receiver(0xC535) # branded as Dell
NANO_RECEIVER_C537 = _nano_receiver(0xc537) NANO_RECEIVER_C537 = _nano_receiver(0xC537)
# NANO_RECEIVER_C542 = _nano_receiver(0xc542) # does not use HID++
NANO_RECEIVER_6042 = _lenovo_receiver(0x6042) NANO_RECEIVER_6042 = _lenovo_receiver(0x6042)
# Lightspeed receivers (usually sold with gaming devices) # Lightspeed receivers (usually sold with gaming devices)
LIGHTSPEED_RECEIVER_C539 = _lightspeed_receiver(0xc539) LIGHTSPEED_RECEIVER_C539 = _lightspeed_receiver(0xC539)
LIGHTSPEED_RECEIVER_C53A = _lightspeed_receiver(0xc53a) LIGHTSPEED_RECEIVER_C53A = _lightspeed_receiver(0xC53A)
LIGHTSPEED_RECEIVER_C53D = _lightspeed_receiver(0xc53d) LIGHTSPEED_RECEIVER_C53D = _lightspeed_receiver(0xC53D)
LIGHTSPEED_RECEIVER_C53F = _lightspeed_receiver(0xc53f) LIGHTSPEED_RECEIVER_C53F = _lightspeed_receiver(0xC53F)
LIGHTSPEED_RECEIVER_C541 = _lightspeed_receiver(0xc541) LIGHTSPEED_RECEIVER_C541 = _lightspeed_receiver(0xC541)
LIGHTSPEED_RECEIVER_C545 = _lightspeed_receiver(0xc545) LIGHTSPEED_RECEIVER_C545 = _lightspeed_receiver(0xC545)
LIGHTSPEED_RECEIVER_C547 = _lightspeed_receiver(0xc547) LIGHTSPEED_RECEIVER_C547 = _lightspeed_receiver(0xC547)
# EX100 old style receiver pre-unifying protocol # EX100 old style receiver pre-unifying protocol
# EX100_27MHZ_RECEIVER_C50C = _ex100_receiver(0xc50C) # in hid/hid-ids.h EX100_27MHZ_RECEIVER_C517 = _ex100_receiver(0xC517)
EX100_27MHZ_RECEIVER_C517 = _ex100_receiver(0xc517)
# EX100_27MHZ_RECEIVER_C51B = _ex100_receiver(0xc51B) # in hid/hid-ids.h
ALL = ( KNOWN_RECEIVERS = {
BOLT_RECEIVER_C548, 0xC548: BOLT_RECEIVER_C548,
UNIFYING_RECEIVER_C52B, 0xC52B: UNIFYING_RECEIVER_C52B,
UNIFYING_RECEIVER_C532, 0xC532: UNIFYING_RECEIVER_C532,
NANO_RECEIVER_ADVANCED, 0xC52F: NANO_RECEIVER_ADVANCED,
NANO_RECEIVER_C518, 0xC518: NANO_RECEIVER_C518,
NANO_RECEIVER_C51A, 0xC51A: NANO_RECEIVER_C51A,
NANO_RECEIVER_C51B, 0xC51B: NANO_RECEIVER_C51B,
NANO_RECEIVER_C521, 0xC521: NANO_RECEIVER_C521,
NANO_RECEIVER_C525, 0xC525: NANO_RECEIVER_C525,
NANO_RECEIVER_C526, 0xC526: NANO_RECEIVER_C526,
NANO_RECEIVER_C52E, 0xC52E: NANO_RECEIVER_C52E,
NANO_RECEIVER_C531, 0xC531: NANO_RECEIVER_C531,
NANO_RECEIVER_C534, 0xC534: NANO_RECEIVER_C534,
NANO_RECEIVER_C535, 0xC535: NANO_RECEIVER_C535,
NANO_RECEIVER_C537, 0xC537: NANO_RECEIVER_C537,
# NANO_RECEIVER_C542, # does not use HID++ 0x6042: NANO_RECEIVER_6042,
NANO_RECEIVER_6042, 0xC539: LIGHTSPEED_RECEIVER_C539,
LIGHTSPEED_RECEIVER_C539, 0xC53A: LIGHTSPEED_RECEIVER_C53A,
LIGHTSPEED_RECEIVER_C53A, 0xC53D: LIGHTSPEED_RECEIVER_C53D,
LIGHTSPEED_RECEIVER_C53D, 0xC53F: LIGHTSPEED_RECEIVER_C53F,
LIGHTSPEED_RECEIVER_C53F, 0xC541: LIGHTSPEED_RECEIVER_C541,
LIGHTSPEED_RECEIVER_C541, 0xC545: LIGHTSPEED_RECEIVER_C545,
LIGHTSPEED_RECEIVER_C545, 0xC547: LIGHTSPEED_RECEIVER_C547,
LIGHTSPEED_RECEIVER_C547, 0xC517: EX100_27MHZ_RECEIVER_C517,
EX100_27MHZ_RECEIVER_C517,
)
_wired_device = lambda product_id, interface: {
'vendor_id': 0x046d,
'product_id': product_id,
'bus_id': 0x3,
'usb_interface': interface,
'isDevice': True
} }
_bt_device = lambda product_id: {'vendor_id': 0x046d, 'product_id': product_id, 'bus_id': 0x5, 'isDevice': True}
DEVICES = [] def get_receiver_info(product_id: int) -> dict[str, Any]:
"""Returns hardcoded information about a Logitech receiver.
for _ignore, d in _DEVICES.items(): Parameters
if d.usbid: ----------
DEVICES.append(_wired_device(d.usbid, d.interface if d.interface else 2)) product_id
if d.btid: Product ID (pid) of the receiver, e.g. 0xC548 for a Logitech
DEVICES.append(_bt_device(d.btid)) Bolt receiver.
Returns
-------
dict[str, Any]
Receiver info with mandatory fields:
- vendor_id
- product_id
def other_device_check(bus_id, vendor_id, product_id): Raises
"""Check whether product is a Logitech USB-connected or Bluetooth device based on bus, vendor, and product IDs ------
This allows Solaar to support receiverless HID++ 2.0 devices that it knows nothing about""" ValueError
if vendor_id != 0x46d: # Logitech If the product ID is unknown.
return """
if bus_id == 0x3: # USB try:
if (product_id >= 0xC07D and product_id <= 0xC094 or product_id >= 0xC32B and product_id <= 0xC344): return KNOWN_RECEIVERS[product_id]
return _wired_device(product_id, 2) except KeyError:
elif bus_id == 0x5: # Bluetooth pass
if (product_id >= 0xB012 and product_id <= 0xB0FF or product_id >= 0xB317 and product_id <= 0xB3FF):
return _bt_device(product_id)
raise ValueError(f"Unknown product ID '0x{product_id:02X}'")
def product_information(usb_id):
if isinstance(usb_id, str):
usb_id = int(usb_id, 16)
for r in ALL:
if usb_id == r.get('product_id'):
return r
return {}
del _DRIVER, _unifying_receiver, _nano_receiver, _lenovo_receiver, _lightspeed_receiver

View File

@ -1,6 +1,5 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by ## it under the terms of the GNU General Public License as published by
@ -15,44 +14,290 @@
## You should have received a copy of the GNU General Public License along ## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from __future__ import annotations
# Some common functions and types. import binascii
import dataclasses
import typing
from binascii import hexlify as _hexlify from enum import Flag
from collections import namedtuple from enum import IntEnum
from typing import Generator
from typing import Iterable
from typing import Optional
from typing import Union
import yaml as _yaml import yaml
is_string = lambda d: isinstance(d, str) from solaar.i18n import _
# if typing.TYPE_CHECKING:
# from logitech_receiver.hidpp20_constants import FirmwareKind
#
LOGITECH_VENDOR_ID = 0x046D
def crc16(data: bytes): def crc16(data: bytes):
''' """
CRC-16 (CCITT) implemented with a precomputed lookup table CRC-16 (CCITT) implemented with a precomputed lookup table
''' """
table = [ table = [
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0x0000,
0xF1EF, 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0x1021,
0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0x2042,
0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738, 0x3063,
0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0x4084,
0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0x50A5,
0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0x60C6,
0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0x70E7,
0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0x8108,
0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0x9129,
0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xA14A,
0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xB16B,
0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xC18C,
0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xD1AD,
0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xE1CE,
0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xF1EF,
0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1231,
0x1EF0 0x0210,
0x3273,
0x2252,
0x52B5,
0x4294,
0x72F7,
0x62D6,
0x9339,
0x8318,
0xB37B,
0xA35A,
0xD3BD,
0xC39C,
0xF3FF,
0xE3DE,
0x2462,
0x3443,
0x0420,
0x1401,
0x64E6,
0x74C7,
0x44A4,
0x5485,
0xA56A,
0xB54B,
0x8528,
0x9509,
0xE5EE,
0xF5CF,
0xC5AC,
0xD58D,
0x3653,
0x2672,
0x1611,
0x0630,
0x76D7,
0x66F6,
0x5695,
0x46B4,
0xB75B,
0xA77A,
0x9719,
0x8738,
0xF7DF,
0xE7FE,
0xD79D,
0xC7BC,
0x48C4,
0x58E5,
0x6886,
0x78A7,
0x0840,
0x1861,
0x2802,
0x3823,
0xC9CC,
0xD9ED,
0xE98E,
0xF9AF,
0x8948,
0x9969,
0xA90A,
0xB92B,
0x5AF5,
0x4AD4,
0x7AB7,
0x6A96,
0x1A71,
0x0A50,
0x3A33,
0x2A12,
0xDBFD,
0xCBDC,
0xFBBF,
0xEB9E,
0x9B79,
0x8B58,
0xBB3B,
0xAB1A,
0x6CA6,
0x7C87,
0x4CE4,
0x5CC5,
0x2C22,
0x3C03,
0x0C60,
0x1C41,
0xEDAE,
0xFD8F,
0xCDEC,
0xDDCD,
0xAD2A,
0xBD0B,
0x8D68,
0x9D49,
0x7E97,
0x6EB6,
0x5ED5,
0x4EF4,
0x3E13,
0x2E32,
0x1E51,
0x0E70,
0xFF9F,
0xEFBE,
0xDFDD,
0xCFFC,
0xBF1B,
0xAF3A,
0x9F59,
0x8F78,
0x9188,
0x81A9,
0xB1CA,
0xA1EB,
0xD10C,
0xC12D,
0xF14E,
0xE16F,
0x1080,
0x00A1,
0x30C2,
0x20E3,
0x5004,
0x4025,
0x7046,
0x6067,
0x83B9,
0x9398,
0xA3FB,
0xB3DA,
0xC33D,
0xD31C,
0xE37F,
0xF35E,
0x02B1,
0x1290,
0x22F3,
0x32D2,
0x4235,
0x5214,
0x6277,
0x7256,
0xB5EA,
0xA5CB,
0x95A8,
0x8589,
0xF56E,
0xE54F,
0xD52C,
0xC50D,
0x34E2,
0x24C3,
0x14A0,
0x0481,
0x7466,
0x6447,
0x5424,
0x4405,
0xA7DB,
0xB7FA,
0x8799,
0x97B8,
0xE75F,
0xF77E,
0xC71D,
0xD73C,
0x26D3,
0x36F2,
0x0691,
0x16B0,
0x6657,
0x7676,
0x4615,
0x5634,
0xD94C,
0xC96D,
0xF90E,
0xE92F,
0x99C8,
0x89E9,
0xB98A,
0xA9AB,
0x5844,
0x4865,
0x7806,
0x6827,
0x18C0,
0x08E1,
0x3882,
0x28A3,
0xCB7D,
0xDB5C,
0xEB3F,
0xFB1E,
0x8BF9,
0x9BD8,
0xABBB,
0xBB9A,
0x4A75,
0x5A54,
0x6A37,
0x7A16,
0x0AF1,
0x1AD0,
0x2AB3,
0x3A92,
0xFD2E,
0xED0F,
0xDD6C,
0xCD4D,
0xBDAA,
0xAD8B,
0x9DE8,
0x8DC9,
0x7C26,
0x6C07,
0x5C64,
0x4C45,
0x3CA2,
0x2C83,
0x1CE0,
0x0CC1,
0xEF1F,
0xFF3E,
0xCF5D,
0xDF7C,
0xAF9B,
0xBFBA,
0x8FD9,
0x9FF8,
0x6E17,
0x7E36,
0x4E55,
0x5E74,
0x2E93,
0x3EB2,
0x0ED1,
0x1EF0,
] ]
crc = 0xFFFF crc = 0xFFFF
@ -69,7 +314,7 @@ class NamedInt(int):
(case-insensitive).""" (case-insensitive)."""
def __new__(cls, value, name): def __new__(cls, value, name):
assert is_string(name) assert isinstance(name, str)
obj = int.__new__(cls, value) obj = int.__new__(cls, value)
obj.name = str(name) obj.name = str(name)
return obj return obj
@ -84,11 +329,11 @@ class NamedInt(int):
return int(self) == int(other) and self.name == other.name return int(self) == int(other) and self.name == other.name
if isinstance(other, int): if isinstance(other, int):
return int(self) == int(other) return int(self) == int(other)
if is_string(other): if isinstance(other, str):
return self.name.lower() == other.lower() return self.name.lower() == other.lower()
# this should catch comparisons with bytes in Py3 # this should catch comparisons with bytes in Py3
if other is not None: if other is not None:
raise TypeError('Unsupported type ' + str(type(other))) raise TypeError(f"Unsupported type {str(type(other))}")
def __ne__(self, other): def __ne__(self, other):
return not self.__eq__(other) return not self.__eq__(other)
@ -100,20 +345,20 @@ class NamedInt(int):
return self.name return self.name
def __repr__(self): def __repr__(self):
return 'NamedInt(%d, %r)' % (int(self), self.name) return f"NamedInt({int(self)}, {self.name!r})"
@classmethod @classmethod
def from_yaml(cls, loader, node): def from_yaml(cls, loader, node):
args = loader.construct_mapping(node) args = loader.construct_mapping(node)
return cls(value=args['value'], name=args['name']) return cls(value=args["value"], name=args["name"])
@classmethod @classmethod
def to_yaml(cls, dumper, data): def to_yaml(cls, dumper, data):
return dumper.represent_mapping('!NamedInt', {'value': int(data), 'name': data.name}, flow_style=True) return dumper.represent_mapping("!NamedInt", {"value": int(data), "name": data.name}, flow_style=True)
_yaml.SafeLoader.add_constructor('!NamedInt', NamedInt.from_yaml) yaml.SafeLoader.add_constructor("!NamedInt", NamedInt.from_yaml)
_yaml.add_representer(NamedInt, NamedInt.to_yaml) yaml.add_representer(NamedInt, NamedInt.to_yaml)
class NamedInts: class NamedInts:
@ -129,17 +374,15 @@ class NamedInts:
if the value already exists in the set (int or string), ValueError will be if the value already exists in the set (int or string), ValueError will be
raised. raised.
""" """
__slots__ = ('__dict__', '_values', '_indexed', '_fallback', '_is_sorted')
def __init__(self, dict=None, **kwargs): __slots__ = ("__dict__", "_values", "_indexed", "_fallback", "_is_sorted")
def __init__(self, dict_=None, **kwargs):
def _readable_name(n): def _readable_name(n):
if not is_string(n): return n.replace("__", "/").replace("_", " ")
raise TypeError('expected string, got ' + str(type(n)))
return n.replace('__', '/').replace('_', ' ')
# print (repr(kwargs)) # print (repr(kwargs))
elements = dict if dict else kwargs elements = dict_ if dict_ else kwargs
values = {k: NamedInt(v, _readable_name(k)) for (k, v) in elements.items()} values = {k: NamedInt(v, _readable_name(k)) for (k, v) in elements.items()}
self.__dict__ = values self.__dict__ = values
self._is_sorted = False self._is_sorted = False
@ -163,13 +406,13 @@ class NamedInts:
def flag_names(self, value): def flag_names(self, value):
unknown_bits = value unknown_bits = value
for k in self._indexed: for k in self._indexed:
assert bin(k).count('1') == 1 assert bin(k).count("1") == 1
if k & value == k: if k & value == k:
unknown_bits &= ~k unknown_bits &= ~k
yield str(self._indexed[k]) yield str(self._indexed[k])
if unknown_bits: if unknown_bits:
yield 'unknown:%06X' % unknown_bits yield f"unknown:{unknown_bits:06X}"
def _sort_values(self): def _sort_values(self):
self._values = sorted(self._values) self._values = sorted(self._values)
@ -187,10 +430,10 @@ class NamedInts:
self._sort_values() self._sort_values()
return value return value
elif is_string(index): elif isinstance(index, str):
if index in self.__dict__: if index in self.__dict__:
return self.__dict__[index] return self.__dict__[index]
return (next((x for x in self._values if str(x) == index), None)) return next((x for x in self._values if str(x) == index), None)
elif isinstance(index, slice): elif isinstance(index, slice):
values = self._values if self._is_sorted else sorted(self._values) values = self._values if self._is_sorted else sorted(self._values)
@ -224,17 +467,17 @@ class NamedInts:
def __setitem__(self, index, name): def __setitem__(self, index, name):
assert isinstance(index, int), type(index) assert isinstance(index, int), type(index)
if isinstance(name, NamedInt): if isinstance(name, NamedInt):
assert int(index) == int(name), repr(index) + ' ' + repr(name) assert int(index) == int(name), f"{repr(index)} {repr(name)}"
value = name value = name
elif is_string(name): elif isinstance(name, str):
value = NamedInt(index, name) value = NamedInt(index, name)
else: else:
raise TypeError('name must be a string') raise TypeError("name must be a string")
if str(value) in self.__dict__: if str(value) in self.__dict__:
raise ValueError('%s (%d) already known' % (value, int(value))) raise ValueError(f"{value} ({int(value)}) already known")
if int(value) in self._indexed: if int(value) in self._indexed:
raise ValueError('%d (%s) already known' % (int(value), value)) raise ValueError(f"{int(value)} ({value}) already known")
self._values.append(value) self._values.append(value)
self._is_sorted = False self._is_sorted = False
@ -247,7 +490,7 @@ class NamedInts:
return self[value] == value return self[value] == value
elif isinstance(value, int): elif isinstance(value, int):
return value in self._indexed return value in self._indexed
elif is_string(value): elif isinstance(value, str):
return value in self.__dict__ or value in self._values return value in self.__dict__ or value in self._values
def __iter__(self): def __iter__(self):
@ -257,14 +500,41 @@ class NamedInts:
return len(self._values) return len(self._values)
def __repr__(self): def __repr__(self):
return 'NamedInts(%s)' % ', '.join(repr(v) for v in self._values) return f"NamedInts({', '.join(repr(v) for v in self._values)})"
def __or__(self, other): def __or__(self, other):
return NamedInts(**self.__dict__, **other.__dict__) return NamedInts(**self.__dict__, **other.__dict__)
def __eq__(self, other):
return isinstance(other, self.__class__) and self._values == other._values
def flag_names(enum_class: Iterable, value: int) -> Generator[str]:
"""Extracts single bit flags from a (binary) number.
Parameters
----------
enum_class
Enum class to extract flags from.
value
Number to extract binary flags from.
"""
indexed = {item.value: item.name for item in enum_class}
unknown_bits = value
for k in indexed:
# Ensure that the key (flag value) is a power of 2 (a single bit flag)
assert bin(k).count("1") == 1
if k & value == k:
unknown_bits &= ~k
yield indexed[k].lower()
# Yield any remaining unknown bits
if unknown_bits != 0:
yield f"unknown:{unknown_bits:06X}"
class UnsortedNamedInts(NamedInts): class UnsortedNamedInts(NamedInts):
def _sort_values(self): def _sort_values(self):
pass pass
@ -276,18 +546,18 @@ class UnsortedNamedInts(NamedInts):
def strhex(x): def strhex(x):
assert x is not None assert x is not None
"""Produce a hex-string representation of a sequence of bytes.""" """Produce a hex-string representation of a sequence of bytes."""
return _hexlify(x).decode('ascii').upper() return binascii.hexlify(x).decode("ascii").upper()
def bytes2int(x, signed=False): def bytes2int(x, signed=False):
return int.from_bytes(x, signed=signed, byteorder='big') return int.from_bytes(x, signed=signed, byteorder="big")
def int2bytes(x, count=None, signed=False): def int2bytes(x, count=None, signed=False):
if count: if count:
return x.to_bytes(length=count, byteorder='big', signed=signed) return x.to_bytes(length=count, byteorder="big", signed=signed)
else: else:
return x.to_bytes(length=8, byteorder='big', signed=signed).lstrip(b'\x00') return x.to_bytes(length=8, byteorder="big", signed=signed).lstrip(b"\x00")
class KwException(Exception): class KwException(Exception):
@ -305,9 +575,102 @@ class KwException(Exception):
return self.args[0].get(k) # was self.args[0][k] return self.args[0].get(k) # was self.args[0][k]
"""Firmware information.""" class FirmwareKind(IntEnum):
FirmwareInfo = namedtuple('FirmwareInfo', ['kind', 'name', 'version', 'extras']) Firmware = 0x00
Bootloader = 0x01
Hardware = 0x02
Other = 0x03
BATTERY_APPROX = NamedInts(empty=0, critical=5, low=20, good=50, full=90)
del namedtuple @dataclasses.dataclass
class FirmwareInfo:
kind: FirmwareKind
name: str
version: str
extras: str | None
class BatteryStatus(Flag):
DISCHARGING = 0x00
RECHARGING = 0x01
ALMOST_FULL = 0x02
FULL = 0x03
SLOW_RECHARGE = 0x04
INVALID_BATTERY = 0x05
THERMAL_ERROR = 0x06
class BatteryLevelApproximation(IntEnum):
EMPTY = 0
CRITICAL = 5
LOW = 20
GOOD = 50
FULL = 90
@dataclasses.dataclass
class Battery:
"""Information about the current state of a battery"""
ATTENTION_LEVEL = 5
level: Optional[Union[BatteryLevelApproximation, int]]
next_level: Optional[Union[NamedInt, int]]
status: Optional[BatteryStatus]
voltage: Optional[int]
light_level: Optional[int] = None # light level for devices with solaar recharging
def __post_init__(self):
if self.level is None: # infer level from status if needed and possible
if self.status == BatteryStatus.FULL:
self.level = BatteryLevelApproximation.FULL
elif self.status in (BatteryStatus.ALMOST_FULL, BatteryStatus.RECHARGING):
self.level = BatteryLevelApproximation.GOOD
elif self.status == BatteryStatus.SLOW_RECHARGE:
self.level = BatteryLevelApproximation.LOW
def ok(self) -> bool:
return self.status not in (BatteryStatus.INVALID_BATTERY, BatteryStatus.THERMAL_ERROR) and (
self.level is None or self.level > Battery.ATTENTION_LEVEL
)
def charging(self) -> bool:
return self.status in (
BatteryStatus.RECHARGING,
BatteryStatus.ALMOST_FULL,
BatteryStatus.FULL,
BatteryStatus.SLOW_RECHARGE,
)
def to_str(self) -> str:
if isinstance(self.level, BatteryLevelApproximation):
level = self.level.name.lower()
status = self.status.name.lower().replace("_", " ") if self.status is not None else "Unknown"
return _("Battery: %(level)s (%(status)s)") % {"level": _(level), "status": _(status)}
elif isinstance(self.level, int):
status = self.status.name.lower().replace("_", " ") if self.status is not None else "Unknown"
return _("Battery: %(percent)d%% (%(status)s)") % {"percent": self.level, "status": _(status)}
return ""
class Alert(IntEnum):
NONE = 0x00
NOTIFICATION = 0x01
SHOW_WINDOW = 0x02
ATTENTION = 0x04
ALL = 0xFF
class Notification(IntEnum):
NO_OPERATION = 0x00
CONNECT_DISCONNECT = 0x40
DJ_PAIRING = 0x41
CONNECTED = 0x42
RAW_INPUT = 0x49
PAIRING_LOCK = 0x4A
POWER = 0x4B
class BusID(IntEnum):
USB = 0x03
BLUETOOTH = 0x05

View File

@ -1,5 +1,3 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
@ -16,30 +14,44 @@
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Devices (not receivers) known to Solaar.
# Solaar can handle many recent devices without having any entry here.
# An entry should only be added to fix problems, such as
# - the device's device ID or WPID falls outside the range that Solaar searches
# - the device uses a USB interface other than 2
# - the name or codename should be different from what the device reports
from collections import namedtuple """Devices (not receivers) known to Solaar.
from . import settings_templates as _ST Solaar can handle many recent devices without having any entry here.
from .common import NamedInts as _NamedInts An entry should only be added to fix problems, such as
from .hidpp10 import DEVICE_KIND as _DK - the device's device ID or WPID falls outside the range that Solaar searches
from .hidpp10 import REGISTERS as _R - the device uses a USB interface other than 2
- the name or codename should be different from what the device reports
"""
# from .hidpp10_constants import DEVICE_KIND
# from .hidpp10_constants import Registers as Reg
#
class _DeviceDescriptor:
def __init__(
self,
name=None,
kind=None,
wpid=None,
codename=None,
protocol=None,
registers=None,
usbid=None,
interface=None,
btid=None,
):
self.name = name
self.kind = kind
self.wpid = wpid
self.codename = codename
self.protocol = protocol
self.registers = registers
self.usbid = usbid
self.interface = interface
self.btid = btid
self.settings = None
_DeviceDescriptor = namedtuple(
'_DeviceDescriptor',
('name', 'kind', 'wpid', 'codename', 'protocol', 'registers', 'settings', 'usbid', 'interface', 'btid')
)
del namedtuple
DEVICES_WPID = {} DEVICES_WPID = {}
DEVICES = {} DEVICES = {}
@ -57,24 +69,35 @@ def _D(
interface=None, interface=None,
btid=None, btid=None,
): ):
if kind is None: if kind is None:
kind = ( kind = (
_DK.mouse if 'Mouse' in name else _DK.keyboard if 'Keyboard' in name else _DK.numpad DEVICE_KIND.mouse
if 'Number Pad' in name else _DK.touchpad if 'Touchpad' in name else _DK.trackball if 'Trackball' in name else None if "Mouse" in name
else DEVICE_KIND.keyboard
if "Keyboard" in name
else DEVICE_KIND.numpad
if "Number Pad" in name
else DEVICE_KIND.touchpad
if "Touchpad" in name
else DEVICE_KIND.trackball
if "Trackball" in name
else None
) )
assert kind is not None, 'descriptor for %s does not have kind set' % name assert kind is not None, f"descriptor for {name} does not have kind set"
if protocol is not None: if protocol is not None:
if wpid: if wpid:
for w in wpid if isinstance(wpid, tuple) else (wpid,): for w in wpid if isinstance(wpid, tuple) else (wpid,):
if protocol > 1.0: if protocol > 1.0:
assert w[0:1] == '4', '%s has protocol %0.1f, wpid %s' % (name, protocol, w) assert w[0:1] == "4", f"{name} has protocol {protocol:0.1f}, wpid {w}"
else: else:
if w[0:1] == '1': if w[0:1] == "1":
assert kind == _DK.mouse, '%s has protocol %0.1f, wpid %s' % (name, protocol, w) assert kind == DEVICE_KIND.mouse, f"{name} has protocol {protocol:0.1f}, wpid {w}"
elif w[0:1] == '2': elif w[0:1] == "2":
assert kind in (_DK.keyboard, _DK.numpad), '%s has protocol %0.1f, wpid %s' % (name, protocol, w) assert kind in (
DEVICE_KIND.keyboard,
DEVICE_KIND.numpad,
), f"{name} has protocol {protocol:0.1f}, wpid {w}"
device_descriptor = _DeviceDescriptor( device_descriptor = _DeviceDescriptor(
name=name, name=name,
@ -83,26 +106,25 @@ def _D(
codename=codename, codename=codename,
protocol=protocol, protocol=protocol,
registers=registers, registers=registers,
settings=settings,
usbid=usbid, usbid=usbid,
interface=interface, interface=interface,
btid=btid btid=btid,
) )
if usbid: if usbid:
found = get_usbid(usbid) found = get_usbid(usbid)
assert found is None, 'duplicate usbid in device descriptors: %s' % (found, ) assert found is None, f"duplicate usbid in device descriptors: {found}"
if btid: if btid:
found = get_btid(btid) found = get_btid(btid)
assert found is None, 'duplicate btid in device descriptors: %s' % (found, ) assert found is None, f"duplicate btid in device descriptors: {found}"
assert codename not in DEVICES, 'duplicate codename in device descriptors: %s' % (DEVICES[codename], ) assert codename not in DEVICES, f"duplicate codename in device descriptors: {DEVICES[codename]}"
if codename: if codename:
DEVICES[codename] = device_descriptor DEVICES[codename] = device_descriptor
if wpid: if wpid:
for w in wpid if isinstance(wpid, tuple) else (wpid,): for w in wpid if isinstance(wpid, tuple) else (wpid,):
assert w not in DEVICES_WPID, 'duplicate wpid in device descriptors: %s' % (DEVICES_WPID[w], ) assert w not in DEVICES_WPID, f"duplicate wpid in device descriptors: {DEVICES_WPID[w]}"
DEVICES_WPID[w] = device_descriptor DEVICES_WPID[w] = device_descriptor
@ -157,177 +179,288 @@ def get_btid(btid):
# The 'protocol' and 'wpid' fields are optional (they can be discovered at # The 'protocol' and 'wpid' fields are optional (they can be discovered at
# runtime), but specifying them here speeds up device discovery and reduces the # runtime), but specifying them here speeds up device discovery and reduces the
# USB traffic Solaar has to do to fully identify peripherals. # USB traffic Solaar has to do to fully identify peripherals.
# Same goes for HID++ 2.0 feature settings (like _feature_fn_swap).
# #
# The 'registers' field indicates read-only registers, specifying a state. These # The 'registers' field indicates read-only registers, specifying a state. These
# are valid (AFAIK) only to HID++ 1.0 devices. # are valid (AFAIK) only to HID++ 1.0 devices.
# The 'settings' field indicates a read/write register; based on them Solaar # The 'settings' field indicates a read/write register; based on them Solaar
# generates, at runtime, the settings controls in the device panel. HID++ 1.0 # generates, at runtime, the settings controls in the device panel.
# devices may only have register-based settings; HID++ 2.0 devices may only have # Solaar now sets up this field in settings_templates.py to eliminate a imports loop.
# HID++ 1.0 devices may only have register-based settings; HID++ 2.0 devices may only have
# feature-based settings. # feature-based settings.
# Devices are organized by kind # Devices are organized by kind
# Within kind devices are sorted by wpid, then by usbid, then by btid, with missing values sorted later # Within kind devices are sorted by wpid, then by usbid, then by btid, with missing values sorted later
# yapf: disable
# Keyboards # Keyboards
_D('Wireless Keyboard EX110', codename='EX110', protocol=1.0, wpid='0055', registers=(_R.battery_status, )) _D("Wireless Keyboard EX110", codename="EX110", protocol=1.0, wpid="0055", registers=(Reg.BATTERY_STATUS,))
_D('Wireless Keyboard S510', codename='S510', protocol=1.0, wpid='0056', registers=(_R.battery_status, )) _D("Wireless Keyboard S510", codename="S510", protocol=1.0, wpid="0056", registers=(Reg.BATTERY_STATUS,))
_D('Wireless Wave Keyboard K550', codename='K550', protocol=1.0, wpid='0060', registers=(_R.battery_status, ), _D("Wireless Wave Keyboard K550", codename="K550", protocol=1.0, wpid="0060", registers=(Reg.BATTERY_STATUS,))
settings=[_ST.RegisterFnSwap]) _D("Wireless Keyboard EX100", codename="EX100", protocol=1.0, wpid="0065", registers=(Reg.BATTERY_STATUS,))
_D('Wireless Keyboard EX100', codename='EX100', protocol=1.0, wpid='0065', registers=(_R.battery_status, )) _D("Wireless Keyboard MK300", codename="MK300", protocol=1.0, wpid="0068", registers=(Reg.BATTERY_STATUS,))
_D('Wireless Keyboard MK300', codename='MK300', protocol=1.0, wpid='0068', registers=(_R.battery_status, )) _D("Number Pad N545", codename="N545", protocol=1.0, wpid="2006", registers=(Reg.BATTERY_STATUS,))
_D('Number Pad N545', codename='N545', protocol=1.0, wpid='2006', registers=(_R.battery_status, )) _D("Wireless Compact Keyboard K340", codename="K340", protocol=1.0, wpid="2007", registers=(Reg.BATTERY_STATUS,))
_D('Wireless Compact Keyboard K340', codename='K340', protocol=1.0, wpid='2007', registers=(_R.battery_status, )) _D("Wireless Keyboard MK700", codename="MK700", protocol=1.0, wpid="2008", registers=(Reg.BATTERY_STATUS,))
_D('Wireless Keyboard MK700', codename='MK700', protocol=1.0, wpid='2008', _D("Wireless Wave Keyboard K350", codename="K350", protocol=1.0, wpid="200A", registers=(Reg.BATTERY_STATUS,))
registers=(_R.battery_status, ), settings=[_ST.RegisterFnSwap]) _D("Wireless Keyboard MK320", codename="MK320", protocol=1.0, wpid="200F", registers=(Reg.BATTERY_STATUS,))
_D('Wireless Wave Keyboard K350', codename='K350', protocol=1.0, wpid='200A', registers=(_R.battery_status, )) _D(
_D('Wireless Keyboard MK320', codename='MK320', protocol=1.0, wpid='200F', registers=(_R.battery_status, )) "Wireless Illuminated Keyboard K800",
_D('Wireless Illuminated Keyboard K800', codename='K800', protocol=1.0, wpid='2010', codename="K800",
registers=(_R.battery_status, _R.three_leds), settings=[_ST.RegisterFnSwap, _ST.RegisterHandDetection]) protocol=1.0,
_D('Wireless Keyboard K520', codename='K520', protocol=1.0, wpid='2011', wpid="2010",
registers=(_R.battery_status, ), settings=[_ST.RegisterFnSwap]) registers=(Reg.BATTERY_STATUS, Reg.THREE_LEDS),
_D('Wireless Solar Keyboard K750', codename='K750', protocol=2.0, wpid='4002', settings=[_ST.FnSwap]) )
_D('Wireless Keyboard K270 (unifying)', codename='K270', protocol=2.0, wpid='4003') _D("Wireless Keyboard K520", codename="K520", protocol=1.0, wpid="2011", registers=(Reg.BATTERY_STATUS,))
_D('Wireless Keyboard K360', codename='K360', protocol=2.0, wpid='4004', settings=[_ST.FnSwap]) _D("Wireless Solar Keyboard K750", codename="K750", protocol=2.0, wpid="4002")
_D('Wireless Keyboard K230', codename='K230', protocol=2.0, wpid='400D') _D("Wireless Keyboard K270 (unifying)", codename="K270", protocol=2.0, wpid="4003")
_D('Wireless Touch Keyboard K400', codename='K400', protocol=2.0, wpid=('400E', '4024'), settings=[_ST.FnSwap]) _D("Wireless Keyboard K360", codename="K360", protocol=2.0, wpid="4004")
_D('Wireless Keyboard MK270', codename='MK270', protocol=2.0, wpid='4023', settings=[_ST.FnSwap]) _D("Wireless Keyboard K230", codename="K230", protocol=2.0, wpid="400D")
_D('Illuminated Living-Room Keyboard K830', codename='K830', protocol=2.0, wpid='4032', settings=[_ST.NewFnSwap]) _D("Wireless Touch Keyboard K400", codename="K400", protocol=2.0, wpid=("400E", "4024"))
_D('Wireless Touch Keyboard K400 Plus', codename='K400 Plus', protocol=2.0, wpid='404D') _D("Wireless Keyboard MK270", codename="MK270", protocol=2.0, wpid="4023")
_D('Wireless Multi-Device Keyboard K780', codename='K780', protocol=4.5, wpid='405B', settings=[_ST.NewFnSwap]) _D("Illuminated Living-Room Keyboard K830", codename="K830", protocol=2.0, wpid="4032")
_D('Wireless Keyboard K375s', codename='K375s', protocol=2.0, wpid='4061', settings=[_ST.K375sFnSwap]) _D("Wireless Touch Keyboard K400 Plus", codename="K400 Plus", protocol=2.0, wpid="404D")
_D('Craft Advanced Keyboard', codename='Craft', protocol=4.5, wpid='4066', btid=0xB350) _D("Wireless Multi-Device Keyboard K780", codename="K780", protocol=4.5, wpid="405B")
_D('Wireless Illuminated Keyboard K800 new', codename='K800 new', protocol=4.5, wpid='406E', settings=[_ST.FnSwap]) _D("Wireless Keyboard K375s", codename="K375s", protocol=2.0, wpid="4061")
_D('Wireless Keyboard K470', codename='K470', protocol=4.5, wpid='4075', settings=[_ST.FnSwap]) _D("Craft Advanced Keyboard", codename="Craft", protocol=4.5, wpid="4066", btid=0xB350)
_D('MX Keys Keyboard', codename='MX Keys', protocol=4.5, wpid='408A', btid=0xB35B) _D("Wireless Illuminated Keyboard K800 new", codename="K800 new", protocol=4.5, wpid="406E")
_D('G915 TKL LIGHTSPEED Wireless RGB Mechanical Gaming Keyboard', codename='G915 TKL', protocol=4.2, wpid='408E', usbid=0xC343) _D("Wireless Keyboard K470", codename="K470", protocol=4.5, wpid="4075")
_D('Illuminated Keyboard', codename='Illuminated', protocol=1.0, usbid=0xc318, interface=1, settings=[_ST.RegisterFnSwap]) _D("MX Keys Keyboard", codename="MX Keys", protocol=4.5, wpid="408A", btid=0xB35B)
_D('G213 Prodigy Gaming Keyboard', codename='G213', usbid=0xc336, interface=1) _D(
_D('G512 RGB Mechanical Gaming Keyboard', codename='G512', usbid=0xc33c, interface=1) "G915 TKL LIGHTSPEED Wireless RGB Mechanical Gaming Keyboard",
_D('G815 Mechanical Keyboard', codename='G815', usbid=0xc33f, interface=1) codename="G915 TKL",
_D('diNovo Edge Keyboard', codename='diNovo', protocol=1.0, wpid='C714', settings=[_ST.RegisterFnSwap]) protocol=4.2,
_D('K845 Mechanical Keyboard', codename='K845', usbid=0xc341, interface=3) wpid="408E",
usbid=0xC343,
)
_D("Illuminated Keyboard", codename="Illuminated", protocol=1.0, usbid=0xC318, interface=1)
_D("G213 Prodigy Gaming Keyboard", codename="G213", usbid=0xC336, interface=1)
_D("G512 RGB Mechanical Gaming Keyboard", codename="G512", usbid=0xC33C, interface=1)
_D("G815 Mechanical Keyboard", codename="G815", usbid=0xC33F, interface=1)
_D("diNovo Edge Keyboard", codename="diNovo", protocol=1.0, wpid="C714")
_D("K845 Mechanical Keyboard", codename="K845", usbid=0xC341, interface=3)
# Mice # Mice
_D('LX5 Cordless Mouse', codename='LX5', protocol=1.0, wpid='0036', registers=(_R.battery_status, )) _D("LX5 Cordless Mouse", codename="LX5", protocol=1.0, wpid="0036", registers=(Reg.BATTERY_STATUS,))
_D('LX7 Cordless Laser Mouse', codename='LX7', protocol=1.0, wpid='0039', registers=(_R.battery_status, )) _D("LX7 Cordless Laser Mouse", codename="LX7", protocol=1.0, wpid="0039", registers=(Reg.BATTERY_STATUS,))
_D('Wireless Wave Mouse M550', codename='M550', protocol=1.0, wpid='003C', registers=(_R.battery_status, )) _D("Wireless Wave Mouse M550", codename="M550", protocol=1.0, wpid="003C", registers=(Reg.BATTERY_STATUS,))
_D('Wireless Mouse EX100', codename='EX100m', protocol=1.0, wpid='003F', registers=(_R.battery_status, )) _D("Wireless Mouse EX100", codename="EX100m", protocol=1.0, wpid="003F", registers=(Reg.BATTERY_STATUS,))
_D('Wireless Mouse M30', codename='M30', protocol=1.0, wpid='0085', registers=(_R.battery_status, )) _D("Wireless Mouse M30", codename="M30", protocol=1.0, wpid="0085", registers=(Reg.BATTERY_STATUS,))
_D('MX610 Laser Cordless Mouse', codename='MX610', protocol=1.0, wpid='1001', registers=(_R.battery_status, )) _D("MX610 Laser Cordless Mouse", codename="MX610", protocol=1.0, wpid="1001", registers=(Reg.BATTERY_STATUS,))
_D('G7 Cordless Laser Mouse', codename='G7', protocol=1.0, wpid='1002', registers=(_R.battery_status, )) _D("G7 Cordless Laser Mouse", codename="G7", protocol=1.0, wpid="1002", registers=(Reg.BATTERY_STATUS,))
_D('V400 Laser Cordless Mouse', codename='V400', protocol=1.0, wpid='1003', registers=(_R.battery_status, )) _D("V400 Laser Cordless Mouse", codename="V400", protocol=1.0, wpid="1003", registers=(Reg.BATTERY_STATUS,))
_D('MX610 Left-Handled Mouse', codename='MX610L', protocol=1.0, wpid='1004', registers=(_R.battery_status, )) _D("MX610 Left-Handled Mouse", codename="MX610L", protocol=1.0, wpid="1004", registers=(Reg.BATTERY_STATUS,))
_D('V450 Laser Cordless Mouse', codename='V450', protocol=1.0, wpid='1005', registers=(_R.battery_status, )) _D("V450 Laser Cordless Mouse", codename="V450", protocol=1.0, wpid="1005", registers=(Reg.BATTERY_STATUS,))
_D('VX Revolution', codename='VX Revolution', kind=_DK.mouse, protocol=1.0, wpid=('1006', '100D', '0612'), _D(
registers=(_R.battery_charge, )) "VX Revolution",
_D('MX Air', codename='MX Air', protocol=1.0, kind=_DK.mouse, wpid=('1007', '100E'), registers=(_R.battery_charge, )) codename="VX Revolution",
_D('MX Revolution', codename='MX Revolution', protocol=1.0, kind=_DK.mouse, wpid=('1008', '100C'), kind=DEVICE_KIND.mouse,
registers=(_R.battery_charge, )) protocol=1.0,
_D('MX620 Laser Cordless Mouse', codename='MX620', protocol=1.0, wpid=('100A', '1016'), registers=(_R.battery_charge, )) wpid=("1006", "100D", "0612"),
_D('VX Nano Cordless Laser Mouse', codename='VX Nano', protocol=1.0, wpid=('100B', '100F'), registers=(Reg.BATTERY_CHARGE,),
registers=(_R.battery_charge, ), settings=[_ST.RegisterSmoothScroll, _ST.RegisterSideScroll]) )
_D('V450 Nano Cordless Laser Mouse', codename='V450 Nano', protocol=1.0, wpid='1011', registers=(_R.battery_charge, )) _D(
_D('V550 Nano Cordless Laser Mouse', codename='V550 Nano', protocol=1.0, wpid='1013', "MX Air",
registers=(_R.battery_charge, ), settings=[_ST.RegisterSmoothScroll, _ST.RegisterSideScroll, ]) codename="MX Air",
_D('MX 1100 Cordless Laser Mouse', codename='MX 1100', protocol=1.0, kind=_DK.mouse, wpid='1014', protocol=1.0,
registers=(_R.battery_charge, ), settings=[_ST.RegisterSmoothScroll, _ST.RegisterSideScroll]) kind=DEVICE_KIND.mouse,
_D('Anywhere Mouse MX', codename='Anywhere MX', protocol=1.0, wpid='1017', wpid=("1007", "100E"),
registers=(_R.battery_charge, ), settings=[_ST.RegisterSmoothScroll, _ST.RegisterSideScroll]) registers=Reg.BATTERY_CHARGE,
)
_D(
"MX Revolution",
codename="MX Revolution",
protocol=1.0,
kind=DEVICE_KIND.mouse,
wpid=("1008", "100C"),
registers=(Reg.BATTERY_CHARGE,),
)
_D(
"MX620 Laser Cordless Mouse",
codename="MX620",
protocol=1.0,
wpid=("100A", "1016"),
registers=(Reg.BATTERY_CHARGE,),
)
_D(
"VX Nano Cordless Laser Mouse",
codename="VX Nano",
protocol=1.0,
wpid=("100B", "100F"),
registers=(Reg.BATTERY_CHARGE,),
)
_D(
"V450 Nano Cordless Laser Mouse",
codename="V450 Nano",
protocol=1.0,
wpid="1011",
registers=(Reg.BATTERY_CHARGE,),
)
_D(
"V550 Nano Cordless Laser Mouse",
codename="V550 Nano",
protocol=1.0,
wpid="1013",
registers=(Reg.BATTERY_CHARGE,),
)
_D(
"MX 1100 Cordless Laser Mouse",
codename="MX 1100",
protocol=1.0,
kind=DEVICE_KIND.mouse,
wpid="1014",
registers=(Reg.BATTERY_CHARGE,),
)
_D("Anywhere Mouse MX", codename="Anywhere MX", protocol=1.0, wpid="1017", registers=(Reg.BATTERY_CHARGE,))
_D(
"Performance Mouse MX",
codename="Performance MX",
protocol=1.0,
wpid="101A",
registers=(Reg.BATTERY_STATUS, Reg.THREE_LEDS),
)
_D(
"Marathon Mouse M705 (M-R0009)",
codename="M705 (M-R0009)",
protocol=1.0,
wpid="101B",
registers=(Reg.BATTERY_CHARGE,),
)
_D(
"Wireless Mouse M350",
codename="M350",
protocol=1.0,
wpid="101C",
registers=(Reg.BATTERY_CHARGE,),
)
_D(
"Wireless Mouse M505",
codename="M505/B605",
protocol=1.0,
wpid="101D",
registers=(Reg.BATTERY_CHARGE,),
)
_D(
"Wireless Mouse M305",
codename="M305",
protocol=1.0,
wpid="101F",
registers=(Reg.BATTERY_STATUS,),
)
_D(
"Wireless Mouse M215",
codename="M215",
protocol=1.0,
wpid="1020",
)
_D(
"G700 Gaming Mouse",
codename="G700",
protocol=1.0,
wpid="1023",
usbid=0xC06B,
interface=1,
registers=(
Reg.BATTERY_STATUS,
Reg.THREE_LEDS,
),
)
_D("Wireless Mouse M310", codename="M310", protocol=1.0, wpid="1024", registers=(Reg.BATTERY_STATUS,))
_D("Wireless Mouse M510", codename="M510", protocol=1.0, wpid="1025", registers=(Reg.BATTERY_STATUS,))
_D("Fujitsu Sonic Mouse", codename="Sonic", protocol=1.0, wpid="1029")
_D(
"G700s Gaming Mouse",
codename="G700s",
protocol=1.0,
wpid="102A",
usbid=0xC07C,
interface=1,
registers=(
Reg.BATTERY_STATUS,
Reg.THREE_LEDS,
),
)
_D("Couch Mouse M515", codename="M515", protocol=2.0, wpid="4007")
_D("Wireless Mouse M175", codename="M175", protocol=2.0, wpid="4008")
_D("Wireless Mouse M325", codename="M325", protocol=2.0, wpid="400A")
_D("Wireless Mouse M525", codename="M525", protocol=2.0, wpid="4013")
_D("Wireless Mouse M345", codename="M345", protocol=2.0, wpid="4017")
_D("Wireless Mouse M187", codename="M187", protocol=2.0, wpid="4019")
_D("Touch Mouse M600", codename="M600", protocol=2.0, wpid="401A")
_D("Wireless Mouse M150", codename="M150", protocol=2.0, wpid="4022")
_D("Wireless Mouse M185", codename="M185", protocol=2.0, wpid="4038")
_D("Wireless Mouse MX Master", codename="MX Master", protocol=4.5, wpid="4041", btid=0xB012)
_D("Anywhere Mouse MX 2", codename="Anywhere MX 2", protocol=4.5, wpid="404A")
_D("Wireless Mouse M510", codename="M510v2", protocol=2.0, wpid="4051")
_D("Wireless Mouse M185 new", codename="M185n", protocol=4.5, wpid="4054")
_D("Wireless Mouse M185/M235/M310", codename="M185/M235/M310", protocol=4.5, wpid="4055")
_D("Wireless Mouse MX Master 2S", codename="MX Master 2S", protocol=4.5, wpid="4069", btid=0xB019)
_D("Multi Device Silent Mouse M585/M590", codename="M585/M590", protocol=4.5, wpid="406B")
_D(
"Marathon Mouse M705 (M-R0073)",
codename="M705 (M-R0073)",
protocol=4.5,
wpid="406D",
)
_D("MX Vertical Wireless Mouse", codename="MX Vertical", protocol=4.5, wpid="407B", btid=0xB020, usbid=0xC08A)
_D("Wireless Mouse Pebble M350", codename="Pebble", protocol=2.0, wpid="4080")
_D("MX Master 3 Wireless Mouse", codename="MX Master 3", protocol=4.5, wpid="4082", btid=0xB023)
_D("PRO X Wireless", kind="mouse", codename="PRO X", wpid="4093", usbid=0xC094)
_D("G9 Laser Mouse", codename="G9", usbid=0xC048, interface=1, protocol=1.0)
class _PerformanceMXDpi(_ST.RegisterDpi): _D("G9x Laser Mouse", codename="G9x", usbid=0xC066, interface=1, protocol=1.0)
choices_universe = _NamedInts.range(0x81, 0x8F, lambda x: str((x - 0x80) * 100)) _D("G502 Gaming Mouse", codename="G502", usbid=0xC07D, interface=1)
validator_options = {'choices': choices_universe} _D("G402 Gaming Mouse", codename="G402", usbid=0xC07E, interface=1)
_D("G900 Chaos Spectrum Gaming Mouse", codename="G900", usbid=0xC081)
_D("G403 Gaming Mouse", codename="G403", usbid=0xC082)
_D('Performance Mouse MX', codename='Performance MX', protocol=1.0, wpid='101A', _D("G903 Lightspeed Gaming Mouse", codename="G903", usbid=0xC086)
registers=(_R.battery_status, _R.three_leds), _D("G703 Lightspeed Gaming Mouse", codename="G703", usbid=0xC087)
settings=[_PerformanceMXDpi, _ST.RegisterSmoothScroll, _ST.RegisterSideScroll]) _D("GPro Gaming Mouse", codename="GPro", usbid=0xC088)
_D('Marathon Mouse M705 (M-R0009)', codename='M705 (M-R0009)', protocol=1.0, wpid='101B', _D("G502 SE Hero Gaming Mouse", codename="G502 Hero", usbid=0xC08B, interface=1)
registers=(_R.battery_charge, ), settings=[_ST.RegisterSmoothScroll, _ST.RegisterSideScroll]) _D("G502 Lightspeed Gaming Mouse", codename="G502 Lightspeed", usbid=0xC08D)
_D('Wireless Mouse M350', codename='M350', protocol=1.0, wpid='101C', registers=(_R.battery_charge, )) _D("MX518 Gaming Mouse", codename="MX518", usbid=0xC08E, interface=1)
_D('Wireless Mouse M505', codename='M505/B605', protocol=1.0, wpid='101D', _D("G703 Hero Gaming Mouse", codename="G703 Hero", usbid=0xC090)
registers=(_R.battery_charge, ), settings=[_ST.RegisterSmoothScroll, _ST.RegisterSideScroll]) _D("G903 Hero Gaming Mouse", codename="G903 Hero", usbid=0xC091)
_D('Wireless Mouse M305', codename='M305', protocol=1.0, wpid='101F', _D(None, kind=DEVICE_KIND.mouse, usbid=0xC092, interface=1) # two mice share this ID
registers=(_R.battery_status, ), settings=[_ST.RegisterSideScroll]) _D("M500S Mouse", codename="M500S", usbid=0xC093, interface=1)
_D('Wireless Mouse M215', codename='M215', protocol=1.0, wpid='1020')
_D('G700 Gaming Mouse', codename='G700', protocol=1.0, wpid='1023', usbid=0xc06b, interface=1,
registers=(_R.battery_status, _R.three_leds,), settings=[_ST.RegisterSmoothScroll, _ST.RegisterSideScroll])
_D('Wireless Mouse M310', codename='M310', protocol=1.0, wpid='1024', registers=(_R.battery_status, ))
_D('Wireless Mouse M510', codename='M510', protocol=1.0, wpid='1025',
registers=(_R.battery_status, ), settings=[_ST.RegisterSideScroll])
_D('Fujitsu Sonic Mouse', codename='Sonic', protocol=1.0, wpid='1029')
_D('G700s Gaming Mouse', codename='G700s', protocol=1.0, wpid='102A', usbid=0xc07c, interface=1,
registers=(_R.battery_status, _R.three_leds,), settings=[_ST.RegisterSmoothScroll, _ST.RegisterSideScroll])
_D('Couch Mouse M515', codename='M515', protocol=2.0, wpid='4007')
_D('Wireless Mouse M175', codename='M175', protocol=2.0, wpid='4008')
_D('Wireless Mouse M325', codename='M325', protocol=2.0, wpid='400A')
_D('Wireless Mouse M525', codename='M525', protocol=2.0, wpid='4013')
_D('Wireless Mouse M345', codename='M345', protocol=2.0, wpid='4017')
_D('Wireless Mouse M187', codename='M187', protocol=2.0, wpid='4019')
_D('Touch Mouse M600', codename='M600', protocol=2.0, wpid='401A')
_D('Wireless Mouse M150', codename='M150', protocol=2.0, wpid='4022')
_D('Wireless Mouse M185', codename='M185', protocol=2.0, wpid='4038')
_D('Wireless Mouse MX Master', codename='MX Master', protocol=4.5, wpid='4041', btid=0xb012)
_D('Anywhere Mouse MX 2', codename='Anywhere MX 2', protocol=4.5, wpid='404A', settings=[_ST.HiresSmoothInvert])
_D('Wireless Mouse M510', codename='M510v2', protocol=2.0, wpid='4051')
_D('Wireless Mouse M185 new', codename='M185n', protocol=4.5, wpid='4054')
_D('Wireless Mouse M185/M235/M310', codename='M185/M235/M310', protocol=4.5, wpid='4055')
_D('Wireless Mouse MX Master 2S', codename='MX Master 2S', protocol=4.5, wpid='4069', btid=0xb019,
settings=[_ST.HiresSmoothInvert])
_D('Multi Device Silent Mouse M585/M590', codename='M585/M590', protocol=4.5, wpid='406B')
_D('Marathon Mouse M705 (M-R0073)', codename='M705 (M-R0073)', protocol=4.5, wpid='406D',
settings=[_ST.HiresSmoothInvert, _ST.PointerSpeed])
_D('MX Vertical Wireless Mouse', codename='MX Vertical', protocol=4.5, wpid='407B', btid=0xb020, usbid=0xc08a)
_D('Wireless Mouse Pebble M350', codename='Pebble', protocol=2.0, wpid='4080')
_D('MX Master 3 Wireless Mouse', codename='MX Master 3', protocol=4.5, wpid='4082', btid=0xb023)
_D('PRO X Wireless', kind='mouse', codename='PRO X', wpid='4093', usbid=0xc094)
_D('G9 Laser Mouse', codename='G9', usbid=0xc048, interface=1, protocol=1.0,
settings=[_PerformanceMXDpi, _ST.RegisterSmoothScroll, _ST.RegisterSideScroll])
_D('G9x Laser Mouse', codename='G9x', usbid=0xc066, interface=1, protocol=1.0,
settings=[_PerformanceMXDpi, _ST.RegisterSmoothScroll, _ST.RegisterSideScroll])
_D('G502 Gaming Mouse', codename='G502', usbid=0xc07d, interface=1)
_D('G402 Gaming Mouse', codename='G402', usbid=0xc07e, interface=1)
_D('G900 Chaos Spectrum Gaming Mouse', codename='G900', usbid=0xc081)
_D('G403 Gaming Mouse', codename='G403', usbid=0xc082)
_D('G903 Lightspeed Gaming Mouse', codename='G903', usbid=0xc086)
_D('G703 Lightspeed Gaming Mouse', codename='G703', usbid=0xc087)
_D('GPro Gaming Mouse', codename='GPro', usbid=0xc088)
_D('G502 SE Hero Gaming Mouse', codename='G502 Hero', usbid=0xc08b, interface=1)
_D('G502 Lightspeed Gaming Mouse', codename='G502 Lightspeed', usbid=0xc08d)
_D('MX518 Gaming Mouse', codename='MX518', usbid=0xc08e, interface=1)
_D('G703 Hero Gaming Mouse', codename='G703 Hero', usbid=0xc090)
_D('G903 Hero Gaming Mouse', codename='G903 Hero', usbid=0xc091)
_D(None, kind=_DK.mouse, usbid=0xc092, interface=1) # two mice share this ID
_D('M500S Mouse', codename='M500S', usbid=0xc093, interface=1)
# _D('G600 Gaming Mouse', codename='G600 Gaming', usbid=0xc24a, interface=1) # not an HID++ device # _D('G600 Gaming Mouse', codename='G600 Gaming', usbid=0xc24a, interface=1) # not an HID++ device
_D('G500s Gaming Mouse', codename='G500s Gaming', usbid=0xc24e, interface=1, protocol=1.0) _D("G500s Gaming Mouse", codename="G500s Gaming", usbid=0xC24E, interface=1, protocol=1.0)
_D('G502 Proteus Spectrum Optical Mouse', codename='G502 Proteus Spectrum', usbid=0xc332, interface=1) _D("G502 Proteus Spectrum Optical Mouse", codename="G502 Proteus Spectrum", usbid=0xC332, interface=1)
_D('Logitech PRO Gaming Keyboard', codename='PRO Gaming Keyboard', usbid=0xc339, interface=1) _D("Logitech PRO Gaming Keyboard", codename="PRO Gaming Keyboard", usbid=0xC339, interface=1)
_D('Logitech MX Revolution Mouse M-RCL 124', codename='M-RCL 124', btid=0xb007, interface=1) _D("Logitech MX Revolution Mouse M-RCL 124", codename="M-RCL 124", btid=0xB007, interface=1)
# Trackballs # Trackballs
_D('Wireless Trackball M570', codename='M570') _D("Wireless Trackball M570", codename="M570")
# Touchpads # Touchpads
_D('Wireless Touchpad', codename='Wireless Touch', protocol=2.0, wpid='4011') _D("Wireless Touchpad", codename="Wireless Touch", protocol=2.0, wpid="4011")
_D('Wireless Rechargeable Touchpad T650', codename='T650', protocol=2.0, wpid='4101') _D("Wireless Rechargeable Touchpad T650", codename="T650", protocol=2.0, wpid="4101")
_D('G Powerplay', codename='Powerplay', protocol=2.0, kind=_DK.touchpad, wpid='405F') # To override self-identification _D(
"G Powerplay", codename="Powerplay", protocol=2.0, kind=DEVICE_KIND.touchpad, wpid="405F"
) # To override self-identification
# Headset # Headset
_D('G533 Gaming Headset', codename='G533 Headset', protocol=2.0, interface=3, kind=_DK.headset, usbid=0x0a66) _D("G533 Gaming Headset", codename="G533 Headset", protocol=2.0, interface=3, kind=DEVICE_KIND.headset, usbid=0x0A66)
_D('G535 Gaming Headset', codename='G535 Headset', protocol=2.0, interface=3, kind=_DK.headset, usbid=0x0ac4) _D("G535 Gaming Headset", codename="G535 Headset", protocol=2.0, interface=3, kind=DEVICE_KIND.headset, usbid=0x0AC4)
_D('G935 Gaming Headset', codename='G935 Headset', protocol=2.0, interface=3, kind=_DK.headset, usbid=0x0a87) _D("G935 Gaming Headset", codename="G935 Headset", protocol=2.0, interface=3, kind=DEVICE_KIND.headset, usbid=0x0A87)
_D('G733 Gaming Headset', codename='G733 Headset', protocol=2.0, interface=3, kind=_DK.headset, usbid=0x0ab5) _D("G733 Gaming Headset", codename="G733 Headset", protocol=2.0, interface=3, kind=DEVICE_KIND.headset, usbid=0x0AB5)
_D('G733 Gaming Headset', codename='G733 Headset New', protocol=2.0, interface=3, kind=_DK.headset, usbid=0x0afe) _D(
_D('PRO X Wireless Gaming Headset', codename='PRO Headset', protocol=2.0, interface=3, kind=_DK.headset, usbid=0x0aba) "G733 Gaming Headset",
codename="G733 Headset New",
protocol=2.0,
interface=3,
kind=DEVICE_KIND.headset,
usbid=0x0AFE,
)
_D(
"PRO X Wireless Gaming Headset",
codename="PRO Headset",
protocol=2.0,
interface=3,
kind=DEVICE_KIND.headset,
usbid=0x0ABA,
)

View File

@ -0,0 +1,129 @@
## Copyright (C) 2024 Solaar contributors
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""Implements the desktop notification service."""
import importlib
import logging
logger = logging.getLogger(__name__)
def notifications_available():
"""Checks if notification service is available."""
notifications_supported = False
try:
import gi
gi.require_version("Notify", "0.7")
gi.require_version("Gtk", "3.0")
importlib.util.find_spec("gi.repository.GLib")
importlib.util.find_spec("gi.repository.Gtk")
importlib.util.find_spec("gi.repository.Notify")
notifications_supported = True
except ValueError as e:
logger.warning(f"Notification service is not available: {e}")
return notifications_supported
available = notifications_available()
if available:
from gi.repository import GLib
from gi.repository import Gtk
from gi.repository import Notify
# cache references to shown notifications here to allow reuse
_notifications = {}
_ICON_LISTS = {}
def init():
"""Initialize desktop notifications."""
global available
if available:
if not Notify.is_initted():
if logger.isEnabledFor(logging.INFO):
logger.info("starting desktop notifications")
try:
return Notify.init("solaar") # replace with better name later
except Exception:
logger.exception("initializing desktop notifications")
available = False
return available and Notify.is_initted()
def uninit():
"""Stop desktop notifications."""
if available and Notify.is_initted():
if logger.isEnabledFor(logging.INFO):
logger.info("stopping desktop notifications")
_notifications.clear()
Notify.uninit()
def show(dev, message: str, icon=None):
"""Show a notification with title and text."""
if available and (Notify.is_initted() or init()):
summary = dev.name
n = _notifications.get(summary) # reuse notification of same name
if n is None:
n = _notifications[summary] = Notify.Notification()
icon_name = device_icon_name(dev.name, dev.kind) if icon is None else icon
n.update(summary, message, icon_name)
n.set_urgency(Notify.Urgency.NORMAL)
n.set_hint("desktop-entry", GLib.Variant("s", "solaar")) # replace with better name late
try:
return n.show()
except Exception:
logger.exception(f"showing {n}")
def device_icon_list(name="_", kind=None):
icon_list = _ICON_LISTS.get(name)
if icon_list is None:
# names of possible icons, in reverse order of likelihood
# the theme will hopefully pick up the most appropriate
icon_list = ["preferences-desktop-peripherals"]
kind = str(kind)
if kind:
if kind == "numpad":
icon_list += ("input-keyboard", "input-dialpad")
elif kind == "touchpad":
icon_list += ("input-mouse", "input-tablet")
elif kind == "trackball":
icon_list += ("input-mouse",)
elif kind == "headset":
icon_list += ("audio-headphones", "audio-headset")
icon_list += (f"input-{kind}",)
_ICON_LISTS[name] = icon_list
return icon_list
def device_icon_name(name, kind=None):
_default_theme = Gtk.IconTheme.get_default()
icon_list = device_icon_list(name, kind)
for n in reversed(icon_list):
if _default_theme.has_icon(n):
return n
else:
def init():
return False
def uninit():
return None
def show(dev, reason=None):
return None

View File

@ -1,6 +1,5 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by ## it under the terms of the GNU General Public License as published by
@ -16,168 +15,203 @@
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import errno as _errno from __future__ import annotations
import errno
import logging import logging
import threading as _threading import threading
import time
import typing
from typing import Callable
from typing import Optional from typing import Optional
from typing import Protocol
import hidapi as _hid from solaar import configuration
import solaar.configuration as _configuration
from . import base as _base from . import descriptors
from . import descriptors as _descriptors from . import exceptions
from . import hidpp10 as _hidpp10 from . import hidpp10
from . import hidpp20 as _hidpp20 from . import hidpp10_constants
from .common import strhex as _strhex from . import hidpp20
from .settings_templates import check_feature_settings as _check_feature_settings from . import settings
from . import settings_templates
from .common import Alert
from .common import Battery
from .hidpp10_constants import NotificationFlag
from .hidpp20_constants import SupportedFeature
if typing.TYPE_CHECKING:
from logitech_receiver import common
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
_R = _hidpp10.REGISTERS _hidpp10 = hidpp10.Hidpp10()
_IR = _hidpp10.INFO_SUBREGISTERS _hidpp20 = hidpp20.Hidpp20()
KIND_MAP = {kind: _hidpp10.DEVICE_KIND[str(kind)] for kind in _hidpp20.DEVICE_KIND}
# class LowLevelInterface(Protocol):
# def open_path(self, path) -> int:
# ...
def find_paired_node(self, receiver_path: str, index: int, timeout: int):
...
def ping(self, handle, number, long_message: bool):
...
def request(self, handle, devnumber, request_id, *params, **kwargs):
...
def close(self, handle, *args, **kwargs) -> bool:
...
def create_device(low_level: LowLevelInterface, device_info, setting_callback=None):
"""Opens a Logitech Device found attached to the machine, by Linux device path.
:returns: An open file handle for the found receiver, or None.
"""
try:
handle = low_level.open_path(device_info.path)
if handle:
# a direct connected device might not be online (as reported by user)
return Device(
low_level,
None,
None,
None,
handle=handle,
device_info=device_info,
setting_callback=setting_callback,
)
except OSError as e:
logger.exception("open %s", device_info)
if e.errno == errno.EACCES:
raise e
except Exception as e:
logger.exception("open %s", device_info)
raise e
class Device: class Device:
instances = [] instances = []
read_register = _hidpp10.read_register read_register: Callable = hidpp10.read_register
write_register = _hidpp10.write_register write_register: Callable = hidpp10.write_register
def __init__( def __init__(
self, self,
low_level: LowLevelInterface,
receiver, receiver,
number, number,
link_notification=None, online,
path=None, pairing_info=None,
handle=None, handle=None,
short=None, device_info=None,
long=None, setting_callback=None,
product_id=None,
bus_id=None
): ):
assert receiver or handle assert receiver or device_info
Device.instances.append(self) if receiver:
assert 0 < number <= 15 # some receivers have devices past their max # of devices
self.low_level = low_level
self.number = number # will be None at this point for directly connected devices
self.online = online # is the device online? - gates many atempts to contact the device
self.descriptor = None
self.isDevice = True # some devices act as receiver so we need a property to distinguish them self.isDevice = True # some devices act as receiver so we need a property to distinguish them
self.may_unpair = False self.may_unpair = False
self.receiver = receiver self.receiver = receiver
self.path = path
self.handle = handle self.handle = handle
self.product_id = product_id self.path = device_info.path if device_info else None
self.hidpp_short = short self.product_id = device_info.product_id if device_info else None
self.hidpp_long = long self.hidpp_short = device_info.hidpp_short if device_info else None
self.bluetooth = bus_id == 0x0005 # Bluetooth connections need long messages self.hidpp_long = device_info.hidpp_long if device_info else None
self.bluetooth = device_info.bus_id == 0x0005 if device_info else False # Bluetooth needs long messages
if receiver: self.hid_serial = device_info.serial if device_info else None
assert number > 0 and number <= 15 # some receivers have devices past their max # of devices self.setting_callback = setting_callback # for changes to settings
self.number = number # will be None at this point for directly connected devices self.status_callback = None # for changes to other potentially visible aspects
self.online = self.descriptor = None self.wpid = pairing_info["wpid"] if pairing_info else None # the Wireless PID is unique per device model
self._kind = pairing_info["kind"] if pairing_info else None # mouse, keyboard, etc (see hidpp10.DEVICE_KIND)
self.wpid = None # the Wireless PID is unique per device model self._serial = pairing_info["serial"] if pairing_info else None # serial number (an 8-char hex string)
self._kind = None # mouse, keyboard, etc (see _hidpp10.DEVICE_KIND) self._polling_rate = pairing_info["polling"] if pairing_info else None
self._codename = None # Unifying peripherals report a codename. self._power_switch = pairing_info["power_switch"] if pairing_info else None
self._name = None # the full name of the model self._name = None # the full name of the model
self._codename = None # Unifying peripherals report a codename.
self._protocol = None # HID++ protocol version, 1.0 or 2.0 self._protocol = None # HID++ protocol version, 1.0 or 2.0
self._serial = None # serial number (an 8-char hex string) self._unitId = None # unit id (distinguishes within a model - generally the same as serial)
self._unitId = None # unit id (distinguishes within a model - the same as serial)
self._modelId = None # model id (contains identifiers for the transports of the device) self._modelId = None # model id (contains identifiers for the transports of the device)
self._tid_map = None # map from transports to product identifiers self._tid_map = None # map from transports to product identifiers
self._persister = None # persister holds settings self._persister = None # persister holds settings
self._led_effects = self._firmware = self._keys = self._remap_keys = self._gestures = None
self._profiles = self._backlight = self._settings = None
self.registers = []
self.notification_flags = None
self.battery_info = None
self.link_encrypted = None
self._active = None # lags self.online - is used to help determine when to setup devices
self.present = True # used for devices that are integral with their receiver but that separately be disconnected
self._firmware = self._keys = self._remap_keys = self._gestures = None
self._polling_rate = self._power_switch = self._led_effects = None
self._gestures_lock = _threading.Lock()
self._profiles = self._backlight = self._registers = self._settings = None
self._feature_settings_checked = False self._feature_settings_checked = False
self._settings_lock = _threading.Lock() self._gestures_lock = threading.Lock()
self._settings_lock = threading.Lock()
# See `add_notification_handler` self._persister_lock = threading.Lock()
self._notification_handlers = {} self._notification_handlers = {} # See `add_notification_handler`
self.cleanups = [] # functions to run on the device when it is closed
if not self.path: if not self.path:
self.path = _hid.find_paired_node(receiver.path, number, 1) if receiver else None self.path = self.low_level.find_paired_node(receiver.path, number, 1) if receiver else None
if not self.handle: if not self.handle:
try: try:
self.handle = _base.open_path(self.path) if self.path else None self.handle = self.low_level.open_path(self.path) if self.path else None
except Exception: # maybe the device wasn't set up except Exception: # maybe the device wasn't set up
try: try:
import time
time.sleep(1) time.sleep(1)
self.handle = _base.open_path(self.path) if self.path else None self.handle = self.low_level.open_path(self.path) if self.path else None
except Exception: # give up except Exception: # give up
self.handle = None self.handle = None # should this give up completely?
if receiver: if receiver:
if link_notification is not None:
self.online = not bool(ord(link_notification.data[0:1]) & 0x40)
self.wpid = _strhex(link_notification.data[2:3] + link_notification.data[1:2])
# assert link_notification.address == (0x04 if unifying else 0x03)
kind = ord(link_notification.data[0:1]) & 0x0F
# get 27Mhz wpid and set kind based on index
if receiver.receiver_kind == '27Mhz': # 27 Mhz receiver
self.wpid = '00' + _strhex(link_notification.data[2:3])
kind = receiver.get_kind_from_index(number)
self._kind = _hidpp10.DEVICE_KIND[kind]
elif receiver.receiver_kind == '27Mhz': # 27 Mhz receiver doesn't have pairing registers
self.wpid = _hid.find_paired_node_wpid(receiver.path, number)
if not self.wpid: if not self.wpid:
logger.error('Unable to get wpid from udev for device %d of %s', number, receiver) raise exceptions.NoSuchDevice(
raise _base.NoSuchDevice(number=number, receiver=receiver, error='Not present 27Mhz device') number=number, receiver=receiver, error="no wpid for device connected to receiver"
kind = receiver.get_kind_from_index(number) )
self._kind = _hidpp10.DEVICE_KIND[kind] self.descriptor = descriptors.get_wpid(self.wpid)
else: # get information from pairing registers
self.online = True
self.update_pairing_information()
self.update_extended_pairing_information()
if not self.wpid and not self._serial: # if neither then the device almost certainly wasn't found
raise _base.NoSuchDevice(number=number, receiver=receiver, error='no wpid or serial')
# the wpid is set to None on this object when the device is unpaired
assert self.wpid is not None, 'failed to read wpid: device %d of %s' % (number, receiver)
self.descriptor = _descriptors.get_wpid(self.wpid)
if self.descriptor is None: if self.descriptor is None:
# Last chance to correctly identify the device; many Nano receivers do not support this call. codename = self.receiver.device_codename(self.number) # Last chance to get a descriptor, may fail
codename = self.receiver.device_codename(self.number)
if codename: if codename:
self._codename = codename self._codename = codename
self.descriptor = _descriptors.get_codename(self._codename) self.descriptor = descriptors.get_codename(self._codename)
else: else:
self.online = None # a direct connected device might not be online (as reported by user) self.descriptor = (
self.descriptor = _descriptors.get_btid(self.product_id) if self.bluetooth else \ descriptors.get_btid(self.product_id) if self.bluetooth else descriptors.get_usbid(self.product_id)
_descriptors.get_usbid(self.product_id) )
if self.number is None: # for direct-connected devices get 'number' from descriptor protocol else use 0xFF if self.number is None: # for direct-connected devices get 'number' from descriptor protocol else use 0xFF
self.number = 0x00 if self.descriptor and self.descriptor.protocol and self.descriptor.protocol < 2.0 else 0xFF if self.descriptor and self.descriptor.protocol and self.descriptor.protocol < 2.0:
number = 0x00
else:
number = 0xFF
self.number = number
self.ping() # determine whether a direct-connected device is online
if self.descriptor: if self.descriptor:
self._name = self.descriptor.name self._name = self.descriptor.name
if self.descriptor.protocol:
self._protocol = self.descriptor.protocol
if self._codename is None: if self._codename is None:
self._codename = self.descriptor.codename self._codename = self.descriptor.codename
if self._kind is None: if self._kind is None:
self._kind = self.descriptor.kind self._kind = self.descriptor.kind
self._protocol = self.descriptor.protocol if self.descriptor.protocol else None
self.registers = self.descriptor.registers if self.descriptor.registers else []
if self._protocol is not None: if self._protocol is not None:
self.features = None if self._protocol < 2.0 else _hidpp20.FeaturesArray(self) self.features = None if self._protocol < 2.0 else hidpp20.FeaturesArray(self)
else: else:
# may be a 2.0 device; if not, it will fix itself later self.features = hidpp20.FeaturesArray(self) # may be a 2.0 device; if not, it will fix itself later
self.features = _hidpp20.FeaturesArray(self)
@classmethod Device.instances.append(self)
def find(self, serial):
assert serial, 'need serial number or unit ID to find a device' def find(self, id): # find a device by serial number or unit ID or name or codename
result = None assert id, "need id to find a device"
for device in Device.instances: for device in Device.instances:
if device.online and (device.unitId == serial or device.serial == serial): if device.online and (device.unitId == id or device.serial == id or device.name == id or device.codename == id):
result = device return device
return result
@property @property
def protocol(self): def protocol(self):
@ -188,38 +222,31 @@ class Device:
@property @property
def codename(self): def codename(self):
if not self._codename: if not self._codename:
if not self.online: # be very defensive
self.ping()
if self.online and self.protocol >= 2.0: if self.online and self.protocol >= 2.0:
self._codename = _hidpp20.get_friendly_name(self) self._codename = _hidpp20.get_friendly_name(self)
if not self._codename: if not self._codename:
self._codename = self.name.split(' ', 1)[0] if self.name else None self._codename = self.name.split(" ", 1)[0] if self.name else None
if not self._codename and self.receiver: if not self._codename and self.receiver:
codename = self.receiver.device_codename(self.number) codename = self.receiver.device_codename(self.number)
if codename: if codename:
self._codename = codename self._codename = codename
elif self.protocol < 2.0: elif self.protocol < 2.0:
self._codename = '? (%s)' % (self.wpid or self.product_id) self._codename = "? (%s)" % (self.wpid or self.product_id)
return self._codename or '?? (%s)' % (self.wpid or self.product_id) return self._codename or f"?? ({self.wpid or self.product_id})"
@property @property
def name(self): def name(self):
if not self._name: if not self._name:
if not self.online: # be very defensive
try:
self.ping()
except _base.NoSuchDevice:
pass
if self.online and self.protocol >= 2.0: if self.online and self.protocol >= 2.0:
self._name = _hidpp20.get_name(self) self._name = _hidpp20.get_name(self)
return self._name or self._codename or ('Unknown device %s' % (self.wpid or self.product_id)) return self._name or self._codename or f"Unknown device {self.wpid or self.product_id}"
def get_ids(self): def get_ids(self):
ids = _hidpp20.get_ids(self) ids = _hidpp20.get_ids(self)
if ids: if ids:
self._unitId, self._modelId, self._tid_map = ids self._unitId, self._modelId, self._tid_map = ids
if logger.isEnabledFor(logging.INFO) and self._serial and self._serial != self._unitId: if logger.isEnabledFor(logging.INFO) and self._serial and self._serial != self._unitId:
logger.info('%s: unitId %s does not match serial %s', self, self._unitId, self._serial) logger.info("%s: unitId %s does not match serial %s", self, self._unitId, self._serial)
@property @property
def unitId(self): def unitId(self):
@ -239,35 +266,14 @@ class Device:
self.get_ids() self.get_ids()
return self._tid_map return self._tid_map
def update_pairing_information(self):
if self.receiver and (not self.wpid or self._kind is None or self._polling_rate is None):
wpid, kind, polling_rate = self.receiver.device_pairing_information(self.number)
if not self.wpid:
self.wpid = wpid
if not self._kind:
self._kind = kind
if not self._polling_rate:
self._polling_rate = str(polling_rate) + 'ms'
def update_extended_pairing_information(self):
if self.receiver:
serial, power_switch = self.receiver.device_extended_pairing_information(self.number)
if not self._serial:
self._serial = serial
if not self._power_switch:
self._power_switch = power_switch
@property @property
def kind(self): def kind(self):
if not self._kind: if not self._kind and self.online and self.protocol >= 2.0:
self.update_pairing_information() self._kind = _hidpp20.get_kind(self)
if not self._kind and self.protocol >= 2.0: return self._kind or "?"
kind = _hidpp20.get_kind(self)
self._kind = KIND_MAP[kind] if kind else None
return self._kind or '?'
@property @property
def firmware(self): def firmware(self) -> tuple[common.FirmwareInfo]:
if self._firmware is None and self.online: if self._firmware is None and self.online:
if self.protocol >= 2.0: if self.protocol >= 2.0:
self._firmware = _hidpp20.get_firmware(self) self._firmware = _hidpp20.get_firmware(self)
@ -277,28 +283,19 @@ class Device:
@property @property
def serial(self): def serial(self):
if not self._serial: return self._serial or ""
self.update_extended_pairing_information()
return self._serial or ''
@property @property
def id(self): def id(self):
if not self.serial:
if self.persister and self.persister.get('_serial', None):
self._serial = self.persister.get('_serial', None)
return self.unitId or self.serial return self.unitId or self.serial
@property @property
def power_switch_location(self): def power_switch_location(self):
if not self._power_switch:
self.update_extended_pairing_information()
return self._power_switch return self._power_switch
@property @property
def polling_rate(self): def polling_rate(self):
if not self._polling_rate: if self.online and self.protocol >= 2.0:
self.update_pairing_information()
if self.protocol >= 2.0:
rate = _hidpp20.get_polling_rate(self) rate = _hidpp20.get_polling_rate(self)
self._polling_rate = rate if rate else self._polling_rate self._polling_rate = rate if rate else self._polling_rate
return self._polling_rate return self._polling_rate
@ -306,7 +303,10 @@ class Device:
@property @property
def led_effects(self): def led_effects(self):
if not self._led_effects and self.online and self.protocol >= 2.0: if not self._led_effects and self.online and self.protocol >= 2.0:
self._led_effects = _hidpp20.LEDEffectsInfo(self) if SupportedFeature.COLOR_LED_EFFECTS in self.features:
self._led_effects = hidpp20.LEDEffectsInfo(self)
elif SupportedFeature.RGB_EFFECTS in self.features:
self._led_effects = hidpp20.RGBEffectsInfo(self)
return self._led_effects return self._led_effects
@property @property
@ -346,14 +346,20 @@ class Device:
self._profiles = _hidpp20.get_profiles(self) self._profiles = _hidpp20.get_profiles(self)
return self._profiles return self._profiles
def set_configuration(self, configuration_, no_reply=False):
if self.online and self.protocol >= 2.0:
_hidpp20.config_change(self, configuration_, no_reply=no_reply)
def reset(self, no_reply=False):
self.set_configuration(0, no_reply)
@property @property
def registers(self): def persister(self):
if not self._registers: if not self._persister:
if self.descriptor and self.descriptor.registers: with self._persister_lock:
self._registers = list(self.descriptor.registers) if not self._persister:
else: self._persister = configuration.persister(self)
self._registers = [] return self._persister
return self._registers
@property @property
def settings(self): def settings(self):
@ -375,37 +381,87 @@ class Device:
if not self._feature_settings_checked: if not self._feature_settings_checked:
with self._settings_lock: with self._settings_lock:
if not self._feature_settings_checked: if not self._feature_settings_checked:
self._feature_settings_checked = _check_feature_settings(self, self._settings) self._feature_settings_checked = settings_templates.check_feature_settings(self, self._settings)
return self._settings return self._settings
def set_configuration(self, configuration, no_reply=False):
if self.online and self.protocol >= 2.0:
_hidpp20.config_change(self, configuration, no_reply=no_reply)
def reset(self, no_reply=False):
self.set_configuration(0, no_reply)
@property
def persister(self):
if not self._persister:
self._persister = _configuration.persister(self)
return self._persister
def battery(self): # None or level, next, status, voltage def battery(self): # None or level, next, status, voltage
if self.protocol < 2.0: if self.protocol < 2.0:
return _hidpp10.get_battery(self) return _hidpp10.get_battery(self)
else: else:
battery_feature = self.persister.get('_battery', None) if self.persister else None battery_feature = self.persister.get("_battery", None) if self.persister else None
if battery_feature != 0: if battery_feature != 0:
result = _hidpp20.get_battery(self, battery_feature) result = _hidpp20.get_battery(self, battery_feature)
try: try:
feature, level, next, status, voltage = result feature, battery = result
if self.persister and battery_feature is None: if self.persister and battery_feature is None:
self.persister['_battery'] = feature self.persister["_battery"] = feature.value
return level, next, status, voltage return battery
except Exception: except Exception:
if self.persister and battery_feature is None: if self.persister and battery_feature is None and result is not None:
self.persister['_battery'] = result self.persister["_battery"] = result.value
def set_battery_info(self, info):
"""Update battery information for device, calling changed callback if necessary"""
if logger.isEnabledFor(logging.DEBUG):
logger.debug("%s: battery %s, %s", self, info.level, info.status)
if info.level is None and self.battery_info: # use previous level if missing from new information
info.level = self.battery_info.level
changed = self.battery_info != info
self.battery_info, old_info = info, self.battery_info
if old_info is None:
old_info = Battery(None, None, None, None)
alert, reason = Alert.NONE, None
if not info.ok():
logger.warning("%s: battery %d%%, ALERT %s", self, info.level, info.status)
if old_info.status != info.status:
alert = Alert.NOTIFICATION | Alert.ATTENTION
reason = info.to_str()
if changed or reason:
# update the leds on the device, if any
_hidpp10.set_3leds(self, info.level, charging=info.charging(), warning=bool(alert))
self.changed(active=True, alert=alert, reason=reason)
# Retrieve and regularize battery status
def read_battery(self):
if self.online:
battery = self.battery()
self.set_battery_info(battery if battery is not None else Battery(None, None, None, None))
def changed(self, active=None, alert=Alert.NONE, reason=None, push=False):
"""The status of the device had changed, so invoke the status callback.
Also push notifications and settings to the device when necessary."""
if logger.isEnabledFor(logging.DEBUG):
logger.debug("device %d changing: active=%s %s present=%s", self.number, active, self._active, self.present)
if active is not None:
self.online = active
was_active, self._active = self._active, active
if active:
# Push settings for new devices when devices request software reconfiguration
# and when devices become active if they don't have wireless device status feature,
if (
was_active is None
or not was_active
or push
and (not self.features or SupportedFeature.WIRELESS_DEVICE_STATUS not in self.features)
):
if logger.isEnabledFor(logging.INFO):
logger.info("%s pushing device settings %s", self, self.settings)
settings.apply_all_settings(self)
if not was_active:
if self.protocol < 2.0: # Make sure to set notification flags on the device
self.notification_flags = self.enable_connection_notifications()
else:
self.set_configuration(0x11) # signal end of configuration
self.read_battery() # battery information may have changed so try to read it now
elif was_active and self.receiver: # need to set configuration pending flag in receiver
hidpp10.set_configuration_pending_flags(self.receiver, 0xFF)
if logger.isEnabledFor(logging.DEBUG):
logger.debug("device %d changed: active=%s %s", self.number, self._active, self.battery_info)
if self.status_callback is not None:
self.status_callback(self, alert, reason)
def enable_connection_notifications(self, enable=True): def enable_connection_notifications(self, enable=True):
"""Enable or disable device (dis)connection notifications on this """Enable or disable device (dis)connection notifications on this
@ -414,22 +470,21 @@ class Device:
return False return False
if enable: if enable:
set_flag_bits = ( set_flag_bits = NotificationFlag.BATTERY_STATUS | NotificationFlag.UI | NotificationFlag.CONFIGURATION_COMPLETE
_hidpp10.NOTIFICATION_FLAG.battery_status
| _hidpp10.NOTIFICATION_FLAG.keyboard_illumination
| _hidpp10.NOTIFICATION_FLAG.wireless
| _hidpp10.NOTIFICATION_FLAG.software_present
)
else: else:
set_flag_bits = 0 set_flag_bits = 0
ok = _hidpp10.set_notification_flags(self, set_flag_bits) ok = _hidpp10.set_notification_flags(self, set_flag_bits)
if not ok: if not ok:
logger.warning('%s: failed to %s device notifications', self, 'enable' if enable else 'disable') logger.warning("%s: failed to %s device notifications", self, "enable" if enable else "disable")
flag_bits = _hidpp10.get_notification_flags(self) flag_bits = _hidpp10.get_notification_flags(self)
flag_names = None if flag_bits is None else tuple(_hidpp10.NOTIFICATION_FLAG.flag_names(flag_bits))
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
logger.info('%s: device notifications %s %s', self, 'enabled' if enable else 'disabled', flag_names) if flag_bits is None:
flag_names = None
else:
flag_names = hidpp10_constants.NotificationFlag.flag_names(flag_bits)
is_enabled = "enabled" if enable else "disabled"
logger.info(f"{self}: device notifications {is_enabled} {flag_names}")
return flag_bits if ok else None return flag_bits if ok else None
def add_notification_handler(self, id: str, fn): def add_notification_handler(self, id: str, fn):
@ -450,7 +505,7 @@ class Device:
"""Unregisters the notification handler under name `id`.""" """Unregisters the notification handler under name `id`."""
if id not in self._notification_handlers and logger.isEnabledFor(logging.INFO): if id not in self._notification_handlers and logger.isEnabledFor(logging.INFO):
logger.info(f'Tried to remove nonexistent notification handler {id} from device {self}.') logger.info(f"Tried to remove nonexistent notification handler {id} from device {self}.")
else: else:
del self._notification_handlers[id] del self._notification_handlers[id]
@ -466,32 +521,50 @@ class Device:
long = self.hidpp_long is True or ( long = self.hidpp_long is True or (
self.hidpp_long is None and (self.bluetooth or self._protocol is not None and self._protocol >= 2.0) self.hidpp_long is None and (self.bluetooth or self._protocol is not None and self._protocol >= 2.0)
) )
return _base.request( return self.low_level.request(
self.handle or self.receiver.handle, self.handle or self.receiver.handle,
self.number, self.number,
request_id, request_id,
*params, *params,
no_reply=no_reply, no_reply=no_reply,
long_message=long, long_message=long,
protocol=self.protocol protocol=self.protocol,
) )
def feature_request(self, feature, function=0x00, *params, no_reply=False): def feature_request(self, feature, function=0x00, *params, no_reply=False):
if self.protocol >= 2.0: if self.protocol >= 2.0:
return _hidpp20.feature_request(self, feature, function, *params, no_reply=no_reply) return hidpp20.feature_request(self, feature, function, *params, no_reply=no_reply)
def ping(self): def ping(self):
"""Checks if the device is online, returns True of False""" """Checks if the device is online and present, returns True of False.
# long = self.bluetooth or self.hidpp_short is False or self._protocol is not None and self._protocol >= 2.0 Some devices are integral with their receiver but may not be present even if the receiver responds to ping."""
long = self.hidpp_long is True or ( long = self.hidpp_long is True or (
self.hidpp_long is None and (self.bluetooth or self._protocol is not None and self._protocol >= 2.0) self.hidpp_long is None and (self.bluetooth or self._protocol is not None and self._protocol >= 2.0)
) )
protocol = _base.ping(self.handle or self.receiver.handle, self.number, long_message=long) handle = self.handle or self.receiver.handle
self.online = protocol is not None try:
protocol = self.low_level.ping(handle, self.number, long_message=long)
except exceptions.NoReceiver: # if ping fails, device is offline
protocol = None
self.online = protocol is not None and self.present
if protocol: if protocol:
self._protocol = protocol self._protocol = protocol
if logger.isEnabledFor(logging.DEBUG):
logger.debug("pinged %s: online %s protocol %s present %s", self.number, self.online, protocol, self.present)
return self.online return self.online
def notify_devices(self): # no need to notify, as there are none
pass
def close(self):
handle, self.handle = self.handle, None
if self in Device.instances:
Device.instances.remove(self)
if hasattr(self, "cleanups"):
for cleanup in self.cleanups:
cleanup(self)
return handle and self.low_level.close(handle)
def __index__(self): def __index__(self):
return self.number return self.number
@ -511,48 +584,17 @@ class Device:
__nonzero__ = __bool__ __nonzero__ = __bool__
def status_string(self):
return self.battery_info.to_str() if self.battery_info is not None else ""
def __str__(self): def __str__(self):
try: try:
name = self.name or self.codename or '?' name = self._name or self._codename or "?"
except _base.NoSuchDevice: except exceptions.NoSuchDevice:
name = 'name not available' name = "name not available"
return '<Device(%d,%s,%s,%s)>' % (self.number, self.wpid or self.product_id, name, self.serial) return f"<Device({int(self.number)},{self.wpid or self.product_id},{name},{self.serial})>"
__repr__ = __str__ __repr__ = __str__
def notify_devices(self): # no need to notify, as there are none
pass
@classmethod
def open(self, device_info):
"""Opens a Logitech Device found attached to the machine, by Linux device path.
:returns: An open file handle for the found receiver, or ``None``.
"""
try:
handle = _base.open_path(device_info.path)
if handle:
return Device(
None,
None,
handle=handle,
path=device_info.path,
short=device_info.hidpp_short,
long=device_info.hidpp_long,
product_id=device_info.product_id,
bus_id=device_info.bus_id
)
except OSError as e:
logger.exception('open %s', device_info)
if e.errno == _errno.EACCES:
raise
except Exception:
logger.exception('open %s', device_info)
def close(self):
handle, self.handle = self.handle, None
if self in Device.instances:
Device.instances.remove(self)
return (handle and _base.close(handle))
def __del__(self): def __del__(self):
self.close() self.close()

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,53 @@
## Copyright (C) 2012-2013 Daniel Pavel
## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from .common import KwException
"""Exceptions that may be raised by this API."""
class NoReceiver(KwException):
"""Raised when trying to talk through a previously open handle, when the
receiver is no longer available. Should only happen if the receiver is
physically disconnected from the machine, or its kernel driver module is
unloaded."""
pass
class NoSuchDevice(KwException):
"""Raised when trying to reach a device number not paired to the receiver."""
pass
class DeviceUnreachable(KwException):
"""Raised when a request is made to an unreachable (turned off) device."""
pass
class FeatureNotSupported(KwException):
"""Raised when trying to request a feature not supported by the device."""
pass
class FeatureCallError(KwException):
"""Raised if the device replied to a feature call with an error."""
pass

View File

@ -1,5 +1,3 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
@ -15,189 +13,75 @@
## You should have received a copy of the GNU General Public License along ## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from __future__ import annotations
import logging import logging
from .common import BATTERY_APPROX as _BATTERY_APPROX from typing import Any
from .common import FirmwareInfo as _FirmwareInfo
from .common import NamedInts as _NamedInts from typing_extensions import Protocol
from .common import bytes2int as _bytes2int
from .common import int2bytes as _int2bytes from . import common
from .common import strhex as _strhex from .common import Battery
from .hidpp20 import BATTERY_STATUS, FIRMWARE_KIND from .common import BatteryLevelApproximation
from .common import BatteryStatus
from .common import FirmwareKind
from .hidpp10_constants import NotificationFlag
from .hidpp10_constants import Registers
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
#
# Constants - most of them as defined by the official Logitech HID++ 1.0
# documentation, some of them guessed.
#
DEVICE_KIND = _NamedInts( class Device(Protocol):
unknown=0x00, def request(self, request_id, *params):
keyboard=0x01, ...
mouse=0x02,
numpad=0x03,
presenter=0x04,
remote=0x07,
trackball=0x08,
touchpad=0x09,
headset=0x0D, # not from Logitech documentation
remote_control=0x0E, # for compatibility with HID++ 2.0
receiver=0x0F # for compatibility with HID++ 2.0
)
POWER_SWITCH_LOCATION = _NamedInts( @property
base=0x01, def kind(self) -> Any:
top_case=0x02, ...
edge_of_top_right_corner=0x03,
top_left_corner=0x05,
bottom_left_corner=0x06,
top_right_corner=0x07,
bottom_right_corner=0x08,
top_edge=0x09,
right_edge=0x0A,
left_edge=0x0B,
bottom_edge=0x0C
)
# Some flags are used both by devices and receivers. The Logitech documentation @property
# mentions that the first and last (third) byte are used for devices while the def online(self) -> bool:
# second is used for the receiver. In practise, the second byte is also used for ...
# some device-specific notifications (keyboard illumination level). Do not
# simply set all notification bits if the software does not support it. For
# example, enabling keyboard_sleep_raw makes the Sleep key a no-operation unless
# the software is updated to handle that event.
# Observations:
# - wireless and software present were seen on receivers, reserved_r1b4 as well
# - the rest work only on devices as far as we can tell right now
# In the future would be useful to have separate enums for receiver and device notification flags,
# but right now we don't know enough.
# additional flags taken from https://drive.google.com/file/d/0BxbRzx7vEV7eNDBheWY0UHM5dEU/view?usp=sharing
NOTIFICATION_FLAG = _NamedInts(
numpad_numerical_keys=0x800000,
f_lock_status=0x400000,
roller_H=0x200000,
battery_status=0x100000, # send battery charge notifications (0x07 or 0x0D)
mouse_extra_buttons=0x080000,
roller_V=0x040000,
keyboard_sleep_raw=0x020000, # system control keys such as Sleep
keyboard_multimedia_raw=0x010000, # consumer controls such as Mute and Calculator
# reserved_r1b4= 0x001000, # unknown, seen on a unifying receiver
reserved5=0x008000,
reserved4=0x004000,
reserved3=0x002000,
reserved2=0x001000,
software_present=0x000800, # .. no idea
reserved1=0x000400,
keyboard_illumination=0x000200, # illumination brightness level changes (by pressing keys)
wireless=0x000100, # notify when the device wireless goes on/off-line
mx_air_3d_gesture=0x000001,
)
ERROR = _NamedInts( @property
invalid_SubID__command=0x01, def protocol(self) -> Any:
invalid_address=0x02, ...
invalid_value=0x03,
connection_request_failed=0x04,
too_many_devices=0x05,
already_exists=0x06,
busy=0x07,
unknown_device=0x08,
resource_error=0x09,
request_unavailable=0x0A,
unsupported_parameter_value=0x0B,
wrong_pin_code=0x0C
)
PAIRING_ERRORS = _NamedInts(device_timeout=0x01, device_not_supported=0x02, too_many_devices=0x03, sequence_timeout=0x06) @property
BOLT_PAIRING_ERRORS = _NamedInts(device_timeout=0x01, failed=0x02) def registers(self) -> list:
"""Known registers. ...
Devices usually have a (small) sub-set of these. Some registers are only
applicable to certain device kinds (e.g. smooth_scroll only applies to mice."""
REGISTERS = _NamedInts(
# only apply to receivers
receiver_connection=0x02,
receiver_pairing=0xB2,
devices_activity=0x2B3,
receiver_info=0x2B5,
bolt_device_discovery=0xC0,
bolt_pairing=0x2C1,
bolt_uniqueId=0x02FB,
# only apply to devices
mouse_button_flags=0x01,
keyboard_hand_detection=0x01,
battery_status=0x07,
keyboard_fn_swap=0x09,
battery_charge=0x0D,
keyboard_illumination=0x17,
three_leds=0x51,
mouse_dpi=0x63,
# apply to both
notifications=0x00,
firmware=0xF1,
# notifications
passkey_request_notification=0x4D,
passkey_pressed_notification=0x4E,
device_discovery_notification=0x4F,
discovery_status_notification=0x53,
pairing_status_notification=0x54,
)
# Subregisters for receiver_info register
INFO_SUBREGISTERS = _NamedInts(
serial_number=0x01, # not found on many receivers
fw_version=0x02,
receiver_information=0x03,
pairing_information=0x20, # 0x2N, by connected device
extended_pairing_information=0x30, # 0x3N, by connected device
device_name=0x40, # 0x4N, by connected device
bolt_pairing_information=0x50, # 0x5N, by connected device
bolt_device_name=0x60, # 0x6N01, by connected device,
)
# Flags taken from https://drive.google.com/file/d/0BxbRzx7vEV7eNDBheWY0UHM5dEU/view?usp=sharing
DEVICE_FEATURES = _NamedInts(
reserved1=0x010000,
special_buttons=0x020000,
enhanced_key_usage=0x040000,
fast_fw_rev=0x080000,
reserved2=0x100000,
reserved3=0x200000,
scroll_accel=0x400000,
buttons_control_resolution=0x800000,
inhibit_lock_key_sound=0x000001,
reserved4=0x000002,
mx_air_3d_engine=0x000004,
host_control_leds=0x000008,
reserved5=0x000010,
reserved6=0x000020,
reserved7=0x000040,
reserved8=0x000080,
)
#
# functions
#
def read_register(device, register_number, *params): def read_register(device: Device, register: Registers | int, *params) -> Any:
assert device is not None, 'tried to read register %02X from invalid device %s' % (register_number, device) assert device is not None, f"tried to read register {register:02X} from invalid device {device}"
# support long registers by adding a 2 in front of the register number # support long registers by adding a 2 in front of the register number
request_id = 0x8100 | (int(register_number) & 0x2FF) request_id = 0x8100 | (int(register) & 0x2FF)
return device.request(request_id, *params) return device.request(request_id, *params)
def write_register(device, register_number, *value): def write_register(device: Device, register: Registers | int, *value) -> Any:
assert device is not None, 'tried to write register %02X to invalid device %s' % (register_number, device) assert device is not None, f"tried to write register {register:02X} to invalid device {device}"
# support long registers by adding a 2 in front of the register number # support long registers by adding a 2 in front of the register number
request_id = 0x8000 | (int(register_number) & 0x2FF) request_id = 0x8000 | (int(register) & 0x2FF)
return device.request(request_id, *value) return device.request(request_id, *value)
def get_battery(device): def get_configuration_pending_flags(receiver):
assert not receiver.isDevice
result = read_register(receiver, Registers.DEVICES_CONFIGURATION)
if result is not None:
return ord(result[:1])
def set_configuration_pending_flags(receiver, devices):
assert not receiver.isDevice
result = write_register(receiver, Registers.DEVICES_CONFIGURATION, devices)
return result is not None
class Hidpp10:
def get_battery(self, device: Device):
assert device is not None assert device is not None
assert device.kind is not None assert device.kind is not None
if not device.online: if not device.online:
@ -207,7 +91,7 @@ def get_battery(device):
# let's just assume HID++ 2.0 devices do not provide the battery info in a register # let's just assume HID++ 2.0 devices do not provide the battery info in a register
return return
for r in (REGISTERS.battery_status, REGISTERS.battery_charge): for r in (Registers.BATTERY_STATUS, Registers.BATTERY_CHARGE):
if r in device.registers: if r in device.registers:
reply = read_register(device, r) reply = read_register(device, r)
if reply: if reply:
@ -215,116 +99,74 @@ def get_battery(device):
return return
# the descriptor does not tell us which register this device has, try them both # the descriptor does not tell us which register this device has, try them both
reply = read_register(device, REGISTERS.battery_charge) reply = read_register(device, Registers.BATTERY_CHARGE)
if reply: if reply:
# remember this for the next time # remember this for the next time
device.registers.append(REGISTERS.battery_charge) device.registers.append(Registers.BATTERY_CHARGE)
return parse_battery_status(REGISTERS.battery_charge, reply) return parse_battery_status(Registers.BATTERY_CHARGE, reply)
reply = read_register(device, REGISTERS.battery_status) reply = read_register(device, Registers.BATTERY_STATUS)
if reply: if reply:
# remember this for the next time # remember this for the next time
device.registers.append(REGISTERS.battery_status) device.registers.append(Registers.BATTERY_STATUS)
return parse_battery_status(REGISTERS.battery_status, reply) return parse_battery_status(Registers.BATTERY_STATUS, reply)
def get_firmware(self, device: Device) -> tuple[common.FirmwareInfo] | None:
def parse_battery_status(register, reply):
if register == REGISTERS.battery_charge:
charge = ord(reply[:1])
status_byte = ord(reply[2:3]) & 0xF0
status_text = (
BATTERY_STATUS.discharging if status_byte == 0x30 else
BATTERY_STATUS.recharging if status_byte == 0x50 else BATTERY_STATUS.full if status_byte == 0x90 else None
)
return charge, None, status_text, None
if register == REGISTERS.battery_status:
status_byte = ord(reply[:1])
charge = (
_BATTERY_APPROX.full if status_byte == 7 # full
else _BATTERY_APPROX.good if status_byte == 5 # good
else _BATTERY_APPROX.low if status_byte == 3 # low
else _BATTERY_APPROX.critical if status_byte == 1 # critical
# pure 'charging' notifications may come without a status
else _BATTERY_APPROX.empty
)
charging_byte = ord(reply[1:2])
if charging_byte == 0x00:
status_text = BATTERY_STATUS.discharging
elif charging_byte & 0x21 == 0x21:
status_text = BATTERY_STATUS.recharging
elif charging_byte & 0x22 == 0x22:
status_text = BATTERY_STATUS.full
else:
logger.warning('could not parse 0x07 battery status: %02X (level %02X)', charging_byte, status_byte)
status_text = None
if charging_byte & 0x03 and status_byte == 0:
# some 'charging' notifications may come with no battery level information
charge = None
# Return None for next charge level and voltage as these are not in HID++ 1.0 spec
return charge, None, status_text, None
def get_firmware(device):
assert device is not None assert device is not None
firmware = [None, None, None] firmware = [None, None, None]
reply = read_register(device, REGISTERS.firmware, 0x01) reply = read_register(device, Registers.FIRMWARE, 0x01)
if not reply: if not reply:
# won't be able to read any of it now... # won't be able to read any of it now...
return return
fw_version = _strhex(reply[1:3]) fw_version = common.strhex(reply[1:3])
fw_version = '%s.%s' % (fw_version[0:2], fw_version[2:4]) fw_version = f"{fw_version[0:2]}.{fw_version[2:4]}"
reply = read_register(device, REGISTERS.firmware, 0x02) reply = read_register(device, Registers.FIRMWARE, 0x02)
if reply: if reply:
fw_version += '.B' + _strhex(reply[1:3]) fw_version += ".B" + common.strhex(reply[1:3])
fw = _FirmwareInfo(FIRMWARE_KIND.Firmware, '', fw_version, None) fw = common.FirmwareInfo(FirmwareKind.Firmware, "", fw_version, None)
firmware[0] = fw firmware[0] = fw
reply = read_register(device, REGISTERS.firmware, 0x04) reply = read_register(device, Registers.FIRMWARE, 0x04)
if reply: if reply:
bl_version = _strhex(reply[1:3]) bl_version = common.strhex(reply[1:3])
bl_version = '%s.%s' % (bl_version[0:2], bl_version[2:4]) bl_version = f"{bl_version[0:2]}.{bl_version[2:4]}"
bl = _FirmwareInfo(FIRMWARE_KIND.Bootloader, '', bl_version, None) bl = common.FirmwareInfo(FirmwareKind.Bootloader, "", bl_version, None)
firmware[1] = bl firmware[1] = bl
reply = read_register(device, REGISTERS.firmware, 0x03) reply = read_register(device, Registers.FIRMWARE, 0x03)
if reply: if reply:
o_version = _strhex(reply[1:3]) o_version = common.strhex(reply[1:3])
o_version = '%s.%s' % (o_version[0:2], o_version[2:4]) o_version = f"{o_version[0:2]}.{o_version[2:4]}"
o = _FirmwareInfo(FIRMWARE_KIND.Other, '', o_version, None) o = common.FirmwareInfo(FirmwareKind.Other, "", o_version, None)
firmware[2] = o firmware[2] = o
if any(firmware): if any(firmware):
return tuple(f for f in firmware if f) return tuple(f for f in firmware if f)
def set_3leds(self, device: Device, battery_level=None, charging=None, warning=None):
def set_3leds(device, battery_level=None, charging=None, warning=None):
assert device is not None assert device is not None
assert device.kind is not None assert device.kind is not None
if not device.online: if not device.online:
return return
if REGISTERS.three_leds not in device.registers: if Registers.THREE_LEDS not in device.registers:
return return
if battery_level is not None: if battery_level is not None:
if battery_level < _BATTERY_APPROX.critical: if battery_level < BatteryLevelApproximation.CRITICAL:
# 1 orange, and force blink # 1 orange, and force blink
v1, v2 = 0x22, 0x00 v1, v2 = 0x22, 0x00
warning = True warning = True
elif battery_level < _BATTERY_APPROX.low: elif battery_level < BatteryLevelApproximation.LOW:
# 1 orange # 1 orange
v1, v2 = 0x22, 0x00 v1, v2 = 0x22, 0x00
elif battery_level < _BATTERY_APPROX.good: elif battery_level < BatteryLevelApproximation.GOOD:
# 1 green # 1 green
v1, v2 = 0x20, 0x00 v1, v2 = 0x20, 0x00
elif battery_level < _BATTERY_APPROX.full: elif battery_level < BatteryLevelApproximation.FULL:
# 2 greens # 2 greens
v1, v2 = 0x20, 0x02 v1, v2 = 0x20, 0x02
else: else:
@ -332,8 +174,8 @@ def set_3leds(device, battery_level=None, charging=None, warning=None):
v1, v2 = 0x20, 0x22 v1, v2 = 0x20, 0x22
if warning: if warning:
# set the blinking flag for the leds already set # set the blinking flag for the leds already set
v1 |= (v1 >> 1) v1 |= v1 >> 1
v2 |= (v2 >> 1) v2 |= v2 >> 1
elif charging: elif charging:
# blink all green # blink all green
v1, v2 = 0x30, 0x33 v1, v2 = 0x30, 0x33
@ -344,10 +186,12 @@ def set_3leds(device, battery_level=None, charging=None, warning=None):
# turn off all leds # turn off all leds
v1, v2 = 0x11, 0x11 v1, v2 = 0x11, 0x11
write_register(device, REGISTERS.three_leds, v1, v2) write_register(device, Registers.THREE_LEDS, v1, v2)
def get_notification_flags(self, device: Device):
return self._get_register(device, Registers.NOTIFICATIONS)
def get_notification_flags(device): def set_notification_flags(self, device: Device, *flag_bits: NotificationFlag):
assert device is not None assert device is not None
# Avoid a call if the device is not online, # Avoid a call if the device is not online,
@ -357,29 +201,15 @@ def get_notification_flags(device):
if device.protocol and device.protocol >= 2.0: if device.protocol and device.protocol >= 2.0:
return return
flags = read_register(device, REGISTERS.notifications) flag_bits = sum(int(b.value) for b in flag_bits)
if flags is not None:
assert len(flags) == 3
return _bytes2int(flags)
def set_notification_flags(device, *flag_bits):
assert device is not None
# Avoid a call if the device is not online,
# or the device does not support registers.
if device.kind is not None:
# peripherals with protocol >= 2.0 don't support registers
if device.protocol and device.protocol >= 2.0:
return
flag_bits = sum(int(b) for b in flag_bits)
assert flag_bits & 0x00FFFFFF == flag_bits assert flag_bits & 0x00FFFFFF == flag_bits
result = write_register(device, REGISTERS.notifications, _int2bytes(flag_bits, 3)) result = write_register(device, Registers.NOTIFICATIONS, common.int2bytes(flag_bits, 3))
return result is not None return result is not None
def get_device_features(self, device: Device):
return self._get_register(device, Registers.MOUSE_BUTTON_FLAGS)
def get_device_features(device): def _get_register(self, device: Device, register: Registers | int):
assert device is not None assert device is not None
# Avoid a call if the device is not online, # Avoid a call if the device is not online,
@ -389,7 +219,67 @@ def get_device_features(device):
if device.protocol and device.protocol >= 2.0: if device.protocol and device.protocol >= 2.0:
return return
flags = read_register(device, REGISTERS.mouse_button_flags) flags = read_register(device, register)
if flags is not None: if flags is not None:
assert len(flags) == 3 assert len(flags) == 3
return _bytes2int(flags) return common.bytes2int(flags)
def parse_battery_status(register: Registers | int, reply) -> Battery | None:
def status_byte_to_charge(status_byte_: int) -> BatteryLevelApproximation:
if status_byte_ == 7:
charge_ = BatteryLevelApproximation.FULL
elif status_byte_ == 5:
charge_ = BatteryLevelApproximation.GOOD
elif status_byte_ == 3:
charge_ = BatteryLevelApproximation.LOW
elif status_byte_ == 1:
charge_ = BatteryLevelApproximation.CRITICAL
else:
# pure 'charging' notifications may come without a status
charge_ = BatteryLevelApproximation.EMPTY
return charge_
def status_byte_to_battery_status(status_byte_: int) -> BatteryStatus:
if status_byte_ == 0x30:
status_text_ = BatteryStatus.DISCHARGING
elif status_byte_ == 0x50:
status_text_ = BatteryStatus.RECHARGING
elif status_byte_ == 0x90:
status_text_ = BatteryStatus.FULL
else:
status_text_ = None
return status_text_
def charging_byte_to_status_text(charging_byte_: int) -> BatteryStatus:
if charging_byte_ == 0x00:
status_text_ = BatteryStatus.DISCHARGING
elif charging_byte_ & 0x21 == 0x21:
status_text_ = BatteryStatus.RECHARGING
elif charging_byte_ & 0x22 == 0x22:
status_text_ = BatteryStatus.FULL
else:
logger.warning("could not parse 0x07 battery status: %02X (level %02X)", charging_byte_, status_byte)
status_text_ = None
return status_text_
if register == Registers.BATTERY_CHARGE:
charge = ord(reply[:1])
status_byte = ord(reply[2:3]) & 0xF0
battery_status = status_byte_to_battery_status(status_byte)
return Battery(charge, None, battery_status, None)
if register == Registers.BATTERY_STATUS:
status_byte = ord(reply[:1])
charging_byte = ord(reply[1:2])
status_text = charging_byte_to_status_text(charging_byte)
charge = status_byte_to_charge(status_byte)
if charging_byte & 0x03 and status_byte == 0:
# some 'charging' notifications may come with no battery level information
charge = None
# Return None for next charge level and voltage as these are not in HID++ 1.0 spec
return Battery(charge, None, status_text, None)

View File

@ -0,0 +1,257 @@
## Copyright (C) 2012-2013 Daniel Pavel
## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from __future__ import annotations
from enum import Flag
from enum import IntEnum
from typing import List
from .common import NamedInts
"""HID constants for HID++ 1.0.
Most of them as defined by the official Logitech HID++ 1.0
documentation, some of them guessed.
"""
DEVICE_KIND = NamedInts(
unknown=0x00,
keyboard=0x01,
mouse=0x02,
numpad=0x03,
presenter=0x04,
remote=0x07,
trackball=0x08,
touchpad=0x09,
tablet=0x0A,
gamepad=0x0B,
joystick=0x0C,
headset=0x0D, # not from Logitech documentation
remote_control=0x0E, # for compatibility with HID++ 2.0
receiver=0x0F, # for compatibility with HID++ 2.0
)
class PowerSwitchLocation(IntEnum):
UNKNOWN = 0x00
BASE = 0x01
TOP_CASE = 0x02
EDGE_OF_TOP_RIGHT_CORNER = 0x03
TOP_LEFT_CORNER = 0x05
BOTTOM_LEFT_CORNER = 0x06
TOP_RIGHT_CORNER = 0x07
BOTTOM_RIGHT_CORNER = 0x08
TOP_EDGE = 0x09
RIGHT_EDGE = 0x0A
LEFT_EDGE = 0x0B
BOTTOM_EDGE = 0x0C
@classmethod
def location(cls, loc: int) -> PowerSwitchLocation:
try:
return cls(loc)
except ValueError:
return cls.UNKNOWN
class NotificationFlag(Flag):
"""Some flags are used both by devices and receivers.
The Logitech documentation mentions that the first and last (third)
byte are used for devices while the second is used for the receiver.
In practise, the second byte is also used for some device-specific
notifications (keyboard illumination level). Do not simply set all
notification bits if the software does not support it. For example,
enabling keyboard_sleep_raw makes the Sleep key a no-operation
unless the software is updated to handle that event.
Observations:
- wireless and software present seen on receivers,
reserved_r1b4 as well
- the rest work only on devices as far as we can tell right now
In the future would be useful to have separate enums for receiver
and device notification flags, but right now we don't know enough.
Additional flags taken from https://drive.google.com/file/d/0BxbRzx7vEV7eNDBheWY0UHM5dEU/view?usp=sharing
"""
@classmethod
def flag_names(cls, flag_bits: int) -> List[str]:
"""Extract the names of the flags from the integer."""
indexed = {item.value: item.name for item in cls}
flag_names = []
unknown_bits = flag_bits
for k in indexed:
# Ensure that the key (flag value) is a power of 2 (a single bit flag)
assert bin(k).count("1") == 1
if k & flag_bits == k:
unknown_bits &= ~k
flag_names.append(indexed[k].replace("_", " ").lower())
# Yield any remaining unknown bits
if unknown_bits != 0:
flag_names.append(f"unknown:{unknown_bits:06X}")
return flag_names
NUMPAD_NUMERICAL_KEYS = 0x800000
F_LOCK_STATUS = 0x400000
ROLLER_H = 0x200000
BATTERY_STATUS = 0x100000 # send battery charge notifications (0x07 or 0x0D)
MOUSE_EXTRA_BUTTONS = 0x080000
ROLLER_V = 0x040000
POWER_KEYS = 0x020000 # system control keys such as Sleep
KEYBOARD_MULTIMEDIA_RAW = 0x010000 # consumer controls such as Mute and Calculator
MULTI_TOUCH = 0x001000 # notify on multi-touch changes
SOFTWARE_PRESENT = 0x000800 # software is controlling part of device behaviour
LINK_QUALITY = 0x000400 # notify on link quality changes
UI = 0x000200 # notify on UI changes
WIRELESS = 0x000100 # notify when the device wireless goes on/off-line
CONFIGURATION_COMPLETE = 0x000004
VOIP_TELEPHONY = 0x000002
THREED_GESTURE = 0x000001
def flags_to_str(flag_bits: int | None, fallback: str) -> str:
flag_names = []
if flag_bits is not None:
if flag_bits == 0:
flag_names = (fallback,)
else:
flag_names = NotificationFlag.flag_names(flag_bits)
return f"\n{' ':15}".join(sorted(flag_names))
class ErrorCode(IntEnum):
INVALID_SUB_ID_COMMAND = 0x01
INVALID_ADDRESS = 0x02
INVALID_VALUE = 0x03
CONNECTION_REQUEST_FAILED = 0x04
TOO_MANY_DEVICES = 0x05
ALREADY_EXISTS = 0x06
BUSY = 0x07
UNKNOWN_DEVICE = 0x08
RESOURCE_ERROR = 0x09
REQUEST_UNAVAILABLE = 0x0A
UNSUPPORTED_PARAMETER_VALUE = 0x0B
WRONG_PIN_CODE = 0x0C
class PairingError(IntEnum):
DEVICE_TIMEOUT = 0x01
DEVICE_NOT_SUPPORTED = 0x02
TOO_MANY_DEVICES = 0x03
SEQUENCE_TIMEOUT = 0x06
class BoltPairingError(IntEnum):
DEVICE_TIMEOUT = 0x01
FAILED = 0x02
class Registers(IntEnum):
"""Known HID registers.
Devices usually have a (small) sub-set of these. Some registers are only
applicable to certain device kinds (e.g. smooth_scroll only applies to mice).
"""
# Generally applicable
NOTIFICATIONS = 0x00
FIRMWARE = 0xF1
# only apply to receivers
RECEIVER_CONNECTION = 0x02
RECEIVER_PAIRING = 0xB2
DEVICES_ACTIVITY = 0x2B3
RECEIVER_INFO = 0x2B5
BOLT_DEVICE_DISCOVERY = 0xC0
BOLT_PAIRING = 0x2C1
BOLT_UNIQUE_ID = 0x02FB
# only apply to devices
MOUSE_BUTTON_FLAGS = 0x01
KEYBOARD_HAND_DETECTION = 0x01
DEVICES_CONFIGURATION = 0x03
BATTERY_STATUS = 0x07
KEYBOARD_FN_SWAP = 0x09
BATTERY_CHARGE = 0x0D
KEYBOARD_ILLUMINATION = 0x17
THREE_LEDS = 0x51
MOUSE_DPI = 0x63
# notifications
PASSKEY_REQUEST_NOTIFICATION = 0x4D
PASSKEY_PRESSED_NOTIFICATION = 0x4E
DEVICE_DISCOVERY_NOTIFICATION = 0x4F
DISCOVERY_STATUS_NOTIFICATION = 0x53
PAIRING_STATUS_NOTIFICATION = 0x54
# Subregisters for receiver_info register
class InfoSubRegisters(IntEnum):
SERIAL_NUMBER = 0x01 # not found on many receivers
FW_VERSION = 0x02
RECEIVER_INFORMATION = 0x03
PAIRING_INFORMATION = 0x20 # 0x2N, by connected device
EXTENDED_PAIRING_INFORMATION = 0x30 # 0x3N, by connected device
DEVICE_NAME = 0x40 # 0x4N, by connected device
BOLT_PAIRING_INFORMATION = 0x50 # 0x5N, by connected device
BOLT_DEVICE_NAME = 0x60 # 0x6N01, by connected device
class DeviceFeature(Flag):
"""Features for devices.
Flags taken from
https://drive.google.com/file/d/0BxbRzx7vEV7eNDBheWY0UHM5dEU/view?usp=sharing
"""
@classmethod
def flag_names(cls, flag_bits: int) -> List[str]:
"""Extract the names of the flags from the integer."""
indexed = {item.value: item.name for item in cls}
flag_names = []
unknown_bits = flag_bits
for k in indexed:
# Ensure that the key (flag value) is a power of 2 (a single bit flag)
assert bin(k).count("1") == 1
if k & flag_bits == k:
unknown_bits &= ~k
flag_names.append(indexed[k].replace("_", " ").lower())
# Yield any remaining unknown bits
if unknown_bits != 0:
flag_names.append(f"unknown:{unknown_bits:06X}")
return flag_names
RESERVED1 = 0x010000
SPECIAL_BUTTONS = 0x020000
ENHANCED_KEY_USAGE = 0x040000
FAST_FW_REV = 0x080000
RESERVED2 = 0x100000
RESERVED3 = 0x200000
SCROLL_ACCEL = 0x400000
BUTTONS_CONTROL_RESOLUTION = 0x800000
INHIBIT_LOCK_KEY_SOUND = 0x000001
RESERVED4 = 0x000002
MX_AIR_3D_ENGINE = 0x000004
HOST_CONTROL_LEDS = 0x000008
RESERVED5 = 0x000010
RESERVED6 = 0x000020
RESERVED7 = 0x000040
RESERVED8 = 0x000080

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,278 @@
## Copyright (C) 2012-2013 Daniel Pavel
## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from enum import IntEnum
from enum import IntFlag
from .common import NamedInts
# <FeaturesSupported.xml sed '/LD_FID_/{s/.*LD_FID_/\t/;s/"[ \t]*Id="/=/;s/" \/>/,/p}' | sort -t= -k2
# additional features names taken from https://github.com/cvuchener/hidpp and
# https://github.com/Logitech/cpg-docs/tree/master/hidpp20
"""Possible features available on a Logitech device.
A particular device might not support all these features, and may support other
unknown features as well.
"""
class SupportedFeature(IntEnum):
ROOT = 0x0000
FEATURE_SET = 0x0001
FEATURE_INFO = 0x0002
# Common
DEVICE_FW_VERSION = 0x0003
DEVICE_UNIT_ID = 0x0004
DEVICE_NAME = 0x0005
DEVICE_GROUPS = 0x0006
DEVICE_FRIENDLY_NAME = 0x0007
KEEP_ALIVE = 0x0008
CONFIG_CHANGE = 0x0020
CRYPTO_ID = 0x0021
TARGET_SOFTWARE = 0x0030
WIRELESS_SIGNAL_STRENGTH = 0x0080
DFUCONTROL_LEGACY = 0x00C0
DFUCONTROL_UNSIGNED = 0x00C1
DFUCONTROL_SIGNED = 0x00C2
DFUCONTROL = 0x00C3
DFU = 0x00D0
BATTERY_STATUS = 0x1000
BATTERY_VOLTAGE = 0x1001
UNIFIED_BATTERY = 0x1004
CHARGING_CONTROL = 0x1010
LED_CONTROL = 0x1300
FORCE_PAIRING = 0x1500
GENERIC_TEST = 0x1800
DEVICE_RESET = 0x1802
OOBSTATE = 0x1805
CONFIG_DEVICE_PROPS = 0x1806
CHANGE_HOST = 0x1814
HOSTS_INFO = 0x1815
BACKLIGHT = 0x1981
BACKLIGHT2 = 0x1982
BACKLIGHT3 = 0x1983
ILLUMINATION = 0x1990
PRESENTER_CONTROL = 0x1A00
SENSOR_3D = 0x1A01
REPROG_CONTROLS = 0x1B00
REPROG_CONTROLS_V2 = 0x1B01
REPROG_CONTROLS_V2_2 = 0x1B02 # LogiOptions 2.10.73 features.xml
REPROG_CONTROLS_V3 = 0x1B03
REPROG_CONTROLS_V4 = 0x1B04
REPORT_HID_USAGE = 0x1BC0
PERSISTENT_REMAPPABLE_ACTION = 0x1C00
WIRELESS_DEVICE_STATUS = 0x1D4B
REMAINING_PAIRING = 0x1DF0
FIRMWARE_PROPERTIES = 0x1F1F
ADC_MEASUREMENT = 0x1F20
# Mouse
LEFT_RIGHT_SWAP = 0x2001
SWAP_BUTTON_CANCEL = 0x2005
POINTER_AXIS_ORIENTATION = 0x2006
VERTICAL_SCROLLING = 0x2100
SMART_SHIFT = 0x2110
SMART_SHIFT_ENHANCED = 0x2111
HI_RES_SCROLLING = 0x2120
HIRES_WHEEL = 0x2121
LOWRES_WHEEL = 0x2130
THUMB_WHEEL = 0x2150
MOUSE_POINTER = 0x2200
ADJUSTABLE_DPI = 0x2201
EXTENDED_ADJUSTABLE_DPI = 0x2202
POINTER_SPEED = 0x2205
ANGLE_SNAPPING = 0x2230
SURFACE_TUNING = 0x2240
XY_STATS = 0x2250
WHEEL_STATS = 0x2251
HYBRID_TRACKING = 0x2400
# Keyboard
FN_INVERSION = 0x40A0
NEW_FN_INVERSION = 0x40A2
K375S_FN_INVERSION = 0x40A3
ENCRYPTION = 0x4100
LOCK_KEY_STATE = 0x4220
SOLAR_DASHBOARD = 0x4301
KEYBOARD_LAYOUT = 0x4520
KEYBOARD_DISABLE_KEYS = 0x4521
KEYBOARD_DISABLE_BY_USAGE = 0x4522
DUALPLATFORM = 0x4530
MULTIPLATFORM = 0x4531
KEYBOARD_LAYOUT_2 = 0x4540
CROWN = 0x4600
# Touchpad
TOUCHPAD_FW_ITEMS = 0x6010
TOUCHPAD_SW_ITEMS = 0x6011
TOUCHPAD_WIN8_FW_ITEMS = 0x6012
TAP_ENABLE = 0x6020
TAP_ENABLE_EXTENDED = 0x6021
CURSOR_BALLISTIC = 0x6030
TOUCHPAD_RESOLUTION = 0x6040
TOUCHPAD_RAW_XY = 0x6100
TOUCHMOUSE_RAW_POINTS = 0x6110
TOUCHMOUSE_6120 = 0x6120
GESTURE = 0x6500
GESTURE_2 = 0x6501
# Gaming Devices
GKEY = 0x8010
MKEYS = 0x8020
MR = 0x8030
BRIGHTNESS_CONTROL = 0x8040
REPORT_RATE = 0x8060
EXTENDED_ADJUSTABLE_REPORT_RATE = 0x8061
COLOR_LED_EFFECTS = 0x8070
RGB_EFFECTS = 0x8071
PER_KEY_LIGHTING = 0x8080
PER_KEY_LIGHTING_V2 = 0x8081
MODE_STATUS = 0x8090
ONBOARD_PROFILES = 0x8100
MOUSE_BUTTON_SPY = 0x8110
LATENCY_MONITORING = 0x8111
GAMING_ATTACHMENTS = 0x8120
FORCE_FEEDBACK = 0x8123
# Headsets
SIDETONE = 0x8300
EQUALIZER = 0x8310
HEADSET_OUT = 0x8320
# Fake features for Solaar internal use
MOUSE_GESTURE = 0xFE00
def __str__(self):
return self.name.replace("_", " ")
class FeatureFlag(IntFlag):
"""Single bit flags."""
INTERNAL = 0x20
HIDDEN = 0x40
OBSOLETE = 0x80
DEVICE_KIND = NamedInts(
keyboard=0x00,
remote_control=0x01,
numpad=0x02,
mouse=0x03,
touchpad=0x04,
trackball=0x05,
presenter=0x06,
receiver=0x07,
)
class OnboardMode(IntEnum):
MODE_NO_CHANGE = 0x00
MODE_ONBOARD = 0x01
MODE_HOST = 0x02
class ChargeLevel(IntEnum):
AVERAGE = 50
FULL = 90
CRITICAL = 5
class ChargeType(IntEnum):
STANDARD = 0x00
FAST = 0x01
SLOW = 0x02
class ErrorCode(IntEnum):
UNKNOWN = 0x01
INVALID_ARGUMENT = 0x02
OUT_OF_RANGE = 0x03
HARDWARE_ERROR = 0x04
LOGITECH_ERROR = 0x05
INVALID_FEATURE_INDEX = 0x06
INVALID_FUNCTION = 0x07
BUSY = 0x08
UNSUPPORTED = 0x09
class GestureId(IntEnum):
"""Gesture IDs for feature GESTURE_2."""
TAP_1_FINGER = 1 # task Left_Click
TAP_2_FINGER = 2 # task Right_Click
TAP_3_FINGER = 3
CLICK_1_FINGER = 4 # task Left_Click
CLICK_2_FINGER = 5 # task Right_Click
CLICK_3_FINGER = 6
DOUBLE_TAP_1_FINGER = 10
DOUBLE_TAP_2_FINGER = 11
DOUBLE_TAP_3_FINGER = 12
TRACK_1_FINGER = 20 # action MovePointer
TRACKING_ACCELERATION = 21
TAP_DRAG_1_FINGER = 30 # action Drag
TAP_DRAG_2_FINGER = 31 # action SecondaryDrag
DRAG_3_FINGER = 32
TAP_GESTURES = 33 # group all tap gestures under a single UI setting
FN_CLICK_GESTURE_SUPPRESSION = 34 # suppresses Tap and Edge gestures, toggled by Fn+Click
SCROLL_1_FINGER = 40 # action ScrollOrPageXY / ScrollHorizontal
SCROLL_2_FINGER = 41 # action ScrollOrPageXY / ScrollHorizontal
SCROLL_2_FINGER_HORIZONTAL = 42 # action ScrollHorizontal
SCROLL_2_FINGER_VERTICAL = 43 # action WheelScrolling
SCROLL_2_FINGER_STATELESS = 44
NATURAL_SCROLLING = 45 # affects native HID wheel reporting by gestures, not when diverted
THUMBWHEEL = (46,) # action WheelScrolling
V_SCROLL_INTERTIA = 48
V_SCROLL_BALLISTICS = 49
SWIPE_2_FINGER_HORIZONTAL = 50 # action PageScreen
SWIPE_3_FINGER_HORIZONTAL = 51 # action PageScreen
SWIPE_4_FINGER_HORIZONTAL = 52 # action PageScreen
SWIPE_3_FINGER_VERTICAL = 53
SWIPE_4_FINGER_VERTICAL = 54
LEFT_EDGE_SWIPE_1_FINGER = 60
RIGHT_EDGE_SWIPE_1_FINGER = 61
BOTTOM_EDGE_SWIPE_1_FINGER = 62
TOP_EDGE_SWIPE_1_FINGER = 63
LEFT_EDGE_SWIPE_1_FINGER_2 = 64 # task HorzScrollNoRepeatSet
RIGHT_EDGE_SWIPE_1_FINGER_2 = 65
BOTTOM_EDGE_SWIPE_1_FINGER_2 = 66
TOP_EDGE_SWIPE_1_FINGER_2 = 67
LEFT_EDGE_SWIPE_2_FINGER = 70
RIGHT_EDGE_SWIPE_2_FINGER = 71
BottomEdgeSwipe2Finger = 72
BOTTOM_EDGE_SWIPE_2_FINGER = 72
TOP_EDGE_SWIPE_2_FINGER = 73
ZOOM_2_FINGER = 80 # action Zoom
ZOOM_2_FINGER_PINCH = 81 # ZoomBtnInSet
ZOOM_2_FINGER_SPREAD = 82 # ZoomBtnOutSet
ZOOM_3_FINGER = 83
ZOOM_2_FINGER_STATELESS = 84
TWO_FINGERS_PRESENT = 85
ROTATE_2_FINGER = 87
FINGER_1 = 90
FINGER_2 = 91
FINGER_3 = 92
FINGER_4 = 93
FINGER_5 = 94
FINGER_6 = 95
FINGER_7 = 96
FINGER_8 = 97
FINGER_9 = 98
FINGER_10 = 99
DEVICE_SPECIFIC_RAW_DATA = 100
class ParamId(IntEnum):
"""Param Ids for feature GESTURE_2"""
EXTRA_CAPABILITIES = 1 # not suitable for use
PIXEL_ZONE = 2 # 4 2-byte integers, left, bottom, width, height; pixels
RATIO_ZONE = 3 # 4 bytes, left, bottom, width, height; unit 1/240 pad size
SCALE_FACTOR = 4 # 2-byte integer, with 256 as normal scale

View File

@ -1,5 +1,3 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
@ -18,70 +16,65 @@
# Translation support for the Logitech receivers library # Translation support for the Logitech receivers library
import gettext as _gettext import gettext
_ = _gettext.gettext _ = gettext.gettext
ngettext = _gettext.ngettext ngettext = gettext.ngettext
# A few common strings, not always accessible as such in the code. # A few common strings, not always accessible as such in the code.
_DUMMY = ( _DUMMY = (
# approximative battery levels # approximative battery levels
_('empty'), _("empty"),
_('critical'), _("critical"),
_('low'), _("low"),
_('average'), _("average"),
_('good'), _("good"),
_('full'), _("full"),
# battery charging statuses # battery charging statuses
_('discharging'), _("discharging"),
_('recharging'), _("recharging"),
_('charging'), _("charging"),
_('not charging'), _("not charging"),
_('almost full'), _("almost full"),
_('charged'), _("charged"),
_('slow recharge'), _("slow recharge"),
_('invalid battery'), _("invalid battery"),
_('thermal error'), _("thermal error"),
_('error'), _("error"),
_('standard'), _("standard"),
_('fast'), _("fast"),
_('slow'), _("slow"),
# pairing errors # pairing errors
_('device timeout'), _("device timeout"),
_('device not supported'), _("device not supported"),
_('too many devices'), _("too many devices"),
_('sequence timeout'), _("sequence timeout"),
# firmware kinds # firmware kinds
_('Firmware'), _("Firmware"),
_('Bootloader'), _("Bootloader"),
_('Hardware'), _("Hardware"),
_('Other'), _("Other"),
# common button and task names (from special_keys.py) # common button and task names (from special_keys.py)
_('Left Button'), _("Left Button"),
_('Right Button'), _("Right Button"),
_('Middle Button'), _("Middle Button"),
_('Back Button'), _("Back Button"),
_('Forward Button'), _("Forward Button"),
_('Mouse Gesture Button'), _("Mouse Gesture Button"),
_('Smart Shift'), _("Smart Shift"),
_('DPI Switch'), _("DPI Switch"),
_('Left Tilt'), _("Left Tilt"),
_('Right Tilt'), _("Right Tilt"),
_('Left Click'), _("Left Click"),
_('Right Click'), _("Right Click"),
_('Mouse Middle Button'), _("Mouse Middle Button"),
_('Mouse Back Button'), _("Mouse Back Button"),
_('Mouse Forward Button'), _("Mouse Forward Button"),
_('Gesture Button Navigation'), _("Gesture Button Navigation"),
_('Mouse Scroll Left Button'), _("Mouse Scroll Left Button"),
_('Mouse Scroll Right Button'), _("Mouse Scroll Right Button"),
# key/button statuses # key/button statuses
_('pressed'), _("pressed"),
_('released'), _("released"),
) )

View File

@ -1,6 +1,5 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by ## it under the terms of the GNU General Public License as published by
@ -17,32 +16,21 @@
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import logging import logging
import threading as _threading import queue
import threading
from . import base as _base from . import base
from . import exceptions
# from time import time as _timestamp
# for both Python 2 and 3
try:
from Queue import Queue as _Queue
except ImportError:
from queue import Queue as _Queue
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
#
#
#
class _ThreadedHandle: class _ThreadedHandle:
"""A thread-local wrapper with different open handles for each thread. """A thread-local wrapper with different open handles for each thread.
Closing a ThreadedHandle will close all handles. Closing a ThreadedHandle will close all handles.
""" """
__slots__ = ('path', '_local', '_handles', '_listener') __slots__ = ("path", "_local", "_handles", "_listener")
def __init__(self, listener, path, handle): def __init__(self, listener, path, handle):
assert listener is not None assert listener is not None
@ -52,15 +40,15 @@ class _ThreadedHandle:
self._listener = listener self._listener = listener
self.path = path self.path = path
self._local = _threading.local() self._local = threading.local()
# take over the current handle for the thread doing the replacement # take over the current handle for the thread doing the replacement
self._local.handle = handle self._local.handle = handle
self._handles = [handle] self._handles = [handle]
def _open(self): def _open(self):
handle = _base.open_path(self.path) handle = base.open_path(self.path)
if handle is None: if handle is None:
logger.error('%r failed to open new handle', self) logger.error("%r failed to open new handle", self)
else: else:
# if logger.isEnabledFor(logging.DEBUG): # if logger.isEnabledFor(logging.DEBUG):
# logger.debug("%r opened new handle %d", self, handle) # logger.debug("%r opened new handle %d", self, handle)
@ -73,15 +61,15 @@ class _ThreadedHandle:
self._local = None self._local = None
handles, self._handles = self._handles, [] handles, self._handles = self._handles, []
if logger.isEnabledFor(logging.DEBUG): if logger.isEnabledFor(logging.DEBUG):
logger.debug('%r closing %s', self, handles) logger.debug("%r closing %s", self, handles)
for h in handles: for h in handles:
_base.close(h) base.close(h)
@property @property
def notifications_hook(self): def notifications_hook(self):
if self._listener: if self._listener:
assert isinstance(self._listener, _threading.Thread) assert isinstance(self._listener, threading.Thread)
if _threading.current_thread() == self._listener: if threading.current_thread() == self._listener:
return self._listener._notifications_hook return self._listener._notifications_hook
def __del__(self): def __del__(self):
@ -104,7 +92,7 @@ class _ThreadedHandle:
return str(int(self)) return str(int(self))
def __repr__(self): def __repr__(self):
return '<_ThreadedHandle(%s)>' % self.path return f"<_ThreadedHandle({self.path})>"
def __bool__(self): def __bool__(self):
return bool(self._local) return bool(self._local)
@ -112,39 +100,28 @@ class _ThreadedHandle:
__nonzero__ = __bool__ __nonzero__ = __bool__
# # How long to wait during a read for the next packet, in seconds.
# # Ideally this should be rather long (10s ?), but the read is blocking and this means that when the thread
# # is signalled to stop, it would take a while for it to acknowledge it.
# Forcibly closing the file handle on another thread does _not_ interrupt the read on Linux systems.
# How long to wait during a read for the next packet, in seconds _EVENT_READ_TIMEOUT = 1.0 # in seconds
# Ideally this should be rather long (10s ?), but the read is blocking
# and this means that when the thread is signalled to stop, it would take
# a while for it to acknowledge it.
# Forcibly closing the file handle on another thread does _not_ interrupt the
# read on Linux systems.
_EVENT_READ_TIMEOUT = 1. # in seconds
# After this many reads that did not produce a packet, call the tick() method.
# This only happens if tick_period is enabled (>0) for the Listener instance.
# _IDLE_READS = 1 + int(5 // _EVENT_READ_TIMEOUT) # wait at least 5 seconds between ticks
class EventsListener(_threading.Thread): class EventsListener(threading.Thread):
"""Listener thread for notifications from the Unifying Receiver. """Listener thread for notifications from the Unifying Receiver.
Incoming packets will be passed to the callback function in sequence. Incoming packets will be passed to the callback function in sequence.
""" """
def __init__(self, receiver, notifications_callback): def __init__(self, receiver, notifications_callback):
try: try:
path_name = receiver.path.split('/')[2] path_name = receiver.path.split("/")[2]
except IndexError: except IndexError:
path_name = receiver.path path_name = receiver.path
super().__init__(name=self.__class__.__name__ + ':' + path_name) super().__init__(name=f"{self.__class__.__name__}:{path_name}")
self.daemon = True self.daemon = True
self._active = False self._active = False
self.receiver = receiver self.receiver = receiver
self._queued_notifications = _Queue(16) self._queued_notifications = queue.Queue(16)
self._notifications_callback = notifications_callback self._notifications_callback = notifications_callback
def run(self): def run(self):
@ -152,30 +129,30 @@ class EventsListener(_threading.Thread):
# replace the handle with a threaded one # replace the handle with a threaded one
self.receiver.handle = _ThreadedHandle(self, self.receiver.path, self.receiver.handle) self.receiver.handle = _ThreadedHandle(self, self.receiver.path, self.receiver.handle)
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
logger.info('started with %s (%d)', self.receiver, int(self.receiver.handle)) logger.info("started with %s (%d)", self.receiver, int(self.receiver.handle))
self.has_started() self.has_started()
if self.receiver.isDevice: # ping (wired or BT) devices to see if they are really online if self.receiver.isDevice: # ping (wired or BT) devices to see if they are really online
if self.receiver.ping(): if self.receiver.ping():
self.receiver.status.changed(True, reason='initialization') self.receiver.changed(active=True, reason="initialization")
while self._active: while self._active:
if self._queued_notifications.empty(): if self._queued_notifications.empty():
try: try:
n = _base.read(self.receiver.handle, _EVENT_READ_TIMEOUT) n = base.read(self.receiver.handle, _EVENT_READ_TIMEOUT)
except _base.NoReceiver: except exceptions.NoReceiver:
logger.warning('%s disconnected', self.receiver.name) logger.warning("%s disconnected", self.receiver.name)
self.receiver.close() self.receiver.close()
break break
if n: if n:
n = _base.make_notification(*n) n = base.make_notification(*n)
else: else:
n = self._queued_notifications.get() # deliver any queued notifications n = self._queued_notifications.get() # deliver any queued notifications
if n: if n:
try: try:
self._notifications_callback(n) self._notifications_callback(n)
except Exception: except Exception:
logger.exception('processing %s', n) logger.exception("processing %s", n)
del self._queued_notifications del self._queued_notifications
self.has_stopped() self.has_stopped()
@ -193,15 +170,11 @@ class EventsListener(_threading.Thread):
"""Called right before the thread stops.""" """Called right before the thread stops."""
pass pass
# def tick(self, timestamp):
# """Called about every tick_period seconds."""
# pass
def _notifications_hook(self, n): def _notifications_hook(self, n):
# Only consider unhandled notifications that were sent from this thread, # Only consider unhandled notifications that were sent from this thread,
# i.e. triggered by a callback handling a previous notification. # i.e. triggered by a callback handling a previous notification.
assert _threading.current_thread() == self assert threading.current_thread() == self
if self._active: # and _threading.current_thread() == self: if self._active: # and threading.current_thread() == self:
# if logger.isEnabledFor(logging.DEBUG): # if logger.isEnabledFor(logging.DEBUG):
# logger.debug("queueing unhandled %s", n) # logger.debug("queueing unhandled %s", n)
if not self._queued_notifications.full(): if not self._queued_notifications.full():

View File

@ -1,4 +1,5 @@
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by ## it under the terms of the GNU General Public License as published by
@ -14,466 +15,498 @@
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# Handles incoming events from the receiver/devices, updating the related """Handles incoming events from the receiver/devices, updating the
# status object as appropriate. object as appropriate.
"""
from __future__ import annotations
import logging import logging
import threading as _threading import struct
import threading
import typing
from struct import unpack as _unpack from solaar.i18n import _
from . import diversion as _diversion from . import base
from . import hidpp10 as _hidpp10 from . import common
from . import hidpp20 as _hidpp20 from . import diversion
from . import settings_templates as _st from . import hidpp10
from .base import DJ_MESSAGE_ID as _DJ_MESSAGE_ID from . import hidpp10_constants
from .common import strhex as _strhex from . import hidpp20
from .i18n import _ from . import settings_templates
from .status import ALERT as _ALERT from .common import Alert
from .status import KEYS as _K from .common import BatteryStatus
from .common import Notification
from .hidpp10_constants import Registers
from .hidpp20_constants import SupportedFeature
if typing.TYPE_CHECKING:
from .base import HIDPPNotification
from .device import Device
from .receiver import Receiver
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
_R = _hidpp10.REGISTERS NotificationHandler = typing.Callable[["Receiver", "HIDPPNotification"], bool]
_F = _hidpp20.FEATURE
# _hidpp10 = hidpp10.Hidpp10()
# _hidpp20 = hidpp20.Hidpp20()
#
notification_lock = _threading.Lock() notification_lock = threading.Lock()
def process(device, notification): def process(device: Device | Receiver, notification: HIDPPNotification):
"""Handle incoming events (notification) from device or receiver."""
assert device assert device
assert notification assert notification
assert hasattr(device, 'status')
status = device.status
assert status is not None
if not device.isDevice: if not device.isDevice:
return _process_receiver_notification(device, status, notification) return process_receiver_notification(device, notification)
return process_device_notification(device, notification)
return _process_device_notification(device, status, notification)
# def process_receiver_notification(receiver: Receiver, notification: HIDPPNotification) -> bool | None:
# """Process event messages from receivers."""
# event_handler_mapping: dict[int, NotificationHandler] = {
Notification.PAIRING_LOCK: handle_pairing_lock,
Registers.DEVICE_DISCOVERY_NOTIFICATION: handle_device_discovery,
Registers.DISCOVERY_STATUS_NOTIFICATION: handle_discovery_status,
Registers.PAIRING_STATUS_NOTIFICATION: handle_pairing_status,
Registers.PASSKEY_PRESSED_NOTIFICATION: handle_passkey_pressed,
Registers.PASSKEY_REQUEST_NOTIFICATION: handle_passkey_request,
}
try:
handler_func = event_handler_mapping[notification.sub_id]
return handler_func(receiver, notification)
except KeyError:
pass
assert notification.sub_id in [
Notification.CONNECT_DISCONNECT,
Notification.DJ_PAIRING,
Notification.CONNECTED,
Notification.RAW_INPUT,
Notification.POWER,
]
logger.warning(f"{receiver}: unhandled notification {notification}")
def _process_receiver_notification(receiver, status, n): def process_device_notification(device: Device, notification: HIDPPNotification):
# supposedly only 0x4x notifications arrive for the receiver """Process event messages from devices."""
assert n.sub_id & 0x40 == 0x40
if n.sub_id == 0x4A: # pairing lock notification # incoming packets with SubId >= 0x80 are supposedly replies from HID++ 1.0 requests, should never get here
status.lock_open = bool(n.address & 0x01) assert notification.sub_id & 0x80 == 0
reason = (_('pairing lock is open') if status.lock_open else _('pairing lock is closed'))
if logger.isEnabledFor(logging.INFO):
logger.info('%s: %s', receiver, reason)
status[_K.ERROR] = None
if status.lock_open:
status.new_device = None
pair_error = ord(n.data[:1])
if pair_error:
status[_K.ERROR] = error_string = _hidpp10.PAIRING_ERRORS[pair_error]
status.new_device = None
logger.warning('pairing error %d: %s', pair_error, error_string)
status.changed(reason=reason)
return True
elif n.sub_id == _R.discovery_status_notification: # Bolt pairing if notification.sub_id == Notification.NO_OPERATION:
with notification_lock: # dispose it
status.discovering = n.address == 0x00
reason = (_('discovery lock is open') if status.discovering else _('discovery lock is closed'))
if logger.isEnabledFor(logging.INFO):
logger.info('%s: %s', receiver, reason)
status[_K.ERROR] = None
if status.discovering:
status.counter = status.device_address = status.device_authentication = status.device_name = None
status.device_passkey = None
discover_error = ord(n.data[:1])
if discover_error:
status[_K.ERROR] = discover_string = _hidpp10.BOLT_PAIRING_ERRORS[discover_error]
logger.warning('bolt discovering error %d: %s', discover_error, discover_string)
status.changed(reason=reason)
return True
elif n.sub_id == _R.device_discovery_notification: # Bolt pairing
with notification_lock:
counter = n.address + n.data[0] * 256 # notification counter
if status.counter is None:
status.counter = counter
else:
if not status.counter == counter:
return None
if n.data[1] == 0:
status.device_kind = n.data[3]
status.device_address = n.data[6:12]
status.device_authentication = n.data[14]
elif n.data[1] == 1:
status.device_name = n.data[3:3 + n.data[2]].decode('utf-8')
return True
elif n.sub_id == _R.pairing_status_notification: # Bolt pairing
with notification_lock:
status.device_passkey = None
status.lock_open = n.address == 0x00
reason = (_('pairing lock is open') if status.lock_open else _('pairing lock is closed'))
if logger.isEnabledFor(logging.INFO):
logger.info('%s: %s', receiver, reason)
status[_K.ERROR] = None
if not status.lock_open:
status.counter = status.device_address = status.device_authentication = status.device_name = None
pair_error = n.data[0]
if status.lock_open:
status.new_device = None
elif n.address == 0x02 and not pair_error:
status.new_device = receiver.register_new_device(n.data[7])
if pair_error:
status[_K.ERROR] = error_string = _hidpp10.BOLT_PAIRING_ERRORS[pair_error]
status.new_device = None
logger.warning('pairing error %d: %s', pair_error, error_string)
status.changed(reason=reason)
return True
elif n.sub_id == _R.passkey_request_notification: # Bolt pairing
with notification_lock:
status.device_passkey = n.data[0:6].decode('utf-8')
return True
elif n.sub_id == _R.passkey_pressed_notification: # Bolt pairing
return True
logger.warning('%s: unhandled notification %s', receiver, n)
#
#
#
def _process_device_notification(device, status, n):
# incoming packets with SubId >= 0x80 are supposedly replies from
# HID++ 1.0 requests, should never get here
assert n.sub_id & 0x80 == 0
if n.sub_id == 00: # no-op feature notification, dispose of it quickly
return False return False
# Allow the device object to handle the notification using custom # Allow the device object to handle the notification using custom per-device state.
# per-device state. handling_ret = device.handle_notification(notification)
handling_ret = device.handle_notification(n)
if handling_ret is not None: if handling_ret is not None:
return handling_ret return handling_ret
# 0x40 to 0x7F appear to be HID++ 1.0 or DJ notifications # 0x40 to 0x7F appear to be HID++ 1.0 or DJ notifications
if n.sub_id >= 0x40: if notification.sub_id >= 0x40:
if n.report_id == _DJ_MESSAGE_ID: if notification.report_id == base.DJ_MESSAGE_ID:
return _process_dj_notification(device, status, n) return _process_dj_notification(device, notification)
else: else:
return _process_hidpp10_notification(device, status, n) return _process_hidpp10_notification(device, notification)
# These notifications are from the device itself, so it must be active # These notifications are from the device itself, so it must be active
device.online = True device.online = True
# At this point, we need to know the device's protocol, otherwise it's # At this point, we need to know the device's protocol, otherwise it's possible to not know how to handle it.
# possible to not know how to handle it.
assert device.protocol is not None assert device.protocol is not None
# some custom battery events for HID++ 1.0 devices # some custom battery events for HID++ 1.0 devices
if device.protocol < 2.0: if device.protocol < 2.0:
return _process_hidpp10_custom_notification(device, status, n) return _process_hidpp10_custom_notification(device, notification)
# assuming 0x00 to 0x3F are feature (HID++ 2.0) notifications # assuming 0x00 to 0x3F are feature (HID++ 2.0) notifications
if not device.features: if not device.features:
logger.warning('%s: feature notification but features not set up: %02X %s', device, n.sub_id, n) logger.warning("%s: feature notification but features not set up: %02X %s", device, notification.sub_id, notification)
return False
try:
feature = device.features.get_feature(n.sub_id)
except IndexError:
logger.warning('%s: notification from invalid feature index %02X: %s', device, n.sub_id, n)
return False return False
return _process_feature_notification(device, status, n, feature) return _process_feature_notification(device, notification)
def _process_dj_notification(device, status, n): def _process_dj_notification(device: Device, notification: HIDPPNotification):
if logger.isEnabledFor(logging.DEBUG): if logger.isEnabledFor(logging.DEBUG):
logger.debug('%s (%s) DJ %s', device, device.protocol, n) logger.debug("%s (%s) DJ %s", device, device.protocol, notification)
if n.sub_id == 0x40: if notification.sub_id == Notification.CONNECT_DISCONNECT:
# do all DJ paired notifications also show up as HID++ 1.0 notifications? # do all DJ paired notifications also show up as HID++ 1.0 notifications?
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
logger.info('%s: ignoring DJ unpaired: %s', device, n) logger.info("%s: ignoring DJ unpaired: %s", device, notification)
return True return True
if n.sub_id == 0x41: if notification.sub_id == Notification.DJ_PAIRING:
# do all DJ paired notifications also show up as HID++ 1.0 notifications? # do all DJ paired notifications also show up as HID++ 1.0 notifications?
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
logger.info('%s: ignoring DJ paired: %s', device, n) logger.info("%s: ignoring DJ paired: %s", device, notification)
return True return True
if n.sub_id == 0x42: if notification.sub_id == Notification.CONNECTED:
connected = not n.address & 0x01 connected = not notification.address & 0x01
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
logger.info('%s: DJ connection: %s %s', device, connected, n) logger.info("%s: DJ connection: %s %s", device, connected, notification)
status.changed(active=connected, alert=_ALERT.NONE, reason=_('connected') if connected else _('disconnected')) device.changed(active=connected, alert=Alert.NONE, reason=_("connected") if connected else _("disconnected"))
return True return True
logger.warning('%s: unrecognized DJ %s', device, n) logger.warning("%s: unrecognized DJ %s", device, notification)
def _process_hidpp10_custom_notification(device, status, n): def _process_hidpp10_custom_notification(device: Device, notification: HIDPPNotification):
if logger.isEnabledFor(logging.DEBUG): if logger.isEnabledFor(logging.DEBUG):
logger.debug('%s (%s) custom notification %s', device, device.protocol, n) logger.debug("%s (%s) custom notification %s", device, device.protocol, notification)
if n.sub_id in (_R.battery_status, _R.battery_charge): if notification.sub_id in (Registers.BATTERY_STATUS, Registers.BATTERY_CHARGE):
# message layout: 10 ix <register> <xx> <yy> <zz> <00> assert notification.data[-1:] == b"\x00"
assert n.data[-1:] == b'\x00' data = chr(notification.address).encode() + notification.data
data = chr(n.address).encode() + n.data device.set_battery_info(hidpp10.parse_battery_status(notification.sub_id, data))
charge, next_charge, status_text, voltage = _hidpp10.parse_battery_status(n.sub_id, data)
status.set_battery_info(charge, next_charge, status_text, voltage)
return True return True
if n.sub_id == _R.keyboard_illumination: logger.warning("%s: unrecognized %s", device, notification)
# message layout: 10 ix 17("address") <??> <?> <??> <light level 1=off..5=max>
# TODO anything we can do with this?
if logger.isEnabledFor(logging.INFO):
logger.info('illumination event: %s', n)
return True
logger.warning('%s: unrecognized %s', device, n)
def _process_hidpp10_notification(device, status, n): def _process_hidpp10_notification(device: Device, notification: HIDPPNotification):
# device unpairing if notification.sub_id == Notification.CONNECT_DISCONNECT: # device unpairing
if n.sub_id == 0x40: if notification.address == 0x02:
if n.address == 0x02:
# device un-paired # device un-paired
status.clear()
device.wpid = None device.wpid = None
device.status = None
if device.number in device.receiver: if device.number in device.receiver:
del device.receiver[device.number] del device.receiver[device.number]
status.changed(active=False, alert=_ALERT.ALL, reason=_('unpaired')) device.changed(active=False, alert=Alert.ALL, reason=_("unpaired"))
## device.status = None
else: else:
logger.warning('%s: disconnection with unknown type %02X: %s', device, n.address, n) logger.warning("%s: disconnection with unknown type %02X: %s", device, notification.address, notification)
return True return True
# device connection (and disconnection) if notification.sub_id == Notification.DJ_PAIRING: # device connection (and disconnection)
if n.sub_id == 0x41: flags = ord(notification.data[:1]) & 0xF0
flags = ord(n.data[:1]) & 0xF0 if notification.address == 0x02: # very old 27 MHz protocol
if n.address == 0x02: # very old 27 MHz protocol wpid = "00" + common.strhex(notification.data[2:3])
wpid = '00' + _strhex(n.data[2:3])
link_established = True link_established = True
link_encrypted = bool(flags & 0x80) link_encrypted = bool(flags & 0x80)
elif n.address > 0x00: # all other protocols are supposed to be almost the same elif notification.address > 0x00: # all other protocols are supposed to be almost the same
wpid = _strhex(n.data[2:3] + n.data[1:2]) wpid = common.strhex(notification.data[2:3] + notification.data[1:2])
link_established = not (flags & 0x40) link_established = not (flags & 0x40)
link_encrypted = bool(flags & 0x20) or n.address == 0x10 # Bolt protocol always encrypted link_encrypted = bool(flags & 0x20) or notification.address == 0x10 # Bolt protocol always encrypted
else: else:
logger.warning('%s: connection notification with unknown protocol %02X: %s', device.number, n.address, n) logger.warning(
"%s: connection notification with unknown protocol %02X: %s", device.number, notification.address, notification
)
return True return True
if wpid != device.wpid: if wpid != device.wpid:
logger.warning('%s wpid mismatch, got %s', device, wpid) logger.warning("%s wpid mismatch, got %s", device, wpid)
if logger.isEnabledFor(logging.DEBUG): if logger.isEnabledFor(logging.DEBUG):
logger.debug( logger.debug(
'%s: protocol %s connection notification: software=%s, encrypted=%s, link=%s, payload=%s', device, n.address, "%s: protocol %s connection notification: software=%s, encrypted=%s, link=%s, payload=%s",
bool(flags & 0x10), link_encrypted, link_established, bool(flags & 0x80) device,
notification.address,
bool(flags & 0x10),
link_encrypted,
link_established,
bool(flags & 0x80),
) )
status[_K.LINK_ENCRYPTED] = link_encrypted device.link_encrypted = link_encrypted
status.changed(active=link_established) if not link_established and device.receiver:
hidpp10.set_configuration_pending_flags(device.receiver, 0xFF)
device.changed(active=link_established)
return True return True
if n.sub_id == 0x49: if notification.sub_id == Notification.RAW_INPUT:
# raw input event? just ignore it # raw input event? just ignore it
# if n.address == 0x01, no idea what it is, but they keep on coming # if notification.address == 0x01, no idea what it is, but they keep on coming
# if n.address == 0x03, appears to be an actual input event, # if notification.address == 0x03, appears to be an actual input event, because they only come when input happents
# because they only come when input happents
return True return True
# power notification if notification.sub_id == Notification.POWER:
if n.sub_id == 0x4B: if notification.address == 0x01:
if n.address == 0x01:
if logger.isEnabledFor(logging.DEBUG): if logger.isEnabledFor(logging.DEBUG):
logger.debug('%s: device powered on', device) logger.debug("%s: device powered on", device)
reason = status.to_string() or _('powered on') reason = device.status_string() or _("powered on")
status.changed(active=True, alert=_ALERT.NOTIFICATION, reason=reason) device.changed(active=True, alert=Alert.NOTIFICATION, reason=reason)
else: else:
logger.warning('%s: unknown %s', device, n) logger.warning("%s: unknown %s", device, notification)
return True return True
logger.warning('%s: unrecognized %s', device, n) logger.warning("%s: unrecognized %s", device, notification)
def _process_feature_notification(device, status, n, feature): def _process_feature_notification(device: Device, notification: HIDPPNotification):
old_present, device.present = device.present, True # the device is generating a feature notification so it must be present
try:
feature = device.features.get_feature(notification.sub_id)
except IndexError:
logger.warning("%s: notification from invalid feature index %02X: %s", device, notification.sub_id, notification)
return False
if logger.isEnabledFor(logging.DEBUG): if logger.isEnabledFor(logging.DEBUG):
logger.debug('%s: notification for feature %s, report %s, data %s', device, feature, n.address >> 4, _strhex(n.data)) logger.debug(
"%s: notification for feature %s, report %s, data %s",
device,
feature,
notification.address >> 4,
common.strhex(notification.data),
)
if feature == _F.BATTERY_STATUS: if feature == SupportedFeature.BATTERY_STATUS:
if n.address == 0x00: if notification.address == 0x00:
_ignore, discharge_level, discharge_next_level, battery_status, voltage = _hidpp20.decipher_battery_status(n.data) device.set_battery_info(hidpp20.decipher_battery_status(notification.data)[1])
status.set_battery_info(discharge_level, discharge_next_level, battery_status, voltage) elif notification.address == 0x10:
elif n.address == 0x10:
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
logger.info('%s: spurious BATTERY status %s', device, n) logger.info("%s: spurious BATTERY status %s", device, notification)
else: else:
logger.warning('%s: unknown BATTERY %s', device, n) logger.warning("%s: unknown BATTERY %s", device, notification)
elif feature == _F.BATTERY_VOLTAGE: elif feature == SupportedFeature.BATTERY_VOLTAGE:
if n.address == 0x00: if notification.address == 0x00:
_ignore, level, nextl, battery_status, voltage = _hidpp20.decipher_battery_voltage(n.data) device.set_battery_info(hidpp20.decipher_battery_voltage(notification.data)[1])
status.set_battery_info(level, nextl, battery_status, voltage)
else: else:
logger.warning('%s: unknown VOLTAGE %s', device, n) logger.warning("%s: unknown VOLTAGE %s", device, notification)
elif feature == _F.UNIFIED_BATTERY: elif feature == SupportedFeature.UNIFIED_BATTERY:
if n.address == 0x00: if notification.address == 0x00:
_ignore, level, nextl, battery_status, voltage = _hidpp20.decipher_battery_unified(n.data) device.set_battery_info(hidpp20.decipher_battery_unified(notification.data)[1])
status.set_battery_info(level, nextl, battery_status, voltage)
else: else:
logger.warning('%s: unknown UNIFIED BATTERY %s', device, n) logger.warning("%s: unknown UNIFIED BATTERY %s", device, notification)
elif feature == _F.ADC_MEASUREMENT: elif feature == SupportedFeature.ADC_MEASUREMENT:
if n.address == 0x00: if notification.address == 0x00:
result = _hidpp20.decipher_adc_measurement(n.data) result = hidpp20.decipher_adc_measurement(notification.data)
if result: if result: # if good data and the device was not present then a push is needed
_ignore, level, nextl, battery_status, voltage = result device.set_battery_info(result[1])
status.set_battery_info(level, nextl, battery_status, voltage) device.changed(active=True, alert=Alert.ALL, reason=_("ADC measurement notification"), push=not old_present)
else: # this feature is used to signal device becoming inactive else: # this feature is also used to signal device becoming inactive
status.changed(active=False) device.present = False # exception to device presence
device.changed(active=False)
else: else:
logger.warning('%s: unknown ADC MEASUREMENT %s', device, n) logger.warning("%s: unknown ADC MEASUREMENT %s", device, notification)
elif feature == _F.SOLAR_DASHBOARD: elif feature == SupportedFeature.SOLAR_DASHBOARD:
if n.data[5:9] == b'GOOD': if notification.data[5:9] == b"GOOD":
charge, lux, adc = _unpack('!BHH', n.data[:5]) charge, lux, adc = struct.unpack("!BHH", notification.data[:5])
# guesstimate the battery voltage, emphasis on 'guess' # guesstimate the battery voltage, emphasis on 'guess'
# status_text = '%1.2fV' % (adc * 2.67793237653 / 0x0672) # status_text = '%1.2fV' % (adc * 2.67793237653 / 0x0672)
status_text = _hidpp20.BATTERY_STATUS.discharging status_text = BatteryStatus.DISCHARGING
if n.address == 0x00: if notification.address == 0x00:
status[_K.LIGHT_LEVEL] = None device.set_battery_info(common.Battery(charge, None, status_text, None))
status.set_battery_info(charge, None, status_text, None) elif notification.address == 0x10:
elif n.address == 0x10:
status[_K.LIGHT_LEVEL] = lux
if lux > 200: if lux > 200:
status_text = _hidpp20.BATTERY_STATUS.recharging status_text = BatteryStatus.RECHARGING
status.set_battery_info(charge, None, status_text, None) device.set_battery_info(common.Battery(charge, None, status_text, None, lux))
elif n.address == 0x20: elif notification.address == 0x20:
if logger.isEnabledFor(logging.DEBUG): if logger.isEnabledFor(logging.DEBUG):
logger.debug('%s: Light Check button pressed', device) logger.debug("%s: Light Check button pressed", device)
status.changed(alert=_ALERT.SHOW_WINDOW) device.changed(alert=Alert.SHOW_WINDOW)
# first cancel any reporting # first cancel any reporting
# device.feature_request(_F.SOLAR_DASHBOARD) # device.feature_request(SupportedFeature.SOLAR_DASHBOARD)
# trigger a new report chain # trigger a new report chain
reports_count = 15 reports_count = 15
reports_period = 2 # seconds reports_period = 2 # seconds
device.feature_request(_F.SOLAR_DASHBOARD, 0x00, reports_count, reports_period) device.feature_request(SupportedFeature.SOLAR_DASHBOARD, 0x00, reports_count, reports_period)
else: else:
logger.warning('%s: unknown SOLAR CHARGE %s', device, n) logger.warning("%s: unknown SOLAR CHARGE %s", device, notification)
else: else:
logger.warning('%s: SOLAR CHARGE not GOOD? %s', device, n) logger.warning("%s: SOLAR CHARGE not GOOD? %s", device, notification)
elif feature == _F.WIRELESS_DEVICE_STATUS: elif feature == SupportedFeature.WIRELESS_DEVICE_STATUS:
if n.address == 0x00: if notification.address == 0x00:
if logger.isEnabledFor(logging.DEBUG): if logger.isEnabledFor(logging.DEBUG):
logger.debug('wireless status: %s', n) logger.debug("wireless status: %s", notification)
reason = 'powered on' if n.data[2] == 1 else None reason = "powered on" if notification.data[2] == 1 else None
if n.data[1] == 1: # device is asking for software reconfiguration so need to change status if notification.data[1] == 1: # device is asking for software reconfiguration so need to change status
alert = _ALERT.NONE alert = Alert.NONE
status.changed(active=True, alert=alert, reason=reason, push=True) device.changed(active=True, alert=alert, reason=reason, push=True)
else: else:
logger.warning('%s: unknown WIRELESS %s', device, n) logger.warning("%s: unknown WIRELESS %s", device, notification)
elif feature == _F.TOUCHMOUSE_RAW_POINTS: elif feature == SupportedFeature.TOUCHMOUSE_RAW_POINTS:
if n.address == 0x00: if notification.address == 0x00:
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
logger.info('%s: TOUCH MOUSE points %s', device, n) logger.info("%s: TOUCH MOUSE points %s", device, notification)
elif n.address == 0x10: elif notification.address == 0x10:
touch = ord(n.data[:1]) touch = ord(notification.data[:1])
button_down = bool(touch & 0x02) button_down = bool(touch & 0x02)
mouse_lifted = bool(touch & 0x01) mouse_lifted = bool(touch & 0x01)
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
logger.info('%s: TOUCH MOUSE status: button_down=%s mouse_lifted=%s', device, button_down, mouse_lifted) logger.info("%s: TOUCH MOUSE status: button_down=%s mouse_lifted=%s", device, button_down, mouse_lifted)
else: else:
logger.warning('%s: unknown TOUCH MOUSE %s', device, n) logger.warning("%s: unknown TOUCH MOUSE %s", device, notification)
# TODO: what are REPROG_CONTROLS_V{2,3}? # TODO: what are REPROG_CONTROLS_V{2,3}?
elif feature == _F.REPROG_CONTROLS: elif feature == SupportedFeature.REPROG_CONTROLS:
if n.address == 0x00: if notification.address == 0x00:
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
logger.info('%s: reprogrammable key: %s', device, n) logger.info("%s: reprogrammable key: %s", device, notification)
else: else:
logger.warning('%s: unknown REPROG_CONTROLS %s', device, n) logger.warning("%s: unknown REPROG_CONTROLS %s", device, notification)
elif feature == _F.BACKLIGHT2: elif feature == SupportedFeature.BACKLIGHT2:
if (n.address == 0x00): if notification.address == 0x00:
level = _unpack('!B', n.data[1:2])[0] level = struct.unpack("!B", notification.data[1:2])[0]
from solaar.ui.config_panel import record_setting # prevent circular import if device.setting_callback:
record_setting(device, _st.Backlight2Level, [level]) device.setting_callback(device, settings_templates.Backlight2Level, [level])
elif feature == _F.REPROG_CONTROLS_V4: elif feature == SupportedFeature.REPROG_CONTROLS_V4:
if n.address == 0x00: if notification.address == 0x00:
if logger.isEnabledFor(logging.DEBUG): if logger.isEnabledFor(logging.DEBUG):
cid1, cid2, cid3, cid4 = _unpack('!HHHH', n.data[:8]) cid1, cid2, cid3, cid4 = struct.unpack("!HHHH", notification.data[:8])
logger.debug('%s: diverted controls pressed: 0x%x, 0x%x, 0x%x, 0x%x', device, cid1, cid2, cid3, cid4) logger.debug("%s: diverted controls pressed: 0x%x, 0x%x, 0x%x, 0x%x", device, cid1, cid2, cid3, cid4)
elif n.address == 0x10: elif notification.address == 0x10:
if logger.isEnabledFor(logging.DEBUG): if logger.isEnabledFor(logging.DEBUG):
dx, dy = _unpack('!hh', n.data[:4]) dx, dy = struct.unpack("!hh", notification.data[:4])
logger.debug('%s: rawXY dx=%i dy=%i', device, dx, dy) logger.debug("%s: rawXY dx=%i dy=%i", device, dx, dy)
elif n.address == 0x20: elif notification.address == 0x20:
if logger.isEnabledFor(logging.DEBUG): if logger.isEnabledFor(logging.DEBUG):
logger.debug('%s: received analyticsKeyEvents', device) logger.debug("%s: received analyticsKeyEvents", device)
elif logger.isEnabledFor(logging.INFO): elif logger.isEnabledFor(logging.INFO):
logger.info('%s: unknown REPROG_CONTROLS_V4 %s', device, n) logger.info("%s: unknown REPROG_CONTROLS_V4 %s", device, notification)
elif feature == _F.HIRES_WHEEL: elif feature == SupportedFeature.HIRES_WHEEL:
if (n.address == 0x00): if notification.address == 0x00:
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
flags, delta_v = _unpack('>bh', n.data[:3]) flags, delta_v = struct.unpack(">bh", notification.data[:3])
high_res = (flags & 0x10) != 0 high_res = (flags & 0x10) != 0
periods = flags & 0x0f periods = flags & 0x0F
logger.info('%s: WHEEL: res: %d periods: %d delta V:%-3d', device, high_res, periods, delta_v) logger.info("%s: WHEEL: res: %d periods: %d delta V:%-3d", device, high_res, periods, delta_v)
elif (n.address == 0x10): elif notification.address == 0x10:
ratchet = n.data[0] ratchet = notification.data[0]
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
logger.info('%s: WHEEL: ratchet: %d', device, ratchet) logger.info("%s: WHEEL: ratchet: %d", device, ratchet)
if ratchet < 2: # don't process messages with unusual ratchet values if ratchet < 2: # don't process messages with unusual ratchet values
from solaar.ui.config_panel import record_setting # prevent circular import if device.setting_callback:
record_setting(device, _st.ScrollRatchet, [2 if ratchet else 1]) device.setting_callback(device, settings_templates.ScrollRatchet, [2 if ratchet else 1])
else: else:
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
logger.info('%s: unknown WHEEL %s', device, n) logger.info("%s: unknown WHEEL %s", device, notification)
elif feature == _F.ONBOARD_PROFILES: elif feature == SupportedFeature.ONBOARD_PROFILES:
if (n.address > 0x10): if notification.address > 0x10:
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
logger.info('%s: unknown ONBOARD PROFILES %s', device, n) logger.info("%s: unknown ONBOARD PROFILES %s", device, notification)
else: else:
if (n.address == 0x00): if notification.address == 0x00:
profile_sector = _unpack('!H', n.data[:2])[0] profile_sector = struct.unpack("!H", notification.data[:2])[0]
if profile_sector: if profile_sector:
profile_change(device, profile_sector) settings_templates.profile_change(device, profile_sector)
elif (n.address == 0x10): elif notification.address == 0x10:
resolution_index = _unpack('!B', n.data[:1])[0] resolution_index = struct.unpack("!B", notification.data[:1])[0]
profile_sector = _unpack('!H', device.feature_request(_F.ONBOARD_PROFILES, 0x40)[:2])[0] profile_sector = struct.unpack("!H", device.feature_request(SupportedFeature.ONBOARD_PROFILES, 0x40)[:2])[0]
if device.setting_callback:
for profile in device.profiles.profiles.values() if device.profiles else []: for profile in device.profiles.profiles.values() if device.profiles else []:
if profile.sector == profile_sector: if profile.sector == profile_sector:
from solaar.ui.config_panel import record_setting # prevent circular import device.setting_callback(
record_setting(device, _st.AdjustableDpi, [profile.resolutions[resolution_index]]) device, settings_templates.AdjustableDpi, [profile.resolutions[resolution_index]]
)
break
_diversion.process_notification(device, status, n, feature) elif feature == SupportedFeature.BRIGHTNESS_CONTROL:
if notification.address > 0x10:
if logger.isEnabledFor(logging.INFO):
logger.info("%s: unknown BRIGHTNESS CONTROL %s", device, notification)
else:
if notification.address == 0x00:
brightness = struct.unpack("!H", notification.data[:2])[0]
device.setting_callback(device, settings_templates.BrightnessControl, [brightness])
elif notification.address == 0x10:
brightness = notification.data[0] & 0x01
if brightness:
brightness = struct.unpack("!H", device.feature_request(SupportedFeature.BRIGHTNESS_CONTROL, 0x10)[:2])[0]
device.setting_callback(device, settings_templates.BrightnessControl, [brightness])
diversion.process_notification(device, notification, feature)
return True return True
# change UI to show result of onboard profile change def handle_pairing_lock(receiver: Receiver, notification: HIDPPNotification) -> bool:
def profile_change(device, profile_sector): receiver.pairing.lock_open = bool(notification.address & 0x01)
from solaar.ui.config_panel import record_setting # prevent circular import reason = _("pairing lock is open") if receiver.pairing.lock_open else _("pairing lock is closed")
record_setting(device, _st.OnboardProfiles, [profile_sector]) if logger.isEnabledFor(logging.INFO):
for profile in device.profiles.profiles.values() if device.profiles else []: logger.info("%s: %s", receiver, reason)
if profile.sector == profile_sector: receiver.pairing.error = None
resolution_index = profile.resolution_default_index if receiver.pairing.lock_open:
record_setting(device, _st.AdjustableDpi, [profile.resolutions[resolution_index]]) receiver.pairing.new_device = None
record_setting(device, _st.ReportRate, [profile.report_rate]) pair_error = ord(notification.data[:1])
break if pair_error:
receiver.pairing.error = error_string = hidpp10_constants.PairingError(pair_error).name
receiver.pairing.new_device = None
logger.warning("pairing error %d: %s", pair_error, error_string)
receiver.changed(reason=reason)
return True
def handle_discovery_status(receiver: Receiver, notification: HIDPPNotification) -> bool:
with notification_lock:
receiver.pairing.discovering = notification.address == 0x00
reason = _("discovery lock is open") if receiver.pairing.discovering else _("discovery lock is closed")
if logger.isEnabledFor(logging.INFO):
logger.info("%s: %s", receiver, reason)
receiver.pairing.error = None
if receiver.pairing.discovering:
receiver.pairing.counter = receiver.pairing.device_address = None
receiver.pairing.device_authentication = receiver.pairing.device_name = None
receiver.pairing.device_passkey = None
discover_error = ord(notification.data[:1])
if discover_error:
receiver.pairing.error = discover_string = hidpp10_constants.BoltPairingError(discover_error).name
logger.warning("bolt discovering error %d: %s", discover_error, discover_string)
receiver.changed(reason=reason)
return True
def handle_device_discovery(receiver: Receiver, notification: HIDPPNotification) -> bool:
with notification_lock:
counter = notification.address + notification.data[0] * 256 # notification counter
if receiver.pairing.counter is None:
receiver.pairing.counter = counter
else:
if not receiver.pairing.counter == counter:
return None
if notification.data[1] == 0:
receiver.pairing.device_kind = notification.data[3]
receiver.pairing.device_address = notification.data[6:12]
receiver.pairing.device_authentication = notification.data[14]
elif notification.data[1] == 1:
receiver.pairing.device_name = notification.data[3 : 3 + notification.data[2]].decode("utf-8")
return True
def handle_pairing_status(receiver: Receiver, notification: HIDPPNotification) -> bool:
with notification_lock:
receiver.pairing.device_passkey = None
receiver.pairing.lock_open = notification.address == 0x00
reason = _("pairing lock is open") if receiver.pairing.lock_open else _("pairing lock is closed")
if logger.isEnabledFor(logging.INFO):
logger.info("%s: %s", receiver, reason)
receiver.pairing.error = None
if not receiver.pairing.lock_open:
receiver.pairing.counter = None
receiver.pairing.device_address = None
receiver.pairing.device_authentication = None
receiver.pairing.device_name = None
pair_error = notification.data[0]
if receiver.pairing.lock_open:
receiver.pairing.new_device = None
elif notification.address == 0x02 and not pair_error:
receiver.pairing.new_device = receiver.register_new_device(notification.data[7])
if pair_error:
receiver.pairing.error = error_string = hidpp10_constants.BoltPairingError(pair_error).name
receiver.pairing.new_device = None
logger.warning("pairing error %d: %s", pair_error, error_string)
receiver.changed(reason=reason)
return True
def handle_passkey_request(receiver: Receiver, notification: HIDPPNotification) -> bool:
with notification_lock:
receiver.pairing.device_passkey = notification.data[0:6].decode("utf-8")
return True
def handle_passkey_pressed(_receiver: Receiver, _hidpp_notification: HIDPPNotification) -> bool:
return True

View File

@ -1,6 +1,5 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by ## it under the terms of the GNU General Public License as published by
@ -16,75 +15,174 @@
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import errno as _errno from __future__ import annotations
import errno
import logging import logging
import time
import typing
import hidapi as _hid from dataclasses import dataclass
from typing import Callable
from typing import Optional
from typing import Protocol
from . import base as _base from solaar.i18n import _
from . import hidpp10 as _hidpp10 from solaar.i18n import ngettext
from .base_usb import product_information as _product_information
from .common import strhex as _strhex from . import exceptions
from . import hidpp10
from . import hidpp10_constants
from .common import Alert
from .common import Notification
from .device import Device from .device import Device
from .hidpp10_constants import InfoSubRegisters
from .hidpp10_constants import NotificationFlag
from .hidpp10_constants import Registers
if typing.TYPE_CHECKING:
from logitech_receiver import common
from .base import HIDPPNotification
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
_R = _hidpp10.REGISTERS _hidpp10 = hidpp10.Hidpp10()
_IR = _hidpp10.INFO_SUBREGISTERS
#
# class LowLevelInterface(Protocol):
# def open_path(self, path):
...
def find_paired_node_wpid(self, receiver_path: str, index: int):
...
def ping(self, handle, number, long_message=False):
...
def request(self, handle, devnumber, request_id, *params, **kwargs):
...
def close(self, handle):
...
@dataclass
class Pairing:
"""Information about the current or most recent pairing"""
lock_open: bool = False
discovering: bool = False
counter: Optional[int] = None
device_address: Optional[bytes] = None
device_authentication: Optional[int] = None
device_kind: Optional[int] = None
device_name: Optional[str] = None
device_passkey: Optional[str] = None
new_device: Optional[Device] = None
error: Optional[any] = None
def extract_serial(response: bytes) -> str:
"""Extracts serial number from receiver response."""
return response.hex().upper()
def extract_max_devices(response: bytes) -> int:
"""Extracts maximum number of supported devices from response."""
max_devices = response[6]
return int(max_devices)
def extract_remaining_pairings(response: bytes) -> int:
ps = ord(response[2:3])
remaining_pairings = ps - 5 if ps >= 5 else -1
return int(remaining_pairings)
def extract_codename(response: bytes) -> str:
codename = response[2 : 2 + ord(response[1:2])]
return codename.decode("ascii")
def extract_power_switch_location(response: bytes) -> str:
"""Extracts power switch location from response."""
index = response[9] & 0x0F
return hidpp10_constants.PowerSwitchLocation.location(index).name.lower()
def extract_connection_count(response: bytes) -> int:
"""Extract connection count from receiver response."""
return ord(response[1:2])
def extract_wpid(response: bytes) -> str:
"""Extract wpid from receiver response."""
return response.hex().upper()
def extract_polling_rate(response: bytes) -> int:
"""Returns polling rate in milliseconds."""
return int(response[2])
def extract_device_kind(response: int) -> str:
return hidpp10_constants.DEVICE_KIND[response]
class Receiver: class Receiver:
"""A Unifying Receiver instance. """A generic Receiver instance, mostly implementing the interface used on Unifying, Nano, and LightSpeed receivers"
The paired devices are available through the sequence interface. The paired devices are available through the sequence interface.
""" """
read_register: Callable = hidpp10.read_register
write_register: Callable = hidpp10.write_register
number = 0xFF number = 0xFF
kind = None kind = None
def __init__(self, handle, path, product_id): def __init__(
self,
low_level: LowLevelInterface,
receiver_kind,
product_info,
handle,
path,
product_id,
setting_callback=None,
):
assert handle assert handle
self.low_level = low_level
self.isDevice = False # some devices act as receiver so we need a property to distinguish them self.isDevice = False # some devices act as receiver so we need a property to distinguish them
self.handle = handle self.handle = handle
self.path = path self.path = path
self.product_id = product_id self.product_id = product_id
product_info = _product_information(self.product_id) self.setting_callback = setting_callback # for changes to settings
if not product_info: self.status_callback = None # for changes to other potentially visible aspects
logger.warning('Unknown receiver type: %s', self.product_id) self.receiver_kind = receiver_kind
product_info = {}
self.receiver_kind = product_info.get('receiver_kind', 'unknown')
# read the serial immediately, so we can find out max_devices
if self.receiver_kind == 'bolt':
serial_reply = self.read_register(_R.bolt_uniqueId)
self.serial = _strhex(serial_reply)
self.max_devices = product_info.get('max_devices', 1)
self.may_unpair = product_info.get('may_unpair', False)
else:
serial_reply = self.read_register(_R.receiver_info, _IR.receiver_information)
if serial_reply:
self.serial = _strhex(serial_reply[1:5])
self.max_devices = ord(serial_reply[6:7])
if self.max_devices <= 0 or self.max_devices > 6:
self.max_devices = product_info.get('max_devices', 1)
self.may_unpair = product_info.get('may_unpair', False)
else: # handle receivers that don't have a serial number specially (i.e., c534 and Bolt receivers)
self.serial = None self.serial = None
self.max_devices = product_info.get('max_devices', 1) self.max_devices = None
self.may_unpair = product_info.get('may_unpair', False)
self.name = product_info.get('name', 'Receiver')
self.re_pairs = product_info.get('re_pairs', False)
self._str = '<%s(%s,%s%s)>' % (
self.name.replace(' ', ''), self.path, '' if isinstance(self.handle, int) else 'T', self.handle
)
self._firmware = None self._firmware = None
self._devices = {}
self._remaining_pairings = None self._remaining_pairings = None
self._devices = {}
self.name = product_info.get("name", "Receiver")
self.may_unpair = product_info.get("may_unpair", False)
self.re_pairs = product_info.get("re_pairs", False)
self.notification_flags = None
self.pairing = Pairing()
self.initialize(product_info)
hidpp10.set_configuration_pending_flags(self, 0xFF)
def initialize(self, product_info: dict):
# read the receiver information subregister, so we can find out max_devices
serial_reply = self.read_register(Registers.RECEIVER_INFO, InfoSubRegisters.RECEIVER_INFORMATION)
if serial_reply:
self.serial = extract_serial(serial_reply[1:5])
self.max_devices = extract_max_devices(serial_reply)
if not (1 <= self.max_devices <= 6):
self.max_devices = product_info.get("max_devices", 1)
else: # handle receivers that don't have a serial number specially (i.e., c534)
self.serial = None
self.max_devices = product_info.get("max_devices", 1)
def close(self): def close(self):
handle, self.handle = self.handle, None handle, self.handle = self.handle, None
@ -92,13 +190,18 @@ class Receiver:
if d: if d:
d.close() d.close()
self._devices.clear() self._devices.clear()
return (handle and _base.close(handle)) return handle and self.low_level.close(handle)
def __del__(self): def __del__(self):
self.close() self.close()
def changed(self, alert=Alert.NOTIFICATION, reason=None):
"""The status of the device had changed, so invoke the status callback"""
if self.status_callback is not None:
self.status_callback(self, alert=alert, reason=reason)
@property @property
def firmware(self): def firmware(self) -> tuple[common.FirmwareInfo]:
if self._firmware is None and self.handle: if self._firmware is None and self.handle:
self._firmware = _hidpp10.get_firmware(self) self._firmware = _hidpp10.get_firmware(self)
return self._firmware return self._firmware
@ -106,10 +209,9 @@ class Receiver:
# how many pairings remain (None for unknown, -1 for unlimited) # how many pairings remain (None for unknown, -1 for unlimited)
def remaining_pairings(self, cache=True): def remaining_pairings(self, cache=True):
if self._remaining_pairings is None or not cache: if self._remaining_pairings is None or not cache:
ps = self.read_register(_R.receiver_connection) ps = self.read_register(Registers.RECEIVER_CONNECTION)
if ps is not None: if ps is not None:
ps = ord(ps[2:3]) self._remaining_pairings = extract_remaining_pairings(ps)
self._remaining_pairings = ps - 5 if ps >= 5 else -1
return self._remaining_pairings return self._remaining_pairings
def enable_connection_notifications(self, enable=True): def enable_connection_notifications(self, enable=True):
@ -119,171 +221,128 @@ class Receiver:
return False return False
if enable: if enable:
set_flag_bits = ( set_flag_bits = NotificationFlag.WIRELESS | NotificationFlag.SOFTWARE_PRESENT
_hidpp10.NOTIFICATION_FLAG.battery_status
| _hidpp10.NOTIFICATION_FLAG.wireless
| _hidpp10.NOTIFICATION_FLAG.software_present
)
else: else:
set_flag_bits = 0 set_flag_bits = 0
ok = _hidpp10.set_notification_flags(self, set_flag_bits) ok = _hidpp10.set_notification_flags(self, set_flag_bits)
if ok is None: if ok is None:
logger.warning('%s: failed to %s receiver notifications', self, 'enable' if enable else 'disable') logger.warning("%s: failed to %s receiver notifications", self, "enable" if enable else "disable")
return None return None
flag_bits = _hidpp10.get_notification_flags(self) flag_bits = _hidpp10.get_notification_flags(self)
flag_names = None if flag_bits is None else tuple(_hidpp10.NOTIFICATION_FLAG.flag_names(flag_bits)) if flag_bits is None:
flag_names = None
else:
flag_names = hidpp10_constants.NotificationFlag.flag_names(flag_bits)
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
logger.info('%s: receiver notifications %s => %s', self, 'enabled' if enable else 'disabled', flag_names) logger.info("%s: receiver notifications %s => %s", self, "enabled" if enable else "disabled", flag_names)
return flag_bits return flag_bits
def device_codename(self, n): def device_codename(self, n):
if self.receiver_kind == 'bolt': codename = self.read_register(Registers.RECEIVER_INFO, InfoSubRegisters.DEVICE_NAME + n - 1)
codename = self.read_register(_R.receiver_info, _IR.bolt_device_name + n, 0x01)
if codename: if codename:
codename = codename[3:3 + min(14, ord(codename[2:3]))] return extract_codename(codename)
return codename.decode('ascii')
return
codename = self.read_register(_R.receiver_info, _IR.device_name + n - 1)
if codename:
codename = codename[2:2 + ord(codename[1:2])]
return codename.decode('ascii')
def device_pairing_information(self, n):
if self.receiver_kind == 'bolt':
pair_info = self.read_register(_R.receiver_info, _IR.bolt_pairing_information + n)
if pair_info:
wpid = _strhex(pair_info[3:4]) + _strhex(pair_info[2:3])
kind = _hidpp10.DEVICE_KIND[ord(pair_info[1:2]) & 0x0F]
return wpid, kind, 0
else:
raise _base.NoSuchDevice(number=n, receiver=self, error='read Bolt wpid')
wpid = 0
kind = None
polling_rate = None
pair_info = self.read_register(_R.receiver_info, _IR.pairing_information + n - 1)
if pair_info: # may be either a Unifying receiver, or an Unifying-ready receiver
wpid = _strhex(pair_info[3:5])
kind = _hidpp10.DEVICE_KIND[ord(pair_info[7:8]) & 0x0F]
polling_rate = str(ord(pair_info[2:3])) + 'ms'
elif self.receiver_kind == '27Mz': # 27Mhz receiver, fill extracting WPID from udev path
wpid = _hid.find_paired_node_wpid(self.path, n)
if not wpid:
logger.error('Unable to get wpid from udev for device %d of %s', n, self)
raise _base.NoSuchDevice(number=n, receiver=self, error='Not present 27Mhz device')
kind = _hidpp10.DEVICE_KIND[self.get_kind_from_index(n)]
elif not self.receiver_kind == 'unifying': # unifying protocol not supported, may be an old Nano receiver
device_info = self.read_register(_R.receiver_info, 0x04)
if device_info:
wpid = _strhex(device_info[3:5])
kind = _hidpp10.DEVICE_KIND[0x00] # unknown kind
else:
raise _base.NoSuchDevice(number=n, receiver=self, error='read pairing information - non-unifying')
else:
raise _base.NoSuchDevice(number=n, receiver=self, error='read pairing information')
return wpid, kind, polling_rate
def device_extended_pairing_information(self, n):
serial = None
power_switch = '(unknown)'
if self.receiver_kind == 'bolt':
pair_info = self.read_register(_R.receiver_info, _IR.bolt_pairing_information + n)
if pair_info:
serial = _strhex(pair_info[4:8])
return serial, power_switch
else:
return '?', power_switch
pair_info = self.read_register(_R.receiver_info, _IR.extended_pairing_information + n - 1)
if pair_info:
power_switch = _hidpp10.POWER_SWITCH_LOCATION[ord(pair_info[9:10]) & 0x0F]
else: # some Nano receivers?
pair_info = self.read_register(0x2D5)
if pair_info:
serial = _strhex(pair_info[1:5])
return serial, power_switch
def get_kind_from_index(self, index):
"""Get device kind from 27Mhz device index"""
# accordingly to drivers/hid/hid-logitech-dj.c
# index 1 or 2 always mouse, index 3 always the keyboard,
# index 4 is used for an optional separate numpad
if index == 1: # mouse
kind = 2
elif index == 2: # mouse
kind = 2
elif index == 3: # keyboard
kind = 1
elif index == 4: # numpad
kind = 3
else: # unknown device number on 27Mhz receiver
logger.error('failed to calculate device kind for device %d of %s', index, self)
raise _base.NoSuchDevice(number=index, receiver=self, error='Unknown 27Mhz device number')
return kind
def notify_devices(self): def notify_devices(self):
"""Scan all devices.""" """Scan all devices."""
if self.handle: if self.handle:
if not self.write_register(_R.receiver_connection, 0x02): if not self.write_register(Registers.RECEIVER_CONNECTION, 0x02):
logger.warning('%s: failed to trigger device link notifications', self) logger.warning("%s: failed to trigger device link notifications", self)
def notification_information(self, number, notification: HIDPPNotification) -> tuple[bool, bool, typing.Any, str]:
"""Extract information from unifying-style notification"""
assert notification.address != 0x02
online = not bool(notification.data[0] & 0x40)
encrypted = bool(notification.data[0] & 0x20) or notification.address == 0x10
kind = extract_device_kind(notification.data[0] & 0x0F)
wpid = extract_wpid(notification.data[2:3] + notification.data[1:2])
return online, encrypted, wpid, kind
def device_pairing_information(self, n: int) -> dict:
"""Return information from pairing registers (and elsewhere when necessary)"""
polling_rate = ""
serial = None
power_switch = "(unknown)"
pair_info = self.read_register(Registers.RECEIVER_INFO, InfoSubRegisters.PAIRING_INFORMATION + n - 1)
if pair_info: # a receiver that uses Unifying-style pairing registers
wpid = extract_wpid(pair_info[3:5])
kind = extract_device_kind(pair_info[7] & 0x0F)
polling_rate_ms = extract_polling_rate(pair_info)
polling_rate = f"{polling_rate_ms}ms"
elif not self.receiver_kind == "unifying": # may be an old Nano receiver
device_info = self.read_register(Registers.RECEIVER_INFO, 0x04) # undocumented
if device_info:
logger.warning("using undocumented register for device wpid")
wpid = extract_wpid(device_info[3:5])
kind = extract_device_kind(0x00) # unknown kind
else:
raise exceptions.NoSuchDevice(number=n, receiver=self, error="read pairing information - non-unifying")
else:
raise exceptions.NoSuchDevice(number=n, receiver=self, error="read pairing information")
pair_info = self.read_register(Registers.RECEIVER_INFO, InfoSubRegisters.EXTENDED_PAIRING_INFORMATION + n - 1)
if pair_info:
power_switch = extract_power_switch_location(pair_info)
serial = extract_serial(pair_info[1:5])
else: # some Nano receivers?
pair_info = self.read_register(0x2D5) # undocumented and questionable
if pair_info:
logger.warning("using undocumented register for device serial number")
serial = extract_serial(pair_info[1:5])
return {"wpid": wpid, "kind": kind, "polling": polling_rate, "serial": serial, "power_switch": power_switch}
def register_new_device(self, number, notification=None): def register_new_device(self, number, notification=None):
if self._devices.get(number) is not None: if self._devices.get(number) is not None:
raise IndexError('%s: device number %d already registered' % (self, number)) raise IndexError(f"{self}: device number {int(number)} already registered")
assert notification is None or notification.devnumber == number assert notification is None or notification.devnumber == number
assert notification is None or notification.sub_id == 0x41 assert notification is None or notification.sub_id == Notification.DJ_PAIRING
try: try:
dev = Device(self, number, notification) time.sleep(0.05) # let receiver settle
info = self.device_pairing_information(number)
if notification is not None:
online, _e, nwpid, nkind = self.notification_information(number, notification)
if info["wpid"] is None:
info["wpid"] = nwpid
elif nwpid is not None and info["wpid"] != nwpid:
logger.warning("mismatch on device WPID %s %s", info["wpid"], nwpid)
if info["kind"] is None:
info["kind"] = nkind
elif nkind is not None and info["kind"] != nkind:
logger.warning("mismatch on device kind %s %s", info["kind"], nkind)
else:
online = True
dev = Device(self.low_level, self, number, online, pairing_info=info, setting_callback=self.setting_callback)
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
logger.info('%s: found new device %d (%s)', self, number, dev.wpid) logger.info("%s: found new device %d (%s)", self, number, dev.wpid)
self._devices[number] = dev self._devices[number] = dev
return dev return dev
except _base.NoSuchDevice as e: except exceptions.NoSuchDevice as e:
logger.warning('register new device failed for %s device %d error %s', e.receiver, e.number, e.error) logger.warning("register new device failed for %s device %d error %s", e.receiver, e.number, e.error)
logger.warning('%s: looked for device %d, not found', self, number) logger.warning("%s: looked for device %d, not found", self, number)
self._devices[number] = None self._devices[number] = None
def set_lock(self, lock_closed=True, device=0, timeout=0): def set_lock(self, lock_closed=True, device=0, timeout=0):
if self.handle: if self.handle:
action = 0x02 if lock_closed else 0x01 action = 0x02 if lock_closed else 0x01
reply = self.write_register(_R.receiver_pairing, action, device, timeout) reply = self.write_register(Registers.RECEIVER_PAIRING, action, device, timeout)
if reply: if reply:
return True return True
logger.warning('%s: failed to %s the receiver lock', self, 'close' if lock_closed else 'open') logger.warning("%s: failed to %s the receiver lock", self, "close" if lock_closed else "open")
def discover(self, cancel=False, timeout=30): # Bolt device discovery
assert self.receiver_kind == 'bolt'
if self.handle:
action = 0x02 if cancel else 0x01
reply = self.write_register(_R.bolt_device_discovery, timeout, action)
if reply:
return True
logger.warning('%s: failed to %s device discovery', self, 'cancel' if cancel else 'start')
def pair_device(self, pair=True, slot=0, address=b'\0\0\0\0\0\0', authentication=0x00, entropy=20): # Bolt pairing
assert self.receiver_kind == 'bolt'
if self.handle:
action = 0x01 if pair is True else 0x03 if pair is False else 0x02
reply = self.write_register(_R.bolt_pairing, action, slot, address, authentication, entropy)
if reply:
return True
logger.warning('%s: failed to %s device %s', self, 'pair' if pair else 'unpair', address)
def count(self): def count(self):
count = self.read_register(_R.receiver_connection) count = self.read_register(Registers.RECEIVER_CONNECTION)
return 0 if count is None else ord(count[1:2]) if count is None:
return 0
# def has_devices(self): return extract_connection_count(count)
# return len(self) > 0 or self.count() > 0
def request(self, request_id, *params): def request(self, request_id, *params):
if bool(self): if bool(self):
return _base.request(self.handle, 0xFF, request_id, *params) return self.low_level.request(self.handle, 0xFF, request_id, *params)
read_register = _hidpp10.read_register def reset_pairing(self):
write_register = _hidpp10.write_register self.pairing = Pairing()
def __iter__(self): def __iter__(self):
connected_devices = self.count() connected_devices = self.count()
@ -308,7 +367,7 @@ class Receiver:
return dev return dev
if not isinstance(key, int): if not isinstance(key, int):
raise TypeError('key must be an integer') raise TypeError("key must be an integer")
if key < 1 or key > 15: # some receivers have devices past their max # devices if key < 1 or key > 15: # some receivers have devices past their max # devices
raise IndexError(key) raise IndexError(key)
@ -335,12 +394,9 @@ class Receiver:
dev.wpid = None dev.wpid = None
if key in self._devices: if key in self._devices:
del self._devices[key] del self._devices[key]
logger.warning('%s removed device %s', self, dev) logger.warning("%s removed device %s", self, dev)
else: else:
if self.receiver_kind == 'bolt': reply = self._unpair_device_per_receiver(key)
reply = self.write_register(_R.bolt_pairing, 0x03, key)
else:
reply = self.write_register(_R.receiver_pairing, 0x03, key)
if reply: if reply:
# invalidate the device # invalidate the device
dev.online = False dev.online = False
@ -348,10 +404,14 @@ class Receiver:
if key in self._devices: if key in self._devices:
del self._devices[key] del self._devices[key]
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
logger.info('%s unpaired device %s', self, dev) logger.info("%s unpaired device %s", self, dev)
else: else:
logger.error('%s failed to unpair device %s', self, dev) logger.error("%s failed to unpair device %s", self, dev)
raise Exception('failed to unpair device %s: %s' % (dev.name, key)) raise Exception(f"failed to unpair device {dev.name}: {key}")
def _unpair_device_per_receiver(self, key):
"""Receiver specific unpairing."""
return self.write_register(Registers.RECEIVER_PAIRING, 0x03, key)
def __len__(self): def __len__(self):
return len([d for d in self._devices.values() if d is not None]) return len([d for d in self._devices.values() if d is not None])
@ -371,26 +431,174 @@ class Receiver:
def __hash__(self): def __hash__(self):
return self.path.__hash__() return self.path.__hash__()
def status_string(self):
count = len(self)
return (
_("No paired devices.")
if count == 0
else ngettext("%(count)s paired device.", "%(count)s paired devices.", count) % {"count": count}
)
def __str__(self): def __str__(self):
return self._str return "<%s(%s,%s%s)>" % (
self.name.replace(" ", ""),
self.path,
"" if isinstance(self.handle, int) else "T",
self.handle,
)
__repr__ = __str__ __repr__ = __str__
__bool__ = __nonzero__ = lambda self: self.handle is not None __bool__ = __nonzero__ = lambda self: self.handle is not None
@classmethod
def open(self, device_info):
"""Opens a Logitech Receiver found attached to the machine, by Linux device path.
:returns: An open file handle for the found receiver, or ``None``. class BoltReceiver(Receiver):
""" """Bolt receivers use a different pairing prototol and have different pairing registers"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def initialize(self, product_info: dict):
serial_reply = self.read_register(Registers.BOLT_UNIQUE_ID)
self.serial = extract_serial(serial_reply)
self.max_devices = product_info.get("max_devices", 1)
def device_codename(self, n):
codename = self.read_register(Registers.RECEIVER_INFO, InfoSubRegisters.BOLT_DEVICE_NAME + n, 0x01)
if codename:
codename = codename[3 : 3 + min(14, ord(codename[2:3]))]
return codename.decode("ascii")
def device_pairing_information(self, n: int) -> dict:
pair_info = self.read_register(Registers.RECEIVER_INFO, InfoSubRegisters.BOLT_PAIRING_INFORMATION + n)
if pair_info:
wpid = extract_wpid(pair_info[3:4] + pair_info[2:3])
kind = extract_device_kind(pair_info[1] & 0x0F)
serial = extract_serial(pair_info[4:8])
return {"wpid": wpid, "kind": kind, "polling": None, "serial": serial, "power_switch": "(unknown)"}
else:
raise exceptions.NoSuchDevice(number=n, receiver=self, error="can't read Bolt pairing register")
def discover(self, cancel=False, timeout=30):
"""Discover Logitech Bolt devices."""
if self.handle:
action = 0x02 if cancel else 0x01
reply = self.write_register(Registers.BOLT_DEVICE_DISCOVERY, timeout, action)
if reply:
return True
logger.warning("%s: failed to %s device discovery", self, "cancel" if cancel else "start")
def pair_device(self, pair=True, slot=0, address=b"\0\0\0\0\0\0", authentication=0x00, entropy=20):
"""Pair a Bolt device."""
if self.handle:
action = 0x01 if pair is True else 0x03 if pair is False else 0x02
reply = self.write_register(Registers.BOLT_PAIRING, action, slot, address, authentication, entropy)
if reply:
return True
logger.warning("%s: failed to %s device %s", self, "pair" if pair else "unpair", address)
def _unpair_device_per_receiver(self, key):
"""Receiver specific unpairing."""
return self.write_register(Registers.BOLT_PAIRING, 0x03, key)
class UnifyingReceiver(Receiver):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class NanoReceiver(Receiver):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class LightSpeedReceiver(Receiver):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class Ex100Receiver(Receiver):
"""A very old style receiver, somewhat different from newer receivers"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def initialize(self, product_info: dict):
self.serial = None
self.max_devices = product_info.get("max_devices", 1)
def notification_information(self, number, notification):
"""Extract information from 27Mz-style notification and device index"""
assert notification.address == 0x02
online = True
encrypted = bool(notification.data[0] & 0x80)
kind = extract_device_kind(_get_kind_from_index(self, number))
wpid = "00" + extract_wpid(notification.data[2:3])
return online, encrypted, wpid, kind
def device_pairing_information(self, number: int) -> dict:
# extract WPID from udev path
wpid = self.low_level.find_paired_node_wpid(self.path, number)
if not wpid:
logger.error("Unable to get wpid from udev for device %d of %s", number, self)
raise exceptions.NoSuchDevice(number=number, receiver=self, error="Not present 27Mhz device")
kind = extract_device_kind(_get_kind_from_index(self, number))
return {"wpid": wpid, "kind": kind, "polling": "", "serial": None, "power_switch": "(unknown)"}
def _get_kind_from_index(receiver, index: int) -> int:
"""Get device kind from 27Mhz device index"""
# From drivers/hid/hid-logitech-dj.c
if index == 1: # mouse
kind = 2
elif index == 2: # mouse
kind = 2
elif index == 3: # keyboard
kind = 1
elif index == 4: # numpad
kind = 3
else: # unknown device number on 27Mhz receiver
logger.error("failed to calculate device kind for device %d of %s", index, receiver)
raise exceptions.NoSuchDevice(number=index, receiver=receiver, error="Unknown 27Mhz device number")
return kind
receiver_class_mapping = {
"bolt": BoltReceiver,
"unifying": UnifyingReceiver,
"lightspeed": LightSpeedReceiver,
"nano": NanoReceiver,
"27Mhz": Ex100Receiver,
}
def create_receiver(low_level: LowLevelInterface, device_info, setting_callback=None) -> Optional[Receiver]:
"""Opens a Logitech Receiver found attached to the machine, by Linux device path."""
try: try:
handle = _base.open_path(device_info.path) handle = low_level.open_path(device_info.path)
if handle: if handle:
return Receiver(handle, device_info.path, device_info.product_id) usb_id = device_info.product_id
if isinstance(usb_id, str):
usb_id = int(usb_id, 16)
try:
product_info = low_level.product_information(usb_id)
except ValueError:
product_info = {}
kind = product_info.get("receiver_kind", "unknown")
rclass = receiver_class_mapping.get(kind, Receiver)
return rclass(
low_level,
kind,
product_info,
handle,
device_info.path,
device_info.product_id,
setting_callback,
)
except OSError as e: except OSError as e:
logger.exception('open %s', device_info) logger.exception("open %s", device_info)
if e.errno == _errno.EACCES: if e.errno == errno.EACCES:
raise raise e
except Exception: except Exception:
logger.exception('open %s', device_info) logger.exception("open %s", device_info)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,744 @@
from __future__ import annotations
import logging
import math
from enum import IntEnum
from logitech_receiver import common
from logitech_receiver.common import NamedInt
from logitech_receiver.common import NamedInts
logger = logging.getLogger(__name__)
def bool_or_toggle(current: bool | str, new: bool | str) -> bool:
if isinstance(new, bool):
return new
try:
return bool(int(new))
except (TypeError, ValueError):
new = str(new).lower()
if new in ("true", "yes", "on", "t", "y"):
return True
if new in ("false", "no", "off", "f", "n"):
return False
if new in ("~", "toggle"):
return not current
return None
class Kind(IntEnum):
TOGGLE = 0x01
CHOICE = 0x02
RANGE = 0x04
MAP_CHOICE = 0x0A
MULTIPLE_TOGGLE = 0x10
PACKED_RANGE = 0x20
MULTIPLE_RANGE = 0x40
HETERO = 0x80
class Validator:
@classmethod
def build(cls, setting_class, device, **kwargs) -> Validator:
return cls(**kwargs)
@classmethod
def to_string(cls, value) -> str:
return str(value)
def compare(self, args, current):
if len(args) != 1:
return False
return args[0] == current
class BooleanValidator(Validator):
__slots__ = ("true_value", "false_value", "read_skip_byte_count", "write_prefix_bytes", "mask", "needs_current_value")
kind = Kind.TOGGLE
default_true = 0x01
default_false = 0x00
# mask specifies all the affected bits in the value
default_mask = 0xFF
def __init__(
self,
true_value=default_true,
false_value=default_false,
mask=default_mask,
read_skip_byte_count=0,
write_prefix_bytes=b"",
):
if isinstance(true_value, int):
assert isinstance(false_value, int)
if mask is None:
mask = self.default_mask
else:
assert isinstance(mask, int)
assert true_value & false_value == 0
assert true_value & mask == true_value
assert false_value & mask == false_value
self.needs_current_value = mask != self.default_mask
elif isinstance(true_value, bytes):
if false_value is None or false_value == self.default_false:
false_value = b"\x00" * len(true_value)
else:
assert isinstance(false_value, bytes)
if mask is None or mask == self.default_mask:
mask = b"\xff" * len(true_value)
else:
assert isinstance(mask, bytes)
assert len(mask) == len(true_value) == len(false_value)
tv = common.bytes2int(true_value)
fv = common.bytes2int(false_value)
mv = common.bytes2int(mask)
assert tv != fv # true and false might be something other than bit values
assert tv & mv == tv
assert fv & mv == fv
self.needs_current_value = any(m != 0xFF for m in mask)
else:
raise Exception(f"invalid mask '{mask!r}', type {type(mask)}")
self.true_value = true_value
self.false_value = false_value
self.mask = mask
self.read_skip_byte_count = read_skip_byte_count
self.write_prefix_bytes = write_prefix_bytes
def validate_read(self, reply_bytes):
reply_bytes = reply_bytes[self.read_skip_byte_count :]
if isinstance(self.mask, int):
reply_value = ord(reply_bytes[:1]) & self.mask
if logger.isEnabledFor(logging.DEBUG):
logger.debug("BooleanValidator: validate read %r => %02X", reply_bytes, reply_value)
if reply_value == self.true_value:
return True
if reply_value == self.false_value:
return False
logger.warning(
"BooleanValidator: reply %02X mismatched %02X/%02X/%02X",
reply_value,
self.true_value,
self.false_value,
self.mask,
)
return False
count = len(self.mask)
mask = common.bytes2int(self.mask)
reply_value = common.bytes2int(reply_bytes[:count]) & mask
true_value = common.bytes2int(self.true_value)
if reply_value == true_value:
return True
false_value = common.bytes2int(self.false_value)
if reply_value == false_value:
return False
logger.warning(
"BooleanValidator: reply %r mismatched %r/%r/%r", reply_bytes, self.true_value, self.false_value, self.mask
)
return False
def prepare_write(self, new_value, current_value=None):
if new_value is None:
new_value = False
else:
assert isinstance(new_value, bool), f"New value {new_value} for boolean setting is not a boolean"
to_write = self.true_value if new_value else self.false_value
if isinstance(self.mask, int):
if current_value is not None and self.needs_current_value:
to_write |= ord(current_value[:1]) & (0xFF ^ self.mask)
if current_value is not None and to_write == ord(current_value[:1]):
return None
to_write = bytes([to_write])
else:
to_write = bytearray(to_write)
count = len(self.mask)
for i in range(0, count):
b = ord(to_write[i : i + 1])
m = ord(self.mask[i : i + 1])
assert b & m == b
# b &= m
if current_value is not None and self.needs_current_value:
b |= ord(current_value[i : i + 1]) & (0xFF ^ m)
to_write[i] = b
to_write = bytes(to_write)
if current_value is not None and to_write == current_value[: len(to_write)]:
return None
if logger.isEnabledFor(logging.DEBUG):
logger.debug("BooleanValidator: prepare_write(%s, %s) => %r", new_value, current_value, to_write)
return self.write_prefix_bytes + to_write
def acceptable(self, args, current):
if len(args) != 1:
return None
val = bool_or_toggle(current, args[0])
return [val] if val is not None else None
class BitFieldValidator(Validator):
__slots__ = ("byte_count", "options")
kind = Kind.MULTIPLE_TOGGLE
def __init__(self, options, byte_count=None):
assert isinstance(options, list)
self.options = options
self.byte_count = (max(x.bit_length() for x in options) + 7) // 8
if byte_count:
assert isinstance(byte_count, int) and byte_count >= self.byte_count
self.byte_count = byte_count
def to_string(self, value) -> str:
def element_to_string(key, val):
k = next((k for k in self.options if int(key) == k), None)
return str(k) + ":" + str(val) if k is not None else "?"
return "{" + ", ".join([element_to_string(k, value[k]) for k in value]) + "}"
def validate_read(self, reply_bytes):
r = common.bytes2int(reply_bytes[: self.byte_count])
value = {int(k): False for k in self.options}
m = 1
for _ignore in range(8 * self.byte_count):
if m in self.options:
value[int(m)] = bool(r & m)
m <<= 1
return value
def prepare_write(self, new_value):
assert isinstance(new_value, dict)
w = 0
for k, v in new_value.items():
if v:
w |= int(k)
return common.int2bytes(w, self.byte_count)
def get_options(self):
return self.options
def acceptable(self, args, current):
if len(args) != 2:
return None
key = next((key for key in self.options if key == args[0]), None)
if key is None:
return None
val = bool_or_toggle(current[int(key)], args[1])
return None if val is None else [int(key), val]
def compare(self, args, current):
if len(args) != 2:
return False
key = next((key for key in self.options if key == args[0]), None)
if key is None:
return False
return args[1] == current[int(key)]
class BitFieldWithOffsetAndMaskValidator(Validator):
__slots__ = ("byte_count", "options", "_option_from_key", "_mask_from_offset", "_option_from_offset_mask")
kind = Kind.MULTIPLE_TOGGLE
sep = 0x01
def __init__(self, options, om_method=None, byte_count=None):
assert isinstance(options, list)
# each element of options is an instance of a class
# that has an id (which is used as an index in other dictionaries)
# and where om_method is a method that returns a byte offset and byte mask
# that says how to access and modify the bit toggle for the option
self.options = options
self.om_method = om_method
# to retrieve the options efficiently:
self._option_from_key = {}
self._mask_from_offset = {}
self._option_from_offset_mask = {}
for opt in options:
offset, mask = om_method(opt)
self._option_from_key[int(opt)] = opt
try:
self._mask_from_offset[offset] |= mask
except KeyError:
self._mask_from_offset[offset] = mask
try:
mask_to_opt = self._option_from_offset_mask[offset]
except KeyError:
mask_to_opt = {}
self._option_from_offset_mask[offset] = mask_to_opt
mask_to_opt[mask] = opt
self.byte_count = (max(om_method(x)[1].bit_length() for x in options) + 7) // 8 # is this correct??
if byte_count:
assert isinstance(byte_count, int) and byte_count >= self.byte_count
self.byte_count = byte_count
def prepare_read(self):
r = []
for offset, mask in self._mask_from_offset.items():
b = offset << (8 * (self.byte_count + 1))
b |= (self.sep << (8 * self.byte_count)) | mask
r.append(common.int2bytes(b, self.byte_count + 2))
return r
def prepare_read_key(self, key):
option = self._option_from_key.get(key, None)
if option is None:
return None
offset, mask = option.om_method(option)
b = offset << (8 * (self.byte_count + 1))
b |= (self.sep << (8 * self.byte_count)) | mask
return common.int2bytes(b, self.byte_count + 2)
def validate_read(self, reply_bytes_dict):
values = {int(k): False for k in self.options}
for query, b in reply_bytes_dict.items():
offset = common.bytes2int(query[0:1])
b += (self.byte_count - len(b)) * b"\x00"
value = common.bytes2int(b[: self.byte_count])
mask_to_opt = self._option_from_offset_mask.get(offset, {})
m = 1
for _ignore in range(8 * self.byte_count):
if m in mask_to_opt:
values[int(mask_to_opt[m])] = bool(value & m)
m <<= 1
return values
def prepare_write(self, new_value):
assert isinstance(new_value, dict)
w = {}
for k, v in new_value.items():
option = self._option_from_key[int(k)]
offset, mask = self.om_method(option)
if offset not in w:
w[offset] = 0
if v:
w[offset] |= mask
return [
common.int2bytes(
(offset << (8 * (2 * self.byte_count + 1)))
| (self.sep << (16 * self.byte_count))
| (self._mask_from_offset[offset] << (8 * self.byte_count))
| value,
2 * self.byte_count + 2,
)
for offset, value in w.items()
]
def get_options(self):
return [int(opt) if isinstance(opt, int) else opt.as_int() for opt in self.options]
def acceptable(self, args, current):
if len(args) != 2:
return None
key = next((option.id for option in self.options if option.as_int() == args[0]), None)
if key is None:
return None
val = bool_or_toggle(current[int(key)], args[1])
return None if val is None else [int(key), val]
def compare(self, args, current):
if len(args) != 2:
return False
key = next((option.id for option in self.options if option.as_int() == args[0]), None)
if key is None:
return False
return args[1] == current[int(key)]
class ChoicesValidator(Validator):
"""Translates between NamedInts and a byte sequence.
:param choices: a list of NamedInts
:param byte_count: the size of the derived byte sequence. If None, it
will be calculated from the choices."""
kind = Kind.CHOICE
def __init__(self, choices=None, byte_count=None, read_skip_byte_count=0, write_prefix_bytes=b""):
assert choices is not None
assert isinstance(choices, NamedInts)
assert len(choices) > 1
self.choices = choices
self.needs_current_value = False
max_bits = max(x.bit_length() for x in choices)
self._byte_count = (max_bits // 8) + (1 if max_bits % 8 else 0)
if byte_count:
assert self._byte_count <= byte_count
self._byte_count = byte_count
assert self._byte_count < 8
self._read_skip_byte_count = read_skip_byte_count
self._write_prefix_bytes = write_prefix_bytes if write_prefix_bytes else b""
assert self._byte_count + self._read_skip_byte_count <= 14
assert self._byte_count + len(self._write_prefix_bytes) <= 14
def to_string(self, value) -> str:
return str(self.choices[value]) if isinstance(value, int) else str(value)
def validate_read(self, reply_bytes):
reply_value = common.bytes2int(reply_bytes[self._read_skip_byte_count : self._read_skip_byte_count + self._byte_count])
valid_value = self.choices[reply_value]
assert valid_value is not None, f"{self.__class__.__name__}: failed to validate read value {reply_value:02X}"
return valid_value
def prepare_write(self, new_value, current_value=None):
if new_value is None:
value = self.choices[:][0]
else:
value = self.choice(new_value)
if value is None:
raise ValueError(f"invalid choice {new_value!r}")
assert isinstance(value, NamedInt)
return self._write_prefix_bytes + value.bytes(self._byte_count)
def choice(self, value):
if isinstance(value, int):
return self.choices[value]
try:
int(value)
if int(value) in self.choices:
return self.choices[int(value)]
except Exception:
pass
if value in self.choices:
return self.choices[value]
else:
return None
def acceptable(self, args, current):
choice = self.choice(args[0]) if len(args) == 1 else None
return None if choice is None else [choice]
class ChoicesMapValidator(ChoicesValidator):
kind = Kind.MAP_CHOICE
def __init__(
self,
choices_map,
key_byte_count=0,
key_postfix_bytes=b"",
byte_count=0,
read_skip_byte_count=0,
write_prefix_bytes=b"",
extra_default=None,
mask=-1,
activate=0,
):
assert choices_map is not None
assert isinstance(choices_map, dict)
max_key_bits = 0
max_value_bits = 0
for key, choices in choices_map.items():
assert isinstance(key, NamedInt)
assert isinstance(choices, NamedInts)
max_key_bits = max(max_key_bits, key.bit_length())
for key_value in choices:
assert isinstance(key_value, NamedInt)
max_value_bits = max(max_value_bits, key_value.bit_length())
self._key_byte_count = (max_key_bits + 7) // 8
if key_byte_count:
assert self._key_byte_count <= key_byte_count
self._key_byte_count = key_byte_count
self._byte_count = (max_value_bits + 7) // 8
if byte_count:
assert self._byte_count <= byte_count
self._byte_count = byte_count
self.choices = choices_map
self.needs_current_value = False
self.extra_default = extra_default
self._key_postfix_bytes = key_postfix_bytes
self._read_skip_byte_count = read_skip_byte_count if read_skip_byte_count else 0
self._write_prefix_bytes = write_prefix_bytes if write_prefix_bytes else b""
self.activate = activate
self.mask = mask
assert self._byte_count + self._read_skip_byte_count + self._key_byte_count <= 14
assert self._byte_count + len(self._write_prefix_bytes) + self._key_byte_count <= 14
def to_string(self, value) -> str:
def element_to_string(key, val):
k, c = next(((k, c) for k, c in self.choices.items() if int(key) == k), (None, None))
return str(k) + ":" + str(c[val]) if k is not None else "?"
return "{" + ", ".join([element_to_string(k, value[k]) for k in sorted(value)]) + "}"
def validate_read(self, reply_bytes, key):
start = self._key_byte_count + self._read_skip_byte_count
end = start + self._byte_count
reply_value = common.bytes2int(reply_bytes[start:end]) & self.mask
# reprogrammable keys starts out as 0, which is not a choice, so don't use assert here
if self.extra_default is not None and self.extra_default == reply_value:
return int(self.choices[key][0])
if reply_value not in self.choices[key]:
assert reply_value in self.choices[key], "%s: failed to validate read value %02X" % (
self.__class__.__name__,
reply_value,
)
return reply_value
def prepare_key(self, key):
return key.to_bytes(self._key_byte_count, "big") + self._key_postfix_bytes
def prepare_write(self, key, new_value):
choices = self.choices.get(key)
if choices is None or (new_value not in choices and new_value != self.extra_default):
logger.error("invalid choice %r for %s", new_value, key)
return None
new_value = new_value | self.activate
return self._write_prefix_bytes + new_value.to_bytes(self._byte_count, "big")
def acceptable(self, args, current):
if len(args) != 2:
return None
key, choices = next(((key, item) for key, item in self.choices.items() if key == args[0]), (None, None))
if choices is None or args[1] not in choices:
return None
choice = next((item for item in choices if item == args[1]), None)
return [int(key), int(choice)] if choice is not None else None
def compare(self, args, current):
if len(args) != 2:
return False
key = next((key for key in self.choices if key == int(args[0])), None)
if key is None:
return False
return args[1] == current[int(key)]
class RangeValidator(Validator):
kind = Kind.RANGE
"""Translates between integers and a byte sequence.
:param min_value: minimum accepted value (inclusive)
:param max_value: maximum accepted value (inclusive)
:param byte_count: the size of the derived byte sequence. If None, it
will be calculated from the range."""
min_value = 0
max_value = 255
@classmethod
def build(cls, setting_class, device, **kwargs):
kwargs["min_value"] = setting_class.min_value
kwargs["max_value"] = setting_class.max_value
return cls(**kwargs)
def __init__(self, min_value=0, max_value=255, byte_count=1):
assert max_value > min_value
self.min_value = min_value
self.max_value = max_value
self.needs_current_value = True # read and check before write (needed for ADC power and probably a good idea anyway)
self._byte_count = math.ceil(math.log(max_value + 1, 256))
if byte_count:
assert self._byte_count <= byte_count
self._byte_count = byte_count
assert self._byte_count < 8
def validate_read(self, reply_bytes):
reply_value = common.bytes2int(reply_bytes[: self._byte_count])
assert reply_value >= self.min_value, f"{self.__class__.__name__}: failed to validate read value {reply_value:02X}"
assert reply_value <= self.max_value, f"{self.__class__.__name__}: failed to validate read value {reply_value:02X}"
return reply_value
def prepare_write(self, new_value, current_value=None):
if new_value < self.min_value or new_value > self.max_value:
raise ValueError(f"invalid choice {new_value!r}")
current_value = self.validate_read(current_value) if current_value is not None else None
to_write = common.int2bytes(new_value, self._byte_count)
# current value is known and same as value to be written return None to signal not to write it
return None if current_value is not None and current_value == new_value else to_write
def acceptable(self, args, current):
arg = args[0]
# None if len(args) != 1 or type(arg) != int or arg < self.min_value or arg > self.max_value else args)
return None if len(args) != 1 or isinstance(arg, int) or arg < self.min_value or arg > self.max_value else args
def compare(self, args, current):
if len(args) == 1:
return args[0] == current
elif len(args) == 2:
return args[0] <= current <= args[1]
else:
return False
class HeteroValidator(Validator):
kind = Kind.HETERO
@classmethod
def build(cls, setting_class, device, **kwargs):
return cls(**kwargs)
def __init__(self, data_class=None, options=None, readable=True):
assert data_class is not None and options is not None
self.data_class = data_class
self.options = options
self.readable = readable
self.needs_current_value = False
def validate_read(self, reply_bytes):
if self.readable:
reply_value = self.data_class.from_bytes(reply_bytes, options=self.options)
return reply_value
def prepare_write(self, new_value, current_value=None):
to_write = new_value.to_bytes(options=self.options)
return to_write
def acceptable(self, args, current): # should this actually do some checking?
return True
class PackedRangeValidator(Validator):
kind = Kind.PACKED_RANGE
"""Several range values, all the same size, all the same min and max"""
min_value = 0
max_value = 255
count = 1
rsbc = 0
write_prefix_bytes = b""
def __init__(
self, keys, min_value=0, max_value=255, count=1, byte_count=1, read_skip_byte_count=0, write_prefix_bytes=b""
):
assert max_value > min_value
self.needs_current_value = True
self.keys = keys
self.min_value = min_value
self.max_value = max_value
self.count = count
self.bc = math.ceil(math.log(max_value + 1 - min(0, min_value), 256))
if byte_count:
assert self.bc <= byte_count
self.bc = byte_count
assert self.bc * self.count
self.rsbc = read_skip_byte_count
self.write_prefix_bytes = write_prefix_bytes
def validate_read(self, reply_bytes):
rvs = {
n: common.bytes2int(reply_bytes[self.rsbc + n * self.bc : self.rsbc + (n + 1) * self.bc], signed=True)
for n in range(self.count)
}
for n in range(self.count):
assert rvs[n] >= self.min_value, f"{self.__class__.__name__}: failed to validate read value {rvs[n]:02X}"
assert rvs[n] <= self.max_value, f"{self.__class__.__name__}: failed to validate read value {rvs[n]:02X}"
return rvs
def prepare_write(self, new_values):
if len(new_values) != self.count:
raise ValueError(f"wrong number of values {new_values!r}")
for new_value in new_values.values():
if new_value < self.min_value or new_value > self.max_value:
raise ValueError(f"invalid value {new_value!r}")
bytes = self.write_prefix_bytes + b"".join(
common.int2bytes(new_values[n], self.bc, signed=True) for n in range(self.count)
)
return bytes
def acceptable(self, args, current):
if len(args) != 2 or int(args[0]) < 0 or int(args[0]) >= self.count:
return None
return None if not isinstance(args[1], int) or args[1] < self.min_value or args[1] > self.max_value else args
def compare(self, args, current):
logger.warning("compare not implemented for packed range settings")
return False
class MultipleRangeValidator(Validator):
kind = Kind.MULTIPLE_RANGE
def __init__(self, items, sub_items):
assert isinstance(items, list) # each element must have .index and its __int__ must return its id (not its index)
assert isinstance(sub_items, dict)
# sub_items: items -> class with .minimum, .maximum, .length (in bytes), .id (a string) and .widget (e.g. 'Scale')
self.items = items
self.keys = NamedInts(**{str(item): int(item) for item in items})
self._item_from_id = {int(k): k for k in items}
self.sub_items = sub_items
def prepare_read_item(self, item):
return common.int2bytes((self._item_from_id[int(item)].index << 1) | 0xFF, 2)
def validate_read_item(self, reply_bytes, item):
item = self._item_from_id[int(item)]
start = 0
value = {}
for sub_item in self.sub_items[item]:
r = reply_bytes[start : start + sub_item.length]
if len(r) < sub_item.length:
r += b"\x00" * (sub_item.length - len(value))
v = common.bytes2int(r)
if not (sub_item.minimum < v < sub_item.maximum):
logger.warning(
f"{self.__class__.__name__}: failed to validate read value for {item}.{sub_item}: "
+ f"{v} not in [{sub_item.minimum}..{sub_item.maximum}]"
)
value[str(sub_item)] = v
start += sub_item.length
return value
def prepare_write(self, value):
seq = []
w = b""
for item in value.keys():
_item = self._item_from_id[int(item)]
b = common.int2bytes(_item.index, 1)
for sub_item in self.sub_items[_item]:
try:
v = value[int(item)][str(sub_item)]
except KeyError:
return None
if not (sub_item.minimum <= v <= sub_item.maximum):
raise ValueError(
f"invalid choice for {item}.{sub_item}: {v} not in [{sub_item.minimum}..{sub_item.maximum}]"
)
b += common.int2bytes(v, sub_item.length)
if len(w) + len(b) > 15:
seq.append(b + b"\xff")
w = b""
w += b
seq.append(w + b"\xff")
return seq
def prepare_write_item(self, item, value):
_item = self._item_from_id[int(item)]
w = common.int2bytes(_item.index, 1)
for sub_item in self.sub_items[_item]:
try:
v = value[str(sub_item)]
except KeyError:
return None
if not (sub_item.minimum <= v <= sub_item.maximum):
raise ValueError(f"invalid choice for {item}.{sub_item}: {v} not in [{sub_item.minimum}..{sub_item.maximum}]")
w += common.int2bytes(v, sub_item.length)
return w + b"\xff"
def acceptable(self, args, current):
# just one item, with at least one sub-item
if not isinstance(args, list) or len(args) != 2 or not isinstance(args[1], dict):
return None
item = next((p for p in self.items if p.id == args[0] or str(p) == args[0]), None)
if not item:
return None
for sub_key, value in args[1].items():
sub_item = next((it for it in self.sub_items[item] if it.id == sub_key), None)
if not sub_item:
return None
if not isinstance(value, int) or not (sub_item.minimum <= value <= sub_item.maximum):
return None
return [int(item), {**args[1]}]
def compare(self, args, current):
logger.warning("compare not implemented for multiple range settings")
return False

File diff suppressed because it is too large Load Diff

View File

@ -1,352 +0,0 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import logging
from time import time as _timestamp
from . import hidpp10 as _hidpp10
from . import hidpp20 as _hidpp20
from . import settings as _settings
from .common import BATTERY_APPROX as _BATTERY_APPROX
from .common import NamedInt as _NamedInt
from .common import NamedInts as _NamedInts
from .i18n import _, ngettext
logger = logging.getLogger(__name__)
_R = _hidpp10.REGISTERS
#
#
#
ALERT = _NamedInts(NONE=0x00, NOTIFICATION=0x01, SHOW_WINDOW=0x02, ATTENTION=0x04, ALL=0xFF)
KEYS = _NamedInts(
BATTERY_LEVEL=1,
BATTERY_CHARGING=2,
BATTERY_STATUS=3,
LIGHT_LEVEL=4,
LINK_ENCRYPTED=5,
NOTIFICATION_FLAGS=6,
ERROR=7,
BATTERY_NEXT_LEVEL=8,
BATTERY_VOLTAGE=9,
)
# If the battery charge is under this percentage, trigger an attention event
# (blink systray icon/notification/whatever).
_BATTERY_ATTENTION_LEVEL = 5
# If no updates have been receiver from the device for a while, ping the device
# and update it status accordingly.
# _STATUS_TIMEOUT = 5 * 60 # seconds
_LONG_SLEEP = 15 * 60 # seconds
#
#
#
def attach_to(device, changed_callback):
assert device
assert changed_callback
if not hasattr(device, 'status') or device.status is None:
if not device.isDevice:
device.status = ReceiverStatus(device, changed_callback)
else:
device.status = DeviceStatus(device, changed_callback)
#
#
#
class ReceiverStatus(dict):
"""The 'runtime' status of a receiver, mostly about the pairing process --
is the pairing lock open or closed, any pairing errors, etc.
"""
def __init__(self, receiver, changed_callback):
assert receiver
self._receiver = receiver
assert changed_callback
self._changed_callback = changed_callback
# self.updated = 0
self.lock_open = False
self.discovering = False
self.counter = None
self.device_address = None
self.device_authentication = None
self.device_kind = None
self.device_name = None
self.device_passkey = None
self.new_device = None
self[KEYS.ERROR] = None
def __str__(self):
count = len(self._receiver)
return (
_('No paired devices.')
if count == 0 else ngettext('%(count)s paired device.', '%(count)s paired devices.', count) % {
'count': count
}
)
def changed(self, alert=ALERT.NOTIFICATION, reason=None):
# self.updated = _timestamp()
self._changed_callback(self._receiver, alert=alert, reason=reason)
# def poll(self, timestamp):
# r = self._receiver
# assert r
#
# if logger.isEnabledFor(logging.DEBUG):
# logger.debug("polling status of %s", r)
#
# # make sure to read some stuff that may be read later by the UI
# r.serial, r.firmware, None
#
# # get an update of the notification flags
# # self[KEYS.NOTIFICATION_FLAGS] = _hidpp10.get_notification_flags(r)
#
#
#
class DeviceStatus(dict):
"""Holds the 'runtime' status of a peripheral -- things like
active/inactive, battery charge, lux, etc. It updates them mostly by
processing incoming notification events from the device itself.
"""
def __init__(self, device, changed_callback):
assert device
self._device = device
assert changed_callback
self._changed_callback = changed_callback
# is the device active?
self._active = None
# timestamp of when this status object was last updated
self.updated = 0
def to_string(self):
def _items():
comma = False
battery_level = self.get(KEYS.BATTERY_LEVEL)
if battery_level is not None:
if isinstance(battery_level, _NamedInt):
yield _('Battery: %(level)s') % {'level': _(str(battery_level))}
else:
yield _('Battery: %(percent)d%%') % {'percent': battery_level}
battery_status = self.get(KEYS.BATTERY_STATUS)
if battery_status is not None:
yield ' (%s)' % _(str(battery_status))
comma = True
light_level = self.get(KEYS.LIGHT_LEVEL)
if light_level is not None:
if comma:
yield ', '
yield _('Lighting: %(level)s lux') % {'level': light_level}
return ''.join(i for i in _items())
def __repr__(self):
return '{' + ', '.join('\'%s\': %r' % (k, v) for k, v in self.items()) + '}'
def __bool__(self):
return bool(self._active)
__nonzero__ = __bool__
def set_battery_info(self, level, nextLevel, status, voltage, timestamp=None):
if logger.isEnabledFor(logging.DEBUG):
logger.debug('%s: battery %s, %s', self._device, level, status)
if level is None:
# Some notifications may come with no battery level info, just
# charging state info, so do our best to infer a level (even if it is just the last level)
# It is not always possible to do this well
if status == _hidpp20.BATTERY_STATUS.full:
level = _BATTERY_APPROX.full
elif status in (_hidpp20.BATTERY_STATUS.almost_full, _hidpp20.BATTERY_STATUS.recharging):
level = _BATTERY_APPROX.good
elif status == _hidpp20.BATTERY_STATUS.slow_recharge:
level = _BATTERY_APPROX.low
else:
level = self.get(KEYS.BATTERY_LEVEL)
else:
assert isinstance(level, int)
# TODO: this is also executed when pressing Fn+F7 on K800.
old_level, self[KEYS.BATTERY_LEVEL] = self.get(KEYS.BATTERY_LEVEL), level
old_status, self[KEYS.BATTERY_STATUS] = self.get(KEYS.BATTERY_STATUS), status
self[KEYS.BATTERY_NEXT_LEVEL] = nextLevel
old_voltage, self[KEYS.BATTERY_VOLTAGE] = self.get(KEYS.BATTERY_VOLTAGE), voltage
charging = status in (
_hidpp20.BATTERY_STATUS.recharging, _hidpp20.BATTERY_STATUS.almost_full, _hidpp20.BATTERY_STATUS.full,
_hidpp20.BATTERY_STATUS.slow_recharge
)
old_charging, self[KEYS.BATTERY_CHARGING] = self.get(KEYS.BATTERY_CHARGING), charging
changed = old_level != level or old_status != status or old_charging != charging or old_voltage != voltage
alert, reason = ALERT.NONE, None
if _hidpp20.BATTERY_OK(status) and (level is None or level > _BATTERY_ATTENTION_LEVEL):
self[KEYS.ERROR] = None
else:
logger.warning('%s: battery %d%%, ALERT %s', self._device, level, status)
if self.get(KEYS.ERROR) != status:
self[KEYS.ERROR] = status
# only show the notification once
alert = ALERT.NOTIFICATION | ALERT.ATTENTION
if isinstance(level, _NamedInt):
reason = _('Battery: %(level)s (%(status)s)') % {'level': _(level), 'status': _(status)}
else:
reason = _('Battery: %(percent)d%% (%(status)s)') % {'percent': level, 'status': status.name}
if changed or reason or not self._active: # a battery response means device is active
# update the leds on the device, if any
_hidpp10.set_3leds(self._device, level, charging=charging, warning=bool(alert))
self.changed(active=True, alert=alert, reason=reason, timestamp=timestamp)
# Retrieve and regularize battery status
def read_battery(self, timestamp=None):
if self._active:
assert self._device
battery = self._device.battery()
self.set_battery_keys(battery)
def set_battery_keys(self, battery):
if battery is not None:
level, nextLevel, status, voltage = battery
self.set_battery_info(level, nextLevel, status, voltage)
elif self.get(KEYS.BATTERY_STATUS, None) is not None:
self[KEYS.BATTERY_STATUS] = None
self[KEYS.BATTERY_CHARGING] = None
self[KEYS.BATTERY_VOLTAGE] = None
self.changed()
def changed(self, active=None, alert=ALERT.NONE, reason=None, push=False, timestamp=None):
assert self._changed_callback
d = self._device
# assert d # may be invalid when processing the 'unpaired' notification
timestamp = timestamp or _timestamp()
if active is not None:
d.online = active
was_active, self._active = self._active, active
if active:
if not was_active:
# Make sure to set notification flags on the device, they
# get cleared when the device is turned off (but not when the device
# goes idle, and we can't tell the difference right now).
if d.protocol < 2.0:
self[KEYS.NOTIFICATION_FLAGS] = d.enable_connection_notifications()
# battery information may have changed so try to read it now
self.read_battery(timestamp)
# Push settings for new devices (was_active is None),
# when devices request software reconfiguration
# and when devices become active if they don't have wireless device status feature,
if was_active is None or push or not was_active and (
not d.features or _hidpp20.FEATURE.WIRELESS_DEVICE_STATUS not in d.features
):
if logger.isEnabledFor(logging.INFO):
logger.info('%s pushing device settings %s', d, d.settings)
_settings.apply_all_settings(d)
else:
if was_active: # don't clear status when devices go inactive
## battery = self.get(KEYS.BATTERY_LEVEL)
## self.clear()
## # If we had a known battery level before, assume it's not going
## # to change much while the device is offline.
## if battery is not None:
## self[KEYS.BATTERY_LEVEL] = battery
pass
# A device that is not active on the first status notification
# but becomes active afterwards does not produce a pop-up notification
# so don't produce one here. This cuts off pop-ups when Solaar starts,
# which can be problematic if Solaar is autostarted.
## if self.updated == 0 and active is True:
## if the device is active on the very first status notification,
## (meaning just when the program started or a new receiver was just
## detected), pop up a notification about it
## alert |= ALERT.NOTIFICATION
self.updated = timestamp
# if logger.isEnabledFor(logging.DEBUG):
# logger.debug("device %d changed: active=%s %s", d.number, self._active, dict(self))
self._changed_callback(d, alert, reason)
# def poll(self, timestamp):
# d = self._device
# if not d:
# logger.error("polling status of invalid device")
# return
#
# if self._active:
# if logger.isEnabledFor(logging.DEBUG):
# logger.debug("polling status of %s", d)
#
# # read these from the device, the UI may need them later
# d.protocol, d.serial, d.firmware, d.kind, d.name, d.settings, None
#
# # make sure we know all the features of the device
# # if d.features:
# # d.features[:]
#
# # devices may go out-of-range while still active, or the computer
# # may go to sleep and wake up without the devices available
# if timestamp - self.updated > _STATUS_TIMEOUT:
# if d.ping():
# timestamp = self.updated = _timestamp()
# else:
# self.changed(active=False, reason='out of range')
#
# # if still active, make sure we know the battery level
# if KEYS.BATTERY_LEVEL not in self:
# self.read_battery(timestamp)
#
# elif timestamp - self.updated > _STATUS_TIMEOUT:
# if d.ping():
# self.changed(active=True)
# else:
# self.updated = _timestamp()

View File

@ -1,5 +1,3 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
@ -16,17 +14,28 @@
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import pkgutil as _pkgutil import pkgutil
import subprocess as _subprocess import subprocess
import sys as _sys import sys
NAME = 'solaar' NAME = "Solaar"
try: try:
__version__ = _subprocess.check_output(['git', 'describe', '--always'], cwd=_sys.path[0], __version__ = (
stderr=_subprocess.DEVNULL).strip().decode() subprocess.check_output(
[
"git",
"describe",
"--always",
],
cwd=sys.path[0],
stderr=subprocess.DEVNULL,
)
.strip()
.decode()
)
except Exception: except Exception:
try: try:
__version__ = _pkgutil.get_data('solaar', 'commit').strip().decode() __version__ = pkgutil.get_data("solaar", "commit").strip().decode()
except Exception: except Exception:
__version__ = _pkgutil.get_data('solaar', 'version').strip().decode() __version__ = pkgutil.get_data("solaar", "version").strip().decode()

View File

@ -1,5 +1,3 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
@ -16,85 +14,91 @@
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import argparse as _argparse import argparse
import logging import logging
import sys as _sys import sys
from importlib import import_module
from traceback import extract_tb
from traceback import format_exc
from logitech_receiver import base
from logitech_receiver import device
from logitech_receiver import receiver
from solaar import NAME from solaar import NAME
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
#
#
#
def _create_parser(): def _create_parser():
parser = _argparse.ArgumentParser( parser = argparse.ArgumentParser(
prog=NAME.lower(), prog=NAME.lower(),
add_help=False, add_help=False,
epilog='For details on individual actions, run `%s <action> --help`.' % NAME.lower() epilog=f"For details on individual actions, run `{NAME.lower()} <action> --help`.",
) )
subparsers = parser.add_subparsers(title='actions', help='optional action to perform') subparsers = parser.add_subparsers(title="actions", help="command-line action to perform")
sp = subparsers.add_parser('show', help='show information about devices') sp = subparsers.add_parser("show", help="show information about devices")
sp.add_argument( sp.add_argument(
'device', "device",
nargs='?', nargs="?",
default='all', default="all",
help='device to show information about; may be a device number (1..6), a serial number, ' help="device to show information about; may be a device number (1..6), a serial number, "
'a substring of a device\'s name, or "all" (the default)' 'a substring of a device\'s name, or "all" (the default)',
) )
sp.set_defaults(action='show') sp.set_defaults(action="show")
sp = subparsers.add_parser('probe', help='probe a receiver (debugging use only)') sp = subparsers.add_parser("probe", help="probe a receiver (debugging use only)")
sp.add_argument( sp.add_argument(
'receiver', nargs='?', help='select receiver by name substring or serial number when more than one is present' "receiver", nargs="?", help="select receiver by name substring or serial number when more than one is present"
) )
sp.set_defaults(action='probe') sp.set_defaults(action="probe")
sp = subparsers.add_parser('profiles', help='read or write onboard profiles', epilog='Only works on active devices.')
sp.add_argument(
'device',
help='device to read or write profiles of; may be a device number (1..6), a serial number, '
'a substring of a device\'s name'
)
sp.add_argument('profiles', nargs='?', help='file containing YAML dump of profiles')
sp.set_defaults(action='profiles')
sp = subparsers.add_parser( sp = subparsers.add_parser(
'config', "profiles",
help='read/write device-specific settings', help="read or write onboard profiles",
epilog='Please note that configuration only works on active devices.' epilog="Only works on active devices.",
) )
sp.add_argument( sp.add_argument(
'device', "device",
help='device to configure; may be a device number (1..6), a serial number, ' help="device to read or write profiles of; may be a device number (1..6), a serial number, "
'or a substring of a device\'s name' "a substring of a device's name",
) )
sp.add_argument('setting', nargs='?', help='device-specific setting; leave empty to list available settings') sp.add_argument("profiles", nargs="?", help="file containing YAML dump of profiles")
sp.add_argument('value_key', nargs='?', help='new value for the setting or key for keyed settings') sp.set_defaults(action="profiles")
sp.add_argument('extra_subkey', nargs='?', help='value for keyed or subkey for subkeyed settings')
sp.add_argument('extra2', nargs='?', help='value for subkeyed settings')
sp.set_defaults(action='config')
sp = subparsers.add_parser( sp = subparsers.add_parser(
'pair', "config",
help='pair a new device', help="read/write device-specific settings",
epilog='The Logitech Unifying Receiver supports up to 6 paired devices at the same time.' epilog="Please note that configuration only works on active devices.",
) )
sp.add_argument( sp.add_argument(
'receiver', nargs='?', help='select receiver by name substring or serial number when more than one is present' "device",
help="device to configure; may be a device number (1..6), a serial number, " "or a substring of a device's name",
) )
sp.set_defaults(action='pair') sp.add_argument("setting", nargs="?", help="device-specific setting; leave empty to list available settings")
sp.add_argument("value_key", nargs="?", help="new value for the setting or key for keyed settings")
sp.add_argument("extra_subkey", nargs="?", help="value for keyed or subkey for subkeyed settings")
sp.add_argument("extra2", nargs="?", help="value for subkeyed settings")
sp.set_defaults(action="config")
sp = subparsers.add_parser('unpair', help='unpair a device') sp = subparsers.add_parser(
sp.add_argument( "pair",
'device', help="pair a new device",
help='device to unpair; may be a device number (1..6), a serial number, ' epilog="The Logitech Unifying Receiver supports up to 6 paired devices at the same time.",
'or a substring of a device\'s name.'
) )
sp.set_defaults(action='unpair') sp.add_argument(
"receiver", nargs="?", help="select receiver by name substring or serial number when more than one is present"
)
sp.set_defaults(action="pair")
sp = subparsers.add_parser("unpair", help="unpair a device")
sp.add_argument(
"device",
help="device to unpair; may be a device number (1..6), a serial number, " "or a substring of a device's name.",
)
sp.set_defaults(action="unpair")
return parser, subparsers.choices return parser, subparsers.choices
@ -104,37 +108,35 @@ print_help = _cli_parser.print_help
def _receivers(dev_path=None): def _receivers(dev_path=None):
from logitech_receiver import Receiver for dev_info in base.receivers():
from logitech_receiver.base import receivers
for dev_info in receivers():
if dev_path is not None and dev_path != dev_info.path: if dev_path is not None and dev_path != dev_info.path:
continue continue
try: try:
r = Receiver.open(dev_info) r = receiver.create_receiver(base, dev_info)
if logger.isEnabledFor(logging.DEBUG): logger.debug("[%s] => %s", dev_info.path, r)
logger.debug('[%s] => %s', dev_info.path, r)
if r: if r:
yield r yield r
except Exception as e: except Exception as e:
logger.exception('opening ' + str(dev_info)) logger.exception("opening " + str(dev_info))
_sys.exit('%s: error: %s' % (NAME, str(e))) sys.exit(f"{NAME.lower()}: error: {str(e)}")
def _receivers_and_devices(dev_path=None): def _receivers_and_devices(dev_path=None):
from logitech_receiver import Device, Receiver for dev_info in base.receivers_and_devices():
from logitech_receiver.base import receivers_and_devices
for dev_info in receivers_and_devices():
if dev_path is not None and dev_path != dev_info.path: if dev_path is not None and dev_path != dev_info.path:
continue continue
try: try:
d = Device.open(dev_info) if dev_info.isDevice else Receiver.open(dev_info) if dev_info.isDevice:
if logger.isEnabledFor(logging.DEBUG): d = device.create_device(base, dev_info)
logger.debug('[%s] => %s', dev_info.path, d) else:
d = receiver.create_receiver(base, dev_info)
logger.debug("[%s] => %s", dev_info.path, d)
if d is not None: if d is not None:
yield d yield d
except Exception as e: except Exception as e:
logger.exception('opening ' + str(dev_info)) logger.exception("opening " + str(dev_info))
_sys.exit('%s: error: %s' % (NAME, str(e))) sys.exit(f"{NAME.lower()}: error: {str(e)}")
def _find_receiver(receivers, name): def _find_receiver(receivers, name):
@ -175,7 +177,9 @@ def _find_device(receivers, name):
for dev in r: for dev in r:
if ( if (
name == dev.serial.lower() or name == dev.codename.lower() or name == str(dev.kind).lower() name == dev.serial.lower()
or name == dev.codename.lower()
or name == str(dev.kind).lower()
or name in dev.name.lower() or name in dev.name.lower()
): ):
yield dev yield dev
@ -184,11 +188,7 @@ def _find_device(receivers, name):
break break
# raise Exception("no device found matching '%s'" % name)
def run(cli_args=None, hidraw_path=None): def run(cli_args=None, hidraw_path=None):
if cli_args: if cli_args:
action = cli_args[0] action = cli_args[0]
args = _cli_parser.parse_args(cli_args) args = _cli_parser.parse_args(cli_args)
@ -196,15 +196,15 @@ def run(cli_args=None, hidraw_path=None):
args = _cli_parser.parse_args() args = _cli_parser.parse_args()
# Python 3 has an undocumented 'feature' that breaks parsing empty args # Python 3 has an undocumented 'feature' that breaks parsing empty args
# http://bugs.python.org/issue16308 # http://bugs.python.org/issue16308
if 'cmd' not in args: if "cmd" not in args:
_cli_parser.print_usage(_sys.stderr) _cli_parser.print_usage(sys.stderr)
_sys.stderr.write('%s: error: too few arguments\n' % NAME.lower()) sys.stderr.write(f"{NAME.lower()}: error: too few arguments\n")
_sys.exit(2) sys.exit(2)
action = args.action action = args.action
assert action in actions assert action in actions
try: try:
if action == 'show' or action == 'probe' or action == 'config' or action == 'profiles': if action == "show" or action == "probe" or action == "config" or action == "profiles":
c = list(_receivers_and_devices(hidraw_path)) c = list(_receivers_and_devices(hidraw_path))
else: else:
c = list(_receivers(hidraw_path)) c = list(_receivers(hidraw_path))
@ -212,13 +212,10 @@ def run(cli_args=None, hidraw_path=None):
raise Exception( raise Exception(
'No supported device found. Use "lsusb" and "bluetoothctl devices Connected" to list connected devices.' 'No supported device found. Use "lsusb" and "bluetoothctl devices Connected" to list connected devices.'
) )
from importlib import import_module m = import_module("." + action, package=__name__)
m = import_module('.' + action, package=__name__)
m.run(c, args, _find_receiver, _find_device) m.run(c, args, _find_receiver, _find_device)
except AssertionError: except AssertionError:
from traceback import extract_tb tb_last = extract_tb(sys.exc_info()[2])[-1]
tb_last = extract_tb(_sys.exc_info()[2])[-1] sys.exit(f"{NAME.lower()}: assertion failed: {tb_last[0]} line {int(tb_last[1])}")
_sys.exit('%s: assertion failed: %s line %d' % (NAME.lower(), tb_last[0], tb_last[1]))
except Exception: except Exception:
from traceback import format_exc sys.exit(f"{NAME.lower()}: error: {format_exc()}")
_sys.exit('%s: error: %s' % (NAME.lower(), format_exc()))

View File

@ -1,5 +1,3 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
@ -16,61 +14,66 @@
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import yaml as _yaml import yaml
from logitech_receiver import settings as _settings from logitech_receiver import settings
from logitech_receiver import settings_templates as _settings_templates from logitech_receiver import settings_templates
from logitech_receiver.common import NamedInts as _NamedInts from logitech_receiver.common import NamedInts
from solaar import configuration as _configuration from logitech_receiver.settings_templates import SettingsProtocol
from solaar import configuration
APP_ID = "io.github.pwr_solaar.solaar"
def _print_setting(s, verbose=True): def _print_setting(s, verbose=True):
print('#', s.label) print("#", s.label)
if verbose: if verbose:
if s.description: if s.description:
print('#', s.description.replace('\n', ' ')) print("#", s.description.replace("\n", " "))
if s.kind == _settings.KIND.toggle: if s.kind == settings.Kind.TOGGLE:
print('# possible values: on/true/t/yes/y/1 or off/false/f/no/n/0 or Toggle/~') print("# possible values: on/true/t/yes/y/1 or off/false/f/no/n/0 or Toggle/~")
elif s.kind == _settings.KIND.choice: elif s.kind == settings.Kind.CHOICE:
print( print(
'# possible values: one of [', ', '.join(str(v) for v in s.choices), "# possible values: one of [",
'], or higher/lower/highest/max/lowest/min' ", ".join(str(v) for v in s.choices),
"], or higher/lower/highest/max/lowest/min",
) )
else: else:
# wtf? # wtf?
pass pass
value = s.read(cached=False) value = s.read(cached=False)
if value is None: if value is None:
print(s.name, '= ? (failed to read from device)') print(s.name, "= ? (failed to read from device)")
else: else:
print(s.name, '=', s.val_to_string(value)) print(s.name, "=", s.val_to_string(value))
def _print_setting_keyed(s, key, verbose=True): def _print_setting_keyed(s, key, verbose=True):
print('#', s.label) print("#", s.label)
if verbose: if verbose:
if s.description: if s.description:
print('#', s.description.replace('\n', ' ')) print("#", s.description.replace("\n", " "))
if s.kind == _settings.KIND.multiple_toggle: if s.kind == settings.Kind.MULTIPLE_TOGGLE:
k = next((k for k in s._labels if key == k), None) k = next((k for k in s._labels if key == k), None)
if k is None: if k is None:
print(s.name, '=? (key not found)') print(s.name, "=? (key not found)")
else: else:
print('# possible values: on/true/t/yes/y/1 or off/false/f/no/n/0 or Toggle/~') print("# possible values: on/true/t/yes/y/1 or off/false/f/no/n/0 or Toggle/~")
value = s.read(cached=False) value = s.read(cached=False)
if value is None: if value is None:
print(s.name, '= ? (failed to read from device)') print(s.name, "= ? (failed to read from device)")
else: else:
print(s.name, s.val_to_string({k: value[str(int(k))]})) print(s.name, s.val_to_string({k: value[str(int(k))]}))
elif s.kind == _settings.KIND.map_choice: elif s.kind == settings.Kind.MAP_CHOICE:
k = next((k for k in s.choices.keys() if key == k), None) k = next((k for k in s.choices.keys() if key == k), None)
if k is None: if k is None:
print(s.name, '=? (key not found)') print(s.name, "=? (key not found)")
else: else:
print('# possible values: one of [', ', '.join(str(v) for v in s.choices[k]), ']') print("# possible values: one of [", ", ".join(str(v) for v in s.choices[k]), "]")
value = s.read(cached=False) value = s.read(cached=False)
if value is None: if value is None:
print(s.name, '= ? (failed to read from device)') print(s.name, "= ? (failed to read from device)")
else: else:
print(s.name, s.val_to_string({k: value[int(k)]})) print(s.name, s.val_to_string({k: value[int(k)]}))
@ -92,55 +95,55 @@ def select_choice(value, choices, setting, key):
break break
if val is not None: if val is not None:
value = val value = val
elif ivalue is not None and ivalue >= 1 and ivalue <= len(choices): elif ivalue is not None and 1 <= ivalue <= len(choices):
value = choices[ivalue - 1] value = choices[ivalue - 1]
elif lvalue in ('higher', 'lower'): elif lvalue in ("higher", "lower"):
old_value = setting.read() if key is None else setting.read_key(key) old_value = setting.read() if key is None else setting.read_key(key)
if old_value is None: if old_value is None:
raise Exception('%s: could not read current value' % setting.name) raise Exception(f"{setting.name}: could not read current value")
if lvalue == 'lower': if lvalue == "lower":
lower_values = choices[:old_value] lower_values = choices[:old_value]
value = lower_values[-1] if lower_values else choices[:][0] value = lower_values[-1] if lower_values else choices[:][0]
elif lvalue == 'higher': elif lvalue == "higher":
higher_values = choices[old_value + 1 :] higher_values = choices[old_value + 1 :]
value = higher_values[0] if higher_values else choices[:][-1] value = higher_values[0] if higher_values else choices[:][-1]
elif lvalue in ('highest', 'max', 'first'): elif lvalue in ("highest", "max", "first"):
value = choices[:][-1] value = choices[:][-1]
elif lvalue in ('lowest', 'min', 'last'): elif lvalue in ("lowest", "min", "last"):
value = choices[:][0] value = choices[:][0]
else: else:
raise Exception('%s: possible values are [%s]' % (setting.name, ', '.join(str(v) for v in choices))) raise Exception(f"{setting.name}: possible values are [{', '.join(str(v) for v in choices)}]")
return value return value
def select_toggle(value, setting, key=None): def select_toggle(value, setting, key=None):
if value.lower() in ('toggle', '~'): if value.lower() in ("toggle", "~"):
value = not (setting.read() if key is None else setting.read()[str(int(key))]) value = not (setting.read() if key is None else setting.read()[str(int(key))])
else: else:
try: try:
value = bool(int(value)) value = bool(int(value))
except Exception: except Exception as exc:
if value.lower() in ('true', 'yes', 'on', 't', 'y'): if value.lower() in ("true", "yes", "on", "t", "y"):
value = True value = True
elif value.lower() in ('false', 'no', 'off', 'f', 'n'): elif value.lower() in ("false", "no", "off", "f", "n"):
value = False value = False
else: else:
raise Exception("%s: don't know how to interpret '%s' as boolean" % (setting.name, value)) raise Exception(f"{setting.name}: don't know how to interpret '{value}' as boolean") from exc
return value return value
def select_range(value, setting): def select_range(value, setting):
try: try:
value = int(value) value = int(value)
except ValueError: except ValueError as exc:
raise Exception("%s: can't interpret '%s' as integer" % (setting.name, value)) raise Exception(f"{setting.name}: can't interpret '{value}' as integer") from exc
min, max = setting.range minimum, maximum = setting.range
if value < min or value > max: if value < minimum or value > maximum:
raise Exception("%s: value '%s' out of bounds" % (setting.name, value)) raise Exception(f"{setting.name}: value '{value}' out of bounds")
return value return value
def run(receivers, args, find_receiver, find_device): def run(receivers, args, _find_receiver, find_device):
assert receivers assert receivers
assert args.device assert args.device
@ -153,21 +156,20 @@ def run(receivers, args, find_receiver, find_device):
dev = None dev = None
if not dev: if not dev:
raise Exception("no online device found matching '%s'" % device_name) raise Exception(f"no online device found matching '{device_name}'")
if not args.setting: # print all settings, so first set them all up if not args.setting: # print all settings, so first set them all up
if not dev.settings: if not dev.settings:
raise Exception('no settings for %s' % dev.name) raise Exception(f"no settings for {dev.name}")
_configuration.attach_to(dev) configuration.attach_to(dev)
# _settings.apply_all_settings(dev) print(dev.name, f"({dev.codename}) [{dev.wpid}:{dev.serial}]")
print(dev.name, '(%s) [%s:%s]' % (dev.codename, dev.wpid, dev.serial))
for s in dev.settings: for s in dev.settings:
print('') print("")
_print_setting(s) _print_setting(s)
return return
setting_name = args.setting.lower() setting_name = args.setting.lower()
setting = _settings_templates.check_feature_setting(dev, setting_name) setting = settings_templates.check_feature_setting(dev, setting_name)
if not setting and dev.descriptor and dev.descriptor.settings: if not setting and dev.descriptor and dev.descriptor.settings:
for sclass in dev.descriptor.settings: for sclass in dev.descriptor.settings:
if sclass.register and sclass.name == setting_name: if sclass.register and sclass.name == setting_name:
@ -176,20 +178,21 @@ def run(receivers, args, find_receiver, find_device):
except Exception: except Exception:
setting = None setting = None
if setting is None: if setting is None:
raise Exception("no setting '%s' for %s" % (args.setting, dev.name)) raise Exception(f"no setting '{args.setting}' for {dev.name}")
if args.value_key is None: if args.value_key is None:
# setting.apply()
_print_setting(setting) _print_setting(setting)
return return
remote = False remote = False
try: try:
import gi import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gio, Gtk gi.require_version("Gtk", "3.0")
from gi.repository import Gio
from gi.repository import Gtk
if Gtk.init_check()[0]: # can Gtk be initialized? if Gtk.init_check()[0]: # can Gtk be initialized?
APP_ID = 'io.github.pwr_solaar.solaar'
application = Gtk.Application.new(APP_ID, Gio.ApplicationFlags.HANDLES_COMMAND_LINE) application = Gtk.Application.new(APP_ID, Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
application.register() application.register()
remote = application.get_is_remote() remote = application.get_is_remote()
@ -201,41 +204,41 @@ def run(receivers, args, find_receiver, find_device):
if message is not None: if message is not None:
print(message) print(message)
if result is None: if result is None:
raise Exception("%s: failed to set value '%s' [%r]" % (setting.name, str(value), value)) raise Exception(f"{setting.name}: failed to set value '{str(value)}' [{value!r}]")
# if the Solaar UI is running tell it to also perform the set, otherwise save the change in the configuration file # if the Solaar UI is running tell it to also perform the set, otherwise save the change in the configuration file
if remote: if remote:
argl = ['config', dev.serial or dev.unitId, setting.name] argl = ["config", dev.serial or dev.unitId, setting.name]
argl.extend([a for a in [args.value_key, args.extra_subkey, args.extra2] if a is not None]) argl.extend([a for a in [args.value_key, args.extra_subkey, args.extra2] if a is not None])
application.run(_yaml.safe_dump(argl)) application.run(yaml.safe_dump(argl))
else: else:
if dev.persister and setting.persist: if dev.persister and setting.persist:
dev.persister[setting.name] = setting._value dev.persister[setting.name] = setting._value
def set(dev, setting, args, save): def set(dev, setting: SettingsProtocol, args, save):
if setting.kind == _settings.KIND.toggle: if setting.kind == settings.Kind.TOGGLE:
value = select_toggle(args.value_key, setting) value = select_toggle(args.value_key, setting)
args.value_key = value args.value_key = value
message = 'Setting %s of %s to %s' % (setting.name, dev.name, value) message = f"Setting {setting.name} of {dev.name} to {value}"
result = setting.write(value, save=save) result = setting.write(value, save=save)
elif setting.kind == _settings.KIND.range: elif setting.kind == settings.Kind.RANGE:
value = select_range(args.value_key, setting) value = select_range(args.value_key, setting)
args.value_key = value args.value_key = value
message = 'Setting %s of %s to %s' % (setting.name, dev.name, value) message = f"Setting {setting.name} of {dev.name} to {value}"
result = setting.write(value, save=save) result = setting.write(value, save=save)
elif setting.kind == _settings.KIND.choice: elif setting.kind == settings.Kind.CHOICE:
value = select_choice(args.value_key, setting.choices, setting, None) value = select_choice(args.value_key, setting.choices, setting, None)
args.value_key = int(value) args.value_key = int(value)
message = 'Setting %s of %s to %s' % (setting.name, dev.name, value) message = f"Setting {setting.name} of {dev.name} to {value}"
result = setting.write(value, save=save) result = setting.write(value, save=save)
elif setting.kind == _settings.KIND.map_choice: elif setting.kind == settings.Kind.MAP_CHOICE:
if args.extra_subkey is None: if args.extra_subkey is None:
_print_setting_keyed(setting, args.value_key) _print_setting_keyed(setting, args.value_key)
return (None, None, None) return None, None, None
key = args.value_key key = args.value_key
ikey = to_int(key) ikey = to_int(key)
k = next((k for k in setting.choices.keys() if key == k), None) k = next((k for k in setting.choices.keys() if key == k), None)
@ -246,17 +249,17 @@ def set(dev, setting, args, save):
args.extra_subkey = int(value) args.extra_subkey = int(value)
args.value_key = str(int(k)) args.value_key = str(int(k))
else: else:
raise Exception("%s: key '%s' not in setting" % (setting.name, key)) raise Exception(f"{setting.name}: key '{key}' not in setting")
message = 'Setting %s of %s key %r to %r' % (setting.name, dev.name, k, value) message = f"Setting {setting.name} of {dev.name} key {k!r} to {value!r}"
result = setting.write_key_value(int(k), value, save=save) result = setting.write_key_value(int(k), value, save=save)
elif setting.kind == _settings.KIND.multiple_toggle: elif setting.kind == settings.Kind.MULTIPLE_TOGGLE:
if args.extra_subkey is None: if args.extra_subkey is None:
_print_setting_keyed(setting, args.value_key) _print_setting_keyed(setting, args.value_key)
return (None, None, None) return None, None, None
key = args.value_key key = args.value_key
all_keys = getattr(setting, 'choices_universe', None) all_keys = getattr(setting, "choices_universe", None)
ikey = all_keys[int(key) if key.isdigit() else key] if isinstance(all_keys, _NamedInts) else to_int(key) ikey = all_keys[int(key) if key.isdigit() else key] if isinstance(all_keys, NamedInts) else to_int(key)
k = next((k for k in setting._labels if key == k), None) k = next((k for k in setting._labels if key == k), None)
if k is None and ikey is not None: if k is None and ikey is not None:
k = next((k for k in setting._labels if ikey == k), None) k = next((k for k in setting._labels if ikey == k), None)
@ -265,18 +268,18 @@ def set(dev, setting, args, save):
args.extra_subkey = value args.extra_subkey = value
args.value_key = str(int(k)) args.value_key = str(int(k))
else: else:
raise Exception("%s: key '%s' not in setting" % (setting.name, key)) raise Exception(f"{setting.name}: key '{key}' not in setting")
message = 'Setting %s key %r to %r' % (setting.name, k, value) message = f"Setting {setting.name} key {k!r} to {value!r}"
result = setting.write_key_value(str(int(k)), value, save=save) result = setting.write_key_value(str(int(k)), value, save=save)
elif setting.kind == _settings.KIND.multiple_range: elif setting.kind == settings.Kind.MULTIPLE_RANGE:
if args.extra_subkey is None: if args.extra_subkey is None:
raise Exception('%s: setting needs both key and value to set' % (setting.name)) raise Exception(f"{setting.name}: setting needs both key and value to set")
key = args.value_key key = args.value_key
all_keys = getattr(setting, 'choices_universe', None) all_keys = getattr(setting, "choices_universe", None)
ikey = all_keys[int(key) if key.isdigit() else key] if isinstance(all_keys, _NamedInts) else to_int(key) ikey = all_keys[int(key) if key.isdigit() else key] if isinstance(all_keys, NamedInts) else to_int(key)
if args.extra2 is None or to_int(args.extra2) is None: if args.extra2 is None or to_int(args.extra2) is None:
raise Exception('%s: setting needs an integer value, not %s' % (setting.name, args.extra2)) raise Exception(f"{setting.name}: setting needs an integer value, not {args.extra2}")
if not setting._value: # ensure that there are values to look through if not setting._value: # ensure that there are values to look through
setting.read() setting.read()
k = next((k for k in setting._value if key == ikey or key.isdigit() and ikey == int(key)), None) k = next((k for k in setting._value if key == ikey or key.isdigit() and ikey == int(key)), None)
@ -287,12 +290,12 @@ def set(dev, setting, args, save):
item[args.extra_subkey] = to_int(args.extra2) item[args.extra_subkey] = to_int(args.extra2)
args.value_key = str(int(k)) args.value_key = str(int(k))
else: else:
raise Exception("%s: key '%s' not in setting" % (setting.name, key)) raise Exception(f"{setting.name}: key '{key}' not in setting")
message = 'Setting %s key %s parameter %s to %r' % (setting.name, k, args.extra_subkey, item[args.extra_subkey]) message = f"Setting {setting.name} key {k} parameter {args.extra_subkey} to {item[args.extra_subkey]!r}"
result = setting.write_key_value(int(k), item, save=save) result = setting.write_key_value(int(k), item, save=save)
value = item value = item
else: else:
raise Exception('NotImplemented') raise Exception("NotImplemented")
return result, message, value return result, message, value

View File

@ -1,5 +1,3 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
@ -16,14 +14,14 @@
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from time import time as _timestamp from time import time
from logitech_receiver import base as _base from logitech_receiver import base
from logitech_receiver import hidpp10 as _hidpp10 from logitech_receiver import hidpp10
from logitech_receiver import notifications as _notifications from logitech_receiver import hidpp10_constants
from logitech_receiver import status as _status from logitech_receiver import notifications
_R = _hidpp10.REGISTERS _hidpp10 = hidpp10.Hidpp10()
def run(receivers, args, find_receiver, _ignore): def run(receivers, args, find_receiver, _ignore):
@ -33,105 +31,107 @@ def run(receivers, args, find_receiver, _ignore):
receiver_name = args.receiver.lower() receiver_name = args.receiver.lower()
receiver = find_receiver(receivers, receiver_name) receiver = find_receiver(receivers, receiver_name)
if not receiver: if not receiver:
raise Exception("no receiver found matching '%s'" % receiver_name) raise Exception(f"no receiver found matching '{receiver_name}'")
else: else:
receiver = receivers[0] receiver = receivers[0]
assert receiver assert receiver
receiver.status = _status.ReceiverStatus(receiver, lambda *args, **kwargs: None)
# check if it's necessary to set the notification flags # check if it's necessary to set the notification flags
old_notification_flags = _hidpp10.get_notification_flags(receiver) or 0 old_notification_flags = _hidpp10.get_notification_flags(receiver) or 0
if not (old_notification_flags & _hidpp10.NOTIFICATION_FLAG.wireless): if not (old_notification_flags & hidpp10_constants.NotificationFlag.WIRELESS):
_hidpp10.set_notification_flags(receiver, old_notification_flags | _hidpp10.NOTIFICATION_FLAG.wireless) _hidpp10.set_notification_flags(receiver, old_notification_flags | hidpp10_constants.NotificationFlag.WIRELESS)
# get all current devices # get all current devices
known_devices = [dev.number for dev in receiver] known_devices = [dev.number for dev in receiver]
class _HandleWithNotificationHook(int): class _HandleWithNotificationHook(int):
def notifications_hook(self, n): def notifications_hook(self, n):
nonlocal known_devices nonlocal known_devices
assert n assert n
if n.devnumber == 0xFF: if n.devnumber == 0xFF:
_notifications.process(receiver, n) notifications.process(receiver, n)
elif n.sub_id == 0x41 and len(n.data) == _base._SHORT_MESSAGE_SIZE - 4: elif n.sub_id == 0x41 and len(n.data) == base.SHORT_MESSAGE_SIZE - 4:
kd, known_devices = known_devices, None # only process one connection notification kd, known_devices = known_devices, None # only process one connection notification
if kd is not None: if kd is not None:
if n.devnumber not in kd: if n.devnumber not in kd:
receiver.status.new_device = receiver.register_new_device(n.devnumber, n) receiver.pairing.new_device = receiver.register_new_device(n.devnumber, n)
elif receiver.re_pairs: elif receiver.re_pairs:
del receiver[n.devnumber] # get rid of information on device re-paired away del receiver[n.devnumber] # get rid of information on device re-paired away
receiver.status.new_device = receiver.register_new_device(n.devnumber, n) receiver.pairing.new_device = receiver.register_new_device(n.devnumber, n)
timeout = 30 # seconds timeout = 30 # seconds
receiver.handle = _HandleWithNotificationHook(receiver.handle) receiver.handle = _HandleWithNotificationHook(receiver.handle)
if receiver.receiver_kind == 'bolt': # Bolt receivers require authentication to pair a device if receiver.receiver_kind == "bolt": # Bolt receivers require authentication to pair a device
receiver.discover(timeout=timeout) receiver.discover(timeout=timeout)
print('Bolt Pairing: long-press the pairing key or button on your device (timing out in', timeout, 'seconds).') print("Bolt Pairing: long-press the pairing key or button on your device (timing out in", timeout, "seconds).")
pairing_start = _timestamp() pairing_start = time()
patience = 5 # the discovering notification may come slightly later, so be patient patience = 5 # the discovering notification may come slightly later, so be patient
while receiver.status.discovering or _timestamp() - pairing_start < patience: while receiver.pairing.discovering or time() - pairing_start < patience:
if receiver.status.device_address and receiver.status.device_authentication and receiver.status.device_name: if receiver.pairing.device_address and receiver.pairing.device_authentication and receiver.pairing.device_name:
break break
n = _base.read(receiver.handle) n = base.read(receiver.handle)
n = _base.make_notification(*n) if n else None n = base.make_notification(*n) if n else None
if n: if n:
receiver.handle.notifications_hook(n) receiver.handle.notifications_hook(n)
address = receiver.status.device_address address = receiver.pairing.device_address
name = receiver.status.device_name name = receiver.pairing.device_name
authentication = receiver.status.device_authentication authentication = receiver.pairing.device_authentication
kind = receiver.status.device_kind kind = receiver.pairing.device_kind
print(f'Bolt Pairing: discovered {name}') print(f"Bolt Pairing: discovered {name}")
receiver.pair_device( receiver.pair_device(
address=address, authentication=authentication, entropy=20 if kind == _hidpp10.DEVICE_KIND.keyboard else 10 address=address,
authentication=authentication,
entropy=20 if kind == hidpp10_constants.DEVICE_KIND.keyboard else 10,
) )
pairing_start = _timestamp() pairing_start = time()
patience = 5 # the discovering notification may come slightly later, so be patient patience = 5 # the discovering notification may come slightly later, so be patient
while receiver.status.lock_open or _timestamp() - pairing_start < patience: while receiver.pairing.lock_open or time() - pairing_start < patience:
if receiver.status.device_passkey: if receiver.pairing.device_passkey:
break break
n = _base.read(receiver.handle) n = base.read(receiver.handle)
n = _base.make_notification(*n) if n else None n = base.make_notification(*n) if n else None
if n: if n:
receiver.handle.notifications_hook(n) receiver.handle.notifications_hook(n)
if authentication & 0x01: if authentication & 0x01:
print(f'Bolt Pairing: type passkey {receiver.status.device_passkey} and then press the enter key') print(f"Bolt Pairing: type passkey {receiver.pairing.device_passkey} and then press the enter key")
else: else:
passkey = f'{int(receiver.status.device_passkey):010b}' passkey = f"{int(receiver.pairing.device_passkey):010b}"
passkey = ', '.join(['right' if bit == '1' else 'left' for bit in passkey]) passkey = ", ".join(["right" if bit == "1" else "left" for bit in passkey])
print(f'Bolt Pairing: press {passkey}') print(f"Bolt Pairing: press {passkey}")
print('and then press left and right buttons simultaneously') print("and then press left and right buttons simultaneously")
while receiver.status.lock_open: while receiver.pairing.lock_open:
n = _base.read(receiver.handle) n = base.read(receiver.handle)
n = _base.make_notification(*n) if n else None n = base.make_notification(*n) if n else None
if n: if n:
receiver.handle.notifications_hook(n) receiver.handle.notifications_hook(n)
else: else:
receiver.set_lock(False, timeout=timeout) receiver.set_lock(False, timeout=timeout)
print('Pairing: turn your new device on (timing out in', timeout, 'seconds).') print("Pairing: Turn your device on or press, hold, and release")
pairing_start = _timestamp() print("a channel button or the channel switch button.")
print("Timing out in", timeout, "seconds.")
pairing_start = time()
patience = 5 # the lock-open notification may come slightly later, wait for it a bit patience = 5 # the lock-open notification may come slightly later, wait for it a bit
while receiver.status.lock_open or _timestamp() - pairing_start < patience: while receiver.pairing.lock_open or time() - pairing_start < patience:
n = _base.read(receiver.handle) n = base.read(receiver.handle)
if n: if n:
n = _base.make_notification(*n) n = base.make_notification(*n)
if n: if n:
receiver.handle.notifications_hook(n) receiver.handle.notifications_hook(n)
if not (old_notification_flags & _hidpp10.NOTIFICATION_FLAG.wireless): if not (old_notification_flags & hidpp10_constants.NotificationFlag.WIRELESS):
# only clear the flags if they weren't set before, otherwise a # only clear the flags if they weren't set before, otherwise a
# concurrently running Solaar app might stop working properly # concurrently running Solaar app might stop working properly
_hidpp10.set_notification_flags(receiver, old_notification_flags) _hidpp10.set_notification_flags(receiver, old_notification_flags)
if receiver.status.new_device: if receiver.pairing.new_device:
dev = receiver.status.new_device dev = receiver.pairing.new_device
print('Paired device %d: %s (%s) [%s:%s]' % (dev.number, dev.name, dev.codename, dev.wpid, dev.serial)) print(f"Paired device {int(dev.number)}: {dev.name} ({dev.codename}) [{dev.wpid}:{dev.serial}]")
else: else:
error = receiver.status.get(_status.KEYS.ERROR) error = receiver.pairing.error
if error: if error:
raise Exception('pairing failed: %s' % error) raise Exception(f"pairing failed: {error}")
else: else:
print('Paired device') # this is better than an error print("Paired device") # this is better than an error

View File

@ -1,5 +1,3 @@
# -*- python-mode -*-
## Copyright (C) 2020 ## Copyright (C) 2020
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
@ -16,12 +14,13 @@
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from logitech_receiver import base as _base from logitech_receiver import base
from logitech_receiver import hidpp10 as _hidpp10 from logitech_receiver.common import strhex
from logitech_receiver.common import strhex as _strhex from logitech_receiver.hidpp10_constants import ErrorCode
from solaar.cli.show import _print_device, _print_receiver from logitech_receiver.hidpp10_constants import Registers
_R = _hidpp10.REGISTERS from solaar.cli.show import _print_device
from solaar.cli.show import _print_receiver
def run(receivers, args, find_receiver, _ignore): def run(receivers, args, find_receiver, _ignore):
@ -31,7 +30,7 @@ def run(receivers, args, find_receiver, _ignore):
receiver_name = args.receiver.lower() receiver_name = args.receiver.lower()
receiver = find_receiver(receivers, receiver_name) receiver = find_receiver(receivers, receiver_name)
if not receiver: if not receiver:
raise Exception("no receiver found matching '%s'" % receiver_name) raise Exception(f"no receiver found matching '{receiver_name}'")
else: else:
receiver = receivers[0] receiver = receivers[0]
@ -43,75 +42,71 @@ def run(receivers, args, find_receiver, _ignore):
_print_receiver(receiver) _print_receiver(receiver)
print('') print("")
print(' Register Dump') print(" Register Dump")
rgst = receiver.read_register(_R.notifications) rgst = receiver.read_register(Registers.NOTIFICATIONS)
print(' Notifications %#04x: %s' % (_R.notifications % 0x100, '0x' + _strhex(rgst) if rgst else 'None')) print(" Notifications %#04x: %s" % (Registers.NOTIFICATIONS % 0x100, f"0x{strhex(rgst)}" if rgst else "None"))
rgst = receiver.read_register(_R.receiver_connection) rgst = receiver.read_register(Registers.RECEIVER_CONNECTION)
print(' Connection State %#04x: %s' % (_R.receiver_connection % 0x100, '0x' + _strhex(rgst) if rgst else 'None')) print(
rgst = receiver.read_register(_R.devices_activity) " Connection State %#04x: %s"
print(' Device Activity %#04x: %s' % (_R.devices_activity % 0x100, '0x' + _strhex(rgst) if rgst else 'None')) % (Registers.RECEIVER_CONNECTION % 0x100, f"0x{strhex(rgst)}" if rgst else "None")
)
rgst = receiver.read_register(Registers.DEVICES_ACTIVITY)
print(
" Device Activity %#04x: %s" % (Registers.DEVICES_ACTIVITY % 0x100, f"0x{strhex(rgst)}" if rgst else "None")
)
for sub_reg in range(0, 16): for sub_reg in range(0, 16):
rgst = receiver.read_register(_R.receiver_info, sub_reg) rgst = receiver.read_register(Registers.RECEIVER_INFO, sub_reg)
print( print(
' Pairing Register %#04x %#04x: %s' % " Pairing Register %#04x %#04x: %s"
(_R.receiver_info % 0x100, sub_reg, '0x' + _strhex(rgst) if rgst else 'None') % (Registers.RECEIVER_INFO % 0x100, sub_reg, f"0x{strhex(rgst)}" if rgst else "None")
) )
for device in range(0, 7): for device in range(0, 7):
for sub_reg in [0x10, 0x20, 0x30, 0x50]: for sub_reg in [0x10, 0x20, 0x30, 0x50]:
rgst = receiver.read_register(_R.receiver_info, sub_reg + device) rgst = receiver.read_register(Registers.RECEIVER_INFO, sub_reg + device)
print( print(
' Pairing Register %#04x %#04x: %s' % " Pairing Register %#04x %#04x: %s"
(_R.receiver_info % 0x100, sub_reg + device, '0x' + _strhex(rgst) if rgst else 'None') % (Registers.RECEIVER_INFO % 0x100, sub_reg + device, f"0x{strhex(rgst)}" if rgst else "None")
) )
rgst = receiver.read_register(_R.receiver_info, 0x40 + device) rgst = receiver.read_register(Registers.RECEIVER_INFO, 0x40 + device)
print( print(
' Pairing Name %#04x %#02x: %s' % " Pairing Name %#04x %#02x: %s"
(_R.receiver_info % 0x100, 0x40 + device, rgst[2:2 + ord(rgst[1:2])] if rgst else 'None') % (Registers.RECEIVER_INFO % 0x100, 0x40 + device, rgst[2 : 2 + ord(rgst[1:2])] if rgst else "None")
) )
for part in range(1, 4): for part in range(1, 4):
rgst = receiver.read_register(_R.receiver_info, 0x60 + device, part) rgst = receiver.read_register(Registers.RECEIVER_INFO, 0x60 + device, part)
print( print(
' Pairing Name %#04x %#02x %#02x: %2d %s' % ( " Pairing Name %#04x %#02x %#02x: %2d %s"
_R.receiver_info % 0x100, 0x60 + device, part, ord(rgst[2:3]) if rgst else 0, % (
rgst[3:3 + ord(rgst[2:3])] if rgst else 'None' Registers.RECEIVER_INFO % 0x100,
0x60 + device,
part,
ord(rgst[2:3]) if rgst else 0,
rgst[3 : 3 + ord(rgst[2:3])] if rgst else "None",
) )
) )
for sub_reg in range(0, 5): for sub_reg in range(0, 5):
rgst = receiver.read_register(_R.firmware, sub_reg) rgst = receiver.read_register(Registers.FIRMWARE, sub_reg)
print( print(
' Firmware %#04x %#04x: %s' % " Firmware %#04x %#04x: %s"
(_R.firmware % 0x100, sub_reg, '0x' + _strhex(rgst) if rgst is not None else 'None') % (Registers.FIRMWARE % 0x100, sub_reg, f"0x{strhex(rgst)}" if rgst is not None else "None")
) )
print('') print("")
for reg in range(0, 0xFF): for reg in range(0, 0xFF):
for offset, reg_type in [(0x00, "Short"), (0x200, "Long")]:
last = None last = None
for sub in range(0, 0xFF): for sub in range(0, 0xFF):
rgst = _base.request(receiver.handle, 0xFF, 0x8100 | reg, sub, return_error=True) rgst = base.request(receiver.handle, 0xFF, 0x8100 | (offset + reg), sub, return_error=True)
if isinstance(rgst, int) and rgst == _hidpp10.ERROR.invalid_address: if isinstance(rgst, int) and rgst == ErrorCode.INVALID_ADDRESS:
break break
elif isinstance(rgst, int) and rgst == _hidpp10.ERROR.invalid_value: elif isinstance(rgst, int) and rgst == ErrorCode.INVALID_VALUE:
continue continue
else: else:
if not isinstance(last, bytes) or not isinstance(rgst, bytes) or last != rgst: if not isinstance(last, bytes) or not isinstance(rgst, bytes) or last != rgst:
print( print(
' Register Short %#04x %#04x: %s' % " Register %s %#04x %#04x: %s"
(reg, sub, '0x' + _strhex(rgst) if isinstance(rgst, bytes) else str(rgst)) % (reg_type, reg, sub, "0x" + strhex(rgst) if isinstance(rgst, bytes) else str(rgst))
)
last = rgst
last = None
for sub in range(0, 0xFF):
rgst = _base.request(receiver.handle, 0xFF, 0x8100 | (0x200 + reg), sub, return_error=True)
if isinstance(rgst, int) and rgst == _hidpp10.ERROR.invalid_address:
break
elif isinstance(rgst, int) and rgst == _hidpp10.ERROR.invalid_value:
continue
else:
if not isinstance(last, bytes) or not isinstance(rgst, bytes) or last != rgst:
print(
' Register Long %#04x %#04x: %s' %
(reg, sub, '0x' + _strhex(rgst) if isinstance(rgst, bytes) else str(rgst))
) )
last = rgst last = rgst

View File

@ -1,5 +1,3 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
@ -16,12 +14,12 @@
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import traceback as _traceback import traceback
import yaml as _yaml import yaml
from logitech_receiver.hidpp20 import OnboardProfiles as _OnboardProfiles from logitech_receiver.hidpp20 import OnboardProfiles
from logitech_receiver.hidpp20 import OnboardProfilesVersion as _OnboardProfilesVersion from logitech_receiver.hidpp20 import OnboardProfilesVersion
def run(receivers, args, find_receiver, find_device): def run(receivers, args, find_receiver, find_device):
@ -38,30 +36,30 @@ def run(receivers, args, find_receiver, find_device):
dev = None dev = None
if not dev: if not dev:
raise Exception("no online device found matching '%s'" % device_name) raise Exception(f"no online device found matching '{device_name}'")
if not (dev.online and dev.profiles): if not (dev.online and dev.profiles):
print(f'Device {dev.name} is either offline or has no onboard profiles') print(f"Device {dev.name} is either offline or has no onboard profiles")
elif not profiles_file: elif not profiles_file:
print(f'#Dumping profiles from {dev.name}') print(f"#Dumping profiles from {dev.name}")
print(_yaml.dump(dev.profiles)) print(yaml.dump(dev.profiles))
else: else:
try: try:
with open(profiles_file, 'r') as f: with open(profiles_file, "r") as f:
print(f'Reading profiles from {profiles_file}') print(f"Reading profiles from {profiles_file}")
profiles = _yaml.safe_load(f) profiles = yaml.safe_load(f)
if not isinstance(profiles, _OnboardProfiles): if not isinstance(profiles, OnboardProfiles):
print('Profiles file does not contain current onboard profiles') print("Profiles file does not contain current onboard profiles")
elif getattr(profiles, 'version', None) != _OnboardProfilesVersion: elif getattr(profiles, "version", None) != OnboardProfilesVersion:
version = getattr(profiles, 'version', None) version = getattr(profiles, "version", None)
print(f'Missing or incorrect profile version {version} in loaded profile') print(f"Missing or incorrect profile version {version} in loaded profile")
elif getattr(profiles, 'name', None) != dev.name: elif getattr(profiles, "name", None) != dev.name:
name = getattr(profiles, 'name', None) name = getattr(profiles, "name", None)
print(f'Different device name {name} in loaded profile') print(f"Different device name {name} in loaded profile")
else: else:
print(f'Loading profiles into {dev.name}') print(f"Loading profiles into {dev.name}")
written = profiles.write(dev) written = profiles.write(dev)
print(f'Wrote {written} sectors to {dev.name}') print(f"Wrote {written} sectors to {dev.name}")
except Exception as exc: except Exception as exc:
print('Profiles not written:', exc) print("Profiles not written:", exc)
print(_traceback.format_exc()) print(traceback.format_exc())

View File

@ -1,5 +1,3 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
@ -16,68 +14,79 @@
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from logitech_receiver import base as _base from logitech_receiver import common
from logitech_receiver import hidpp10 as _hidpp10 from logitech_receiver import exceptions
from logitech_receiver import hidpp20 as _hidpp20 from logitech_receiver import hidpp10
from logitech_receiver import receiver as _receiver from logitech_receiver import hidpp10_constants
from logitech_receiver import settings_templates as _settings_templates from logitech_receiver import hidpp20
from logitech_receiver.common import NamedInt as _NamedInt from logitech_receiver import hidpp20_constants
from logitech_receiver.common import strhex as _strhex from logitech_receiver import receiver
from solaar import NAME, __version__ from logitech_receiver import settings_templates
from logitech_receiver.common import LOGITECH_VENDOR_ID
from logitech_receiver.common import NamedInt
from logitech_receiver.common import strhex
from logitech_receiver.hidpp20_constants import SupportedFeature
_F = _hidpp20.FEATURE from solaar import NAME
from solaar import __version__
_hidpp10 = hidpp10.Hidpp10()
_hidpp20 = hidpp20.Hidpp20()
def _print_receiver(receiver): def _print_receiver(receiver):
paired_count = receiver.count() paired_count = receiver.count()
print(receiver.name) print(receiver.name)
print(' Device path :', receiver.path) print(" Device path :", receiver.path)
print(' USB id : 046d:%s' % receiver.product_id) print(f" USB id : {LOGITECH_VENDOR_ID:04x}:{receiver.product_id}")
print(' Serial :', receiver.serial) print(" Serial :", receiver.serial)
pending = hidpp10.get_configuration_pending_flags(receiver)
if pending:
print(f" C Pending : {pending:02x}")
if receiver.firmware: if receiver.firmware:
for f in receiver.firmware: for f in receiver.firmware:
print(' %-11s: %s' % (f.kind, f.version)) print(" %-11s: %s" % (f.kind, f.version))
print(' Has', paired_count, 'paired device(s) out of a maximum of %d.' % receiver.max_devices) print(" Has", paired_count, f"paired device(s) out of a maximum of {int(receiver.max_devices)}.")
if receiver.remaining_pairings() and receiver.remaining_pairings() >= 0: if receiver.remaining_pairings() and receiver.remaining_pairings() >= 0:
print(' Has %d successful pairing(s) remaining.' % receiver.remaining_pairings()) print(f" Has {int(receiver.remaining_pairings())} successful pairing(s) remaining.")
notification_flags = _hidpp10.get_notification_flags(receiver) notification_flags = _hidpp10.get_notification_flags(receiver)
if notification_flags is not None: if notification_flags is not None:
if notification_flags: if notification_flags:
notification_names = _hidpp10.NOTIFICATION_FLAG.flag_names(notification_flags) notification_names = hidpp10_constants.NotificationFlag.flag_names(notification_flags)
print(' Notifications: %s (0x%06X)' % (', '.join(notification_names), notification_flags)) print(f" Notifications: {', '.join(notification_names)} (0x{notification_flags:06X})")
else: else:
print(' Notifications: (none)') print(" Notifications: (none)")
activity = receiver.read_register(_hidpp10.REGISTERS.devices_activity) activity = receiver.read_register(hidpp10_constants.Registers.DEVICES_ACTIVITY)
if activity: if activity:
activity = [(d, ord(activity[d - 1 : d])) for d in range(1, receiver.max_devices)] activity = [(d, ord(activity[d - 1 : d])) for d in range(1, receiver.max_devices)]
activity_text = ', '.join(('%d=%d' % (d, a)) for d, a in activity if a > 0) activity_text = ", ".join(f"{int(d)}={int(a)}" for d, a in activity if a > 0)
print(' Device activity counters:', activity_text or '(empty)') print(" Device activity counters:", activity_text or "(empty)")
def _battery_text(level): def _battery_text(level) -> str:
if level is None: if level is None:
return 'N/A' return "N/A"
elif isinstance(level, _NamedInt): elif isinstance(level, NamedInt):
return str(level) return str(level)
else: else:
return '%d%%' % level return f"{int(level)}%"
def _battery_line(dev): def _battery_line(dev):
battery = dev.battery() battery = dev.battery()
if battery is not None: if battery is not None:
level, nextLevel, status, voltage = battery level, nextLevel, status, voltage = battery.level, battery.next_level, battery.status, battery.voltage
text = _battery_text(level) text = _battery_text(level)
if voltage is not None: if voltage is not None:
text = text + (' %smV ' % voltage) text = f"{text} {voltage}mV "
nextText = '' if nextLevel is None else ', next level ' + _battery_text(nextLevel) nextText = "" if nextLevel is None else f", next level {_battery_text(nextLevel)}"
print(' Battery: %s, %s%s.' % (text, status, nextText)) print(f" Battery: {text}, {status}{nextText}.")
else: else:
print(' Battery status unavailable.') print(" Battery status unavailable.")
def _print_device(dev, num=None): def _print_device(dev, num=None):
@ -85,230 +94,244 @@ def _print_device(dev, num=None):
# try to ping the device to see if it actually exists and to wake it up # try to ping the device to see if it actually exists and to wake it up
try: try:
dev.ping() dev.ping()
except _base.NoSuchDevice: except exceptions.NoSuchDevice:
print(' %s: Device not found' % num or dev.number) print(f" {num}: Device not found" or dev.number)
return return
if num or dev.number < 8: if num or dev.number < 8:
print(' %d: %s' % (num or dev.number, dev.name)) print(f" {int(num or dev.number)}: {dev.name}")
else: else:
print('%s' % dev.name) print(f"{dev.name}")
print(' Device path :', dev.path) print(" Device path :", dev.path)
if dev.wpid: if dev.wpid:
print(' WPID : %s' % dev.wpid) print(f" WPID : {dev.wpid}")
if dev.product_id: if dev.product_id:
print(' USB id : 046d:%s' % dev.product_id) print(f" USB id : {LOGITECH_VENDOR_ID:04x}:{dev.product_id}")
print(' Codename :', dev.codename) print(" Codename :", dev.codename)
print(' Kind :', dev.kind) print(" Kind :", dev.kind)
if dev.protocol: if dev.protocol:
print(' Protocol : HID++ %1.1f' % dev.protocol) print(f" Protocol : HID++ {dev.protocol:1.1f}")
else: else:
print(' Protocol : unknown (device is offline)') print(" Protocol : unknown (device is offline)")
if dev.polling_rate: if dev.polling_rate:
print(' Report Rate :', dev.polling_rate) print(" Report Rate :", dev.polling_rate)
print(' Serial number:', dev.serial) print(" Serial number:", dev.serial)
if dev.modelId: if dev.modelId:
print(' Model ID: ', dev.modelId) print(" Model ID: ", dev.modelId)
if dev.unitId: if dev.unitId:
print(' Unit ID: ', dev.unitId) print(" Unit ID: ", dev.unitId)
if dev.firmware: if dev.firmware:
for fw in dev.firmware: for fw in dev.firmware:
print(' %11s:' % fw.kind, (fw.name + ' ' + fw.version).strip()) print(f" {fw.kind:11}:", (fw.name + " " + fw.version).strip())
if dev.power_switch_location: if dev.power_switch_location:
print(' The power switch is located on the %s.' % dev.power_switch_location) print(f" The power switch is located on the {dev.power_switch_location}.")
if dev.online: if dev.online:
notification_flags = _hidpp10.get_notification_flags(dev) notification_flags = _hidpp10.get_notification_flags(dev)
if notification_flags is not None: if notification_flags is not None:
if notification_flags: if notification_flags:
notification_names = _hidpp10.NOTIFICATION_FLAG.flag_names(notification_flags) notification_names = hidpp10_constants.NotificationFlag.flag_names(notification_flags)
print(' Notifications: %s (0x%06X).' % (', '.join(notification_names), notification_flags)) print(f" Notifications: {', '.join(notification_names)} (0x{notification_flags:06X}).")
else: else:
print(' Notifications: (none).') print(" Notifications: (none).")
device_features = _hidpp10.get_device_features(dev) device_features = _hidpp10.get_device_features(dev)
if device_features is not None: if device_features is not None:
if device_features: if device_features:
device_features_names = _hidpp10.DEVICE_FEATURES.flag_names(device_features) device_features_names = hidpp10_constants.DeviceFeature.flag_names(device_features)
print(' Features: %s (0x%06X)' % (', '.join(device_features_names), device_features)) print(f" Features: {', '.join(device_features_names)} (0x{device_features:06X})")
else: else:
print(' Features: (none)') print(" Features: (none)")
if dev.online and dev.features: if dev.online and dev.features:
print(' Supports %d HID++ 2.0 features:' % len(dev.features)) print(f" Supports {len(dev.features)} HID++ 2.0 features:")
dev_settings = [] dev_settings = []
_settings_templates.check_feature_settings(dev, dev_settings) settings_templates.check_feature_settings(dev, dev_settings)
for feature, index in dev.features.enumerate(): for feature, index in dev.features.enumerate():
flags = dev.request(0x0000, feature.bytes(2)) if isinstance(feature, str):
feature_bytes = bytes.fromhex(feature[-4:])
else:
feature_bytes = feature.to_bytes(2, byteorder="little")
feature_int = int.from_bytes(feature_bytes, byteorder="little")
flags = dev.request(0x0000, feature_bytes)
flags = 0 if flags is None else ord(flags[1:2]) flags = 0 if flags is None else ord(flags[1:2])
flags = _hidpp20.FEATURE_FLAG.flag_names(flags) flags = common.flag_names(hidpp20_constants.FeatureFlag, flags)
version = dev.features.get_feature_version(int(feature)) version = dev.features.get_feature_version(feature_int)
version = version if version else 0 version = version if version else 0
print(' %2d: %-22s {%04X} V%s %s ' % (index, feature, feature, version, ', '.join(flags))) print(" %2d: %-22s {%04X} V%s %s " % (index, feature, feature_int, version, ", ".join(flags)))
if feature == _hidpp20.FEATURE.HIRES_WHEEL: if feature == SupportedFeature.HIRES_WHEEL:
wheel = _hidpp20.get_hires_wheel(dev) wheel = _hidpp20.get_hires_wheel(dev)
if wheel: if wheel:
multi, has_invert, has_switch, inv, res, target, ratchet = wheel multi, has_invert, has_switch, inv, res, target, ratchet = wheel
print(' Multiplier: %s' % multi) print(f" Multiplier: {multi}")
if has_invert: if has_invert:
print(' Has invert:', 'Inverse wheel motion' if inv else 'Normal wheel motion') print(" Has invert:", "Inverse wheel motion" if inv else "Normal wheel motion")
if has_switch: if has_switch:
print(' Has ratchet switch:', 'Normal wheel mode' if ratchet else 'Free wheel mode') print(" Has ratchet switch:", "Normal wheel mode" if ratchet else "Free wheel mode")
if res: if res:
print(' High resolution mode') print(" High resolution mode")
else: else:
print(' Low resolution mode') print(" Low resolution mode")
if target: if target:
print(' HID++ notification') print(" HID++ notification")
else: else:
print(' HID notification') print(" HID notification")
elif feature == _hidpp20.FEATURE.MOUSE_POINTER: elif feature == SupportedFeature.MOUSE_POINTER:
mouse_pointer = _hidpp20.get_mouse_pointer_info(dev) mouse_pointer = _hidpp20.get_mouse_pointer_info(dev)
if mouse_pointer: if mouse_pointer:
print(' DPI: %s' % mouse_pointer['dpi']) print(f" DPI: {mouse_pointer['dpi']}")
print(' Acceleration: %s' % mouse_pointer['acceleration']) print(f" Acceleration: {mouse_pointer['acceleration']}")
if mouse_pointer['suggest_os_ballistics']: if mouse_pointer["suggest_os_ballistics"]:
print(' Use OS ballistics') print(" Use OS ballistics")
else: else:
print(' Override OS ballistics') print(" Override OS ballistics")
if mouse_pointer['suggest_vertical_orientation']: if mouse_pointer["suggest_vertical_orientation"]:
print(' Provide vertical tuning, trackball') print(" Provide vertical tuning, trackball")
else: else:
print(' No vertical tuning, standard mice') print(" No vertical tuning, standard mice")
elif feature == _hidpp20.FEATURE.VERTICAL_SCROLLING: elif feature == SupportedFeature.VERTICAL_SCROLLING:
vertical_scrolling_info = _hidpp20.get_vertical_scrolling_info(dev) vertical_scrolling_info = _hidpp20.get_vertical_scrolling_info(dev)
if vertical_scrolling_info: if vertical_scrolling_info:
print(' Roller type: %s' % vertical_scrolling_info['roller']) print(f" Roller type: {vertical_scrolling_info['roller']}")
print(' Ratchet per turn: %s' % vertical_scrolling_info['ratchet']) print(f" Ratchet per turn: {vertical_scrolling_info['ratchet']}")
print(' Scroll lines: %s' % vertical_scrolling_info['lines']) print(f" Scroll lines: {vertical_scrolling_info['lines']}")
elif feature == _hidpp20.FEATURE.HI_RES_SCROLLING: elif feature == SupportedFeature.HI_RES_SCROLLING:
scrolling_mode, scrolling_resolution = _hidpp20.get_hi_res_scrolling_info(dev) scrolling_mode, scrolling_resolution = _hidpp20.get_hi_res_scrolling_info(dev)
if scrolling_mode: if scrolling_mode:
print(' Hi-res scrolling enabled') print(" Hi-res scrolling enabled")
else: else:
print(' Hi-res scrolling disabled') print(" Hi-res scrolling disabled")
if scrolling_resolution: if scrolling_resolution:
print(' Hi-res scrolling multiplier: %s' % scrolling_resolution) print(f" Hi-res scrolling multiplier: {scrolling_resolution}")
elif feature == _hidpp20.FEATURE.POINTER_SPEED: elif feature == SupportedFeature.POINTER_SPEED:
pointer_speed = _hidpp20.get_pointer_speed_info(dev) pointer_speed = _hidpp20.get_pointer_speed_info(dev)
if pointer_speed: if pointer_speed:
print(' Pointer Speed: %s' % pointer_speed) print(f" Pointer Speed: {pointer_speed}")
elif feature == _hidpp20.FEATURE.LOWRES_WHEEL: elif feature == SupportedFeature.LOWRES_WHEEL:
wheel_status = _hidpp20.get_lowres_wheel_status(dev) wheel_status = _hidpp20.get_lowres_wheel_status(dev)
if wheel_status: if wheel_status:
print(' Wheel Reports: %s' % wheel_status) print(f" Wheel Reports: {wheel_status}")
elif feature == _hidpp20.FEATURE.NEW_FN_INVERSION: elif feature == SupportedFeature.NEW_FN_INVERSION:
inversion = _hidpp20.get_new_fn_inversion(dev) inversion = _hidpp20.get_new_fn_inversion(dev)
if inversion: if inversion:
inverted, default_inverted = inversion inverted, default_inverted = inversion
print(' Fn-swap:', 'enabled' if inverted else 'disabled') print(" Fn-swap:", "enabled" if inverted else "disabled")
print(' Fn-swap default:', 'enabled' if default_inverted else 'disabled') print(" Fn-swap default:", "enabled" if default_inverted else "disabled")
elif feature == _hidpp20.FEATURE.HOSTS_INFO: elif feature == SupportedFeature.HOSTS_INFO:
host_names = _hidpp20.get_host_names(dev) host_names = _hidpp20.get_host_names(dev)
for host, (paired, name) in host_names.items(): for host, (paired, name) in host_names.items():
print(' Host %s (%s): %s' % (host, 'paired' if paired else 'unpaired', name)) print(f" Host {host} ({'paired' if paired else 'unpaired'}): {name}")
elif feature == _hidpp20.FEATURE.DEVICE_NAME: elif feature == SupportedFeature.DEVICE_NAME:
print(' Name: %s' % _hidpp20.get_name(dev)) print(f" Name: {_hidpp20.get_name(dev)}")
print(' Kind: %s' % _hidpp20.get_kind(dev)) print(f" Kind: {_hidpp20.get_kind(dev)}")
elif feature == _hidpp20.FEATURE.DEVICE_FRIENDLY_NAME: elif feature == SupportedFeature.DEVICE_FRIENDLY_NAME:
print(' Friendly Name: %s' % _hidpp20.get_friendly_name(dev)) print(f" Friendly Name: {_hidpp20.get_friendly_name(dev)}")
elif feature == _hidpp20.FEATURE.DEVICE_FW_VERSION: elif feature == SupportedFeature.DEVICE_FW_VERSION:
for fw in _hidpp20.get_firmware(dev): for fw in _hidpp20.get_firmware(dev):
extras = _strhex(fw.extras) if fw.extras else '' extras = strhex(fw.extras) if fw.extras else ""
print(' Firmware: %s %s %s %s' % (fw.kind, fw.name, fw.version, extras)) print(f" Firmware: {fw.kind} {fw.name} {fw.version} {extras}")
ids = _hidpp20.get_ids(dev) ids = _hidpp20.get_ids(dev)
if ids: if ids:
unitId, modelId, tid_map = ids unitId, modelId, tid_map = ids
print(' Unit ID: %s Model ID: %s Transport IDs: %s' % (unitId, modelId, tid_map)) print(f" Unit ID: {unitId} Model ID: {modelId} Transport IDs: {tid_map}")
elif feature == _hidpp20.FEATURE.REPORT_RATE or feature == _hidpp20.FEATURE.EXTENDED_ADJUSTABLE_REPORT_RATE: elif feature == SupportedFeature.REPORT_RATE or feature == SupportedFeature.EXTENDED_ADJUSTABLE_REPORT_RATE:
print(' Report Rate: %s' % _hidpp20.get_polling_rate(dev)) print(f" Report Rate: {_hidpp20.get_polling_rate(dev)}")
elif feature == _hidpp20.FEATURE.REMAINING_PAIRING: elif feature == SupportedFeature.CONFIG_CHANGE:
print(' Remaining Pairings: %d' % _hidpp20.get_remaining_pairing(dev)) response = dev.feature_request(SupportedFeature.CONFIG_CHANGE, 0x00)
elif feature == _hidpp20.FEATURE.ONBOARD_PROFILES: print(f" Configuration: {response.hex()}")
if _hidpp20.get_onboard_mode(dev) == _hidpp20.ONBOARD_MODES.MODE_HOST: elif feature == SupportedFeature.REMAINING_PAIRING:
mode = 'Host' print(f" Remaining Pairings: {int(_hidpp20.get_remaining_pairing(dev))}")
elif feature == SupportedFeature.ONBOARD_PROFILES:
if _hidpp20.get_onboard_mode(dev) == hidpp20_constants.OnboardMode.MODE_HOST:
mode = "Host"
else: else:
mode = 'On-Board' mode = "On-Board"
print(' Device Mode: %s' % mode) print(f" Device Mode: {mode}")
elif _hidpp20.battery_functions.get(feature, None): elif hidpp20.battery_functions.get(feature, None):
print('', end=' ') print("", end=" ")
_battery_line(dev) _battery_line(dev)
for setting in dev_settings: for setting in dev_settings:
if setting.feature == feature: if setting.feature == feature:
if setting._device and getattr(setting._device, 'persister', None) and \ if (
setting._device.persister.get(setting.name) is not None: setting._device
and getattr(setting._device, "persister", None)
and setting._device.persister.get(setting.name) is not None
):
v = setting.val_to_string(setting._device.persister.get(setting.name)) v = setting.val_to_string(setting._device.persister.get(setting.name))
print(' %s (saved): %s' % (setting.label, v)) print(f" {setting.label} (saved): {v}")
try: try:
v = setting.val_to_string(setting.read(False)) v = setting.val_to_string(setting.read(False))
except _hidpp20.FeatureCallError as e: except exceptions.FeatureCallError as e:
v = 'HID++ error ' + str(e) v = "HID++ error " + str(e)
except AssertionError as e: except AssertionError as e:
v = 'AssertionError ' + str(e) v = "AssertionError " + str(e)
print(' %s : %s' % (setting.label, v)) print(f" {setting.label} : {v}")
if dev.online and dev.keys: if dev.online and dev.keys:
print(' Has %d reprogrammable keys:' % len(dev.keys)) print(f" Has {len(dev.keys)} reprogrammable keys:")
for k in dev.keys: for k in dev.keys:
# TODO: add here additional variants for other REPROG_CONTROLS # TODO: add here additional variants for other REPROG_CONTROLS
if dev.keys.keyversion == _hidpp20.FEATURE.REPROG_CONTROLS_V2: if dev.keys.keyversion == SupportedFeature.REPROG_CONTROLS_V2:
print(' %2d: %-26s => %-27s %s' % (k.index, k.key, k.default_task, ', '.join(k.flags))) print(" %2d: %-26s => %-27s %s" % (k.index, k.key, k.default_task, ", ".join(k.flags)))
if dev.keys.keyversion == _hidpp20.FEATURE.REPROG_CONTROLS_V4: if dev.keys.keyversion == SupportedFeature.REPROG_CONTROLS_V4:
print(' %2d: %-26s, default: %-27s => %-26s' % (k.index, k.key, k.default_task, k.mapped_to)) print(" %2d: %-26s, default: %-27s => %-26s" % (k.index, k.key, k.default_task, k.mapped_to))
gmask_fmt = ','.join(k.group_mask) gmask_fmt = ",".join(k.group_mask)
gmask_fmt = gmask_fmt if gmask_fmt else 'empty' gmask_fmt = gmask_fmt if gmask_fmt else "empty"
print(' %s, pos:%d, group:%1d, group mask:%s' % (', '.join(k.flags), k.pos, k.group, gmask_fmt)) flag_names = list(common.flag_names(hidpp20.KeyFlag, k.flags.value))
report_fmt = ', '.join(k.mapping_flags) print(
report_fmt = report_fmt if report_fmt else 'default' f" {', '.join(flag_names)}, pos:{int(k.pos)}, group:{int(k.group):1}, group mask:{gmask_fmt}"
print(' reporting: %s' % (report_fmt)) )
report_fmt = list(common.flag_names(hidpp20.MappingFlag, k.mapping_flags.value))
report_fmt = report_fmt if report_fmt else "default"
print(f" reporting: {report_fmt}")
if dev.online and dev.remap_keys: if dev.online and dev.remap_keys:
print(' Has %d persistent remappable keys:' % len(dev.remap_keys)) print(f" Has {len(dev.remap_keys)} persistent remappable keys:")
for k in dev.remap_keys: for k in dev.remap_keys:
print(' %2d: %-26s => %s%s' % (k.index, k.key, k.action, ' (remapped)' if k.cidStatus else '')) print(" %2d: %-26s => %s%s" % (k.index, k.key, k.action, " (remapped)" if k.cidStatus else ""))
if dev.online and dev.gestures: if dev.online and dev.gestures:
print( print(
' Has %d gesture(s), %d param(s) and %d spec(s):' % " Has %d gesture(s), %d param(s) and %d spec(s):"
(len(dev.gestures.gestures), len(dev.gestures.params), len(dev.gestures.specs)) % (len(dev.gestures.gestures), len(dev.gestures.params), len(dev.gestures.specs))
) )
for k in dev.gestures.gestures.values(): for k in dev.gestures.gestures.values():
print( print(
' %-26s Enabled(%4s): %-5s Diverted:(%4s) %s' % " %-26s Enabled(%4s): %-5s Diverted:(%4s) %s"
(k.gesture, k.index, k.enabled(), k.diversion_index, k.diverted()) % (k.gesture, k.index, k.enabled(), k.diversion_index, k.diverted())
) )
for k in dev.gestures.params.values(): for k in dev.gestures.params.values():
print(' %-26s Value (%4s): %s [Default: %s]' % (k.param, k.index, k.value, k.default_value)) print(" %-26s Value (%4s): %s [Default: %s]" % (k.param, k.index, k.value, k.default_value))
for k in dev.gestures.specs.values(): for k in dev.gestures.specs.values():
print(' %-26s Spec (%4s): %s' % (k.spec, k.id, k.value)) print(" %-26s Spec (%4s): %s" % (k.spec, k.id, k.value))
if dev.online: if dev.online:
_battery_line(dev) _battery_line(dev)
else: else:
print(' Battery: unknown (device is offline).') print(" Battery: unknown (device is offline).")
def run(devices, args, find_receiver, find_device): def run(devices, args, find_receiver, find_device):
assert devices assert devices
assert args.device assert args.device
print('%s version %s' % (NAME, __version__)) print(f"{NAME.lower()} version {__version__}")
print('') print("")
device_name = args.device.lower() device_name = args.device.lower()
if device_name == 'all': if device_name == "all":
for d in devices: for d in devices:
if isinstance(d, _receiver.Receiver): if isinstance(d, receiver.Receiver):
_print_receiver(d) _print_receiver(d)
count = d.count() count = d.count()
if count: if count:
for dev in d: for dev in d:
print('') print("")
_print_device(dev, dev.number) _print_device(dev, dev.number)
count -= 1 count -= 1
if not count: if not count:
break break
print('') print("")
else: else:
print('') print("")
_print_device(d) _print_device(d)
return return
@ -319,6 +342,6 @@ def run(devices, args, find_receiver, find_device):
dev = next(find_device(devices, device_name), None) dev = next(find_device(devices, device_name), None)
if not dev: if not dev:
raise Exception("no device found matching '%s'" % device_name) raise Exception(f"no device found matching '{device_name}'")
_print_device(dev) _print_device(dev)

View File

@ -1,5 +1,3 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
@ -24,17 +22,17 @@ def run(receivers, args, find_receiver, find_device):
device_name = args.device.lower() device_name = args.device.lower()
dev = next(find_device(receivers, device_name), None) dev = next(find_device(receivers, device_name), None)
if not dev: if not dev:
raise Exception("no device found matching '%s'" % device_name) raise Exception(f"no device found matching '{device_name}'")
if not dev.receiver.may_unpair: if not dev.receiver.may_unpair:
print( print(
'Receiver with USB id %s for %s [%s:%s] does not unpair, but attempting anyway.' % f"Receiver with USB id {dev.receiver.product_id} for {dev.name} [{dev.wpid}:{dev.serial}] does not unpair,",
(dev.receiver.product_id, dev.name, dev.wpid, dev.serial) "but attempting anyway.",
) )
try: try:
# query these now, it's last chance to get them # query these now, it's last chance to get them
number, codename, wpid, serial = dev.number, dev.codename, dev.wpid, dev.serial number, codename, wpid, serial = dev.number, dev.codename, dev.wpid, dev.serial
dev.receiver._unpair_device(number, True) # force an unpair dev.receiver._unpair_device(number, True) # force an unpair
print('Unpaired %d: %s (%s) [%s:%s]' % (number, dev.name, codename, wpid, serial)) print(f"Unpaired {int(number)}: {dev.name} ({codename}) [{wpid}:{serial}]")
except Exception as e: except Exception as e:
raise e raise e

View File

@ -1,6 +1,5 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by ## it under the terms of the GNU General Public License as published by
@ -16,57 +15,54 @@
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import json as _json import json
import logging import logging
import os as _os import os
import os.path as _path import threading
from threading import Lock as _Lock import yaml
from threading import Timer as _Timer
import yaml as _yaml from logitech_receiver.common import NamedInt
from logitech_receiver.common import NamedInt as _NamedInt
from solaar import __version__ from solaar import __version__
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
_XDG_CONFIG_HOME = _os.environ.get('XDG_CONFIG_HOME') or _path.expanduser(_path.join('~', '.config')) _XDG_CONFIG_HOME = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser(os.path.join("~", ".config"))
_yaml_file_path = _path.join(_XDG_CONFIG_HOME, 'solaar', 'config.yaml') _yaml_file_path = os.path.join(_XDG_CONFIG_HOME, "solaar", "config.yaml")
_json_file_path = _path.join(_XDG_CONFIG_HOME, 'solaar', 'config.json') _json_file_path = os.path.join(_XDG_CONFIG_HOME, "solaar", "config.json")
_KEY_VERSION = '_version' _KEY_VERSION = "_version"
_KEY_NAME = '_NAME' _KEY_NAME = "_NAME"
_KEY_WPID = '_wpid' _KEY_WPID = "_wpid"
_KEY_SERIAL = '_serial' _KEY_SERIAL = "_serial"
_KEY_MODEL_ID = '_modelId' _KEY_MODEL_ID = "_modelId"
_KEY_UNIT_ID = '_unitId' _KEY_UNIT_ID = "_unitId"
_KEY_ABSENT = '_absent' _KEY_ABSENT = "_absent"
_KEY_SENSITIVE = '_sensitive' _KEY_SENSITIVE = "_sensitive"
_config = [] _config = []
def _load(): def _load():
loaded_config = [] loaded_config = []
if _path.isfile(_yaml_file_path): if os.path.isfile(_yaml_file_path):
path = _yaml_file_path path = _yaml_file_path
try: try:
with open(_yaml_file_path) as config_file: with open(_yaml_file_path) as config_file:
loaded_config = _yaml.safe_load(config_file) loaded_config = yaml.safe_load(config_file)
except Exception as e: except Exception as e:
logger.error('failed to load from %s: %s', _yaml_file_path, e) logger.error("failed to load from %s: %s", _yaml_file_path, e)
elif _path.isfile(_json_file_path): elif os.path.isfile(_json_file_path):
path = _json_file_path path = _json_file_path
try: try:
with open(_json_file_path) as config_file: with open(_json_file_path) as config_file:
loaded_config = _json.load(config_file) loaded_config = json.load(config_file)
except Exception as e: except Exception as e:
logger.error('failed to load from %s: %s', _json_file_path, e) logger.error("failed to load from %s: %s", _json_file_path, e)
loaded_config = _convert_json(loaded_config) loaded_config = _convert_json(loaded_config)
else: else:
path = None path = None
if logger.isEnabledFor(logging.DEBUG): logger.debug("load => %s", loaded_config)
logger.debug('load => %s', loaded_config)
global _config global _config
_config = _parse_config(loaded_config, path) _config = _parse_config(loaded_config, path)
@ -81,48 +77,49 @@ def _parse_config(loaded_config, config_path):
loaded_version = loaded_config[0] loaded_version = loaded_config[0]
discard_derived_properties = loaded_version != current_version discard_derived_properties = loaded_version != current_version
if discard_derived_properties: if discard_derived_properties:
if logger.isEnabledFor(logging.INFO):
logger.info( logger.info(
'config file \'%s\' was generated by another version of solaar ' "config file '%s' was generated by another version of solaar "
'(config: %s, current: %s). refreshing detected device capabilities', config_path, loaded_version, "(config: %s, current: %s). refreshing detected device capabilities",
current_version config_path,
loaded_version,
current_version,
) )
for device in loaded_config[1:]: for device in loaded_config[1:]:
assert isinstance(device, dict) assert isinstance(device, dict)
parsed_config.append(_device_entry_from_config_dict(device, discard_derived_properties)) parsed_config.append(_device_entry_from_config_dict(device, discard_derived_properties))
except Exception as e: except Exception as e:
logger.warning('Exception processing config file \'%s\', ignoring contents: %s', config_path, e) logger.warning("Exception processing config file '%s', ignoring contents: %s", config_path, e)
return parsed_config return parsed_config
def _device_entry_from_config_dict(data, discard_derived_properties): def _device_entry_from_config_dict(data, discard_derived_properties):
divert = data.get('divert-keys') divert = data.get("divert-keys")
if divert: if divert:
sliding = data.get('dpi-sliding') sliding = data.get("dpi-sliding")
if sliding: # convert old-style dpi-sliding setting to divert-keys entry if sliding: # convert old-style dpi-sliding setting to divert-keys entry
divert[int(sliding)] = 3 divert[int(sliding)] = 3
data.pop('dpi-sliding', None) data.pop("dpi-sliding", None)
gestures = data.get('mouse-gestures') gestures = data.get("mouse-gestures")
if gestures: # convert old-style mouse-gestures setting to divert-keys entry if gestures: # convert old-style mouse-gestures setting to divert-keys entry
divert[int(gestures)] = 2 divert[int(gestures)] = 2
data.pop('mouse-gestures', None) data.pop("mouse-gestures", None)
# remove any string entries (from bad conversions) # remove any string entries (from bad conversions)
data['divert-keys'] = {k: v for k, v in divert.items() if isinstance(k, int)} data["divert-keys"] = {k: v for k, v in divert.items() if isinstance(k, int)}
if data.get('_sensitive', None) is None: # make scroll wheel settings default to ignore if data.get("_sensitive", None) is None: # make scroll wheel settings default to ignore
data['_sensitive'] = { data["_sensitive"] = {
'hires-smooth-resolution': 'ignore', "hires-smooth-resolution": "ignore",
'hires-smooth-invert': 'ignore', "hires-smooth-invert": "ignore",
'hires-scroll-mode': 'ignore' "hires-scroll-mode": "ignore",
} }
if discard_derived_properties: if discard_derived_properties:
data.pop('_absent', None) data.pop("_absent", None)
data.pop('_battery', None) data.pop("_battery", None)
return _DeviceEntry(**data) return _DeviceEntry(**data)
save_timer = None save_timer = None
save_lock = _Lock() configuration_lock = threading.Lock()
defer_saves = False # don't allow configuration saves to be deferred defer_saves = False # don't allow configuration saves to be deferred
@ -130,62 +127,59 @@ def save(defer=False):
global save_timer global save_timer
if not _config: if not _config:
return return
dirname = _os.path.dirname(_yaml_file_path) dirname = os.path.dirname(_yaml_file_path)
if not _path.isdir(dirname): if not os.path.isdir(dirname):
try: try:
_os.makedirs(dirname) os.makedirs(dirname)
except Exception: except Exception:
logger.error('failed to create %s', dirname) logger.error("failed to create %s", dirname)
return return
if not defer or not defer_saves: if not defer or not defer_saves:
do_save() do_save()
else: else:
with save_lock: with configuration_lock:
if not save_timer: if not save_timer:
from gi.repository import GLib save_timer = threading.Timer(5.0, do_save)
save_timer = _Timer(5.0, lambda: GLib.idle_add(do_save))
save_timer.start() save_timer.start()
def do_save(): def do_save():
global save_timer global save_timer
with save_lock: with configuration_lock:
if save_timer: if save_timer:
save_timer.cancel() save_timer.cancel()
save_timer = None save_timer = None
try: try:
with open(_yaml_file_path, 'w') as config_file: with open(_yaml_file_path, "w") as config_file:
_yaml.dump(_config, config_file, default_flow_style=None, width=150) yaml.dump(_config, config_file, default_flow_style=None, width=150)
if logger.isEnabledFor(logging.INFO): logger.info("saved %s to %s", _config, _yaml_file_path)
logger.info('saved %s to %s', _config, _yaml_file_path)
except Exception as e: except Exception as e:
logger.error('failed to save to %s: %s', _yaml_file_path, e) logger.error("failed to save to %s: %s", _yaml_file_path, e)
def _convert_json(json_dict): def _convert_json(json_dict):
config = [json_dict.get(_KEY_VERSION)] config = [json_dict.get(_KEY_VERSION)]
for key, dev in json_dict.items(): for key, dev in json_dict.items():
key = key.split(':') key = key.split(":")
if len(key) == 2: if len(key) == 2:
dev[_KEY_WPID] = dev.get(_KEY_WPID) if dev.get(_KEY_WPID) else key[0] dev[_KEY_WPID] = dev.get(_KEY_WPID) if dev.get(_KEY_WPID) else key[0]
dev[_KEY_SERIAL] = dev.get(_KEY_SERIAL) if dev.get(_KEY_SERIAL) else key[1] dev[_KEY_SERIAL] = dev.get(_KEY_SERIAL) if dev.get(_KEY_SERIAL) else key[1]
for k, v in dev.items(): for k, v in dev.items():
if type(k) == str and not k.startswith('_') and type(v) == dict: # convert string keys to ints if isinstance(k, str) and not k.startswith("_") and isinstance(v, dict): # convert string keys to ints
v = {int(dk) if type(dk) == str else dk: dv for dk, dv in v.items()} v = {int(dk) if isinstance(dk, str) else dk: dv for dk, dv in v.items()}
dev[k] = v dev[k] = v
for k in ['mouse-gestures', 'dpi-sliding']: for k in ["mouse-gestures", "dpi-sliding"]:
v = dev.get(k, None) v = dev.get(k, None)
if v is True or v is False: if v is True or v is False:
dev.pop(k) dev.pop(k)
if '_name' in dev: if "_name" in dev:
dev[_KEY_NAME] = dev['_name'] dev[_KEY_NAME] = dev["_name"]
dev.pop('_name') dev.pop("_name")
config.append(dev) config.append(dev)
return config return config
class _DeviceEntry(dict): class _DeviceEntry(dict):
def __init__(self, **kwargs): def __init__(self, **kwargs):
super().__init__(**kwargs) super().__init__(**kwargs)
@ -193,17 +187,17 @@ class _DeviceEntry(dict):
super().__setitem__(key, value) super().__setitem__(key, value)
save(defer=True) save(defer=True)
def update(self, device, modelId): def update(self, name, wpid, serial, modelId, unitId):
if device.name and device.name != self.get(_KEY_NAME): if name and name != self.get(_KEY_NAME):
super().__setitem__(_KEY_NAME, device.name) super().__setitem__(_KEY_NAME, name)
if device.wpid and device.wpid != self.get(_KEY_WPID): if wpid and wpid != self.get(_KEY_WPID):
super().__setitem__(_KEY_WPID, device.wpid) super().__setitem__(_KEY_WPID, wpid)
if device.serial and device.serial != '?' and device.serial != self.get(_KEY_SERIAL): if serial and serial != self.get(_KEY_SERIAL):
super().__setitem__(_KEY_SERIAL, device.serial) super().__setitem__(_KEY_SERIAL, serial)
if modelId and modelId != self.get(_KEY_MODEL_ID): if modelId and modelId != self.get(_KEY_MODEL_ID):
super().__setitem__(_KEY_MODEL_ID, modelId) super().__setitem__(_KEY_MODEL_ID, modelId)
if device.unitId and device.unitId != self.get(_KEY_UNIT_ID): if unitId and unitId != self.get(_KEY_UNIT_ID):
super().__setitem__(_KEY_UNIT_ID, device.unitId) super().__setitem__(_KEY_UNIT_ID, unitId)
def get_sensitivity(self, name): def get_sensitivity(self, name):
return self.get(_KEY_SENSITIVE, {}).get(name, False) return self.get(_KEY_SENSITIVE, {}).get(name, False)
@ -216,17 +210,17 @@ class _DeviceEntry(dict):
def device_representer(dumper, data): def device_representer(dumper, data):
return dumper.represent_mapping('tag:yaml.org,2002:map', data) return dumper.represent_mapping("tag:yaml.org,2002:map", data)
_yaml.add_representer(_DeviceEntry, device_representer) yaml.add_representer(_DeviceEntry, device_representer)
def named_int_representer(dumper, data): def named_int_representer(dumper, data):
return dumper.represent_scalar('tag:yaml.org,2002:int', str(int(data))) return dumper.represent_scalar("tag:yaml.org,2002:int", str(int(data)))
_yaml.add_representer(_NamedInt, named_int_representer) yaml.add_representer(NamedInt, named_int_representer)
# A device can be identified by a combination of WPID and serial number (for receiver-connected devices) # A device can be identified by a combination of WPID and serial number (for receiver-connected devices)
@ -234,33 +228,32 @@ _yaml.add_representer(_NamedInt, named_int_representer)
# But some devices have empty (all zero) modelIds and unitIds. Use the device name as a backup for the modelId. # But some devices have empty (all zero) modelIds and unitIds. Use the device name as a backup for the modelId.
# The worst situation is a receiver-connected device that Solaar has never seen on-line # The worst situation is a receiver-connected device that Solaar has never seen on-line
# that is directly connected. Here there is no way to realize that the two devices are the same. # that is directly connected. Here there is no way to realize that the two devices are the same.
# So new entries are not created for unseen off-line receiver-connected devices except for those with protocol 1.0 # So new entries are not created for unseen off-line receiver-connected devices
def persister(device): def persister(device):
def match(wpid, serial, modelId, unitId, c): def match(wpid, serial, modelId, unitId, c):
return ((wpid and wpid == c.get(_KEY_WPID) and serial and serial == c.get(_KEY_SERIAL)) or ( return (wpid and wpid == c.get(_KEY_WPID) and serial and serial == c.get(_KEY_SERIAL)) or (
modelId and modelId != '000000000000' and modelId == c.get(_KEY_MODEL_ID) and unitId modelId and modelId == c.get(_KEY_MODEL_ID) and unitId and unitId == c.get(_KEY_UNIT_ID)
and unitId == c.get(_KEY_UNIT_ID) )
))
with configuration_lock:
if not _config: if not _config:
_load() _load()
entry = None entry = None
modelId = device.modelId if device.modelId != '000000000000' else device.name if device.modelId else None # some devices report modelId and unitId as zero so use name and serial for them
modelId = device.modelId if device.modelId != "000000000000" else device._name if device.modelId else None
unitId = device.unitId if device.modelId != "000000000000" else device._serial if device.unitId else None
for c in _config: for c in _config:
if isinstance(c, _DeviceEntry) and match(device.wpid, device.serial, modelId, device.unitId, c): if isinstance(c, _DeviceEntry) and match(device.wpid, device._serial, modelId, unitId, c):
entry = c entry = c
break break
if not entry: if not entry:
if not device.online and not device.serial: # don't create entry for offline devices without serial number if not device.online: # don't create entry for offline devices
if logger.isEnabledFor(logging.INFO): logger.info("not setting up persister for offline device %s", device._name)
logger.info('not setting up persister for offline device %s with missing serial number', device.name)
return return
if logger.isEnabledFor(logging.INFO): logger.info("setting up persister for device %s", device.name)
logger.info('setting up persister for device %s', device.name)
entry = _DeviceEntry() entry = _DeviceEntry()
_config.append(entry) _config.append(entry)
entry.update(device, modelId) entry.update(device.name, device.wpid, device.serial, modelId, unitId)
return entry return entry

View File

@ -0,0 +1,28 @@
import logging
class CustomLogger(logging.Logger):
"""Logger, that avoids unnecessary string computations.
Does not compute messages for disabled log levels.
"""
def debug(self, msg, *args, **kwargs):
if self.isEnabledFor(logging.DEBUG):
super().debug(msg, *args, **kwargs)
def info(self, msg, *args, **kwargs):
if self.isEnabledFor(logging.INFO):
super().info(msg, *args, **kwargs)
def warning(self, msg, *args, **kwargs):
if self.isEnabledFor(logging.WARNING):
super().warning(msg, *args, **kwargs)
def error(self, msg, *args, **kwargs):
if self.isEnabledFor(logging.ERROR):
super().error(msg, *args, **kwargs)
def critical(self, msg, *args, **kwargs):
if self.isEnabledFor(logging.CRITICAL):
super().critical(msg, *args, **kwargs)

87
lib/solaar/dbus.py Normal file
View File

@ -0,0 +1,87 @@
## Copyright (C) 2012-2013 Daniel Pavel
## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along
## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from __future__ import annotations
import logging
from typing import Callable
logger = logging.getLogger(__name__)
try:
import dbus
from dbus.mainloop.glib import DBusGMainLoop # integration into the main GLib loop
DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
assert bus
except Exception:
# Either the dbus library is not available or the system dbus is not running
logger.warning("failed to set up dbus")
bus = None
_suspend_callback = None
_resume_callback = None
def _suspend_or_resume(suspend):
if suspend and _suspend_callback:
_suspend_callback()
if not suspend and _resume_callback:
_resume_callback()
_LOGIND_PATH = "/org/freedesktop/login1"
_LOGIND_INTERFACE = "org.freedesktop.login1.Manager"
def watch_suspend_resume(
on_resume_callback: Callable[[], None] | None = None,
on_suspend_callback: Callable[[], None] | None = None,
):
"""Register callback for suspend/resume events.
They are called only if the system DBus is running, and the Login daemon is available."""
global _resume_callback, _suspend_callback
_suspend_callback = on_suspend_callback
_resume_callback = on_resume_callback
if bus is not None and on_resume_callback is not None or on_suspend_callback is not None:
bus.add_signal_receiver(
_suspend_or_resume,
"PrepareForSleep",
dbus_interface=_LOGIND_INTERFACE,
path=_LOGIND_PATH,
)
logger.info("connected to system dbus, watching for suspend/resume events")
_BLUETOOTH_PATH_PREFIX = "/org/bluez/hci0/dev_"
_BLUETOOTH_INTERFACE = "org.freedesktop.DBus.Properties"
_bluetooth_callbacks = {}
def watch_bluez_connect(serial, callback=None):
if _bluetooth_callbacks.get(serial):
_bluetooth_callbacks.get(serial).remove()
path = _BLUETOOTH_PATH_PREFIX + serial.replace(":", "_").upper()
if bus is not None and callback is not None:
_bluetooth_callbacks[serial] = bus.add_signal_receiver(
callback, "PropertiesChanged", path=path, dbus_interface=_BLUETOOTH_INTERFACE
)

View File

@ -1,6 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- python-mode -*-
# -*- coding: UTF-8 -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
@ -18,7 +16,10 @@
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import argparse
import faulthandler
import importlib import importlib
import locale
import logging import logging
import os.path import os.path
import platform import platform
@ -26,17 +27,20 @@ import signal
import sys import sys
import tempfile import tempfile
import solaar.cli as _cli from traceback import format_exc
import solaar.i18n as _i18n
from solaar import NAME, __version__ from solaar import NAME
from solaar import __version__
from solaar import cli
from solaar import configuration
from solaar import dbus
from solaar import listener
from solaar import ui
from solaar.custom_logger import CustomLogger
logging.setLoggerClass(CustomLogger)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
#
#
#
def _require(module, os_package, gi=None, gi_package=None, gi_version=None): def _require(module, os_package, gi=None, gi_package=None, gi_version=None):
try: try:
@ -44,145 +48,162 @@ def _require(module, os_package, gi=None, gi_package=None, gi_version=None):
gi.require_version(gi_package, gi_version) gi.require_version(gi_package, gi_version)
return importlib.import_module(module) return importlib.import_module(module)
except (ImportError, ValueError): except (ImportError, ValueError):
sys.exit('%s: missing required system package %s' % (NAME, os_package)) sys.exit(f"{NAME.lower()}: missing required system package {os_package}")
battery_icons_style = 'regular' battery_icons_style = "regular"
temp = tempfile.NamedTemporaryFile(prefix='Solaar_', mode='w', delete=True) tray_icon_size = None
temp = tempfile.NamedTemporaryFile(prefix="Solaar_", mode="w", delete=True)
def create_parser():
arg_parser = argparse.ArgumentParser(
prog=NAME.lower(), epilog="For more information see https://pwr-solaar.github.io/Solaar"
)
arg_parser.add_argument(
"-d",
"--debug",
action="count",
default=0,
help="print logging messages, for debugging purposes (may be repeated for extra verbosity)",
)
arg_parser.add_argument(
"-D",
"--hidraw",
action="store",
dest="hidraw_path",
metavar="PATH",
help="unifying receiver to use; the first detected receiver if unspecified. Example: /dev/hidraw2",
)
arg_parser.add_argument(
"--restart-on-wake-up",
action="store_true",
help="restart Solaar on sleep wake-up (experimental)",
)
arg_parser.add_argument(
"-w",
"--window",
choices=("show", "hide", "only"),
help="start with window showing / hidden / only (no tray icon)",
)
arg_parser.add_argument(
"-b",
"--battery-icons",
choices=("regular", "symbolic", "solaar"),
help="prefer regular battery / symbolic battery / solaar icons",
)
arg_parser.add_argument("--tray-icon-size", type=int, help="explicit size for tray icons")
arg_parser.add_argument("-V", "--version", action="version", version="%(prog)s " + __version__)
arg_parser.add_argument("--help-actions", action="store_true", help="describe the command-line actions")
arg_parser.add_argument(
"action",
nargs=argparse.REMAINDER,
choices=cli.actions,
help="command-line action to perform (optional); append ' --help' to show args",
)
return arg_parser
def _parse_arguments(): def _parse_arguments():
import argparse arg_parser = create_parser()
arg_parser = argparse.ArgumentParser(
prog=NAME.lower(), epilog='For more information see https://pwr-solaar.github.io/Solaar'
)
arg_parser.add_argument(
'-d',
'--debug',
action='count',
default=0,
help='print logging messages, for debugging purposes (may be repeated for extra verbosity)'
)
arg_parser.add_argument(
'-D',
'--hidraw',
action='store',
dest='hidraw_path',
metavar='PATH',
help='unifying receiver to use; the first detected receiver if unspecified. Example: /dev/hidraw2'
)
arg_parser.add_argument('--restart-on-wake-up', action='store_true', help='restart Solaar on sleep wake-up (experimental)')
arg_parser.add_argument(
'-w', '--window', choices=('show', 'hide', 'only'), help='start with window showing / hidden / only (no tray icon)'
)
arg_parser.add_argument(
'-b',
'--battery-icons',
choices=('regular', 'symbolic', 'solaar'),
help='prefer regular battery / symbolic battery / solaar icons'
)
arg_parser.add_argument('--tray-icon-size', type=int, help='explicit size for tray icons')
arg_parser.add_argument('-V', '--version', action='version', version='%(prog)s ' + __version__)
arg_parser.add_argument('--help-actions', action='store_true', help='print help for the optional actions')
arg_parser.add_argument('action', nargs=argparse.REMAINDER, choices=_cli.actions, help='optional actions to perform')
args = arg_parser.parse_args() args = arg_parser.parse_args()
if args.help_actions: if args.help_actions:
_cli.print_help() cli.print_help()
return return
if args.window is None: if args.window is None:
args.window = 'show' # default behaviour is to show main window args.window = "show" # default behaviour is to show main window
global battery_icons_style global battery_icons_style
battery_icons_style = args.battery_icons if args.battery_icons is not None else 'regular' battery_icons_style = args.battery_icons if args.battery_icons is not None else "regular"
global tray_icon_size global tray_icon_size
tray_icon_size = args.tray_icon_size tray_icon_size = args.tray_icon_size
log_format = '%(asctime)s,%(msecs)03d %(levelname)8s [%(threadName)s] %(name)s: %(message)s' log_format = "%(asctime)s,%(msecs)03d %(levelname)8s [%(threadName)s] %(name)s: %(message)s"
log_level = logging.ERROR - 10 * args.debug log_level = logging.ERROR - 10 * args.debug
logging.getLogger('').setLevel(min(log_level, logging.WARNING)) logging.getLogger("").setLevel(min(log_level, logging.WARNING))
file_handler = logging.StreamHandler(temp) file_handler = logging.StreamHandler(temp)
file_handler.setLevel(max(min(log_level, logging.WARNING), logging.INFO)) file_handler.setLevel(max(min(log_level, logging.WARNING), logging.INFO))
file_handler.setFormatter(logging.Formatter(log_format)) file_handler.setFormatter(logging.Formatter(log_format))
logging.getLogger('').addHandler(file_handler) logging.getLogger("").addHandler(file_handler)
if args.debug > 0: if args.debug > 0:
stream_handler = logging.StreamHandler() stream_handler = logging.StreamHandler()
stream_handler.setFormatter(logging.Formatter(log_format)) stream_handler.setFormatter(logging.Formatter(log_format))
stream_handler.setLevel(log_level) stream_handler.setLevel(log_level)
logging.getLogger('').addHandler(stream_handler) logging.getLogger("").addHandler(stream_handler)
if not args.action: if not args.action:
if logger.isEnabledFor(logging.INFO): language, encoding = locale.getlocale()
logger.info('version %s, language %s (%s)', __version__, _i18n.language, _i18n.encoding) logger.info("version %s, language %s (%s)", __version__, language, encoding)
return args return args
# On first SIGINT, dump threads to stderr; on second, exit # On first SIGINT, dump threads to stderr; on second, exit
def _handlesig(signl, stack): def _handlesig(signl, stack):
import faulthandler
signal.signal(signal.SIGINT, signal.SIG_DFL) signal.signal(signal.SIGINT, signal.SIG_DFL)
signal.signal(signal.SIGTERM, signal.SIG_DFL) signal.signal(signal.SIGTERM, signal.SIG_DFL)
if signl == int(signal.SIGINT): if signl == int(signal.SIGINT):
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
faulthandler.dump_traceback() faulthandler.dump_traceback()
sys.exit('%s: exit due to keyboard interrupt' % (NAME.lower())) sys.exit(f"{NAME.lower()}: exit due to keyboard interrupt")
else: else:
sys.exit(0) sys.exit(0)
def main(): def main():
if platform.system() not in ('Darwin', 'Windows'): if platform.system() not in ("Darwin", "Windows"):
_require('pyudev', 'python3-pyudev') _require("pyudev", "python3-pyudev")
args = _parse_arguments() args = _parse_arguments()
if not args: if not args:
# explicit close before return
temp.close()
return return
if args.action: if args.action:
# if any argument, run comandline and exit # if any argument, run comandline and exit
return _cli.run(args.action, args.hidraw_path) result = cli.run(args.action, args.hidraw_path)
# explicit close before return
temp.close()
return result
gi = _require('gi', 'python3-gi (in Ubuntu) or python3-gobject (in Fedora)') gi = _require("gi", "python3-gi (in Ubuntu) or python3-gobject (in Fedora)")
_require('gi.repository.Gtk', 'gir1.2-gtk-3.0', gi, 'Gtk', '3.0') _require("gi.repository.Gtk", "gir1.2-gtk-3.0", gi, "Gtk", "3.0")
# handle ^C in console # handle ^C in console
signal.signal(signal.SIGINT, signal.SIG_DFL) signal.signal(signal.SIGINT, signal.SIG_DFL)
signal.signal(signal.SIGINT, _handlesig) signal.signal(signal.SIGINT, _handlesig)
signal.signal(signal.SIGTERM, _handlesig) signal.signal(signal.SIGTERM, _handlesig)
udev_file = '42-logitech-unify-permissions.rules' udev_file = "42-logitech-unify-permissions.rules"
if logger.isEnabledFor(logging.WARNING) \ if (
and not os.path.isfile('/etc/udev/rules.d/' + udev_file) \ platform.system() == "Linux"
and not os.path.isfile('/usr/lib/udev/rules.d/' + udev_file) \ and logger.isEnabledFor(logging.WARNING)
and not os.path.isfile('/usr/local/lib/udev/rules.d/' + udev_file): and not os.path.isfile("/etc/udev/rules.d/" + udev_file)
logger.warning('Solaar udev file not found in expected location') and not os.path.isfile("/usr/lib/udev/rules.d/" + udev_file)
logger.warning('See https://pwr-solaar.github.io/Solaar/installation for more information') and not os.path.isfile("/usr/local/lib/udev/rules.d/" + udev_file)
):
logger.warning("Solaar udev file not found in expected location")
logger.warning("See https://pwr-solaar.github.io/Solaar/installation for more information")
try: try:
import solaar.listener as listener listener.setup_scanner(ui.status_changed, ui.setting_changed, ui.common.error_dialog)
import solaar.ui as ui
listener.setup_scanner(ui.status_changed, ui.error_dialog)
import solaar.upower as _upower
if args.restart_on_wake_up: if args.restart_on_wake_up:
_upower.watch(listener.start_all, listener.stop_all) dbus.watch_suspend_resume(listener.start_all, listener.stop_all)
else: else:
_upower.watch(lambda: listener.ping_all(True)) dbus.watch_suspend_resume(lambda: listener.ping_all(True))
import solaar.configuration as _configuration configuration.defer_saves = True # allow configuration saves to be deferred
_configuration.defer_saves = True # allow configuration saves to be deferred
# main UI event loop # main UI event loop
ui.run_loop(listener.start_all, listener.stop_all, args.window != 'only', args.window != 'hide') ui.run_loop(listener.start_all, listener.stop_all, args.window != "only", args.window != "hide")
except Exception: except Exception:
from traceback import format_exc sys.exit(f"{NAME.lower()}: error: {format_exc()}")
sys.exit('%s: error: %s' % (NAME.lower(), format_exc()))
temp.close() temp.close()
if __name__ == '__main__': if __name__ == "__main__":
main() main()

View File

@ -1,5 +1,3 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
@ -16,47 +14,60 @@
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import gettext as _gettext import gettext
import locale import locale
import logging
import os
import sys
from solaar import NAME as _NAME from glob import glob
# from solaar import NAME
#
# _LOCALE_DOMAIN = NAME.lower()
logger = logging.getLogger(__name__)
def _find_locale_path(lc_domain): def _find_locale_path(locale_domain: str) -> str:
import os.path as _path prefix_share = os.path.normpath(os.path.join(os.path.realpath(sys.path[0]), ".."))
import sys as _sys src_share = os.path.normpath(os.path.join(os.path.realpath(sys.path[0]), "..", "share"))
prefix_share = _path.normpath(_path.join(_path.realpath(_sys.path[0]), '..'))
src_share = _path.normpath(_path.join(_path.realpath(_sys.path[0]), '..', 'share'))
del _sys
from glob import glob as _glob
for location in prefix_share, src_share: for location in prefix_share, src_share:
mo_files = _glob(_path.join(location, 'locale', '*', 'LC_MESSAGES', lc_domain + '.mo')) mo_files = glob(os.path.join(location, "locale", "*", "LC_MESSAGES", f"{locale_domain}.mo"))
if mo_files: if mo_files:
return _path.join(location, 'locale') return os.path.join(location, "locale")
raise FileNotFoundError(f"Could not find locale path for {locale_domain}")
# del _path
def set_locale_to_system_default() -> None:
"""Sets locale for translations to the system default.
If locale is unsupported, fallback to standard English without
translation 'C'.
Set LC_ALL environment variable to enforce a locale setting e.g.
'de_DE.UTF-8'. Run Solaar with your desired localization, for German
use:
'LC_ALL=de_DE.UTF-8 solaar'
"""
try:
locale.setlocale(locale.LC_ALL, "") # system default
except locale.Error:
logger.error("User locale not supported by system, using no translation.")
locale.setlocale(locale.LC_ALL, "C") # untranslated (English)
return
try: try:
locale.setlocale(locale.LC_ALL, '')
except Exception:
pass
language, encoding = locale.getlocale()
del locale
_LOCALE_DOMAIN = _NAME.lower()
path = _find_locale_path(_LOCALE_DOMAIN) path = _find_locale_path(_LOCALE_DOMAIN)
except FileNotFoundError:
path = None
gettext.bindtextdomain(_LOCALE_DOMAIN, path)
gettext.textdomain(_LOCALE_DOMAIN)
gettext.install(_LOCALE_DOMAIN)
_gettext.bindtextdomain(_LOCALE_DOMAIN, path)
_gettext.textdomain(_LOCALE_DOMAIN)
_gettext.install(_LOCALE_DOMAIN)
_ = _gettext.gettext set_locale_to_system_default()
ngettext = _gettext.ngettext
_ = gettext.gettext
ngettext = gettext.ngettext

View File

@ -1,6 +1,5 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by ## it under the terms of the GNU General Public License as published by
@ -16,94 +15,83 @@
## with this program; if not, write to the Free Software Foundation, Inc., ## with this program; if not, write to the Free Software Foundation, Inc.,
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import errno as _errno from __future__ import annotations
import errno
import logging import logging
import subprocess
import time import time
import typing
from collections import namedtuple from collections import namedtuple
from functools import partial
from typing import Callable
import gi import gi
import logitech_receiver
from logitech_receiver import Device, Receiver from logitech_receiver import base
from logitech_receiver import base as _base from logitech_receiver import exceptions
from logitech_receiver import hidpp10 as _hidpp10 from logitech_receiver import hidpp10_constants
from logitech_receiver import listener as _listener from logitech_receiver import listener
from logitech_receiver import notifications as _notifications from logitech_receiver import notifications
from logitech_receiver import status as _status
from . import configuration from . import configuration
from . import dbus
from . import i18n
from .ui import common
gi.require_version('Gtk', '3.0') # NOQA: E402 if typing.TYPE_CHECKING:
from hidapi.common import DeviceInfo
gi.require_version("Gtk", "3.0") # NOQA: E402
from gi.repository import GLib # NOQA: E402 # isort:skip from gi.repository import GLib # NOQA: E402 # isort:skip
# from solaar.i18n import _ if typing.TYPE_CHECKING:
from logitech_receiver.device import Device
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
_R = _hidpp10.REGISTERS ACTION_ADD = "add"
_IR = _hidpp10.INFO_SUBREGISTERS
# _GHOST_DEVICE = namedtuple("_GHOST_DEVICE", ("receiver", "number", "name", "kind", "online", "path"))
#
#
_GHOST_DEVICE = namedtuple('_GHOST_DEVICE', ('receiver', 'number', 'name', 'kind', 'status', 'online'))
_GHOST_DEVICE.__bool__ = lambda self: False _GHOST_DEVICE.__bool__ = lambda self: False
_GHOST_DEVICE.__nonzero__ = _GHOST_DEVICE.__bool__ _GHOST_DEVICE.__nonzero__ = _GHOST_DEVICE.__bool__
del namedtuple
def _ghost(device): def _ghost(device):
return _GHOST_DEVICE( return _GHOST_DEVICE(
receiver=device.receiver, number=device.number, name=device.name, kind=device.kind, status=None, online=False receiver=device.receiver, number=device.number, name=device.name, kind=device.kind, online=False, path=None
) )
# class SolaarListener(listener.EventsListener):
# """Keeps the status of a Receiver or Device (member name is receiver but it can also be a device)."""
#
# how often to poll devices that haven't updated their statuses on their own
# (through notifications)
# _POLL_TICK = 5 * 60 # seconds
class ReceiverListener(_listener.EventsListener):
"""Keeps the status of a Receiver.
"""
def __init__(self, receiver, status_changed_callback): def __init__(self, receiver, status_changed_callback):
super().__init__(receiver, self._notifications_handler)
# no reason to enable polling yet
# self.tick_period = _POLL_TICK
# self._last_tick = 0
assert status_changed_callback assert status_changed_callback
super().__init__(receiver, self._notifications_handler)
self.status_changed_callback = status_changed_callback self.status_changed_callback = status_changed_callback
_status.attach_to(receiver, self._status_changed) receiver.status_callback = self._status_changed
def has_started(self): def has_started(self):
if logger.isEnabledFor(logging.INFO): logger.info("%s: notifications listener has started (%s)", self.receiver, self.receiver.handle)
logger.info('%s: notifications listener has started (%s)', self.receiver, self.receiver.handle)
nfs = self.receiver.enable_connection_notifications() nfs = self.receiver.enable_connection_notifications()
if logger.isEnabledFor(logging.WARNING): if not self.receiver.isDevice and not ((nfs if nfs else 0) & hidpp10_constants.NotificationFlag.WIRELESS.value):
if not self.receiver.isDevice and not ((nfs if nfs else 0) & _hidpp10.NOTIFICATION_FLAG.wireless):
logger.warning( logger.warning(
'Receiver on %s might not support connection notifications, GUI might not show its devices', "Receiver on %s might not support connection notifications, GUI might not show its devices",
self.receiver.path self.receiver.path,
) )
self.receiver.status[_status.KEYS.NOTIFICATION_FLAGS] = nfs self.receiver.notification_flags = nfs
self.receiver.notify_devices() self.receiver.notify_devices()
self._status_changed(self.receiver) # , _status.ALERT.NOTIFICATION) self._status_changed(self.receiver)
def has_stopped(self): def has_stopped(self):
r, self.receiver = self.receiver, None r, self.receiver = self.receiver, None
assert r is not None assert r is not None
if logger.isEnabledFor(logging.INFO): logger.info("%s: notifications listener has stopped", r)
logger.info('%s: notifications listener has stopped', r)
# because udev is not notifying us about device removal, # because udev is not notifying us about device removal, make sure to clean up in _all_listeners
# make sure to clean up in _all_listeners
_all_listeners.pop(r.path, None) _all_listeners.pop(r.path, None)
# this causes problems but what is it doing (pfps) - r.status = _('The receiver was unplugged.') # this causes problems but what is it doing (pfps) - r.status = _('The receiver was unplugged.')
@ -111,63 +99,33 @@ class ReceiverListener(_listener.EventsListener):
try: try:
r.close() r.close()
except Exception: except Exception:
logger.exception('closing receiver %s' % r.path) logger.exception(f"closing receiver {r.path}")
self.status_changed_callback(r) # , _status.ALERT.NOTIFICATION) self.status_changed_callback(r)
# def tick(self, timestamp): def _status_changed(self, device, alert=None, reason=None):
# if not self.tick_period:
# raise Exception("tick() should not be called without a tick_period: %s", self)
#
# # not necessary anymore, we're now using udev monitor to watch for receiver status
# # if self._last_tick > 0 and timestamp - self._last_tick > _POLL_TICK * 2:
# # # if we missed a couple of polls, most likely the computer went into
# # # sleep, and we have to reinitialize the receiver again
# # logger.warning("%s: possible sleep detected, closing this listener", self.receiver)
# # self.stop()
# # return
#
# self._last_tick = timestamp
#
# try:
# # read these in case they haven't been read already
# # self.receiver.serial, self.receiver.firmware
# if self.receiver.status.lock_open:
# # don't mess with stuff while pairing
# return
#
# self.receiver.status.poll(timestamp)
#
# # Iterating directly through the reciver would unnecessarily probe
# # all possible devices, even unpaired ones.
# # Checking for each device number in turn makes sure only already
# # known devices are polled.
# # This is okay because we should have already known about them all
# # long before the first poll() happents, through notifications.
# for number in range(1, 6):
# if number in self.receiver:
# dev = self.receiver[number]
# if dev and dev.status is not None:
# dev.status.poll(timestamp)
# except Exception as e:
# logger.exception("polling", e)
def _status_changed(self, device, alert=_status.ALERT.NONE, reason=None):
assert device is not None assert device is not None
if logger.isEnabledFor(logging.INFO): if logger.isEnabledFor(logging.INFO):
try: try:
device.ping()
if device.kind is None: if device.kind is None:
logger.info( logger.info(
'status_changed %r: %s, %s (%X) %s', device, 'present' if bool(device) else 'removed', device.status, "status_changed %r: %s (%X) %s",
alert, reason or '' device,
"present" if bool(device) else "removed",
alert if alert is not None else 0,
reason or "",
) )
else: else:
device.ping()
logger.info( logger.info(
'status_changed %r: %s %s, %s (%X) %s', device, 'paired' if bool(device) else 'unpaired', "status_changed %r: %s %s (%X) %s",
'online' if device.online else 'offline', device.status, alert, reason or '' device,
"paired" if bool(device) else "unpaired",
"online" if device.online else "offline",
alert if alert is not None else 0,
reason or "",
) )
except Exception: except Exception as e:
logger.info('status_changed for unknown device') logger.info("status_changed for unknown device: %s", e)
if device.kind is None: if device.kind is None:
assert device == self.receiver assert device == self.receiver
@ -178,53 +136,43 @@ class ReceiverListener(_listener.EventsListener):
# not true for wired devices - assert device.receiver == self.receiver # not true for wired devices - assert device.receiver == self.receiver
if not device: if not device:
# Device was unpaired, and isn't valid anymore. # Device was unpaired, and isn't valid anymore.
# We replace it with a ghost so that the UI has something to work # We replace it with a ghost so that the UI has something to work with while cleaning up.
# with while cleaning up. logger.info("device %s was unpaired, ghosting", device)
if logger.isEnabledFor(logging.INFO):
logger.info('device %s was unpaired, ghosting', device)
device = _ghost(device) device = _ghost(device)
self.status_changed_callback(device, alert, reason) self.status_changed_callback(device, alert, reason)
if not device: if not device:
# the device was just unpaired, need to update the # the device was just unpaired, need to update the status of the receiver as well
# status of the receiver as well
self.status_changed_callback(self.receiver) self.status_changed_callback(self.receiver)
def _notifications_handler(self, n): def _notifications_handler(self, n):
assert self.receiver assert self.receiver
# if logger.isEnabledFor(logging.DEBUG):
# logger.debug("%s: handling %s", self.receiver, n)
if n.devnumber == 0xFF: if n.devnumber == 0xFF:
# a receiver notification # a receiver notification
_notifications.process(self.receiver, n) notifications.process(self.receiver, n)
return return
# a notification that came in to the device listener - strange, but nothing needs to be done here # a notification that came in to the device listener - strange, but nothing needs to be done here
if self.receiver.isDevice: if self.receiver.isDevice:
if logger.isEnabledFor(logging.DEBUG): logger.debug("Notification %s via device %s being ignored.", n, self.receiver)
logger.debug('Notification %s via device %s being ignored.', n, self.receiver)
return return
# DJ pairing notification - ignore - hid++ 1.0 pairing notification is all that is needed # DJ pairing notification - ignore - hid++ 1.0 pairing notification is all that is needed
if n.sub_id == 0x41 and n.report_id == _base.DJ_MESSAGE_ID: if n.sub_id == 0x41 and n.report_id == base.DJ_MESSAGE_ID:
if logger.isEnabledFor(logging.INFO): logger.info("ignoring DJ pairing notification %s", n)
logger.info('ignoring DJ pairing notification %s', n)
return return
# a device notification # a device notification
if not (0 < n.devnumber <= 16): # some receivers have devices past their max # devices if not (0 < n.devnumber <= 16): # some receivers have devices past their max # devices
if logger.isEnabledFor(logging.WARNING): logger.warning("Unexpected device number (%s) in notification %s.", n.devnumber, n)
logger.warning('Unexpected device number (%s) in notification %s.', n.devnumber, n)
return return
already_known = n.devnumber in self.receiver already_known = n.devnumber in self.receiver
# FIXME: hacky fix for kernel/hardware race condition # FIXME: hacky fix for kernel/hardware race condition
# If the device was just turned on or woken up from sleep, it may not # If the device was just turned on or woken up from sleep, it may not be ready to receive commands.
# be ready to receive commands. The "payload" bit of the wireless # The "payload" bit of the wireless status notification seems to tell us this. If this is the case, we
# status notification seems to tell us this. If this is the case, we # must wait a short amount of time to avoid causing a broken pipe error.
# must wait a short amount of time to avoid causing a broken pipe
# error.
device_ready = not bool(ord(n.data[0:1]) & 0x80) or n.sub_id != 0x41 device_ready = not bool(ord(n.data[0:1]) & 0x80) or n.sub_id != 0x41
if not device_ready: if not device_ready:
time.sleep(0.01) time.sleep(0.01)
@ -234,176 +182,178 @@ class ReceiverListener(_listener.EventsListener):
if n.sub_id == 0x41: if n.sub_id == 0x41:
if not already_known: if not already_known:
if n.address == 0x0A and not self.receiver.receiver_kind == 'bolt': if n.address == 0x0A and not self.receiver.receiver_kind == "bolt":
# some Nanos send a notification even if no new pairing - check that there really is a device there # some Nanos send a notification even if no new pairing - check that there really is a device there
if self.receiver.read_register(_R.receiver_info, _IR.pairing_information + n.devnumber - 1) is None: if (
self.receiver.read_register(
hidpp10_constants.Registers.RECEIVER_INFO,
hidpp10_constants.InfoSubRegisters.PAIRING_INFORMATION + n.devnumber - 1,
)
is None
):
return return
dev = self.receiver.register_new_device(n.devnumber, n) dev = self.receiver.register_new_device(n.devnumber, n)
elif self.receiver.status.lock_open and self.receiver.re_pairs and not ord(n.data[0:1]) & 0x40: elif self.receiver.pairing.lock_open and self.receiver.re_pairs and not ord(n.data[0:1]) & 0x40:
dev = self.receiver[n.devnumber] dev = self.receiver[n.devnumber]
del self.receiver[n.devnumber] # get rid of information on device re-paired away del self.receiver[n.devnumber] # get rid of information on device re-paired away
self._status_changed(dev) # signal that this device has changed self._status_changed(dev) # signal that this device has changed
dev = self.receiver.register_new_device(n.devnumber, n) dev = self.receiver.register_new_device(n.devnumber, n)
self.receiver.status.new_device = self.receiver[n.devnumber] self.receiver.pairing.new_device = self.receiver[n.devnumber]
else: else:
dev = self.receiver[n.devnumber] dev = self.receiver[n.devnumber]
else: else:
dev = self.receiver[n.devnumber] dev = self.receiver[n.devnumber]
if not dev: if not dev:
logger.warning('%s: received %s for invalid device %d: %r', self.receiver, n, n.devnumber, dev) logger.warning("%s: received %s for invalid device %d: %r", self.receiver, n, n.devnumber, dev)
return return
# Apply settings every time the device connects # Apply settings every time the device connects
if n.sub_id == 0x41: if n.sub_id == 0x41:
if logger.isEnabledFor(logging.INFO): logger.info("connection %s for device wpid %s kind %s serial %s", n, dev.wpid, dev.kind, dev._serial)
try:
dev.ping()
logger.info('connection %s for %r', n, dev)
except Exception:
logger.info('connection %s for unknown device, number %s', n, n.devnumber)
# If there are saved configs, bring the device's settings up-to-date. # If there are saved configs, bring the device's settings up-to-date.
# They will be applied when the device is marked as online. # They will be applied when the device is marked as online.
configuration.attach_to(dev) configuration.attach_to(dev)
_status.attach_to(dev, self._status_changed) dev.status_callback = self._status_changed
# the receiver changed status as well # the receiver changed status as well
self._status_changed(self.receiver) self._status_changed(self.receiver)
if not hasattr(dev, 'status') or dev.status is None: notifications.process(dev, n)
# notification before device status set up - don't process it
logger.warning('%s before device %s has status', n, dev)
else:
_notifications.process(dev, n)
if self.receiver.status.lock_open and not already_known: if self.receiver.pairing.lock_open and not already_known:
# this should be the first notification after a device was paired # this should be the first notification after a device was paired
assert n.sub_id == 0x41, 'first notification was not a connection notification' logger.warning("first notification was not a connection notification")
if logger.isEnabledFor(logging.INFO): logger.info("%s: pairing detected new device", self.receiver)
logger.info('%s: pairing detected new device', self.receiver) self.receiver.pairing.new_device = dev
self.receiver.status.new_device = dev
elif dev.online is None: elif dev.online is None:
dev.ping() dev.ping()
def __str__(self): def __str__(self):
return '<ReceiverListener(%s,%s)>' % (self.receiver.path, self.receiver.handle) return f"<SolaarListener({self.receiver.path},{self.receiver.handle})>"
# def _process_bluez_dbus(device: Device, path, dictionary: dict, signature):
# """Process bluez dbus property changed signals for device status
# changes to discover disconnections and connections.
"""
# all known receiver listeners if device:
# listeners that stop on their own may remain here if dictionary.get("Connected") is not None:
_all_listeners = {} connected = dictionary.get("Connected")
logger.info("bluez dbus for %s: %s", device, "CONNECTED" if connected else "DISCONNECTED")
device.changed(connected, reason=i18n._("connected") if connected else i18n._("disconnected"))
elif device is not None:
logger.info("bluez cleanup for %s", device)
_cleanup_bluez_dbus(device)
def _start(device_info): def _cleanup_bluez_dbus(device: Device):
assert _status_callback """Remove dbus signal receiver for device"""
isDevice = device_info.isDevice logger.info("bluez cleanup for %s", device)
if not isDevice: dbus.watch_bluez_connect(device.hid_serial, None)
receiver = Receiver.open(device_info)
_all_listeners = {} # all known receiver listeners, listeners that stop on their own may remain here
def _start(device_info: DeviceInfo):
assert _status_callback and _setting_callback
if not device_info.isDevice:
receiver_ = logitech_receiver.receiver.create_receiver(base, device_info, _setting_callback)
else: else:
receiver = Device.open(device_info) receiver_ = logitech_receiver.device.create_device(base, device_info, _setting_callback)
configuration.attach_to(receiver) if receiver_:
configuration.attach_to(receiver_)
if receiver_.bluetooth and receiver_.hid_serial:
dbus.watch_bluez_connect(receiver_.hid_serial, partial(_process_bluez_dbus, receiver_))
receiver_.cleanups.append(_cleanup_bluez_dbus)
if receiver: if receiver_:
rl = ReceiverListener(receiver, _status_callback) rl = SolaarListener(receiver_, _status_callback)
rl.start() rl.start()
_all_listeners[device_info.path] = rl _all_listeners[device_info.path] = rl
return rl return rl
logger.warning('failed to open %s', device_info) logger.warning("failed to open %s", device_info)
def start_all(): def start_all():
# just in case this it called twice in a row... stop_all() # just in case this it called twice in a row...
stop_all() logger.info("starting receiver listening threads")
for device_info in base.receivers_and_devices():
if logger.isEnabledFor(logging.INFO): _process_receiver_event(ACTION_ADD, device_info)
logger.info('starting receiver listening threads')
for device_info in _base.receivers_and_devices():
_process_receiver_event('add', device_info)
def stop_all(): def stop_all():
listeners = list(_all_listeners.values()) listeners = list(_all_listeners.values())
_all_listeners.clear() _all_listeners.clear()
if listeners: if listeners:
if logger.isEnabledFor(logging.INFO): logger.info("stopping receiver listening threads %s", listeners)
logger.info('stopping receiver listening threads %s', listeners) for listener_thread in listeners:
listener_thread.stop()
for l in listeners:
l.stop()
configuration.save() configuration.save()
if listeners: if listeners:
for l in listeners: for listener_thread in listeners:
l.join() listener_thread.join()
# ping all devices to find out whether they are connected # after a resume, the device may have been off so mark its saved status to ensure
# after a resume, the device may have been off # that the status is pushed to the device when it comes back
# so mark its saved status to ensure that the status is pushed to the device when it comes back
def ping_all(resuming=False): def ping_all(resuming=False):
if logger.isEnabledFor(logging.INFO): logger.info("ping all devices%s", " when resuming" if resuming else "")
logger.info('ping all devices%s', ' when resuming' if resuming else '') for listener_thread in _all_listeners.values():
for l in _all_listeners.values(): if listener_thread.receiver.isDevice:
if l.receiver.isDevice: if resuming:
if resuming and hasattr(l.receiver, 'status'): listener_thread.receiver._active = None # ensure that settings are pushed
l.receiver.status._active = None # ensure that settings are pushed if listener_thread.receiver.ping():
if l.receiver.ping(): listener_thread.receiver.changed(active=True, push=True)
l.receiver.status.changed(active=True, push=True) listener_thread._status_changed(listener_thread.receiver)
l._status_changed(l.receiver)
else: else:
count = l.receiver.count() count = listener_thread.receiver.count()
if count: if count:
for dev in l.receiver: for dev in listener_thread.receiver:
if resuming and hasattr(dev, 'status'): if resuming:
dev.status._active = None # ensure that settings are pushed dev._active = None # ensure that settings are pushed
if dev.ping(): if dev.ping():
dev.status.changed(active=True, push=True) dev.changed(active=True, push=True)
l._status_changed(dev) listener_thread._status_changed(dev)
count -= 1 count -= 1
if not count: if not count:
break break
_status_callback = None _status_callback = None # GUI callback to change UI in response to changes to receiver or device status
_error_callback = None _setting_callback = None # GUI callback to change UI in response to changes to status
_error_callback = None # GUI callback to report errors
def setup_scanner(status_changed_callback, error_callback): def setup_scanner(status_changed_callback: Callable, setting_changed_callback: Callable, error_callback: Callable):
global _status_callback, _error_callback global _status_callback, _error_callback, _setting_callback
assert _status_callback is None, 'scanner was already set-up' assert _status_callback is None, "scanner was already set-up"
_status_callback = status_changed_callback _status_callback = status_changed_callback
_setting_callback = setting_changed_callback
_error_callback = error_callback _error_callback = error_callback
base.notify_on_receivers_glib(GLib, _process_receiver_event)
_base.notify_on_receivers_glib(_process_receiver_event)
def _process_add(device_info, retry): def _process_add(device_info: DeviceInfo, retry):
try: try:
_start(device_info) _start(device_info)
except OSError as e: except OSError as e:
if e.errno == _errno.EACCES: if e.errno == errno.EACCES:
try: try:
import subprocess output = subprocess.check_output(["/usr/bin/getfacl", "-p", device_info.path], text=True)
output = subprocess.check_output(['/usr/bin/getfacl', '-p', device_info.path], text=True) logger.warning("Missing permissions on %s\n%s.", device_info.path, output)
if logger.isEnabledFor(logging.WARNING):
logger.warning('Missing permissions on %s\n%s.', device_info.path, output)
except Exception: except Exception:
pass pass
if retry: if retry:
GLib.timeout_add(2000.0, _process_add, device_info, retry - 1) GLib.timeout_add(2000.0, _process_add, device_info, retry - 1)
else: else:
_error_callback('permissions', device_info.path) _error_callback(common.ErrorReason.PERMISSIONS, device_info.path)
else: else:
_error_callback('nodevice', device_info.path) _error_callback(common.ErrorReason.NO_DEVICE, device_info.path)
except _base.NoReceiver: except exceptions.NoReceiver:
_error_callback('nodevice', device_info.path) _error_callback(common.ErrorReason.NO_DEVICE, device_info.path)
# receiver add/remove events will start/stop listener threads # receiver add/remove events will start/stop listener threads
@ -411,17 +361,12 @@ def _process_receiver_event(action, device_info):
assert action is not None assert action is not None
assert device_info is not None assert device_info is not None
assert _error_callback assert _error_callback
logger.info("receiver event %s %s", action, device_info)
if logger.isEnabledFor(logging.INFO):
logger.info('receiver event %s %s', action, device_info)
# whatever the action, stop any previous receivers at this path # whatever the action, stop any previous receivers at this path
l = _all_listeners.pop(device_info.path, None) listener_thread = _all_listeners.pop(device_info.path, None)
if l is not None: if listener_thread is not None:
assert isinstance(l, ReceiverListener) assert isinstance(listener_thread, SolaarListener)
l.stop() listener_thread.stop()
if action == ACTION_ADD:
if action == 'add': # a new device was detected
_process_add(device_info, 3) _process_add(device_info, 3)
return False return False

View File

@ -1,6 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- python-mode -*-
# -*- coding: UTF-8 -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## ##
@ -20,26 +18,21 @@
import logging import logging
from threading import Thread as _Thread from threading import Thread
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
try: try:
from Queue import Queue as _Queue from Queue import Queue
except ImportError: except ImportError:
from queue import Queue as _Queue from queue import Queue
#
#
#
class TaskRunner(_Thread): class TaskRunner(Thread):
def __init__(self, name): def __init__(self, name):
super().__init__(name=name) super().__init__(name=name)
self.daemon = True self.daemon = True
self.queue = _Queue(16) self.queue = Queue(16)
self.alive = False self.alive = False
def __call__(self, function, *args, **kwargs): def __call__(self, function, *args, **kwargs):
@ -53,8 +46,7 @@ class TaskRunner(_Thread):
def run(self): def run(self):
self.alive = True self.alive = True
if logger.isEnabledFor(logging.DEBUG): logger.debug("started")
logger.debug('started')
while self.alive: while self.alive:
task = self.queue.get() task = self.queue.get()
@ -64,7 +56,6 @@ class TaskRunner(_Thread):
try: try:
function(*args, **kwargs) function(*args, **kwargs)
except Exception: except Exception:
logger.exception('calling %s', function) logger.exception("calling %s", function)
if logger.isEnabledFor(logging.DEBUG): logger.debug("stopped")
logger.debug('stopped')

View File

@ -1,6 +1,5 @@
# -*- python-mode -*-
## Copyright (C) 2012-2013 Daniel Pavel ## Copyright (C) 2012-2013 Daniel Pavel
## Copyright (C) 2014-2024 Solaar Contributors https://pwr-solaar.github.io/Solaar/
## ##
## This program is free software; you can redistribute it and/or modify ## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by ## it under the terms of the GNU General Public License as published by
@ -18,107 +17,56 @@
import logging import logging
import yaml as _yaml from enum import Enum
from typing import Callable
import gi # isort:skip import gi
import yaml
gi.require_version('Gtk', '3.0') # NOQA: E402 from logitech_receiver.common import Alert
from gi.repository import GLib, Gtk, Gio # NOQA: E402 # isort:skip
from logitech_receiver.status import ALERT # NOQA: E402 # isort:skip from solaar.i18n import _
from solaar.i18n import _ # NOQA: E402 # isort:skip from solaar.ui.config_panel import change_setting
from solaar.ui.config_panel import record_setting
from solaar.ui.window import find_device
from . import common
from . import desktop_notifications
from . import diversion_rules
from . import tray
from . import window
gi.require_version("Gtk", "3.0")
from gi.repository import Gio # NOQA: E402
from gi.repository import GLib # NOQA: E402
from gi.repository import Gtk # NOQA: E402
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# assert Gtk.get_major_version() > 2, "Solaar requires Gtk 3 python bindings"
#
#
assert Gtk.get_major_version() > 2, 'Solaar requires Gtk 3 python bindings'
GLib.threads_init()
#
#
#
def _error_dialog(reason, object): APP_ID = "io.github.pwr_solaar.solaar"
logger.error('error: %s %s', reason, object)
if reason == 'permissions':
title = _('Permissions error')
text = (
_('Found a Logitech receiver or device (%s), but did not have permission to open it.') % object + '\n\n' +
_("If you've just installed Solaar, try disconnecting the receiver or device and then reconnecting it.")
)
elif reason == 'nodevice':
title = _('Cannot connect to device error')
text = (
_('Found a Logitech receiver or device at %s, but encountered an error connecting to it.') % object + '\n\n' +
_('Try disconnecting the device and then reconnecting it or turning it off and then on.')
)
elif reason == 'unpair':
title = _('Unpairing failed')
text = (
_('Failed to unpair %{device} from %{receiver}.').format(device=object.name, receiver=object.receiver.name) +
'\n\n' + _('The receiver returned an error, with no further details.')
)
else:
raise Exception("ui.error_dialog: don't know how to handle (%s, %s)", reason, object)
assert title
assert text
m = Gtk.MessageDialog(None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, text)
m.set_title(title)
m.run()
m.destroy()
def error_dialog(reason, object): class GtkSignal(Enum):
assert reason is not None ACTIVATE = "activate"
GLib.idle_add(_error_dialog, reason, object) COMMAND_LINE = "command-line"
SHUTDOWN = "shutdown"
#
#
#
_task_runner = None
def ui_async(function, *args, **kwargs):
if _task_runner:
_task_runner(function, *args, **kwargs)
#
#
#
from . import diversion_rules, notify, tray, window # isort:skip # noqa: E402
def _startup(app, startup_hook, use_tray, show_window): def _startup(app, startup_hook, use_tray, show_window):
if logger.isEnabledFor(logging.DEBUG): logger.debug("startup registered=%s, remote=%s", app.get_is_registered(), app.get_is_remote())
logger.debug('startup registered=%s, remote=%s', app.get_is_registered(), app.get_is_remote()) common.start_async()
desktop_notifications.init()
from solaar.tasks import TaskRunner as _TaskRunner
global _task_runner
_task_runner = _TaskRunner('AsyncUI')
_task_runner.start()
notify.init()
if use_tray: if use_tray:
tray.init(lambda _ignore: window.destroy()) tray.init(lambda _ignore: window.destroy())
window.init(show_window, use_tray) window.init(show_window, use_tray)
startup_hook() startup_hook()
def _activate(app): def _activate(app):
if logger.isEnabledFor(logging.DEBUG): logger.debug("activate")
logger.debug('activate')
if app.get_windows(): if app.get_windows():
window.popup() window.popup()
else: else:
@ -127,14 +75,11 @@ def _activate(app):
def _command_line(app, command_line): def _command_line(app, command_line):
args = command_line.get_arguments() args = command_line.get_arguments()
args = _yaml.safe_load(''.join(args)) if args else args args = yaml.safe_load("".join(args)) if args else args
if not args: if not args:
_activate(app) _activate(app)
elif args[0] == 'config': # config call from remote instance elif args[0] == "config": # config call from remote instance
if logger.isEnabledFor(logging.INFO): logger.info("remote command line %s", args)
logger.info('remote command line %s', args)
from solaar.ui.config_panel import change_setting # prevent circular import
from solaar.ui.window import find_device # prevent circular import
dev = find_device(args[1]) dev = find_device(args[1])
if dev: if dev:
setting = next((s for s in dev.settings if s.name == args[2]), None) setting = next((s for s in dev.settings if s.name == args[2]), None)
@ -143,59 +88,60 @@ def _command_line(app, command_line):
return 0 return 0
def _shutdown(app, shutdown_hook): def _shutdown(_app, shutdown_hook):
if logger.isEnabledFor(logging.DEBUG): logger.debug("shutdown")
logger.debug('shutdown')
shutdown_hook() shutdown_hook()
common.stop_async()
# stop the async UI processor
global _task_runner
_task_runner.stop()
_task_runner = None
tray.destroy() tray.destroy()
notify.uninit() desktop_notifications.uninit()
def run_loop(startup_hook, shutdown_hook, use_tray, show_window): def run_loop(
assert use_tray or show_window, 'need either tray or visible window' startup_hook: Callable[[], None],
# from gi.repository.Gio import ApplicationFlags as _ApplicationFlags shutdown_hook: Callable[[], None],
APP_ID = 'io.github.pwr_solaar.solaar' use_tray: bool,
show_window: bool,
):
assert use_tray or show_window, "need either tray or visible window"
application = Gtk.Application.new(APP_ID, Gio.ApplicationFlags.HANDLES_COMMAND_LINE) application = Gtk.Application.new(APP_ID, Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
application.connect('startup', lambda app, startup_hook: _startup(app, startup_hook, use_tray, show_window), startup_hook) application.connect(
application.connect('command-line', _command_line) "startup",
application.connect('activate', _activate) lambda app, startup_hook: _startup(app, startup_hook, use_tray, show_window),
application.connect('shutdown', _shutdown, shutdown_hook) startup_hook,
)
application.connect(GtkSignal.COMMAND_LINE.value, _command_line)
application.connect(GtkSignal.ACTIVATE.value, _activate)
application.connect(GtkSignal.SHUTDOWN.value, _shutdown, shutdown_hook)
application.register() application.register()
if application.get_is_remote(): if application.get_is_remote():
print(_('Another Solaar process is already running so just expose its window')) print(_("Another Solaar process is already running so just expose its window"))
application.run() application.run()
#
#
#
def _status_changed(device, alert, reason, refresh=False): def _status_changed(device, alert, reason, refresh=False):
assert device is not None assert device is not None
if logger.isEnabledFor(logging.DEBUG): logger.debug("status changed: %s (%s) %s", device, alert, reason)
logger.debug('status changed: %s (%s) %s', device, alert, reason) if alert is None:
alert = Alert.NONE
tray.update(device) tray.update(device)
if alert & ALERT.ATTENTION: if alert & Alert.ATTENTION:
tray.attention(reason) tray.attention(reason)
need_popup = alert & ALERT.SHOW_WINDOW need_popup = alert & Alert.SHOW_WINDOW
window.update(device, need_popup, refresh) window.update(device, need_popup, refresh)
diversion_rules.update_devices() diversion_rules.update_devices()
if alert & (ALERT.NOTIFICATION | ALERT.ATTENTION): if alert & (Alert.NOTIFICATION | Alert.ATTENTION):
notify.show(device, reason) desktop_notifications.show(device, reason)
def status_changed(device, alert=ALERT.NONE, reason=None, refresh=False): def status_changed(device, alert=Alert.NONE, reason=None, refresh=False):
GLib.idle_add(_status_changed, device, alert, reason, refresh) GLib.idle_add(_status_changed, device, alert, reason, refresh)
def setting_changed(device, setting_class, vals):
record_setting(device, setting_class, vals)

Some files were not shown because too many files have changed in this diff Show More