上QQ阅读APP看书,第一时间看更新
Running a receiver application on a PC
To run a receiver app on a PC, follow the sequence described here:
- Install and launch a PostgreSQL container:
docker run --rm --name postgres-container -e POSTGRES_PASSWORD=password -it -p 5433:5432 postgres
docker exec -it postgres-container createdb -U postgres iot-book
- Create the receiver folder.
- Create the ./receiver/package.json file with the following content:
{
"name": "receiver",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"pg": "^6.2.3"
}
}
- Create the ./receiver/index.js file with the following content, replacing the database credentials with the correct values:
var restify = require('restify');
var server = restify.createServer({name: 'MyApp'});
server.use(restify.bodyParser());
var Pool = require('pg').Pool;
var pool = new Pool({
database: 'iot-book',
host: 'host',
password: 'password',
port: 5433,
user: 'postgres',
});
//ensure table exists in db
pool.query('CREATE TABLE IF NOT EXISTS "sensor-logs" (id serial NOT NULL PRIMARY KEY, data json NOT NULL)', function (err, result) {
if (err) console.log(err);
});
server.post('/', function create(req, res, next) {
console.log(req.params);
//save in db
pool.query('INSERT INTO "sensor-logs" (data) VALUES ($1)', [req.params], function (err, result) {
if (err) console.log(err);
res.send(201, result);
});
return next();
});
server.get('/stats', function search(req, res, next) {
pool.query('SELECT AVG("Variable1"), MAX("Variable1"), MIN("Variable1"), COUNT(*), SUM("Variable1") FROM (SELECT (data->>\'Variable1\')::int "Variable1" FROM "sensor-logs" ORDER BY id DESC LIMIT 10) data', function (err, result) {
if (err) console.log(err);
res.send(result.rows);
});
return next();
});
server.listen(process.env.PORT || 8080);
- Create the ./receiver/Dockerfile file with the following content:
FROM node:boron-onbuild
EXPOSE 8080
- Build an image and run a Docker container:
# Build an image from a Dockerfile
docker build -t opcua-receiver .
# Run container in foreground
docker run -p 8080:8080 -it --rm --name opcua-receiver-container opcua-receiver
# Run container in background
# docker run -p 8080:8080 -d --rm --name opcua-receiver-container opcua-receiver
# Fetch the logs of a container
# docker logs -f opcua-sensor-container
# Stop running container
# docker stop opcua-receiver-container
Console output when a receiver app is running