Wideband autonomous SDR analysis engine forked from sdr-visual-suite
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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