UNPKG

esp8266-configurator

Version:

This module allows you to fetch configuration for an ESP8266 device on network connection.

115 lines (109 loc) 3.31 kB
'use strict'; const bunyan = require("bunyan"); var db ; const log = bunyan.createLogger({ name: "ESP8266Configurator-dao", src: false, streams: [ { level:'debug', stream: process.stdout } ] }); const self = module.exports = { configure: (_db_) => { db = _db_; }, saveDevice: (device, callback, errorCallback) => { db.devices.find({"deviceId": device.deviceId}, (err, devices) => { if(devices.length == 0) { db.devices.insert(device, function (err) { if(err) { log.error("Error saving device ", err); errorCallback(); } else { callback(); } }); } else { db.devices.remove({ deviceId: device.deviceId }, {}, function (err, numRemoved) { log.warn("Device already found, updating ", device); self.saveDevice(device, callback, errorCallback); }); } }); }, saveDeviceConfiguration: (device, callback, errorCallback) => { db.devices.find({ "deviceId": device.deviceId}, (err, devices) => { if(devices.length > 0) { devices[0].configuration = device.configuration; var newDevice = devices[0]; newDevice.configuration = device.configuration; console.log(newDevice); db.devices.update({"deviceId": device.deviceId}, newDevice, (error, replaced) => { if(error) { errorCallback(error); } else { log.debug("Updated new configuration for device ", devices[0]); callback(replaced); } }); } }); }, saveGlobalConfiguration: (config, callback, errorCallback) => { console.log("Trying to save configuration ", config); db.config.find({"key": config.key, "deviceId": config.deviceId}, (err, configs) => { if(configs.length == 0) { db.config.insert(config, function (err) { if(err) { log.error("Error saving configuration ", err); errorCallback(); } else { callback(); } }); } else { db.config.update({"deviceId":config.deviceId},{"key": config.key, "value": config.value, "deviceId":config.deviceId}, (error, replaced) => { if(error) { log.error("Error updating config to new one", error); errorCallback(); } else { log.info("Updated config ", config) callback(); } }); } }); }, fetchDevices: (callback, errorCallback) => { db.devices.find({ }, function (err, devices) { if(err) { log.error("Error fetching device list", err); errorCallback(); } else { callback(devices); } }); }, findDeviceConfiguration: (device, callback, errorCallback) => { db.devices.find({"deviceId": device}, (err, configs) => { log.debug("Found configuration for device ", device, configs); if(configs.length == 0) { errorCallback("Configuration not found"); } else { callback(configs[0]); } }); }, findGlobalConfiguration: (callback, errorCallback) => { db.config.find({}, (err, configs) => { if(err) { errorCallback(err); } else { callback(configs); } }); } };