2022-09-04 06:26:51 +00:00
|
|
|
/**
|
|
|
|
* 树莓派状态 JSON 数据接口
|
|
|
|
*/
|
|
|
|
require('dotenv').config()
|
|
|
|
const fs = require('fs')
|
|
|
|
const http = require('http')
|
|
|
|
const hostname = require('os').hostname()
|
|
|
|
const exec = require('child_process').exec
|
|
|
|
const MEMINFO_FILE_PATH = '/proc/meminfo'
|
|
|
|
const TEMPERATURE_FILE_PATH = '/sys/class/thermal/thermal_zone0/temp'
|
|
|
|
const server = http.createServer(function (request, response) {
|
|
|
|
response.setHeader('Access-Control-Allow-Origin', '*')
|
2022-09-05 00:12:05 +00:00
|
|
|
response.setHeader('Access-Control-Allow-Methods', 'GET')
|
2022-09-05 00:11:23 +00:00
|
|
|
// response.setHeader('Access-Control-Allow-Methods', 'HEAD,GET,POST,OPTIONS,PATCH,PUT,DELETE')
|
|
|
|
// response.setHeader('Access-Control-Allow-Headers', 'Origin,X-Requested-With,Authorization,Content-Type,Accept,Z-Key')
|
2022-09-04 06:26:51 +00:00
|
|
|
response.setHeader('Content-Type', 'application/json')
|
|
|
|
try {
|
2022-09-04 23:15:14 +00:00
|
|
|
const temp_string = Number(fs.readFileSync(TEMPERATURE_FILE_PATH))
|
2022-09-04 06:26:51 +00:00
|
|
|
const meminfo_string = String(fs.readFileSync(MEMINFO_FILE_PATH))
|
|
|
|
const meminfo_total = meminfo_string.match(/MemTotal\:\s+(\d+) kB/)
|
|
|
|
const meminfo_available = meminfo_string.match(/MemAvailable\:\s+(\d+) kB/)
|
|
|
|
const result = {
|
|
|
|
hostname,
|
|
|
|
cpu: {
|
2022-09-04 23:18:21 +00:00
|
|
|
temperature: temp_string / 1000,
|
2022-09-04 06:26:51 +00:00
|
|
|
},
|
|
|
|
memory: {
|
2022-09-04 23:18:21 +00:00
|
|
|
total: meminfo_total[1] / 1024,
|
|
|
|
available: meminfo_available[1] / 1024,
|
2022-09-04 06:26:51 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
exec("cat /proc/stat |grep cpu |tail -1|awk '{print ($5*100)/($2+$3+$4+$5+$6+$7+$8+$9+$10)}'|awk '{print 100 - $1}'", (err, stdout, stderr) => {
|
|
|
|
result.cpu.load = Number((stdout / 100).toFixed(4))
|
|
|
|
response.end(JSON.stringify(result))
|
|
|
|
})
|
|
|
|
} catch (error) {
|
|
|
|
response.statusCode = 500
|
|
|
|
response.end(JSON.stringify({ error }))
|
|
|
|
}
|
|
|
|
})
|
|
|
|
const port = process.env.PORT || 3000
|
2022-09-04 08:29:49 +00:00
|
|
|
const host = process.env.HOST || 'localhost'
|
2022-09-04 10:37:13 +00:00
|
|
|
server.listen(port, host, () => console.log(`rpi status http server is running at http://${host}:${port}`))
|