-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchirpchirp.py
230 lines (187 loc) · 4.98 KB
/
chirpchirp.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
#!/usr/bin/env python -u
'''chirpchirp.py - transmit data over audio with chirp modulation
Usage:
python -u chirpchirp.py (tx | rx) <fmin> <fmax> <period> [<volume>]
python chirpchirp.py -h
Options:
-h Print this help.
'''
from __future__ import print_function
import codecs
import functools
import numpy
import os
import pyaudio
try:
import queue
except ImportError:
import Queue as queue
import sys
import termios
__author__ = 'Mansour Moufid'
__email__ = '[email protected]'
__copyright__ = 'Copyright 2018, 2019, Mansour Moufid'
__license__ = 'ISC'
__version__ = '0.2'
__status__ = 'Development'
PCM_DTYPE = numpy.int16
PCM_MAX = 2.0 ** (16 - 1) - 1.0
def setnoncanonical(fd):
assert os.isatty(fd)
attr = termios.tcgetattr(fd)
lflags = attr[3]
lflags &= ~termios.ICANON
attr[3] = lflags
termios.tcsetattr(fd, termios.TCSANOW, attr)
def readbytes(f, tty=None):
while True:
char = f.read(1)
if char == '':
break
byte = ord(char)
if tty and byte == 4:
break
yield byte
def F(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return F(n - 1) + F(n - 2)
def encode(x):
n = 1
while F(n) <= x:
n = n + 1
b = []
r = x
for i in range(n - 1, 1, -1):
if F(i) <= r:
r = r - F(i)
b.append(1)
else:
b.append(0)
return b[::-1] + [1]
def decode(x):
w = 0
for i, b in enumerate(x[:-1]):
w = w + F(i + 2) * b
return w
def tobits(bytes):
for byte in bytes:
for bit in encode(byte):
yield bit
def tobyte(bits):
return decode(bits)
def modxcor(x, y):
m = x.size
n = y.size
x = numpy.copy(x)
y = numpy.copy(y[::-1])
x.resize(m + n)
y.resize(m + n)
X = numpy.fft.rfft(x)
Y = numpy.fft.rfft(y)
Z = X * Y
z = numpy.fft.irfft(Z, n=(m + n))
return z[(n / 2):-(n / 2)]
linspace = functools.partial(
numpy.linspace,
dtype=numpy.float32,
endpoint=False,
)
def chirp(bandwidth, period, samples):
t = linspace(0.0, period, num=samples)
fmin, fmax = bandwidth
k = (fmax - fmin) / period
f = t * k / 2 + fmin
return numpy.sin(2.0 * numpy.pi * f * t)
def mod(zero, one, bit):
data = one if bit == 1 else zero
pcm = PCM_DTYPE(data * PCM_MAX)
frames = pcm.tostring()
return frames
def dem(zero, one, bits, frames, nframes=None, timing=None, status=None):
pcm = numpy.fromstring(frames, dtype=PCM_DTYPE)
data = numpy.float32(pcm) / (PCM_MAX + 1.0)
xc0 = modxcor(data, zero)
xc1 = modxcor(data, one)
k0 = (numpy.max(xc0) - numpy.min(xc0)) / numpy.std(xc0)
k1 = (numpy.max(xc1) - numpy.min(xc1)) / numpy.std(xc1)
if k0 > 2 * k1:
bits.put(0)
if k1 > 2 * k0:
bits.put(1)
return (None, pyaudio.paContinue)
if __name__ == '__main__':
if len(sys.argv) == 2 and sys.argv[1] == '-h':
print(__doc__)
sys.exit(0)
try:
assert sys.argv[1] in ['tx', 'rx']
tx = sys.argv[1] == 'tx'
fmin = int(sys.argv[2])
fmax = int(sys.argv[3])
period = float(sys.argv[4])
try:
amplitude = float(sys.argv[5])
except:
amplitude = 1.0
except:
print(__doc__)
sys.exit(os.EX_USAGE)
sys.stdin = codecs.getreader(sys.stdin.encoding)(sys.stdin)
sys.stdout = codecs.getwriter(sys.stdout.encoding)(sys.stdout)
audio = pyaudio.PyAudio()
if tx:
info = audio.get_default_output_device_info()
else:
info = audio.get_default_input_device_info()
fs = int(info['defaultSampleRate'])
samples = int(fs * period)
audio.open = functools.partial(
audio.open,
channels=1,
format=pyaudio.paInt16,
rate=fs,
)
one = chirp((fmin, fmax), period, samples) * amplitude
zero = one[::-1]
if tx:
stream = audio.open(
frames_per_buffer=2 ** 12,
output=True,
)
if sys.stdin.isatty():
setnoncanonical(sys.stdin.fileno())
tty = os.ctermid()
else:
tty = None
for bit in tobits(readbytes(sys.stdin, tty=tty)):
frames = mod(zero, one, bit)
stream.write(frames)
if tty:
with open(tty, 'w') as f:
f.write('\n')
else:
q = queue.Queue()
stream = audio.open(
frames_per_buffer=one.size,
input=True,
stream_callback=functools.partial(dem, zero, one, q),
)
stream.start_stream()
bits = []
while stream.is_active():
try:
bit = q.get_nowait()
except queue.Empty:
continue
bits.append(bit)
if bits[-2:] == [1, 1]:
byte = tobyte(bits)
sys.stdout.write(unichr(byte))
bits = []
stream.stop_stream()
stream.close()
audio.terminate()