Parth1234
Posts: 38
Joined: Mon Mar 12, 2018 3:14 pm

How to add java script code into python program?

Tue Jun 05, 2018 9:44 am

I am using raspbian and PI3 I wrote python program to blink led. and its work. When Led blink I want to blink light bulb on webpage with apache server.
Program

Code: Select all

import time
import RPi.GPIO as GPIO       ## Import GPIO library
GPIO.setmode(GPIO.BOARD)      ## Use board pin numbering
GPIO.setup(22, GPIO.OUT)      ## Setup GPIO Pin 24 to OUT
while True:
	GPIO.output(22,True)  ## Turn on Led
	time.sleep(1)         ## Wait for one second
	GPIO.output(22,False) ## Turn off Led
	time.sleep(1)         ## Wait for one second
I looked this example for GUI https://www.w3schools.com/js/tryit.asp? ... _lightbulb

How to add given java script code in link into python program?

scotty101
Posts: 3185
Joined: Fri Jun 08, 2012 6:03 pm

Re: How to add java script code into python program?

Tue Jun 05, 2018 11:16 am

This is often the difficult part for beginners to get. When you are dealing with webpages there are two computers at work, the host/server and the client/browser.
Your client runs a webbrowser which parses the HTML and other data that it has requested from the server and will run any client side scripting. Javascript is the 'universally' supported client scripting language.
The server runs an HTTP server, like Apache, to deliver data to a web browser on request. It will also deal with any server-side scripting like PHP, Python, Ruby, Node.JS etc etc

Your python program at the moment runs on the server (the raspberry Pi), you need to communicate to the web page the status of the LED to turn on a bulb. The web server can't send data 'unsolicited' to a browser, the browser has to request the data.
This can either be by requesting a new page from the server (A GET/POST request) or a 'background' request conducted by Javascript typically called AJAX. AJAX requests can happen without having to refresh the whole page.

Personally, I'd use python-flask running on your server and then have the javascript on the web browser periodically ask for the status of the LED.

Short answer is that is it more complicated than adding javascript to your python code.. (which isn't possible)
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

ghans
Posts: 7806
Joined: Mon Dec 12, 2011 8:30 pm
Location: Germany

Re: How to add java script code into python program?

Tue Jun 05, 2018 12:35 pm

Use this to create a GUI for your program:
https://github.com/dddomodossola/remi

Your GUI will automatically work in most browsers, remotely.

ghans
• Don't like the board ? Missing features ? Change to the prosilver theme ! You can find it in your settings.
• Don't like to search the forum BEFORE posting 'cos it's useless ? Try googling : yoursearchtermshere site:raspberrypi.org

Parth1234
Posts: 38
Joined: Mon Mar 12, 2018 3:14 pm

Re: How to add java script code into python program?

Tue Jun 05, 2018 1:14 pm

ghans wrote:
Tue Jun 05, 2018 12:35 pm
Use this to create a GUI for your program:
https://github.com/dddomodossola/remi

Your GUI will automatically work in most browsers, remotely.

ghans
thanks ghans I have installed the package as instructed and trying to run the first example:
getting the following error:

[email protected]:~/Downloads/remi-master/examples $ sudo python widgets_overview_app.py
Traceback (most recent call last):
File "widgets_overview_app.py", line 15, in <module>
import remi.gui as gui
ImportError: No module named remi.gui

Parth1234
Posts: 38
Joined: Mon Mar 12, 2018 3:14 pm

Re: How to add java script code into python program?

Tue Jun 05, 2018 1:24 pm

scotty101 wrote:
Tue Jun 05, 2018 11:16 am
This is often the difficult part for beginners to get. When you are dealing with webpages there are two computers at work, the host/server and the client/browser..

Short answer is that is it more complicated than adding javascript to your python code.. (which isn't possible)
Thanks scotty for your detail explanation. yahh I know it's not easy. That's reason I started with small example like creating GUI for LED.
I did searched on internet and I found that we can create GUI with java script. first task I did that I wrote python program to blink led and then I wanted to create GUI so I did the google search and I found one of example that I have posted in my previous post..

I think This example will help to understand basics .once I get the idea that how python and GUI program work together. I can try to make other tasks

B.Goode
Posts: 6544
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: How to add java script code into python program?

Tue Jun 05, 2018 1:30 pm

Parth1234 wrote:
Tue Jun 05, 2018 1:14 pm
ghans wrote:
Tue Jun 05, 2018 12:35 pm
Use this to create a GUI for your program:
https://github.com/dddomodossola/remi

Your GUI will automatically work in most browsers, remotely.

ghans
thanks ghans I have installed the package as instructed and trying to run the first example:
getting the following error:

[email protected]:~/Downloads/remi-master/examples $ sudo python widgets_overview_app.py
Traceback (most recent call last):
File "widgets_overview_app.py", line 15, in <module>
import remi.gui as gui
ImportError: No module named remi.gui

The developer's documentation does not say that sudo is needed to run this script. But that may not be the source of the problem.

That import statement appears at the start of every one of the example scripts. It is so fundamental that I am sure the developer will have tested it..

It indicates that the remi.gui module has not been installed correctly for your python system.


Which of the two suggested options for installing the remi package did you use? Did the process appear to complete without any errors?


Disclaimer: it isn't clear to me how this library will help towards your aim of integration of JavaScript into a python program.

hippy
Posts: 3914
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: How to add java script code into python program?

Tue Jun 05, 2018 2:40 pm

ghans wrote:
Tue Jun 05, 2018 12:35 pm
Use this to create a GUI for your program:
https://github.com/dddomodossola/remi

Your GUI will automatically work in most browsers, remotely.
I had not heard of that so thanks for pointing to it. It installed on my Pi 3B using the "pip install" method. Required sudo to work -

Code: Select all

[email protected]:~/widgets$ sudo pip install git+https://github.com/dddomodossola/remi.git
Collecting git+https://github.com/dddomodossola/remi.git
  Cloning https://github.com/dddomodossola/remi.git to /tmp/pip-OiVgvM-build
Installing collected packages: remi
  Running setup.py install for remi ... done
Successfully installed remi-1.1
No "widgets_overview_app.py" installed but cut and pasted the "A basic application appears like this:" code and that ran just fine.

I could access it from the Pi's desktop using Chromium, and with a bit of twiddling to the start parameters had it accessible over the network.

Code: Select all

[email protected]:~/widgets$ python test.py
remi.server      INFO     Started httpserver http://192.168.0.130:8081/ 

ghans
Posts: 7806
Joined: Mon Dec 12, 2011 8:30 pm
Location: Germany

Re: How to add java script code into python program?

Tue Jun 05, 2018 3:10 pm

Why should a Python beginner learn all about AJAX, Websockets and some (any?) Javascript framework just to make his/her script remote-controllable trough webbroswsers ? I believe remi shows that you don't need all that baggage for simple applications. It just works like a regular GUI widget kit.

ghans
• Don't like the board ? Missing features ? Change to the prosilver theme ! You can find it in your settings.
• Don't like to search the forum BEFORE posting 'cos it's useless ? Try googling : yoursearchtermshere site:raspberrypi.org

Parth1234
Posts: 38
Joined: Mon Mar 12, 2018 3:14 pm

Re: How to add java script code into python program?

Tue Jun 05, 2018 4:41 pm

ghans wrote:
Tue Jun 05, 2018 3:10 pm
Why should a Python beginner learn all about AJAX, Websockets and some (any?) Javascript framework just to make his/her script remote-controllable trough webbroswsers ? I believe remi shows that you don't need all that baggage for simple applications. It just works like a regular GUI widget kit.

ghans
I did as you suggested I can see that app on my browser. When i run program it automatically open in my browser

But still I am looking answer for my main question. How to create GUI for LED blink on web page ?

B.Goode
Posts: 6544
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: How to add java script code into python program?

Tue Jun 05, 2018 5:15 pm

How to create GUI for LED blink on web page ?


Assuming you don't mandate the use of JavaScript any more? (Because that is still the topic of the thread.)


Do you want a 'virtual' (on screen) button that activates a 'real' electrically connected led?

The "Press me" button in the widgets_overview_app.py example script seems to show the basics of creating an on screen button and linking it to a predefined action. You already know how to flash an led, as shown in your first post.

Parth1234
Posts: 38
Joined: Mon Mar 12, 2018 3:14 pm

Re: How to add java script code into python program?

Wed Jun 06, 2018 3:39 am

scotty101 wrote:
Tue Jun 05, 2018 11:16 am

Personally, I'd use python-flask running on your server and then have the javascript on the web browser periodically ask for the status of the LED.
I thought it would be better if I check my code with server..

I am running flask server. I checked with hello program . server is running on my browser.

I am getting problem when I try led blinking code

Code: Select all

from flask import Flask, render_template
 
from flask_responses import  json_response, xml_response, auto_response
import RPi.GPIO as GPIO
import time


app = Flask(__name__)

@app.route('/')
def index():
            GPIO.setmode(GPIO.BOARD)      ## Use board pin numbering
            GPIO.setup(22, GPIO.OUT)      ## Setup GPIO Pin 24 to OUT
            while True:
	    GPIO.output(22,True)  ## Turn on Led
	    time.sleep(1)         ## Wait for one second
	    GPIO.output(22,False) ## Turn off Led
	    time.sleep(1)         ## Wait for one second

if __name__ == '__main__':
        app.run(debug=True, host='0.0.0.0', port=4000)


I am getting following error

Code: Select all

[email protected]:~/Flask $ python flask2.py
Traceback (most recent call last):
  File "flask2.py", line 3, in <module>
    from flask_responses import  json_response, xml_response, auto_response
ImportError: No module named flask_responses
What's the wrong in that line?

scotty101
Posts: 3185
Joined: Fri Jun 08, 2012 6:03 pm

Re: How to add java script code into python program?

Wed Jun 06, 2018 8:46 am

Have you installed flask_responses. I don't believe it comes with Flask by default?
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

Parth1234
Posts: 38
Joined: Mon Mar 12, 2018 3:14 pm

Re: How to add java script code into python program?

Wed Jun 06, 2018 10:14 am

scotty101 wrote:
Wed Jun 06, 2018 8:46 am
Have you installed flask_responses. I don't believe it comes with Flask by default?
Thanks! I missed it.

Now my server is running but LED is not blinking

Code: Select all

from flask import Flask, render_template
 
from flask_responses import  json_response, xml_response, auto_response
import RPi.GPIO as GPIO
import time


app = Flask(__name__)

@app.route('/')
def index():
            GPIO.setmode(GPIO.BOARD)      ## Use board pin numbering
            GPIO.setup(22, GPIO.OUT)      ## Setup GPIO Pin 24 to OUT
            while True:
	                        GPIO.output(22,True)  ## Turn on Led
	                        time.sleep(1)         ## Wait for one second
	                        GPIO.output(22,False) ## Turn off Led
	                        time.sleep(1)         ## Wait for one second

if __name__ == '__main__':
        app.run(debug=True, host='0.0.0.0', port=4000)

Code: Select all

p[email protected]:~/Flask $ python flask2.py
 * Running on http://0.0.0.0:4000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger pin code: 239-128-378
Why Led is not blinking ?

B.Goode
Posts: 6544
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: How to add java script code into python program?

Wed Jun 06, 2018 10:40 am

Why Led is not blinking ?
Tell us more?

Just running the server won't blink the led.

Have you tried navigating to http://server_ip_address:4000 from a web browser? That should try to fetch the default index page and invoke the gpio code... The window in which you started the server should give you some debugging output.

Parth1234
Posts: 38
Joined: Mon Mar 12, 2018 3:14 pm

Re: How to add java script code into python program?

Wed Jun 06, 2018 10:47 am

B.Goode wrote:
Wed Jun 06, 2018 10:40 am
Why Led is not blinking ?
Tell us more?

Just running the server won't blink the led.

Have you tried navigating to http://server_ip_address:4000 from a web browser? That should try to fetch the default index page and invoke the gpio code... The window in which you started the server should give you some debugging output.
This is output
[email protected]:~ $ cd Flask
[email protected]:~/Flask $ python flask2.py
* Running on http://0.0.0.0:4000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger pin code: 239-128-378


When I type IP address 192.168.0.107 it show preious output Hellow world!

When I type 192.168.0.107:4000 it say unable to connect

Is there any mistake in code ?

B.Goode
Posts: 6544
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: How to add java script code into python program?

Wed Jun 06, 2018 1:32 pm

When I type IP address 192.168.0.107 it show preious output Hellow world!

When I type 192.168.0.107:4000 it say unable to connect

Is there any mistake in code ?

You do not appear to have done anything that would affect the behaviour of any existing server listening on port 80 (the default for http) so there is no reason why that behaviour should change.

I am not a Flask user, but since it is offering an http service I would expect that it would return some valid HTML to the browser. Seeing only 'raw' python in your index() method doesn't seem right. But that is just a hunch from ignorance that someone else might comment on.

(This assumes that 192.168.0.107 is the IP address of the RPi running the Flask server.)

scotty101
Posts: 3185
Joined: Fri Jun 08, 2012 6:03 pm

Re: How to add java script code into python program?

Wed Jun 06, 2018 1:51 pm

It returns unable to connect because you program isn't returning anything so your browser never receives any data in response.

At the very least your code should return some static text

Code: Select all

@app.route('/')
def index():
    return "Hello World!"
Since you have a "while True" loop in your code, it will be stuck in that loop and never return anything.

Forget the LED blinking right now. Lets just get the lights turning on and off from a webpage.

Give this a try. (Untested since I don't have a Pi handy)

Code: Select all

from flask import Flask, render_template
 
from flask_responses import  json_response, xml_response, auto_response
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)      ## Use board pin numbering
GPIO.setup(22, GPIO.OUT)      ## Setup GPIO Pin 24 to OUT

app = Flask(__name__)

example_page = """<a href="/On">Turn LED On</a><br><a href="/Off">Turn LED Off</a>"""

@app.route('/')
def index():
    return example_page

@app.route('/Off')
def Off():
    GPIO.output(22,False)  ## Turn on Led
    return example_page

@app.route('/On')
def On():
    GPIO.output(22,True)  ## Turn on Led
    return example_page

if __name__ == '__main__':
        app.run(debug=True, host='0.0.0.0', port=4000)
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

Parth1234
Posts: 38
Joined: Mon Mar 12, 2018 3:14 pm

Re: How to add java script code into python program?

Wed Jun 06, 2018 4:26 pm

scotty101 wrote:
Wed Jun 06, 2018 1:51 pm


Forget the LED blinking right now. Lets just get the lights turning on and off from a webpage.

Give this a try. (Untested since I don't have a Pi handy)
hey scotty101 thanks! you have given me new life line. It's working for me.

Now I am interested to see this https://www.w3schools.com/js/js_intro.asptype of web page

That was my main goal to create this thread. I want to see the given light and two button's on web page. I am interested to see how do you insert java script code in to main code.

scotty101
Posts: 3185
Joined: Fri Jun 08, 2012 6:03 pm

Re: How to add java script code into python program?

Wed Jun 06, 2018 4:35 pm

I have a project hosted on GitHub that I use to control my TV from a webpage via flask and an IR LED.
https://github.com/scotty3785/pi_tv_remote

It contains inside the templates folder an html page that has the necessary JavaScript to make a "background" request to the flask web server to send a command. See line 38
In my case it is a button number, but this could be easily modified to send a 'on/off' signal or just a blank request to the @app.route('/Off') function.

I don't have time to put together a full example but most of the code is either inside the example on my github project, the w3schools page you shared and the code I've given you already in this topic.

I am interested to see how do you insert java script code in to main code.
As I've said already, you don't put javascript inside the main code. The Javascript is processed by your web browser, not flask/python. The javascript code is placed either 'inline' inside the HTML file or as a seperate .js file.
The HTML text including the javascript could be placed inside the python file like i've done with the simple example in this topic but I wouldn't recommend that for anything larger than I've done already. Keep the HTML code inside either the template folder or the static folder of your Flask application.
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

Parth1234
Posts: 38
Joined: Mon Mar 12, 2018 3:14 pm

Re: How to add java script code into python program?

Wed Jun 06, 2018 5:15 pm

scotty101 wrote:
Wed Jun 06, 2018 4:35 pm
I don't have time to put together a full example but most of the code is either inside the example on my github project, the w3schools page you shared and the code I've given you already in this topic.
I have seen most of the example with simple button only . Please whenever you will have time. make the full example on github. This will very helpful for Beginners like me. because whenever someone start to learn, They start from simple like LED bulb. They can see the combination of python code, Flask server and java script together

I don't think i can make it workable because my lack of python and java script knowledge But I am trying to do it myself. Really it would be very helpful for others

scotty101
Posts: 3185
Joined: Fri Jun 08, 2012 6:03 pm

Re: How to add java script code into python program?

Thu Jun 07, 2018 8:37 am

No guarantees. I can't test any of this on such a restrictive windows PC.

Create a folder called LightShow (doesn't need to be that name but that's what I called it)
Under that create a folder called static
Place in static the below index.html file
Place in static the two light image files downloaded from the below links
https://www.w3schools.com/js/pic_bulbon.gif
https://www.w3schools.com/js/pic_bulboff.gif
Place in the LightShow directory the below app.py file.


index.html

Code: Select all

<!DOCTYPE html>
<html>
<head>
    <script>
        var sendCommand = function(command) {
            var xhttp = new XMLHttpRequest();
            var urlCommand = window.location.href + command;
            xhttp.open("GET", urlCommand, true);
            xhttp.send();
        };
            
        var lightOn = function() {
            document.getElementById('myImage').src='/static/pic_bulbon.gif';
            sendCommand('On');
            console.log("Light On");
        };
        
        var lightOff = function() {
            document.getElementById('myImage').src='/static/pic_bulboff.gif';
            sendCommand('On');
            console.log("Light Off");
        };
        
    </script>
</head>

<body>


<h2>What Can JavaScript Do?</h2>

<p>JavaScript can change HTML attribute values.</p>

<p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>

<button onclick="lightOn()">Turn on the light</button>

<img id="myImage" src="/static/pic_bulboff.gif" style="width:100px">

<button onclick="lightOff()">Turn off the light</button>

</body>
</html>
app.py

Code: Select all

from flask import Flask, render_template, url_for

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)      ## Use board pin numbering
GPIO.setup(22, GPIO.OUT)      ## Setup GPIO Pin 24 to OUT

app = Flask(__name__)

@app.route('/')
def index():
    return app.send_static_file('index.html');

# On and Off functions don't actually return any HTML to the browser, they
# just react to the request and send something back to prevent an error.
@app.route('/Off')
def Off():
    GPIO.output(22,False)  ## Turn on Led
    return "On"

@app.route('/On')
def On():
    GPIO.output(22,True)  ## Turn on Led
    return "Off"

if __name__ == '__main__':
        app.run(debug=True, host='0.0.0.0', port=4000)
I'll leave it up you to debug any errors since I've given you so much.
Last edited by scotty101 on Tue Jun 26, 2018 8:55 am, edited 1 time in total.
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

Parth1234
Posts: 38
Joined: Mon Mar 12, 2018 3:14 pm

Re: How to add java script code into python program?

Thu Jun 07, 2018 5:26 pm

I can get the two buttons and one light bulb on browser. when I press ON Button on browser light goes to ON on the browser but Doesn't turn on physically LED. There may be something wrong in code

I am getting following output

[email protected]:~ $ cd LightShow
[email protected]:~/LightShow $ python app.py
app.py:6: RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.
GPIO.setup(22, GPIO.OUT) ## Setup GPIO Pin 24 to OUT
* Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
* Restarting with stat
app.py:6: RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.
GPIO.setup(22, GPIO.OUT) ## Setup GPIO Pin 24 to OUT
* Debugger is active!
* Debugger pin code: 239-128-378
192.168.0.104 - - [07/Jun/2018 16:50:47] "GET / HTTP/1.1" 200 -
192.168.0.104 - - [07/Jun/2018 16:50:50] "GET /static/pic_bulboff.gif HTTP/1.1" 200 -
192.168.0.104 - - [07/Jun/2018 16:50:50] "GET /favicon.ico HTTP/1.1" 404 -
192.168.0.104 - - [07/Jun/2018 16:50:54] "GET //On HTTP/1.1" 301 -
192.168.0.104 - - [07/Jun/2018 16:50:54] "GET /static/pic_bulbon.gif HTTP/1.1" 200 -

scotty101
Posts: 3185
Joined: Fri Jun 08, 2012 6:03 pm

Re: How to add java script code into python program?

Thu Jun 07, 2018 8:47 pm

How far did you get in debugging this yourself? 5 minutes? 10 minutes?

Code: Select all

var urlCommand = window.location.href + "/" + command;
Should be

Code: Select all

var urlCommand = window.location.href + command;
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

Parth1234
Posts: 38
Joined: Mon Mar 12, 2018 3:14 pm

Re: How to add java script code into python program?

Fri Jun 08, 2018 2:38 am

scotty101 wrote:
Thu Jun 07, 2018 8:47 pm

Should be

Code: Select all

var urlCommand = window.location.href + command;
I did changes in html file but the problem is same

B.Goode
Posts: 6544
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: How to add java script code into python program?

Fri Jun 08, 2018 5:31 am

when I press ON Button on browser light goes to ON on the browser but Doesn't turn on physically LED. There may be something wrong in code
Have you tested the led with a simple Python+RPi.GPIO script to check that the LED is wired up and working correctly? You could use the script you posted in the first message in this thread.


Where is the led connected? The #comment on the GPIO.setup() statement is incorrect - you are using GPIO.BOARD numbering, so physical pin #22 (which is what you should have wired up) is actually GPIO25. The comment won't break the code, but it may indicate that you have got the connection wrong.

Return to “Beginners”