Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sending serial data from python script to node script

Tags:

node.js

I have got two scripts - one python script and another a node script. The python script runs in an infinte loop and reads the serial data. Once it receives the serial data, it has to pass it to node.js scipt so it can be processed in a node server.

I thought of using the node.js child_process module to read the data from the python script but since the python script is a infinite loop, its not returning any data to the node script. Can anyone please let me know how to solve this issue ?

Python script:

import serial
ser = serial.Serial('COM10', 9600, timeout =1)
while 1 :
    print ser.readline()'

Node.js Script:

var spawn = require('child_process').spawn,
ls    = spawn('python',['pyserial.py']);

ls.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});

ls.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});

Note : My only reason for going with python script is node.js serialport module is not working currently for my project due to some issue in serialport module.

like image 294
Android Beginner Avatar asked Jun 01 '13 13:06

Android Beginner


1 Answers

You need to flush the standard output stream in your python script after printing. Here is an example that prints the time (I don't have a serial device to test):

Python:

import sys
from datetime import datetime
from time import sleep
while 1:
    print datetime.now()
    sys.stdout.flush()
    sleep(5)

Node.js:

var spawn = require('child_process').spawn,
    ls    = spawn('python',['test.py']);

ls.stdout.on('data', function (data) {
    console.log('stdout: ' + data);
});

ls.stderr.on('data', function (data) {
    console.log('stderr: ' + data);
});
like image 105
mr.freeze Avatar answered Sep 28 '22 08:09

mr.freeze