All Projects → jens-maus → node-unifi

jens-maus / node-unifi

Licence: MIT license
NodeJS class for querying/controlling a UniFi-Controller (www.ubnt.com)

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to node-unifi

udm-patches
Contains onboot.d setup scripts and wrappers for custom OpenVPN client
Stars: ✭ 42 (-54.35%)
Mutual labels:  unifi, ubiquiti, udm, udm-pro
udm-host-records
Scripts to list, add, update, and remove host records in the Ubiquiti UniFI Dream Machine DNS forwarder.
Stars: ✭ 109 (+18.48%)
Mutual labels:  unifi, ubiquiti, udm, udm-pro
udm-utilities
A collection of things I have made to make the Unifi Dream Machine more useful
Stars: ✭ 2,228 (+2321.74%)
Mutual labels:  unifi, ubiquiti, udm, udm-pro
unifiZabbix
Zabbix templates to monitor pretty much all Unifi devices
Stars: ✭ 66 (-28.26%)
Mutual labels:  unifi, ubiquiti, udm, udm-pro
unpoller
Application: Collect ALL UniFi Controller, Site, Device & Client Data - Export to InfluxDB or Prometheus
Stars: ✭ 1,613 (+1653.26%)
Mutual labels:  unifi, ubiquiti, unifi-controller, udm
udm-kernel-tools
Tools for bootstrapping custom kernels on the UniFi Dream Machine
Stars: ✭ 211 (+129.35%)
Mutual labels:  unifi, udm, udm-pro
UFiber.Configurator
UFiber Configuration Tool
Stars: ✭ 44 (-52.17%)
Mutual labels:  unifi, ubiquiti, unifi-controller
ubios-cert
Manage SSL / TLS certificates with acme.sh (Let's Encrypt, ZeroSSL) for Ubiquiti UbiOS firmwares
Stars: ✭ 17 (-81.52%)
Mutual labels:  unifi, ubiquiti, unifi-controller
unifi-pfsense
A script that installs the UniFi Controller software on pfSense and other FreeBSD systems
Stars: ✭ 617 (+570.65%)
Mutual labels:  unifi, ubiquiti, unifi-controller
addon-unifi
UniFi Network Application - Home Assistant Community Add-ons
Stars: ✭ 190 (+106.52%)
Mutual labels:  unifi, ubiquiti, unifi-controller
split-vpn
A split tunnel VPN script for Unifi OS routers (UDM, UXG, UDR) with policy based routing.
Stars: ✭ 589 (+540.22%)
Mutual labels:  udm, udm-pro
homebridge-unifi-occupancy-sensor
An occupancy sensor for Homebridge and UniFi
Stars: ✭ 71 (-22.83%)
Mutual labels:  unifi, unifi-controller
ubnt-cloudflared
Install Cloudflare's DNS proxy on UBNT gateways
Stars: ✭ 22 (-76.09%)
Mutual labels:  unifi, ubiquiti
pyunifi
unifi-sdn.ubnt.com/
Stars: ✭ 186 (+102.17%)
Mutual labels:  unifi, ubiquiti
ntopng-udm
ntopng Docker image for the UDM base and UDM pro
Stars: ✭ 147 (+59.78%)
Mutual labels:  ubiquiti, udm
unifi2mqtt
Connect Ubiquiti UniFi controller to MQTT 📡
Stars: ✭ 66 (-28.26%)
Mutual labels:  unifi, ubiquiti
unifi-controllable-switch
TOUGHswitch firmware to integrate with the UniFi Controller (experimental).
Stars: ✭ 24 (-73.91%)
Mutual labels:  unifi-controller
pyunifiprotect
Unofficial UniFi Protect Python API and CLI
Stars: ✭ 57 (-38.04%)
Mutual labels:  ubiquiti
monitoring-utilities
Miscellaneous tools and utilities for collection, manipulation, and logging of various metrics
Stars: ✭ 16 (-82.61%)
Mutual labels:  ubiquiti
unifi2mqtt
A unifi controller device status to mqtt bridge process
Stars: ✭ 14 (-84.78%)
Mutual labels:  unifi


node-unifi

Build NPM version Downloads License Donate GitHub stars

NPM

Node-UniFi is a NodeJS module that allows to query/control UniFi devices via the official UniFi-Controller API. It is developed to be compatible to the UniFi-Controller API version starting with v4.x.x up to v7.x.x

Features

  • Support all UniFi-Controller API features introduced with v4.x.x, v5.x.x, v6.x.x, v7.x.x.
  • Support CloudKey Gen1, CloudKey Gen2, UnifiOS-based UDM-Pro Controller as well as self-hostd UniFi controller software.
  • Returns all data in well-defined JSON parsable strings/objects.
  • Use of modern axios-based nodejs http library.
  • API functions returning NodeJS Promises for modern nodejs uses via async/await or then()/catch().
  • Support for WebSocket-based push notifications of UniFi controllers for listening for state/object changes using EventEmitter-based nodejs functionality.

Requirements

  • Installed UniFi-Controller version v4, v5, v6, or v7 CloudKey Gen1, Gen2 or UDM-Pro.
  • Direct network connectivity between the application using node-unifi and the host:port (normally TCP port 443 or 8443) where the UniFi controller is running on.
  • Use of local accounts for authentication; not UniFi Cloud accounts nor 2FA.
  • Node.js version >= 14.x

Installation

node-unifi can be installed using the following npm command:

npm install node-unifi

Examples

node-unifi has been designed to be used quite straight forward and without introducing ackward language constructs. The following example should give a brief introduction on how to use node-unifi in your own applications using its Promises-based API interface:

const Unifi = require('node-unifi');
const unifi = new Unifi.Controller({'<HOSTNAME>', '<PORT>', sslverify: false});

(async () => {
  try {
    // LOGIN
    const loginData = await unifi.login('<USERNAME>', '<PASSWORD>');
    console.log('login: ' + loginData);

    // GET SITE STATS
    const sites = await unifi.getSitesStats();
    console.log('getSitesStats: ' + sites[0].name + ':' + sites.length);
    console.log(JSON.stringify(sites));

    // GET SITE SYSINFO
    const sysinfo = await unifi.getSiteSysinfo();
    console.log('getSiteSysinfo: ' + sysinfo.length);
    console.log(JSON.stringify(sysinfo));

    // GET CLIENT DEVICES
    const clientData = await unifi.getClientDevices();
    console.log('getClientDevices: ' + clientData.length);
    console.log(JSON.stringify(clientData));

    // GET ALL USERS EVER CONNECTED
    const usersData = await unifi.getAllUsers();
    console.log('getAllUsers: ' + usersData.length);
    console.log(JSON.stringify(usersData));

    // LOGOUT
    const logoutData = await unifi.logout();
    console.log('logout: ' + JSON.stringify(logoutData));
  } catch (error) {
    console.log('ERROR: ' + error);
  }
})();

Please note that every unifi.XXXXX() function returns a Promise, thus async/await as well as .then()/.catch() can be used accordingly.

Event-Emitter WebSockets Interface

Since version 2.0.0 node-unifi supports (thanks to unifi-axios-events) the WebSocket interface of a UniFi controller. This new interface allows to listen for events using unifi.listen() and automatically receive events as soon as the UniFi controller sends them out via its WebSocket functionality. For receiving these events in a nodejs-compatible way node-unifi uses internally EventEmitter2 which allows to execute actions based on event filters defined by unifi.on(...).

An example on how to use this EventEmitter-based functionality of node-unifi to immediately receive state changes rather than regularly having to poll a unifi controller for changes can be seen here:

const Unifi = require('node-unifi');
const unifi = new Unifi.Controller({'<HOSTNAME>', '<PORT>', sslverify: false});

(async () => {
  try {
    // LOGIN
    const loginData = await unifi.login('<USERNAME>', '<PASSWORD>');
    console.log('login: ' + loginData);

    // LISTEN for WebSocket events
    const listenData = await unifi.listen();
    console.log('listen: ' + listenData);

    // Listen for alert.client_connected
    unifi.on('alert.client_connected', function (data) {
      const ts = new Date(data[0].timestamp).toISOString();
      console.log(`${ts} - ${this.event}: ${data[0].parameters.CLIENT.id} (${data[0].parameters.CLIENT.name})`);
    });

    // Listen for alert.client_disconnected
    unifi.on('alert.client_disconnected', function (data) {
      const ts = new Date(data[0].timestamp).toISOString();
      console.log(`${ts} - ${this.event}: ${data[0].parameters.CLIENT.id} (${data[0].parameters.CLIENT.name})`);
    });

    // Listen for ctrl.* events
    unifi.on('ctrl.*', function () {
      console.log(`${this.event}`);
    });
  } catch (error) {
    console.log('ERROR: ' + error);
  }
})();

More examples can be found in the "examples" sub-directory of this GitHub repository.

Moving from v1 of node-unifi to v2+

If you are having an application still using the obsolete v1 version of node-unifi and you want to port it to using the new/revised v2 version, all you have to do is:

  • make sure your application can deal with NodeJS Promises as all node-unifi API functions return proper Promises allowing to use async/await or .then()/.catch() logic for synchronous processing of events (see Examples) rather than expecting callback functions, forcing you to nest them properly.
  • eliminate the previously necessary site function argument required when calling a node-unifi function. Now you can either use the { site: 'my site' } argument when passing contructor options to node-unifi or you switch to a different site using unifi.opts.site='my site' before calling a node-unifi API function.
  • as the API functions had been changed to work on a single site only, make sure your app is changed so that it expects a single site JSON return dataset only.
  • The new version by default verifies SSL connections and certificates. To restore the behaviour of the old version set sslverify: false in the constructor options

References

This nodejs package/class uses functionality/Know-How gathered from different third-party projects:

Use-Cases

The following projects are known to use this nodejs class for query/control UniFi devices:

License

The MIT License (MIT)

Copyright (c) 2017-2022 Jens Maus <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].