Files
rat8plus-rgb/rat8.py
T

206 lines
7.8 KiB
Python
Raw Normal View History

"""Mad Catz R.A.T. 8+ (USB 12CF:0C05) lighting control without the vendor software.
Protocol taken from the vendor's .NET app (Controllers/RAT8P.dll, decompiled).
The vendor channel is interface 1, collection 3 (usage page 0x08). All traffic is
HID feature reports, padded to 2053 bytes:
report 12 command [12, 0xC4, cmd, args...]; reply via GetFeature(12) = [0xB0, ...]
cmd 0 = reload settings from storage (makes a profile write take effect)
cmd 8 = firmware version -> [B0 55 AA ver]
cmd 12 = read profile slot -> GetFeature(5)
cmd 22 = active profile -> [B0 C6 slot]
report 5 profile [5, 0, slot, checksum, 733 bytes]; ack [B0 05 slot x x]
read reply [5, B0, slot, checksum, 733 bytes]
LED block: 3 zones of 191 bytes starting at profile offset 160.
zone 0 = under the scroll wheel, zone 1 = palm logo, zone 2 = under the thumb wheel
static: [1, brightness, R, G, B]
breathe: [2, 0,0,0,0, period_s lo, hi, 0,0,0,0, 1, brightness, R, G, B]
Every profile write goes to the mouse's own storage (~160 ms), so don't stream
colours that way: it wears the flash.
Live control (found by disassembling firmware v18, not used by the vendor app):
[12, C4, 3, 4, 1, zone, R, G, B] set zone 0-2 straight on the LED driver, RAM only.
The first one pauses the mouse's own effect.
[12, C4, 3, 4, 2, 1, R, G, B] set all zones
[12, C4, 3, 3, 3] release: back to the stored profile lighting
"""
import argparse, json, sys, time
import hid
VID, PID = 0x12CF, 0x0C05
FEAT_LEN = 2053
PROFILE_LEN = 733
LED_OFFSET = 160
LED_ZONE_LEN = 191
ZONES = {"scroll": 0, "palm": 1, "thumb": 2}
def checksum(data):
return (256 - (sum(data) & 0xFF)) & 0xFF
class Rat8:
def __init__(self):
paths = [d["path"] for d in hid.enumerate(VID, PID) if d["usage_page"] == 0x08]
if not paths:
raise SystemExit("R.A.T. 8+ vendor interface not found (is the mouse plugged in?)")
self.h = hid.device()
self.h.open_path(paths[0])
def set_feature(self, data):
if self.h.send_feature_report(bytes(data) + bytes(FEAT_LEN - len(data))) < 0:
raise IOError("SetFeature failed")
def get_feature(self, rid):
return bytes(self.h.get_feature_report(rid, FEAT_LEN))
def cmd(self, *args):
self.set_feature([12, 0xC4, *args])
def _wait(self, rid, ok, tries=20, delay=0.05):
for _ in range(tries):
r = self.get_feature(rid)
if ok(r):
return r
time.sleep(delay)
return None
def firmware(self):
self.cmd(8); time.sleep(0.05)
r = self._wait(12, lambda r: r[:3] == b"\xb0\x55\xaa")
return r[3] if r else None
def active_slot(self):
self.cmd(22); time.sleep(0.05)
r = self._wait(12, lambda r: r[0] == 0xB0 and r[1] == 0xC6)
if not r:
raise IOError("could not read the active profile")
return r[2]
def read_profile(self, slot):
self.cmd(12, slot); time.sleep(0.1)
r = self._wait(5, lambda r: r[0] == 5 and r[1] == 0xB0 and r[2] == slot
and r[3] != 0 and r[3] == checksum(r[4:4 + 736]), tries=10, delay=0.1)
if not r:
raise IOError(f"could not read profile {slot}")
return bytearray(r[4:4 + PROFILE_LEN])
def write_profile(self, slot, data):
assert len(data) == PROFILE_LEN
self.set_feature([5, 0, slot, checksum(data), *data])
r = self._wait(12, lambda r: r[0] == 0xB0 and r[1] == 5 and r[2] == slot and r[3] == r[4],
tries=25, delay=0.02)
if not r:
raise IOError(f"mouse did not confirm the write to profile {slot}")
def reload(self):
self.cmd(0)
def set_zone(p, zone, block):
"""Write block into a zone; None entries keep the byte already there (as the vendor app does)."""
o = LED_OFFSET + zone * LED_ZONE_LEN
for i, v in enumerate(block):
if v is not None:
p[o + i] = v
def static_block(rgb, brightness):
return [1, brightness, *rgb]
def breathe_block(rgb, brightness, period):
K = None
return [2, K, K, K, K, period & 0xFF, period >> 8, K, K, K, K, 1, brightness, *rgb]
def parse_color(s):
s = s.lstrip("#")
if len(s) != 6:
raise argparse.ArgumentTypeError(f"bad colour {s!r}, use RRGGBB")
return tuple(int(s[i:i + 2], 16) for i in (0, 2, 4))
def zone_colors(args):
"""Return {zone_index: rgb}; one colour means all zones."""
cols = args.colors
if len(cols) == 1:
return {z: cols[0] for z in range(3)}
if len(cols) == 3:
return {ZONES["scroll"]: cols[0], ZONES["palm"]: cols[1], ZONES["thumb"]: cols[2]}
raise SystemExit("give 1 colour (all zones) or 3 colours (scroll palm thumb)")
def apply(m, args, build):
slots = range(4) if args.all_slots else [m.active_slot()]
for slot in slots:
p = m.read_profile(slot)
for zone, rgb in zone_colors(args).items():
set_zone(p, zone, build(rgb))
m.write_profile(slot, p)
print(f"profile {slot}: written")
m.reload()
def main():
ap = argparse.ArgumentParser(description="Mad Catz R.A.T. 8+ lighting control")
sub = ap.add_subparsers(dest="cmd", required=True)
sub.add_parser("info", help="firmware, active profile and current LED settings")
for name, hlp in (("static", "solid colours"), ("breathe", "breathing effect")):
sp = sub.add_parser(name, help=hlp)
sp.add_argument("colors", nargs="+", type=parse_color,
help="RRGGBB, either one for all zones or three: scroll palm thumb")
sp.add_argument("-b", "--brightness", type=int, default=255)
sp.add_argument("--all-slots", action="store_true", help="write all 4 profiles, not just the active one")
if name == "breathe":
sp.add_argument("-p", "--period", type=int, default=3, help="seconds per breath")
sp = sub.add_parser("live", help="set colours live (RAM only, no storage write; lost on replug)")
sp.add_argument("colors", nargs="+", type=parse_color, help="RRGGBB, one or three: scroll palm thumb")
sub.add_parser("release", help="hand the LEDs back to the mouse's own stored lighting")
sp = sub.add_parser("off", help="turn all LEDs off")
sp.add_argument("--all-slots", action="store_true")
sub.add_parser("backup", help="save all 4 profiles to a JSON file").add_argument("file")
sub.add_parser("restore", help="write profiles back from a backup file").add_argument("file")
args = ap.parse_args()
m = Rat8()
if args.cmd == "info":
slot = m.active_slot()
print("firmware:", m.firmware(), " active profile:", slot)
p = m.read_profile(slot)
for name, z in ZONES.items():
o = LED_OFFSET + z * LED_ZONE_LEN
print(f" {name:6} {p[o:o + 16].hex(' ')}")
elif args.cmd == "static":
apply(m, args, lambda rgb: static_block(rgb, args.brightness))
elif args.cmd == "breathe":
apply(m, args, lambda rgb: breathe_block(rgb, args.brightness, args.period))
elif args.cmd == "live":
for zone, rgb in zone_colors(args).items():
m.cmd(3, 4, 1, zone, *rgb)
elif args.cmd == "release":
m.cmd(3, 3, 3)
elif args.cmd == "off":
args.colors = [(0, 0, 0)]
apply(m, args, lambda rgb: static_block(rgb, 0))
elif args.cmd == "backup":
data = {str(s): m.read_profile(s).hex() for s in range(4)}
json.dump(data, open(args.file, "w"), indent=1)
print("saved", args.file)
elif args.cmd == "restore":
data = json.load(open(args.file))
for s, hx in data.items():
if hx:
m.write_profile(int(s), bytearray.fromhex(hx))
print(f"profile {s}: restored")
m.reload()
if __name__ == "__main__":
main()