Skip to content

Instantly share code, notes, and snippets.

@nahtnam
Last active October 29, 2019 06:53
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 nahtnam/593f6064f4ecf5b6c420f6614ed1db5c to your computer and use it in GitHub Desktop.
Save nahtnam/593f6064f4ecf5b6c420f6614ed1db5c to your computer and use it in GitHub Desktop.
MagicMirror script to turn on the screen when your phone is connected to the WiFi
const shell = require('shelljs');
const offlineTime = 300; // 5 minutes
const exec = cmd => shell.exec(cmd, { silent: true });
let state = true;
let lastOnlineAt = Date.now();
const ips = ['INSERT IP 1 HERE', 'INSERT MORE IF YOU NEED'];
exec('vcgencmd display_power 1'); // turn on the monitor to make sure the state is correct
const checkStatus = () => {
// turn off from 12AM to 8AM
const date = new Date();
const hour = date.getHours();
if (hour < 8) {
return false;
}
// check all of the ips
for (let ip of ips) {
const isUp = exec(`nmap -sP ${ip}`).includes('Host is up');
if (isUp) {
lastOnlineAt = Date.now();
}
}
// if they haven't been online for `offlineTime`, turn off the monitor
if ((Date.now() - lastOnlineAt) > offlineTime * 1000) {
return false;
}
// otherwise keep it on
return true;
};
const loop = () => {
try {
const enable = checkStatus();
if (enable && !state) {
exec('vcgencmd display_power 1');
state = true;
}
if (!enable && state) {
exec('vcgencmd display_power 0');
state = false;
}
} catch (err) {
console.log(err);
}
setTimeout(loop, 30000);
};
loop();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment