api.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "time"
  12. "ai-status-light/internal/database"
  13. "ai-status-light/internal/logger"
  14. mqttcli "ai-status-light/internal/mqtt"
  15. "ai-status-light/internal/web"
  16. )
  17. type ClientStatus struct {
  18. Code string `json:"code"`
  19. Timestamp string `json:"timestamp"`
  20. }
  21. type EventRequest struct {
  22. Code string `json:"code"`
  23. Timestamp string `json:"timestamp,omitempty"`
  24. }
  25. type SSEClient struct {
  26. ch chan string
  27. closed bool
  28. mu sync.Mutex
  29. }
  30. type Server struct {
  31. db *database.DB
  32. server *http.Server
  33. sseClients map[*SSEClient]bool
  34. sseMu sync.Mutex
  35. statusMap map[int]*ClientStatus
  36. statusMu sync.RWMutex
  37. certFile string
  38. keyFile string
  39. mqttClient *mqttcli.Client
  40. bleStdin io.Writer
  41. }
  42. type Response struct {
  43. Code int `json:"code"`
  44. Message string `json:"message"`
  45. Data interface{} `json:"data,omitempty"`
  46. }
  47. func New(db *database.DB, addr string) *Server {
  48. s := &Server{
  49. db: db,
  50. sseClients: make(map[*SSEClient]bool),
  51. statusMap: make(map[int]*ClientStatus),
  52. }
  53. mux := http.NewServeMux()
  54. mux.HandleFunc("/api/clients", s.handleClients)
  55. mux.HandleFunc("/api/event", s.handleEvent)
  56. mux.HandleFunc("/api/events", s.handleSSE)
  57. mux.HandleFunc("/api/mqtt", s.handleMQTT)
  58. mux.HandleFunc("/api/mqtt/", s.handleMQTTByID)
  59. mux.HandleFunc("/api/ble", s.handleBLE)
  60. mux.HandleFunc("/api/ble/", s.handleBLEByID)
  61. mux.HandleFunc("/api/health", s.handleHealth)
  62. mux.HandleFunc("/api/device/config", s.handleDeviceConfig)
  63. mux.HandleFunc("/api/device/config/", s.handleDeviceConfigByID)
  64. mux.HandleFunc("/api/device/config/push", s.handleDeviceConfigPush)
  65. mux.HandleFunc("/", web.Handler())
  66. s.server = &http.Server{
  67. Addr: addr,
  68. Handler: corsMiddleware(mux),
  69. }
  70. return s
  71. }
  72. func (s *Server) EnableTLS(certFile, keyFile string) {
  73. s.certFile = certFile
  74. s.keyFile = keyFile
  75. }
  76. func (s *Server) SetMQTTClient(client *mqttcli.Client) {
  77. s.mqttClient = client
  78. }
  79. func (s *Server) SetBLEStdin(stdin io.Writer) {
  80. s.bleStdin = stdin
  81. }
  82. func (s *Server) Start() error {
  83. if s.certFile != "" && s.keyFile != "" {
  84. logger.Info("API 服务器开始监听 (HTTPS): %s", s.server.Addr)
  85. err := s.server.ListenAndServeTLS(s.certFile, s.keyFile)
  86. if err != nil && err != http.ErrServerClosed {
  87. logger.Error("API 服务器监听失败: %v", err)
  88. }
  89. return err
  90. }
  91. logger.Info("API 服务器开始监听: %s", s.server.Addr)
  92. err := s.server.ListenAndServe()
  93. if err != nil && err != http.ErrServerClosed {
  94. logger.Error("API 服务器监听失败: %v", err)
  95. }
  96. return err
  97. }
  98. func corsMiddleware(next http.Handler) http.Handler {
  99. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  100. w.Header().Set("Access-Control-Allow-Origin", "*")
  101. w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
  102. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  103. if r.Method == "OPTIONS" {
  104. w.WriteHeader(http.StatusOK)
  105. return
  106. }
  107. next.ServeHTTP(w, r)
  108. })
  109. }
  110. func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
  111. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "ok"})
  112. }
  113. func (s *Server) handleEvent(w http.ResponseWriter, r *http.Request) {
  114. if r.Method != http.MethodPost {
  115. writeJSON(w, http.StatusMethodNotAllowed, Response{Code: -1, Message: "方法不允许"})
  116. return
  117. }
  118. var req EventRequest
  119. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  120. logger.Warn("事件请求体解析失败: %v", err)
  121. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "无效的请求体"})
  122. return
  123. }
  124. if req.Code == "" {
  125. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "code 不能为空"})
  126. return
  127. }
  128. logger.Info("收到事件: code=%s", req.Code)
  129. // 通过 MQTT 发送
  130. if s.mqttClient != nil {
  131. payload := map[string]interface{}{
  132. "code": req.Code,
  133. "timestamp": time.Now().Format(time.RFC3339),
  134. }
  135. if err := s.mqttClient.PublishRaw(s.mqttClient.GetTopic(), payload); err != nil {
  136. logger.Error("MQTT 发送失败: %v", err)
  137. }
  138. }
  139. // 通过 BLE 发送
  140. if s.bleStdin != nil {
  141. msg := fmt.Sprintf(`{"code":"%s"}`+"\n", req.Code)
  142. if _, err := s.bleStdin.Write([]byte(msg)); err != nil {
  143. logger.Error("BLE 发送失败: %v", err)
  144. }
  145. }
  146. // 广播到 SSE 客户端
  147. s.broadcastSSE(req.Code)
  148. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "ok"})
  149. }
  150. func (s *Server) handleSSE(w http.ResponseWriter, r *http.Request) {
  151. flusher, ok := w.(http.Flusher)
  152. if !ok {
  153. http.Error(w, "SSE 不支持", http.StatusInternalServerError)
  154. return
  155. }
  156. w.Header().Set("Content-Type", "text/event-stream")
  157. w.Header().Set("Cache-Control", "no-cache")
  158. w.Header().Set("Connection", "keep-alive")
  159. w.Header().Set("Access-Control-Allow-Origin", "*")
  160. client := &SSEClient{
  161. ch: make(chan string, 10),
  162. }
  163. s.sseMu.Lock()
  164. s.sseClients[client] = true
  165. s.sseMu.Unlock()
  166. logger.Info("SSE 客户端已连接,当前连接数: %d", len(s.sseClients))
  167. defer func() {
  168. s.sseMu.Lock()
  169. delete(s.sseClients, client)
  170. s.sseMu.Unlock()
  171. client.Close()
  172. logger.Info("SSE 客户端已断开,当前连接数: %d", len(s.sseClients))
  173. }()
  174. // 发送初始连接消息
  175. fmt.Fprintf(w, "event: connected\ndata: {\"status\":\"ok\"}\n\n")
  176. flusher.Flush()
  177. ctx := r.Context()
  178. for {
  179. select {
  180. case <-ctx.Done():
  181. return
  182. case msg, ok := <-client.ch:
  183. if !ok {
  184. return
  185. }
  186. fmt.Fprintf(w, "event: status\ndata: %s\n\n", msg)
  187. flusher.Flush()
  188. }
  189. }
  190. }
  191. func (s *Server) broadcastSSE(code string) {
  192. ts := time.Now().Format(time.RFC3339)
  193. s.statusMu.Lock()
  194. s.statusMap[0] = &ClientStatus{
  195. Code: code,
  196. Timestamp: ts,
  197. }
  198. s.statusMu.Unlock()
  199. s.sseMu.Lock()
  200. defer s.sseMu.Unlock()
  201. if len(s.sseClients) == 0 {
  202. return
  203. }
  204. payload := map[string]interface{}{
  205. "code": code,
  206. "timestamp": ts,
  207. }
  208. data, err := json.Marshal(payload)
  209. if err != nil {
  210. logger.Error("序列化 SSE 消息失败: %v", err)
  211. return
  212. }
  213. msg := string(data)
  214. for client := range s.sseClients {
  215. client.Send(msg)
  216. }
  217. }
  218. func (c *SSEClient) Send(msg string) {
  219. c.mu.Lock()
  220. defer c.mu.Unlock()
  221. if c.closed {
  222. return
  223. }
  224. select {
  225. case c.ch <- msg:
  226. default:
  227. logger.Debug("SSE 客户端缓冲区已满,丢弃消息")
  228. }
  229. }
  230. func (c *SSEClient) Close() {
  231. c.mu.Lock()
  232. defer c.mu.Unlock()
  233. if !c.closed {
  234. c.closed = true
  235. close(c.ch)
  236. }
  237. }
  238. func (s *Server) handleClients(w http.ResponseWriter, r *http.Request) {
  239. if r.Method != http.MethodGet {
  240. writeJSON(w, http.StatusMethodNotAllowed, Response{Code: -1, Message: "方法不允许"})
  241. return
  242. }
  243. s.statusMu.RLock()
  244. result := make([]*ClientStatus, 0, len(s.statusMap))
  245. for _, cs := range s.statusMap {
  246. result = append(result, cs)
  247. }
  248. s.statusMu.RUnlock()
  249. sort.Slice(result, func(i, j int) bool {
  250. return result[i].Code < result[j].Code
  251. })
  252. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "success", Data: result})
  253. }
  254. func (s *Server) handleMQTT(w http.ResponseWriter, r *http.Request) {
  255. logger.Debug("HTTP %s %s", r.Method, r.URL.Path)
  256. switch r.Method {
  257. case http.MethodGet:
  258. s.listMQTTConfigs(w, r)
  259. case http.MethodPost:
  260. s.createMQTTConfig(w, r)
  261. default:
  262. logger.Warn("不支持的 HTTP 方法: %s %s", r.Method, r.URL.Path)
  263. writeJSON(w, http.StatusMethodNotAllowed, Response{Code: -1, Message: "方法不允许"})
  264. }
  265. }
  266. func (s *Server) handleMQTTByID(w http.ResponseWriter, r *http.Request) {
  267. logger.Debug("HTTP %s %s", r.Method, r.URL.Path)
  268. idStr := strings.TrimPrefix(r.URL.Path, "/api/mqtt/")
  269. id, err := strconv.Atoi(idStr)
  270. if err != nil {
  271. logger.Warn("无效的配置 ID: %s", idStr)
  272. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "无效的 ID"})
  273. return
  274. }
  275. switch r.Method {
  276. case http.MethodGet:
  277. s.getMQTTConfig(w, id)
  278. case http.MethodPut:
  279. s.updateMQTTConfig(w, r, id)
  280. case http.MethodDelete:
  281. s.deleteMQTTConfig(w, id)
  282. default:
  283. logger.Warn("不支持的 HTTP 方法: %s %s", r.Method, r.URL.Path)
  284. writeJSON(w, http.StatusMethodNotAllowed, Response{Code: -1, Message: "方法不允许"})
  285. }
  286. }
  287. func (s *Server) handleBLE(w http.ResponseWriter, r *http.Request) {
  288. logger.Debug("HTTP %s %s", r.Method, r.URL.Path)
  289. switch r.Method {
  290. case http.MethodGet:
  291. s.listBLEConfigs(w, r)
  292. case http.MethodPost:
  293. s.createBLEConfig(w, r)
  294. default:
  295. logger.Warn("不支持的 HTTP 方法: %s %s", r.Method, r.URL.Path)
  296. writeJSON(w, http.StatusMethodNotAllowed, Response{Code: -1, Message: "方法不允许"})
  297. }
  298. }
  299. func (s *Server) handleBLEByID(w http.ResponseWriter, r *http.Request) {
  300. logger.Debug("HTTP %s %s", r.Method, r.URL.Path)
  301. idStr := strings.TrimPrefix(r.URL.Path, "/api/ble/")
  302. id, err := strconv.Atoi(idStr)
  303. if err != nil {
  304. logger.Warn("无效的配置 ID: %s", idStr)
  305. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "无效的 ID"})
  306. return
  307. }
  308. switch r.Method {
  309. case http.MethodGet:
  310. s.getBLEConfig(w, id)
  311. case http.MethodPut:
  312. s.updateBLEConfig(w, r, id)
  313. case http.MethodDelete:
  314. s.deleteBLEConfig(w, id)
  315. default:
  316. logger.Warn("不支持的 HTTP 方法: %s %s", r.Method, r.URL.Path)
  317. writeJSON(w, http.StatusMethodNotAllowed, Response{Code: -1, Message: "方法不允许"})
  318. }
  319. }
  320. func (s *Server) listMQTTConfigs(w http.ResponseWriter, r *http.Request) {
  321. configs, err := s.db.ListMQTTConfigs()
  322. if err != nil {
  323. logger.Error("查询 MQTT 配置列表失败: %v", err)
  324. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  325. return
  326. }
  327. logger.Debug("查询 MQTT 配置列表: %d 条", len(configs))
  328. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "ok", Data: configs})
  329. }
  330. func (s *Server) createMQTTConfig(w http.ResponseWriter, r *http.Request) {
  331. var cfg database.MQTTConfig
  332. if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
  333. logger.Warn("创建配置请求体解析失败: %v", err)
  334. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "无效的请求体"})
  335. return
  336. }
  337. if cfg.Broker == "" {
  338. logger.Warn("创建配置: broker 为空")
  339. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "broker 不能为空"})
  340. return
  341. }
  342. if cfg.ClientID == "" {
  343. cfg.ClientID = "opencode-monitor"
  344. }
  345. if cfg.Topic == "" {
  346. cfg.Topic = "opencode/status"
  347. }
  348. if err := s.db.SaveMQTTConfig(&cfg); err != nil {
  349. logger.Error("创建 MQTT 配置失败: %v", err)
  350. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  351. return
  352. }
  353. logger.Info("MQTT 配置已创建: id=%d, broker=%s, topic=%s", cfg.ID, cfg.Broker, cfg.Topic)
  354. writeJSON(w, http.StatusCreated, Response{Code: 0, Message: "创建成功", Data: cfg})
  355. }
  356. func (s *Server) getMQTTConfig(w http.ResponseWriter, id int) {
  357. configs, err := s.db.ListMQTTConfigs()
  358. if err != nil {
  359. logger.Error("查询 MQTT 配置失败: id=%d, %v", id, err)
  360. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  361. return
  362. }
  363. for _, cfg := range configs {
  364. if cfg.ID == id {
  365. logger.Debug("查询 MQTT 配置: id=%d", id)
  366. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "ok", Data: cfg})
  367. return
  368. }
  369. }
  370. logger.Warn("MQTT 配置不存在: id=%d", id)
  371. writeJSON(w, http.StatusNotFound, Response{Code: -1, Message: "配置不存在"})
  372. }
  373. func (s *Server) updateMQTTConfig(w http.ResponseWriter, r *http.Request, id int) {
  374. var cfg database.MQTTConfig
  375. if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
  376. logger.Warn("更新配置请求体解析失败: id=%d, %v", id, err)
  377. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "无效的请求体"})
  378. return
  379. }
  380. cfg.ID = id
  381. if cfg.Broker == "" {
  382. logger.Warn("更新配置: broker 为空, id=%d", id)
  383. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "broker 不能为空"})
  384. return
  385. }
  386. if cfg.ClientID == "" {
  387. cfg.ClientID = "opencode-monitor"
  388. }
  389. if cfg.Topic == "" {
  390. cfg.Topic = "opencode/status"
  391. }
  392. if err := s.db.SaveMQTTConfig(&cfg); err != nil {
  393. logger.Error("更新 MQTT 配置失败: id=%d, %v", id, err)
  394. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  395. return
  396. }
  397. logger.Info("MQTT 配置已更新: id=%d, broker=%s, topic=%s", id, cfg.Broker, cfg.Topic)
  398. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "更新成功", Data: cfg})
  399. }
  400. func (s *Server) deleteMQTTConfig(w http.ResponseWriter, id int) {
  401. if err := s.db.DeleteMQTTConfig(id); err != nil {
  402. logger.Error("删除 MQTT 配置失败: id=%d, %v", id, err)
  403. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  404. return
  405. }
  406. logger.Info("MQTT 配置已删除: id=%d", id)
  407. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "删除成功"})
  408. }
  409. func (s *Server) listBLEConfigs(w http.ResponseWriter, r *http.Request) {
  410. configs, err := s.db.ListBLEConfigs()
  411. if err != nil {
  412. logger.Error("查询 BLE 配置列表失败: %v", err)
  413. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  414. return
  415. }
  416. logger.Debug("查询 BLE 配置列表: %d 条", len(configs))
  417. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "ok", Data: configs})
  418. }
  419. func (s *Server) createBLEConfig(w http.ResponseWriter, r *http.Request) {
  420. var cfg database.BLEConfig
  421. if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
  422. logger.Warn("创建 BLE 配置请求体解析失败: %v", err)
  423. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "无效的请求体"})
  424. return
  425. }
  426. if cfg.DeviceName == "" || cfg.ServiceUUID == "" || cfg.ModeCharUUID == "" || cfg.ConfigCharUUID == "" {
  427. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "device_name, service_uuid, mode_char_uuid, config_char_uuid 不能为空"})
  428. return
  429. }
  430. if err := s.db.SaveBLEConfig(&cfg); err != nil {
  431. logger.Error("创建 BLE 配置失败: %v", err)
  432. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  433. return
  434. }
  435. logger.Info("BLE 配置已创建: id=%d, device=%s", cfg.ID, cfg.DeviceName)
  436. writeJSON(w, http.StatusCreated, Response{Code: 0, Message: "创建成功", Data: cfg})
  437. }
  438. func (s *Server) getBLEConfig(w http.ResponseWriter, id int) {
  439. configs, err := s.db.ListBLEConfigs()
  440. if err != nil {
  441. logger.Error("查询 BLE 配置失败: id=%d, %v", id, err)
  442. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  443. return
  444. }
  445. for _, cfg := range configs {
  446. if cfg.ID == id {
  447. logger.Debug("查询 BLE 配置: id=%d", id)
  448. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "ok", Data: cfg})
  449. return
  450. }
  451. }
  452. logger.Warn("BLE 配置不存在: id=%d", id)
  453. writeJSON(w, http.StatusNotFound, Response{Code: -1, Message: "配置不存在"})
  454. }
  455. func (s *Server) updateBLEConfig(w http.ResponseWriter, r *http.Request, id int) {
  456. var cfg database.BLEConfig
  457. if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
  458. logger.Warn("更新 BLE 配置请求体解析失败: id=%d, %v", id, err)
  459. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "无效的请求体"})
  460. return
  461. }
  462. cfg.ID = id
  463. if cfg.DeviceName == "" || cfg.ServiceUUID == "" || cfg.ModeCharUUID == "" || cfg.ConfigCharUUID == "" {
  464. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "device_name, service_uuid, mode_char_uuid, config_char_uuid 不能为空"})
  465. return
  466. }
  467. if err := s.db.SaveBLEConfig(&cfg); err != nil {
  468. logger.Error("更新 BLE 配置失败: id=%d, %v", id, err)
  469. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  470. return
  471. }
  472. logger.Info("BLE 配置已更新: id=%d, device=%s", id, cfg.DeviceName)
  473. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "更新成功", Data: cfg})
  474. }
  475. func (s *Server) deleteBLEConfig(w http.ResponseWriter, id int) {
  476. if err := s.db.DeleteBLEConfig(id); err != nil {
  477. logger.Error("删除 BLE 配置失败: id=%d, %v", id, err)
  478. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  479. return
  480. }
  481. logger.Info("BLE 配置已删除: id=%d", id)
  482. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "删除成功"})
  483. }
  484. func writeJSON(w http.ResponseWriter, statusCode int, data interface{}) {
  485. w.Header().Set("Content-Type", "application/json")
  486. w.WriteHeader(statusCode)
  487. json.NewEncoder(w).Encode(data)
  488. }
  489. func (s *Server) GetAddr() string {
  490. return s.server.Addr
  491. }
  492. func (s *Server) handleDeviceConfig(w http.ResponseWriter, r *http.Request) {
  493. logger.Debug("HTTP %s %s", r.Method, r.URL.Path)
  494. switch r.Method {
  495. case http.MethodGet:
  496. s.listDeviceConfigs(w, r)
  497. case http.MethodPost:
  498. s.createDeviceConfig(w, r)
  499. default:
  500. logger.Warn("不支持的 HTTP 方法: %s %s", r.Method, r.URL.Path)
  501. writeJSON(w, http.StatusMethodNotAllowed, Response{Code: -1, Message: "方法不允许"})
  502. }
  503. }
  504. func (s *Server) handleDeviceConfigByID(w http.ResponseWriter, r *http.Request) {
  505. logger.Debug("HTTP %s %s", r.Method, r.URL.Path)
  506. idStr := strings.TrimPrefix(r.URL.Path, "/api/device/config/")
  507. if idStr == "push" {
  508. s.handleDeviceConfigPush(w, r)
  509. return
  510. }
  511. id, err := strconv.Atoi(idStr)
  512. if err != nil {
  513. logger.Warn("无效的配置 ID: %s", idStr)
  514. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "无效的 ID"})
  515. return
  516. }
  517. switch r.Method {
  518. case http.MethodGet:
  519. s.getDeviceConfig(w, id)
  520. case http.MethodPut:
  521. s.updateDeviceConfig(w, r, id)
  522. case http.MethodDelete:
  523. s.deleteDeviceConfig(w, id)
  524. default:
  525. logger.Warn("不支持的 HTTP 方法: %s %s", r.Method, r.URL.Path)
  526. writeJSON(w, http.StatusMethodNotAllowed, Response{Code: -1, Message: "方法不允许"})
  527. }
  528. }
  529. func (s *Server) handleDeviceConfigPush(w http.ResponseWriter, r *http.Request) {
  530. if r.Method != http.MethodPost {
  531. writeJSON(w, http.StatusMethodNotAllowed, Response{Code: -1, Message: "方法不允许"})
  532. return
  533. }
  534. if s.mqttClient == nil {
  535. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "MQTT 未连接"})
  536. return
  537. }
  538. var req struct {
  539. ID int `json:"id"`
  540. Reset bool `json:"reset,omitempty"`
  541. }
  542. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  543. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "无效的请求体"})
  544. return
  545. }
  546. configs, err := s.db.ListDeviceConfigs()
  547. if err != nil {
  548. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  549. return
  550. }
  551. var targetCfg *database.DeviceConfig
  552. for _, cfg := range configs {
  553. if cfg.ID == req.ID {
  554. targetCfg = &cfg
  555. break
  556. }
  557. }
  558. if targetCfg == nil {
  559. writeJSON(w, http.StatusNotFound, Response{Code: -1, Message: "配置不存在"})
  560. return
  561. }
  562. payload := map[string]interface{}{}
  563. if targetCfg.WifiSSID != "" {
  564. payload["wifi_ssid"] = targetCfg.WifiSSID
  565. }
  566. if targetCfg.WifiPass != "" {
  567. payload["wifi_pass"] = targetCfg.WifiPass
  568. }
  569. if targetCfg.MqttBroker != "" {
  570. payload["mqtt_broker"] = targetCfg.MqttBroker
  571. }
  572. if targetCfg.MqttPort > 0 {
  573. payload["mqtt_port"] = targetCfg.MqttPort
  574. }
  575. if targetCfg.MqttUser != "" {
  576. payload["mqtt_user"] = targetCfg.MqttUser
  577. }
  578. if targetCfg.MqttPass != "" {
  579. payload["mqtt_pass"] = targetCfg.MqttPass
  580. }
  581. if targetCfg.MqttClient != "" {
  582. payload["mqtt_client"] = targetCfg.MqttClient
  583. }
  584. if targetCfg.MqttTopic != "" {
  585. payload["mqtt_topic"] = targetCfg.MqttTopic
  586. }
  587. if targetCfg.MqttStatus != "" {
  588. payload["mqtt_status"] = targetCfg.MqttStatus
  589. }
  590. if targetCfg.PinRed > 0 {
  591. payload["pin_red"] = targetCfg.PinRed
  592. }
  593. if targetCfg.PinGreen > 0 {
  594. payload["pin_green"] = targetCfg.PinGreen
  595. }
  596. if targetCfg.PinYellow > 0 {
  597. payload["pin_yellow"] = targetCfg.PinYellow
  598. }
  599. if req.Reset {
  600. payload["factory_reset"] = true
  601. }
  602. if err := s.mqttClient.PublishRaw(targetCfg.ConfigTopic, payload); err != nil {
  603. logger.Error("推送设备配置失败: %v", err)
  604. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: "推送配置失败: " + err.Error()})
  605. return
  606. }
  607. logger.Info("设备配置已推送到 topic: %s", targetCfg.ConfigTopic)
  608. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "配置已推送"})
  609. }
  610. func (s *Server) listDeviceConfigs(w http.ResponseWriter, r *http.Request) {
  611. configs, err := s.db.ListDeviceConfigs()
  612. if err != nil {
  613. logger.Error("查询设备配置列表失败: %v", err)
  614. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  615. return
  616. }
  617. logger.Debug("查询设备配置列表: %d 条", len(configs))
  618. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "ok", Data: configs})
  619. }
  620. func (s *Server) createDeviceConfig(w http.ResponseWriter, r *http.Request) {
  621. var cfg database.DeviceConfig
  622. if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
  623. logger.Warn("创建设备配置请求体解析失败: %v", err)
  624. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "无效的请求体"})
  625. return
  626. }
  627. if cfg.DeviceName == "" {
  628. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "device_name 不能为空"})
  629. return
  630. }
  631. if cfg.ConfigTopic == "" {
  632. cfg.ConfigTopic = "agent/status/config"
  633. }
  634. if err := s.db.SaveDeviceConfig(&cfg); err != nil {
  635. logger.Error("创建设备配置失败: %v", err)
  636. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  637. return
  638. }
  639. logger.Info("设备配置已创建: id=%d, device=%s", cfg.ID, cfg.DeviceName)
  640. writeJSON(w, http.StatusCreated, Response{Code: 0, Message: "创建成功", Data: cfg})
  641. }
  642. func (s *Server) getDeviceConfig(w http.ResponseWriter, id int) {
  643. configs, err := s.db.ListDeviceConfigs()
  644. if err != nil {
  645. logger.Error("查询设备配置失败: id=%d, %v", id, err)
  646. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  647. return
  648. }
  649. for _, cfg := range configs {
  650. if cfg.ID == id {
  651. logger.Debug("查询设备配置: id=%d", id)
  652. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "ok", Data: cfg})
  653. return
  654. }
  655. }
  656. logger.Warn("设备配置不存在: id=%d", id)
  657. writeJSON(w, http.StatusNotFound, Response{Code: -1, Message: "配置不存在"})
  658. }
  659. func (s *Server) updateDeviceConfig(w http.ResponseWriter, r *http.Request, id int) {
  660. var cfg database.DeviceConfig
  661. if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
  662. logger.Warn("更新设备配置请求体解析失败: id=%d, %v", id, err)
  663. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "无效的请求体"})
  664. return
  665. }
  666. cfg.ID = id
  667. if cfg.DeviceName == "" {
  668. writeJSON(w, http.StatusBadRequest, Response{Code: -1, Message: "device_name 不能为空"})
  669. return
  670. }
  671. if cfg.ConfigTopic == "" {
  672. cfg.ConfigTopic = "agent/status/config"
  673. }
  674. if err := s.db.SaveDeviceConfig(&cfg); err != nil {
  675. logger.Error("更新设备配置失败: id=%d, %v", id, err)
  676. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  677. return
  678. }
  679. logger.Info("设备配置已更新: id=%d, device=%s", id, cfg.DeviceName)
  680. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "更新成功", Data: cfg})
  681. }
  682. func (s *Server) deleteDeviceConfig(w http.ResponseWriter, id int) {
  683. if err := s.db.DeleteDeviceConfig(id); err != nil {
  684. logger.Error("删除设备配置失败: id=%d, %v", id, err)
  685. writeJSON(w, http.StatusInternalServerError, Response{Code: -1, Message: err.Error()})
  686. return
  687. }
  688. logger.Info("设备配置已删除: id=%d", id)
  689. writeJSON(w, http.StatusOK, Response{Code: 0, Message: "删除成功"})
  690. }