This repository has been archived by the owner on Jul 3, 2024. It is now read-only.
forked from fss/solis-inverter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
71 lines (60 loc) · 1.54 KB
/
index.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
const SolisInverterClient = require('./lib/solis_inverter_client.js')
const { name } = require('./package.json')
let interval = parseInt(process.env.INTERVAL)
if (isNaN(interval) || interval < 30) {
interval = 30
}
const port = 8000
const address = process.env.SOLIS_ADDRESS
const username = process.env.SOLIS_USERNAME
const password = process.env.SOLIS_PASSWORD
if (!address) {
console.error('address not given')
process.exit(1)
}
if (!port) {
console.error('port not given')
process.exit(1)
}
const inverter = new SolisInverterClient(address, username, password)
/**
* @type {Object|null}
*/
let lastResponse = null
/**
* @type {Date|null}
*/
let lastDate = new Date()
/**
* @param what
*/
const log = what => console.log([(new Date()).toISOString(), name, what].join(' '))
const server = require('http').createServer((req, res) => {
if (lastResponse) {
res.writeHead(200, { 'Last-Modified': lastDate.toString() })
res.end(JSON.stringify(lastResponse))
} else {
res.writeHead(500)
res.end('No data')
}
})
/**
* @return {Promise}
*/
const fetchData = () => inverter.fetchData()
.then(data => {
if (data.inverter.serial) {
// only store valid responses
lastResponse = data
lastDate.setTime(Date.now())
}
})
.catch(err => log(`Could not fetch data from inverter: ${err}`))
server.listen(port, err => {
if (err) {
log(`unable to listen on port ${port}: ${err}`)
} else {
log(`listening on port ${port}`)
fetchData().then(() => setInterval(fetchData, interval * 1000))
}
})