-
Notifications
You must be signed in to change notification settings - Fork 0
/
demodWindow.py
338 lines (282 loc) · 11.9 KB
/
demodWindow.py
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
from PySide6.QtWidgets import QMainWindow, QVBoxLayout, QHBoxLayout, QFormLayout, QWidget, QLabel, QComboBox, QPushButton
from PySide6.QtWidgets import QSpinBox, QMessageBox, QLineEdit, QTextBrowser, QSlider, QGroupBox, QRadioButton
from PySide6.QtCore import Qt, Signal, Slot, QRectF
# from PySide6.QtGui import QFontDatabase
import pyqtgraph as pg
import numpy as np
import scipy.signal as sps
from functools import partial
from dsp import makeFreq, SimpleDemodulatorBPSK, SimpleDemodulatorQPSK, SimpleDemodulator8PSK, SimpleDemodulatorPSK
class DemodWindow(QMainWindow):
def __init__(self, slicedData=None, startIdx=None, endIdx=None, fs=1.0):
super().__init__()
# Attaching data
self.slicedData = slicedData
self.fs = int(fs)
# Aesthetics..
self.setWindowTitle("Demodulator")
# Main layout
widget = QWidget()
self.layout = QVBoxLayout()
widget.setLayout(self.layout)
self.setCentralWidget(widget)
self.topLayout = QHBoxLayout()
self.layout.addLayout(self.topLayout)
self.midLayout = QHBoxLayout()
self.layout.addLayout(self.midLayout)
self.btmLayout = QHBoxLayout()
self.layout.addLayout(self.btmLayout)
# Plots
self.setupPlots() # This has to be before setupOptions for layout reasons
# Options menus
self.setupOptions()
# Bits results
self.setupBitsViews()
# Object holder for the demodulator
self.demodulator = None
# Holders for the demodulator constellation selection
self.txtanchor = None # These follow QTextCursor
self.txtposition = None
def setupBitsViews(self):
self.rotGrpBox = QGroupBox()
self.btmLayout.addWidget(self.rotGrpBox)
self.rotGrpLayout = QVBoxLayout()
self.rotGrpBox.setLayout(self.rotGrpLayout)
# Preload many radio buttons
self.rotRadioBtns = [
QRadioButton() for i in range(8) # For now, 8 maximum
]
for i, btn in enumerate(self.rotRadioBtns):
self.rotGrpLayout.addWidget(btn)
# Start out as hidden
btn.hide()
# Connect it
btn.clicked.connect(partial(self.rotChanged, i))
self.phaseBrowser = QTextBrowser()
self.phaseBrowser.setFontFamily("Monospace")
self.phaseBrowser.selectionChanged.connect(self.onPhaseBrowserSelectionChanged)
self.btmLayout.addWidget(self.phaseBrowser)
self.hexBrowser = QTextBrowser()
# self.hexBrowser.setMinimumHeight(300)
self.hexBrowser.setFontFamily("Monospace")
self.btmLayout.addWidget(self.hexBrowser)
self.asciiBrowser = QTextBrowser()
self.asciiBrowser.setFontFamily("Monospace")
self.btmLayout.addWidget(self.asciiBrowser)
def setupPlots(self):
# ==== Top layout
# Left: abs plot with selection controls below,
# right: main demod options (see setupOptions)
self.abswin = pg.GraphicsLayoutWidget()
self.topLayout.addWidget(self.abswin)
self.absplt = self.abswin.addPlot()
self.abspltitem = self.absplt.plot(
np.arange(self.slicedData.size)/self.fs, np.abs(self.slicedData))
# ==== Vertical middle layout
# Left: the eye opening plot, right: the constellation plot
self.rwin = pg.GraphicsLayoutWidget()
self.rwin.setMinimumHeight(300)
self.midLayout.addWidget(self.rwin)
self.eoplt = self.rwin.addPlot(0, 0)
self.conplt = self.rwin.addPlot(0, 1)
self.symSizeSlider = QSlider(Qt.Vertical)
self.symSizeSlider.setRange(1, 100)
self.midLayout.addWidget(self.symSizeSlider)
self.symSizeSlider.valueChanged.connect(self.adjustSymSize)
def setupOptions(self):
self.optOuterLayout = QVBoxLayout()
self.topLayout.addLayout(self.optOuterLayout)
self.optLayout = QFormLayout()
self.optOuterLayout.addLayout(self.optLayout)
self.modDropdown = QComboBox()
self.modtypestrings = ["Select Scheme", "BPSK", "QPSK", "8PSK"]
self.modDropdown.addItems(self.modtypestrings)
self.modDropdown.currentIndexChanged.connect(self.makeDemodulator)
self.optLayout.addRow("Modulation Type", self.modDropdown)
self.fsLabel = QLabel(str(self.fs))
self.optLayout.addRow("Input Sample Rate: ", self.fsLabel)
self.baud = 1
self.baudSpinbox = QSpinBox()
# Arbitrarily set maximum to int32 max
self.baudSpinbox.setRange(1, 2147483647)
self.baudSpinbox.valueChanged.connect(self.setBaud)
self.optLayout.addRow("Baud Rate", self.baudSpinbox)
self.osrSpinbox = QSpinBox()
self.osr = 1
self.osrSpinbox.setMinimum(1)
self.osrSpinbox.valueChanged.connect(self.osrChanged)
self.optLayout.addRow("Target OSR", self.osrSpinbox)
self.updownLabel = QLabel()
self.optLayout.addRow("Resample Factors: ", self.updownLabel)
self.finalfsLabel = QLabel()
self.optLayout.addRow("Output Sample Rate: ", self.finalfsLabel)
# Call the slot once to initialize the other values
self.osrChanged(self.osr)
self.demodBtn = QPushButton("Demodulate")
self.demodBtn.clicked.connect(self.runDemod)
self.optOuterLayout.addWidget(self.demodBtn)
@Slot(int)
def adjustSymSize(self, size):
symSize = size / 100 * self.maxSymbolSize
self.conpltitem.setSymbolSize(symSize)
@Slot(int)
def setBaud(self, baud):
self.baud = baud
# Re-evaluate the resampling factors
self.evaluateResampling()
@Slot(int)
def osrChanged(self, osr):
self.osr = osr
# Re-evaluate the resampling factors
self.evaluateResampling()
def evaluateResampling(self):
# Evaluate the resample factors
self.up = np.lcm(self.fs, self.osr * self.baud) // self.fs
self.down = np.lcm(self.fs, self.osr *
self.baud) // (self.baud * self.osr)
self.finalfs = self.osr * self.baud
# Place them in their widgets
self.updownLabel.setText("%d/%d" % (self.up, self.down))
self.finalfsLabel.setText("%f" % self.finalfs)
@Slot(int)
def makeDemodulator(self, modidx: int):
modtype = self.modtypestrings[modidx]
if modtype == 'BPSK':
self.demodulator = SimpleDemodulatorBPSK()
print("Created BPSK")
elif modtype == 'QPSK':
self.demodulator = SimpleDemodulatorQPSK()
print("Created QPSK")
elif modtype == '8PSK':
self.demodulator = SimpleDemodulator8PSK()
print("Created 8PSK")
else:
self.demodulator = None
@Slot()
def runDemod(self):
# Clear the plots (important otherwise gets messy on reruns)
self.conplt.clear()
self.eoplt.clear()
# Ensure a scheme is selected
if self.modDropdown.currentText() == self.modtypestrings[0]:
# Raise dialog to say already exists
QMessageBox.critical(
self,
"Invalid Options",
"Please select a modulation scheme.",
QMessageBox.Ok)
return
# First check if need to resample
if self.up > 1 or self.down > 1:
# Run the resampling
resampled = sps.resample_poly(self.slicedData, self.up, self.down)
else:
resampled = self.slicedData
# Run demodulator
if resampled.size % self.osr != 0:
resampled = resampled[:-(resampled.size % self.osr)]
self.demodulator.demod(resampled.astype(
np.complex64), self.osr, verb=False)
# Plot the eye-opening
self.eoplt.clear() # Clear plot for re-runs
self.eopltitem = self.eoplt.plot(
self.demodulator.eo_metric
)
# Plot the constellation
self.plotConstellation()
# Update the options for rotation
self.updateRotations()
# Interpret and post to text browsers
self.interpret()
def plotConstellation(self, start: int = 0, end: int = None):
# Default to plot all
if end is None:
end = self.demodulator.reimc.size
self.conplt.clear() # Clear plot for re-runs
# Plot the constellation
maxbound = np.max(self.demodulator.reimc.view(np.float32)) * 1.5
self.conpltitem = self.conplt.plot(
np.real(self.demodulator.reimc[start:end]),
np.imag(self.demodulator.reimc[start:end]),
symbol='o',
symbolPen=None,
symbolBrush='w',
pen=None
)
self.maxSymbolSize = self.conpltitem.opts['symbolSize']
self.symSizeSlider.setValue(100) # Maximum at the start
self.conplt.setLimits(
xMin=-maxbound*2,
xMax=maxbound*2, # Need longer range for x when window is viewed in standard 16:9
yMin=-maxbound,
yMax=maxbound
)
self.conplt.setAspectLocked()
def interpret(self, phaseSymShift: int = 0):
# ======= Update the text browsers
# The phase browser ignores the plain text selection
self.phaseBrowser.setPlainText(
"".join(["%d" % (i) for i in self.demodulator.syms])
)
# Search for the one with the best readable text
iSkip, utf8chars = self.demodulator.findPlainText(
phaseSymShift=phaseSymShift)
# TODO: add widget to turn this off i.e. manually select the skips
hexvals = self.demodulator.packBinaryBytesToBits(
self.demodulator.unpackToBinaryBytes(
self.demodulator.symsToBits(
self.demodulator.syms[iSkip:],
phaseSymShift=phaseSymShift)
)
)
self.hexBrowser.setPlainText(
' '.join(["%02X" % i for i in hexvals])
# ' '.join([np.base_repr(i, base=16) for i in hexvals])
)
# There may be issues converting to a readable string..
readable = hexvals.tobytes().decode("utf-8", "backslashreplace")
# May contain null chars?
readable = readable.replace("\0", " ") # Replace with spaces?
self.asciiBrowser.setPlainText(
str(readable)
)
def updateRotations(self):
# Only show buttons up to the current mod type
[self.rotRadioBtns[i].show() for i in range(self.demodulator.m)]
# Hide everything after
[self.rotRadioBtns[i].hide() for i in range(
self.demodulator.m, len(self.rotRadioBtns))]
# Check the first one
self.rotRadioBtns[0].setChecked(True)
@Slot(int)
def rotChanged(self, i: int):
print("Rotation %d selected" % i)
# Reinterpret
self.interpret(i)
@Slot()
def onPhaseBrowserSelectionChanged(self):
# Note, this seems to fire very often, even
# when the selection doesn't change i.e.
# when mouse moves but not enough to select 1 more letter,
# this still fires; hence we should track and replot only
# when actual changes happen
txtCursor = self.phaseBrowser.textCursor()
if (
self.txtanchor != txtCursor.anchor() or
self.txtposition != txtCursor.position()
):
self.txtanchor = txtCursor.anchor()
self.txtposition = txtCursor.position()
# Then figure out start and end
if self.txtanchor < self.txtposition:
start = self.txtanchor
end = self.txtposition
elif self.txtanchor > self.txtposition:
start = self.txtposition
end = self.txtanchor
else:
# No real selection, plot everything again
start = 0
end = len(self.demodulator.syms)
# Replot the constellation
self.plotConstellation(start, end)