-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpypcr1000.py
2314 lines (1956 loc) · 82.4 KB
/
pypcr1000.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
# Copyright (C) 2004 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!!
import sys, Tkinter, ScrolledText, tkMessageBox, tkColorChooser
import time, thread, math, os, traceback, string, pickle
from types import *
import serial
DEBUG = 1 # Write debug messages?
LOGGER = None # This has a write(text) method for logging messages
IniFile = {} # A dictionary to store state in an INI file
SerialPollMillisecs = 10 # Time to poll serial port
ScanMillisecs = 100 # Time to pause at each frequency when scanning the band
bpady = 1 # Standard padding for equal-height buttons
# Define fonts used by all widgets
bfont = 'helvetica 10' # button font
lfont = 'helvetica 10' # label font
vfont = 'helvetica 10' # font for volume control
mfont = 'helvetica 8' # S-Meter font
# Define colors used by all widgets
Red = '#FF3300'
Black = '#000000'
White = '#FFFFFF'
Green = '#66FF33'
Gray = '#999999'
Blue = '#3333FF'
Yellow = '#FFFF33'
acolor = '#FFFF33' # active color for text items
scolor = '#CCCC33' # selected check and radio buttons
ccolor = '#FFFF33' # active color for right-click buttons
fcolor = '#FFFFCC' # background for freq display and call
mcolort = '#FFFFFF' # S-Meter text color
mcolorf = '#6633FF' # S-Meter foreground color
mcolorb = '#66CCFF' # S-Meter background color
bcolorb = '#66CC99' # Bandscope background
bcolort = '#000000' # Bandscope text color
bcolorc = '#000000' # '#FFFF00' # Bandscope center line
bcolorl = '#993300' # Bandscope signal level color
ncolor = '#FF3300' # Active scanner button color
# Interface definition:
# app.dispFreq.Set(new_freq)
# app.radio.RadioSetBandScope(turn_on)
# app.dispMode.Set(new_mode)
# app.dispFilter.Set(new_filter)
# app.StepBandChange(new_step)
StatusBar = None
def Help(widget, text):
"""Create help text for widget"""
widget.help = text
widget.bind('<Enter>', Enter, add=1)
widget.bind('<Leave>', Leave, add=1)
def Enter(event):
if StatusBar.show_help:
StatusBar.itemconfig(StatusBar.idText, text=event.widget.help)
def Leave(event):
if StatusBar.show_help:
StatusBar.itemconfig(StatusBar.idText, text='')
def MouseWheel(*args, **kw):
pass # print event
def FormatTb():
"""Write text from a traceback"""
if LOGGER:
ty, value, tb = sys.exc_info()
tb = traceback.format_exception(ty, value, tb)
LOGGER.write(''.join(tb))
def GetTextExtent(window, text, font):
id = window.create_text(0, 0, text=text, font=font, anchor='nw')
bbox = window.bbox(id)
w = bbox[2] - bbox[0]
h = bbox[3] - bbox[1]
window.delete(id)
return w, h
def MakeFreq(text):
"""Return integer frequency for text."""
tail = text[-1] # text must be stripped: text.strip()
if tail in "Kk":
mult = 1000
text = text[0:-1]
elif tail in "Mm":
mult = 1000000
text = text[0:-1]
else:
mult = 1
return int(float(text) * mult)
def ShowFreq(freq):
"""Return a string for frequency"""
freq = int(freq)
if freq % 1000 == 0:
t = str(freq / 1000)
add = 'k'
elif abs(freq) > 1000 and freq % 100 == 0:
t = str(freq / 100)
add = '.%sk' % t[-1]
t = t[0:-1]
else:
t = str(freq)
add = ''
l = len(t)
if t[0] == '-':
l = l - 1
if l > 9:
t = "%s,%s,%s,%s%s" % (t[0:-9], t[-9:-6], t[-6:-3], t[-3:], add)
elif l > 6:
t = "%s,%s,%s%s" % (t[0:-6], t[-6:-3], t[-3:], add)
elif l > 3:
t = "%s,%s%s" % (t[0:-3], t[-3:], add)
else:
t = t + add
return t
def BandFileNames():
"""return a list of band file names"""
l = []
for name in os.listdir('.'):
if name[-6:].lower() == '.bands':
l.append(name)
return l
def ReadBands(filename):
"""
Read data in the Bands file
Button text, Freq Start, Freq End, Freq Step, Mode, Filter, Description
80m, 3.5M, 4.0m, 100, LSB, 2.8k, Ham 80 meters
"""
b = []
try:
fp = open(filename, "r")
except IOError:
return b
fp.readline() # Throw away the header
for text in fp.readlines():
data = text.split(',')
data = map(string.strip, data)
data[1] = MakeFreq(data[1])
data[2] = MakeFreq(data[2])
data[3] = MakeFreq(data[3])
b.append(data)
fp.close()
return b
class Application(Tkinter.Tk):
"""This application displays a radio control screen."""
def __init__(self):
Tkinter.Tk.__init__(self)
# Read in persistent state from an INI file
try:
fp = open("PyPCR1000.ini", "r")
except IOError:
pass
else:
for line in fp.readlines():
keyval = line.split('=')
if len(keyval) == 2:
IniFile[keyval[0].strip()] = keyval[1].strip()
fp.close()
self.band_step = 1000
self.varCall = Tkinter.StringVar()
self.varStation = Tkinter.StringVar()
self.varMultBands = Tkinter.IntVar() # Select multiple bands?
self.varShowHelp = Tkinter.IntVar() # Show help in status bar?
self.varShowHelp.set(1)
self.textDTMF = '' # DTMF tones received
self.ReadStations()
self.win_title = "Python PCR1000"
self.wm_title(self.win_title)
self.wm_resizable(1, 1)
self.screenheight = self.winfo_screenheight()
self.screenwidth = self.winfo_screenwidth()
self.one_mm = float(self.screenwidth) / self.winfo_screenmmwidth()
self.logging = 0
self.scanner = 0 # 1==scan up, -1==scan down
self.memscanner = False
# self.bind('<<HaveInput>>', self.HaveInput)
self.sequence = 0
self.radio = PCR1000(self)
self.wm_protocol("WM_DELETE_WINDOW", self.WmDeleteWindow)
self.wm_protocol("WM_SAVE_YOURSELF", self.WmDeleteWindow)
frame = self.frame = Tkinter.Frame(self)
frame.pack(expand=1, fill='both')
# Help status bar at bottom
global StatusBar
StatusBar = Tkinter.Canvas(frame, bd=2, relief='groove')
w, h = GetTextExtent(StatusBar, 'Status', font=bfont)
StatusBar.statusHeight = h
StatusBar.configure(height=h)
StatusBar.idText = StatusBar.create_text(2, 2 + h / 2, text="", anchor='w', font=bfont)
StatusBar.pack(side='bottom', anchor='s', fill='x')
StatusBar.show_help = self.varShowHelp.get()
# Measure some widget sizes
Canvas = Tkinter.Canvas(frame)
w, h = GetTextExtent(Canvas, 'Volume', font=vfont)
w = w * 12 / 10
b = Tkinter.Radiobutton(Canvas, text="USB", font=bfont, width=4, padx=0, pady=bpady, indicatoron=0)
radioW = b.winfo_reqwidth()
radioH = b.winfo_reqheight()
b.destroy()
Canvas.destroy()
# Left vertical box for power and knobs
Left = Tkinter.Frame(frame, bd=5, relief='groove')
Left.pack(side='left', anchor='w', fill='y')
# Populate left box
bg = Left.cget('background')
self.power_button = PowerButton(Left, text='Power', font=vfont, width=w, bg=bg, bd=3, relief='raised',
command=self.Power)
self.power_button.SetColorNum(0)
Help(self.power_button, 'Power button: press to turn radio on and off.')
self.power_button.pack(side='top', anchor='n', expand=1)
self.dispVolume = VolumeKnob(Left, text='Volume', font=vfont, highlightthickness=0, button=1, radio=self.radio,
width=w, bg=bg, relief='flat')
Help(self.dispVolume, 'Volume control: press knob and turn.')
Help(self.dispVolume.iButton, 'Press to mute (set volume to zero), press again to restore.')
self.dispVolume.pack(side='top', anchor='n', expand=1)
self.dispSquelch = SquelchKnob(Left, text='Squelch', font=vfont, highlightthickness=0, radio=self.radio,
width=w, bg=bg, relief='flat')
Help(self.dispSquelch, 'Squelch control: press knob and turn.')
self.dispSquelch.pack(side='top', anchor='n', expand=1)
self.dispIfShift = IfShiftKnob(Left, text='IF Shift', font=vfont, highlightthickness=0, button=1,
radio=self.radio, width=w, bg=bg, relief='flat')
Help(self.dispIfShift, 'Intermediate frequency shift control: press knob and turn.')
Help(self.dispIfShift.iButton, 'Press to set to 50% (no IF shift).')
self.dispIfShift.pack(side='top', anchor='n', expand=1)
# Top box for display, tuning, ...
Top = Tkinter.Frame(frame)
Top.pack(side='top', anchor='n', fill='x')
# TopLeft box for frequency display, signal meter, check buttons
TopLeft = Tkinter.Frame(Top, bd=5, relief='groove')
TopLeft.pack(side='left', anchor='w')
# TopRight box for tuning buttons, memory buttons, etc.
TopRight = Tkinter.Frame(Top, bd=5, relief='groove')
TopRight.pack(side='right', anchor='e', expand=1, fill='x')
# h = int(self.one_mm * 25.4 + 0.5)
# frequency display, signal meter
frm = Tkinter.Frame(TopLeft)
frm.pack(side='top', anchor='nw')
self.dispFreq = FreqDisplay(frm, app=self, width=radioW * 6, bg=fcolor, radio=self.radio)
self.dispFreq.pack(side='top', anchor='nw')
self.dispFreq.Set(self.radio.frequency)
Help(self.dispFreq,
'To tune, press top of digit to increase, bottom to decrease. The H and L show FM frequency high or low.')
f = Tkinter.Frame(frm)
f.pack(side='top', anchor='nw', fill='x')
self.varShift = Tkinter.IntVar()
self.shift_delta = 600000
b = Tkinter.Checkbutton(f, text="+600k", indicatoron=0, width=5, selectcolor=scolor, font=mfont, padx=0, pady=0,
activebackground=ccolor, variable=self.varShift, command=self.ShiftButton)
b.pack(side='right', anchor='ne')
b.bind('<ButtonPress-3>', self.ShiftButtonMenu)
Help(b, 'Press to shift frequency temporarily, press again to shift back. Configure with right click.')
self.dispSignal = SignalMeter(f)
Help(self.dispSignal, 'Signal strength meter.')
self.dispSignal.pack(side='right', anchor='nw', expand=1, fill='both')
# mode, filter and check buttons
frm = Tkinter.Frame(TopLeft)
frm.pack(side='top', anchor='nw', fill='x')
self.dispMode = ModeDisplay(frm, self.radio)
# height=radioH, relief='groove')
# self.dispMode.pack_propagate(0)
self.dispMode.pack(side='top', anchor='nw', fill='x')
Help(self.dispMode, 'Radio reception mode: lower/upper sideband, AM, CW, narrow/wide FM')
self.dispFilter = FilterDisplay(frm, self.radio)
Help(self.dispFilter, 'Radio IF bandwidth')
self.dispMode.dispFilter = self.dispFilter
# height=radioH, relief='groove')
# self.dispFilter.pack_propagate(0)
self.dispFilter.pack(side='top', anchor='nw', fill='x')
self.dispCheckB = CheckButtons(frm, self.radio)
# height=radioH, relief='groove')
# self.dispCheckB.pack_propagate(0)
self.dispCheckB.pack(side='top', anchor='nw', fill='x')
frm = Tkinter.Frame(TopRight)
frm.pack(side='top', anchor='n', fill='x')
fru = Tkinter.Frame(frm)
fru.pack(side='top', anchor='nw', fill='x')
frd = Tkinter.Frame(frm)
frd.pack(side='bottom', anchor='sw', fill='x')
b = RepeaterButton(frd, text='<Sta', width=6, font=bfont, pady=bpady, padx=0, command=Shim(self.NextStation, 0))
Help(b,
'Tune down to the next station in the selected bands. Hold to repeat. Stations are recorded in the file Stations.csv.')
b.pack(side='left', anchor='w', expand=1, fill='x')
b = RepeaterButton(frd, width=6, font=bfont, pady=bpady, padx=0, command=Shim(self.NextFrequency, 0),
activebackground=ccolor)
Help(b,
'Tune down by the indicated frequency step, but stay in the bands. Hold to repeat. Configure with right click.')
b.pack(side='left', anchor='w', expand=1, fill='x')
b.bind('<ButtonPress-3>', self.StepBandMenu)
self.dispStepBandD = b
b = Tkinter.Button(frd, text='<Scn', width=6, font=bfont, pady=bpady, padx=0, command=self.ScanDownBand)
Help(b, 'Start the scanner and scan down in the selected bands. Stop when the squelch opens.')
b.pack(side='left', anchor='w', expand=1, fill='x')
self.dispScanDown = b
self.btnBcolor = b.cget('background') # Save color
self.btnAcolor = b.cget('activebackground')
# Memory buttons
self.Memories = []
for i in range(5, 10):
b = Tkinter.Button(frd, text="M%s" % i, width=3, pady=bpady, padx=0, font=bfont, activebackground=ccolor,
command=Shim(self.MemoryButtonCmd, i), state='disabled')
Help(b, 'Memory button: press to change to that frequency. Configure with right click.')
b.pack(side='left', anchor='w')
b.bind('<ButtonPress-3>', self.MemoryButtonMenu)
b.index = i
self.Memories.append(None)
b = Tkinter.Button(frd, text='Unused 2', font=bfont, pady=bpady, width=8, command=self.OnButtonUnused2)
Help(b, 'Program this button yourself in Python!')
b.pack(side='right', anchor='e')
b = RepeaterButton(fru, text='Sta>', width=6, font=bfont, pady=bpady, padx=0, command=Shim(self.NextStation, 1))
Help(b,
'Tune up to the next station in the selected bands. Hold to repeat. Stations are recorded in the file Stations.csv.')
b.pack(side='left', anchor='w', expand=1, fill='x')
b = RepeaterButton(fru, width=6, font=bfont, pady=bpady, padx=0, command=Shim(self.NextFrequency, 1),
activebackground=ccolor)
Help(b,
'Tune up by the indicated frequency step, but stay in the bands. Hold to repeat. Configure with right click.')
b.pack(side='left', anchor='w', expand=1, fill='x')
b.bind('<ButtonPress-3>', self.StepBandMenu)
self.dispStepBandU = b
b = Tkinter.Button(fru, text='Scn>', width=6, font=bfont, pady=bpady, padx=0, command=self.ScanUpBand)
Help(b, 'Start the scanner and scan up in the selected bands. Stop when the squelch opens.')
b.pack(side='left', anchor='w', expand=1, fill='x')
self.dispScanUp = b
for i in range(0, 5):
b = Tkinter.Button(fru, text="M%s" % i, width=3, pady=bpady, padx=0, font=bfont, activebackground=ccolor,
command=Shim(self.MemoryButtonCmd, i), state='disabled')
Help(b, 'Memory button: press to change to that frequency. Configure with right click.')
b.pack(side='left', anchor='w')
b.bind('<ButtonPress-3>', self.MemoryButtonMenu)
b.index = i
self.Memories.append(None)
b = Tkinter.Button(fru, text='Memscan', font=bfont, pady=bpady, width=8, command=self.OnButtonMemscan)
Help(b, 'Scan frequencies in Stations.csv. Resume when squelch re-closes.')
b.pack(side='right', anchor='e')
self.dispMemscan = b
self.StepBandChange(self.band_step)
# Band buttons: Room for three rows of seven columns
self.bandRows = []
for i in range(3): # Create three rows
frs = Tkinter.Frame(TopRight)
frs.pack(side='top', anchor='nw', fill='x')
self.bandRows.append(frs)
self.Bands = []
# Call entries
frm = Tkinter.Frame(frame, bd=5, relief='groove')
frm.pack(side='top', anchor='n', fill='x')
b = Tkinter.Label(frm, text="Call", font=lfont)
b.pack(side='left', anchor='nw')
b = Tkinter.Entry(frm, bg=fcolor, width=12, textvariable=self.varCall)
# b.bind('<MouseWheel>', MouseWheel)
# print b.bind()
Help(b,
'Enter the call sign of known stations, and hit "Enter". Stations are recorded in the file Stations.csv.')
b.pack(side='left', anchor='nw')
b.bind('<Key-Return>', self.SetStation)
b = Tkinter.Entry(frm, bg=fcolor, textvariable=self.varStation)
Help(b,
'Enter a description of known stations, and hit "Enter". Stations are recorded in the file Stations.csv.')
b.pack(side='left', anchor='nw', expand=1, fill='x')
b.bind('<Key-Return>', self.SetStation)
b = Tkinter.Label(frm, font=lfont, text='Config', bd=1, relief='raised')
Help(b, 'Right click to get a configuration menu.')
b.pack(side='right', anchor='e')
b.bind('<ButtonPress-3>', self.ConfigMenu)
self.dispDTMF = Tkinter.Label(frm, font=lfont, width=25, anchor='w', text=" DTMF Tone:")
self.dispDTMF.pack(side='right', anchor='ne')
Help(self.dispDTMF, 'If a DTMF tone is received, it is displayed here.')
for i in range(0, 2):
self.SetDtmf(`i % 10`)
# Band scope goes in right box bottom
bscope = self.dispBandScope = BandScope(frame, self, width=1, height=1, bg=bcolorb)
Help(bscope, 'Bandscope: Right click to configure. To tune, click grid, or press "Tune" and drag mouse.')
bscope.pack(side='top', anchor='n', expand=1, fill='both')
# End of widget create and place
try:
self.MakeBands(IniFile['AppBandFileName'])
except:
pass
self.radio.SetAll()
self.logging = 1
# print self.option_get()
def ConfigMenu(self, event):
menu = Tkinter.Menu(self, tearoff=0)
menu.add_checkbutton(label='Select multiple bands', variable=self.varMultBands)
menu.add_checkbutton(label='Show help at bottom', variable=self.varShowHelp, command=self.HelpCmd)
menu.add_separator()
bands = Tkinter.Menu(menu, tearoff=0)
for name in BandFileNames():
bands.add_command(label=name, command=Shim(self.MakeBands, name))
menu.add_cascade(label='Load band file', menu=bands)
menu.add_separator()
menu.add_command(label="Show serial port...", command=self.OnButtonSerial)
menu.tk_popup(event.x_root, event.y_root)
def HelpCmd(self):
if self.varShowHelp.get():
StatusBar.show_help = 1
StatusBar.configure(bd=2, height=StatusBar.statusHeight)
else:
StatusBar.show_help = 0
StatusBar.configure(bd=0, height=0)
def ReadStations(self):
"""
Read data in Stations.csv
Frequency, Call, Mode, Filter, Description
146.030m, K3MXU, nFM, 15k, Imaginary station
"""
d = {}
fp = open("Stations.csv", "r")
self.stHeading = fp.readline() # Save the heading
for text in fp.readlines():
data = text.split(',')
freq = MakeFreq(data[0].strip())
d[freq] = data
fp.close()
self.Stations = d
self.ListStations = d.keys()
self.ListStations.sort()
self.changedStations = 0
def WriteStations(self):
"""Write the changed Stations.csv"""
dict = self.Stations
text = self.stHeading
for freq in self.ListStations:
data = dict[freq]
t = ','.join(data)
text = text + t
fp = open("Stations.csv", "w")
fp.write(text)
fp.close()
def WmDeleteWindow(self):
self.radio.RadioPower(0)
# if self.changedStations:
# self.WriteStations()
try:
fp = open("PyPCR1000.ini", "w")
except IOError:
pass
else:
for k, v in IniFile.items():
fp.write("%s=%s\n" % (k, v))
fp.close()
self.destroy()
def ClearBands(self):
for data in self.Bands:
data[0].configure(relief='raised')
data[1] = 0
def MakeBands(self, name):
for data in self.Bands:
data[0].pack_forget()
data[0].destroy()
del self.Bands[:]
filedata = ReadBands(name)
IniFile['AppBandFileName'] = name
count = len(filedata)
row = col = 0
maxcol = (count + 2) / 3 # number of columns
if maxcol < 2:
maxcol = 2
elif maxcol > 7:
maxcol = 7
for i in range(3 * maxcol): # There are always three rows
if col == maxcol:
row = row + 1
col = 0
if i < count:
b = Tkinter.Button(self.bandRows[row], text=filedata[i][0], font=bfont, pady=bpady, state='normal',
padx=0, width=5, command=Shim(self.SelectBand, i))
# self.Bands is a list of [button, selected, filedata]
self.Bands.append([b, 0, filedata[i]])
else:
b = Tkinter.Button(self.bandRows[row], text='', font=bfont, pady=bpady, state='disabled', padx=0,
width=5)
self.Bands.append([b, 0, []])
Help(b, 'Band buttons: press to select the band and tune to its start.')
b.pack(side='left', anchor='nw', expand=1, fill='x')
col = col + 1
if count:
self.SelectBand(0)
def SelectBand(self, index):
"""
self.Bands is a list of [button, selected, filedata]
filedata is [Button text, Freq Start, Freq End, Freq Step, Mode, Filter, Description]
"""
mult = self.varMultBands.get()
if mult and self.Bands[index][1]: # Is the band selected?
self.Bands[index][0].configure(relief='raised')
self.Bands[index][1] = 0
else:
data = self.Bands[index][2]
self.dispMode.Set(data[4])
self.dispFilter.Set(data[5])
self.dispFreq.Set(data[1])
self.StepBandChange(data[3])
if not mult:
self.ClearBands()
self.Bands[index][0].configure(relief='sunken')
self.Bands[index][1] = 1
def DisplayStation(self, freq):
if self.Stations.has_key(freq):
data = self.Stations[freq]
self.varCall.set(data[1].strip())
self.varStation.set(data[4].strip())
else:
self.varCall.set('')
self.varStation.set('')
def NextStation(self, up):
""" Tune to next station."""
from bisect import bisect_left, bisect_right
if not self.ListStations:
return
if up:
i = bisect_right(self.ListStations, self.radio.frequency)
if i == len(self.ListStations): # we're at the right end, wrap around
i = 0
freq = self.ListStations[i]
else:
i = bisect_left(self.ListStations, self.radio.frequency)
if i == 0: # we're at the left end, wrap around
i = len(self.ListStations)
freq = self.ListStations[i - 1]
self.dispFreq.Set(freq)
self.dispMode.Set(self.Stations[freq][2])
self.dispFilter.Set(self.Stations[freq][3])
def NextFrequency(self, up, wrap=0):
bands = []
for b, sel, data in self.Bands:
if sel: # Band is selected
if data[1] <= self.radio.frequency <= data[2]: # We are in this band
step = self.band_step
if up:
freq = ((self.radio.frequency + step) / step) * step
else:
now = self.radio.frequency
freq = (now / step) * step
if freq == now:
freq = freq - step
if data[1] <= freq <= data[2]: # New freq is still within the band
self.dispFreq.Set(freq)
return 1
else:
bands.append(data)
# We need to change bands
freq = self.radio.frequency
if up:
for data in bands:
if freq <= data[1]:
self.dispFreq.Set(data[1])
self.StepBandChange(data[3])
self.dispMode.Set(data[4])
self.dispFilter.Set(data[5])
return 1
else:
bands.reverse()
for data in bands:
if freq >= data[2]:
self.dispFreq.Set(data[2])
self.StepBandChange(data[3])
self.dispMode.Set(data[4])
self.dispFilter.Set(data[5])
return 1
# We failed to change to a new frequency. If "wrap" then restart.
if not wrap:
return
if up:
for b, sel, data in self.Bands:
if sel: # Band is selected
self.dispFreq.Set(data[1])
self.StepBandChange(data[3])
self.dispMode.Set(data[4])
self.dispFilter.Set(data[5])
return 1
else:
bands = []
bands.extend(self.Bands)
for b, sel, data in bands:
if sel: # Band is selected
self.dispFreq.Set(data[2])
self.StepBandChange(data[3])
self.dispMode.Set(data[4])
self.dispFilter.Set(data[5])
return 1
def ScanDownBand(self):
if self.radio.power != 1:
return
if self.memscanner:
self.StopMemscan()
if self.scanner == 1:
self.ScanUpBand() # Turn off previous scan
if self.scanner:
self.scanner = 0
self.dispScanDown.config(background=self.btnBcolor, activebackground=self.btnAcolor, relief='raised')
else:
self.dispScanDown.config(background=ncolor, activebackground=ncolor, relief='sunken')
self.scanner = -1
if self.NextFrequency(0, 1):
self.after(ScanMillisecs, self.RunScanner)
def ScanUpBand(self):
if self.radio.power != 1:
return
if self.memscanner:
self.StopMemscan()
if self.scanner == -1:
self.ScanDownBand() # Turn off previous scan
if self.scanner:
self.scanner = 0
self.dispScanUp.config(background=self.btnBcolor, activebackground=self.btnAcolor, relief='raised')
else:
self.dispScanUp.config(background=ncolor, activebackground=ncolor, relief='sunken')
self.scanner = 1
if self.NextFrequency(1, 1):
self.after(ScanMillisecs, self.RunScanner)
def StopScanner(self):
if self.scanner > 0:
self.ScanUpBand()
elif self.scanner < 0:
self.ScanDownBand()
def RunScanner(self):
p = self.radio.serialport
if p.isOpen() and self.scanner:
self.after(ScanMillisecs, self.RunScanner) # Reschedule
if self.radio.squelch_open:
self.StopScanner()
elif self.scanner > 0:
if not self.NextFrequency(1, 1):
self.StopScanner()
elif self.scanner < 0:
if not self.NextFrequency(0, 1):
self.StopScanner()
else:
self.StopScanner()
def StepBandMenu(self, event):
menu = Tkinter.Menu(self, tearoff=0)
for t in ('100', '1k', '2k', '2.5k', '5k', '10k', '15k', '20k', '50k', '100k'):
menu.add_command(label=t, command=Shim(self.StepBandChange, MakeFreq(t)))
menu.tk_popup(event.x_root, event.y_root)
def StepBandChange(self, freq):
text = ShowFreq(freq)
self.dispStepBandU.config(text=text + '>')
self.dispStepBandD.config(text='<' + text)
self.band_step = freq
def MemoryButtonCmd(self, index):
tup = self.Memories[index]
# tup is freq, mode, filter
if tup:
self.dispMode.Set(tup[1])
self.dispFilter.Set(tup[2])
self.dispFreq.Set(tup[0])
def MemoryButtonMenu(self, event):
widget = event.widget
index = widget.index
tup = self.Memories[index] # tup is freq, mode, filter
menu = Tkinter.Menu(self, tearoff=0)
t = 'Set memory button'
menu.add_command(label=t, command=Shim(self.MemoryButtonSet, event))
if tup:
t = 'Erase %s %s %s' % (ShowFreq(tup[0]), tup[1], tup[2])
else:
t = 'Erase'
menu.add_command(label=t, command=Shim(self.MemoryButtonErase, event))
menu.tk_popup(event.x_root, event.y_root)
def MemoryButtonSet(self, event):
widget = event.widget
index = widget.index
self.Memories[index] = (self.radio.frequency, self.radio.mode, self.radio.filter)
widget.configure(state='normal')
def MemoryButtonErase(self, event):
widget = event.widget
index = widget.index
self.Memories[index] = None
widget.configure(state='disabled')
def ShiftButton(self):
if self.varShift.get():
self.shift_back = self.radio.frequency
self.dispFreq.Set(self.shift_back + self.shift_delta)
else:
self.dispFreq.Set(self.shift_back)
def ShiftButtonMenu(self, event):
menu = Tkinter.Menu(self, tearoff=0)
lst = ('100k', '600k', '1.2m')
for t in lst:
t = '+' + t
menu.add_command(label=t, command=Shim(self.ShiftButtonChange, event.widget, t))
for t in lst:
t = '-' + t
menu.add_command(label=t, command=Shim(self.ShiftButtonChange, event.widget, t))
menu.tk_popup(event.x_root, event.y_root)
def ShiftButtonChange(self, widget, text):
self.varShift.set(0)
widget.config(text=text)
self.shift_delta = MakeFreq(text)
def Power(self): # The power button was pressed
if self.radio.power == 1: # Radio is on
self.radio.RadioPower(0)
else:
self.radio.RadioPower(1)
if self.radio.power == 1: # Radio is on
self.power_button.SetColorNum(1)
else:
self.power_button.SetColorNum(0)
def SetStation(self, event):
freq = self.radio.frequency
call = self.varCall.get().strip()
call = string.replace(call, ',', ' ') # Remove commas
desc = self.varStation.get().strip()
desc = string.replace(desc, ',', ' ')
# Frequency, Call, Mode, Filter, Description
self.changedStations = 1
if not call and not desc: # delete station
if freq in self.ListStations:
self.ListStations.remove(freq)
del self.Stations[freq]
elif freq in self.ListStations:
self.Stations[freq] = [self.Stations[freq][0], call, self.radio.mode, self.radio.filter, desc + '\n']
else:
self.ListStations.append(freq)
self.ListStations.sort()
self.Stations[freq] = [str(freq), call, self.radio.mode, self.radio.filter, desc + '\n']
self.WriteStations()
def OnButtonSerial(self):
global LOGGER
if isinstance(LOGGER, DialogSerial):
LOGGER.focus_set() # Do not create two serial dialog boxes
elif self.radio.serialport:
LOGGER = DialogSerial(self.radio.serialport, None)
LOGGER.wm_transient(self)
def ReadSerial(self):
p = self.radio.serialport
if p.isOpen():
try:
text = p.read() # this will time out
except:
FormatTb()
p.close()
return
if text:
if LOGGER:
LOGGER.write(text)
self.radio.RadioParseInput(text)
def OnButtonMemscan(self):
if self.radio.power != 1:
return
if self.scanner: # band scanning currently in progress, stop
self.StopScanner()
if self.memscanner:
self.StopMemscan()
else:
self.StartMemscan()
def RunMemscan(self):
p = self.radio.serialport
if p.isOpen() and self.memscanner:
if self.radio.squelch_open:
self.after(ScanMillisecs, self.PauseMemscan)
else:
self.NextStation(1) # tune to the next channel
self.after(ScanMillisecs, self.RunMemscan) # Reschedule ourself
def PauseMemscan(self):
if self.radio.squelch_open:
self.after(ScanMillisecs, self.PauseMemscan) # wait for squelch to close
else:
self.after(3000, self.HoldForFollowupMemscan) # delay in case it comes back right away
def HoldForFollowupMemscan(self):
if self.radio.squelch_open:
self.after(ScanMillisecs, self.PauseMemscan)
else:
self.after(ScanMillisecs, self.RunMemscan)
def StopMemscan(self):
self.memscanner = False
self.dispMemscan.config(background=self.btnBcolor, activebackground=self.btnAcolor, relief='raised')
def StartMemscan(self):
self.memscanner = True
self.dispMemscan.config(background=ncolor, activebackground=ncolor, relief='sunken')
self.after(ScanMillisecs, self.RunMemscan)
def OnButtonUnused2(self):
pass
def SetDtmf(self, ch):
t = self.textDTMF + ch
t = t[-12:]
self.textDTMF = t
self.dispDTMF.config(text=' DTMF Tone: ' + t)
class PCR1000:
"""This class implements the interface to an Icom PCR1000 radio."""
modes = ('LSB', 'CW', 'USB', 'AM', 'nFM', 'wFM')
dictMode = {'LSB': 0, 'CW': 3, 'USB': 1, 'AM': 2, 'nFM': 5, 'wFM': 6}
filters = ('2.8k', '6k', '15k', '50k', '230k')
dictFilter = {'2.8k': 0, '6k': 1, '15k': 2, '50k': 3, '230k': 4}
mode2filter = {'LSB': '2.8k', 'CW': '2.8k', 'USB': '2.8k', 'AM': '6k', 'nFM': '15k', 'wFM': '230k'}
hexDigits = '0123456789aAbBcCdDeEfF'
def __init__(self, app):
self.app = app
self.serialport = serial.Serial(baudrate=9600, timeout=0.1)
p = IniFile.get('AppSerialPortName', '0')
if len(p) == 1 and p in '0123456789':
p = int(p)
self.serialport.setPort(p)
self.power = -1 # radio power status is unknown:-1, off:0, on:1
self.parse_n = 0 # Number of characters from serial port parsed.
self.parse_bs = [0] * 17 # data for band scope
self.bandscope = 1 # band scope: 0==off, 1==on, -1==unavailable
self.bad_cmd = 0 # count of bad commands
self.squelch_open = 0
# Set initial frequency, filter, etc.
self.frequency = 1234567890
self.mode = 'USB'
self.intmode = self.dictMode[self.mode]
self.filter = '2.8k'
self.intfilter = self.dictFilter[self.filter]
self.AGC = 0
self.AFC = 0
self.ATT = 0
self.NB = 0
self.squelch = float(IniFile.get('Squelch', '0.0'))
self.volume = float(IniFile.get('Volume', '0.25'))
self.ifshift = 0.5
# Start polling the serial port even though it is not open
self.PollSerial()
def PollSerial(self):
"""Poll the serial port"""
self.app.after(SerialPollMillisecs, self.PollSerial) # Reschedule the poll
p = self.serialport
if p.isOpen():
n = p.inWaiting()
while n:
try:
text = p.read(size=n)
except:
FormatTb()
p.close()
break
else:
if LOGGER:
LOGGER.write(text)
self.RadioParseInput(text)
n = p.inWaiting()
def SerialWrite(self, s):
p = self.serialport
if p.isOpen():
p.write(s)
def RadioParseInput(self, text):
for ch in text:
if not self.parse_n:
if ch in 'GHIN': # Start of command
self.parse_ch0 = ch
self.parse_n = 1
continue
ch0 = self.parse_ch0
length = self.parse_n
if ch0 == 'I':
if length == 1:
if ch in '0123':
self.parse_ch1 = ch