Skip to content

Instantly share code, notes, and snippets.

@bushev
Created January 31, 2018 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bushev/70168f078ccd41d1a7b8ca04b822e224 to your computer and use it in GitHub Desktop.
Save bushev/70168f078ccd41d1a7b8ca04b822e224 to your computer and use it in GitHub Desktop.
Macbook power state alerting [Node.js]
'use strict';
const exec = require('child_process').exec;
const https = require('https');
const API_KEY = `*****`;
const PHONE_NUMBER = `7920*****`;
let state = 'Unknown';
setInterval(checkStatusAndUpdate, 500);
function checkStatusAndUpdate() {
exec('pmset -g ps | head -1', (err, stdout, stderr) => {
if (err) {
console.error(`Error: ${err}`);
return;
}
if (stderr) {
console.error(`stderr: ${stderr}`);
return;
}
let newState;
if (stdout.indexOf('AC Power') > -1) {
newState = `AC Power`;
} else if (stdout.indexOf('Battery Power') > -1) {
newState = `Battery Power`;
} else {
console.log(`stdout: ${stdout}`);
newState = `Unknown`;
}
if (state !== newState) {
notifyStateChanged({
from: state,
to: newState
});
state = newState;
}
});
}
function notifyStateChanged(options) {
const msg = `State: ${options.from} -> ${options.to}`;
console.log(msg);
https.request({
hostname: 'sms.ru',
port: 443,
path: `/sms/send?api_id=${API_KEY}&to=${PHONE_NUMBER}&msg=${encodeURIComponent(msg)}&json=1`,
method: 'GET',
headers: {'Content-Type': 'application/json'}
}, res => {
res.setEncoding('utf-8');
res.on('data', data => {
console.log(data);
});
}).on('error', err => {
console.log('problem with request: ' + err.message);
}).end();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment