rgb.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. intdevice "netdome.biz/paul/qmk-rgb/internal/device"
  7. intrgb "netdome.biz/paul/qmk-rgb/internal/rgb"
  8. "netdome.biz/paul/qmk-rgb/internal/via"
  9. )
  10. type zoneProtocol interface {
  11. SetValue(via.Channel, uint8, uint8) error
  12. SetColor(via.Channel, uint8, uint8) error
  13. }
  14. type rgbProtocol interface {
  15. zoneProtocol
  16. GetValue(via.Channel, uint8) ([]byte, error)
  17. DetectChannels() ([]via.Channel, error)
  18. Close() error
  19. }
  20. // keyboardFor is a seam for tests; it reads the optional keyboards.json.
  21. var keyboardFor = intdevice.KeyboardFor
  22. // targetDeviceData is everything a command needs before it opens the keyboard.
  23. type targetDeviceData struct {
  24. Device intdevice.Device
  25. Display map[uint16]string
  26. // Alternatives are the names a channel also answers to besides the one its
  27. // definition gives it, so a name the user already knows keeps working.
  28. Alternatives map[uint16][]string
  29. // Requested is nil when no --zone was given, which means every channel
  30. // the keyboard has.
  31. Requested []via.Channel
  32. }
  33. // prepareTarget resolves the keyboard, its display names and the requested
  34. // channels. Enumeration does not open a HID handle, so an unusable --zone value
  35. // is still rejected before the device is opened.
  36. var prepareTarget = func() (targetDeviceData, error) {
  37. devices, err := discoverAll()
  38. if err != nil {
  39. return targetDeviceData{}, fmt.Errorf("discover: %w", err)
  40. }
  41. dev, err := selectDevice(devices, targetDevice)
  42. if err != nil {
  43. return targetDeviceData{}, err
  44. }
  45. keyboard, _, err := keyboardFor(dev.VendorID, dev.ProductID)
  46. if err != nil {
  47. return targetDeviceData{}, err
  48. }
  49. // The definition's own names for the channels win, because they are the names
  50. // VIA shows, and keyboards.json keeps its names as alternatives so a command
  51. // written before the definition arrived still resolves.
  52. display, alternatives := applyDefinitionLabels(keyboard.Channels, dev.VendorID, dev.ProductID)
  53. keyboard.Channels = display
  54. requested, err := resolveZoneName(targetZone, display, alternatives)
  55. if err != nil {
  56. return targetDeviceData{}, err
  57. }
  58. return targetDeviceData{
  59. Device: dev,
  60. Display: keyboard.Channels,
  61. Alternatives: alternatives,
  62. Requested: requested,
  63. }, nil
  64. }
  65. func forEachChannel(channels []via.Channel, fn func(via.Channel) error) error {
  66. for _, ch := range channels {
  67. if err := fn(ch); err != nil {
  68. return err
  69. }
  70. }
  71. return nil
  72. }
  73. func setValueOnChannels(proto zoneProtocol, channels []via.Channel, param, value uint8) error {
  74. return forEachChannel(channels, func(ch via.Channel) error {
  75. return proto.SetValue(ch, param, value)
  76. })
  77. }
  78. // zoneResult records what was requested for a zone and what the keyboard
  79. // reported afterwards. The two differ on real hardware: the Impact 80 clamps
  80. // brightness at 160 on the logo and side channels and scales it up to 255 on
  81. // the backlight channel.
  82. type zoneResult struct {
  83. Name string
  84. Requested uint8
  85. Applied uint8
  86. }
  87. // Mismatch reports whether the keyboard applied something other than the
  88. // requested value.
  89. func (r zoneResult) Mismatch() bool { return r.Applied != r.Requested }
  90. // anyMismatch reports whether any zone deviated from the request.
  91. func anyMismatch(results []zoneResult) bool {
  92. for _, r := range results {
  93. if r.Mismatch() {
  94. return true
  95. }
  96. }
  97. return false
  98. }
  99. // formatResults renders one line stating what each selected zone actually
  100. // holds, so a partial application is visible instead of being summarised as
  101. // the value that was asked for.
  102. func formatResults(label string, results []zoneResult) string {
  103. var b strings.Builder
  104. b.WriteString(label)
  105. for _, r := range results {
  106. fmt.Fprintf(&b, " %s %d", r.Name, r.Applied)
  107. }
  108. if len(results) > 0 {
  109. fmt.Fprintf(&b, " (requested %d)", results[0].Requested)
  110. }
  111. return b.String()
  112. }
  113. // readBackValues reads one value ID from every channel, in the order given.
  114. // Every verified set reads back through this, so a parameter that needs no new
  115. // read-back path reuses it.
  116. func readBackValues(proto rgbProtocol, channels []via.Channel, display map[uint16]string, param uint8) ([]uint8, error) {
  117. values := make([]uint8, 0, len(channels))
  118. for _, ch := range channels {
  119. raw, err := proto.GetValue(ch, param)
  120. if err != nil {
  121. return nil, fmt.Errorf("read back value 0x%02x for %s: %w", param, channelName(ch, display), err)
  122. }
  123. if len(raw) == 0 {
  124. return nil, fmt.Errorf("read back value 0x%02x for %s: empty response", param, channelName(ch, display))
  125. }
  126. values = append(values, raw[0])
  127. }
  128. return values, nil
  129. }
  130. // setValueVerified writes one value ID to every zone and reads each back, so a
  131. // clamped or rescaled value is reported instead of silently claimed as set.
  132. // The firmware transform differs per channel and per value ID, so the read-back
  133. // is not optional for any parameter the keyboard rescales.
  134. func setValueVerified(proto rgbProtocol, channels []via.Channel, display map[uint16]string, param, value uint8) ([]zoneResult, error) {
  135. if err := setValueOnChannels(proto, channels, param, value); err != nil {
  136. return nil, err
  137. }
  138. applied, err := readBackValues(proto, channels, display, param)
  139. if err != nil {
  140. return nil, err
  141. }
  142. results := make([]zoneResult, 0, len(channels))
  143. for i, ch := range channels {
  144. results = append(results, zoneResult{Name: channelName(ch, display), Requested: value, Applied: applied[i]})
  145. }
  146. return results, nil
  147. }
  148. // effectResult records the effect a zone was asked for and the one the keyboard
  149. // holds afterwards. The Impact 80's logo and side channels do not take effect ID
  150. // 0: the firmware reads it as "lighting off" and leaves the mode register where
  151. // it was, so the effect that is still running has to be named rather than
  152. // reported as the requested one.
  153. type effectResult struct {
  154. Name string
  155. RequestedName string
  156. RequestedID uint8
  157. AppliedName string
  158. AppliedID uint8
  159. }
  160. // Mismatch reports whether the keyboard holds an effect other than the one
  161. // requested.
  162. func (r effectResult) Mismatch() bool { return r.AppliedID != r.RequestedID }
  163. // anyEffectMismatch reports whether any zone kept an effect of its own.
  164. func anyEffectMismatch(results []effectResult) bool {
  165. for _, r := range results {
  166. if r.Mismatch() {
  167. return true
  168. }
  169. }
  170. return false
  171. }
  172. // formatEffectResults names the effect each selected zone actually holds, so an
  173. // effect the keyboard refused is visible instead of being summarised as the one
  174. // that was asked for.
  175. func formatEffectResults(requestedName string, results []effectResult) string {
  176. var b strings.Builder
  177. b.WriteString("Effect")
  178. for _, r := range results {
  179. fmt.Fprintf(&b, " %s %q (%d)", r.Name, r.AppliedName, r.AppliedID)
  180. }
  181. if len(results) > 0 {
  182. fmt.Fprintf(&b, " (requested %q (%d))", requestedName, results[0].RequestedID)
  183. }
  184. return b.String()
  185. }
  186. // setEffectVerified writes one effect ID per channel and reads every channel
  187. // back. It cannot reuse setValueVerified, because one effect name is a
  188. // different index on each subsystem, so the requested value is carried per
  189. // target while the read-back stays shared.
  190. func setEffectVerified(proto rgbProtocol, targets []intrgb.EffectTarget, display map[uint16]string, catalog *intrgb.Catalog) ([]effectResult, error) {
  191. channels := make([]via.Channel, 0, len(targets))
  192. requested := make(map[via.Channel]uint8, len(targets))
  193. for _, t := range targets {
  194. if err := proto.SetValue(t.Channel, uint8(intrgb.EffectID), t.ID); err != nil {
  195. return nil, fmt.Errorf("set effect on %s: %w", channelName(t.Channel, display), err)
  196. }
  197. channels = append(channels, t.Channel)
  198. requested[t.Channel] = t.ID
  199. }
  200. applied, err := readBackValues(proto, channels, display, uint8(intrgb.EffectID))
  201. if err != nil {
  202. return nil, err
  203. }
  204. results := make([]effectResult, 0, len(channels))
  205. for i, ch := range channels {
  206. results = append(results, effectResult{
  207. Name: channelName(ch, display),
  208. RequestedName: catalog.EffectName(ch, requested[ch]),
  209. RequestedID: requested[ch],
  210. AppliedName: catalog.EffectName(ch, applied[i]),
  211. AppliedID: applied[i],
  212. })
  213. }
  214. return results, nil
  215. }
  216. // setBrightnessVerified writes the brightness and reads every channel back.
  217. func setBrightnessVerified(proto rgbProtocol, channels []via.Channel, display map[uint16]string, value uint8) ([]zoneResult, error) {
  218. return setValueVerified(proto, channels, display, uint8(intrgb.Brightness), value)
  219. }
  220. // setSpeedVerified writes the speed and reads every channel back.
  221. func setSpeedVerified(proto rgbProtocol, channels []via.Channel, display map[uint16]string, value uint8) ([]zoneResult, error) {
  222. return setValueVerified(proto, channels, display, uint8(intrgb.Speed), value)
  223. }
  224. // setModeVerified writes a raw effect index and reads every channel back. A
  225. // board that does not implement the index clamps it to the highest ID it holds
  226. // rather than refusing it, so the index the keyboard ended up with is the only
  227. // honest thing to print.
  228. func setModeVerified(proto rgbProtocol, channels []via.Channel, display map[uint16]string, value uint8) ([]zoneResult, error) {
  229. return setValueVerified(proto, channels, display, uint8(intrgb.EffectID), value)
  230. }
  231. // colorResult records the hue and saturation one channel holds after a color was
  232. // written to it. The color value ID carries two bytes, so both components are
  233. // read back: a keyboard that stored another saturation must not be reported as
  234. // having taken the requested color.
  235. type colorResult struct {
  236. Name string
  237. RequestedHue uint8
  238. RequestedSaturation uint8
  239. Hue uint8
  240. Saturation uint8
  241. }
  242. // Mismatch reports whether the keyboard stored something other than the
  243. // requested color.
  244. func (r colorResult) Mismatch() bool {
  245. return r.Hue != r.RequestedHue || r.Saturation != r.RequestedSaturation
  246. }
  247. // setColorVerified writes one hue and saturation to every channel and reads each
  248. // back, for the same reason setValueVerified exists: the command must report
  249. // what the keyboard holds, not what it was asked for.
  250. func setColorVerified(proto rgbProtocol, channels []via.Channel, display map[uint16]string, hue, saturation uint8) ([]colorResult, error) {
  251. if err := setColorOnChannels(proto, channels, hue, saturation); err != nil {
  252. return nil, err
  253. }
  254. results := make([]colorResult, 0, len(channels))
  255. for _, ch := range channels {
  256. raw, err := proto.GetValue(ch, uint8(intrgb.ColorValue))
  257. if err != nil {
  258. return nil, fmt.Errorf("read back color for %s: %w", channelName(ch, display), err)
  259. }
  260. if len(raw) < 2 {
  261. return nil, fmt.Errorf("read back color for %s: got %d bytes, want hue and saturation", channelName(ch, display), len(raw))
  262. }
  263. results = append(results, colorResult{
  264. Name: channelName(ch, display),
  265. RequestedHue: hue,
  266. RequestedSaturation: saturation,
  267. Hue: raw[0],
  268. Saturation: raw[1],
  269. })
  270. }
  271. return results, nil
  272. }
  273. func setColorOnChannels(proto zoneProtocol, channels []via.Channel, hue, saturation uint8) error {
  274. return forEachChannel(channels, func(ch via.Channel) error {
  275. return proto.SetColor(ch, hue, saturation)
  276. })
  277. }
  278. func setBrightnessOnChannels(proto zoneProtocol, channels []via.Channel, value uint8) error {
  279. return setValueOnChannels(proto, channels, uint8(intrgb.Brightness), value)
  280. }
  281. func setSpeedChannels(proto zoneProtocol, channels []via.Channel, value uint8) error {
  282. return setValueOnChannels(proto, channels, uint8(intrgb.Speed), value)
  283. }
  284. func disableLightingOnChannels(proto zoneProtocol, channels []via.Channel) error {
  285. return forEachChannel(channels, func(ch via.Channel) error {
  286. if err := proto.SetValue(ch, uint8(intrgb.EffectID), 0); err != nil {
  287. return err
  288. }
  289. return proto.SetValue(ch, uint8(intrgb.Brightness), 0)
  290. })
  291. }
  292. func enableLightingOnChannels(proto zoneProtocol, channels []via.Channel, catalog *intrgb.Catalog) error {
  293. return forEachChannel(channels, func(ch via.Channel) error {
  294. effect, ok := catalog.DefaultEffect(ch)
  295. if !ok {
  296. return fmt.Errorf("no default effect for %s", channelName(ch, nil))
  297. }
  298. if err := proto.SetValue(ch, uint8(intrgb.EffectID), effect); err != nil {
  299. return err
  300. }
  301. return proto.SetValue(ch, uint8(intrgb.Brightness), 160)
  302. })
  303. }
  304. func setModeOnChannels(proto zoneProtocol, channels []via.Channel, value uint8) error {
  305. return setValueOnChannels(proto, channels, uint8(intrgb.EffectID), value)
  306. }
  307. // openTarget opens the keyboard and resolves the requested channels against the
  308. // ones it actually has. It is a seam because a command needs all three: the
  309. // handle it writes to, the names it reports with, and the channels it may touch.
  310. var openTarget = func() (rgbProtocol, targetDeviceData, []via.Channel, error) {
  311. target, err := prepareTarget()
  312. if err != nil {
  313. return nil, targetDeviceData{}, nil, err
  314. }
  315. proto, err := via.New(target.Device)
  316. if err != nil {
  317. return nil, targetDeviceData{}, nil, fmt.Errorf("open protocol: %w", err)
  318. }
  319. channels, err := resolveChannels(proto, target)
  320. if err != nil {
  321. proto.Close()
  322. return nil, targetDeviceData{}, nil, err
  323. }
  324. return proto, target, channels, nil
  325. }
  326. // resolveChannels intersects the requested channels with the detected ones, and
  327. // refuses a name that resolves to a channel this keyboard does not have.
  328. func resolveChannels(proto rgbProtocol, target targetDeviceData) ([]via.Channel, error) {
  329. present, err := proto.DetectChannels()
  330. if err != nil {
  331. return nil, err
  332. }
  333. if err := displayNameConflicts(target.Display, present); err != nil {
  334. return nil, err
  335. }
  336. if target.Requested == nil {
  337. if len(present) == 0 {
  338. return nil, fmt.Errorf("this keyboard exposes no VIA lighting channels")
  339. }
  340. return present, nil
  341. }
  342. presentSet := make(map[via.Channel]bool, len(present))
  343. for _, ch := range present {
  344. presentSet[ch] = true
  345. }
  346. var found []via.Channel
  347. for _, ch := range target.Requested {
  348. if presentSet[ch] {
  349. found = append(found, ch)
  350. }
  351. }
  352. if len(found) == 0 {
  353. return nil, fmt.Errorf("channel %s is not present on this keyboard", target.Requested[0].Subsystem())
  354. }
  355. return found, nil
  356. }
  357. // lightingEnabled reports whether a channel is lit: a mode other than none and a
  358. // brightness above zero.
  359. func lightingEnabled(mode, brightness uint8) bool {
  360. return mode != 0 && brightness > 0
  361. }
  362. func ParseUint8(s string) (uint8, error) {
  363. v, err := strconv.ParseUint(s, 10, 8)
  364. if err != nil {
  365. return 0, fmt.Errorf("invalid value: %w", err)
  366. }
  367. return uint8(v), nil
  368. }