SHARE
TWEET

GnuRadio + Flask - blocks.file_source()

furas Aug 22nd, 2019 (edited) 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # https://stackoverflow.com/questions/57599127/runtimeerror-cant-open-file
  2. # date: 2019.08.22
  3.  
  4. from __future__ import print_function
  5. from gnuradio import analog
  6. from gnuradio import audio
  7. from gnuradio import blocks
  8. from gnuradio import eng_notation
  9. from gnuradio import gr
  10. from gnuradio.eng_option import eng_option
  11. from gnuradio.filter import firdes
  12. from optparse import OptionParser
  13.  
  14.  
  15. class TopBlock22(gr.top_block):
  16.  
  17.     def __init__(self, sample_rate=32000, amplitude=0, frequency=0):
  18.  
  19.         gr.top_block.__init__(self, "Top Block 22")
  20.         ##################################################
  21.         # Variables
  22.         ##################################################
  23.         self.sample_rate = sample_rate
  24.         print('[TopBlock22] __init__: sample_rate:', self.sample_rate)
  25.  
  26.         self.amplitude = amplitude
  27.         print('[TopBlock22] __init__: amplitude:', self.amplitude)
  28.  
  29.         self.frequency = frequency
  30.         print('[TopBlock22] __init__: frequency:', self.frequency)
  31.  
  32.         ##################################################
  33.         # Blocks
  34.         ##################################################
  35.         self.blocks_add_xx = blocks.add_vff(1)
  36.         self.audio_sink = audio.sink(32000, '', True)
  37.         self.analog_sig_source_x_1 = analog.sig_source_f(sample_rate, analog.GR_COS_WAVE, 440,  amplitude, 0)
  38.         self.analog_sig_source_x_0 = analog.sig_source_f(sample_rate, analog.GR_COS_WAVE, 350, amplitude, 0)
  39.         self.analog_noise_source_x_0 = analog.noise_source_f(analog.GR_GAUSSIAN,  amplitude, -42)
  40.         ##################################################
  41.         # Connections
  42.         ##################################################
  43.         self.connect((self.analog_noise_source_x_0, 0), (self.blocks_add_xx, 2))
  44.         self.connect((self.analog_sig_source_x_0, 0), (self.blocks_add_xx, 0))
  45.         self.connect((self.analog_sig_source_x_1, 0), (self.blocks_add_xx, 1))
  46.         self.connect((self.blocks_add_xx, 0), (self.audio_sink, 0))
  47.  
  48.     def getfile(self, filename):
  49.         print('[TopBlock22] getfile: filename:', filename)
  50.        
  51.         # solution for: GNURadio TypeError: in method 'file_source_make', argument 2 of type 'char const *'
  52.         filename = filename.encode('utf-8')
  53.        
  54.         self.blocks_file_source_0 = blocks.file_source(gr.sizeof_float*1, self.file_name, True)
  55.         self.audio_sink = audio.sink(32000, '', True)
  56.  
  57.         ##################################################
  58.         # Connections
  59.         ##################################################
  60.         self.connect((self.blocks_file_source_0, 0), (self.audio_sink, 0))
  61.  
  62.     def change_sample_rate(self, value=None):
  63.         if value is not None:
  64.             self.sample_rate = value
  65.             print('[TopBlock22] change: sample_rate:', value)
  66.             self.analog_sig_source_x_1.set_sampling_freq(value)
  67.             self.analog_sig_source_x_0.set_sampling_freq(value)
  68.  
  69.     def change_amplitude(self, value=None):
  70.         if value is not None:
  71.             value /= 10000.
  72.             self.amplitude = value
  73.             print('[TopBlock22] change: amplitude:', value)
  74.             self.analog_sig_source_x_1.set_amplitude(value)
  75.             self.analog_sig_source_x_0.set_amplitude(value)
  76.             self.analog_noise_source_x_0.set_amplitude(value)
  77.  
  78.     def change_frequency(self, value=None):
  79.         if value is not None:
  80.             self.frequency = value
  81.             print('[TopBlock22] change: frequency:', value)
  82.             self.analog_sig_source_x_0.set_frequency(value)
  83.  
  84.     def change(self, sample_rate=None, amplitude=None, frequency=None):
  85.  
  86.         if sample_rate is not None:
  87.             self.change_sample_rate(sample_rate)
  88.  
  89.         if amplitude is not None:
  90.             self.change_amplitude(amplitude)
  91.  
  92.         if frequency is not None:
  93.             self.change_frequency(frequency)
  94.  
  95.     def turn_off(self):
  96.         self.change(0, 0, 0)
  97.  
  98.  
  99. # -----------------------------------------------------------------------------
  100.  
  101. from flask import Flask, flash, request, redirect, jsonify, render_template_string
  102.  
  103.  
  104. app = Flask(__name__)
  105.  
  106.  
  107. tb = TopBlock22(0, 0, 0)
  108. tb.start()
  109.  
  110.  
  111. @app.route("/")
  112. def index():
  113.     args_filename = request.args.get('filename', '')
  114.  
  115.     #if args_filename:
  116.     #    tb.getfile(filename) # already loaded in `/getfile`
  117.        
  118.     return render_template_string('''<!DOCTYPE html>
  119. <html>
  120. <head>
  121.  <meta charset="utf-8">
  122.  <title>GNURadio Slider Example</title>
  123.  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  124.  <link href="https://cdnjs.cloudflare.com/ajax/libs/roundSlider/1.3.2/roundslider.min.css" rel="stylesheet" />
  125.  <script src="https://cdnjs.cloudflare.com/ajax/libs/roundSlider/1.3.2/roundslider.min.js"></script>
  126.  
  127. <style>
  128. .slider {
  129. position: absolute;
  130. align:center;
  131. }    
  132.  
  133. .row1 {top:100px;}
  134. .row2 {top:450px;}
  135.  
  136. .col1 {left:75px;}
  137. .col2 {left:470px;}
  138. .col3 {left:870px;}
  139. </style>
  140.  
  141. </head>
  142.  
  143. <body>
  144.  
  145. <!-- Previous filename: {{ filename }} -->
  146. <form action="getfile" method="POST" enctype="multipart/form-data">
  147.    Project file path: <input type="file" name="file"><br>
  148.    <input type="submit" value="Submit">
  149. </form>
  150.  
  151. <div id="slider1" class='slider row1 col1'></div>
  152. <!--  <p>Sample Rate Slider</p> -->
  153.  
  154. <div id="slider2" class='slider row1 col2'></div>
  155. <!--  <p>Amplitude Slider2</p> -->
  156.  
  157. <div id="slider3" class='slider row1 col3'></div>
  158. <!-- <p>Frequency Slider3</p> -->
  159.  
  160. <div id="slider4" class='slider row2 col1'></div>
  161. <!-- <p>Slider4</p>  -->
  162.  
  163. <div id="slider5" class='slider row2 col2'></div>
  164. <!-- <p>Slider5</p>  -->
  165.  
  166. <div id="slider6" class='slider row2 col3'></div>
  167. <!-- <p>Slider6</p>  -->
  168.  
  169. <button id="turn_off_button">TURN OFF</button>
  170.  
  171. <script>
  172.  
  173.  // create sliders
  174.  
  175.  $("#slider1").roundSlider({
  176.    radius: 150,
  177.    min: 0,
  178.    max: 1000000,
  179.    value: 0, // default value at start
  180.    //change: function(event) { $.getJSON('/valueofslider', {slide1_val: event.value}); }
  181.    change: function(event) { $.getJSON('/set_sample_rate/' + event.value); }
  182.  });
  183.  
  184.  $("#slider2").roundSlider({
  185.    radius: 150,
  186.    min: 0,
  187.    max: 1000000,
  188.    value: 0, // default value at start
  189.    //change: function(event) { $.getJSON('/valueofslider', {slide2_val: event.value}); }
  190.    change: function(event) { $.getJSON('/set_amplitude/' + event.value); }
  191.  });
  192.  
  193.  $("#slider3").roundSlider({
  194.    radius: 150,
  195.    min: 0,
  196.    max: 10000000000,
  197.    value: 0, // default value at start
  198.    //change: function(event) { $.getJSON('/valueofslider', {slide3_val: event.value}); }
  199.    change: function(event) { $.getJSON('/set_frequency/' + event.value); }
  200.  });
  201.  
  202.  $("#slider4").roundSlider({
  203.    radius: 150,
  204.    min: 0,
  205.    max: 10000000000,
  206.    value: 0, // default value at start
  207.    change: function(event) { $.getJSON('/valueofslider', {slide4_val: event.value}); }
  208.  });
  209.  
  210.  $("#slider5").roundSlider({
  211.    radius: 150,
  212.    min: 0,
  213.    max: 10000000000,
  214.    value: 0, // default value at start
  215.    change: function(event) { $.getJSON('/valueofslider', {slide5_val: event.value}); }
  216.  });
  217.  
  218.  $("#slider6").roundSlider({
  219.    radius: 150,
  220.    min: 0,
  221.    max: 10000000000,
  222.    value: 0, // default value at start
  223.    change: function (event) { $.getJSON('/valueofslider', {slide6_val: event.value}); }
  224.  });
  225.  
  226.  $("#turn_off_button").click(function(){
  227.      // set sliders
  228.      $("#slider1").data("roundSlider").setValue(0);
  229.      $("#slider2").data("roundSlider").setValue(0);
  230.      $("#slider3").data("roundSlider").setValue(0);
  231.  
  232.      // send to server
  233.      $.getJSON('/valueofslider', {
  234.        slide1_val: 0,
  235.        slide2_val: 0,
  236.        slide3_val: 0,
  237.      });
  238.  });
  239.  
  240. </script>
  241.  
  242. </body>
  243. </html>''', filename=args_filename)
  244.  
  245.  
  246. @app.route('/getfile', methods=['GET','POST'])
  247. def getfile():
  248.     #print('[/getfile] args:', request.args)
  249.     #print('[/getfile] form:', request.form)
  250.     #print('[/getfile] files:', request.files)
  251.    
  252.     result = request.files.get('file')
  253.     print('[/getfile] result:', result.filename)
  254.  
  255.     if result:
  256.         # save on disk
  257.         result.save(result.filename) # TODO: save with unique name which couldn't overwrite file with passwords
  258.  
  259.         # load it from disk
  260.         tb.getfile(result.filename)
  261.  
  262.         # go back to main page with filename
  263.         #return redirect('/?filename={}'.format(result.filename))
  264.  
  265.     return redirect('/')
  266.  
  267. @app.route('/off')
  268. def off():
  269.     """Turn off sound."""
  270.     tb.turn_off()
  271.     #return jsonify({'val': 0})
  272.     return 'off'
  273.  
  274. @app.route('/set_sample_rate/<int:value>')
  275. def set_sample_rate(value):
  276.     #sound(sample_rate=value)
  277.     tb.change_sample_rate(value)
  278.     #return jsonify({'sample_rate': value})
  279.     return str(value)
  280.  
  281. @app.route('/set_amplitude/<int:value>')
  282. def set_amplitude(value):
  283.     #sound(amplitude=value)
  284.     tb.change_amplitude(value)
  285.     #return jsonify({'amplitude': value})
  286.     return str(value)
  287.  
  288. @app.route('/set_frequency/<int:value>')
  289. def set_frequency(value):
  290.     #sound(frequency=value)
  291.     tb.change_frequency(value)
  292.     #return jsonify({'frequency': value})
  293.     return str(value)
  294.  
  295. @app.route('/valueofslider')
  296. def slide():
  297.     sample_rate = request.args.get('slide1_val', None)
  298.     amplitude   = request.args.get('slide2_val', None)
  299.     frequency   = request.args.get('slide3_val', None)
  300.  
  301.     sound(
  302.         sample_rate=sample_rate,
  303.         amplitude=amplitude,
  304.         frequency=frequency,
  305.     )
  306.  
  307.     return 'sample_rate: {}, amplitude: {}, frequency : {}'.format(sample_rate, amplitude, frequency )
  308.  
  309. def sound(sample_rate=None, amplitude=None, frequency=None):
  310.     """version which uses `change()`"""
  311.  
  312.     if sample_rate is not None:
  313.         sample_rate = int(sample_rate)
  314.         tb.change_sample_rate(sample_rate)
  315.  
  316.     if amplitude is not None:
  317.         amplitude = int(amplitude)
  318.         tb.change_amplitude(amplitude)
  319.  
  320.     if frequency is not None:
  321.         frequency = int(frequency )
  322.         tb.change_frequency(frequency )
  323.  
  324.     print('[sound] sample_rate:', sample_rate)
  325.     print('[sound] amplitude:', amplitude)
  326.     print('[sound] frequency:', frequency)
  327.  
  328.  
  329. if __name__ == '__main__':
  330.     app.run(host='0.0.0.0', debug=True)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top