Use Raspberry Pi as server, script
He must provide data on demand to another device, client, or execute programs on demand.
Installing the Services and Data Server Using Node.js
You need the latest version of Node, not version 0.10 in Raspbian! To install it automatically, here's a small script:
#!/bin/sh
curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs
The script must be executed on Raspberry, not Windows, as the shell is sensitive to line-ending codes. To do this, enter:
leafpad instnode
Then copy the above code (assuming this page is loaded into the Pi browser). You can also upload the script to a zip archive for unpacking to Pi.
There is no sudo because the script is used as a user, not an administrator. Then you need to change the permissions to make it executable. Right-click on the file name from the file manager, click on the permissions and change "make executable" to "all."
You can then run the script using:
./instnode
If necessary, you can create a folder for the server on the default user account in/home/pi.
mkdir www
The root of the server will be:
/home/pi/www
The server is a simple JavaScript program that is run to bring Pi online. To connect Pi and other computers to the network, sending HTML pages is not the goal, it is primarily sending commands and receiving data. Here is an example of a server that executes commands and sends information in return. Asynchronous.
1) Node.js server
This service server does not send files to the browser, the script that does this is presented in another article, Creating a page server with Node.js. It gets the command name and data to go to this command and executes the corresponding script .
var runner = require("child_process"),
http = require("http"),
path = require("path"),
url = require("url"),
fs = require("fs");
function sendError(errCode, errString, response)
{
response.writeHeader(errCode, {"Content-Type": "text/plain"});
response.write(errString + "\n");
response.end();
return;
}
function sendData(err, content, response)
{
if(err) return sendError(500, err, response);
response.writeHeader(200, {"Content-Type": "text/plain"});
response.write(content + "\n");
response.end();
}
/*
Run a script
This script will send data to the user when it wants.
*/
function runScript(params, response)
{
var command = "";
if(params.script == undefined) return;
if(params.data == undefined) return;
var child = runner.execFile("node",
[params.script, params.data],
function(error, stdout, stderr) {
console.log(error + " " + stdout);
sendData(error, stdout, response);
});
child.on('close', function(code) {
process.exit(1);
});
}
function getCommand(request, response)
{
if(request.method != "POST") {
console.log("POST only supported.");
return;
}
var data = "";
request.on("data", function(chunk) {
data += chunk;
});
request.on("end", function() {
var urlpath = url.parse(request.url).pathname;
if(urlpath == "favicon.ico") return;
var localpath = path.join(process.cwd(), urlpath);
console.log("Requested script: " + localpath);
fs.exists(localpath, function(result) {
var params = {
"script": localpath,
"data" : "\"" + data + "\""
};
runScript(params, response);
});
});
}
var server = http.createServer(getCommand);
server.listen(3000);
console.log("Server available...");
The code has the necessary functions to create a server, execute a script and transfer data to this script. In response to the request, it returns the result displayed by the script.
2) Example of a very basic service
This demo script receives and displays the data sent by the remote computer in raspi. In response, he sends a message "Hello computer!."
function processCommand(data) {
console.log("Received from computer: " + data);
var answer = "Hello computer!";
console.log("Answer:");
console.log(answer);
}
console.log("\nRaspberry: Starting script.js...");
var data = process.argv[2];
processCommand(data);
3) Service usage code of another computer
This is again a JavaScript script on the command line, but any other language or interface may be suitable. It sends the name of the script (script.js) and the data for processing to the server, in this case the message "Hello Raspi !"
It then displays the response sent by the script to raspi.
http = require("http");
var options = {
host: 'xxx.xxx.xxx.xxx', // the IP of your Raspberry Pi
path: '/script.js',
port: '3000',
method: 'POST'
};
function received(response) {
var message = ''
response.on('data', function (chunk) {
message += chunk;
});
response.on('end', function () {
console.log(message);
});
}
var req = http.request(options, received);
req.write("Hello Raspi!");
req.end();
For the script to work, you need to assign the IP address of your distribution to the host attribute in the options. Subsequently, you will also be able to choose from several scenarios and send them data as needed ...
This code works great, but is voluntarily simplified. You can improve the server with a list of scripts when selecting and exchanging JSON objects, rather than simple messages. The principle is the same with the use of stringyphic and parsistic methods. Another improvement would be to use Wi-Fi rather than the internet, which works better for most projects in Raspberry. This will be the subject of further articles.
Download code:
Start.js and script.js place themselves on the print in the user directory. We start the server by "node start.js ."
Computer.js is hosted on a device that wants to communicate with a raspi. The script runs as "node computer.js."