Created
January 31, 2018 11:07
-
-
Save bushev/70168f078ccd41d1a7b8ca04b822e224 to your computer and use it in GitHub Desktop.
Macbook power state alerting [Node.js]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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