Python Forum
I am having a problem with my Slider
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I am having a problem with my Slider
#1
I am trying to control the frequency sampling rate of my dial_tone python code through a Flask webserver. The audio output still works but when I drag the slider it doesnt affect the audio!


Here is my webserver script:

from flask import Flask
from flask import request
from dial_tone_modified import dial_tone_modified
app = Flask(__name__)

tb = dial_tone_modified()

@app.route("/set_samp_rate")
def set_samp_rate():
  samp_rate = request.args.get("samp_rate")
  print "Received " + str(samp_rate)

@app.route("/")

def web_interface():
  html = open("web_interface.html")
  response = html.read().replace('\n', '')
  html.close()
  return response


tb.start()


def main():

    return "Welcome to my Flask Page!"

if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=8000)
And this is my dial_tone code:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: Dial Tone Modified
# Generated: Mon Jul 15 11:15:28 2019
##################################################


from gnuradio import analog
from gnuradio import audio
from gnuradio import blocks
from gnuradio import eng_notation
from gnuradio import gr
from gnuradio.eng_option import eng_option
from gnuradio.filter import firdes
from optparse import OptionParser



class dial_tone_modified(gr.top_block):

    def __init__(self):
        gr.top_block.__init__(self, "Dial Tone Modified")

        ##################################################
        # Variables
        ##################################################
        self.samp_rate_0 = samp_rate_0 = 32000
        self.samp_rate = samp_rate = 32000

        ##################################################
        # Blocks
        ##################################################
        self.blocks_add_xx = blocks.add_vff(1)
        self.audio_sink = audio.sink(32000, '', True)
        self.analog_sig_source_x_1 = analog.sig_source_f(samp_rate, analog.GR_COS_WAVE, 440, .4, 0)
        self.analog_sig_source_x_0 = analog.sig_source_f(samp_rate, analog.GR_COS_WAVE, 350, .4, 0)
        self.analog_noise_source_x_0 = analog.noise_source_f(analog.GR_GAUSSIAN, 0.005, -42)

        ##################################################
        # Connections
        ##################################################
        self.connect((self.analog_noise_source_x_0, 0), (self.blocks_add_xx, 2))
        self.connect((self.analog_sig_source_x_0, 0), (self.blocks_add_xx, 0))
        self.connect((self.analog_sig_source_x_1, 0), (self.blocks_add_xx, 1))
        self.connect((self.blocks_add_xx, 0), (self.audio_sink, 0))

    def get_samp_rate_0(self, a=32000):
        self.samp_rate_0=a
        return

    def set_samp_rate_0(self, samp_rate_0):
        self.samp_rate_0 = samp_rate_0

    def get_samp_rate(self):
        return self.samp_rate

    def set_samp_rate(self, samp_rate):
        self.samp_rate = samp_rate
        self.analog_sig_source_x_1.set_sampling_freq(self.samp_rate)
        self.analog_sig_source_x_0.set_sampling_freq(self.samp_rate)


def main(top_block_cls=dial_tone_modified, options=None):

    tb = dial_tone_modified()
    tb.start()
    try:
        raw_input('Press Enter to quit: ')
    except EOFError:
        pass
    tb.stop()
    tb.wait()


if __name__ == '__main__':
    main()
And this is my html code:

<!DOCTYPE html>
<html>
<body>

<h1>Web Browser Control</h1>
<p>Drag the slider to display the current value.</p>

<div id="slidecontainer">
  <input type="range" min="0" max="32e3" value="0" id="range1">
  <p>Value: <span id="range1_value"></span></p>
</div>

<script>
var slider = document.getElementById("range1");
var output = document.getElementById("range1_value");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = slider.value;
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    }
  };
  xhttp.open("GET", "http://127.0.0.1:5000/set_samp_rate_0?samp_rate_0=" + slider.value, true);
  xhttp.send();
}

</script>

</body>
</html>
Can any one help me how to solve this problem, please!
Reply
#2
Can show i slider roundSlider that i have used before and coded AJAX for to flask server.
I have not used xhttp in in html,as jQuery with AJAX make this a little simpler.
app.py
from flask import Flask, render_template, jsonify, request, redirect, url_for
from random import randint

app = Flask(__name__)
@app.route('/')
def hex_color():
    return render_template("index.html")

@app.route('/valueofslider')
def slide():
    slide_val = request.args.get('slide_val')
    print(slide_val)
    return slide_val

if __name__ == '__main__':
    app.run(debug=True)
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>jQuery roundSlider - JS Bin</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/roundSlider/1.3.2/roundslider.min.css" rel="stylesheet" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/roundSlider/1.3.2/roundslider.min.js"></script>
</head>
<body>
  <!-- Only html needed   -->
  <div id="slider"></div>
  
  <script>
    var val;
    $("#slider").roundSlider({
      radius: 85,
      sliderType: "min-range",
      change: function () {
        var obj1 = $("#slider").data("roundSlider");
        val = obj1.getValue();
        value: 1
        $.getJSON('/valueofslider', {
          slide_val: val
        });
      }
    });
  </script>
</body>
</html>
Run app.py see that values from slider come live to server.
λ python app.py
 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 148-447-994
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
So slide_val is what you need to integrate in GNU Radio code.
You have pick a project that's not so easy if new to all of this Undecided
Reply
#3
(Jul-23-2019, 02:29 PM)snippsat Wrote: So slide_val is what you need to integrate in GNU Radio code.
You have pick a project that's not so easy if new to all of this Undecided
And thats my problem!! I am really new to these stuff. I spent the last 5 hours trying mimic your codes and apply them to mine but no luck at all. It is getting me crazy! I will keep trying, no other choice. Though thanks a lot to your entry snippsat.
Reply
#4
Here is folder setup.
slider\
|-- app.py
  templates\
    |-- index.html
  static\
    css\
      |-- style.css # can be empty or missing
You have done pip install Flask
In folder:
E:\all_flask\2019\slider
λ ls # or dir in cmd
app.py  static/  templates/

# Check install
E:\all_flask\2019\slider
λ pip install Flask
Requirement already satisfied: Flask in c:\python37\lib\site-packages (1.0.2)
Requirement already satisfied: Werkzeug>=0.14 in c:\python37\lib\site-packages (from Flask) (0.14.1)
Requirement already satisfied: itsdangerous>=0.24 in c:\python37\lib\site-packages (from Flask) (0.24)
Requirement already satisfied: click>=5.1 in c:\python37\lib\site-packages (from Flask) (7.0)
Requirement already satisfied: Jinja2>=2.10 in c:\python37\lib\site-packages (from Flask) (2.10)
Requirement already satisfied: MarkupSafe>=0.23 in c:\python37\lib\site-packages (from Jinja2>=2.10->Flask) (1.0)

# Run app
E:\all_flask\2019\slider
λ python app.py
 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 334-187-997
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Now you see address http://127.0.0.1:5000/ copy to browser.
How it shall look in browser,see that values are live updated when move slider.
[Image: 3qC9Ey.jpg]
Reply
#5
(Jul-23-2019, 06:45 PM)snippsat Wrote: Now you see address http://127.0.0.1:5000/ copy to browser.
OH YEAHHHHH ... Now I got self confidence back :D

[Image: QnRj3G.png]


So, now it should be easy for me to apply it to my project, I hope?
Reply
#6
(Jul-23-2019, 06:45 PM)snippsat Wrote: How
How can I increase the slider value, I want to increase it to more than 100?

(Jul-24-2019, 01:25 PM)Hadad Wrote: How can I increase the slider value, I want to increase it to more than 100?
I found it. I found the below lines of script and helped me determine the value of the slider.

$("#slider").roundSlider(
{
        value:0,
        min: 0,
        max: 100,
        width: 30,
        step: 1,
        sliderType: "min-range",
         change: function (args) {
                console.log(args.value);
            $('#range').html(args.value)
         }        
    }
);

(Jul-23-2019, 02:29 PM)snippsat Wrote: slide_val

I started getting this error when I run my code:

^Cfit-pc@fitpc-fitlet2:~$ python /home/fit-pc/my_flask_app/virtualenv/Slider/top_bloc22.py
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 269-962-008
127.0.0.1 - - [24/Jul/2019 10:24:26] "GET / HTTP/1.1" 200 -
None
127.0.0.1 - - [24/Jul/2019 10:24:30] "GET /valueofslider?slide_val=277 HTTP/1.1" 500 -
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1615, in full_dispatch_request
    return self.finalize_request(rv)
  File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1630, in finalize_request
    response = self.make_response(rv)
  File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1725, in make_response
    raise ValueError('View function did not return a response')
ValueError: View function did not return a response
Once I cancel the process on the Terminal (ctrl + c) my program will start working (which is a simple dial tone)!

This is the html code:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>jQuery roundSlider - JS Bin</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/roundSlider/1.3.2/roundslider.min.css" rel="stylesheet" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/roundSlider/1.3.2/roundslider.min.js"></script>
</head>
<body>
  <!-- Only html needed   -->
  <div id="slider"></div>
   
  <script>
    var val;
    $("#slider").roundSlider({
      radius: 215,
        min: 0,
        max: 40000,

      change: function () {
        var obj1 = $("#slider").data("roundSlider");
        val = obj1.getValue();
        value: 1
        $.getJSON('/valueofslider', {
          slide_val: val
        });
      }
    });
  </script>
</body>
And this is my Python code:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: Top Block 22
# Generated: Tue Jul 23 15:54:16 2019
##################################################


from gnuradio import analog
from gnuradio import audio
from gnuradio import blocks
from gnuradio import eng_notation
from gnuradio import gr
from gnuradio.eng_option import eng_option
from gnuradio.filter import firdes
from optparse import OptionParser
from flask import Flask, render_template, jsonify, request, redirect, url_for
from random import randint
app = Flask(__name__)


class top_block_22(gr.top_block):

    def __init__(self):
        gr.top_block.__init__(self, "Top Block 22")

        ##################################################
        # Variables
        ##################################################
        self.samp_rate = samp_rate = 32000

        ##################################################
        # Blocks
        ##################################################
        self.blocks_add_xx = blocks.add_vff(1)
        self.audio_sink = audio.sink(32000, '', True)
        self.analog_sig_source_x_1 = analog.sig_source_f(samp_rate, analog.GR_COS_WAVE, 440, 0.4, 0)
        self.analog_sig_source_x_0 = analog.sig_source_f(samp_rate, analog.GR_COS_WAVE, 350, 0.4, 0)
        self.analog_noise_source_x_0 = analog.noise_source_f(analog.GR_GAUSSIAN, 0.005, -42)

        ##################################################
        # Connections
        ##################################################
        self.connect((self.analog_noise_source_x_0, 0), (self.blocks_add_xx, 2))
        self.connect((self.analog_sig_source_x_0, 0), (self.blocks_add_xx, 0))
        self.connect((self.analog_sig_source_x_1, 0), (self.blocks_add_xx, 1))
        self.connect((self.blocks_add_xx, 0), (self.audio_sink, 0))


    @app.route('/')
    def hex_color():
            return render_template("index.html")
         
    @app.route('/valueofslider')
    def slide():
            samp_rate = request.args.get('samp_rate')
            print(samp_rate)
            return samp_rate 

def main(top_block_cls=top_block_22, options=None):



    tb = top_block_cls()
    tb.start()
    try:
        raw_input('Press Enter to quit: ')
    except EOFError:
        pass
    tb.stop()
    tb.wait()

if __name__ == '__main__':
    app.run(debug=True)

if __name__ == '__main__':
    main()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Using range slider in flask webpage to use in python KimPet 2 7,528 Jan-23-2021, 11:58 PM
Last Post: snippsat
  reduce volume slider to 0% metulburr 6 3,557 Jun-15-2019, 09:58 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020