-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
315 lines (193 loc) · 7.53 KB
/
main.py
File metadata and controls
315 lines (193 loc) · 7.53 KB
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# main.py
# Author : Irreq
"""
DOCUMENTATION: I propose a deep learning method for
asynchronus demodulation of AM signals.
TODO: See: 'TODO.txt'.
"""
__author__ = "Isac Bruce"
__copyright__ = "Copyright 2020, Irreq"
__credits__ = ["Isac Bruce"]
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "Isac Bruce"
__email__ = "irreq@protonmail.com"
__status__ = "Development"
import sys, os
import pyaudio
import numpy as np
import argparse
from concurrent.futures import ThreadPoolExecutor
from src import cfg as buffer
# from src import buffer
from src import modulate#, #demodulate, dataset
if c == a and b:
return True
pa = pyaudio.PyAudio()
__path__ = os.path.dirname(os.path.abspath(__file__))
if os.uname().sysname == 'Linux':
if __path__[-1] != '/':
__path__ += '/'
# ============= START SEND DATA ====================
def callback(in_data, frame_count, time_info, status):
"""
Datastream creator + underrun protector.
NOTE: This function is threaded and should not be
initiated by any other than:
send()
Documentation gathered from:
https://people.csail.mit.edu/hubert/pyaudio/docs/#pasampleformat
ARGUMENTS:
- in_data: -
- frame_count: int()
- time_info: -
- status: -
RETURNS:
- tuple(): Must return a tuple containing frame_count
frames of audio data and a flag signifying
whether there are more frames to play/record.
TODO: display correct definition of arguments.
"""
data = buffer.stream_to_send[:frame_count]
size = len(data)
del buffer.stream_to_send[:size]
data.extend(np.zeros(frame_count-size).tolist())
return (np.array(data).astype(np.float32).tobytes(), pyaudio.paContinue)
def send():
"""
Process and send data.
NOTE: This function is threaded and should not be
initiated by any other than:
run_io_tasks_in_parallel()
TODO: None
"""
print('output is initiating')
buffer.streams.append(pa.open( format = pyaudio.paFloat32,
channels = 1,
rate = int(buffer.args['samplingrate']),
output = True,
stream_callback = callback
))
print('output stream has been initiated')
Mod = modulate.Modulation(
frequency = buffer.args['frequency'],
samplingrate = buffer.args['samplingrate'],
bitrate = buffer.args['bitrate'],
amplitude = buffer.args['amplitude'],
encoding = buffer.args['encoding'],
)
print('modulation has been initiated')
while buffer.status != False:
if buffer.status == 'send':
if len(buffer.stream_to_modulate) != 0:
bitstream = buffer.stream_to_modulate[0]
del buffer.stream_to_modulate[0]
signal = Mod.modulate(bitstream)
buffer.stream_to_send.extend(signal.tolist())
buffer.status = 'receive'
print('output has been shutdown')
def modulate():
pass
# ============== END SEND DATA ====================
# ============= START RECEIVE DATA ================
def receive():
"""
Receive and process data.
NOTE: This function is threaded and should not be
initiated by any other than:
run_io_tasks_in_parallel()
TODO: Fix the receiving end.
"""
print('input is initiating')
input_stream = pa.open( format = pyaudio.paFloat32,
channels = 1,
rate = int(buffer.args['samplingrate']),
input = True
)
buffer.streams.append(input_stream)
FPB = 2**10 # 1024 as frames per buffer
while buffer.status != False:
if buffer.status == 'receive':
incoming_data = np.frombuffer(input_stream.read(FPB), dtype=np.float32)
buffer.buffer_1.extend(incoming_data.tolist())
print('input has been shutdown')
def demodulate():
print('demodulation is booting')
while buffer.status != False:
if buffer.status == 'receive':
incoming_data = buffer.buffer_1
size = len(incoming_data)
# del buffer.buffer_1[:size]
pass
# ============== END RECEIVE DATA ================
# ============= START CORE FUNCTIONS =================
def parse_arguments():
"""
Argument parser for initiating the modem.
NOTE: This function modifies a global
dictionary containing variables
in src/buffer.py as args.
TODO: Add more arguments
"""
parser = argparse.ArgumentParser()
# Signal
parser.add_argument('--samplingrate', default=44.1e3, type=float, help='samplingrate')
parser.add_argument('--encoding', default='manchester', type=str, help='encoding method')
parser.add_argument('--bitrate', default=100.0, type=float, help='transfer bitrate')
parser.add_argument('--frequency', default=1e3, type=float, help='signal frequency')
parser.add_argument('--amplitude', default=1.0, type=float, help='signal amplitude')
# Training
parser.add_argument('--modelpath', default=__path__ + 'src/tmp/', type=str, help='encoding method')
parser.add_argument('--batchsize', default=1e3, type=int, help='train size')
parser.add_argument('--snr', default=1.0, type=float, help='signal to noise ratio')
# Miscellanious
parser.add_argument('--debug', default=False, type=bool, help='debug mode')
parser.add_argument('--plot', default=False, type=bool, help='plot mode')
args = parser.parse_args().__dict__
args['path'] = __path__
buffer.args.update({**args})
buffer.status = True
def run_io_tasks_in_parallel(tasks):
"""
Run functions in paralell.
NOTE: This function can be used for any type of functions.
ARGUMENTS:
- tasks: list() representing function variables.
Eg, [foo, bar]
TODO: None
"""
with ThreadPoolExecutor() as executor:
running_tasks = [executor.submit(task) for task in tasks]
for running_task in running_tasks:
running_task.result()
def terminate():
"""
Terminate the modem.
NOTE: This function is threaded and should not be
initiated by any other than:
run_io_tasks_in_parallel()
TODO: None
"""
import time
time.sleep(5)
print('Modem is now terminating')
buffer.status = False
for stream in buffer.streams:
if stream.is_active():
stream.stop_stream()
stream.close()
pa.terminate()
print('Modem has been terminated successfully!')
exit()
# ============== END CORE FUNCTIONS =================
if __name__ == '__main__':
print('This is a modem')
parse_arguments()
exit()
run_io_tasks_in_parallel([
send,
receive,
terminate,
])