api.go 22 KB

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