profile.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "sort"
  8. "strings"
  9. "github.com/spf13/cobra"
  10. intrgb "netdome.biz/paul/impact-80/internal/rgb"
  11. "netdome.biz/paul/impact-80/internal/via"
  12. )
  13. // profilesDir is a var so tests can redirect it at a temp directory.
  14. var profilesDir = "profiles"
  15. type Profile struct {
  16. Name string `json:"name"`
  17. Version int `json:"version"`
  18. Zones map[intrgb.Zone]*ZoneSettings `json:"zones"`
  19. }
  20. type ZoneSettings struct {
  21. Enabled bool `json:"enabled"`
  22. Effect string `json:"effect"`
  23. Brightness uint8 `json:"brightness"`
  24. Speed uint8 `json:"speed"`
  25. Color string `json:"color"`
  26. }
  27. func ProfilesPath() string {
  28. return filepath.Join(profilesDir)
  29. }
  30. func (p *Profile) Save() error {
  31. if p.Name == "" {
  32. return fmt.Errorf("profile name is required")
  33. }
  34. if err := os.MkdirAll(profilesDir, 0755); err != nil {
  35. return fmt.Errorf("create profiles directory: %w", err)
  36. }
  37. data, err := json.MarshalIndent(p, "", " ")
  38. if err != nil {
  39. return fmt.Errorf("marshal profile: %w", err)
  40. }
  41. path := filepath.Join(profilesDir, sanitizeFilename(p.Name)+".json")
  42. if err := os.WriteFile(path, data, 0644); err != nil {
  43. return fmt.Errorf("write profile: %w", err)
  44. }
  45. return nil
  46. }
  47. func LoadProfile(name string) (*Profile, error) {
  48. path := filepath.Join(profilesDir, sanitizeFilename(name)+".json")
  49. data, err := os.ReadFile(path)
  50. if err != nil {
  51. return nil, fmt.Errorf("read profile %s: %w", name, err)
  52. }
  53. var p Profile
  54. if err := json.Unmarshal(data, &p); err != nil {
  55. return nil, fmt.Errorf("parse profile %s: %w", name, err)
  56. }
  57. return &p, nil
  58. }
  59. func ListProfiles() ([]string, error) {
  60. entries, err := os.ReadDir(profilesDir)
  61. if err != nil {
  62. if os.IsNotExist(err) {
  63. return nil, nil
  64. }
  65. return nil, fmt.Errorf("list profiles: %w", err)
  66. }
  67. var names []string
  68. for _, entry := range entries {
  69. if entry.IsDir() {
  70. continue
  71. }
  72. name := entry.Name()
  73. if strings.HasSuffix(name, ".json") {
  74. name = name[:len(name)-5]
  75. names = append(names, name)
  76. }
  77. }
  78. return names, nil
  79. }
  80. func DeleteProfile(name string) error {
  81. path := filepath.Join(profilesDir, sanitizeFilename(name)+".json")
  82. if err := os.Remove(path); err != nil {
  83. if os.IsNotExist(err) {
  84. return fmt.Errorf("profile %s not found", name)
  85. }
  86. return fmt.Errorf("delete profile %s: %w", name, err)
  87. }
  88. return nil
  89. }
  90. func sanitizeFilename(name string) string {
  91. name = strings.ToLower(name)
  92. name = strings.Map(func(r rune) rune {
  93. if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
  94. return r
  95. }
  96. return '-'
  97. }, name)
  98. if len(name) > 0 && name[0] == '-' {
  99. name = "unnamed-" + name
  100. }
  101. return name
  102. }
  103. // applyProfile reads RGB state from the device and stores it in a Profile.
  104. func applyProfileToProfile(proto rgbProtocol, p *Profile) error {
  105. zones, err := selectedZones()
  106. if err != nil {
  107. // Fall back to all zones for save
  108. zones = intrgb.AllZones()
  109. }
  110. out, err := readInfo(proto, zones)
  111. if err != nil {
  112. return fmt.Errorf("read device state: %w", err)
  113. }
  114. p.Zones = make(map[intrgb.Zone]*ZoneSettings)
  115. for _, zi := range out.Zones {
  116. if zi.Error != "" {
  117. continue
  118. }
  119. p.Zones[zi.Zone] = &ZoneSettings{
  120. Enabled: zi.Enabled,
  121. Effect: zi.Effect,
  122. Brightness: zi.Brightness,
  123. Speed: zi.Speed,
  124. Color: fmt.Sprintf("%02x%02x", zi.Color.Hue, zi.Color.Saturation),
  125. }
  126. }
  127. return nil
  128. }
  129. // loadProfileFromDevice reads RGB state from device and saves it.
  130. func loadProfileFromDevice(name string) error {
  131. proto, err := openRGBProtocol()
  132. if err != nil {
  133. return err
  134. }
  135. defer proto.Close()
  136. p := &Profile{
  137. Name: name,
  138. Version: 1,
  139. }
  140. if err := applyProfileToProfile(proto, p); err != nil {
  141. return err
  142. }
  143. return p.Save()
  144. }
  145. func NewProfileSaveCmd() *cobra.Command {
  146. var name string
  147. cmd := &cobra.Command{
  148. Use: "save [name]",
  149. Short: "Save current RGB state to a profile",
  150. Long: "Read the current RGB settings from the keyboard and save them as a JSON profile in the profiles/ directory.",
  151. Args: cobra.MaximumNArgs(1),
  152. RunE: func(cmd *cobra.Command, args []string) error {
  153. if len(args) == 0 {
  154. name = "default"
  155. } else {
  156. name = args[0]
  157. }
  158. return loadProfileFromDevice(name)
  159. },
  160. }
  161. return cmd
  162. }
  163. func NewProfileLoadCmd() *cobra.Command {
  164. var name string
  165. cmd := &cobra.Command{
  166. Use: "load [name]",
  167. Short: "Load a profile and apply it to the keyboard",
  168. Long: "Read a JSON profile from the profiles/ directory and apply the saved RGB settings to the keyboard.",
  169. Args: cobra.MaximumNArgs(1),
  170. RunE: func(cmd *cobra.Command, args []string) error {
  171. if len(args) == 0 {
  172. name = "default"
  173. } else {
  174. name = args[0]
  175. }
  176. proto, err := openRGBProtocol()
  177. if err != nil {
  178. return err
  179. }
  180. defer proto.Close()
  181. p, err := LoadProfile(name)
  182. if err != nil {
  183. return err
  184. }
  185. selected, err := selectedZones()
  186. if err != nil {
  187. return err
  188. }
  189. // Iterate the profile in a deterministic order and honour --zone,
  190. // so `--zone logo load <name>` restores the logo and leaves the
  191. // other zones untouched.
  192. profileZones := make([]intrgb.Zone, 0, len(p.Zones))
  193. for zone := range p.Zones {
  194. profileZones = append(profileZones, zone)
  195. }
  196. sort.Slice(profileZones, func(i, j int) bool {
  197. return profileZones[i] < profileZones[j]
  198. })
  199. applied := 0
  200. for _, zone := range filterZones(profileZones, selected) {
  201. settings := p.Zones[zone]
  202. channel := via.LEDType(zone.Channel())
  203. // Resolve effect name to ID
  204. targets, _, err := intrgb.ResolveEffect(settings.Effect, []intrgb.Zone{zone})
  205. if err != nil {
  206. fmt.Fprintf(cmd.ErrOrStderr(), "Warning: effect %q not found on zone %s, skipping\n", settings.Effect, zone)
  207. continue
  208. }
  209. if err := proto.SetValue(channel, uint8(intrgb.EffectID), targets[0].ID); err != nil {
  210. return err
  211. }
  212. if err := proto.SetValue(channel, uint8(intrgb.Brightness), settings.Brightness); err != nil {
  213. return err
  214. }
  215. if err := proto.SetValue(channel, uint8(intrgb.Speed), settings.Speed); err != nil {
  216. return err
  217. }
  218. if settings.Enabled {
  219. // Parse hex color (Hue+Sat as 2-byte hex)
  220. if settings.Color != "" {
  221. hue, sat, err := hexToHSV(settings.Color)
  222. if err != nil {
  223. fmt.Fprintf(cmd.ErrOrStderr(), "Warning: invalid color %q on zone %s, skipping\n", settings.Color, zone)
  224. } else {
  225. if err := proto.SetColor(channel, hue, sat); err != nil {
  226. return err
  227. }
  228. }
  229. }
  230. }
  231. applied++
  232. }
  233. if applied == 0 {
  234. fmt.Fprintf(cmd.ErrOrStderr(),
  235. "Warning: profile %q has no settings for the selected zone(s); nothing applied\n", name)
  236. }
  237. return nil
  238. },
  239. }
  240. return cmd
  241. }
  242. func NewProfileListCmd() *cobra.Command {
  243. return &cobra.Command{
  244. Use: "list",
  245. Short: "List saved profiles",
  246. Args: cobra.NoArgs,
  247. RunE: func(cmd *cobra.Command, args []string) error {
  248. names, err := ListProfiles()
  249. if err != nil {
  250. return err
  251. }
  252. if names == nil {
  253. names = []string{}
  254. }
  255. type list struct {
  256. Profiles []string `json:"profiles"`
  257. }
  258. return encodeJSON(cmd.OutOrStdout(), list{Profiles: names})
  259. },
  260. }
  261. }
  262. func NewProfileDeleteCmd() *cobra.Command {
  263. var name string
  264. cmd := &cobra.Command{
  265. Use: "delete [name]",
  266. Short: "Delete a saved profile",
  267. Args: cobra.MaximumNArgs(1),
  268. RunE: func(cmd *cobra.Command, args []string) error {
  269. if len(args) == 0 {
  270. name = "default"
  271. } else {
  272. name = args[0]
  273. }
  274. return DeleteProfile(name)
  275. },
  276. }
  277. return cmd
  278. }
  279. func hexToHSV(s string) (uint8, uint8, error) {
  280. if len(s) != 4 {
  281. return 0, 0, fmt.Errorf("invalid HSV hex (expected 4 hex digits): %s", s)
  282. }
  283. var hue, sat uint8
  284. _, err := fmt.Sscanf(s, "%02x%02x", &hue, &sat)
  285. return hue, sat, err
  286. }