'How do I get data returned from the python script into node js?
I am trying to run a python script that uses HC-SR04 sensors to monitor distance and returns the distance measured back to my NodeJS code. If I run the python script by itself it seems to be printing out the correct outputs. But when I console log it in NodeJS nothing returns?
below is the python script
import sys, json
import RPi.GPIO as GPIO
import time
print('test')
GPIO.setmode(GPIO.BCM)
#set GPIO Pins
GPIO_TRIGGER = 22
GPIO_ECHO = 27
#set either in or out
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
def distance():
#set trigger high
GPIO.output(GPIO_TRIGGER, True)
#set trigger low
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
StartTime = time.time()
StopTime = time.time()
while GPIO.input(GPIO_ECHO) == 0:
StartTime = time.time()
while GPIO.input(GPIO_ECHO) == 1:
StopTime = time.time()
TimeElapsed = StopTime - StartTime
distance = (TimeElapsed * 34300) / 2
return distance
try:
while True:
data = distance()
print(data)
time.sleep(1)
except KeyboardInterrupt:
print("stopped by user")
GPIO.cleanup()
Below is the app.js
var express = require('express');
var app = express();
var path = require('path');
process.env.PYTHONPATH = '/usr/lib/python3';
console.log(process.env.PYTHONPATH)
const spawn = require('child_process').spawn;
// set the view engine to ejs
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '/views'));
app.use(express.static(__dirname + '/'));
// use res.render to load up an ejs view file
// index page
app.get('/', function(req, res) {
res.render('index.ejs');
});
//make data string as python does not do json
//let stringifiedData = JSON.stringify(data);
//call python process
const py = spawn('/usr/bin/python3', ['sensors.py']);
var resultString = ' ';
py.stdout.on('data', function (data) {
console.log('Data on');
resultString += data;
console.log(resultString);
});
py.stdout.on('end', function (){
let resultData = resultString;
console.log(resultString);
});
py.on('close', (code) => {
console.log(`child process close all stdio with code ${code}`);
});
app.listen(80);
console.log('Server is listening on port 80');
console.log('Server is running!');
So yeah that's about it please help.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
