forked from espressif/esp-adf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
77 lines (65 loc) · 2.83 KB
/
server.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
import os, datetime, sys, urlparse
import SimpleHTTPServer, BaseHTTPServer
import wave
PORT = 8000
HOST = '0.0.0.0'
class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def _set_headers(self, length):
self.send_response(200)
if length > 0:
self.send_header('Content-length', str(length))
self.end_headers()
def _get_chunk_size(self):
data = self.rfile.read(2)
while data[-2:] != b"\r\n":
data += self.rfile.read(1)
return int(data[:-2], 16)
def _get_chunk_data(self, chunk_size):
data = self.rfile.read(chunk_size)
self.rfile.read(2)
return data
def _write_wav(self, data, rates, bits, ch):
t = datetime.datetime.utcnow()
time = t.strftime('%Y%m%dT%H%M%SZ')
filename = str.format('{}_{}_{}_{}.wav', time, rates, bits, ch)
wavfile = wave.open(filename, 'wb')
wavfile.setparams((ch, bits/8, rates, 0, 'NONE', 'NONE'))
wavfile.writeframes(bytearray(data))
wavfile.close()
return filename
def do_POST(self):
urlparts = urlparse.urlparse(self.path)
request_file_path = urlparts.path.strip('/')
total_bytes = 0
sample_rates = 0
bits = 0
channel = 0
if (request_file_path == 'upload'
and self.headers.get('Transfer-Encoding', '').lower() == 'chunked'):
data = []
sample_rates = self.headers.get('x-audio-sample-rates', '').lower()
bits = self.headers.get('x-audio-bits', '').lower()
channel = self.headers.get('x-audio-channel', '').lower()
sample_rates = self.headers.get('x-audio-sample-rates', '').lower()
print("Audio information, sample rates: {}, bits: {}, channel(s): {}".format(sample_rates, bits, channel))
# https://stackoverflow.com/questions/24500752/how-can-i-read-exactly-one-response-chunk-with-pythons-http-client
while True:
chunk_size = self._get_chunk_size()
total_bytes += chunk_size
print("Total bytes received: {}".format(total_bytes))
sys.stdout.write("\033[F")
if (chunk_size == 0):
break
else:
chunk_data = self._get_chunk_data(chunk_size)
data += chunk_data
filename = self._write_wav(data, int(sample_rates), int(bits), int(channel))
body = 'File {} was written, size {}'.format(filename, total_bytes)
self._set_headers(len(body))
self.wfile.write(body)
self.wfile.close()
else:
return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
httpd = BaseHTTPServer.HTTPServer((HOST, PORT), Handler)
print("Serving HTTP on {} port {}".format(HOST, PORT));
httpd.serve_forever()