Raspberry Pi Node JS wifi and connection checker
This file contains 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
const fs = require('fs') | |
const Wifi = require('rpi-wifi-connection') | |
const internetAvailable = require('internet-available') | |
const logIntervalMs = 1000 // 1000 * 60 * 10 | |
const errIntervalMs = 5000 | |
let lastLog = Date.now() | |
const wifi = new Wifi() | |
const logToFile = ({ text, fileName = 'log.txt' }) => { | |
const date = new Date() | |
const dateString = `${date.toLocaleDateString('en-UK')} ${date.toLocaleTimeString()}` | |
const logLine = `${dateString}: ${text}\n` | |
console.log(`logging ${logLine}`) | |
fs.appendFile(`log/${fileName}`, logLine, err => { | |
if (err) console.error('Cant write file!') | |
}) | |
} | |
setInterval(() => { | |
console.log('getting status') | |
wifi.getStatus().then(status => { | |
console.log(status) | |
if (status.ssid) { | |
internetAvailable() | |
.then(() => { | |
// Do a normal log every 10 minutes just to prove the script hasn't died | |
const now = Date.now() | |
if (now > lastLog + logIntervalMs) { | |
logToFile({ text: `${status.ssid}` }) | |
lastLog = now | |
} | |
}) | |
.catch(() => { | |
logToFile({ text: `NO INTERNET: ${status.ssid}`, fileName: 'error.txt' }) | |
}) | |
} else { | |
logToFile({ text: `NO WIFI`, fileName: 'error.txt' }) | |
} | |
}) | |
}, errIntervalMs); |
This file contains 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
{ | |
"name": "wifi-test", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"internet-available": "^1.0.0", | |
"rpi-wifi-connection": "^1.0.14" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment