-
Notifications
You must be signed in to change notification settings - Fork 5
/
microkiwi_patch.diff
269 lines (259 loc) · 8.95 KB
/
microkiwi_patch.diff
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
--- microkiwi_waterfall.py 2021-06-26 07:48:51.769275069 +0200
+++ microkiwi_waterfall.py 2021-06-26 07:48:51.769275069 +0200
@@ -1,30 +1,61 @@
-import numpy as np
-import struct
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+""" Here is the IS0KYB microkiwi_waterfall script, modified to use python instead of jupyther notebook """
+
+# python 2/3 compatibility
+from __future__ import print_function
+from __future__ import division
+from __future__ import absolute_import
-import array
-import logging
+import numpy as np
import socket
import struct
import time
+import matplotlib.pyplot as plt
+from matplotlib.colors import LinearSegmentedColormap
+import io
from datetime import datetime
-
from kiwi import wsclient
-
import mod_pywebsocket.common
from mod_pywebsocket.stream import Stream
from mod_pywebsocket.stream import StreamOptions
-
from optparse import OptionParser
+from mpl_toolkits.axes_grid1 import make_axes_locatable
+
+processfailed = False
+
+cdict1 = {
+ 'red': ((0.0, 0.0, 0.0),
+ (0.2, 0.0, 0.0),
+ (0.4, 1.0, 1.0),
+ (0.6, 1.0, 1.0),
+ (0.8, 1.0, 1.0),
+ (1.0, 1.0, 1.0)),
+
+ 'green': ((0.0, 0.0, 0.0),
+ (0.2, 0.0, 0.0),
+ (0.4, 1.0, 1.0),
+ (0.6, 0.0, 0.0),
+ (0.8, 0.0, 0.0),
+ (1.0, 0.764, 0.764)),
+
+ 'blue': ((0.0, 0.0, 0.0),
+ (0.2, 1.0, 1.0),
+ (0.4, 0.0, 0.0),
+ (0.6, 0.0, 0.0),
+ (0.8, 1.0, 1.0),
+ (1.0, 1.0, 1.0)),
+}
+
+cmap = LinearSegmentedColormap('SAColorMap', cdict1, 1024)
parser = OptionParser()
-parser.add_option("-f", "--file", dest="filename", type=str,
- help="write waterfall data to binary FILE", metavar="FILE")
parser.add_option("-s", "--server", type=str,
help="server name", dest="server", default='192.168.1.82')
parser.add_option("-p", "--port", type=int,
help="port number", dest="port", default=8073)
parser.add_option("-l", "--length", type=int,
- help="how many samples to draw from the server", dest="length", default=100)
+ help="how many samples to draw from the server", dest="length", default=200)
parser.add_option("-z", "--zoom", type=int,
help="zoom factor", dest="zoom", default=0)
parser.add_option("-o", "--offset", type=int,
@@ -32,126 +63,124 @@
parser.add_option("-v", "--verbose", type=int,
help="whether to print progress and debug info", dest="verbosity", default=0)
-
options = vars(parser.parse_args()[0])
-
-if 'filename' in options:
- filename = options['filename']
-else:
- filename = None
-
host = options['server']
port = options['port']
-print "KiwiSDR Server: %s:%d" % (host,port)
+
# the default number of bins is 1024
bins = 1024
-print "Number of waterfall bins: %d" % bins
-
zoom = options['zoom']
-print "Zoom factor:", zoom
-
-offset_khz = options['start'] # this is offset in kHz
-
-full_span = 30000.0 # for a 30MHz kiwiSDR
-if zoom>0:
- span = full_span / 2.**zoom
+offset_khz = options['start'] # this is offset in kHz
+full_span = 30000 # for a 30MHz kiwiSDR
+if zoom > 0:
+ span = full_span // 2.**zoom
else:
- span = full_span
-
-rbw = span/bins
-if offset_khz>0:
-# offset = (offset_khz-span/2)/(full_span/bins)*2**(zoom)*1000.
- offset = (offset_khz+100)/(full_span/bins)*2**(4)*1000.
- offset = max(0, offset)
+ span = full_span
+rbw = span//bins
+if offset_khz > 0:
+ offset = (offset_khz+100)//(full_span//bins)*2**4*1000.
+ offset = max(0, offset)
else:
- offset = 0
-
-print span, offset
-
-center_freq = span/2+offset_khz
-print "Center frequency: %.3f MHz" % (center_freq/1000)
-
-now = str(datetime.now())
+ offset = 0
+center_freq = span//2+offset_khz
+now = b'(datetime.now()'
header = [center_freq, span, now]
header_bin = struct.pack("II26s", *header)
-print "Trying to contact server..."
try:
mysocket = socket.socket()
mysocket.connect((host, port))
except:
- print "Failed to connect"
- exit()
-print "Socket open..."
+ print("Failed to connect")
+ exit()
uri = '/%d/%s' % (int(time.time()), 'W/F')
handshake = wsclient.ClientHandshakeProcessor(mysocket, host, port)
handshake.handshake(uri)
-
request = wsclient.ClientRequest(mysocket)
request.ws_version = mod_pywebsocket.common.VERSION_HYBI13
-
stream_option = StreamOptions()
stream_option.mask_send = True
stream_option.unmask_receive = False
-
mystream = Stream(request, stream_option)
-print "Data stream active..."
-
# send a sequence of messages to the server, hardcoded for now
# max wf speed, no compression
-msg_list = ['SET auth t=kiwi p=', 'SET zoom=%d start=%d'%(zoom,offset),\
-'SET maxdb=0 mindb=-100', 'SET wf_speed=4', 'SET wf_comp=0']
+msg_list = ['SET auth t=kiwi p=', 'SET zoom=%d start=%d' % (zoom, offset),
+ 'SET maxdb=0 mindb=-100', 'SET wf_speed=4', 'SET wf_comp=0']
for msg in msg_list:
mystream.send_message(msg)
-print "Starting to retrieve waterfall data..."
# number of samples to draw from server
length = options['length']
# create a numpy array to contain the waterfall data
wf_data = np.zeros((length, bins))
binary_wf_list = []
time = 0
-while time<length:
+
+while time < length:
# receive one msg from server
- tmp = mystream.receive_message()
- if "W/F" in tmp: # this is one waterfall line
- tmp = tmp[16:] # remove some header from each msg
+ try:
+ tmp = mystream.receive_message()
+ except:
+ processfailed = True
+ break
+ if b'W/F' in tmp: # this is one waterfall line
+ tmp = tmp[16:] # remove some header from each msg
+ print("received sample")
if options['verbosity']:
- print time,
- #spectrum = np.array(struct.unpack('%dB'%len(tmp), tmp) ) # convert from binary data to uint8
- spectrum = np.ndarray(len(tmp), dtype='B', buffer=tmp) # convert from binary data to uint8
- if filename:
- binary_wf_list.append(tmp) # append binary data to be saved to file
- #wf_data[time, :] = spectrum-255 # mirror dBs
+ print(time),
+ spectrum = np.array(struct.unpack('%dB' % len(tmp), tmp)) # convert from binary data to uint8
+ # spectrum = np.ndarray(len(tmp), dtype='B', buffer=tmp) # convert from binary data to uint8
+ binary_wf_list.append(tmp) # append binary data to be saved to file
+ # wf_data[time, :] = spectrum-255 # mirror dBs
wf_data[time, :] = spectrum
wf_data[time, :] = -(255 - wf_data[time, :]) # dBm
wf_data[time, :] = wf_data[time, :] - 13 # typical Kiwi wf cal
time += 1
- else: # this is chatter between client and server
- #print tmp
+ else: # this is chatter between client and server
pass
try:
mystream.close_connection(mod_pywebsocket.common.STATUS_GOING_AWAY)
mysocket.close()
except Exception as e:
- print "exception: %s" % e
-
-
-avg_wf = np.mean(wf_data, axis=0) # average over time
+ print("exception: %s" % e)
+avg_wf = np.mean(wf_data, axis=0) # average over time
p95 = np.percentile(avg_wf, 95)
median = np.percentile(avg_wf, 50)
+maxsig = np.max(wf_data)
+minsig = np.min(wf_data)
-print "Average SNR computation..."
-print "Waterfall with %d bins: median= %f dB, p95= %f dB - SNR= %f rbw= %f kHz" % (bins, median, p95,p95-median, rbw)
-
+# print "Waterfall with %d bins: median= %f dB, p95= %f dB - SNR= %f rbw= %f kHz" % (bins, median, p95,p95-median, rbw)
+print("SNR: %i dB [median: %i dB, p95: %i dB, high: %i dBm, low: %i dBm]" % (p95 - median, median, p95, maxsig, minsig))
-if filename:
- print "Saving binary data to file..."
- with open(filename, "wb") as fd:
- fd.write(header_bin) # write the header info at the top
- for line in binary_wf_list:
- fd.write(line)
-print "All done!"
+fd = io.BytesIO() # no more file to write on disk
+fd.write(header_bin) # write the header info at the top
+for line in binary_wf_list:
+ fd.write(line)
+
+fd.seek(0)
+buff = fd.read()
+header_len = 8 + 26 # 2 unsigned int for center_freq and span: 8 bytes PLUS 26 bytes for datetime
+length = len(buff[header_len:])
+n_t = length // bins
+header = struct.unpack('2I26s', buff[:header_len])
+data = struct.unpack('%dB' % length, buff[header_len:])
+waterfall_array = np.reshape(np.array(data[:]), (n_t, bins))
+waterfall_array -= 255
+plt.figure(figsize=(14, 5))
+plt.yticks(np.arange(0, 0, step=1))
+plt.xlabel('MHz')
+plt.xticks(np.linspace(0, bins, 31), np.linspace(0, 30, num=31, endpoint=True, dtype=int))
+plt.pcolormesh(waterfall_array[:, 1:], cmap=cmap, vmin=minsig+30, vmax=maxsig+30)
+if processfailed:
+ plt.title("Sorry, measurement failed on this Kiwi, no slot available, try later")
+else:
+ plt.title("HF waterfall @ " + str(host) + " - [SNR: %i dB" % (p95 - median) + "]")
+divider = make_axes_locatable(plt.gca())
+cax = divider.append_axes("right", "2%", pad="1%")
+clb = plt.colorbar(cax=cax)
+clb.ax.set_title('dBm')
+plt.tight_layout()
+plt.show()