You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

55 lines
1.1 KiB

package nanoleaf
import (
"context"
"encoding/json"
"errors"
"fmt"
lucifer3 "git.aiterp.net/lucifer3/server"
"net/http"
)
func Discover(ctx context.Context, ip string, register bool) (string, *DeviceInfo, error) {
res, err := http.Get(fmt.Sprintf("http://%s/device_info", ip))
if err != nil {
return "", nil, err
}
defer res.Body.Close()
deviceInfo := DeviceInfo{}
err = json.NewDecoder(res.Body).Decode(&deviceInfo)
if err != nil {
return "", nil, err
}
if deviceInfo.ModelNumber == "" {
return "", nil, lucifer3.ErrUnexpectedResponse
}
token := ""
if register {
req, err := http.NewRequest("POST", fmt.Sprintf("http://%s:16021/api/v1/new/", ip), nil)
if err != nil {
return "", nil, err
}
res, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
return "", nil, err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return "", nil, errors.New(res.Status)
}
tokenResponse := TokenResponse{}
err = json.NewDecoder(res.Body).Decode(&tokenResponse)
if err != nil {
return "", nil, err
}
token = tokenResponse.Token
}
return token, &deviceInfo, nil
}