forked from ngrie/powerinterface
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
171 lines (149 loc) · 4.75 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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import fs from 'fs'
import YAML from 'yaml'
import axios from 'axios'
import express from 'express'
import morgan from 'morgan'
import paramConverter from './src/paramConverter.js'
import paramDefinition from './src/paramDefinition.js'
import {
isMaintenanceChargeEndedEvent,
isMaintenanceChargeStartedEvent,
isWinterModeEndedEvent,
isWinterModeStartedEvent,
parseEvent,
} from './src/eventParser.js'
import { initStats, updateStats } from './src/inMemoryStats.js'
import buildWebinterface from './src/webinterface.js'
import { logUnknownRequest, runUpdateCheck, handleSigInt } from './src/utils.js'
import CURRENT_VERSION from './currentVersion.js'
import InfluxDbAction from './src/actions/InfluxDbAction.js'
import PushoverAction from './src/actions/PushoverAction.js'
const actionClasses = {
influxdb: InfluxDbAction,
pushover: PushoverAction,
}
const actions = []
handleSigInt()
let config = {}
let forwardRequests = false
let logRequests = false
let webReload = 60
if (fs.existsSync('./config.yml')) {
config = YAML.parse(fs.readFileSync('./config.yml', 'utf8')) || {}
if (!Object.keys(config).length) {
console.log('Empty or invalid config.yml found, ignoring')
} else if (config.actions && Array.isArray(config.actions)) {
config.actions.forEach(({ type, ...actionConfig }) => {
if (!actionClasses[type]) {
console.warn(`Invalid action "${type}" found in config.yml, ignoring`)
return
}
const actionInstance = new actionClasses[type](actionConfig)
actionInstance.boot({ paramDefinition })
actions.push(actionInstance)
console.log(`Action registered: ${type}`)
})
}
if (config.forwardRequests) {
forwardRequests = true
}
if (config.logRequests) {
logRequests = true
}
if ('webReload' in config) {
webReload = parseInt(config.webReload)
}
}
const app = express()
const port = 80
app.use(express.json())
app.use(morgan('combined'))
let updateAvailable = false
let currentData = {}
let currentStatuses = {}
let events = []
let isWinterMode = false
let isMaintenanceCharge = false
let lastUpdate = null
let stats = initStats()
runUpdateCheck(CURRENT_VERSION, () => updateAvailable = true)
app.get('/', (req, res) => {
res.send(buildWebinterface(currentData, stats, { isWinterMode, isMaintenanceCharge }, { webReload }, lastUpdate, updateAvailable))
})
app.get('/values.json', (req, res) => {
res.type('json').send(currentData)
})
app.get('/status.json', (req, res) => {
res.type('json').send(currentStatuses)
})
app.get('/events.json', (req, res) => {
res.type('json').send([...events].reverse())
})
app.post('/logs.json', (req, res) => {
try {
const { data, statuses } = paramConverter(req.body, paramDefinition)
currentData = data
currentStatuses = statuses
lastUpdate = new Date()
updateStats(data, stats)
if (logRequests) {
logUnknownRequest(req)
}
const powerRouterId = req.body.header.powerrouter_id
actions.forEach((action, index) => {
try {
action.update({ data, powerRouterId })
} catch (e) {
console.error(`Failed to invoke action at index ${index}`, e)
}
})
if (forwardRequests) {
// forward request to logging1.powerrouter.com
axios.post('http://77.222.80.91/logs.json', req.body, { headers: { Host: 'logging1.powerrouter.com' } })
.catch(({ response }) => {
console.error('Forwarding request to logging1.powerrouter.com failed', response && response.status)
})
}
} catch (e) {
console.error(e)
if (logRequests) {
logUnknownRequest(req, e)
}
}
res.type('json').status(201).send({ 'next-log-level': 2, status: 'ok' })
})
app.post('/events.json', (req, res) => {
try {
const event = parseEvent(req.body.event)
if (isWinterModeStartedEvent(event)) isWinterMode = true
if (isWinterModeEndedEvent(event)) isWinterMode = false
if (isMaintenanceChargeStartedEvent(event)) isMaintenanceCharge = true
if (isMaintenanceChargeEndedEvent(event)) isMaintenanceCharge = false
events.push(event)
if (events.length > 300) {
events.shift()
}
} catch (e) {
console.error(e)
}
if (logRequests) {
logUnknownRequest(req)
}
if (forwardRequests) {
// forward request to logging1.powerrouter.com
axios.post('http://77.222.80.91/events.json', req.body, { headers: { Host: 'logging1.powerrouter.com' } })
.catch(({ response }) => {
console.error('Forwarding request to logging1.powerrouter.com failed', response && response.status)
})
}
res.type('json').status(201).send({ 'next-log-level': 2, status: 'ok' })
})
app.route('*').all((req, res) => {
if (logRequests) {
logUnknownRequest(req)
}
res.sendStatus(404)
})
app.listen(port, () => {
console.log('Power interface started')
})