3

We want to send a boolean value from python to javascript so we can use it in our html website.

We tried using sockets but thats too complicated for us. Our next thought was to use an api and we know how to get information from an api using javascript. What we want to do is post a python boolean value to an api, and then get the boolean value from the api using javascript. But we don't know how to do so.

We are using a raspberry pi for all our code and a hardware-button which returns true in python when pressed.

We are currently testing code we found from https://healeycodes.com/javascript/python/beginners/webdev/2019/04/11/talking-between-languages.html

But this code doesnt work for us. We are also using pycharm as our workspace, is this a problem?

Our current code in javascript:

    const request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.onreadystatechange = function() {
        if (request.readyState === 4 && request.status === 200) {
            success(JSON.parse(request.responseText));
        }
    };
    request.send();
     setInterval(get("button-status.json", receiveStatus), 3000);
}


function receiveStatus(response) {
    if (response.status !== status) {  // only do something if status has changed
        status = response.status;
        console.log('button status is now', status);
    }
}
let status;
// checks every 100ms
get()

Our python code we're using for testing:

import random
import json
import time
button_status = False
path = (r"C:\Users\Sam\Desktop\pythonProject\pythonflask\emplates")  # replace with your actual path

def save_button_status():
    with open(path + "/button-status.json", "w") as f:
        json.dump({'status': button_status}, f)



while True :
    value = random.randrange(1, 10)
    if ( value <= 5) :
        button_status = True
        save_button_status()
        time.sleep(3)
    else :
        button_status = False
        save_button_status()
        time.sleep(3)

    print(button_status)
Sw3que
  • 31
  • 6
  • 'We tried using sockets but thats too complicated' why? Also is this boolean in a running python program or just the output of running one? – Jared Smith Jan 07 '21 at 15:25
  • It's too complicated because were new to programming and don't know where to start. This boolean is just the output of a running python script. – Sw3que Jan 07 '21 at 21:51
  • nodejs, like most languages has a [facility for running and capturing the output of a shell command](https://stackoverflow.com/questions/12941083/execute-and-get-the-output-of-a-shell-command-in-node-js)...like one invoking your python script. – Jared Smith Jan 08 '21 at 00:56
  • I see you're talking about nodejs. We're using pycharm as our workspace, is this a problem? The source you linked to talks about child_process but this doesn't work in our code and we don't know what the problem is. – Sw3que Jan 08 '21 at 14:48
  • If I understand rightly you have a public website, and you want to put the javascript there, and have it access a value from some Python code running locally on your raspberry pi? Is your website hosted on a server, or are you even hosting the website on the pi? – Stuart Jan 08 '21 at 15:01
  • 2
    child_process is indeed a node.js module that works in a node.js console, and cannot be used within javascript that is part of a webpage and accessed through the browser. – Stuart Jan 08 '21 at 15:36
  • We're using a localhost for the website running on our raspberry pi. And you're correct in thinking that our sensors are controlled using python on our raspberry pi. We could maybe try to use flask to make this a local server instead of a local host, if that is any help. – Sw3que Jan 08 '21 at 15:43
  • 1
    Check the new code you have posted - looks like some lines got copied in the wrong place? – Stuart Jan 09 '21 at 21:29
  • You're right we changed some lines that we shouldn't have changed. It all works fine now. Thank you so much for your help! @Stuart – Sw3que Jan 10 '21 at 18:33

2 Answers2

1

Javascript within a webpage cannot directly run a Python script on your computer or read information from a local terminal. What you could do is have your Python program output a small json file to your localhost folder which is overwritten when the button is pressed or released, like this:

import json
button_status = False   # assuming it is initially off
path = "path/to/your/localhost/folder"  # replace with your actual path

def save_button_status():
    with open(path + "/button-status.json", "w") as f:
        json.dump({'status': button_status}, f)

# Then call save_button_status() whenever the status changes

Then in your javascript, set an interval to periodically call a function that gets this json file and does something based on the value if it has changed:

function get(url, success) {
    //--- Get JSON data at the given URL and call `success` if successful
    const request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.onreadystatechange = function() {
        if (request.readyState === 4 && request.status === 200) {
            success(JSON.parse(request.responseText));
        }   
    };
    request.send();
}

function receiveStatus(response) {
    if (response.status !== status) {  // only do something if status has changed
        status = response.status;
        console.log('button status is now', status);
    }
}
let status;
let interval = setInterval(() => get("button-status.json", receiveStatus), 100); // checks every 100ms

There may be some lag as your local server updates the file.

Stuart
  • 9,597
  • 1
  • 21
  • 30
  • Thank you for your help @Stuart. This code looks very promising, but the only way we can make it work is like i've editted it on my original question. Since I couldn't post my code in a comment because it's too many characters. The problem is that it creates a lot of lag and doesn't work consistant. Do you have any idea what we are doing wrong? – Sw3que Jan 09 '21 at 20:52
0

You can try to set up a SQL Database. Write a SQL statement in Python to receive your boolean. After that make a PHP script on your Web server to receive the SQL data. Then sent a request to the URL of the PHP script using an XHTTP JavasScript request.

SemBauke
  • 147
  • 11