forked from jimahlstrom/quisk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
quisk.py
6692 lines (6635 loc) · 253 KB
/
quisk.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# All QUISK software is Copyright (C) 2006-2024 by James C. Ahlstrom.
# This free software is licensed for use under the GNU General Public
# License (GPL), see http://www.opensource.org.
# Note that there is NO WARRANTY AT ALL. USE AT YOUR OWN RISK!!
"""The main program for Quisk, a software defined radio.
Usage: python quisk.py [-c | --config config_file_path]
This can also be installed as a package and run as quisk.main().
"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
# Change to the directory of quisk.py. This is necessary to import Quisk packages,
# to load other extension modules that link against _quisk.so, to find shared libraries *.dll and *.so,
# and to find ./__init__.py and ./help.html.
import sys, os
#print ('getcwd', os.getcwd())
#print ('__file__', __file__)
os.chdir(os.path.normpath(os.path.dirname(__file__))) # change directory to the location of this script
if sys.path[0] != '': # Make sure the current working directory is on path
sys.path.insert(0, '')
#print ('getcwd', os.getcwd())
import wx, wx.html, wx.lib.stattext, wx.lib.colourdb, wx.grid
import math, cmath, time, traceback, string, select, subprocess
import threading, pickle, webbrowser, json
try:
from xmlrpc.client import ServerProxy
except ImportError:
from xmlrpclib import ServerProxy
import _quisk as QS
from quisk_widgets import *
from filters import Filters
import dxcluster
import configure
import quisk_conf_defaults as conf
import quisk_wdsp
for name in configure.name2format: # Add defaults. These may be overwritten by a user config file.
setattr(conf, name, configure.name2format[name][1])
DEBUGSHELL = False
if DEBUGSHELL:
from wx.py.crust import CrustFrame
from wx.py.shell import ShellFrame
# Fldigi XML-RPC control opens a local socket. If socket.setdefaulttimeout() is not
# called, the timeout on Linux is zero (1 msec) and on Windows is 2 seconds. So we
# call it to insure consistent behavior.
import socket
socket.setdefaulttimeout(0.005)
HAMLIB_DEBUG = 0
application = None
if sys.version_info.major > 2:
Q3StringTypes = str
else:
Q3StringTypes = (str, unicode)
class StdOutput(wx.Frame):
def __init__(self, app):
self.app = app
self.ctrl = None
self.old_stdout = sys.stdout
self.old_stderr = sys.stderr
self.old_excepthook = sys.excepthook
self.path = os.path.join(app.QuiskFilesDir, "quisk_logfile.txt")
try:
size = os.path.getsize(self.path)
except:
size = 0
if size > 10000:
try:
fp = open(self.path, 'r')
lines = fp.readlines()
fp.close()
fp = open(self.path, 'w')
for i in range(len(lines) // 2, len(lines)):
fp.write(lines[i])
fp.close()
except:
pass
try:
self.fp = open(self.path, "a", buffering=1, encoding='utf-8', errors='replace', newline=None)
except:
self.fp = None
sys.stdout = self
sys.stderr = self
sys.excepthook = self.ExceptHook
if self.fp:
self.fp.write("\n\n*** Quisk started on %s at %s\n" % (sys.platform, time.asctime()))
def Create(self, parent):
w = self.app.screen_width * 4 // 10
h = self.app.screen_height * 4 // 10
title = "Quisk Log File %s" % self.path
wx.Frame.__init__(self, parent, -1, title, size = (w, h), style=wx.DEFAULT_FRAME_STYLE)
self.ctrl = wx.TextCtrl(self, style=wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL)
self.Bind(wx.EVT_SIZE, self.OnSize)
self.Bind(wx.EVT_CLOSE, self.OnBtnClose)
self.ctrl.write("*** Quisk started on %s at %s\n" % (sys.platform, time.asctime()))
def OnSize(self, event):
event.Skip()
w, h = self.GetClientSize()
self.ctrl.SetSize(w, h)
def OnBtnClose(self, event):
self.Show(False)
def Logfile(self, text):
if self.fp:
self.fp.write(text)
self.fp.write("\n")
def write(self, text):
if self.fp:
self.fp.write(text)
if self.old_stdout:
self.old_stdout.write(text)
if self.ctrl:
self.ctrl.write(text)
def flush(self):
pass
def ExceptHook(self, typ, value, traceb):
self.Show(True)
self.Raise()
self.old_excepthook(typ, value, traceb)
# Command line parsing: be able to specify the config file.
from optparse import OptionParser
parser = OptionParser()
parser.add_option('-c', '--config', dest='config_file_path',
help='Specify the configuration file path')
parser.add_option('', '--config2', dest='config_file_path2', default='',
help='Specify a second configuration file to read after the first')
parser.add_option('-r', '--radio', dest="radio", default='',
help='Specify the radio to use when starting')
parser.add_option('-a', '--ask', action="store_true", dest='AskMe', default=False,
help='Ask which radio to use when starting')
parser.add_option('', '--local', dest='local_option', default='',
help='Specify a custom option that you have programmed yourself')
argv_options = parser.parse_args()[0]
ConfigPath = argv_options.config_file_path # Get config file path
ConfigPath2 = argv_options.config_file_path2
LocalOption = argv_options.local_option
if sys.platform == 'win32':
path = os.getenv('HOMEDRIVE', '') + os.getenv('HOMEPATH', '')
for thedir in ("Documents", "My Documents", "Eigene Dateien", "Documenti", "Mine Dokumenter"):
config_dir = os.path.join(path, thedir)
if os.path.isdir(config_dir):
break
else:
config_dir = os.path.join(path, "My Documents")
try:
try:
import winreg as Qwinreg
except ImportError:
import _winreg as Qwinreg
key = Qwinreg.OpenKey(Qwinreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders")
val = Qwinreg.QueryValueEx(key, "Personal")
val = Qwinreg.ExpandEnvironmentStrings(val[0])
Qwinreg.CloseKey(key)
if os.path.isdir(val):
DefaultConfigDir = val
else:
DefaultConfigDir = config_dir
except:
traceback.print_exc()
DefaultConfigDir = config_dir
if not ConfigPath:
ConfigPath = os.path.join(DefaultConfigDir, "quisk_conf.py")
if not os.path.isfile(ConfigPath):
path = os.path.join(config_dir, "quisk_conf.py")
if os.path.isfile(path):
ConfigPath = path
del config_dir
else:
DefaultConfigDir = os.path.expanduser('~')
if not ConfigPath:
ConfigPath = os.path.join(DefaultConfigDir, ".quisk_conf.py")
# These FFT sizes have multiple small factors, and are preferred for efficiency. FFT size must be an even number.
fftPreferedSizes = []
for f2 in range(1, 13):
for y in (1, 3, 5, 7, 9, 11, 13, 15):
for z in (1, 3, 5, 7, 9, 11, 13, 15):
x = 2**f2 * y * z
if 300 <= x <= 5000 and x not in fftPreferedSizes:
fftPreferedSizes.append(x)
fftPreferedSizes.sort()
def round(x): # round float to nearest integer
if x >= 0:
return int(x + 0.5)
else:
return - int(-x + 0.5)
def str2freq (freq):
if '.' in freq:
freq = int(float(freq) * 1E6 + 0.1)
else:
freq = int(freq)
return freq
def get_filter_tx(mode): # Return the bandwidth, center of the Tx filters
if mode in ('LSB', 'USB'):
bw = 2700
center = 1650
elif mode in ('CWL', 'CWU'):
bw = 10
center = 0
elif mode in ('AM', 'DGT-IQ'):
bw = 6000
center = 0
elif mode in ('FM', 'DGT-FM'):
bw = 10000
center = 0
elif mode in ('FDV-L', 'FDV-U'):
bw = 2700
center = 1500
else:
bw = 2700
center = 1650
if mode in ('CWL', 'LSB', 'DGT-L', 'FDV-L'):
center = - center
return bw, center
Mode2Index = {'CWL':0, 'CWU':1, 'LSB':2, 'USB':3, 'AM':4, 'FM':5, 'EXT':6, 'DGT-U':7, 'DGT-L':8, 'DGT-IQ':9,
'IMD':10, 'FDV-U':11, 'FDV-L':12, 'DGT-FM':13}
class Timer:
"""Debug: measure and print times every ptime seconds.
Call with msg == '' to start timer, then with a msg to record the time.
"""
def __init__(self, ptime = 1.0):
self.ptime = ptime # frequency to print in seconds
self.time0 = 0 # time zero; measure from this time
self.time_print = 0 # last time data was printed
self.timers = {} # one timer for each msg
self.names = [] # ordered list of msg
self.heading = 1 # print heading on first use
def __call__(self, msg):
tm = time.time()
if msg:
if not self.time0: # Not recording data
return
if msg in self.timers:
count, average, highest = self.timers[msg]
else:
self.names.append(msg)
count = 0
average = highest = 0.0
count += 1
delta = tm - self.time0
average += delta
if highest < delta:
highest = delta
self.timers[msg] = (count, average, highest)
if tm - self.time_print > self.ptime: # time to print results
self.time0 = 0 # end data recording, wait for reset
self.time_print = tm
if self.heading:
self.heading = 0
print ("count, msg, avg, max (msec)")
print("%4d" % count, end=' ')
for msg in self.names: # keep names in order
count, average, highest = self.timers[msg]
if not count:
continue
average /= count
print(" %s %7.3f %7.3f" % (msg, average * 1e3, highest * 1e3), end=' ')
self.timers[msg] = (0, 0.0, 0.0)
print()
else: # reset the time to zero
self.time0 = tm # Start timer
if not self.time_print:
self.time_print = tm
## T = Timer() # Make a timer instance
class HamlibHandlerSerial:
"Create a serial port for Hamlib control that emulates the FlexRadio PowerSDR 2.x command set."
# This implements some Kenwood TS-2000 commands, but it is far from complete.
# See http://k5fr.com/binary/CatCommandReferenceGuide.pdf
# Test on linux by setting the Quisk serial port to /tmp/QuiskTTY0 and using putty with font Ubuntu Mono.
# Commands are "ZZAR;" and "ZZAR+030;" - no newline.
# Additional logic contributed by Dr. Karsten Schmidt
Mo2CoKen = {'CWL':7, 'CWU':3, 'LSB':1, 'USB':2, 'AM':5, 'FM':4, 'DGT-U':9, 'DGT-L':6, 'DGT-FM':4, 'DGT-IQ':9}
Co2MoKen = {1:'LSB', 2:'USB', 3:'CWU', 4:'FM', 5:'AM', 6:'DGT-L', 7:'CWL', 9:'DGT-U'}
Mo2CoFlex = {'CWL':3, 'CWU':4, 'LSB':0, 'USB':1, 'AM':6, 'FM':5, 'DGT-U':7, 'DGT-L':9, 'DGT-FM':5, 'DGT-IQ':7}
Co2MoFlex = {0:'LSB', 1:'USB', 3:'CWL', 4:'CWU', 5:'FM', 6:'AM', 7:'DGT-U', 9:'DGT-L'}
ConvertZZAC_P1_2_Step = { 0: 1,
1: 10,
2: 50,
3: 100,
4: 250,
5: 500,
6: 1000,
7: 5000,
8: 9000,
9: 10000,
10: 100000,
11: 250000,
12: 500000,
13: 1000000,
14: 10000000}
ConvertZZAC_Step_2_P1 = { 1: 0,
10: 1,
50: 2,
100: 3,
250: 4,
500: 5,
1000: 6,
5000: 7,
9000: 8,
10000: 9,
100000: 10,
250000: 11,
500000: 12,
1000000: 13,
10000000: 14}
def __init__(self, app, public_name):
self.app = app
self.port = None
self.received = ''
self.radio_id = '019'
self.public_name = public_name # the public name for the serial port
self.tune_step = 1000
if sys.platform == 'win32' or public_name.startswith("/dev/"):
self.port_is_mod_serial = True # self.port is from the serial module
try:
import serial
except:
print ("Please install the pyserial module.")
else:
try:
self.port = serial.Serial(public_name, timeout=0, write_timeout=0)
if HAMLIB_DEBUG: print ("Open CAT serial port", public_name)
except:
print ("The serial port %s could not be opened." % public_name)
else:
import tty
self.port_is_mod_serial = False # self.port is a file descriptor
if os.path.lexists(public_name):
try:
os.remove(public_name)
except:
print ("Can not remove the file", public_name)
try:
self.port, slave = os.openpty() # we are the master device fd, slave is a pseudo tty
tty.setraw(self.port)
tty.setraw(slave)
except:
print ("Can not create the serial port")
self.port = None
else:
try:
os.symlink(os.ttyname(slave), public_name) # create a link from the specified name to the slave device
except:
print ("Can not create a link named", public_name)
self.port = None
else:
if HAMLIB_DEBUG: print ("Create", public_name, "from", os.ttyname(slave))
def open(self):
return
def close(self):
if self.port_is_mod_serial:
if self.port:
self.port.close()
self.port = None
else:
if self.public_name:
try:
os.remove(self.public_name)
except:
pass
def Read(self):
if self.port is None:
return
if self.port_is_mod_serial:
text = self.port.read(99)
if not isinstance(text, Q3StringTypes):
text = text.decode('utf-8')
self.received += text
else:
while True:
r, w, x = select.select((self.port,), (), (), 0)
if not r:
break
text = os.read(self.port, 1)
if not isinstance(text, Q3StringTypes):
text = text.decode('utf-8')
self.received += text
def Process(self):
"""This is the main processing loop, and is called frequently. It reads and satisfies requests."""
self.Read()
if ';' in self.received: # A complete command ending with semicolon is available
cmd, self.received = self.received.split(';', 1) # Split off the command, save any further characters
else:
return
cmd = cmd.strip() # Here is our command and data
if cmd[0:2] in ('ZZ', 'zz', 'Zz', 'zZ'):
data = cmd[4:]
cmd = cmd[0:4].upper()
func = cmd
else:
data = cmd[2:]
cmd = cmd[0:2].upper()
if cmd in ('FA', 'FB', 'IF', 'PS'): # Use the ZZxx command method
func = 'ZZ' + cmd
else: # Use the two-letter method
func = cmd
if data:
if HAMLIB_DEBUG: print ("Process command :", cmd, data)
try:
func = getattr(self, func)
except:
print ("Unimplemented serial port function", func, 'cmd', cmd, 'data', data)
self.Write('?;')
return
func(cmd, data, len(data))
def Error(self, cmd, data):
self.Write('?;')
print ("*** Error for cmd %s data %s" % (cmd, data))
def Write(self, data):
if HAMLIB_DEBUG: print ("Serial port write:", data)
if self.port is None:
return
if isinstance(data, Q3StringTypes):
data = data.encode('utf-8', errors='ignore')
if self.port_is_mod_serial:
self.port.write(data)
else:
r, w, x = select.select((), (self.port,), (), 0)
if w:
os.write(self.port, data)
def set_frequency(self, freq): # This changes the Rx frequency
self.app.ChangeRxTxFrequency(freq, None)
if HAMLIB_DEBUG: print("New Freq rx,tx", self.app.txFreq + self.app.VFO, self.app.rxFreq + self.app.VFO)
def ZZAC(self, cmd, data, length): # Set or read tune steps
if length == 0:
xxx = self.ConvertZZAC_Step_2_P1.get(self.tune_step)
self.Write("%s%02d;" % (cmd, xxx))
elif length == 2:
p1 = int(data, base=10)
try:
self.tune_step = self.ConvertZZAC_P1_2_Step.get(p1)
except:
self.Error(cmd, data)
else:
self.Error(cmd, data)
def ZZAD(self, cmd, data, length): # VFO A down by a selected step
if length == 0:
oldfreq = self.app.rxFreq + self.app.VFO
freq = oldfreq - self.tune_step
self.set_frequency(freq)
else:
self.Error(cmd, data)
def AG(self, cmd, data, length): # audio gain
if length == 1:
self.Write("%s%s120;" % (cmd, data[0]))
def ZZAG(self, cmd, data, length): # audio gain
if length == 0:
n = (self.app.volumeAudio + 5) / 10
self.Write("%s%03d;" % (cmd, n))
elif length == 3:
vol = int(data, base=10) * 10
self.app.sliderVol.SetValue(vol)
self.app.ChangeVolume()
else:
self.Error(cmd, data)
def ZZAR(self, cmd, data, length): # AGC level
if length == 0:
n = self.app.levelAGC * 140 // 1000 - 20 # Convert AGC 0 to 1000 -> -20 to 120
if n < 0:
self.Write("%s-%03d;" % (cmd, - n))
else:
self.Write("%s+%03d;" % (cmd, n))
elif length == 4:
val = int(data, base=10)
val = (val + 20) * 1000 // 140 # Convert AGC -20 to 120 -> 0 to 1000
self.app.SliderAGC.SetSlider(value_on=val)
self.app.BtnAGC.SetValue(True, True)
else:
self.Error(cmd, data)
def ZZAU(self, cmd, data, length): # VFO A up by a selected step
if length == 0:
oldfreq = self.app.rxFreq + self.app.VFO
freq = oldfreq + self.tune_step
self.set_frequency(freq)
else:
self.Error(cmd, data)
def ZZBS(self, cmd, data, length): # band switch
if length == 0:
band = self.app.lastBand
try:
band = int(band, base=10)
self.Write("%s%03d;" % (cmd, band))
except:
self.Write("%s888;" % cmd)
elif length == 3:
band = data
if band[0] == '0':
band = band[1:]
if band[0] == '0':
band = band[1:]
try:
self.app.bandBtnGroup.SetLabel(band, do_cmd=True, direction=0)
except:
self.Error(cmd, data)
else:
self.Error(cmd, data)
def ZZAI(self, cmd, data, length): # broadcast changes
if length == 0:
self.Write("%s0;" % cmd)
elif length == 1 and data[0] == '0':
pass
else:
self.Error(cmd, data)
def ZZFA(self, cmd, data, length): # frequency of VFO A, the receive frequency
if length == 0:
self.Write("%s%011d;" % (cmd, self.app.rxFreq + self.app.VFO))
elif length == 11:
freq = int(data, base=10)
self.set_frequency(freq)
else:
self.Error(cmd, data)
def ZZFB(self, cmd, data, length): # frequency of VFO B
if length == 0:
self.Write("%s%011d;" % (cmd, self.app.txFreq + self.app.VFO))
elif length == 11:
freq = int(data, base=10)
tune = freq - self.app.VFO
d = self.app.sample_rate * 45 // 100
if -d <= tune <= d: # Frequency is on-screen
vfo = self.app.VFO
else: # Change the VFO
vfo = (freq // 5000) * 5000 - 5000
tune = freq - vfo
self.app.BandFromFreq(freq)
self.app.ChangeHwFrequency(tune, vfo, 'FreqEntry')
else:
self.Error(cmd, data)
def FR(self, cmd, data, length): # receive VFO is always VFO A
if length == 0:
self.Write("%s0;" % cmd)
elif length == 1 and data[0] == '0':
pass
else:
self.Error(cmd, data)
def FT(self, cmd, data, length): # transmit VFO
if self.app.split_rxtx:
vfo = '1'
else:
vfo = '0'
if length == 0:
self.Write("%s%s;" % (cmd, vfo))
elif length == 1 and data[0] == vfo:
pass
else:
self.Error(cmd, data)
def ID(self, cmd, data, length): # return radio ID
if length == 0:
self.Write('%s%s;' % (cmd, self.radio_id))
else:
self.Error(cmd, data)
def ZZID(self, cmd, data, length): # set radio id to Flex
if length == 0:
self.radio_id = '900'
else:
self.Error(cmd, data)
def ZZIF(self, cmd, data, length): # return information for ZZIF and IF
ritFreq = self.app.ritScale.GetValue()
if self.app.ritButton.GetValue():
rit = 1
else:
rit = 0
mode = self.app.mode
info = cmd
info += "%011d" % (self.app.rxFreq + self.app.VFO) # frequency, ZZFA
info += '0000'
if ritFreq < 0: # RIT freq
info += "-%05d" % -ritFreq
else:
info += "+%05d" % ritFreq
info += "%d" % rit # RIT status
info += '0000'
if QS.is_key_down(): # MOX, key down
info += '1'
else:
info += '0'
if len(cmd) == 4: # Flex ZZIF
code = self.Mo2CoFlex.get(mode, 1)
info += "%02d" % code # operating mode
else: # Kenwood IF
code = self.Mo2CoKen.get(mode, 1)
info += "%d" % code # operating mode
info += '00'
if self.app.split_rxtx: # VFO split status
info += '1'
else:
info += '0'
info += '0000'
info += ';'
self.Write(info)
def MD(self, cmd, data, length): # the mode; USB, CW, etc.
if length == 0:
mode = self.app.mode
code = self.Mo2CoKen.get(mode, 2)
self.Write("%s%d;" % (cmd, code))
elif length == 1:
code = int(data, base=10)
mode = self.Co2MoKen.get(code, 'USB')
self.app.modeButns.SetLabel(mode, True) # Set mode
else:
self.Error(cmd, data)
def ZZMD(self, cmd, data, length): # the mode; USB, CW, etc.
if length == 0:
mode = self.app.mode
code = self.Mo2CoFlex.get(mode, 1)
self.Write("%s%02d;" % (cmd, code))
elif length == 2:
code = int(data, base=10)
mode = self.Co2MoFlex.get(code, 'USB')
self.app.modeButns.SetLabel(mode, True) # Set mode
else:
self.Error(cmd, data)
def ZZMU(self, cmd, data, length): # MultiRx on/off
if length == 0:
self.Write("%s0;" % cmd)
def OI(self, cmd, data, length): # return information
self.ZZIF(cmd, data, length)
def ZZPS(self, cmd, data, length): # power status
if length == 0:
self.Write("%s1;" % cmd)
def ZZRS(self, cmd, data, length): # the RX2 status
if length == 0:
self.Write("%s0;" % cmd)
elif length == 1 and data[0] == '0':
pass
else:
self.Error(cmd, data)
def RX(self, cmd, data, length): # turn off MOX
if length == 0:
self.app.pttButton.SetValue(0, True)
else:
self.Error(cmd, data)
def ZZSM(self, cmd, data, length): # return the S-meter value in dB * 2; 0 to 260
if length == 0: # 0 to 260 is -140 to -10 dB; S9 == -73 dB == 134; dB = ZZSM / 2 - 140
i = round((self.app.hamlib_strength + 67) * 2)
if i < 0:
i = 0
elif i > 260:
i = 260
self.Write('%s%03d;' % (cmd, i))
else:
self.Error(cmd, data)
def ZZSP(self, cmd, data, length): # the split status
if length == 0:
if self.app.split_rxtx:
self.Write("%s1;" % cmd)
else:
self.Write("%s0;" % cmd)
else:
self.Error(cmd, data)
def ZZSW(self, cmd, data, length): # transmit VFO is A or B
if length == 0:
if self.app.split_rxtx:
self.Write("%s1;" % cmd)
else:
self.Write("%s0;" % cmd)
def TX(self, cmd, data, length): # turn on MOX
if length == 0:
self.app.pttButton.SetValue(1, True)
else:
self.Error(cmd, data)
def ZZTX(self, cmd, data, length): # the MOX status
if length == 0:
if QS.is_key_down():
self.Write("%s1;" % cmd)
else:
self.Write("%s0;" % cmd)
elif length == 1:
if data[0] == '0':
self.app.pttButton.SetValue(0, True)
else:
self.app.pttButton.SetValue(1, True)
else:
self.Error(cmd, data)
def ZZVE(self, cmd, data, length): # is VOX enabled
if length == 0:
if self.app.useVOX:
self.Write("%s1;" % cmd)
else:
self.Write("%s0;" % cmd)
else:
self.Error(cmd, data)
def XT(self, cmd, data, length): # the XIT
if length == 0:
self.Write("%s0;" % cmd)
elif length == 1 and data[0] == '0':
pass
else:
self.Error(cmd, data)
class HamlibHandlerRig2: # Test with telnet localhost 4532
"""This class is created for each connection to the server. It services requests from each client."""
SingleLetters = { # convert single-letter commands to long commands
'_':'info',
'f':'freq',
'i':'split_freq',
'l':'level',
'm':'mode',
'p':'parm',
's':'split_vfo',
't':'ptt',
'u':'func',
'v':'vfo',
}
def __init__(self, app, sock, address):
self.app = app # Reference back to the "hardware"
self.sock = sock
sock.settimeout(0.0)
self.address = address
self.params = '' # params is the string following the command
self.received = ''
self.input = ''
self.vfo = "Main"
self.split_mode = 0
self.split_vfo = 'VFO'
h = self.Handlers = {}
h[''] = self.ErrProtocol
h['dump_state'] = self.DumpState
h['chk_vfo'] = self.ChkVfo # Thanks to Franco Spinelli, IW2DHW
h['get_freq'] = self.GetFreq
h['set_freq'] = self.SetFreq
h['get_info'] = self.GetInfo
h['get_mode'] = self.GetMode
h['set_mode'] = self.SetMode
h['get_vfo'] = self.GetVfo
h['set_vfo'] = self.SetVfo
h['get_func'] = self.GetFunc
h['set_func'] = self.SetFunc
h['get_level'] = self.GetLevel
h['set_level'] = self.SetLevel
h['get_parm'] = self.GetParm
h['set_parm'] = self.SetParm
h['get_ptt'] = self.GetPtt
h['set_ptt'] = self.SetPtt
h['get_split_freq'] = self.GetSplitFreq
h['set_split_freq'] = self.SetSplitFreq
h['get_split_vfo'] = self.GetSplitVfo
h['set_split_vfo'] = self.SetSplitVfo
self.MakeDumpState()
def MakeDumpState(self):
dump_state = []
# rigctld protocol version
dump_state.append( b"0" )
# rig model
dump_state.append( b"2" )
# ITU region
dump_state.append( b"1" ) # Europe, Africa and Northern Asia
#dump_state.append( b"2" ) # North America, South America and Greenland
#dump_state.append( b"3" ) # South Pacific and Southern Asia
# RX frequency ranges
# start, end, modes, low_power, high_power, vfo, ant
#dump_state.append( b"150000.000000 1500000000.000000 0x1ff -1 -1 0x10000003 0x3" )
# AM | CW | USB | LSB | NFM | WFM | DSB
dump_state.append( b"100000.000000 6000000000.000000 0x8006f -1 -1 0x4000000 0x3" ) # HackRF (100kHz - 6GHz), VFO:Main
# End of RX frequency ranges
dump_state.append( b"0 0 0 0 0 0 0" )
# TX frequency ranges
# start, end, modes, low_power, high_power, vfo, ant
dump_state.append( b"100000.000000 6000000000.000000 0x8006f -1 -1 0x4000000 0x3" ) # HackRF (100kHz - 6GHz), VFO:Main
# End of TX frequency ranges
dump_state.append( b"0 0 0 0 0 0 0" )
# Tuning steps
# mode, tuning_step
dump_state.append( b"0x1ff 1" )
dump_state.append( b"0x1ff 0" )
# End of tuning steps
dump_state.append( b"0 0" )
# Filter sizes
# mode, width
dump_state.append( b"0x1e 2400" )
dump_state.append( b"0x2 500" )
dump_state.append( b"0x1 8000" )
dump_state.append( b"0x1 2400" )
dump_state.append( b"0x20 15000" )
dump_state.append( b"0x20 8000" )
dump_state.append( b"0x40 230000" )
# End of filter sizes
dump_state.append( b"0 0" )
# ------ ??? ------
# max_rit
dump_state.append( b"9990" )
# max_xit
dump_state.append( b"9990" )
# max_ifshift
dump_state.append( b"10000" )
# announces
dump_state.append( b"0" )
# MAXDBLSTSIZ preamp
dump_state.append( b"10" )
# MAXDBLSTSIZ attenuator
dump_state.append( b"10 20 30" )
# has_get_func
dump_state.append( b"0x3effffff" )
# has_set_func
dump_state.append( b"0x3effffff" )
# has_get_level
dump_state.append( b"0xfffffffff7ffffff" )
# has_set_level
dump_state.append( b"0xffffffff83ffffff" )
# has_get_parm
dump_state.append( b"0xffffffffffffffff" )
# has_set_parm
dump_state.append( b"0xffffffffffffffbf" )
# END
self.dump_state = b'\n'.join(dump_state)
self.dump_state += b'\n'
def Send(self, text):
"""Send text back to the client."""
if isinstance(text, Q3StringTypes):
text = text.encode('utf-8', errors='ignore')
if HAMLIB_DEBUG:
print ("Rig2 send", text)
try:
self.sock.sendall(text)
except socket.error:
self.sock.close()
self.sock = None
def Reply(self, *args): # args is name, value, name, value, ..., int
"""Create a string reply of name, value pairs, and an ending integer code."""
if self.extended: # Use extended format; echo the command and parameters.
t = "%s:" % self.command
if self.params:
t += " %s" % self.params
t += self.extended
for i in range(0, len(args) - 1, 2):
t = "%s%s: %s%c" % (t, args[i], args[i+1], self.extended)
t += "RPRT %d\n" % args[-1]
elif len(args) > 1: # Use simple format
t = ''
for i in range(1, len(args) - 1, 2):
t = "%s%s\n" % (t, args[i])
else: # No names; just the required integer code
t = "RPRT %d\n" % args[0]
self.Send(t)
def Reply2(self, text, code):
"""Create a reply string in a different format."""
if self.extended: # Use extended format
t = "%s: %s%s%s\nRPRT %d\n" % (self.command, self.params, self.extended, text, code)
self.Send(t)
else:
if self.command[0:4] == "set_":
self.Send("%s\nRPRT %d\n" % (text, code))
else:
self.Send("%s\n" % text)
def ErrParam(self): # Invalid parameter
self.input = ''
self.Reply(-1)
def UnImplemented(self): # Command not implemented
self.input = ''
self.Reply(-4)
def ErrProtocol(self): # Protocol error
self.input = ''
self.Reply(-8)
def GetParamNumber(self):
if not self.input:
return None
number = ''
for i in range(len(self.input)):
ch = self.input[i]
if ch in "+-.0123456789":
number = number + ch
else:
self.input = self.input[i:].strip()
break
else:
self.input = ''
if self.params:
self.params = self.params + ' ' + number
else:
self.params = number
try:
if '.' in number:
return float(number)
else:
return int(number)
except:
return None
def GetParamName(self):
if not self.input:
return ''
if self.input[0] == '?':
self.params = '?'
self.input = self.input[1:].strip()
return '?'
name = ''
for i in range(len(self.input)):
ch = self.input[i]
if ch in string.ascii_letters or ch in "_-":
name = name + ch
else:
self.input = self.input[i:].strip()
break
else:
self.input = ''
if self.params:
self.params = self.params + ' ' + name
else:
self.params = name
return name
def Process(self):
"""This is the main processing loop, and is called frequently. It reads and satisfies requests."""
if not self.sock:
return 0
try: # Read any data from the socket
text = self.sock.recv(1024)
except socket.timeout: # This does not work
pass
except socket.error: # Nothing to read
pass
else: # We got some characters
if not isinstance(text, Q3StringTypes):
text = text.decode('utf-8')
self.received += text
if '\n' in self.received: # A complete command ending with newline is available
self.input, self.received = self.received.split('\n', 1) # Split off the command, save any further characters
else:
return 1
self.input = self.input.strip() # Here is our command line
if HAMLIB_DEBUG:
print ("Rig2 received", self.input)
while self.input:
# Parse the commands and call the appropriate handlers
self.params = ''
if self.input[0] == '+': # rigctld Extended Response Protocol
self.extended = '\n'
self.input = self.input[1:].strip()
elif self.input[0] in ';|,': # rigctld Extended Response Protocol
self.extended = self.input[0]
self.input = self.input[1:].strip()
else:
self.extended = None
letter = self.input[0:1]
if letter == '\\': # long form command starting with backslash
args = self.input[1:].split(None, 1)
self.command = args[0]
if len(args) == 1:
self.input = ''
else:
self.input = args[1].strip()
else: # single-letter commands
self.input = self.input[1:].strip()
if letter in 'Qq': # Quit command
self.sock.close()
self.input = ''
return 0
try:
command = self.SingleLetters[letter.lower()]
except KeyError:
self.UnImplemented()
return 1
else:
if letter in string.ascii_uppercase:
self.command = 'set_' + command
else:
self.command = 'get_' + command
self.Handlers.get(self.command, self.UnImplemented)()
return 1
# These are the handlers for each request
def DumpState(self):
self.Send(self.dump_state)
def ChkVfo(self):
if self.extended:
self.Send('ChkVFO: 0\n')
else:
self.Send('0\n')
def GetFreq(self): # The Rx frequency
rx = self.app.multi_rx_screen.receiver_list
if rx:
rx = rx[0]
self.Reply('Frequency', rx.txFreq + rx.VFO, 0)
if HAMLIB_DEBUG:
print ("GetFreq rx", rx.txFreq, rx.VFO)
else:
self.Reply('Frequency', self.app.rxFreq + self.app.VFO, 0)
if HAMLIB_DEBUG:
print ("GetFreq app", self.app.rxFreq, self.app.txFreq, self.app.VFO)
def SetFreq(self): # The Rx frequency
freq = self.GetParamNumber()