Wideband autonomous SDR analysis engine forked from sdr-visual-suite
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

283 líneas
10KB

  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "log"
  6. "net/http"
  7. "os"
  8. "path/filepath"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "time"
  13. "sdr-wideband-suite/internal/config"
  14. "sdr-wideband-suite/internal/detector"
  15. "sdr-wideband-suite/internal/events"
  16. "sdr-wideband-suite/internal/pipeline"
  17. fftutil "sdr-wideband-suite/internal/fft"
  18. "sdr-wideband-suite/internal/recorder"
  19. "sdr-wideband-suite/internal/runtime"
  20. )
  21. func registerAPIHandlers(mux *http.ServeMux, cfgPath string, cfgManager *runtime.Manager, srcMgr *sourceManager, dspUpdates chan dspUpdate, gpuState *gpuStatus, recMgr *recorder.Manager, sigSnap *signalSnapshot, eventMu *sync.RWMutex) {
  22. mux.HandleFunc("/api/config", func(w http.ResponseWriter, r *http.Request) {
  23. w.Header().Set("Content-Type", "application/json")
  24. switch r.Method {
  25. case http.MethodGet:
  26. _ = json.NewEncoder(w).Encode(cfgManager.Snapshot())
  27. case http.MethodPost:
  28. var update runtime.ConfigUpdate
  29. if err := json.NewDecoder(r.Body).Decode(&update); err != nil {
  30. http.Error(w, "invalid json", http.StatusBadRequest)
  31. return
  32. }
  33. prev := cfgManager.Snapshot()
  34. next, err := cfgManager.ApplyConfig(update)
  35. if err != nil {
  36. http.Error(w, err.Error(), http.StatusBadRequest)
  37. return
  38. }
  39. sourceChanged := prev.CenterHz != next.CenterHz || prev.SampleRate != next.SampleRate || prev.GainDb != next.GainDb || prev.AGC != next.AGC || prev.TunerBwKHz != next.TunerBwKHz
  40. if sourceChanged {
  41. if err := srcMgr.ApplyConfig(next); err != nil {
  42. cfgManager.Replace(prev)
  43. http.Error(w, "failed to apply source config", http.StatusInternalServerError)
  44. return
  45. }
  46. }
  47. if err := config.Save(cfgPath, next); err != nil {
  48. log.Printf("config save failed: %v", err)
  49. }
  50. detChanged := prev.Detector.ThresholdDb != next.Detector.ThresholdDb ||
  51. prev.Detector.MinDurationMs != next.Detector.MinDurationMs ||
  52. prev.Detector.HoldMs != next.Detector.HoldMs ||
  53. prev.Detector.EmaAlpha != next.Detector.EmaAlpha ||
  54. prev.Detector.HysteresisDb != next.Detector.HysteresisDb ||
  55. prev.Detector.MinStableFrames != next.Detector.MinStableFrames ||
  56. prev.Detector.GapToleranceMs != next.Detector.GapToleranceMs ||
  57. prev.Detector.CFARMode != next.Detector.CFARMode ||
  58. prev.Detector.CFARGuardHz != next.Detector.CFARGuardHz ||
  59. prev.Detector.CFARTrainHz != next.Detector.CFARTrainHz ||
  60. prev.Detector.CFARRank != next.Detector.CFARRank ||
  61. prev.Detector.CFARScaleDb != next.Detector.CFARScaleDb ||
  62. prev.Detector.CFARWrapAround != next.Detector.CFARWrapAround ||
  63. prev.SampleRate != next.SampleRate ||
  64. prev.FFTSize != next.FFTSize
  65. windowChanged := prev.FFTSize != next.FFTSize
  66. var newDet *detector.Detector
  67. var newWindow []float64
  68. if detChanged {
  69. newDet = detector.New(next.Detector, next.SampleRate, next.FFTSize)
  70. }
  71. if windowChanged {
  72. newWindow = fftutil.Hann(next.FFTSize)
  73. }
  74. pushDSPUpdate(dspUpdates, dspUpdate{cfg: next, det: newDet, window: newWindow, dcBlock: next.DCBlock, iqBalance: next.IQBalance, useGPUFFT: next.UseGPUFFT})
  75. _ = json.NewEncoder(w).Encode(next)
  76. default:
  77. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  78. }
  79. })
  80. mux.HandleFunc("/api/sdr/settings", func(w http.ResponseWriter, r *http.Request) {
  81. w.Header().Set("Content-Type", "application/json")
  82. if r.Method != http.MethodPost {
  83. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  84. return
  85. }
  86. var update runtime.SettingsUpdate
  87. if err := json.NewDecoder(r.Body).Decode(&update); err != nil {
  88. http.Error(w, "invalid json", http.StatusBadRequest)
  89. return
  90. }
  91. prev := cfgManager.Snapshot()
  92. next, err := cfgManager.ApplySettings(update)
  93. if err != nil {
  94. http.Error(w, err.Error(), http.StatusBadRequest)
  95. return
  96. }
  97. if prev.AGC != next.AGC || prev.TunerBwKHz != next.TunerBwKHz {
  98. if err := srcMgr.ApplyConfig(next); err != nil {
  99. cfgManager.Replace(prev)
  100. http.Error(w, "failed to apply sdr settings", http.StatusInternalServerError)
  101. return
  102. }
  103. }
  104. if prev.DCBlock != next.DCBlock || prev.IQBalance != next.IQBalance {
  105. pushDSPUpdate(dspUpdates, dspUpdate{cfg: next, dcBlock: next.DCBlock, iqBalance: next.IQBalance})
  106. }
  107. if err := config.Save(cfgPath, next); err != nil {
  108. log.Printf("config save failed: %v", err)
  109. }
  110. _ = json.NewEncoder(w).Encode(next)
  111. })
  112. mux.HandleFunc("/api/stats", func(w http.ResponseWriter, r *http.Request) {
  113. w.Header().Set("Content-Type", "application/json")
  114. _ = json.NewEncoder(w).Encode(srcMgr.Stats())
  115. })
  116. mux.HandleFunc("/api/gpu", func(w http.ResponseWriter, r *http.Request) {
  117. w.Header().Set("Content-Type", "application/json")
  118. _ = json.NewEncoder(w).Encode(gpuState.snapshot())
  119. })
  120. mux.HandleFunc("/api/pipeline/policy", func(w http.ResponseWriter, r *http.Request) {
  121. w.Header().Set("Content-Type", "application/json")
  122. cfg := cfgManager.Snapshot()
  123. _ = json.NewEncoder(w).Encode(pipeline.PolicyFromConfig(cfg))
  124. })
  125. mux.HandleFunc("/api/events", func(w http.ResponseWriter, r *http.Request) {
  126. w.Header().Set("Content-Type", "application/json")
  127. limit := 200
  128. if v := r.URL.Query().Get("limit"); v != "" {
  129. if parsed, err := strconv.Atoi(v); err == nil {
  130. limit = parsed
  131. }
  132. }
  133. var since time.Time
  134. if v := r.URL.Query().Get("since"); v != "" {
  135. if parsed, err := parseSince(v); err == nil {
  136. since = parsed
  137. } else {
  138. http.Error(w, "invalid since", http.StatusBadRequest)
  139. return
  140. }
  141. }
  142. snap := cfgManager.Snapshot()
  143. eventMu.RLock()
  144. evs, err := events.ReadRecent(snap.EventPath, limit, since)
  145. eventMu.RUnlock()
  146. if err != nil {
  147. http.Error(w, "failed to read events", http.StatusInternalServerError)
  148. return
  149. }
  150. _ = json.NewEncoder(w).Encode(evs)
  151. })
  152. mux.HandleFunc("/api/signals", func(w http.ResponseWriter, r *http.Request) {
  153. w.Header().Set("Content-Type", "application/json")
  154. if sigSnap == nil {
  155. _ = json.NewEncoder(w).Encode([]detector.Signal{})
  156. return
  157. }
  158. _ = json.NewEncoder(w).Encode(sigSnap.get())
  159. })
  160. mux.HandleFunc("/api/candidates", func(w http.ResponseWriter, r *http.Request) {
  161. w.Header().Set("Content-Type", "application/json")
  162. if sigSnap == nil {
  163. _ = json.NewEncoder(w).Encode([]pipeline.Candidate{})
  164. return
  165. }
  166. sigs := sigSnap.get()
  167. _ = json.NewEncoder(w).Encode(pipeline.CandidatesFromSignals(sigs, "tracked-signal-snapshot"))
  168. })
  169. mux.HandleFunc("/api/decoders", func(w http.ResponseWriter, r *http.Request) {
  170. w.Header().Set("Content-Type", "application/json")
  171. _ = json.NewEncoder(w).Encode(decoderKeys(cfgManager.Snapshot()))
  172. })
  173. mux.HandleFunc("/api/recordings", func(w http.ResponseWriter, r *http.Request) {
  174. if r.Method != http.MethodGet {
  175. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  176. return
  177. }
  178. w.Header().Set("Content-Type", "application/json")
  179. snap := cfgManager.Snapshot()
  180. list, err := recorder.ListRecordings(snap.Recorder.OutputDir)
  181. if err != nil {
  182. http.Error(w, "failed to list recordings", http.StatusInternalServerError)
  183. return
  184. }
  185. _ = json.NewEncoder(w).Encode(list)
  186. })
  187. mux.HandleFunc("/api/recordings/", func(w http.ResponseWriter, r *http.Request) {
  188. w.Header().Set("Content-Type", "application/json")
  189. id := strings.TrimPrefix(r.URL.Path, "/api/recordings/")
  190. if id == "" {
  191. http.Error(w, "missing id", http.StatusBadRequest)
  192. return
  193. }
  194. snap := cfgManager.Snapshot()
  195. base := filepath.Clean(filepath.Join(snap.Recorder.OutputDir, id))
  196. if !strings.HasPrefix(base, filepath.Clean(snap.Recorder.OutputDir)) {
  197. http.Error(w, "invalid path", http.StatusBadRequest)
  198. return
  199. }
  200. if r.URL.Path == "/api/recordings/"+id+"/audio" {
  201. http.ServeFile(w, r, filepath.Join(base, "audio.wav"))
  202. return
  203. }
  204. if r.URL.Path == "/api/recordings/"+id+"/iq" {
  205. http.ServeFile(w, r, filepath.Join(base, "signal.cf32"))
  206. return
  207. }
  208. if r.URL.Path == "/api/recordings/"+id+"/decode" {
  209. mode := r.URL.Query().Get("mode")
  210. cmd := buildDecoderMap(cfgManager.Snapshot())[mode]
  211. if cmd == "" {
  212. http.Error(w, "decoder not configured", http.StatusBadRequest)
  213. return
  214. }
  215. meta, err := recorder.ReadMeta(filepath.Join(base, "meta.json"))
  216. if err != nil {
  217. http.Error(w, "meta read failed", http.StatusInternalServerError)
  218. return
  219. }
  220. audioPath := filepath.Join(base, "audio.wav")
  221. if _, errStat := os.Stat(audioPath); errStat != nil {
  222. audioPath = ""
  223. }
  224. res, err := recorder.DecodeOnDemand(cmd, filepath.Join(base, "signal.cf32"), meta.SampleRate, audioPath)
  225. if err != nil {
  226. http.Error(w, res.Stderr, http.StatusInternalServerError)
  227. return
  228. }
  229. _ = json.NewEncoder(w).Encode(res)
  230. return
  231. }
  232. http.ServeFile(w, r, filepath.Join(base, "meta.json"))
  233. })
  234. mux.HandleFunc("/api/streams", func(w http.ResponseWriter, r *http.Request) {
  235. w.Header().Set("Content-Type", "application/json")
  236. n := recMgr.ActiveStreams()
  237. _ = json.NewEncoder(w).Encode(map[string]any{"active_sessions": n})
  238. })
  239. mux.HandleFunc("/api/demod", func(w http.ResponseWriter, r *http.Request) {
  240. if r.Method != http.MethodGet {
  241. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  242. return
  243. }
  244. q := r.URL.Query()
  245. freq, _ := strconv.ParseFloat(q.Get("freq"), 64)
  246. bw, _ := strconv.ParseFloat(q.Get("bw"), 64)
  247. sec, _ := strconv.Atoi(q.Get("sec"))
  248. if sec < 1 {
  249. sec = 1
  250. }
  251. if sec > 10 {
  252. sec = 10
  253. }
  254. mode := q.Get("mode")
  255. data, _, err := recMgr.DemodLive(freq, bw, mode, sec)
  256. if err != nil {
  257. http.Error(w, err.Error(), http.StatusBadRequest)
  258. return
  259. }
  260. w.Header().Set("Content-Type", "audio/wav")
  261. _, _ = w.Write(data)
  262. })
  263. }
  264. func newHTTPServer(addr string, webRoot string, h *hub, cfgPath string, cfgManager *runtime.Manager, srcMgr *sourceManager, dspUpdates chan dspUpdate, gpuState *gpuStatus, recMgr *recorder.Manager, sigSnap *signalSnapshot, eventMu *sync.RWMutex) *http.Server {
  265. mux := http.NewServeMux()
  266. registerWSHandlers(mux, h, recMgr)
  267. registerAPIHandlers(mux, cfgPath, cfgManager, srcMgr, dspUpdates, gpuState, recMgr, sigSnap, eventMu)
  268. mux.Handle("/", http.FileServer(http.Dir(webRoot)))
  269. return &http.Server{Addr: addr, Handler: mux}
  270. }
  271. func shutdownServer(server *http.Server) {
  272. ctxTimeout, cancelTimeout := context.WithTimeout(context.Background(), 5*time.Second)
  273. defer cancelTimeout()
  274. _ = server.Shutdown(ctxTimeout)
  275. }