• Stars
    star
    138
  • Rank 264,508 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 8 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

NodeJS class for querying/controlling a UniFi-Controller (UDM-Pro, UDM-SE, UDM, UDR, UDW, CloudKey Gen1/Gen2) from Ubiquiti (www.ui.com)


node-unifi

Build NPM version Downloads License Donate GitHub stars

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-2023 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.

More Repositories

1

RaspberryMatic

๐Ÿ  A feature-rich but lightweight, buildroot-based Linux operating system alternative for your CloudFree CCU3/ELV-Charly 'homematicIP CCU' IoT smarthome central. Running as a pure virtual appliance (ProxmoxVE, Home Assistant, LXC, Docker/OCI, Kubernetes/K8s, etc.) on a dedicated embedded device (RaspberryPi, etc.) or generic x86/ARM hardware.
JavaScript
1,518
star
2

node-ical

NodeJS class for parsing iCalendar/ICS files
JavaScript
118
star
3

amissl

๐Ÿ” AmiSSL is the AmigaOS/MorphOS/AROS port of OpenSSL. It wraps the full functionality of OpenSSL into a full-fledged Amiga shared library that makes it possible for Amiga applications to use the full OpenSSL API through a standard Amiga shared library interface (e.g. web browsers wanting to support HTTPS, etc.)...
C
86
star
4

cuxd

CUx-Daemon โ€“ a universal interface between the HomeMatic CCU logic layer (ReGaHSS) and third-party (EnOcean, M-Bus, 1-Wire, ArtDMX, etc.) external and virtual devices.
C
65
star
5

yam

๐Ÿ“ฌ YAM (short for 'Yet Another Mailer') is a MIME-compliant open-source Internet email client written for Amiga-based computer systems (AmigaOS4, AmigaOS3, MorphOS, AROS). It supports POP3, SMTP, TLSv1/SSLv3 connection security, multiple users, multiple identities, PGPv2/v5 encryption, unlimited hierarchical folders, an ARexx interface, etc...
C
61
star
6

thinRoot

thinRoot is a buildroot (https://buildroot.org/) powered operating system environment to create lightweight user-defined kiosk systems or ThinClients (e.g. using x86 hardware, RaspberryPi, ASUS Tinkerboard, etc.) to smoothly connect to server-based desktop environments via ThinLinc, RDP, SPICE@ProxmoxVE, VNC or to create a simply web-kiosk.
Python
51
star
7

libcodesets

codesets.library is an AmigaOS shared library to handle different codesets (i.e. ISO-8859-1, UTF-8, etc.) and their respective conversions. It provides public functions for applications to deal with multiple codesets and convert them properly.
C
18
star
8

lrecog

A neuronal network based image recognition application that aims on the automatic recognition of tree species according to available images of the leaves of each species. With help of this application botanists can then identify different species...
Java
14
star
9

magicmenu

MagicMenu is a menu enhancer for AmigaOS oriented operating systems. It allows to override the default look&feel of menus presented in AmigaOS and provides a user configurable way to show nice looking menus instead of the default ones...
C
12
star
10

vxext_fs

Linux kernel module for VxWorks extended DOS filesystem support.
C
9
star
11

node-panasonic-viera

NodeJS class to query and control Panasonicโ„ข Vieraโ„ข Smart-TVs
JavaScript
8
star
12

libopenurl

A library (openurl.library) and tools for opening an application in accordance to a supplied URL. It is explicitly designed to be used by AmigaOS compatible operating systems such as AmigaOS3, AmigaOS4, MorphOS or AROS.
C
7
star
13

amide

AmIDE - Amiga Integrated Development Environment is a modern MUI based IDE system that should make the Amiga developer able to use his favourite Compiler system with a modern looking GUI System with features like filetype handling, Build/Make, TextEd
C
6
star
14

newsrog

NewsRog is the most powerful newsreader available for the Amiga platform. Combining a Magic User Interface frontend, an OOP approach and its overwhelming list of features, it provides the best experience even to the most demanding Usenetters.
C
6
star
15

anfs

An implementation of the Network File System protocol (NFS) for AmigaOS-based operating systems. This project is open source and based on the formerly known 'ch_nfs' NFS client and the "nfsd" NFS server implementation originally targeted for AmiTCP...
C
5
star
16

jens-maus

Personal Page Repo
4
star
17

dessolver

A Java-based Ordinary Differential Equation (ODE) System Solver Application...
Java
4
star
18

betterlayers

A replacement library which aim in replacing the default AmigaOS "layers.library" to more efficently manage layers operations on modern AmigaOS operating systems. It comes with some advanced layers techniques to speed up operations...
C
4
star
19

occu-test

Automated System Tests of "ReGaHss" - the HomeMatic (O)CCU "Logic Layer" Engine...
JavaScript
3
star
20

librtdebug

librtdebug is a comprehensive runtime debugging library which allows developers to insert predefined macros within their own source code and track the 'runtime' of their applications via standardized textual output...
C++
2
star
21

xmlrpcpp

Fork of unmaintained http://xmlrpcpp.sf.net with patches and certain fixes applied
C++
1
star