go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/experiments/huectl/pkg/hue/discover.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 hue
     9  
    10  import (
    11  	"context"
    12  	"encoding/json"
    13  	"io"
    14  	"net/http"
    15  )
    16  
    17  // DiscoverAll performs a discovery on the network looking for bridges using https://www.meethue.com/api/nupnp service
    18  // and returns a list of Bridges.
    19  func DiscoverAll(ctx context.Context) ([]Bridge, error) {
    20  	req, err := http.NewRequest(http.MethodGet, "https://discovery.meethue.com", nil)
    21  	if err != nil {
    22  		return nil, err
    23  	}
    24  
    25  	req = req.WithContext(ctx)
    26  	res, err := http.DefaultClient.Do(req)
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  
    31  	defer res.Body.Close()
    32  
    33  	d, err := io.ReadAll(res.Body)
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  
    38  	var bridges []Bridge
    39  	err = json.Unmarshal(d, &bridges)
    40  	if err != nil {
    41  		return nil, err
    42  	}
    43  
    44  	return bridges, nil
    45  }
    46  
    47  // DiscoverFirst performs a discovery on the network looking for bridges using https://www.meethue.com/api/nupnp service.
    48  func DiscoverFirst(ctx context.Context) (b Bridge, ok bool, err error) {
    49  	var bridges []Bridge
    50  	bridges, err = DiscoverAll(ctx)
    51  	if err != nil {
    52  		return
    53  	}
    54  	if len(bridges) > 0 {
    55  		b = bridges[0]
    56  		ok = true
    57  		return
    58  	}
    59  	return
    60  }