diff --git a/lib/logitech_receiver/common.py b/lib/logitech_receiver/common.py index 3be447b1..cab8a650 100644 --- a/lib/logitech_receiver/common.py +++ b/lib/logitech_receiver/common.py @@ -21,6 +21,8 @@ from binascii import hexlify as _hexlify from collections import namedtuple +import yaml as _yaml + is_string = lambda d: isinstance(d, str) # @@ -28,6 +30,38 @@ is_string = lambda d: isinstance(d, str) # +def crc16(data: bytes): + ''' + CRC-16 (CCITT) implemented with a precomputed lookup table + ''' + table = [ + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, + 0xF1EF, 0x1231, 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 + for byte in data: + crc = (crc << 8) ^ table[(crc >> 8) ^ byte] + crc &= 0xFFFF # important, crc must stay 16bits all the way through + return crc + + class NamedInt(int): """A regular Python integer with an attached name. @@ -68,6 +102,19 @@ class NamedInt(int): def __repr__(self): return 'NamedInt(%d, %r)' % (int(self), self.name) + @classmethod + def from_yaml(cls, loader, node): + args = loader.construct_mapping(node) + return cls(value=args['value'], name=args['name']) + + @classmethod + def to_yaml(cls, dumper, data): + return dumper.represent_mapping('!NamedInt', {'value': int(data), 'name': data.name}, flow_style=True) + + +_yaml.SafeLoader.add_constructor('!NamedInt', NamedInt.from_yaml) +_yaml.add_representer(NamedInt, NamedInt.to_yaml) + class NamedInts: """An ordered set of NamedInt values. diff --git a/lib/logitech_receiver/device.py b/lib/logitech_receiver/device.py index 106964e7..d3b8977d 100644 --- a/lib/logitech_receiver/device.py +++ b/lib/logitech_receiver/device.py @@ -79,9 +79,7 @@ class Device: self._remap_keys = None self._gestures = None self._gestures_lock = _threading.Lock() - self._backlight = None - self._registers = None - self._settings = None + self._profiles = self._backlight = self._registers = self._settings = None self._feature_settings_checked = False self._settings_lock = _threading.Lock() self._polling_rate = None @@ -323,6 +321,13 @@ class Device: self._backlight = _hidpp20.get_backlight(self) return self._backlight + @property + def profiles(self): + if self._profiles is None: + if self.online and self.protocol >= 2.0: + self._profiles = _hidpp20.get_profiles(self) + return self._profiles + @property def registers(self): if not self._registers: diff --git a/lib/logitech_receiver/hidpp20.py b/lib/logitech_receiver/hidpp20.py index 0b9325ee..aba4a3f9 100644 --- a/lib/logitech_receiver/hidpp20.py +++ b/lib/logitech_receiver/hidpp20.py @@ -29,6 +29,8 @@ from struct import pack as _pack from struct import unpack as _unpack from typing import List +import yaml as _yaml + from . import special_keys from .common import BATTERY_APPROX as _BATTERY_APPROX from .common import FirmwareInfo as _FirmwareInfo @@ -37,6 +39,7 @@ from .common import NamedInt as _NamedInt from .common import NamedInts as _NamedInts from .common import UnsortedNamedInts as _UnsortedNamedInts from .common import bytes2int as _bytes2int +from .common import crc16 as _crc16 from .common import int2bytes as _int2bytes _log = getLogger(__name__) @@ -1141,6 +1144,286 @@ class Backlight: self.device.feature_request(FEATURE.BACKLIGHT2, 0x10, data_bytes) +ButtonBehaviors = _NamedInts(MacroExecute=0x0, MacroStop=0x1, MacroStopAll=0x2, Send=0x8, Function=0x9) +ButtonMappingTypes = _NamedInts(No_Action=0x0, Button=0x1, Modifier_And_Key=0x2, Consumer_Key=0x3) +ButtonFunctions = _NamedInts( + No_Action=0x0, + Tilt_Left=0x1, + Tilt_Right=0x2, + Next_DPI=0x3, + Previous_DPI=0x4, + Cycle_DPI=0x5, + Default_DPI=0x6, + Shift_DPI=0x7, + Next_Profile=0x8, + Previous_Profile=0x9, + Cycle_Profile=0xA, + G_Shift=0xB, + Battery_Status=0xC +) +ButtonButtons = special_keys.MOUSE_BUTTONS +ButtonModifiers = special_keys.modifiers +ButtonKeys = special_keys.USB_HID_KEYCODES +ButtonConsumerKeys = special_keys.HID_CONSUMERCODES + + +class Button: + """A button mapping""" + + def __init__(self, **kwargs): + self.behavior = None + for key, val in kwargs.items(): + setattr(self, key, val) + + @classmethod + def from_yaml(cls, loader, node): + args = loader.construct_mapping(node) + return cls(**args) + + @classmethod + def to_yaml(cls, dumper, data): + return dumper.represent_mapping('!Button', data.__dict__, flow_style=True) + + @classmethod + def from_bytes(cls, bytes): + behavior = ButtonBehaviors[bytes[0] >> 4] + if behavior == ButtonBehaviors.MacroExecute or behavior == ButtonBehaviors.MacroStop: + sector = (bytes[0] & 0x0F) << 8 + bytes[1] + address = bytes[2] << 8 + bytes[3] + result = cls(behavior=behavior, sector=sector, address=address) + elif behavior == ButtonBehaviors.Send: + mapping_type = ButtonMappingTypes[bytes[1]] + if mapping_type == ButtonMappingTypes.Button: + value = ButtonButtons[(bytes[2] << 8) + bytes[3]] + result = cls(behavior=behavior, type=mapping_type, value=value) + elif mapping_type == ButtonMappingTypes.Modifier_And_Key: + modifiers = ButtonModifiers[bytes[2]] + value = ButtonKeys[bytes[3]] + result = cls(behavior=behavior, type=mapping_type, modifiers=modifiers, value=value) + elif mapping_type == ButtonMappingTypes.Consumer_Key: + value = ButtonConsumerKeys[(bytes[2] << 8) + bytes[3]] + result = cls(behavior=behavior, type=mapping_type, value=value) + elif behavior == ButtonBehaviors.Function: + value = ButtonFunctions[bytes[1]] + result = cls(behavior=behavior, value=value) + else: + result = cls(behavior=None) + return result + + def to_bytes(self): + bytes = _int2bytes(self.behavior << 4, 1) if self.behavior is not None else None + if self.behavior == ButtonBehaviors.MacroExecute or self.behavior == ButtonBehaviors.MacroStop: + bytes = _int2bytes(self.sector, 2) + _int2bytes(self.address, 2) + bytes[0] += self.behavior << 4 + elif self.behavior == ButtonBehaviors.Send: + bytes += _int2bytes(self.type, 1) + if self.type == ButtonMappingTypes.Button: + bytes += _int2bytes(self.value, 2) + elif self.type == ButtonMappingTypes.Modifier_And_Key: + bytes += _int2bytes(self.modifiers, 1) + bytes += _int2bytes(self.value, 1) + elif self.type == ButtonMappingTypes.Consumer_Key: + bytes += _int2bytes(self.value, 2) + elif self.behavior == ButtonBehaviors.Function: + bytes += _int2bytes(self.value, 1) + b'\xff\x00' + else: + bytes = b'\xff\xff\xff\xff' + return bytes + + def __repr__(self): + return '%s{%s}' % ( + self.__class__.__name__, ', '.join([str(key) + ':' + str(val) for key, val in self.__dict__.items()]) + ) + + +_yaml.SafeLoader.add_constructor('!Button', Button.from_yaml) +_yaml.add_representer(Button, Button.to_yaml) + + +# Doesn't handle light information (feature x8070) +class OnboardProfile: + """A single onboard profile""" + + def __init__(self, **kwargs): + for key, val in kwargs.items(): + setattr(self, key, val) + + @classmethod + def from_yaml(cls, loader, node): + args = loader.construct_mapping(node) + return cls(**args) + + @classmethod + def to_yaml(cls, dumper, data): + return dumper.represent_mapping('!OnboardProfile', data.__dict__) + + @classmethod + def from_bytes(cls, sector, enabled, buttons, gbuttons, bytes): + return cls( + sector=sector, + enabled=enabled, + report_rate=bytes[0], + resolution_default_index=bytes[1], + resolution_shift_index=bytes[2], + resolutions=[_unpack(' 0x03 or macro != 0x01: + return + count, oob, buttons, sectors, size, shift = _unpack('!BBBBHB', response[3:10]) + gbuttons = buttons if (shift & 0x3 == 0x2) else 0 + i = 0 + profiles = {} + chunk = device.feature_request(FEATURE.ONBOARD_PROFILES, 0x50, 0, 0, 0, i) + while chunk[0:2] != b'\xff\xff': + sector, enabled = _unpack('!HB', chunk[0:3]) + profiles[i + 1] = OnboardProfile.from_dev(device, i, sector, size, enabled, buttons, gbuttons) + i += 1 + chunk = device.feature_request(FEATURE.ONBOARD_PROFILES, 0x50, 0, 0, 0, i * 4) + return cls(count=count, buttons=buttons, gbuttons=gbuttons, sectors=sectors, size=size, profiles=profiles) + + def to_bytes(self): + bytes = b'' + for i in range(1, len(self.profiles) + 1): + bytes += _int2bytes(self.profiles[i].sector, 2) + _int2bytes(self.profiles[i].enabled, 1) + b'\x00' + bytes += b'\xff\xff\x00\x00' # marker after last profile + while len(bytes) < self.size - 2: # leave room for CRC + bytes += b'\xff' + bytes += _int2bytes(_crc16(bytes), 2) + return bytes + + @classmethod + def read_sector(cls, dev, sector, s): # doesn't check for valid sector or length + bytes = b'' + o = 0 + while o < s - 15: + chunk = dev.feature_request(FEATURE.ONBOARD_PROFILES, 0x50, sector >> 8, sector & 0xFF, o >> 8, o & 0xFF) + bytes += chunk + o += 16 + chunk = dev.feature_request(FEATURE.ONBOARD_PROFILES, 0x50, sector >> 8, sector & 0xFF, (s - 16) >> 8, (s - 16) & 0xFF) + bytes += chunk[16 + o - s:] # the last chunk has to be read in an awkward way + return bytes + + @classmethod + def write_sector(cls, device, s, bs): # doesn't check for valid sector or length + rbs = OnboardProfiles.read_sector(device, s, len(bs)) + if rbs[:-2] == bs[:-2]: + return False + device.feature_request(FEATURE.ONBOARD_PROFILES, 0x60, s >> 8, s & 0xFF, 0, 0, len(bs) >> 8, len(bs) & 0xFF) + o = 0 + while o < len(bs) - 1: + device.feature_request(FEATURE.ONBOARD_PROFILES, 0x70, bs[o:o + 16]) + o += 16 + device.feature_request(FEATURE.ONBOARD_PROFILES, 0x80) + return True + + def write(self, device): # doesn't check for valid sectors or length + try: + written = 1 if OnboardProfiles.write_sector(device, 0, self.to_bytes()) else 0 + except Exception as e: + _log.warn('Exception writing onboard profile control sector') + raise e + for p in self.profiles.values(): + try: + written += 1 if OnboardProfiles.write_sector(device, p.sector, p.to_bytes(self.size)) else 0 + except Exception as e: + _log.warn(f'Exception writing onboard profile sector {p.sector}') + raise e + return written + + def show(self): + print(_yaml.dump(self)) + + +_yaml.SafeLoader.add_constructor('!OnboardProfiles', OnboardProfiles.from_yaml) +_yaml.add_representer(OnboardProfiles, OnboardProfiles.to_yaml) + # # # @@ -1433,6 +1716,13 @@ def get_backlight(device): return Backlight(device) +def get_profiles(device): + if getattr(device, '_profiles', None) is not None: + return device._profiles + if FEATURE.ONBOARD_PROFILES in device.features: + return OnboardProfiles.from_device(device) + + def get_mouse_pointer_info(device): pointer_info = feature_request(device, FEATURE.MOUSE_POINTER) if pointer_info: diff --git a/lib/solaar/cli/__init__.py b/lib/solaar/cli/__init__.py index ace57f90..782067e9 100644 --- a/lib/solaar/cli/__init__.py +++ b/lib/solaar/cli/__init__.py @@ -56,6 +56,15 @@ def _create_parser(): ) 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( 'config', help='read/write device-specific settings', @@ -198,7 +207,7 @@ def run(cli_args=None, hidraw_path=None): assert action in actions try: - if action == 'show' or action == 'probe' or action == 'config': + if action == 'show' or action == 'probe' or action == 'config' or action == 'profiles': c = list(_receivers_and_devices(hidraw_path)) else: c = list(_receivers(hidraw_path)) diff --git a/lib/solaar/cli/profiles.py b/lib/solaar/cli/profiles.py new file mode 100644 index 00000000..b4da2f81 --- /dev/null +++ b/lib/solaar/cli/profiles.py @@ -0,0 +1,57 @@ +# -*- 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 yaml as _yaml + +from logitech_receiver.hidpp20 import OnboardProfiles as _OnboardProfiles + + +def run(receivers, args, find_receiver, find_device): + assert receivers + assert args.device + + device_name = args.device.lower() + profiles_file = args.profiles + + dev = None + for dev in find_device(receivers, device_name): + if dev.ping(): + break + dev = None + + if not dev: + raise Exception("no online device found matching '%s'" % device_name) + + if not (dev.online and dev.profiles): + print(f'Device {dev.name} is either offline or has no onboard profiles') + elif not profiles_file: + print(f'Dumping profiles from {dev.name}') + print(_yaml.dump(dev.profiles)) + else: + try: + with open(profiles_file, 'r') as f: + print(f'Reading profiles from {profiles_file}') + profiles = _yaml.safe_load(f) + if not isinstance(profiles, _OnboardProfiles): + print('Profiles file does not contain onboard profiles') + else: + print(f'Loading profiles into {dev.name}') + written = profiles.write(dev) + print(f'Wrote {written} sectors to {dev.name}') + except Exception as exc: + print('Profiles not written:', exc)