definition.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "github.com/spf13/cobra"
  10. intrgb "netdome.biz/paul/qmk-rgb/internal/rgb"
  11. "netdome.biz/paul/qmk-rgb/internal/via"
  12. )
  13. // definitionHost serves the definitions VIA ships, one file per board, named by
  14. // vendor and product ID. The path segment is the definition generation, not the
  15. // protocol version: a board gets v3 and falls back to v2.
  16. const definitionHost = "https://www.usevia.app"
  17. // httpGet is a seam so a fetch can be tested without a network. It returns the
  18. // body and the status code.
  19. var httpGet = func(url string) ([]byte, int, error) {
  20. resp, err := http.Get(url)
  21. if err != nil {
  22. return nil, 0, err
  23. }
  24. defer resp.Body.Close()
  25. body, err := io.ReadAll(resp.Body)
  26. return body, resp.StatusCode, err
  27. }
  28. func NewDefinitionCmd() *cobra.Command {
  29. cmd := &cobra.Command{
  30. Use: "definition",
  31. Short: "Manage keyboard definition files",
  32. Long: "A keyboard's effect names come from a VIA definition file, the same one VIA\n" +
  33. "itself uses. `fetch` downloads the file for the connected keyboard into the\n" +
  34. "data directory; to use a file you already have, put it in that directory or\n" +
  35. "pass it with --definition.",
  36. }
  37. cmd.AddCommand(newDefinitionFetchCmd(), newDefinitionListCmd())
  38. return cmd
  39. }
  40. func newDefinitionFetchCmd() *cobra.Command {
  41. return &cobra.Command{
  42. Use: "fetch",
  43. Short: "Download the definition file for the connected keyboard",
  44. Long: "Identify the connected keyboard, then download its VIA definition into the\n" +
  45. "data directory. VIA does not carry a definition for every board, and answers\n" +
  46. "an unknown one with its own web page, so a downloaded file is parsed and\n" +
  47. "matched against the keyboard before it is stored.",
  48. Args: cobra.NoArgs,
  49. RunE: runDefinitionFetch,
  50. }
  51. }
  52. func newDefinitionListCmd() *cobra.Command {
  53. return &cobra.Command{
  54. Use: "list",
  55. Short: "List the definition files in the data directory",
  56. Args: cobra.NoArgs,
  57. RunE: runDefinitionList,
  58. }
  59. }
  60. func runDefinitionFetch(cmd *cobra.Command, args []string) error {
  61. target, err := prepareTarget()
  62. if err != nil {
  63. return err
  64. }
  65. def, err := fetchDefinition(target.Device.VendorID, target.Device.ProductID)
  66. if err != nil {
  67. return err
  68. }
  69. dir, err := ensureDefinitionsDir()
  70. if err != nil {
  71. return err
  72. }
  73. path := filepath.Join(dir, definitionFileName(def))
  74. if err := os.WriteFile(path, []byte(def.raw), 0o644); err != nil {
  75. return fmt.Errorf("write %s: %w", path, err)
  76. }
  77. fmt.Fprintf(cmd.OutOrStdout(), "Saved definition for %s (0x%04X/0x%04X) to %s\n",
  78. def.Definition.Name, def.Definition.VendorID, def.Definition.ProductID, path)
  79. for _, ch := range def.channels {
  80. fmt.Fprintf(cmd.OutOrStdout(), " %-10s %d effects\n", ch.Subsystem(), len(def.Definition.Catalog.Effects(ch)))
  81. }
  82. return nil
  83. }
  84. func runDefinitionList(cmd *cobra.Command, args []string) error {
  85. dir, err := definitionsDir()
  86. if err != nil {
  87. return err
  88. }
  89. if _, statErr := os.Stat(dir); os.IsNotExist(statErr) {
  90. if jsonOutput {
  91. return encodeJSON(cmd.OutOrStdout(), struct {
  92. Directory string `json:"directory"`
  93. Definitions []definitionLine `json:"definitions"`
  94. }{Directory: dir, Definitions: []definitionLine{}})
  95. }
  96. fmt.Fprintf(cmd.OutOrStdout(), "No definition directory yet at %s; run `definition fetch` "+
  97. "or put a manufacturer file there\n", dir)
  98. return nil
  99. }
  100. defs, err := intrgb.LoadDefinitionsDir(dir)
  101. if err != nil {
  102. return err
  103. }
  104. lines := make([]definitionLine, 0, len(defs))
  105. for _, def := range defs {
  106. line := definitionLine{
  107. Name: def.Name,
  108. VendorID: fmt.Sprintf("0x%04X", def.VendorID),
  109. ProductID: fmt.Sprintf("0x%04X", def.ProductID),
  110. Path: def.Path,
  111. }
  112. for _, ch := range via.LightingChannels {
  113. effects := def.Catalog.Effects(ch)
  114. if len(effects) == 0 {
  115. continue
  116. }
  117. // The label is what VIA calls the channel, so the name here is the
  118. // name the user sees there. The subsystem stays as the fallback and
  119. // as the spelling that works everywhere.
  120. name := def.Labels[uint16(ch)]
  121. if name == "" {
  122. name = ch.Subsystem()
  123. }
  124. line.Channels = append(line.Channels, definitionChannel{
  125. Name: name,
  126. Subsystem: ch.Subsystem(),
  127. Channel: uint8(ch),
  128. Effects: len(effects),
  129. })
  130. }
  131. lines = append(lines, line)
  132. }
  133. if jsonOutput {
  134. return encodeJSON(cmd.OutOrStdout(), struct {
  135. Directory string `json:"directory"`
  136. Definitions []definitionLine `json:"definitions"`
  137. }{Directory: dir, Definitions: lines})
  138. }
  139. if len(lines) == 0 {
  140. fmt.Fprintf(cmd.OutOrStdout(), "No definition files in %s\n", dir)
  141. return nil
  142. }
  143. for _, line := range lines {
  144. fmt.Fprintf(cmd.OutOrStdout(), "%s (%s/%s) %s\n", line.Name, line.VendorID, line.ProductID, line.Path)
  145. for _, ch := range line.Channels {
  146. fmt.Fprintf(cmd.OutOrStdout(), " %-10s %-10s %d effects\n", ch.Name, ch.Subsystem, ch.Effects)
  147. }
  148. }
  149. return nil
  150. }
  151. // definitionLine is one definition file as the list command reports it. The
  152. // identifiers are hex strings, the way the files themselves spell them, so the
  153. // two can be compared by eye.
  154. type definitionLine struct {
  155. Name string `json:"name"`
  156. VendorID string `json:"vendorId"`
  157. ProductID string `json:"productId"`
  158. Path string `json:"path"`
  159. Channels []definitionChannel `json:"channels"`
  160. }
  161. // definitionChannel is one lighting channel a definition names effects for.
  162. type definitionChannel struct {
  163. Name string `json:"name"`
  164. Subsystem string `json:"subsystem"`
  165. Channel uint8 `json:"channel"`
  166. Effects int `json:"effects"`
  167. }
  168. // fetchedDefinition is a definition together with the bytes it came from, so it
  169. // can be stored exactly as it was served.
  170. type fetchedDefinition struct {
  171. Definition *intrgb.Definition
  172. raw string
  173. channels []via.Channel
  174. }
  175. // fetchDefinition downloads the definition for a board. It is separate from the
  176. // command so the download and the checks can be tested on their own.
  177. func fetchDefinition(vendorID, productID uint16) (*fetchedDefinition, error) {
  178. vpid := intrgb.VendorProductID(vendorID, productID)
  179. var lastReason string
  180. for _, version := range []string{"v3", "v2"} {
  181. url := fmt.Sprintf("%s/definitions/%s/%d.json", definitionHost, version, vpid)
  182. body, status, err := httpGet(url)
  183. if err != nil {
  184. lastReason = err.Error()
  185. continue
  186. }
  187. if status != http.StatusOK {
  188. lastReason = fmt.Sprintf("HTTP %d", status)
  189. continue
  190. }
  191. def, err := intrgb.ParseDefinition(url, body)
  192. if err != nil {
  193. lastReason = "the server did not return a definition"
  194. continue
  195. }
  196. if !def.Matches(vendorID, productID) {
  197. lastReason = fmt.Sprintf("it is a definition for 0x%04X/0x%04X", def.VendorID, def.ProductID)
  198. continue
  199. }
  200. return &fetchedDefinition{
  201. Definition: def,
  202. raw: string(body),
  203. channels: via.LightingChannels,
  204. }, nil
  205. }
  206. return nil, fmt.Errorf("no definition for this keyboard (0x%04X/0x%04X) at %s: %s; "+
  207. "if the manufacturer publishes one, put it in %s or pass --definition",
  208. vendorID, productID, definitionHost, lastReason, intrgb.DefinitionsDir)
  209. }
  210. // definitionFileName names a stored definition after the board, so a directory
  211. // of them is readable.
  212. func definitionFileName(def *fetchedDefinition) string {
  213. name := def.Definition.Name
  214. var b strings.Builder
  215. for _, r := range strings.ToLower(name) {
  216. switch {
  217. case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
  218. b.WriteRune(r)
  219. default:
  220. b.WriteRune('_')
  221. }
  222. }
  223. slug := strings.Trim(b.String(), "_")
  224. if slug == "" {
  225. slug = "keyboard"
  226. }
  227. return fmt.Sprintf("%s_0x%04X_0x%04X.json", slug, def.Definition.VendorID, def.Definition.ProductID)
  228. }