device.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package device
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "github.com/wobkey/rgb/internal/hid"
  8. )
  9. // Keyboard represents a VIA-compatible keyboard from keyboards.json.
  10. type Keyboard struct {
  11. Name string `json:"name"`
  12. VendorID uint16 `json:"vendorId"`
  13. ProductID uint16 `json:"productId"`
  14. Protocol string `json:"protocol"`
  15. VIAVersion int `json:"viaVersion"`
  16. LEDLayout string `json:"ledLayout"`
  17. }
  18. // Device represents a connected keyboard device.
  19. type Device struct {
  20. Keyboard
  21. Path string
  22. VendorID uint16
  23. ProductID uint16
  24. }
  25. // LoadKeyboards reads keyboard definitions from keyboards.json.
  26. func LoadKeyboards() ([]Keyboard, error) {
  27. path, err := findKeyboardsJSON()
  28. if err != nil {
  29. return nil, fmt.Errorf("find keyboards.json: %w", err)
  30. }
  31. data, err := os.ReadFile(path)
  32. if err != nil {
  33. return nil, fmt.Errorf("read keyboards.json: %w", err)
  34. }
  35. var keyboards []Keyboard
  36. if err := json.Unmarshal(data, &keyboards); err != nil {
  37. return nil, fmt.Errorf("parse keyboards.json: %w", err)
  38. }
  39. return keyboards, nil
  40. }
  41. // findKeyboardsJSON searches for keyboards.json in common locations.
  42. var findKeyboardsJSON = func() (string, error) {
  43. exe, err := os.Executable()
  44. if err == nil {
  45. path := filepath.Join(filepath.Dir(exe), "keyboards.json")
  46. if _, err := os.Stat(path); err == nil {
  47. return path, nil
  48. }
  49. }
  50. path := "keyboards.json"
  51. if _, err := os.Stat(path); err == nil {
  52. return path, nil
  53. }
  54. cwd, err := os.Getwd()
  55. if err == nil {
  56. path := filepath.Join(cwd, "keyboards.json")
  57. if _, err := os.Stat(path); err == nil {
  58. return path, nil
  59. }
  60. }
  61. return "", fmt.Errorf("keyboards.json not found")
  62. }
  63. // Discover scans all HID devices and returns connected VIA-compatible keyboards.
  64. func Discover(keyboards []Keyboard) ([]Device, error) {
  65. devices, err := hid.DiscoverAll()
  66. if err != nil {
  67. return nil, fmt.Errorf("enumerate HID devices: %w", err)
  68. }
  69. var found []Device
  70. for _, kb := range keyboards {
  71. for _, d := range devices {
  72. if d.VendorID == kb.VendorID && d.ProductID == kb.ProductID {
  73. found = append(found, Device{
  74. Keyboard: kb,
  75. Path: d.Path,
  76. VendorID: d.VendorID,
  77. ProductID: d.ProductID,
  78. })
  79. }
  80. }
  81. }
  82. return found, nil
  83. }