node-raspberry-server/index.js

92 lines
2.0 KiB
JavaScript
Raw Normal View History

2019-01-01 22:59:16 +01:00
const express = require("express");
const cors = require("cors");
2019-01-12 10:32:24 +01:00
const mongoose = require("mongoose");
const mongoDB = "mongodb://127.0.0.1/chillroom-database";
const dbSchema = require("./dbScheme");
mongoose.connect(
mongoDB,
{ useNewUrlParser: true }
);
2019-01-01 22:59:16 +01:00
const app = express();
app.use(cors());
app.options("*", cors());
const port = 3000;
2019-01-12 11:36:07 +01:00
const save_data = async url => {
const value_data = await getScript(url);
const data = JSON.parse(value_data);
const item = new dbSchema({
name: data.Sensors[0].TaskName,
status: data.Sensors[0].Switch
});
await item.save();
};
2019-01-12 10:32:24 +01:00
let interval = setInterval(() => {
2019-01-12 11:36:07 +01:00
save_data("192.168.8.107");
2019-01-12 10:32:24 +01:00
}, 5000);
2019-01-01 22:59:16 +01:00
const getScript = url => {
return new Promise((resolve, reject) => {
const http = require("http");
let client = http;
2019-01-12 10:32:24 +01:00
url = "http://" + url + "/json";
2019-01-01 22:59:16 +01:00
2019-01-12 11:36:07 +01:00
console.log("DATA URL => " + url);
2019-01-01 22:59:16 +01:00
client
.get(url, resp => {
let data = "";
2019-01-12 10:32:24 +01:00
// Dane zostały pobrane
2019-01-01 22:59:16 +01:00
resp.on("data", chunk => {
data += chunk;
});
2019-01-12 10:32:24 +01:00
// Cały response pobrany i print
2019-01-01 22:59:16 +01:00
resp.on("end", () => {
resolve(data);
2019-01-12 10:32:24 +01:00
console.log(data);
2019-01-01 22:59:16 +01:00
});
})
.on("error", err => {
reject(err);
});
});
};
app.get("/chillroom-server", (req, res) => {
(async url => {
res.json(await getScript(url));
})(req.query.ip);
});
2019-01-12 10:32:24 +01:00
app.get("/stop", (req, res) => {
clearInterval(interval);
interval = null;
res.json({ message: "Przestalem dzialac :<" });
});
app.get("/start", (req, res) => {
if (interval === null) {
interval = setInterval(() => {
2019-01-12 11:36:07 +01:00
save_data("192.168.8.107");
2019-01-12 10:32:24 +01:00
}, 5000);
res.json({ message: "Zaczalem dzialac :>" });
} else {
res.json({ message: "Dzialam i nie mozna mnie rozpoczac raz jeszcze :p" });
}
});
app.get("/all", async (req, res) => {
const items = await dbSchema.find({});
res.json(items);
});
2019-01-01 22:59:16 +01:00
app.listen(port, () =>
console.log(`Chillroom server nasluchuje na porcie ${port}!`)
);