· 6 years ago · Mar 17, 2019, 06:58 PM
1var cryptoJS = require('crypto-js');
2var io = require('socket.io')();
3
4const port = 5247;
5const com_port = "/dev/ttyACM0";
6const SerialPort = require('serialport')
7const Readline = require('@serialport/parser-readline')
8const serialPort = new SerialPort(com_port, {
9 baudRate: 115200
10});
11
12const parser = serialPort.pipe(new Readline({ delimiter: '\r\n' }))
13parser.on('data', console.log) // in place of console.log write function that handles incoming data
14
15const writeLine = (string) => {
16 serialPort.write(string, function(err) {
17 if (err) {
18 return console.log('Error on write: ', err.message)
19 }
20 console.log('message written')
21 })
22}
23
24const writeRGB = (r, g, b) => {
25 // r,g,b = 0-255
26 r = r * 255;
27 g = g * 255;
28 b = b * 255;
29 message = "rgb," + r + "," + g + "," + b
30 console.log(message)
31 writeLine(message)
32}
33
34const writeServo = (angle) => {
35 // angle = 0°-180°
36 message = "servo," + angle
37 writeLine(message)
38}
39
40const secretKey = 'secretKey';
41
42io.listen(port);
43
44console.log('Server running on port: ' + port)
45
46const smartHomeState = {
47 'alarm': false,
48 'door': false,
49 'lights': false,
50 'lighting': 0
51}
52
53io.on('connection', (client) => {
54 console.log('Client connected')
55 client.emit('connectionResponse', 'New client with ID: ' + client.id);
56 client.on('alarm', (alarm) => {
57 console.log('Alarm state: ' + alarm)
58 smartHomeState['alarm'] = alarm
59 });
60 client.on('door', (door) => {
61 console.log('Door state: ' + door)
62 smartHomeState['door'] = door
63 });
64 client.on('lights', (lights) => {
65 console.log('Lights state: ' + lights)
66 smartHomeState['lights'] = lights
67 });
68 client.on('lighting', (lighting) => {
69 console.log('Lighting state: ' + lighting)
70 smartHomeState['lighting'] = lighting
71 writeRGB(smartHomeState['lighting'], smartHomeState['lighting'], smartHomeState['lighting']);
72 });
73 // Sending a generated temperature reading to the client
74 client.on('temperature', () => {
75 console.log('Emitting a temperature reading to the client.')
76 client.emit('temperature', generateTemperatureData(29, 15))
77 });
78});