-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
58 lines (48 loc) · 1.55 KB
/
server.js
File metadata and controls
58 lines (48 loc) · 1.55 KB
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
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const path = require('path');
const { WeatherProcessor } = require('./services/weatherProcessor');
const { ACController } = require('./services/acController');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const weatherProcessor = new WeatherProcessor();
const acController = new ACController();
app.use(express.static('public'));
wss.on('connection', (ws) => {
console.log('Client connected');
const sendUpdate = () => {
const weatherData = weatherProcessor.getCurrentWeather();
ws.send(JSON.stringify({
type: 'update',
weather: weatherData
}));
};
// Send initial data
sendUpdate();
// Handle incoming messages
ws.on('message', (message) => {
const data = JSON.parse(message);
if (data.type === 'control') {
const status = acController.getStatus(
weatherProcessor.getCurrentWeather().temperature,
data.targetTemp,
data.powerMode
);
ws.send(JSON.stringify({
type: 'status',
status: status
}));
}
});
// Update weather periodically
const interval = setInterval(sendUpdate, 5000);
ws.on('close', () => {
clearInterval(interval);
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});