dec0ntamination/watcher.js

42 lines
1.7 KiB
JavaScript

import axios from 'axios'
import WebSocket from 'ws'
import fs from 'fs'
import exec from 'child_process'
let config = JSON.parse(fs.readFileSync('config.json', 'utf8'))
let ws = new WebSocket(`ws://${config.servers.deconz.url}:${config.servers.deconz.websocketPort}`)
ws.on('message', msg => {
let data = JSON.parse(msg)
try {
if (data.state) {
let device = config.wsDevices.find(device => device.uniqueId === data.uniqueid)
if (device) {
let influxPayload = `${device.name} ${device.influxKey}=${data.state[device.valueKey]?0:1}`
console.log(`${new Date().toString()} 👉🏻 Sending ${influxPayload}`)
axios.post(`${config.servers.influx.url}/api/v2/write?orgID=${config.servers.influx.orgId}&bucket=${config.servers.influx.bucket}`,
influxPayload,
{
headers: {
Authorization: `Token ${config.servers.influx.apiKey}`,
'Content-Type': 'text/plain'
}
}
).then(response => {
console.log(response.data)
}).catch(error => {
console.error(error)
})
if (device.openScript && data.state[device.valueKey]){
console.log("Running open script")
try {
console.log(exec.execSync(device.openScript).toString())
} catch (error) {
console.error(error)
}
}
}
}
} catch (error) {
console.error(error)
}
})