rgb.go 14 KB

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