I have a python interactive script that talks with my 3D printer. If I open this script, I type two commands that outputs information to stdout:
- connect to the printer (USB) at 250000 bauds
- Get the temperature
I would like the connection with the printer to remain permanently, because in the future, I may connect again to the script to poll for the ETA of the current print job.
Then, NodeJS with Express allows me to create a simple web API that communicates with this script using a child process, but I am getting a lot of errors.
My code:
var express = require('express');
var app = express();
var child_process = require('child_process');
spawn = child_process.spawn;
var n = child_process.spawn('/home/pi/virtualenvs/printrun/bin/python', ['-i','-u','/home/pi/projects/printrun/Printrun/pronsole.py']);
n.stdin.write('connect /dev/ttyACM0 250000');
n.stdin.write('\n');
app.get('/printer_temp', function (req, res) {
n.stdin.write('gettemp');
n.stdin.write('\n');
n.stdout.on('data', function(data){
res.json({printer_status: data}); //I should get kind of like an "OK", with a bunch of other lines.
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Starting server');
});
I'm getting errors line 29: Error: Can't set headers after they are sent.
What am I doing wrong?