Improved manual battery system in meshcore.js

Ylian Saint-Hilaire committed Aug 31, 2020 at 16:45 UTC df47f0a068ae8cbb18e77aeca6ecdea4af868c0d
1 file changed +12 -13
agents/meshcore.js
+12 -13
@@ -251,27 +251,27 @@ function createMeshCore(agent) {
251 return (svc);
252 }
253
254 - // TODO: Monitor the file 'batterystate.txt' in the agent's folder and sends battery update when this file is changed.
255 - /*
256 - if (require('fs').existsSync(process.cwd() + 'batterystate.txt')) {
254 + // Monitor the file 'batterystate.txt' in the agent's folder and sends battery update when this file is changed.
255 + if ((require('fs').existsSync(process.cwd() + 'batterystate.txt')) && (require('fs').watch != null)) {
256 // Setup manual battery monitoring
258 - sendConsoleText('Manual Battery State Monitor');
259 - require('MeshAgent')._batteryFileWatcher = require('fs').watch(process.cwd(), function (a) {
257 + require('MeshAgent')._batteryFileWatcher = require('fs').watch(process.cwd(), function () {
258 if (require('MeshAgent')._batteryFileTimer != null) return;
259 require('MeshAgent')._batteryFileTimer = setTimeout(function () {
262 - sendConsoleText('Battery State Changed');
260 try {
261 require('MeshAgent')._batteryFileTimer = null;
265 - var data = require('fs').readFileSync(process.cwd() + 'batterystate.txt').toString();
266 - if (data.length < 10) {
262 + var data = null;
263 + try { data = require('fs').readFileSync(process.cwd() + 'batterystate.txt').toString(); } catch (ex) { }
264 + if ((data != null) && (data.length < 10)) {
265 data = data.split(',');
268 - if ((data.length == 2) && ((data[0] == 'ac') || (data[0] == 'dc'))) { require('MeshAgent').SendCommand({ action: 'battery', state: data[0], level: parseInt(data[1]) }); }
266 + if ((data.length == 2) && ((data[0] == 'ac') || (data[0] == 'dc'))) {
267 + var level = parseInt(data[1]);
268 + if ((level >= 0) && (level <= 100)) { require('MeshAgent').SendCommand({ action: 'battery', state: data[0], level: level }); }
269 + }
270 }
271 } catch (ex) { }
272 }, 1000);
273 });
274 } else {
274 - */
275 // Setup normal battery monitoring
276 if (require('identifiers').isBatteryPowered && require('identifiers').isBatteryPowered()) {
277 require('MeshAgent')._battLevelChanged = function _battLevelChanged(val) {
@@ -288,14 +288,13 @@ function createMeshCore(agent) {
288 if (status == 0) {
289 require('power-monitor').removeListener('acdc', this._powerChanged);
290 require('power-monitor').removeListener('batteryLevel', this._battLevelChanged);
291 - }
292 - else {
291 + } else {
292 require('power-monitor').on('acdc', this._powerChanged);
293 require('power-monitor').on('batteryLevel', this._battLevelChanged);
294 }
295 });
296 }
298 - //}
297 + }
298
299
300 /*