api.go 24 KB

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