-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrtl_sdr_fm_player
executable file
·1001 lines (914 loc) · 42.7 KB
/
rtl_sdr_fm_player
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/python3
"""This program provides an FM radio GUI."""
import tkinter as tk
import subprocess
import time
import threading
import socket
import json
import re
#pylint: disable=no-name-in-module
from setproctitle import setproctitle
#pylint: enable=no-name-in-module
from settings import *
def permissive_json_loads(text):
"""Progressively loads and fixes mis-escaped json objects"""
while True:
try:
data = json.loads(text)
except json.decoder.JSONDecodeError as exc:
if exc.msg == 'Invalid \\escape':
text = text[:exc.pos] + '\\' + text[exc.pos:]
else:
raise
else:
return data
class Marquee(tk.Canvas): # pylint: disable=too-many-ancestors
"""A scrolling text marquee using tkinter canvas widget"""
def __init__(self, parent, text, font=None, the_args=None):
if the_args is None:
the_args = {'margin': 2, 'borderwidth': 0, 'fps': 30,
'width': 265, 'height': 22, 'highlightthickness': 0,
'relief': 'flat', 'font': None, 'fgd': None, 'bgd': None,
'highlightcolor': None,
'highlightbackground': None}
tk.Canvas.__init__(self, parent, borderwidth=the_args['borderwidth'],
relief=the_args['relief'], bg=the_args['bgd'],
width=the_args['width'], height=the_args['height'],
highlightthickness=the_args['highlightthickness'],
highlightcolor=the_args['highlightcolor'],
highlightbackground=the_args['highlightbackground'])
self.fps = the_args['fps']
self.font = font
self.fgd = the_args['fgd']
self.text = self.create_text(0, -1000, fill=self.fgd, font=self.font,
text=text, anchor="w", tags=("text",))
self.animate()
def update_text(self, new_text):
"""Update marquee text"""
self.delete(self.text)
self.text = self.create_text(0, -1000, fill=self.fgd, font=self.font,
text=new_text, anchor="w", tags=("text",))
def animate(self):
"""Scroll the marquee text"""
(x_0, y_0, x_1, _y_1) = self.bbox("text")
if x_1 < 0 or y_0 < 0:
x_0 = self.winfo_width()
y_0 = int(self.winfo_height() / 2)
self.coords("text", x_0, y_0)
else:
self.move("text", -1, 0)
self.after_id = self.after(int(1000/self.fps), self.animate)
class PresetButton(tk.Radiobutton): # pylint: disable=too-many-ancestors
"""A custom radio button using tkinter Radiobutton widget"""
def __init__(self, parent, args=None):
if args is None:
args = {'w': 5, 'bw': 0, 'sc': 'black', 'fg': 'white', 'bg': 'gray11',
'afg': 'white', 'abg': 'gray11', 'hlc': 'gray11', 'hlbg': 'gray11',
'txt': '', 'val': '', 'name': '', 'var': None, 'sp_cmd': None, 'lp_cmd': None}
tk.Radiobutton.__init__(
self, parent, width=args['w'], borderwidth=args['bw'],
selectcolor=args['sc'], fg=args['fg'], bg=args['bg'], indicatoron=0,
activeforeground=args['afg'], activebackground=args['abg'],
highlightcolor=args['hlc'], highlightbackground=args['hlbg'],
name=args['name'], text=args['txt'], value=args['val'], variable=args['var'])
self.short_press_cmd = args.get('sp_cmd', None)
self.long_press_cmd = args.get('lp_cmd', None)
self.press_time = None
self.release_time = None
self.after_id = None
self.parent = parent
self.bind("<ButtonPress-1>", self._on_press)
self.bind("<ButtonRelease-1>", self._on_release)
def _on_press(self, event):
del event # unused
self.press_time = time.time()
def _on_release(self, event):
del event # unused
self.release_time = time.time()
if self.release_time - self.press_time > 2:
if self.long_press_cmd is not None:
self.long_press_cmd()
else:
if self.short_press_cmd is not None:
self.short_press_cmd()
def set_short_press_cmd(self, cmd):
"""Set short press command"""
self.short_press_cmd = cmd
def set_long_press_cmd(self, cmd):
"""Set long press command"""
self.long_press_cmd = cmd
class RoundedButton(tk.Canvas): # pylint: disable=too-many-ancestors
"""A custom rounded-corner button using tkinter canvas widget"""
def __init__(self, parent, args=None):
if args is None:
args = {'width': 64, 'height': 64, 'cornerradius': 8,
'padding': 0, 'color': 'black', 'bg': 'gray11', 'image': None,
'press_command': None, 'release_command': None,
'repeatdelay': None, 'repeatinterval': None}
tk.Canvas.__init__(self, parent, borderwidth=0, selectborderwidth=0,
insertwidth=0, relief="flat", highlightthickness=0,
bg=args['bg'])
self.press_command = args.get('press_command', None)
self.release_command = args.get('release_command', None)
self.repeatdelay = args.get('repeatdelay', None)
self.repeatinterval = args.get('repeatinterval', None)
self.after_id = None
self.parent = parent
self.canvas_back = None
if args['cornerradius'] > 0.5 * args['width']:
print("Error: cornerradius is greater than width.")
return None
if args['cornerradius'] > 0.5 * args['height']:
print("Error: cornerradius is greater than height.")
return None
rad = 2 * args['cornerradius']
def shape():
self.create_polygon(
(args['padding'],
args['height']-args['cornerradius']-args['padding']-1,
args['padding'],
args['cornerradius']+args['padding'],
args['padding']+args['cornerradius'],
args['padding'],
args['width']-args['padding']-args['cornerradius']-1,
args['padding'],
args['width']-args['padding']-1,
args['cornerradius']+args['padding'],
args['width']-args['padding']-1,
args['height']-args['cornerradius']-args['padding']-1,
args['width']-args['padding']-args['cornerradius']-1,
args['height']-args['padding']-1,
args['padding']+args['cornerradius'],
args['height']-args['padding']-1),
fill=args['color'], outline=args['color'], width=0)
self.create_arc(
(args['padding'], args['padding']+rad,
args['padding']+rad, args['padding']),
start=90, extent=90,
fill=args['color'], outline=args['color'], width=0)
self.create_arc(
(args['width']-args['padding']-rad-1, args['padding'],
args['width']-args['padding']-1, args['padding']+rad),
start=0, extent=90,
fill=args['color'], outline=args['color'], width=0)
self.create_arc(
(args['width']-args['padding']-1, args['height']-rad-args['padding']-1,
args['width']-args['padding']-rad-1, args['height']-args['padding']-1),
start=270, extent=90,
fill=args['color'], outline=args['color'], width=0)
self.create_arc(
(args['padding'], args['height']-args['padding']-rad-1,
args['padding']+rad, args['height']-args['padding']-1),
start=180, extent=90,
fill=args['color'], outline=args['color'], width=0)
shape()
(x_0, y_0, x_1, y_1) = self.bbox("all")
width = (x_1-x_0-3)
height = (y_1-y_0-3)
self.configure(width=width, height=height)
self.bind("<ButtonPress-1>", self._on_press)
self.bind("<ButtonRelease-1>", self._on_release)
if args.get('image', None) is not None:
bg_pos_x = (width / 2)
bg_pos_y = (height / 2)
self.canvas_back = self.create_image(bg_pos_x, bg_pos_y,
image=args['image'])
return None
def _on_press(self, event):
del event # unused
self.configure(relief="sunken")
if self.press_command is not None:
self.press_command()
if self.repeatdelay is not None:
self.after_id = self.after(self.repeatdelay, self._on_repeat)
def _on_repeat(self):
self.configure(relief="sunken")
if self.press_command is not None:
self.press_command()
if self.repeatinterval is not None:
self.after_id = self.after(self.repeatinterval, self._on_repeat)
def _on_release(self, event):
del event # unused
self.configure(relief="raised")
if self.after_id is not None:
self.after_cancel(self.after_id)
if self.release_command is not None:
self.release_command()
def update_image(self, image=None):
"""Change the button image"""
if image is not None:
self.itemconfig(self.canvas_back, image=image)
class CPUInfo:
"""Displays current CPU usage info in a tkinter label"""
def __init__(self, tk_cpu_label):
self.cpu_utilisation = ''
self.cpu_text = tk_cpu_label
# credit https://rosettacode.org/wiki/Linux_CPU_utilization
def _cpu_utilisation(self):
"""Calculate CPU utilisation"""
last_idle = last_total = 0
while True and self.cpu_utilisation is not None:
with open('/proc/stat') as proc_stat:
fields = [float(column) for column in proc_stat.readline().strip().split()[1:]]
idle, total = fields[3], sum(fields)
idle_delta, total_delta = idle - last_idle, total - last_total
last_idle, last_total = idle, total
utilisation = 100.0 * (1.0 - idle_delta / total_delta)
self.cpu_utilisation = ('%5.1f%%' % utilisation)
time.sleep(2)
def _cpu_info(self):
"""Update displayed CPU information"""
self.cpu_text.config(text='CPU %s' % self.cpu_utilisation)
self.cpu_text.after(2000, self._cpu_info)
def start(self):
"""Start daemon and label updater"""
cpu_thread = threading.Thread(target=self._cpu_utilisation)
cpu_thread.daemon = True
cpu_thread.start()
self._cpu_info()
def get_cpu_utilisation(self):
"""Return CPU utilisation string"""
return self.cpu_utilisation
class PlayerApp:
"""Player Application"""
def __init__(self, freq_list, current_freq, extra_args=None):
if extra_args is None:
extra_args = {'temp_dir': None, 'play_str': None,
'vol_down_cmd': None, 'vol_up_cmd': None,
'hst': None, 'api_prt': None, 'use_srv': False}
self.frequencies = freq_list
self.current_freq = current_freq
self.temp_dir = extra_args['temp_dir']
self.status = {
'Stop': True, 'Muted': False, 'Tuning': 'finished',
'using_server': extra_args['use_srv']}
self.cmds = {'play_string': extra_args['play_str'],
'vol_down_cmd': extra_args['vol_down_cmd'],
'vol_up_cmd': extra_args['vol_up_cmd']}
self.api = {'host': extra_args['hst'], 'api_port': extra_args['api_prt']}
self.player_gui = None
def play(self, p_string):
"""Run external demodulator program"""
print('Play String %s' % p_string)
proc = subprocess.Popen(p_string, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
while not self.status['Stop']:
time.sleep(.2)
print('STOP: %s' % self.status['Stop'])
proc.terminate()
if self.status['using_server']:
subprocess.run(['killall', 'ffplay'])
else:
subprocess.run(['killall', '-s', 'SEGV', 'rtl_fm'])
def start(self, frequency):
"""Start playing a given frequency"""
preset_list = self.player_gui.get_preset_list()
if self.status['Stop']:
print('starting play_thread')
if self.status['using_server']:
freq = int(float(frequency) * 1000000)
p_string = self.cmds['play_string'].replace('/freq/', '/%s/' % freq)
else:
self.player_gui.clear_station_data()
p_string = self.cmds['play_string'].replace(
'rtl_fm', 'rtl_fm -f %sM' % frequency)
play_thread = threading.Thread(target=self.play, args=([p_string]))
play_thread.daemon = True
play_thread.start()
if frequency in preset_list:
self.player_gui.set_preset_rb_var(frequency)
else:
self.player_gui.set_preset_rb_var(None)
print(p_string)
self.status['Stop'] = False
else:
print('stopping play_thread')
self.status['Stop'] = True
def stop(self):
"""Stop playing audio from currently tuned frequency"""
self.status['Stop'] = True
def mute(self):
"""Toggle muting the volume"""
if self.status['Muted']:
self.status['Muted'] = False
else:
self.status['Muted'] = True
subprocess.run(['amixer', '-q', '-D', 'pulse', 'sset', 'Master', 'toggle'])
def vol_up(self):
"""Turn up volume"""
print('vol up')
cmd_list = self.cmds['vol_up_cmd'].split()
subprocess.run(cmd_list)
def vol_down(self):
"""Turn down volume"""
cmd_list = self.cmds['vol_down_cmd'].split()
subprocess.run(cmd_list)
def next_station(self):
"""Switch to next preset station/frequency"""
if not self.status['using_server']:
self.stop()
if self.current_freq in self.frequencies:
curr_freq = self.frequencies.index(self.current_freq)
if self.frequencies[curr_freq] == self.frequencies[-1]:
self.current_freq = self.frequencies[0]
else:
self.current_freq = self.frequencies[curr_freq + 1]
else:
freq_list = [i for i in self.frequencies if i > self.current_freq]
if freq_list:
self.current_freq = freq_list[0]
else:
self.current_freq = self.frequencies[0]
if self.status['using_server']:
self.api_set_frequency(self.current_freq)
else:
time.sleep(1)
self.start(self.current_freq)
def previous_station(self):
"""Switch to previous preset station/frequency"""
if not self.status['using_server']:
self.stop()
if self.current_freq in self.frequencies:
curr_freq = self.frequencies.index(self.current_freq)
if self.frequencies[curr_freq] == self.frequencies[0]:
self.current_freq = self.frequencies[-1]
else:
self.current_freq = self.frequencies[curr_freq - 1]
else:
freq_list = [i for i in self.frequencies if i < self.current_freq]
if freq_list:
self.current_freq = freq_list[0]
else:
self.current_freq = self.frequencies[-1]
if self.status['using_server']:
self.api_set_frequency(self.current_freq)
else:
time.sleep(1)
self.start(self.current_freq)
def select_preset(self, freq, pbn):
"""Switch to given preset station/frequency"""
print('called select_preset ' + freq + ' ' + pbn)
if freq == 'Preset':
self.player_gui.set_preset_rb_var(self.get_current_freq())
return
if not self.status['using_server']:
self.stop()
self.current_freq = freq
if self.status['using_server']:
self.api_set_frequency(self.current_freq)
else:
time.sleep(1)
self.start(self.current_freq)
def save_preset(self, freq, pbn):
"""Switch to given preset station/frequency"""
print('called save_preset ' + freq + ' ' + pbn)
if freq in self.player_gui.get_preset_list() and freq != 'Preset':
self.player_gui.set_preset_rb_var(self.get_current_freq())
return
master = self.player_gui.get_tk_root()
master.nametowidget(pbn).config(text=self.current_freq, value=pbn + self.current_freq)
master.nametowidget(pbn).set_short_press_cmd(
lambda s=self.current_freq, pb=pbn: self.select_preset(s, pb))
master.nametowidget(pbn).set_long_press_cmd(
lambda s=self.current_freq, pb=pbn: self.save_preset(s, pb))
self.player_gui.set_preset_rb_var(self.get_current_freq(), pbn)
preset_list = []
for num in range(1, 9):
preset_list.append(master.nametowidget('pb' + str(num)).cget('text'))
update_stations(preset_list)
self.frequencies = preset_list
def manual_tune(self, direction='down'):
"""Manually tune up or down by 0.1MHz"""
if not self.status['using_server']:
if not self.status['Stop']:
self.stop()
self.status['Tuning'] = 'started'
if direction == 'up':
self.current_freq = str(round((float(self.current_freq) + 0.1), 1))
else:
self.current_freq = str(round((float(self.current_freq) - 0.1), 1))
print('Tuning %s' % self.current_freq)
def tuning_stop(self):
"""Stop tuning"""
self.status['Tuning'] = 'stopped'
def tune(self):
"""Finish tuning to currently set frequency"""
if self.status['Tuning'] == 'stopped':
if self.status['using_server']:
self.api_set_frequency(self.current_freq)
else:
self.start(self.current_freq)
self.status['Tuning'] = 'finished'
print('Tuning to %s' % self.current_freq)
master = self.player_gui.get_tk_root()
master.after(200, self.tune)
def power_off(self):
"""Exit the application"""
self.stop()
subprocess.call('rm -r ' + self.temp_dir, shell=True)
time.sleep(1)
write_config()
if self.status['using_server']:
subprocess.run(['killall', 'rtl_fm_streamer'])
master = self.player_gui.get_tk_root()
master.destroy()
def _api_make_request(self, payload):
"""Make a request via rtl_fm_streamer API"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as soc:
soc.connect((self.api['host'], int(self.api['api_port'])))
soc.sendall(json.dumps(payload).encode('utf-8'))
data = soc.recv(1024)
return data
def api_set_frequency(self, frequency):
"""Set frequency using rtl_fm_streamer API"""
preset_list = self.player_gui.get_preset_list()
freq = int(float(frequency) * 1000000)
print('setting frequency to %s' % freq)
payload = {"method": "SetFrequency", "params": [freq]}
self._api_make_request(payload)
if frequency in preset_list:
self.player_gui.set_preset_rb_var(frequency)
else:
self.player_gui.set_preset_rb_var(None)
def api_get_power_level(self):
"""Get power level in dBFS from rtl_fm_streamer API"""
power_level = None
payload = {"method": "GetPowerLevel"}
data = self._api_make_request(payload).decode('utf-8')
pwr_lvl = re.search(':\\t(.+?)\\n', data)
if pwr_lvl:
power_level = float(pwr_lvl[0].strip(':\t\n'))
return power_level
def scan(self, direction='down'):
"""Automatically scan up or down frequencies based on signal power level"""
if self.status['Stop']:
return
power_level = self.api_get_power_level()
station = False
freq = float(self.current_freq)
while int(freq) in range(86, 109):
if direction == 'up':
freq = round(freq + 0.2, 1)
else:
freq = round(freq - 0.2, 1)
self.api_set_frequency(freq)
self.current_freq = str(freq)
time.sleep(.2)
power_level = self.api_get_power_level()
if power_level > -15:
station = True
print('Station found %s' % freq)
break
if station:
self.fine_tune(freq, power_level)
def fine_tune(self, freq, power_level):
"""Fine-tune automatically-scanned frequency"""
pwr_lvl = power_level
test = freq
count = False
while pwr_lvl >= power_level:
test = round(test + 0.1, 1)
self.api_set_frequency(test)
self.current_freq = str(test)
time.sleep(0.5)
pwr_lvl = self.api_get_power_level()
print('PL', pwr_lvl)
if pwr_lvl > power_level:
count = True
print('Count', count)
else:
if count:
freq = round(test - 0.1, 1)
self.api_set_frequency(freq)
self.current_freq = str(freq)
if not count:
pwr_lvl = power_level
test = freq
while pwr_lvl >= power_level:
test = round(test - 0.1, 1)
self.api_set_frequency(test)
self.current_freq = str(test)
time.sleep(0.5)
pwr_lvl = self.api_get_power_level()
print('PL', pwr_lvl)
if pwr_lvl > power_level:
count = True
print('Count', count)
else:
if count:
freq = round(test + 0.1, 1)
self.api_set_frequency(freq)
self.current_freq = str(freq)
if not count:
self.api_set_frequency(freq)
self.current_freq = str(freq)
def get_current_freq(self):
"""Return current frequency"""
return self.current_freq
def get_using_server(self):
"""Return whether or not the server is being used"""
return self.status['using_server']
def set_player_gui(self, gui_instance):
"""Set player GUI instance"""
self.player_gui = gui_instance
class PlayerGUI:
"""Player GUI"""
def __init__(self, master, app, stns, extra_args=None):
if extra_args is None:
extra_args = {'freq_list': [], 'bg_color': 'gray11', 'fnt_color': 'white',
'btn_color': 'black', 'ico_path': None, 'rds_log': None}
self.master = master
self.app = app
self.data = {
'stations': stns,
'freq_list': extra_args['freq_list'],
'preset_list': [],
'preset_rb_var': None,
'radio_text': ''}
self.colors = {'bg_color': extra_args['bg_color'],
'fnt_color': extra_args['fnt_color'],
'btn_color': extra_args['btn_color']}
self.paths = {'ico_path': extra_args['ico_path'],
'rds_log': extra_args['rds_log']}
self.imgs = {
'bg_img': None, 'play_img': None, 'stop_img': None,
'power_img': None, 'back_img': None, 'vol_down_img': None,
'vol_up_img': None, 'vol_unmuted_img': None, 'vol_muted_img': None,
'prev_img': None, 'next_img': None, 'tune_down_img': None,
'tune_up_img': None, 'scan_down_img': None, 'scan_up_img': None}
self.widgets = {
'canvas': None, 'freq_text': None, 'freq_unit': None,
'rt_label': None, 'rt_marquee': None, 'clock': None,
'cpu_text': None, 'play_btn': None, 'power_btn': None,
'back_btn': None, 'vol_down_btn': None, 'vol_up_btn': None,
'vol_mute_btn': None, 'previous_btn': None, 'next_btn': None,
'tune_down_btn': None, 'tune_up_btn': None, 'scan_down_btn': None,
'scan_up_btn': None}
self.master.title("RTL-SDR FM Player")
screen_width = self.master.winfo_screenwidth()
screen_height = self.master.winfo_screenheight()
if screen_width > 800 or screen_height > 480:
self.master.geometry("800x480")
self.master.wm_attributes('-zoomed', 1)
self.master.wm_attributes('-fullscreen', 1)
else:
self.master.geometry("%dx%d+0+0" % (screen_width, screen_height))
self.master.wm_attributes('-zoomed', 1)
self.master.wm_attributes('-fullscreen', 1)
self.widgets['canvas'] = tk.Canvas(self.master, width=800, height=480)
self.widgets['canvas'].config(background=self.colors['bg_color'], highlightthickness=0)
self.widgets['canvas'].pack()
self.imgs['bg_img'] = tk.PhotoImage(file=app_res_path('background.png'))
self.widgets['canvas'].create_image(400, 240, image=self.imgs['bg_img'])
self._create_texts()
self.create_presets(self.data['freq_list'])
self._create_buttons()
self._tick()
self._update_freq_label()
self._update_play_button()
self._update_vol_button()
self.clear_station_data()
self._update_station_data()
def _create_texts(self):
"""Create text elements"""
self.widgets['canvas'].create_text(
400, 20, anchor=tk.N,
font=('Quicksand Medium', 16, 'bold', 'italic'),
fill=self.colors['fnt_color'],
text='RTL-SDR FM Player', width=400)
self.widgets['freq_text'] = tk.Label(
self.master, font=("Quicksand Medium", 96, 'bold'),
fg=self.colors['fnt_color'], bg=self.colors['bg_color'],
padx=0, pady=0)
self.widgets['freq_text'].config(justify='right', fg=self.colors['fnt_color'])
self.widgets['freq_text'].place(relx=1, rely=1, x=-88, y=-104, anchor=tk.SE)
self.widgets['freq_unit'] = tk.Label(
self.master, font=("Quicksand Medium", 24, 'bold'),
fg=self.colors['fnt_color'], bg=self.colors['bg_color'],
padx=0, pady=25, text='MHz')
self.widgets['freq_unit'].config(justify='left', fg=self.colors['fnt_color'])
self.widgets['freq_unit'].place(relx=1, rely=1, x=-20, y=-104, anchor=tk.SE)
self.widgets['rt_label'] = tk.Label(
self.master, font=("Quicksand Medium", 12, 'bold'),
fg=self.colors['fnt_color'], bg=self.colors['bg_color'], text='RT:')
self.widgets['rt_label'].config(
anchor=tk.CENTER, width=3, wraplength=0, fg=self.colors['fnt_color'],
highlightthickness=1, highlightcolor=self.colors['bg_color'],
highlightbackground=self.colors['bg_color'])
self.widgets['rt_label'].place(relx=1, rely=1, x=-362, y=-280, anchor=tk.SE)
self.widgets['rt_marquee'] = Marquee(
self.master, text="",
font=('Quicksand Medium', 12, 'bold', 'italic'),
the_args={'margin': 2, 'borderwidth': 1, 'fps': 30,
'width': 265, 'height': 22, 'highlightthickness': 1,
'relief': 'flat', 'fgd': self.colors['fnt_color'],
'bgd': self.colors['bg_color'],
'highlightcolor': self.colors['bg_color'],
'highlightbackground': self.colors['bg_color']})
self.widgets['rt_marquee'].place(relx=1, rely=1, x=-94, y=-280, anchor=tk.SE)
self.widgets['clock'] = tk.Label(
self.master, font=('Quicksand Medium', 16, 'bold'),
bg=self.colors['bg_color'], fg=self.colors['fnt_color'])
self.widgets['clock'].place(relx=1, x=-20, y=20, anchor=tk.NE)
self.widgets['cpu_text'] = tk.Label(
self.master, font=('Quicksand Medium', 16, 'bold', 'italic'),
justify='left', bg=self.colors['bg_color'], fg=self.colors['fnt_color'])
self.widgets['cpu_text'].place(relx=0, rely=0, x=20, y=20, anchor=tk.NW)
def create_presets(self, freq_list):
"""Create preset radio buttons"""
preset_x = 0.15
preset_y = 0.25
self.data['preset_list'] = freq_list[:8]
if len(self.data['preset_list']) < 8:
while len(self.data['preset_list']) < 8:
self.data['preset_list'].append('Preset')
self.data['preset_rb_var'] = tk.StringVar()
if self.app.get_current_freq() in self.data['preset_list']:
self.data['preset_rb_var'].set(
'pb' + str(self.data['preset_list'].index(
self.app.get_current_freq()) + 1) + self.app.get_current_freq())
else:
self.data['preset_rb_var'].set(None)
for p_id, preset in enumerate(self.data['preset_list']):
b_id = 'pb' + str(p_id + 1)
b_name = PresetButton(
self.master,
args={
'w': 5, 'bw': 0, 'sc': 'black', 'fg': 'white', 'bg': 'gray11', 'afg': 'white',
'abg': 'gray11', 'hlc': 'gray11', 'hlbg': 'gray11', 'txt': preset,
'val': b_id + preset, 'var': self.data['preset_rb_var'], 'name': b_id,
'sp_cmd': lambda s=preset, pb=b_id: self.app.select_preset(s, pb),
'lp_cmd': lambda s=preset, pb=b_id: self.app.save_preset(s, pb)})
b_name.config(font=('Quicksand Medium', 16, 'bold', 'italic'), pady=14, anchor=tk.CENTER)
b_name.place(relx=preset_x, rely=preset_y)
if (p_id + 1) % 2 != 0:
preset_x += 0.15
else:
preset_x -= 0.15
preset_y += 0.13
def _create_buttons(self):
"""Create main custom buttons """
self.imgs['play_img'] = tk.PhotoImage(
file='%splay_64x64.png' % self.paths['ico_path'])
self.imgs['stop_img'] = tk.PhotoImage(
file='%sstop-circle_64x64.png' % self.paths['ico_path'])
self.widgets['play_btn'] = RoundedButton(
self.master, args={
'width': 64, 'height': 64,
'cornerradius': 8, 'padding': 0,
'color': self.colors['btn_color'],
'bg': self.colors['bg_color'],
'image': self.imgs['play_img'],
'release_command': lambda: self.app.start(self.app.get_current_freq())})
self.widgets['play_btn'].place(relx=0.5, rely=1, x=0, y=-20, anchor=tk.S)
self.imgs['power_img'] = tk.PhotoImage(
file='%spower_64x64.png' % self.paths['ico_path'])
self.widgets['power_btn'] = RoundedButton(
self.master, args={
'width': 64, 'height': 64,
'cornerradius': 8, 'padding': 0,
'color': self.colors['btn_color'],
'bg': self.colors['bg_color'],
'image': self.imgs['power_img'],
'release_command': self.app.power_off})
self.widgets['power_btn'].place(relx=1, rely=1, x=-20, y=-20, anchor=tk.SE)
self.imgs['back_img'] = tk.PhotoImage(
file='%sarrow-left-circle_64x64.png' % self.paths['ico_path'])
self.widgets['back_btn'] = RoundedButton(
self.master, args={
'width': 64, 'height': 64,
'cornerradius': 8, 'padding': 0,
'color': self.colors['btn_color'],
'bg': self.colors['bg_color'],
'image': self.imgs['back_img'],
'release_command': self._back})
self.widgets['back_btn'].place(relx=0, rely=1, x=20, y=-20, anchor=tk.SW)
self.imgs['vol_up_img'] = tk.PhotoImage(
file='%schevron-up_64x64.png' % self.paths['ico_path'])
self.widgets['vol_up_btn'] = RoundedButton(
self.master, args={
'width': 64, 'height': 64,
'cornerradius': 8, 'padding': 0,
'color': self.colors['btn_color'],
'bg': self.colors['bg_color'],
'image': self.imgs['vol_up_img'],
'press_command': self.app.vol_up,
'repeatdelay': 200,
'repeatinterval': 500})
self.widgets['vol_up_btn'].place(relx=0, rely=0.5, x=20, y=-74, anchor=tk.W)
self.imgs['vol_unmuted_img'] = tk.PhotoImage(
file='%svolume-2_64x64.png' % self.paths['ico_path'])
self.imgs['vol_muted_img'] = tk.PhotoImage(
file='%svolume-x_64x64.png' % self.paths['ico_path'])
self.widgets['vol_mute_btn'] = RoundedButton(
self.master, args={
'width': 64, 'height': 64,
'cornerradius': 8, 'padding': 0,
'color': self.colors['btn_color'],
'bg': self.colors['bg_color'],
'image': self.imgs['vol_unmuted_img'],
'release_command': self.app.mute})
self.widgets['vol_mute_btn'].place(relx=0, rely=0.5, x=20, y=0, anchor=tk.W)
self.imgs['vol_down_img'] = tk.PhotoImage(
file='%schevron-down_64x64.png' % self.paths['ico_path'])
self.widgets['vol_down_btn'] = RoundedButton(
self.master, args={
'width': 64, 'height': 64,
'cornerradius': 8, 'padding': 0,
'color': self.colors['btn_color'],
'bg': self.colors['bg_color'],
'image': self.imgs['vol_down_img'],
'press_command': self.app.vol_down,
'repeatdelay': 200,
'repeatinterval': 500})
self.widgets['vol_down_btn'].place(relx=0, rely=0.5, x=20, y=74, anchor=tk.W)
self.imgs['prev_img'] = tk.PhotoImage(
file='%sskip-back_64x64.png' % self.paths['ico_path'])
self.widgets['previous_btn'] = RoundedButton(
self.master, args={
'width': 64, 'height': 64,
'cornerradius': 8, 'padding': 0,
'color': self.colors['btn_color'],
'bg': self.colors['bg_color'],
'image': self.imgs['prev_img'],
'release_command': self.app.previous_station})
self.widgets['previous_btn'].place(relx=0.5, rely=1, x=-74, y=-20, anchor=tk.S)
self.imgs['next_img'] = tk.PhotoImage(
file='%sskip-forward_64x64.png' % self.paths['ico_path'])
self.widgets['next_btn'] = RoundedButton(
self.master, args={
'width': 64, 'height': 64,
'cornerradius': 8, 'padding': 0,
'color': self.colors['btn_color'],
'bg': self.colors['bg_color'],
'image': self.imgs['next_img'],
'release_command': self.app.next_station})
self.widgets['next_btn'].place(relx=0.5, rely=1, x=74, y=-20, anchor=tk.S)
self.imgs['tune_down_img'] = tk.PhotoImage(
file='%schevron-left_64x64.png' % self.paths['ico_path'])
self.widgets['tune_down_btn'] = RoundedButton(
self.master, args={
'width': 64, 'height': 64,
'cornerradius': 8, 'padding': 0,
'color': self.colors['btn_color'],
'bg': self.colors['bg_color'],
'image': self.imgs['tune_down_img'],
'press_command': self.app.manual_tune,
'release_command': self.app.tuning_stop,
'repeatdelay': 500,
'repeatinterval': 200})
self.widgets['tune_down_btn'].place(relx=0.5, rely=1, x=-148, y=-20, anchor=tk.S)
self.imgs['tune_up_img'] = tk.PhotoImage(
file='%schevron-right_64x64.png' % self.paths['ico_path'])
self.widgets['tune_up_btn'] = RoundedButton(
self.master, args={
'width': 64, 'height': 64,
'cornerradius': 8, 'padding': 0,
'color': self.colors['btn_color'],
'bg': self.colors['bg_color'],
'image': self.imgs['tune_up_img'],
'press_command': lambda d='up': self.app.manual_tune(d),
'release_command': self.app.tuning_stop,
'repeatdelay': 500,
'repeatinterval': 200})
self.widgets['tune_up_btn'].place(relx=0.5, rely=1, x=148, y=-20, anchor=tk.S)
if self.app.get_using_server():
self.imgs['scan_down_img'] = tk.PhotoImage(
file='%schevrons-left_64x64.png' % self.paths['ico_path'])
self.widgets['scan_down_btn'] = RoundedButton(
self.master, args={
'width': 64, 'height': 64,
'cornerradius': 8, 'padding': 0,
'color': self.colors['btn_color'],
'bg': self.colors['bg_color'],
'image': self.imgs['scan_down_img'],
'release_command': self.app.scan})
self.widgets['scan_down_btn'].place(relx=0.5, rely=1, x=-222, y=-20, anchor=tk.S)
self.imgs['scan_up_img'] = tk.PhotoImage(
file='%schevrons-right_64x64.png' % self.paths['ico_path'])
self.widgets['scan_up_btn'] = RoundedButton(
self.master, args={
'width': 64, 'height': 64,
'cornerradius': 8, 'padding': 0,
'color': self.colors['btn_color'],
'bg': self.colors['bg_color'],
'image': self.imgs['scan_up_img'],
'release_command': lambda d='up': self.app.scan(d)})
self.widgets['scan_up_btn'].place(relx=0.5, rely=1, x=222, y=-20, anchor=tk.S)
def _back(self):
"""Minimize the application window"""
self.master.wm_state("iconic")
def _update_freq_label(self):
"""Update displayed frequency"""
self.widgets['freq_text'].config(text=self.app.get_current_freq())
self.widgets['freq_text'].after(100, self._update_freq_label)
def _update_play_button(self):
"""Swap play and stop icons"""
if self.app.status['Stop']:
button_img = self.imgs['play_img']
else:
button_img = self.imgs['stop_img']
self.widgets['play_btn'].update_image(button_img)
self.widgets['play_btn'].after(200, self._update_play_button)
def _update_vol_button(self):
"""Swap unmuted and muted volume icons"""
if self.app.status['Muted']:
button_image = self.imgs['vol_muted_img']
else:
button_image = self.imgs['vol_unmuted_img']
self.widgets['vol_mute_btn'].update_image(button_image)
self.widgets['vol_mute_btn'].after(200, self._update_vol_button)
def clear_station_data(self):
"""Clear out displayed Radio Text"""
self.data['radio_text'] = ''
self.widgets['rt_marquee'].update_text(new_text='')
def _update_station_data(self):
"""Update displayed Radio Text from RDS"""
if not self.app.get_using_server() and use_rds:
previous_rt = self.data['radio_text']
try:
rds_rt_json_lines = subprocess.check_output(['grep', '\"radiotext\"',
self.paths['rds_log']])
except subprocess.CalledProcessError as exc:
if exc.returncode > 1:
raise
rds_rt_json_lines = ''
if rds_rt_json_lines != '':
rds_rt_json = rds_rt_json_lines.decode('utf-8').splitlines()[-1]
print(rds_rt_json)
rds_rt_data = permissive_json_loads(rds_rt_json)
self.data['radio_text'] = rds_rt_data[u'radiotext'].strip()
if self.data['radio_text'] != previous_rt:
self.widgets['rt_marquee'].update_text(new_text='%s' % self.data['radio_text'])
subprocess.call(
'echo "$(tail -n500 ' + self.paths['rds_log'] + ')" > ' + self.paths['rds_log'],
shell=True)
else:
if self.app.get_current_freq() in self.data['stations']:
self.widgets['rt_marquee'].update_text(
new_text='%s' % self.data['stations'][self.app.get_current_freq()])
else:
self.widgets['rt_marquee'].update_text(new_text='%s' % self.app.get_current_freq())
self.widgets['rt_marquee'].after(5000, self._update_station_data)
def _tick(self):
"""Update displayed time"""
time_string = ''
time_now = time.strftime('%H:%M')
if time_now != time_string:
self.widgets['clock'].config(text=time_now.lstrip('0'))
self.widgets['clock'].after(200, self._tick)
def get_tk_root(self):
"""Return tkinter root element"""
return self.master
def get_cpu_text_label(self):
"""Return CPU text label"""
return self.widgets['cpu_text']
def get_preset_list(self):
"""Return preset list"""
return self.data['preset_list']
def set_preset_rb_var(self, frequency, pbn=None):
"""Set preset radio button variable"""
if pbn is None and frequency in self.data['preset_list']:
self.data['preset_rb_var'].set(
'pb' + str(self.data['preset_list'].index(frequency) + 1) + frequency)
elif pbn is None:
self.data['preset_rb_var'].set('pb0' + str(frequency))
else:
self.data['preset_rb_var'].set(pbn + frequency)
def main():
"""Main application"""
setproctitle('rtl_sdr_fm_player')
temp_directory = subprocess.check_output(
'tempdir=$(mktemp -dt "rtl_sdr_fm_player.XXXXXXXX"'
+ ' --tmpdir=/run/user/$(id -u));echo -n $tempdir',
shell=True).decode('utf-8')
rds_log_path = subprocess.check_output(
'tempfile=$(mktemp -t "rds.XXXXXXXX" --tmpdir='
+ temp_directory + ');echo -n $tempfile',
shell=True).decode('utf-8')
if start_server:
subprocess.Popen(rtl_fm_streamer_command)
global play_string
if use_rds:
play_string = play_string.replace('rds_log_path', rds_log_path)
root = tk.Tk()
player_app = PlayerApp(
frequencies, current_frequency,
extra_args={'temp_dir': temp_directory, 'play_str': play_string,
'vol_down_cmd': volume_down_command,
'vol_up_cmd': volume_up_command,
'hst': host, 'api_prt': api_port, 'use_srv': use_server})
player_gui = PlayerGUI(
root, player_app, stations,
extra_args={'freq_list': frequencies, 'bg_color': background_color,
'fnt_color': font_color, 'btn_color': button_color,
'ico_path': icon_path, 'rds_log': rds_log_path})
player_app.set_player_gui(player_gui)
player_app.tune()
cpu_info = CPUInfo(player_gui.get_cpu_text_label())
cpu_info.start()
root.mainloop()
if __name__ == "__main__":