rgb.go 14 KB

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