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

  1. package nanoleaf
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. lucifer3 "git.aiterp.net/lucifer3/server"
  8. "net/http"
  9. )
  10. func Discover(ctx context.Context, ip string, register bool) (string, *DeviceInfo, error) {
  11. res, err := http.Get(fmt.Sprintf("http://%s/device_info", ip))
  12. if err != nil {
  13. return "", nil, err
  14. }
  15. defer res.Body.Close()
  16. deviceInfo := DeviceInfo{}
  17. err = json.NewDecoder(res.Body).Decode(&deviceInfo)
  18. if err != nil {
  19. return "", nil, err
  20. }
  21. if deviceInfo.ModelNumber == "" {
  22. return "", nil, lucifer3.ErrUnexpectedResponse
  23. }
  24. token := ""
  25. if register {
  26. req, err := http.NewRequest("POST", fmt.Sprintf("http://%s:16021/api/v1/new/", ip), nil)
  27. if err != nil {
  28. return "", nil, err
  29. }
  30. res, err := http.DefaultClient.Do(req.WithContext(ctx))
  31. if err != nil {
  32. return "", nil, err
  33. }
  34. defer res.Body.Close()
  35. if res.StatusCode != 200 {
  36. return "", nil, errors.New(res.Status)
  37. }
  38. tokenResponse := TokenResponse{}
  39. err = json.NewDecoder(res.Body).Decode(&tokenResponse)
  40. if err != nil {
  41. return "", nil, err
  42. }
  43. token = tokenResponse.Token
  44. }
  45. return token, &deviceInfo, nil
  46. }