client.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. package main
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "time"
  10. )
  11. // APIClient handles communication with the server
  12. type APIClient struct {
  13. baseURL string
  14. token string
  15. httpClient *http.Client
  16. }
  17. // NewAPIClient creates a new API client
  18. func NewAPIClient(baseURL string) *APIClient {
  19. return &APIClient{
  20. baseURL: baseURL,
  21. httpClient: &http.Client{
  22. Timeout: 30 * time.Second,
  23. },
  24. }
  25. }
  26. // SetToken sets the authentication token
  27. func (c *APIClient) SetToken(token string) {
  28. c.token = token
  29. }
  30. // RegistrationRequest is sent to register a device
  31. type RegistrationRequest struct {
  32. DeviceID string `json:"device_id"`
  33. EthIP *string `json:"eth_ip,omitempty"`
  34. WlanIP *string `json:"wlan_ip,omitempty"`
  35. }
  36. // RegistrationResponse is returned from registration
  37. type RegistrationResponse struct {
  38. DeviceToken string `json:"device_token"`
  39. DevicePassword string `json:"device_password,omitempty"`
  40. SSHTunnel struct {
  41. Enabled bool `json:"enabled"`
  42. RemotePort int `json:"remote_port"`
  43. Server string `json:"server"`
  44. } `json:"ssh_tunnel,omitempty"`
  45. }
  46. // Register registers a device with the server
  47. func (c *APIClient) Register(req *RegistrationRequest) (*RegistrationResponse, error) {
  48. body, err := json.Marshal(req)
  49. if err != nil {
  50. return nil, err
  51. }
  52. httpReq, err := http.NewRequest("POST", c.baseURL+"/registration", bytes.NewReader(body))
  53. if err != nil {
  54. return nil, err
  55. }
  56. httpReq.Header.Set("Content-Type", "application/json")
  57. resp, err := c.httpClient.Do(httpReq)
  58. if err != nil {
  59. return nil, err
  60. }
  61. defer resp.Body.Close()
  62. if resp.StatusCode != 201 && resp.StatusCode != 200 {
  63. respBody, _ := io.ReadAll(resp.Body)
  64. return nil, fmt.Errorf("registration failed: %d %s", resp.StatusCode, string(respBody))
  65. }
  66. var regResp RegistrationResponse
  67. if err := json.NewDecoder(resp.Body).Decode(&regResp); err != nil {
  68. return nil, err
  69. }
  70. return &regResp, nil
  71. }
  72. // ServerConfig is the configuration returned by the server
  73. type ServerConfig struct {
  74. // ForceCloud overrides local mode setting - for remote support
  75. ForceCloud bool `json:"force_cloud"`
  76. BLE struct {
  77. Enabled bool `json:"enabled"`
  78. BatchIntervalMs int `json:"batch_interval_ms"`
  79. UUIDFilterHex string `json:"uuid_filter_hex,omitempty"`
  80. } `json:"ble"`
  81. WiFi struct {
  82. MonitorEnabled bool `json:"monitor_enabled"`
  83. ClientEnabled bool `json:"client_enabled"`
  84. SSID string `json:"ssid"`
  85. PSK string `json:"psk"`
  86. BatchIntervalMs int `json:"batch_interval_ms"`
  87. } `json:"wifi"`
  88. SSHTunnel struct {
  89. Enabled bool `json:"enabled"`
  90. Server string `json:"server"`
  91. Port int `json:"port"`
  92. User string `json:"user"`
  93. RemotePort int `json:"remote_port"`
  94. KeepaliveInterval int `json:"keepalive_interval"`
  95. } `json:"ssh_tunnel"`
  96. Net struct {
  97. NTP struct {
  98. Servers []string `json:"servers"`
  99. } `json:"ntp"`
  100. } `json:"net"`
  101. Debug bool `json:"debug"`
  102. }
  103. // GetConfig fetches configuration from the server
  104. func (c *APIClient) GetConfig(deviceID string) (*ServerConfig, error) {
  105. httpReq, err := http.NewRequest("GET", c.baseURL+"/config", nil)
  106. if err != nil {
  107. return nil, err
  108. }
  109. q := httpReq.URL.Query()
  110. q.Set("device_id", deviceID)
  111. httpReq.URL.RawQuery = q.Encode()
  112. if c.token != "" {
  113. httpReq.Header.Set("Authorization", "Bearer "+c.token)
  114. }
  115. resp, err := c.httpClient.Do(httpReq)
  116. if err != nil {
  117. return nil, err
  118. }
  119. defer resp.Body.Close()
  120. if resp.StatusCode != 200 {
  121. return nil, fmt.Errorf("config fetch failed: %d", resp.StatusCode)
  122. }
  123. var cfg ServerConfig
  124. if err := json.NewDecoder(resp.Body).Decode(&cfg); err != nil {
  125. return nil, err
  126. }
  127. return &cfg, nil
  128. }
  129. // EventBatch is a batch of events to upload
  130. type EventBatch struct {
  131. DeviceID string `json:"device_id"`
  132. Events []interface{} `json:"events"`
  133. }
  134. // UploadEvents uploads a batch of events (gzipped)
  135. func (c *APIClient) UploadEvents(endpoint string, batch *EventBatch) error {
  136. // Serialize to JSON
  137. jsonData, err := json.Marshal(batch)
  138. if err != nil {
  139. return err
  140. }
  141. // Gzip compress
  142. var buf bytes.Buffer
  143. gw := gzip.NewWriter(&buf)
  144. if _, err := gw.Write(jsonData); err != nil {
  145. return err
  146. }
  147. if err := gw.Close(); err != nil {
  148. return err
  149. }
  150. // Store compressed data for retries
  151. compressedData := buf.Bytes()
  152. url := c.baseURL + endpoint
  153. // Send with retries
  154. var lastErr error
  155. for attempt := 1; attempt <= 3; attempt++ {
  156. // Create fresh request for each attempt (body can only be read once)
  157. httpReq, err := http.NewRequest("POST", url, bytes.NewReader(compressedData))
  158. if err != nil {
  159. return err
  160. }
  161. httpReq.Header.Set("Content-Type", "application/json")
  162. httpReq.Header.Set("Content-Encoding", "gzip")
  163. if c.token != "" {
  164. httpReq.Header.Set("Authorization", "Bearer "+c.token)
  165. }
  166. resp, err := c.httpClient.Do(httpReq)
  167. if err != nil {
  168. lastErr = err
  169. time.Sleep(time.Duration(attempt) * time.Second)
  170. continue
  171. }
  172. resp.Body.Close()
  173. if resp.StatusCode >= 200 && resp.StatusCode < 300 {
  174. return nil
  175. }
  176. lastErr = fmt.Errorf("upload failed: %d", resp.StatusCode)
  177. time.Sleep(time.Duration(attempt) * time.Second)
  178. }
  179. return lastErr
  180. }