rgb.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. // formatEffectIDResults renders the same line as formatEffectResults, with the
  219. // numbers: the request was a number, and a board without a definition has no name
  220. // to put in its place.
  221. func formatEffectIDResults(results []effectResult) string {
  222. var b strings.Builder
  223. b.WriteString("Effect")
  224. for _, r := range results {
  225. fmt.Fprintf(&b, " %s %d", r.Name, r.AppliedID)
  226. }
  227. if len(results) > 0 {
  228. fmt.Fprintf(&b, " (requested %d)", results[0].RequestedID)
  229. }
  230. return b.String()
  231. }
  232. // colorResult records the hue and saturation one channel holds after a color was
  233. // written to it. The color value ID carries two bytes, so both components are
  234. // read back: a keyboard that stored another saturation must not be reported as
  235. // having taken the requested color.
  236. type colorResult struct {
  237. Name string
  238. RequestedHue uint8
  239. RequestedSaturation uint8
  240. Hue uint8
  241. Saturation uint8
  242. }
  243. // Mismatch reports whether the keyboard stored something other than the
  244. // requested color.
  245. func (r colorResult) Mismatch() bool {
  246. return r.Hue != r.RequestedHue || r.Saturation != r.RequestedSaturation
  247. }
  248. // setColorVerified writes one hue and saturation to every channel and reads each
  249. // back, for the same reason setValueVerified exists: the command must report
  250. // what the keyboard holds, not what it was asked for.
  251. func setColorVerified(proto rgbProtocol, channels []via.Channel, display map[uint16]string, hue, saturation uint8) ([]colorResult, error) {
  252. if err := setColorOnChannels(proto, channels, hue, saturation); err != nil {
  253. return nil, err
  254. }
  255. results := make([]colorResult, 0, len(channels))
  256. for _, ch := range channels {
  257. raw, err := proto.GetValue(ch, uint8(intrgb.ColorValue))
  258. if err != nil {
  259. return nil, fmt.Errorf("read back color for %s: %w", channelName(ch, display), err)
  260. }
  261. if len(raw) < 2 {
  262. return nil, fmt.Errorf("read back color for %s: got %d bytes, want hue and saturation", channelName(ch, display), len(raw))
  263. }
  264. results = append(results, colorResult{
  265. Name: channelName(ch, display),
  266. RequestedHue: hue,
  267. RequestedSaturation: saturation,
  268. Hue: raw[0],
  269. Saturation: raw[1],
  270. })
  271. }
  272. return results, nil
  273. }
  274. func setColorOnChannels(proto zoneProtocol, channels []via.Channel, hue, saturation uint8) error {
  275. return forEachChannel(channels, func(ch via.Channel) error {
  276. return proto.SetColor(ch, hue, saturation)
  277. })
  278. }
  279. func setBrightnessOnChannels(proto zoneProtocol, channels []via.Channel, value uint8) error {
  280. return setValueOnChannels(proto, channels, uint8(intrgb.Brightness), value)
  281. }
  282. func setSpeedChannels(proto zoneProtocol, channels []via.Channel, value uint8) error {
  283. return setValueOnChannels(proto, channels, uint8(intrgb.Speed), value)
  284. }
  285. func disableLightingOnChannels(proto zoneProtocol, channels []via.Channel) error {
  286. return forEachChannel(channels, func(ch via.Channel) error {
  287. if err := proto.SetValue(ch, uint8(intrgb.EffectID), 0); err != nil {
  288. return err
  289. }
  290. return proto.SetValue(ch, uint8(intrgb.Brightness), 0)
  291. })
  292. }
  293. func enableLightingOnChannels(proto zoneProtocol, channels []via.Channel, catalog *intrgb.Catalog) error {
  294. return forEachChannel(channels, func(ch via.Channel) error {
  295. effect, ok := catalog.DefaultEffect(ch)
  296. if !ok {
  297. return fmt.Errorf("no default effect for %s", channelName(ch, nil))
  298. }
  299. if err := proto.SetValue(ch, uint8(intrgb.EffectID), effect); err != nil {
  300. return err
  301. }
  302. return proto.SetValue(ch, uint8(intrgb.Brightness), 160)
  303. })
  304. }
  305. // openTarget opens the keyboard and resolves the requested channels against the
  306. // ones it actually has. It is a seam because a command needs all three: the
  307. // handle it writes to, the names it reports with, and the channels it may touch.
  308. var openTarget = func() (rgbProtocol, targetDeviceData, []via.Channel, error) {
  309. target, err := prepareTarget()
  310. if err != nil {
  311. return nil, targetDeviceData{}, nil, err
  312. }
  313. proto, err := via.New(target.Device)
  314. if err != nil {
  315. return nil, targetDeviceData{}, nil, fmt.Errorf("open protocol: %w", err)
  316. }
  317. channels, err := resolveChannels(proto, target)
  318. if err != nil {
  319. proto.Close()
  320. return nil, targetDeviceData{}, nil, err
  321. }
  322. return proto, target, channels, nil
  323. }
  324. // resolveChannels intersects the requested channels with the detected ones, and
  325. // refuses a name that resolves to a channel this keyboard does not have.
  326. func resolveChannels(proto rgbProtocol, target targetDeviceData) ([]via.Channel, error) {
  327. present, err := proto.DetectChannels()
  328. if err != nil {
  329. return nil, err
  330. }
  331. if err := displayNameConflicts(target.Display, present); err != nil {
  332. return nil, err
  333. }
  334. if target.Requested == nil {
  335. if len(present) == 0 {
  336. return nil, fmt.Errorf("this keyboard exposes no VIA lighting channels")
  337. }
  338. return present, nil
  339. }
  340. presentSet := make(map[via.Channel]bool, len(present))
  341. for _, ch := range present {
  342. presentSet[ch] = true
  343. }
  344. var found []via.Channel
  345. for _, ch := range target.Requested {
  346. if presentSet[ch] {
  347. found = append(found, ch)
  348. }
  349. }
  350. if len(found) == 0 {
  351. return nil, fmt.Errorf("channel %s is not present on this keyboard", target.Requested[0].Subsystem())
  352. }
  353. return found, nil
  354. }
  355. // lightingEnabled reports whether a channel is lit: a mode other than none and a
  356. // brightness above zero.
  357. func lightingEnabled(mode, brightness uint8) bool {
  358. return mode != 0 && brightness > 0
  359. }
  360. func ParseUint8(s string) (uint8, error) {
  361. v, err := strconv.ParseUint(s, 10, 8)
  362. if err != nil {
  363. return 0, fmt.Errorf("invalid value: %w", err)
  364. }
  365. return uint8(v), nil
  366. }