-
Notifications
You must be signed in to change notification settings - Fork 8
/
segdsp.go
314 lines (255 loc) · 7.1 KB
/
segdsp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/racerxdl/radioserver/client"
"github.com/racerxdl/radioserver/protocol"
"github.com/racerxdl/segdsp/demodcore"
"github.com/racerxdl/segdsp/dsp/fft"
"github.com/racerxdl/segdsp/eventmanager"
"github.com/racerxdl/segdsp/recorders"
"github.com/racerxdl/segdsp/tools"
"log"
"math"
"net/http"
"os"
"os/signal"
"runtime/pprof"
"syscall"
"time"
)
var displayRange = 90
var displayOffset = -60
var lastFFT []float32
var fftSamples []uint8
var fftSamplesF []float32
var smartIqSamples []complex64
type segdspCallback struct {
rs *client.RadioClient
}
func (cb *segdspCallback) OnSmartData(data []complex64) {
go onSmartIQ(cb.rs, data)
}
func (cb *segdspCallback) OnData(data []complex64) {
addComplex(data)
}
func onDeviceSync(rs *client.RadioClient) {
var d = deviceMessage{
DeviceName: rs.GetName(),
DisplayCenterFrequency: rs.GetSmartCenterFrequency(),
DisplayBandwidth: rs.GetSmartSampleRate(),
DisplayOffset: int32(displayOffset),
DisplayRange: int32(displayRange),
DisplayPixels: uint32(displayPixels),
CurrentSampleRate: rs.GetSampleRate(),
ChannelCenterFrequency: rs.GetCenterFrequency(),
Gain: rs.GetGain(),
OutputRate: uint32(outputRate),
FilterBandwidth: uint32(filterBandwidth),
DemodulatorMode: demodulatorMode,
DemodulatorParams: nil,
StationName: stationName,
WebCanControl: webCanControl,
TCPCanControl: tcpCanControl,
IsMuted: false,
}
if demodulator != nil {
d.DemodulatorParams = demodulator.GetDemodParams()
d.IsMuted = demodulator.IsMuted()
}
currDevice = makeDeviceMessage(d)
refreshDevice()
}
func refreshDevice() {
sendPacket := currDevice.Gain != protocol.Invalid
if sendPacket {
m, err := json.Marshal(currDevice)
if err != nil {
log.Println("Error serializing JSON: ", err)
}
go broadcastMessage(string(m))
}
}
func onSmartIQ(rs *client.RadioClient, data []complex64) {
var scale = 256 / float32(displayRange)
data = data[:displayPixels]
if smartIqSamples == nil || len(smartIqSamples) != len(data) {
smartIqSamples = make([]complex64, len(data))
}
copy(smartIqSamples, data)
fftCData := fft.FFT(smartIqSamples)
var l = len(fftCData)
var scaledV float32
if fftSamples == nil || len(fftSamples) != len(fftCData) {
fftSamples = make([]uint8, len(fftCData))
fftSamplesF = make([]float32, len(fftCData))
}
if lastFFT == nil || len(lastFFT) != len(fftSamples) {
lastFFT = make([]float32, len(fftCData))
}
for i, v := range fftCData {
var m = float64(tools.ComplexAbsSquared(v) * (1.0 / float32(rs.GetSmartSampleRate())))
var o = float32(10 * math.Log10(m))
fftSamplesF[i] = o
}
for i := range fftSamplesF {
fftSamplesF[i] = (lastFFT[i] + fftSamplesF[i]) / 2
}
copy(lastFFT, fftSamplesF)
for i, v := range fftSamplesF {
// FFT is symmetric
var oI = (i + l/2) % l
scaledV = 255 + ((v - float32(displayOffset)) * scale)
if scaledV < 0 {
scaledV = 0
} else if scaledV > 255 {
scaledV = 255
}
fftSamples[oI] = uint8(scaledV)
}
onFFT(fftSamples)
}
func onFFT(data []uint8) {
//log.Println("Received FFT! ", len(data))
var j = makeFFTMessage(data, demodulator.GetLevel())
m, err := json.Marshal(j)
if err != nil {
log.Println("Error serializing JSON: ", err)
}
go broadcastMessage(string(m))
}
func sendData(data interface{}) {
switch data := data.(type) {
case demodcore.DemodData:
var b = data
go broadcastBMessage(b.Data.MarshalByteArray())
go recordAudio(b.Data)
default:
var j = makeDataMessage(data)
m, err := json.Marshal(j)
if err != nil {
log.Println("Error serializing JSON: ", err)
}
go broadcastMessage(string(m))
}
}
func createServer() *http.Server {
srv := &http.Server{Addr: httpAddr}
fs := http.FileServer(http.Dir("./content/static"))
http.HandleFunc("/ws", ws)
http.Handle("/static/", http.StripPrefix("/static", fs))
http.HandleFunc("/", content)
go func() {
log.Println(http.ListenAndServe(httpAddr, nil))
}()
return srv
}
var squelchOn chan interface{}
var squelchOff chan interface{}
func onSquelchOn(data eventmanager.SquelchEventData) {
log.Println("Squelch ON", data.AvgValue, data.Threshold)
currDevice.IsMuted = demodulator.IsMuted()
stopRecording()
refreshDevice()
}
func onSquelchOff(data eventmanager.SquelchEventData) {
log.Println("Squelch OFF", data.AvgValue, data.Threshold)
currDevice.IsMuted = demodulator.IsMuted()
startRecording()
refreshDevice()
}
func main() {
var err error
setEnv()
log.SetFlags(0)
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Println(err)
return
}
log.Println("Starting CPU Profile")
err = pprof.StartCPUProfile(f)
if err != nil {
panic(err)
}
defer pprof.StopCPUProfile()
}
squelchOn = make(chan interface{})
squelchOff = make(chan interface{})
var ev = eventmanager.EventManager{}
ev.AddHandler(eventmanager.EvSquelchOn, squelchOn)
ev.AddHandler(eventmanager.EvSquelchOff, squelchOff)
go func() {
log.Println("Starting Handler loop")
for {
select {
case msg := <-squelchOn:
onSquelchOn(msg.(eventmanager.SquelchEventData))
case msg := <-squelchOff:
onSquelchOff(msg.(eventmanager.SquelchEventData))
}
}
//log.Println("Ending Handler loop")
}()
recorder = &recorders.FileRecorder{}
recordingParams.recorderEnable = record
if recordMethod != "file" {
panic("Only\"file\" method is supported for recording.")
}
initDSP()
var rs = client.MakeRadioClient(radioserverhost, "User", "SegDSP")
var cb = segdspCallback{
rs: rs,
}
rs.SetCallback(&cb)
rs.Connect()
defer rs.Disconnect()
log.Println(fmt.Sprintf("Device: %s", rs.GetName()))
var srs = rs.GetAvailableSampleRates()
log.Println("Available SampleRates:")
for i := 0; i < len(srs); i++ {
log.Println(fmt.Sprintf(" %f msps (dec stage %d)", float32(srs[i])/1e6, i))
}
rs.SetIQEnabled(true)
rs.SetSmartIQEnabled(true)
rs.SetSmartDecimation(uint32(displayDecimationStage))
rs.SetSmartCenterFrequency(uint32(displayFrequency))
if rs.SetDecimationStage(uint32(channelDecimationStage)) == protocol.Invalid {
log.Println("Error setting sample rate.")
}
if rs.SetCenterFrequency(uint32(channelFrequency)) == protocol.Invalid {
log.Println("Error setting center frequency.")
}
time.Sleep(10 * time.Millisecond)
log.Println("IQ Sample Rate: ", rs.GetSampleRate())
log.Println("IQ Center Frequency ", rs.GetCenterFrequency())
log.Println("SmartIQ Center Frequency ", rs.GetSmartCenterFrequency())
log.Println("SmartIQ Sample Rate: ", rs.GetSmartSampleRate())
demodulator = buildDSP(rs.GetSampleRate())
demodulator.SetEventManager(&ev)
dspCb = sendData
sigs := make(chan os.Signal, 1)
done := make(chan bool, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
fmt.Println(sig)
done <- true
}()
var srv = createServer()
onDeviceSync(rs)
startDSP()
log.Println("Starting")
rs.Start()
<-done
err = srv.Shutdown(context.TODO())
if err != nil {
log.Println(err)
}
log.Print("Stopping")
rs.Stop()
stopDSP()
fmt.Println("Work Done")
}