GithubHelp home page GithubHelp logo

oznu / unifi-events Goto Github PK

View Code? Open in Web Editor NEW
53.0 6.0 19.0 119 KB

A Node.js module to listen for events from a UniFi Controller.

License: MIT License

JavaScript 100.00%
unifi unifi-controller api events nodejs npm-module websocket

unifi-events's Introduction

unifi-events

npm npm License

unifi-events is a Node.js module that allows you to listen for events from and call methods on the UniFi API (UniFi is Ubiquiti Networks wifi controller software).

Requirements

Installation

$ npm install unifi-events

Example

const Unifi = require('unifi-events')

const unifi = new Unifi({
  host: 'unifi',                        // The hostname or ip address of the unifi controller (default: 'unifi')
  port: 8443,                           // Port of the unifi controller (default: 8443)
  username: 'admin',                    // Username (default: 'admin').
  password: 'ubnt',                     // Password (default: 'ubnt').
  site: 'default',                      // The UniFi site to connect to (default: 'default').
  insecure: true,                       // Allow connections if SSL certificate check fails (default: false).
  unifios: false                        // For devices with UnifiOS turn this on
});

// Listen for any event
unifi.on('**', function (data) {
  console.log(this.event, data);
});

Events

unifi-events uses EventEmitter2 and namespaced events.

namespace ctrl

These events indicate the status of the connection to the UniFi controller

  • ctrl.connect - emitted when the connection to the controller is established
  • ctrl.disconnect - emitted when the connection to the controller is lost
  • ctrl.error -
  • ctrl.reconnect -

namespaces wu, wg, lu, ...

This JSON file shows all possible events: https://demo.ubnt.com/manage/locales/en/eventStrings.json?v=5.4.11.2 The prefix EVT_ gets stripped, the first underscore is replaced by the namespace separating dot, everything is converted to lower case. Some events such as EVT_AD_LOGIN (Admin Login) are not emitted by the UniFi Controller.

Example Wireless User events

  • wu.connected - Wireless User connected
  • wu.disconnected - Wireless User disconnected
  • wu.roam - Wireless User roamed from one AP to another
  • wu.roam_radio - Wireless User changed channel on the same AP

Example Wireless Guest Events

  • wg.connected - Wireless Guest connected
  • wg.disconnected - Wireless Guest disconnected
  • wg.roam - Wireless Guest roamed from one AP to another
  • wg.roam_radio - Wireless Guest changed channel on the same AP
  • wg.authorization_ended - Wireless Guest became unauthorised

Wildcard usage

Example listing for events on Guest Wireless networks only:

unifi.on('wg.*', function (data) {
  console.log(this.event, data);
})

Example listening for connected events on all network types:

unifi.on('*.connected', function (data) {
  console.log(this.event, data);
});

Methods

connect()

Connect to the UniFi controller. Is called in the constructor, so normally you don't need to call it (except if you want to re-establish a connection that was closed before).

close()

Closes the connection to the UniFi controller

UniFi API Methods

Following methods operate on the configured site. The path gets prefixed with https://<host>:<port>/api/s/<site>/ if it does not start with a slash, otherwise it gets prefixed with https://<host>:<port>. To explore available API endpoints you can use the UniFi-API-browser.

These methods are returning a promise.

get(path)

Do a HTTP GET on the API.

Examples:

  • Get a list of all clients
unifi.get('stat/sta').then(console.log);
  • Get infos of a specific client
unifi.get('stat/user/<mac>').then(console.log);
  • Get alarms
unifi.get('list/alarm').then(console.log);
  • Get wireless network IDs
unifi.get('rest/wlanconf').then(res => {
    res.data.forEach(wlan => {
        console.log(wlan.name, wlan._id);
    });
});
  • Get device IDs
unifi.get('stat/device').then(res => {
     res.data.forEach(dev => {
        console.log(dev.name, dev._id);
     });
});

del(path)

Do a HTTP DELETE on the API.

post(path, body)

Do a HTTP POST on the API.

Examples:

  • Enable all LEDs of all APs
unifi.post('set/setting/mgmt', {led_enabled: true}).then(console.log);
  • Disable a WLAN
unifi.post('upd/wlanconf/<wlan_id>', {enabled: false}).then(console.log);

put(path, body)

Do a HTTP PUT on the API.

Examples:

  • Enable LED of AP
unifi.put('rest/device/<device_id>', {led_override: 'on'}).then(console.log);

License

unifi-events's People

Contributors

dependabot[bot] avatar hobbyquaker avatar jmara avatar kienz avatar muxa avatar oznu avatar steffjenl avatar tickez avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

unifi-events's Issues

TypeError: Cannot read property 'prototype' of undefined

When I try to use the example script with the example server or my local unifi-manager, it throws an error. (Node v8.11.4)

8118-3D-8E-0F:unifi$ node -v
v8.11.4
8118-3D-8E-0F:unifi$ node main.js
/Users/unifi/node_modules/request-promise-core/configure/request2.js:34
    var originalInit = options.request.Request.prototype.init;
                                               ^

TypeError: Cannot read property 'prototype' of undefined
    at module.exports (/Users/unifi/node_modules/request-promise-core/configure/request2.js:34:48)
    at Object.<anonymous> (/Users/unifi/node_modules/request-promise/lib/rp.js:28:1)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/unifi/node_modules/unifi-events/index.js:4:12)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/unifi/Documents/development/unifi/main.js:1:83)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)

Keeps disconnecting

I'm trying to connect to a UDM. For that I've updated the web socket url from

`wss://${this.controller.host}/wss/s/${this.opts.site}/events`

to

`wss://${this.controller.host}/proxy/network/wss/s/${this.opts.site}/events`

in the source code of the library.

When trying to connect, it connects and then disconnected immediately:

UniFi Events: Connected (1) - wss://192.168.1.1/proxy/network/wss/s/default/events
UniFi Events: Disconnected (1) - Retry in 5000ms

And then it keeps trying and disconnects again.

I've added the following code to be able to log these events:

unifi.on('websocket-status', (data) => {
  console.log(data)
})

I have tested connecting to UDM using https://github.com/NickWaterton/Unifi-websocket-interface and it worked, so I know the connection to UDM works.

Any suggestions?

client alias

Great module, thanks! Is there any way to get events with the client aliases instead of the MAC address or hostname? Or some way to retrieve the MAC > alias index?

Help: Not working

I have a UCK Gen2 with 5.11.39 installed. Also current node version on a Pi3 b. Edited the file slack-incoming-webhook.js with my controller IP and also a Telegram Webhook. Webhook itself works like a charm.

Started this with forever telegram-incoming-webhook.js and it is running without errors.

But I am not getting any message even though the Webhook and the login credentials are correct. What am I doing wrong?

Here is my .js:

'use strict'

/*
 * Send notifications to a Slack channel when devices connect or disconnect from the UniFi network.
 * Setup an incoming webhook using slack: https://my.slack.com/services/new/incoming-webhook/
 */

const rp = require('request-promise')
const UnifiEvents = require('../')

// Enter the webhook url provided by Slack here
let webhook = 'https://api.telegram.org/API_KEY/sendMessage?chat_id=XXXXX&parse_mode=html&text=test'

let sendNotification = (text) => {
  return rp.post(webhook, {
    json: {
      text: text,
      username: 'UniFi Notify'
    }
  })
  .then(() => {
    console.log(text)
  })
  .catch((err) => {
    console.log(err)
  })
}

let unifi = new UnifiEvents({
  controller: 'https://10.0.0.2:8443',
  username: 'USER',
  password: 'PASS',
  rejectUnauthorized: 'false',
  site: 'default',
  listen: 'true'
})

unifi.on('ready', () => {
  console.log('Connected To UniFi Controller')
})

unifi.on('connected', (data) => {
  unifi.getAp(data.ap).then((ap) => {
    sendNotification(`Device *${data.hostname}* has Connected to *${data.ssid}* (${ap.name}) on channel ${data.channel}.`)
  })
})

unifi.on('disconnected', (data) => {
  unifi.getAp(data.ap).then((ap) => {
    sendNotification(`Device *${data.hostname}* has Disconnected from *${data.ssid}* (${ap.name})`)
  })
})

Many Disconnects From Clients

In my network I have a lot of disconnects - don’t know whether it is related to bad coverage of UAP or this plugin. That means I also get a bunch of messages via telegram which I use as a notification bot with this script when new guests connect or disconnect.

Anyway, is there a possibility of setting some kind of threshold or delay? E.g. monitor for new connected clients in a range of 5 minutes and only then notify that a new device has been connected?

Issue with / prepending

Hi. Thanks for the library, just thought i'd show you an error

function _url(path)

line 160 should be changed from

return${this.controller.href}proxy/network/${path};

to
return${this.controller.href}proxy/network${path};

and 166 (this is obviously just an example)

const url = this.controller.href.slice(0,-1) return${url}${path}
instead of
return${this.controller.href}${path};

Sorry about the formatting...

Stopped working: RequestError

Hi @oznu,

I really love your work, especially this one and docker-homebridge.

I just recognised that this wonderful event handler unexpectedly has stopped working. The only thing I am aware of is a apt-get update && apt-get upgrade.

I would really appreciate your help! Node is v13.3.0.

pi@xxx:~/node_modules/unifi-events $ node telegram-notification.js
RequestError: TypeError [ERR_UNESCAPED_CHARACTERS]: Request path contains unescaped characters
    at new RequestError (/home/pi/node_modules/request-promise-core/lib/errors.js:14:15)
    at Request.plumbing.callback (/home/pi/node_modules/request-promise-core/lib/plumbing.js:87:29)
    at Request.RP$callback [as _callback] (/home/pi/node_modules/request-promise-core/lib/plumbing.js:46:31)
    at self.callback (/home/pi/node_modules/request/request.js:185:22)
    at Request.emit (events.js:219:5)
    at Request.start (/home/pi/node_modules/request/request.js:753:10)
    at Request.write (/home/pi/node_modules/request/request.js:1497:10)
    at end (/home/pi/node_modules/request/request.js:549:18)
    at Immediate._onImmediate (/home/pi/node_modules/request/request.js:578:7)
    at processImmediate (internal/timers.js:444:21) {
  name: 'RequestError',
  message: 'TypeError [ERR_UNESCAPED_CHARACTERS]: Request path contains unescaped characters',
  cause: TypeError [ERR_UNESCAPED_CHARACTERS]: Request path contains unescaped characters
      at new ClientRequest (_http_client.js:147:13)
      at Object.request (https.js:308:10)
      at Request.start (/home/pi/node_modules/request/request.js:751:32)
      at Request.write (/home/pi/node_modules/request/request.js:1497:10)
      at end (/home/pi/node_modules/request/request.js:549:18)
      at Immediate._onImmediate (/home/pi/node_modules/request/request.js:578:7)
      at processImmediate (internal/timers.js:444:21) {
    code: 'ERR_UNESCAPED_CHARACTERS'
  },
  error: TypeError [ERR_UNESCAPED_CHARACTERS]: Request path contains unescaped characters
      at new ClientRequest (_http_client.js:147:13)
      at Object.request (https.js:308:10)
      at Request.start (/home/pi/node_modules/request/request.js:751:32)
      at Request.write (/home/pi/node_modules/request/request.js:1497:10)
      at end (/home/pi/node_modules/request/request.js:549:18)
      at Immediate._onImmediate (/home/pi/node_modules/request/request.js:578:7)
      at processImmediate (internal/timers.js:444:21) {
    code: 'ERR_UNESCAPED_CHARACTERS'
  },
  options: {
    json: {
      text: '✅Connected to <b>xxx</b>!%0A%0A<b>Device</b>: xxx%0A<b>AP:</b> AP Pro xx%0A<b>Channel:</b> 11',
      username: 'UniFi Notify'
    },
    uri: 'https://api.telegram.org/xxx/sendMessage?chat_id=xxx&parse_mode=html&text=✅Connected to <b>xxx</b>!%0A%0A<b>Device</b>: xxx%0A<b>AP:</b> AP Pro xx%0A<b>Channel:</b> 11',
    method: 'POST',
    callback: [Function: RP$callback],
    transform: undefined,
    simple: true,
    resolveWithFullResponse: false,
    transform2xxOnly: false
  },
  response: undefined
}

This is my .js:

const rp = require('request-promise')
const UnifiEvents = require('unifi-events')

// Enter the webhook url provided by Slack here
let webhook = 'https://api.telegram.org/xxx/sendMessage?chat_id=xxx&parse_mode=html&text='

let sendNotification = (text) => {
  return rp.post(webhook + text, {
    json: {
      text: text,
      username: 'UniFi Notify'
    }
  })
  .then(() => {
    console.log(text)
  })
  .catch((err) => {
    console.log(err)
  })
}

let unifi = new UnifiEvents({
  controller: 'https://10.0.0.2:8443',  // Required. The url of the UniFi Controller
  username: 'xxx',               // Required.
  password: 'xxx',                 // Required.
  site: 'default',                      // Optional. The UniFi site to connect to, if not set will use the default site.
  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
})

unifi.on('ready', () => {
  console.log('Connected To UniFi Controller')
})

// Listen for users and guests connecting to the network
//unifi.on('connected', (data) => {
//  console.log(data)
//})

// Listen for users and guests disconnecting from the network
//unifi.on('disconnected', (data) => {
//  console.log(data)
//})

unifi.on('EVT_WG_Connected', (data) => {
  unifi.getAp(data.ap).then((ap) => {
    sendNotification(`✅Connected to <b>${data.ssid}</b>!%0A%0A<b>Device</b>: ${data.hostname}%0A<b>AP:</b> ${ap.name}%0A<b>Channel:</b> ${data.channel}`)
  })
})

unifi.on('EVT_WG_Disconnected', (data) => {
  unifi.getAp(data.ap).then((ap) => {
    sendNotification(`🚫<b>${data.hostname}</b> disconnected from <b>${data.ssid}</b> (${ap.name})`)
  })
})

// Listen for any event
//unifi.on('event', (data) => {
//  console.log(data)
//})

Listen to all sites?

Amazing project!

Is it possible to listen all sites running on the same controller? Or do we need to spin separate instances for each site in order to achieve this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.