forked from daltonvarao/energysaver
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
85 lines (77 loc) · 2.42 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// chamada do express
var express = require("express");
// faz a juncao de diretorios
var path = require("path");
// faz o log no terminal
var logger = require("morgan");
// pega valores do front-end
var bodyPaser = require("body-parser");
var cookieParser = require("cookie-parser");
// cira sessoes
var session = require("express-session");
var passport = require('passport');
// broker mqtt
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://localhost');
// banco de dados
var mongoose = require("mongoose");
// junta models views e controller
var load = require("express-load");
// envia mensagens para o front-end
var flash = require("express-flash");
// formarta data e hora
var app = express();
// socket.io
var socket = require("socket.io");
// http
var http = require("http");
// conexao com banco de dados
mongoose.connect("mongodb://localhost:27017/energysaver", function(err) {
if (err) {
console.log("Erro ao conectar banco de dados: " + err);
} else {
console.log("Conexao com banco de dados efetuada com sucesso");
}
});
// conexao com mqtt
client.on('connect', function() {
client.subscribe('Tapajos-IoT');
});
client.on('message', function(topic, message) {
msg = JSON.parse(message.toString());
var Dados = app.models.dados;
var model = new Dados(msg);
model.save(function(err) {
if (err) {
console.log('Erro ao armazenar o dado: ' + err);
} else {
console.log('Dado salvo com sucesso: ' + message.toString());
io.sockets.emit("msg", { msg: msg });
}
});
});
// setups start
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.set("porta", process.env.PORT || 3000);
app.use(logger("dev"));
app.use(bodyPaser.json());
app.use(bodyPaser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({ secret: "daltonfelipe" }));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, "public")));
app.use(flash());
// helpers
app.use(function(req, res, next) {
res.locals.session = req.session.usuario;
res.locals.isLogged = req.session.usuario ? true : false;
next();
});
load("models").then("controllers").then("routes").into(app);
// levanta o servidor na porta 3000
var server = http.createServer(app).listen(app.get("porta"), function() {
console.log("Listen on port 3000");
});
var io = socket.listen(server);