zigbee2mqtt/lib/util/settings.js

45 lines
1.2 KiB
JavaScript
Raw Normal View History

2018-04-25 10:29:03 -07:00
const YAWN = require('yawn-yaml/cjs');
const fs = require('fs');
2018-05-11 20:04:15 -07:00
const data = require('./data');
2018-05-12 01:58:06 -07:00
const file = data.joinPath('configuration.yaml');
2018-04-25 10:29:03 -07:00
let yawn = read();
2018-04-18 09:25:40 -07:00
function write() {
2018-04-25 10:29:03 -07:00
fs.writeFileSync(file, yawn.yaml);
2018-04-18 09:25:40 -07:00
}
function read() {
2018-04-25 10:29:03 -07:00
return new YAWN(fs.readFileSync(file, 'utf8'));
2018-04-18 09:25:40 -07:00
}
2018-04-25 10:29:03 -07:00
function addDevice(id) {
if (!yawn.json.devices) {
const first = "\n" +
2018-04-25 10:29:03 -07:00
"# List of devices, automatically updates when new devices join, E.G.:\n" +
"# '0x00158d0001d8e1d2':\n" +
"# friendly_name: bedroom_switch # Friendly name to be used in MQTT topic\n" +
"# retain: true # Retain MQTT messages\n" +
"devices:\n" +
` '${id}':\n` +
` friendly_name: '${id}'\n` +
` retain: false`;
yawn.yaml += first;
} else {
const devices = yawn.json.devices;
devices[id] = {friendly_name: id, retain: false};
yawn.json = {...yawn.json, devices: devices};
}
write();
yawn = read();
}
2018-04-18 09:25:40 -07:00
module.exports = {
2018-04-25 10:29:03 -07:00
get: () => yawn.json,
2018-04-18 11:53:22 -07:00
write: () => write(),
2018-04-25 10:29:03 -07:00
getDevice: (id) => yawn.json.devices ? yawn.json.devices[id] : false,
addDevice: (id) => addDevice(id),
2018-04-18 09:25:40 -07:00
}