Skip to content

Instantly share code, notes, and snippets.

@funwithtriangles
Last active March 4, 2020 02:05
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 funwithtriangles/0f19c29b2b7572165cb5f8883b227e00 to your computer and use it in GitHub Desktop.
Save funwithtriangles/0f19c29b2b7572165cb5f8883b227e00 to your computer and use it in GitHub Desktop.
Raspberry Pi Node JS wifi and connection checker
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);
{
"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