effect.go 2.3 KB

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