node-raspberry-server/index.js
2019-01-19 17:47:37 +01:00

150 lines
3.6 KiB
JavaScript

const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const mongoDB = "mongodb://127.0.0.1/chillroom-database";
const deviceSchema = require("./deviceSchema");
const bodyParser = require("body-parser");
const statusSchema = require("./statusSchema");
mongoose.connect(
mongoDB,
{ useNewUrlParser: true }
);
const app = express();
app.use(cors());
app.options("*", cors());
app.use(bodyParser.json());
const port = 3000;
const save_data = async time => {
try {
const devices = await deviceSchema.find({});
//console.log("DEVICES => " + devices);
for (const { ip, _id, lastStatus } of devices) {
const value_data = await getScript(ip);
const data = JSON.parse(value_data);
//console.log(lastStatus, data.Sensors[0].Switch);
if (lastStatus != data.Sensors[0].Switch) {
await statusSchema.findOneAndUpdate(
{ device: _id },
{
$push: { status: { value: data.Sensors[0].Switch, time } }
}
);
await deviceSchema.findByIdAndUpdate(_id, {
lastStatus: data.Sensors[0].Switch
});
}
}
} catch (error) {
//console.log("ERROR z CATCHA => " + error);
}
};
let interval = setInterval(() => {
save_data(Date.now());
}, 1000);
const getScript = url => {
return new Promise((resolve, reject) => {
const http = require("http");
let client = http;
url = "http://" + url + "/json";
//console.log("DATA URL => " + url);
client
.get(url, resp => {
let data = "";
// Dane zostały pobrane
resp.on("data", chunk => {
data += chunk;
});
// Cały response pobrany i print
resp.on("end", () => {
resolve(data);
//console.log(data);
});
})
.on("error", err => {
resolve('{"Sensors": [{ "Switch": 2 }]}');
});
});
};
app.get("/chillroom-server", (req, res) => {
(async url => {
res.json(await getScript(url));
})(req.query.ip);
});
app.get("/stop", (req, res) => {
clearInterval(interval);
interval = null;
res.json({ message: "Przestalem dzialac :<" });
});
app.get("/status/:id", async (req, res) => {
const data = await statusSchema
.findOne({
device: mongoose.Types.ObjectId(req.params.id)
})
.select("status");
const status = data.status.sort((a, b) => {
return b.time - a.time;
});
res.json(status);
});
app.get("/start", (req, res) => {
if (interval === null) {
interval = setInterval(() => {
save_data(Date.now());
}, 15000);
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 deviceSchema.find({});
res.json(items);
});
app.post("/device", async (req, res) => {
//console.log(req.body);
const newDevice = await deviceSchema.create({
name: req.body.name,
ip: req.body.ip
});
await statusSchema.create({ device: newDevice });
res.json({ Sukces: "Dodaje OK" });
});
app.delete("/device/:ip", async (req, res) => {
//console.log(req.body);
const newDevice = await deviceSchema.findOneAndRemove({ ip: req.params.ip });
await statusSchema.findOneAndRemove({ device: newDevice });
res.json({ Sukces: "Usuwa OK" });
});
app.put("/device/:id", async (req, res) => {
const newDevice = await deviceSchema.findByIdAndUpdate(
req.params.id,
req.body
);
res.json(newDevice);
});
app.listen(port, () =>
console.log(`Chillroom server nasluchuje na porcie ${port}!`)
);