-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathft8.py
1615 lines (1321 loc) · 59.7 KB
/
ft8.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
#
# ft8.py - A Python module for working with FT8 signals
#
# Copyright (C) 2019 James Kelly, VK3JPK
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Based on protocols and algorithms from WSJT-X, Copyright (C) 2001-2019 Joe Taylor, K1JT
# See https://physics.princeton.edu/pulsar/k1jt/wsjtx.html for further information on WSJT-X
import numpy as np
import scipy.signal
tr_period = 15
start_delay = 0.5
baud_rate = 12000 / 1920
freq_shift = baud_rate
tone_order = 3
tone_count = 1 << tone_order
gaussian_bandwidth = 2.0
msg_bits = 77
# CRC polynomial from WSJT-X lib/crc14.cpp
crc_bits = 14
crc_padded_bits = 96
crc_polynomial = 0x2757
# LDPC generator matrix from WSJT-X lib/ft8/ldpc_174_91_c_generator.f90
generator_hex_strings = [
"8329ce11bf31eaf509f27fc",
"761c264e25c259335493132",
"dc265902fb277c6410a1bdc",
"1b3f417858cd2dd33ec7f62",
"09fda4fee04195fd034783a",
"077cccc11b8873ed5c3d48a",
"29b62afe3ca036f4fe1a9da",
"6054faf5f35d96d3b0c8c3e",
"e20798e4310eed27884ae90",
"775c9c08e80e26ddae56318",
"b0b811028c2bf997213487c",
"18a0c9231fc60adf5c5ea32",
"76471e8302a0721e01b12b8",
"ffbccb80ca8341fafb47b2e",
"66a72a158f9325a2bf67170",
"c4243689fe85b1c51363a18",
"0dff739414d1a1b34b1c270",
"15b48830636c8b99894972e",
"29a89c0d3de81d665489b0e",
"4f126f37fa51cbe61bd6b94",
"99c47239d0d97d3c84e0940",
"1919b75119765621bb4f1e8",
"09db12d731faee0b86df6b8",
"488fc33df43fbdeea4eafb4",
"827423ee40b675f756eb5fe",
"abe197c484cb74757144a9a",
"2b500e4bc0ec5a6d2bdbdd0",
"c474aa53d70218761669360",
"8eba1a13db3390bd6718cec",
"753844673a27782cc42012e",
"06ff83a145c37035a5c1268",
"3b37417858cc2dd33ec3f62",
"9a4a5a28ee17ca9c324842c",
"bc29f465309c977e89610a4",
"2663ae6ddf8b5ce2bb29488",
"46f231efe457034c1814418",
"3fb2ce85abe9b0c72e06fbe",
"de87481f282c153971a0a2e",
"fcd7ccf23c69fa99bba1412",
"f0261447e9490ca8e474cec",
"4410115818196f95cdd7012",
"088fc31df4bfbde2a4eafb4",
"b8fef1b6307729fb0a078c0",
"5afea7acccb77bbc9d99a90",
"49a7016ac653f65ecdc9076",
"1944d085be4e7da8d6cc7d0",
"251f62adc4032f0ee714002",
"56471f8702a0721e00b12b8",
"2b8e4923f2dd51e2d537fa0",
"6b550a40a66f4755de95c26",
"a18ad28d4e27fe92a4f6c84",
"10c2e586388cb82a3d80758",
"ef34a41817ee02133db2eb0",
"7e9c0c54325a9c15836e000",
"3693e572d1fde4cdf079e86",
"bfb2cec5abe1b0c72e07fbe",
"7ee18230c583cccc57d4b08",
"a066cb2fedafc9f52664126",
"bb23725abc47cc5f4cc4cd2",
"ded9dba3bee40c59b5609b4",
"d9a7016ac653e6decdc9036",
"9ad46aed5f707f280ab5fc4",
"e5921c77822587316d7d3c2",
"4f14da8242a8b86dca73352",
"8b8b507ad467d4441df770e",
"22831c9cf1169467ad04b68",
"213b838fe2ae54c38ee7180",
"5d926b6dd71f085181a4e12",
"66ab79d4b29ee6e69509e56",
"958148682d748a38dd68baa",
"b8ce020cf069c32a723ab14",
"f4331d6d461607e95752746",
"6da23ba424b9596133cf9c8",
"a636bcbc7b30c5fbeae67fe",
"5cb0d86a07df654a9089a20",
"f11f106848780fc9ecdd80a",
"1fbb5364fb8d2c9d730d5ba",
"fcb86bc70a50c9d02a5d034",
"a534433029eac15f322e34c",
"c989d9c7c3d3b8c55d75130",
"7bb38b2f0186d46643ae962",
"2644ebadeb44b9467d1f42c",
"608cc857594bfbb55d69600" ]
generator_matrix = []
for hex_string in generator_hex_strings:
generator_matrix.append(int(hex_string, base=16) >> 1)
ldpc_parity_bits = len(generator_matrix)
encoded_bits = msg_bits + crc_bits + ldpc_parity_bits
# LDPC parity check equations from WSJT-X lib/ft8/ldpc_174_91_c_reordered_parity.f90
# Each row in the matrix corresponds to a bit position in the LDPC codeword
# There are 174 rows corresponding to the 174 bits in the LDPC codeword
# The entries in each row are the parity check equations that include the bit
bit_terms = np.array([16, 45, 73,
25, 51, 62,
33, 58, 78,
1, 44, 45,
2, 7, 61,
3, 6, 54,
4, 35, 48,
5, 13, 21,
8, 56, 79,
9, 64, 69,
10, 19, 66,
11, 36, 60,
12, 37, 58,
14, 32, 43,
15, 63, 80,
17, 28, 77,
18, 74, 83,
22, 53, 81,
23, 30, 34,
24, 31, 40,
26, 41, 76,
27, 57, 70,
29, 49, 65,
3, 38, 78,
5, 39, 82,
46, 50, 73,
51, 52, 74,
55, 71, 72,
44, 67, 72,
43, 68, 78,
1, 32, 59,
2, 6, 71,
4, 16, 54,
7, 65, 67,
8, 30, 42,
9, 22, 31,
10, 18, 76,
11, 23, 82,
12, 28, 61,
13, 52, 79,
14, 50, 51,
15, 81, 83,
17, 29, 60,
19, 33, 64,
20, 26, 73,
21, 34, 40,
24, 27, 77,
25, 55, 58,
35, 53, 66,
36, 48, 68,
37, 46, 75,
38, 45, 47,
39, 57, 69,
41, 56, 62,
20, 49, 53,
46, 52, 63,
45, 70, 75,
27, 35, 80,
1, 15, 30,
2, 68, 80,
3, 36, 51,
4, 28, 51,
5, 31, 56,
6, 20, 37,
7, 40, 82,
8, 60, 69,
9, 10, 49,
11, 44, 57,
12, 39, 59,
13, 24, 55,
14, 21, 65,
16, 71, 78,
17, 30, 76,
18, 25, 80,
19, 61, 83,
22, 38, 77,
23, 41, 50,
7, 26, 58,
29, 32, 81,
33, 40, 73,
18, 34, 48,
13, 42, 64,
5, 26, 43,
47, 69, 72,
54, 55, 70,
45, 62, 68,
10, 63, 67,
14, 66, 72,
22, 60, 74,
35, 39, 79,
1, 46, 64,
1, 24, 66,
2, 5, 70,
3, 31, 65,
4, 49, 58,
1, 4, 5,
6, 60, 67,
7, 32, 75,
8, 48, 82,
9, 35, 41,
10, 39, 62,
11, 14, 61,
12, 71, 74,
13, 23, 78,
11, 35, 55,
15, 16, 79,
7, 9, 16,
17, 54, 63,
18, 50, 57,
19, 30, 47,
20, 64, 80,
21, 28, 69,
22, 25, 43,
13, 22, 37,
2, 47, 51,
23, 54, 74,
26, 34, 72,
27, 36, 37,
21, 36, 63,
29, 40, 44,
19, 26, 57,
3, 46, 82,
14, 15, 58,
33, 52, 53,
30, 43, 52,
6, 9, 52,
27, 33, 65,
25, 69, 73,
38, 55, 83,
20, 39, 77,
18, 29, 56,
32, 48, 71,
42, 51, 59,
28, 44, 79,
34, 60, 62,
31, 45, 61,
46, 68, 77,
6, 24, 76,
8, 10, 78,
40, 41, 70,
17, 50, 53,
42, 66, 68,
4, 22, 72,
36, 64, 81,
13, 29, 47,
2, 8, 81,
56, 67, 73,
5, 38, 50,
12, 38, 64,
59, 72, 80,
3, 26, 79,
45, 76, 81,
1, 65, 74,
7, 18, 77,
11, 56, 59,
14, 39, 54,
16, 37, 66,
10, 28, 55,
15, 60, 70,
17, 25, 82,
20, 30, 31,
12, 67, 68,
23, 75, 80,
27, 32, 62,
24, 69, 75,
19, 21, 71,
34, 53, 61,
35, 46, 47,
33, 59, 76,
40, 43, 83,
41, 42, 63,
49, 75, 83,
20, 44, 48,
42, 49, 57]).reshape(encoded_bits, 3)
bit_terms -= 1 # Convert from Fortran to Python indexing
# We need the parity check equations in various forms.
# This function calculates these forms from the cannonical
# representation provided by the bit_terms matrix.
# The check_terms form of the parity equations has one row per
# parity equation with entries in that row specifying the bit
# positions that are part of the corresponding parity check equation.
# The flat versions of bit_terms and check_terms allow numpy to
# be used instead of Python loops in some algorithms.
def _build_parity_equations():
check_terms = []
check_flat_terms = []
for i in range(ldpc_parity_bits):
check_terms.append([])
check_flat_terms.append([])
for i, row in enumerate(bit_terms):
for j, t in enumerate(row):
check_terms[t].append(i)
check_flat_terms[t].append(i * 3 + j)
bit_flat_terms = []
for i in range(encoded_bits):
bit_flat_terms.append([])
for i, row in enumerate(check_terms):
for j, t in enumerate(row):
bit_flat_terms[t].append(i * 7 + j)
if j == 5:
check_terms[i].append(-1)
check_flat_terms[i].append(-1)
return np.array(check_terms), np.array(check_flat_terms), np.array(bit_flat_terms)
check_terms, check_flat_terms, bit_flat_terms = _build_parity_equations()
adjusted_check_terms = check_terms + 1
adjusted_check_flat_terms = check_flat_terms + 3
del _build_parity_equations
encoded_bits = msg_bits + crc_bits + ldpc_parity_bits
encoded_symbols = encoded_bits // tone_order
# Gray map and Costas array from WSJT-X lib/ft8/genft8.f90
gray_map = [0, 1, 3, 2, 5, 6, 4, 7]
costas = [3, 1, 4, 0, 6, 5, 2]
costas_offsets = [0, 36, 72]
costas_order = len(costas)
costas_symbols = costas_order * len(costas_offsets)
symbol_offsets = (list(range(costas_order, costas_offsets[1])) +
list(range(costas_offsets[1] + costas_order, costas_offsets[2])))
assert encoded_symbols == len(symbol_offsets)
total_symbols = encoded_symbols + costas_symbols
class Callsign:
"""Callsign management"""
# Character sets for encoding callsigns
full_charset = ' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ/'
charset_1 = full_charset[:-1]
charset_2 = full_charset[1:-1]
charset_3 = full_charset[1:11]
charset_456 = full_charset[0] + full_charset[11:-1]
charsets = [charset_1, charset_2, charset_3, charset_456, charset_456, charset_456]
# Values for different types of callsigns
max_std_calls = 1
for charset in charsets:
max_std_calls *= len(charset)
max_non_std_calls = 1 << 22
max_tokens = (1 << 28) - max_std_calls - max_non_std_calls
# Tokens
tokens = ['DE', 'QRZ', 'CQ']
# Hash table
hash_table = {}
hash_table[10] = {}
hash_table[12] = {}
hash_table[22] = {}
# Dictionary of all callsigns
all_calls = {}
def __init__(self, call):
"""Constructor for Callsign class
Raises a ValueError exception if call parameter is not a valid token or callsign
"""
self.call = call
# Check for token
self.pack28 = Callsign._token_pack(call)
self.token = self.pack28 != None
if self.token:
self.hash = (None, None, None)
self.standard = False
return
# Not a token so we assume it is a callsign
# Check callsign is a single word
words = call.split()
if (len(words) > 1):
raise ValueError('Callsign contains spaces')
# Check if we have a standard callsign
self.pack28 = Callsign._standard_pack(call)
self.standard = self.pack28 != None
# Check if non-standard callsign is valid
if (not self.standard):
l = len(call)
if l > 11:
raise ValueError('Callsign more than 10 characters long')
elif not all(c in Callsign.full_charset for c in call):
raise ValueError('Callsign contains invalid characters')
# At this point we have a valid callsign so calculate hash code
i = 0
for c in call.ljust(11):
i = i * len(Callsign.full_charset) + Callsign.full_charset.index(c)
hash64 = (i * 47055833459) & (2**64 - 1)
# Calculate hash codes of various lengths and update tables
hash22 = hash64 >> 42
hash12 = hash64 >> 52
hash10 = hash64 >> 54
self.hash = (hash10, hash12, hash22)
Callsign.hash_table[10][hash10] = self
Callsign.hash_table[12][hash12] = self
Callsign.hash_table[22][hash22] = self
# Update 28 bit packing for non-standard callsigns now we have a hash code
if not self.standard:
self.pack28 = hash22 + Callsign.max_tokens
# Add callsign to callsign dictionary
Callsign.all_calls[call] = self
return
def __str__(self):
"""Returns callsign as a string"""
if (not self.standard) and (not self.token):
# Non-standard hashed callsign
return '<' + self.call + '>'
else:
# Token or standard callsign
return self.call
def isToken(self):
"""Returns true if callsign is a token"""
return self.token
def isStandard(self):
"""Returns true if callsign is a non-hashed standard callsign"""
return self.standard
@classmethod
def getHash(cls, code, length=22):
"""Fetch callsign corresponding to hash code of specified length"""
if code in cls.hash_table[length]:
return cls.hash_table[length][code]
else:
return None
@classmethod
def unpack28(cls, i):
"""Attempt to unpack 28-bit packed callsign"""
# Check for token
if i < cls.max_tokens:
# DE, QRZ, CQ
if i < len(cls.tokens):
return Callsign(cls.tokens[i])
# CQ nnn
elif i < len(cls.tokens) + 1000:
return Callsign('CQ ' + str(i - len(cls.tokens)))
# CQ aaaa
elif i < len(cls.tokens) + 1000 + len(cls.charset_456)**4:
i = i - len(cls.tokens) - 1000
c = []
s = len(cls.charset_456)
for j in range(4):
c.insert(0, cls.charset_456[i % s])
i = i // s
c = "".join(c).strip()
return Callsign('CQ ' + c)
# Unknown token
return None
# Check for hashed non-standard callsign
if i < cls.max_tokens + cls.max_non_std_calls:
hash22 = i - cls.max_tokens
if hash22 in cls.hash_table[22]:
return cls.hash_table[22][hash22]
else:
# Consider unknown callsign instead
return None
# Unpack standard callsign
i = i - cls.max_tokens - cls.max_non_std_calls
c = []
for charset in reversed(cls.charsets):
size = len(charset)
c.insert(0, charset[i % size])
i = i // size
c = ''.join(c).strip()
# Handle special cases
if c[0] == 'Q':
c = '3X' + c[1:]
elif c[:3] == '3D0':
c = '3DA0' + c[3:]
# Check if callsign object already exists for this callsign
if c in cls.all_calls:
return cls.all_calls[c]
else:
return Callsign(c)
@classmethod
def _standard_pack(cls, call):
"""Helper function to pack standard callsigns
Returns a 28 bit packing of the callsign if it is a standard callsign, otherwise None.
"""
# First check for some special cases that would otherwise be non-standard
l = len(call)
# Replace 3DA0... with 3D0... for Swaziland callsigns
if l > 4 and call[:4] == '3DA0':
call = '3D0' + call[4:]
l -= 1
# Replace 3X.... with Q.... for Guinea callsigns
elif l > 2 and call[:2] == '3X' and call[2].isalpha():
call = 'Q' + call[2:]
l -= 1
# Find last digit in callsign
last_digit = None
for i, c in enumerate(call):
if c.isdigit():
last_digit = i
# If last digit is second character of callsign, prepend a space
if last_digit == 1:
call = ' ' + call
l += 1
# Check if callsign can be packed with standard callsign packing method
if l > 6 or l < 3 or not all(c in charset for charset, c in zip(cls.charsets, call)):
return None
# Perform standard callsign packing
i = 0
for charset, c in zip(cls.charsets, call.ljust(len(cls.charsets))):
i = i * len(charset) + charset.index(c)
i = i + cls.max_tokens + (1 << 22)
return i
@classmethod
def _token_pack(cls, token):
"""Helper function to pack tokens
Returns a 28 bit packing of the token if it is a valid token, otherwise None.
"""
words = token.split()
if words[0] not in cls.tokens:
return None
l = len(words)
# DE, QRZ, CQ
if (l == 1):
return cls.tokens.index(token)
if words[0] != 'CQ' or l != 2:
return None
# CQ nnn
if words[1].isdecimal():
v = int(words[1])
if v < 0 or v > 999:
return None
return v + len(cls.tokens)
l = len(words[1])
if l > 4 or not all(c in cls.charset_456 for c in words[1]):
return None
# CQ aaaa
v = 0
for c in words[1].ljust(4):
v = v * len(cls.charset_456) + cls.charset_456.index(c)
return v + len(cls.tokens) + 1000
class Report:
"""Report superclass"""
max_grid_4 = 180*180
max_serial = 4095
types = ['location', 'signal', 'other']
other_reports = ['', 'RRR', 'RR73', '73']
charset_12 = "ABCDEFGHIJKLMNOPQR"
charset_34 = "0123456789"
charset_56 = "abcdefghijklmnopqrstuvwx"
charsets = [charset_12, charset_12, charset_34, charset_34, charset_56, charset_56]
def __init__(self, value):
self.value = value
self.pack5 = None
self.pack12 = None
self.pack15 = None
self.pack25 = None
def __str__(self):
return str(self.value)
def __eq__(self, other):
if isinstance(other, Report):
return self.value == other.value
return False
@classmethod
def unpack15(cls, i):
if i <= cls.max_grid_4:
c = []
for charset in reversed(cls.charsets[:4]):
size = len(charset)
c.insert(0, charset[i % size])
i = i // size
return LocationReport(''.join(c))
i -= cls.max_grid_4
if i <= 4:
return OtherReport(cls.other_reports[i-1])
if i <= 65:
return SignalReport(i - 35)
return None
class LocationReport(Report):
"""Location report"""
def __init__(self, value):
super().__init__(value)
l = len(value)
if not l in [4, 6] or not all(c in charset for charset, c in zip(Report.charsets, value)):
raise ValueError()
i = 0
for charset, c in zip(Report.charsets, value):
i = i * len(charset) + charset.index(c)
if l == 4:
self.pack15 = i
else:
self.pack25 = i
class SignalReport(Report):
"""Signal report"""
def __init__(self, value):
super().__init__(value)
if not isinstance(value, int) or value < -30 or value > 30:
raise ValueError()
self.pack15 = Report.max_grid_4 + 35 + value
self.pack5 = (value + 30) / 2
def __str__(self):
return "{:=+03d}".format(self.value)
class OtherReport(Report):
"""Other report"""
def __init__(self, value):
super().__init__(value)
if not value in Report.other_reports:
raise ValueError()
self.pack15 = Report.max_grid_4 + Report.other_reports.index(value) + 1
class SerialReport(Report):
"""Serial number report"""
def __init__(self, value):
super().__init__(value)
if not isinstance(value, int) or value > Report.max_serial:
raise ValueError()
self.pack12 = value
class RTTYSignal:
"""ARRL RTTY Contest Signal"""
def __init__(self, value):
if value < 529 or value > 599 or (value % 10) != 9:
raise ValueError()
self.value = value
self.pack3 = (self.value - 509) // 10 - 2
def __str__(self):
return str(self.value)
@classmethod
def unpack3(cls, bits):
return cls((bits + 2) * 10 + 509)
class RTTYState:
"""ARRL RTTY Contest State"""
states = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA",
"HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD",
"MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ",
"NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC",
"SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY",
"NB", "NS", "QC", "ON", "MB", "SK", "AB", "BC", "NWT", "NF",
"LB", "NU", "YT", "PEI", "DC"]
state_offset = 8001
def __init__(self, value):
self.value = value
if value.isnumeric() and value < self.state_offset:
self.pack13 = value
elif value in self.states:
self.pack13 = self.state_offset + self.states.index(value)
else:
raise ValueError()
def __str__(self):
if self.pack13 < self.state_offset:
return "{:04d}".format(self.value)
else:
return self.value
@classmethod
def unpack13(cls, bits):
if bits < cls.state_offset:
return cls(bits)
else:
return cls(cls.states[bits - cls.state_offset])
class Message:
class MessageError(Exception):
"""Superclass for errors generated when creating messages"""
class CRCError(MessageError):
"""CRC bits did not match message bits"""
class UnsupportedError(MessageError):
"""Message type or subtype is unsupported"""
def __eq__(self, other):
return str(self) == str(other)
@staticmethod
def _crc(msg, chk):
"""Calculate FT8 CRC."""
# msg is the 77 bit message stored in a Python 3 integer
# chk is a 14 bit CRC stored in a Python 3 integer
# Set chk to zero if calculating CRC or the received CRC to check CRC
# Returns calculated CRC or zero if provided CRC is correct
# Pad msg with 96-77 = 19 zeros to create 96 bit number and add checksum
# Padding must be at least CRC size bits for the CRC algorithm to work
# FT8 designers rounded up padding to make the padded message a whole number of bytes
remainder = (msg << (crc_padded_bits - msg_bits)) | chk
# Mask starts at most significant bit
mask = 1 << (crc_padded_bits - 1)
# Align most significant bit of polynomial with mask
# Note that the specified polynomial does not include the most significant bit
# So we must add the most significant bit before we align the polynomial
shifted_poly = ((1 << crc_bits) | crc_polynomial) << (crc_padded_bits - crc_bits - 1)
# Polynomial long division modulo 2
# We are only interested in the remainder so we don't bother calculating the quotient
for i in range(crc_padded_bits - crc_bits):
if (remainder & mask):
remainder ^= shifted_poly
mask >>= 1
shifted_poly >>= 1
return remainder
def encode(self):
"""Encode message into 79 symbols."""
# Symbols are returned in a Python list of integers
# Applies CRC, LDPC, Gray codes and adds Costas arrays
# Calculate 14-bit CRC and append to the packed message to get
# 77 + 14 = 91 bit packed message with CRC
msg_crc = self.pack77 << 14 | Message._crc(self.pack77, 0)
# Generate 83 bits of parity by multiplying generator matrix by message bits.
# We use the logical AND operator to perform modulo 2 multiplication.
# We then count the set bits to find the sum modulo 2.
# While this is concise it is probably not that efficient
parity = 0
for row in generator_matrix:
parity = parity << 1
parity = parity | (bin(row & msg_crc).count('1') % 2)
# Construct 174 bit codeword by combining 91 bit message and 83 bits of parity
codeword = (msg_crc << 83) | parity
# Split 174 bit codeword into 58 x 3 bit symbols and apply gray code
msg_symbols = []
mask = (1 << 3) - 1
for i in range(174 // 3):
msg_symbols.insert(0, gray_map[codeword & mask])
codeword = codeword >> 3
# Add 3 x 7 symbol Costas arrays to the 58 symbol encoded message to get 79 symbols
symbols = costas + msg_symbols[:encoded_symbols // 2] + costas + msg_symbols[encoded_symbols // 2:] + costas
return symbols
@classmethod
def unpack77(cls, bits):
"""Attempt to unpack message from bits."""
msg_type = bits & 7
if msg_type == 0:
msg_subtype = (bits >> 3) & 7
if msg_subtype == TextMessage.msg_subtype:
return TextMessage.unpack77(bits)
elif msg_subtype == TelemetryMessage.msg_subtype:
return TelemetryMessage.unpack77(bits)
elif msg_type == StandardMessage.msg_type:
return StandardMessage.unpack77(bits)
elif msg_type == EUVHFMessage.msg_type:
return EUVHFMessage.unpack77(bits)
elif msg_type == RTTYMessage.msg_type:
return RTTYMessage.unpack77(bits)
else:
raise cls.UnsupportedError()
@classmethod
def unpack91(cls, bits):
"""Unpack message from bits after checking CRC appended to bits."""
crc = bits & ((1 << crc_bits) - 1)
msg = bits >> crc_bits
if cls._crc(msg, crc):
raise cls.CRCError()
return cls.unpack77(msg)
class TextMessage(Message):
"""Class to represent text messages"""
# Text messages use a limited character set
charset = ' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ+=./?'
charset_size = len(charset)
msg_type = 0
msg_subtype = 0
# Text messages can be up to 13 characters long
max_msg_size = 13
def __init__(self, text):
self.text = text.strip()
if len(text) > TextMessage.max_msg_size or not all(c in TextMessage.charset for c in text):
raise ValueError()
i = 0
for c in self.text:
i *= TextMessage.charset_size
i += TextMessage.charset.index(c)
self.pack77 = (i << 6) | (TextMessage.msg_subtype << 3) | TextMessage.msg_type
def __str__(self):
return 'TextMessage("{}")'.format(self.text)
@classmethod
def unpack77(cls, bits):
"""Unpack text message from bits"""
i = bits >> 6
c = []
for j in range(cls.max_msg_size):
c.insert(0, cls.charset[i % cls.charset_size])
i = i // cls.charset_size
return cls(''.join(c).strip())
class TelemetryMessage(Message):
"""A class to represent telemetry messages"""
msg_type = 0
msg_subtype = 5
def __init__(self, bits):
self.bits = bits
self.pack77 = (bits << 6) | (TelemetryMessage.msg_subtype << 3) | TelemetryMessage.msg_type
def __str__(self):
return "TelemetryMessage({})".format(hex(self.bits))
@classmethod
def unpack77(cls, bits):
"""Unpack telemetry message from bits"""
return cls(bits >> 6)
class StandardMessage(Message):
"""A class to represent standard messages"""
# Standard messages contain 2 callsigns, a report and an optional roger
# Format: 28 bits for first callsign, 1 bit for first callsign rover status
# 28 bits for second callsign, 1 bit for second callsign rover status
# 1 bit for roger, 15 bits for a report and 3 bits for message type
msg_type = 1
field_widths = [28, 1, 28, 1, 1, 15, 3]
def __init__(self, call_1, call_2, report, roger=False, rover_1=False, rover_2=False):
self.call_1 = call_1
self.rover_1 = rover_1
self.call_2 = call_2
self.rover_2 = rover_2
self.roger = roger
self.report = report
self.fields = [self.call_1, self.rover_1, self.call_2, self.rover_2, self.roger, self.report]
field_bits = [call_1.pack28, rover_1, call_2.pack28, rover_2, roger,
report.pack15, self.msg_type]
self.pack77 = 0
for w, f in zip(self.field_widths, field_bits):
self.pack77 = (self.pack77 << w) | int(f)
return
def __str__(self):
if self.msg_type == 1:
r = '/R'
elif self.msg_type == 2:
r = '/P'
s = str(self.call_1)
if self.rover_1:
s += r
s += ' ' + str(self.call_2)
if self.rover_2:
s += r
s += ' '
if self.fields[4]:
s += 'R'
s += str(self.report)
return '{}({})'.format(self.__class__.__name__, s)
@classmethod
def unpack77(cls, bits):
"""Unpack standard message from bits"""
f = []
for w in reversed(cls.field_widths):
f.insert(0, bits & ((1 << w) - 1))
bits >>= w
return cls(Callsign.unpack28(f[0]), Callsign.unpack28(f[2]), Report.unpack15(f[5]),
f[4] != 0, f[1] != 0, f[3] != 0)
class EUVHFMessage(StandardMessage):
"""A class to represent EU VHF Contest messages"""
msg_type = 2
def __init__(self, call_1, call_2, report, roger=False, portable_1=False, portable_2=False):
super().__init__(call_1, call_2, report, roger, portable_1, portable_2)
class RTTYMessage(Message):
"""A class to represent ARRL RTTY contest messages"""
msg_type = 3
field_widths = [1, 28, 28, 1, 3, 13, 3]
def __init__(self, call_1, call_2, roger, signal, state, thank_you=False):
if not isinstance(call_1, Callsign):
raise ValueError()
self.call_1 = call_1
if not isinstance(call_2, Callsign):
raise ValueError()
self.call_2 = call_2
if not isinstance(signal, RTTYSignal):
raise ValueError()