effect.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. "github.com/spf13/cobra"
  7. intrgb "netdome.biz/paul/impact-80/internal/rgb"
  8. "netdome.biz/paul/impact-80/internal/via"
  9. )
  10. var listEffects bool
  11. func resolveEffectTargets(name string, zones []intrgb.Zone) ([]intrgb.EffectTarget, []intrgb.Zone, error) {
  12. if name == "static" {
  13. name = "solid"
  14. }
  15. return intrgb.ResolveEffect(name, zones)
  16. }
  17. func NewEffectCmd() *cobra.Command {
  18. cmd := &cobra.Command{
  19. Use: "effect [name]",
  20. Short: "Set or list RGB effects",
  21. Long: "Set the RGB lighting effect on the connected keyboard. Without an argument, lists all effects.",
  22. Args: cobra.MaximumNArgs(1),
  23. RunE: func(cmd *cobra.Command, args []string) error {
  24. if listEffects || len(args) == 0 {
  25. return listAllEffects(cmd)
  26. }
  27. return runEffectSet(cmd, args)
  28. },
  29. }
  30. cmd.Flags().BoolVar(&listEffects, "list", false, "List all available effects per zone")
  31. return cmd
  32. }
  33. func listAllEffects(cmd *cobra.Command) error {
  34. type ZoneEffectList struct {
  35. Zone string `json:"zone"`
  36. Effect string `json:"effect"`
  37. ID uint8 `json:"id"`
  38. }
  39. type EffectList struct {
  40. Zones []ZoneEffectList `json:"zones"`
  41. }
  42. var list EffectList
  43. for _, zone := range intrgb.AllZones() {
  44. names := intrgb.ZoneEffects(zone)
  45. for id, name := range names {
  46. list.Zones = append(list.Zones, ZoneEffectList{
  47. Zone: string(zone),
  48. Effect: name,
  49. ID: uint8(id),
  50. })
  51. }
  52. }
  53. data, _ := json.MarshalIndent(list.Zones, "", " ")
  54. fmt.Fprintf(cmd.OutOrStdout(), "%s\n", string(data))
  55. return nil
  56. }
  57. func runEffectSet(cmd *cobra.Command, args []string) error {
  58. zones, err := selectedZones()
  59. if err != nil {
  60. return err
  61. }
  62. targets, skipped, err := resolveEffectTargets(args[0], zones)
  63. if err != nil {
  64. return err
  65. }
  66. if len(skipped) > 0 {
  67. skippedNames := make([]string, len(skipped))
  68. for i, zone := range skipped {
  69. skippedNames[i] = string(zone)
  70. }
  71. fmt.Fprintf(cmd.ErrOrStderr(), "Warning: effect not supported on zone(s): %s\n", strings.Join(skippedNames, ", "))
  72. }
  73. proto, err := openRGBProtocol()
  74. if err != nil {
  75. return err
  76. }
  77. defer proto.Close()
  78. for _, target := range targets {
  79. if err := proto.SetValue(via.LEDType(target.Zone.Channel()), uint8(intrgb.EffectID), target.ID); err != nil {
  80. return fmt.Errorf("set effect on %s: %w", target.Zone, err)
  81. }
  82. }
  83. fmt.Fprintf(cmd.OutOrStdout(), "Effect set to %q\n", args[0])
  84. return nil
  85. }