-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
98 lines (82 loc) · 2.51 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
require("dotenv").config();
const express = require("express");
const scheduledFunctions = require("./scheduled/updateDb.js");
const cors = require("cors");
const { default: fetch } = require("node-fetch");
const MyAir = require("./myAir.js");
const dbo = require("./db/connect");
const apiRoutes = require("./routes/api.js");
const app = express();
app.set("port", process.env.SERVER_PORT || 3001);
const client = new MyAir(
process.env.MYAIR_IP,
parseInt(process.env.MYAIR_PORT),
process.env.MYAIR_AIRCON
);
const baseUrl = `http://${client._host}:${client._port}`;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use("/api", apiRoutes);
// Execute scheduled tasks
if (process.env.NODE_ENV === "production") {
scheduledFunctions.initScheduledJobs(client);
}
app.get("/zones", async (req, res) => {
await client.update();
res.send(client.zoneArray);
// console.log(client.zones ='{"z02":{"state":"open"}}');
// console.log(client.zoneArray);
});
app.get("/info", async (req, res) => {
await client.update();
res.send(`<pre>${JSON.stringify(client.info, null, 2)}</pre>`);
// console.log(client.zones ='{"z02":{"state":"open"}}');
// console.log(client.zoneArray);
});
app.get("/update", async (req, res) => {
await client.update();
const zones = client.zoneArray;
const myZone = client.myzone;
const info = {
fan: client.info.fan,
mode: client.info.mode,
setTemp: client.info.setTemp,
state: client.info.state,
};
let timestamp = new Date();
console.log(timestamp);
timestamp = new Date(
timestamp.getTime() - timestamp.getTimezoneOffset() * 60 * 1000
);
console.log(timestamp);
let updateObject = {
timestamp: timestamp,
myZone: myZone,
myZoneName: zones[myZone - 1]["name"],
...info,
zones: [...zones],
};
res.send(`<pre>${JSON.stringify(updateObject, null, 2)}</pre>`);
});
// app.use( '/foo', (req, res) => {
// return res.json({ "foo": "bar" })
// })
app.get("/status", async (req, res) => {
await fetch(`${baseUrl}/getSystemData`)
.then((/** @type {{ json: () => any; }} */ response) => response.json())
.then((/** @type {any} */ result) => {
res.set("Content-Type", "application/json");
res.send(result);
})
.catch((/** @type {any} */ error) => console.log("error", error));
});
try {
dbo.connectToServer();
} catch (err) {
console.error(err);
process.exit();
}
app.listen(process.env.SERVER_PORT, () => {
console.log("App listening on port " + app.get("port"));
});