go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/experiments/huectl/pkg/command/list_lights.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package command
     9  
    10  import (
    11  	"fmt"
    12  	"os"
    13  
    14  	"github.com/urfave/cli/v2"
    15  
    16  	"go.charczuk.com/experiments/huectl/pkg/hue"
    17  )
    18  
    19  // ListLights returns a command.
    20  func ListLights() *cli.Command {
    21  	return &cli.Command{
    22  		Name:  "list-lights",
    23  		Usage: "List lights associated with a given bridge.",
    24  		Flags: append(DefaultFlags, append(OutputFlags, GroupFlags...)...),
    25  		Action: func(c *cli.Context) error {
    26  			bridge, err := initHelper(c)
    27  			if err != nil {
    28  				return err
    29  			}
    30  
    31  			if c.Int(flagGroupID) > 0 && c.String(flagGroupName) != "" {
    32  				return fmt.Errorf("please specify one of --group-id or --group-name")
    33  			}
    34  			var group *hue.Group
    35  			if c.Int(flagGroupID) > 0 || c.String(flagGroupName) != "" {
    36  				group, err = getGroup(c, &bridge, getGroupArgs{
    37  					ID:   c.Int(flagGroupID),
    38  					Name: c.String(flagGroupName),
    39  				})
    40  				if err != nil {
    41  					return err
    42  				}
    43  			}
    44  
    45  			lights, err := bridge.GetLights(c.Context)
    46  			if err != nil {
    47  				return err
    48  			}
    49  
    50  			if group != nil {
    51  				var filtered []hue.Light
    52  				for _, light := range lights {
    53  					var include bool
    54  					for _, lightID := range group.Lights {
    55  						if lightID == fmt.Sprint(light.ID) {
    56  							include = true
    57  							break
    58  						}
    59  					}
    60  					if include {
    61  						filtered = append(filtered, light)
    62  					}
    63  				}
    64  				output(c, os.Stdout, filtered)
    65  				return nil
    66  			}
    67  
    68  			output(c, os.Stdout, lights)
    69  			return nil
    70  		},
    71  	}
    72  }