Skip to content

Instantly share code, notes, and snippets.

@arrancorbett
Created June 17, 2020 13:17
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 arrancorbett/3cc7dcee9adfdbbc771d11e07c9e350e to your computer and use it in GitHub Desktop.
Save arrancorbett/3cc7dcee9adfdbbc771d11e07c9e350e to your computer and use it in GitHub Desktop.
unifi controller event listener
const UnifiEvents = require("unifi-events");
const axios = require("axios");
console.log("starting");
let unifi = new UnifiEvents({
controller: "https://<UNIFI CONTROLLER IP>:8443", // Required. The url of the UniFi Controller
username: "<USERNAME>", // Required.
password: "<PASSWORD>",
rejectUnauthorized: false, // Optional. Set to false if you don't have a valid SSL
listen: true // Optional. Set to false if you don't want to listen for events
});
// Listen for users and guests connecting to the network
unifi.on("EVT_WU_Disconnected", data => {
if (data.user == "<MAC ADDRESS>" || data.user == "<MAC ADDRESS>") {
console.log(data.user + " Disconnected");
postEvent(data, "disconnected");
}
});
// Listen for users and guests connecting to the network
unifi.on("EVT_WU_Connected", data => {
console.log(data);
if (data.user == "<MAC ADDRESS>" || data.user == "<MAC ADDRESS>") {
console.log(data.user + " Connected");
postEvent(data, "connected");
}
});
const API_ROOT = axios.create({
baseURL: "http://<INTERNAL API IP>:8888"
});
async function postEvent(payload, connectionType) {
let response = null;
try {
let postEventResp = await API_ROOT.post(
"/events/unifi/connection/" + connectionType,
{
timeout: 1000,
data: payload
}
);
response = postEventResp.data;
console.log(response);
} catch (err) {
console.log(err);
response = { state: "failed", data: err };
}
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment