-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
143 lines (128 loc) · 4.66 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
//===================DEPENDENCIES=============================
const express = require('express');
const logger = require('morgan');
const cors = require('cors');
const bodyParser = require('body-parser');
const http = require('http');
const socketIo = require('socket.io');
const fs = require('fs');
const fileUpload = require('express-fileupload');
const mongoose = require('mongoose');
const helmet = require('helmet');
const expressRateLimit = require('express-rate-limit');
const SerialPort = require('serialport');
const Readline = require('@serialport/parser-readline');
const Events = require('events');
//===================SERVER INIT==============================
const limiter = expressRateLimit({
windowMs: 60*1000, //60 sec
max: 100 //requests
})
const port = process.env.PORT || 3001
const app = express()
app.use(cors())
app.use(helmet()) //security
app.use(limiter)
app.use(logger('dev')) //for log
app.use(fileUpload())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
const server = http.createServer(app)
//===================ROUTES===================================
const printer = require("./src/printer")
app.use(printer)
const user = require("./src/user")
app.use(user)
//===================SOCKET INIT==============================
const io = socketIo(server)
app.get("/", (req, res) => {
res.send({ response: "Hello World" }).status(200);
});
//===================SERIAL PORT==============================
/*var ports = []
var parsers = []
newPorta(1, '/dev/ttyUSB0', 250000)
// const porta = new SerialPort('/dev/ttyUSB0', { baudRate: 250000 });
// const parser = porta.pipe(new Readline({ delimiter: '\n' }));
// // Read the port data
// porta.on("open", () => {
// console.log('serial port open');
// });
// parser.on('data', data =>{
// //let lettera = String.fromCharCode(data)
// console.log(data)
// io.emit("new command from printer", id, data);
// //console.log('got word from arduino:', lettera)
// });
/*
SerialPort.list().then(ports => {
console.log(ports)
}).catch(e => console.log(e))
porta.write(command+"\n")
*//*
function newPorta(id, porta, baudrate){
ports[id] = new SerialPort(porta, {baudRate: baudrate}) //problema con promise non catturata se porta non esistente
parsers[id] = ports[id].pipe(new Readline({delimiter: '\n'}))
ports[id].on("open", () => {
console.log('serial port '+porta+' open');
});
parsers[id].on('data', data =>{
console.log(data)
io.emit("new command from printer", id, data);
});
}*/
//===================SOCKET===================================
io.on("connection", socket => {
console.log("User connected")
socket.on("new command", (id, command, fn) => {
console.log(id+": "+command)
fn("ok")
let string = "3-"+Date.now()+"-"+command
fs.appendFile("./logs/printed/printer"+id+".log", string+"\n1-"+Date.now()+"-ok\n", err => {if(err)console.error(err)})
ports[id].write(command+"\n")
socket.broadcast.emit("new command from client", id, command)
io.emit("new command from printer", id, "ok")
})
socket.on("get status", () => {
socket.emit("res status", )
})
socket.on("status update", (id, newStatus) => {
// setPrinterStatus(id, newStatus)
console.log("Status change: "+id+", "+newStatus)
io.emit("set printers status", id, newStatus)
})
socket.on("new printer", (name, port, baudrate, fn) => {
newPrinter(name, port, baudrate)
})
socket.on("switch print tab", (id) => {
socket.emit("switch print tab", id)
})
//esempi di socket
socket.on("volatile example", message => { //se la connessione è sovraccarica o troppo lenta non viene recapitato
// socket.volatile.emit("volatile example", "test")
console.log(message)
})
socket.on("cinesino che risponde", (message, fn) => {
fn("ok")
console.log(message)
// socket.emit("cinesino che risponde", "ciao", data => {
// console.log(data)
// })
})
socket.on('disconnect', () => {
console.log('User disconnected')
})
})
//===================SERVER LISTEN============================
server.listen(port, () => {
console.log("Server running on port "+port)
})
//===================DATABASE=================================
const dburl = 'mongodb://127.0.0.1:27017/fab-printers'
mongoose.connect(dburl, {useNewUrlParser: true, useUnifiedTopology: true})
const db = mongoose.connection
db.once('open', () => {console.log("Database Connected")})
db.on('error', err => {console.log("Database Error: "+err)})
//==================GCODE=====================================
//==================FILE PARSING==============================
//https://stackoverflow.com/questions/16010915/parsing-huge-logfiles-in-node-js-read-in-line-by-line