Skip to content

Instantly share code, notes, and snippets.

@dishbreak
Last active October 16, 2018 05:56
Show Gist options
  • Save dishbreak/23fb0e0944d0c9f5ec3215aaab6e6bcb to your computer and use it in GitHub Desktop.
Save dishbreak/23fb0e0944d0c9f5ec3215aaab6e6bcb to your computer and use it in GitHub Desktop.

Wifi Logger Webtask

This is intended to work with the Google Wifi applet on If This Then That (IFTTT) to log when specific devices connect and disconnect from the wifi network. It exposes two endpoints, both POSTs.

Note: We calculate connection/disconnection time server-side. This isn't the best way to do this, but this is for fun, after all.

POST /start/:deviceName

This marks the start of a connection of a device with name deviceName.

POST /end/:deviceName

This marks the end of a connection for a device with name deviceName.

To use this, create a webtask, add npm package mongodb at version 2.2.33, and paste in the contents of the JS file. Set the Google Wifi channels to post to the respective endpoints for start and end.

Configuring

You'll need to set the following secrets in your webtask editor:

  • mongo.uri - A mongo connection string pointing to a database. (mLab is a great place to get a sandbox hosted db).
  • mongo.collection - The collection within the database to use.
var express = require('express');
var Webtask = require('webtask-tools');
var MongoClient = require('mongodb').MongoClient;
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
function timestamp() {
return Math.floor(new Date() / 1000)
}
function writeToMongo(mongo_uri, collection, data, callback) {
MongoClient.connect(mongo_uri, function (error, db) {
if (error) {
return callback(error);
}
db.collection(collection).insertOne(data, function(err) {
if (err) {
console.error("Error writing to db: " + err);
return callback(err);
}
return callback(null)
})
return callback(null);
});
}
function toDocument(device_name, event, time) {
return {
"device_name": device_name,
"event": event,
"time": time
}
}
app.get('/', function (req, res) {
res.sendStatus(200);
});
app.use(function (req, res, next) {
let incoming_time = timestamp();
console.info("Received request at " + incoming_time);
req.wifilogger = {};
req.wifilogger.incoming_time = incoming_time;
next();
})
app.post("/start/:deviceName", function (req, res) {
console.info("Google Wifi saw " + req.params.deviceName + " connect");
writeToMongo(
req.webtaskContext.secrets['mongo.uri'],
req.webtaskContext.secrets['mongo.collection'],
toDocument(req.params.deviceName, "CONNECTED", req.wifilogger.incoming_time),
function (error) {
if (error) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment