Giter VIP home page Giter VIP logo

unifi-api-client's Introduction

UniFi Controller API client class

A PHP class that provides access to Ubiquiti's UniFi Network Application API.

UniFi Network Application software versions 5.X.X, 6.X.X, 7.X.X, and 8.X.X (version 8.1.104 has been confirmed to work) are supported as well as Network Applications on UniFi OS-based consoles (UniFi OS 3.2.12 has been confirmed to work). This class is used by our API Browser tool, which can be found here.

The package can be installed manually or by using composer/packagist for easy inclusion in your projects.

Requirements

  • a server with:
    • PHP 7.4.0 or higher (use version 1.1.83 for PHP 7.3.x and lower)
    • PHP json and PHP cURL modules
    • tested on Apache 2.4 with PHP 7.4.27 and cURL 7.60.0 and with PHP 8.2.12 and cURL 7.81.0
  • direct network connectivity between this server and the host and port (usually TCP port 8443 or port 443 for UniFi OS) where the UniFi Controller is running
  • you must use accounts with local access permissions to access the UniFi Controller API through this class
  • do not use UniFi Cloud accounts and do not enable 2FA for the accounts that you use with this class

UniFi OS Support

Support for UniFi OS-based controllers has been added as of version 1.1.47. These devices have been verified to work:

  • UniFi Dream Router (UDR)
  • UniFi Dream Machine (UDM)
  • UniFi Dream Machine Pro (UDM PRO)
  • UniFi Cloud Key Gen2 (UCK G2), firmware version 2.0.24 or higher
  • UniFi Cloud Key Gen2 Plus (UCK G2 Plus), firmware version 2.0.24 or higher
  • UniFi Cloud Console, details here
  • UniFi Express (UX)

The class automatically detects UniFi OS consoles and adjusts the URLs and several functions/methods accordingly.

UniFi OS consoles require you to connect using port 443 instead of 8443 which is used for "software-based" controllers. If your own code implements strict validation of the URL that is passed to the constructor, please adapt your logic to allow URLs without a port suffix or with port 443 when working with a UniFi OS-based controller.

Remote API access to UniFi OS-based controllers

When connecting to a UniFi OS gateway through the WAN interface, you need to create a specific firewall rule to allow this. See this blog post on the Art of WiFi website for more details: https://artofwifi.net/blog/how-to-access-the-unifi-controller-by-wan-ip-or-hostname-on-a-udm-pro

The "custom firewall rule" approach described there is the recommended method.

Upgrading from a previous version

When upgrading from a version before 1.1.84, please:

  • make sure you are using PHP 7.4 or higher
  • test the client with your code for any breaking changes; the class methods now have strict parameter type hints and response types which can break your code in certain cases where the wrong type is passed or a different response type is expected back

Installation

Use Composer, Git or simply Download the Release to install the API client class.

Composer

The preferred installation method is through composer. Follow these installation instructions if you don't have composer installed already.

Once composer is installed, simply execute this command from the shell in your project directory:

composer require art-of-wifi/unifi-api-client

Or manually add the package to your composer.json file:

{
    "require": {
        "art-of-wifi/unifi-api-client": "^1.1"
    }
}

Finally, be sure to include the composer autoloader in your code if your framework doesn't already do this for you:

/**
 * load the class using the composer autoloader
 */
require_once 'vendor/autoload.php';

Git

Execute the following git command from the shell in your project directory:

git clone https://github.com/Art-of-WiFi/UniFi-API-client.git

When git is done cloning, include the file containing the class like so in your code:

/**
 * load the class directly instead of using the composer autoloader
 */
require_once 'path/to/src/Client.php';

Download the Release

If you prefer not to use composer or git, simply download the package, unpack the zip file, then include the file containing the class in your code like so:

/**
 * load the class directly instead of using the composer autoloader
 */
require_once 'path/to/src/Client.php';

Example usage

A basic example how to use the class:

/**
 * load the class using the composer autoloader
 */
require_once 'vendor/autoload.php';

/**
 * initialize the UniFi API connection class, log in to the controller and request the alarms collection
 * (this example assumes you have already assigned the correct values to the variables used)
 */
$unifi_connection = new UniFi_API\Client($controller_user, $controller_password, $controller_url, $site_id, $controller_version, true);
$login            = $unifi_connection->login();
$results          = $unifi_connection->list_alarms(); // returns a PHP array containing alarm objects

Please refer to the examples/ directory for some more detailed examples which can be used as a starting point for your own PHP code.

IMPORTANT NOTES:

  1. In the above example, $site_id is the short site "name" (usually 8 characters long) that is visible in the URL when managing the site in the UniFi Network Controller. For example with this URL:

    https://<controller IP address or FQDN>:8443/manage/site/jl3z2shm/dashboard

    jl3z2shm is the short site "name" and the value to assign to $site_id.

  2. The 6th optional parameter that is passed to the constructor in the above example (true), enables validation of the controller's SSL certificate which is otherwise disabled by default. It is highly recommended to enable this feature in production environments where you have a valid SSL cert installed on the UniFi Controller that is associated with the FQDN in the controller_url parameter. This option was added with API client version 1.1.16.

  3. Using an administrator account ($controller_user in the above example) with read-only permissions can limit visibility on certain collection/object properties. See this issue and this issue for an example where the WPA2 password isn't visible for read-only administrator accounts.

Functions/methods supported

The class currently supports the following functions/methods to access the UniFi Controller API. This list is sorted alphabetically. Please refer to the comments in the source code for more details on each of the functions/methods, their purpose, and their respective parameters.

  • adopt_device()
  • advanced_adopt_device()
  • archive_alarm()
  • assign_existing_admin()
  • authorize_guest()
  • block_sta()
  • cancel_rolling_upgrade()
  • check_controller_update()
  • check_firmware_update()
  • cmd_stat()
  • count_alarms()
  • create_apgroup()
  • create_dynamicdns()
  • create_firewallgroup()
  • create_hotspotop()
  • create_network()
  • create_radius_account()
  • create_user()
  • create_usergroup()
  • create_voucher()
  • create_wlan()
  • custom_api_request()
  • delete_apgroup()
  • delete_device()
  • delete_firewallgroup()
  • delete_network()
  • delete_radius_account()
  • delete_site()
  • delete_usergroup()
  • delete_wlan()
  • disable_ap()
  • disable_wlan()
  • edit_apgroup()
  • edit_client_fixedip()
  • edit_client_name()
  • edit_firewallgroup()
  • edit_usergroup()
  • extend_guest_validity()
  • forget_sta()
  • generate_backup()
  • generate_backup_site()
  • get_class_version()
  • get_cookie()
  • get_cookies()
  • get_curl_connection_timeout()
  • get_curl_http_version()
  • get_curl_method()
  • get_curl_request_timeout()
  • get_curl_request_timeout()
  • get_curl_ssl_verify_host()
  • get_curl_ssl_verify_peer()
  • get_debug()
  • get_is_unifi_os()
  • get_last_error_message()
  • get_last_results_raw()
  • get_site()
  • invite_admin()
  • led_override()
  • list_admins()
  • list_all_admins()
  • list_alarms()
  • list_aps()
  • list_backups()
  • list_clients()
  • list_country_codes()
  • list_current_channels()
  • list_dashboard()
  • list_device_name_mappings()
  • list_device_states()
  • list_devices()
  • list_devices_basic()
  • list_dynamicdns()
  • list_events()
  • list_extension()
  • list_firewallgroups()
  • list_firmware()
  • list_guests()
  • list_health()
  • list_hotspotop()
  • list_known_rogueaps()
  • list_networkconf()
  • list_portconf()
  • list_portforward_stats()
  • list_portforwarding()
  • list_radius_accounts()
  • list_radius_profiles()
  • list_self()
  • list_settings()
  • list_sites()
  • list_tags()
  • list_users()
  • list_wlan_groups()
  • list_wlanconf()
  • locate_ap()
  • login()
  • logout()
  • move_device()
  • power_cycle_switch_port()
  • reboot_cloudkey()
  • rename_ap()
  • revoke_admin()
  • revoke_voucher()
  • set_ap_radiosettings()
  • set_ap_wlangroup()
  • set_connection_timeout()
  • set_cookies()
  • set_curl_http_version()
  • set_curl_request_timeout()
  • set_curl_ssl_verify_host()
  • set_curl_ssl_verify_peer()
  • set_debug()
  • set_device_settings_base()
  • set_dynamicdns()
  • set_element_adoption()
  • set_guestlogin_settings()
  • set_guestlogin_settings_base()
  • set_ips_settings_base()
  • set_is_unifi_os()
  • set_locate_ap() (deprecated but still available as alias)
  • set_networksettings_base()
  • set_radius_account_base()
  • set_request_method()
  • set_request_timeout()
  • set_site()
  • set_site_connectivity()
  • set_site_country()
  • set_site_guest_access()
  • set_site_locale()
  • set_site_mgmt()
  • set_site_name()
  • set_site_ntp()
  • set_site_snmp()
  • set_sta_name()
  • set_sta_note()
  • set_super_identity_settings_base()
  • set_super_mgmt_settings_base()
  • set_super_smtp_settings_base()
  • set_usergroup()
  • set_wlan_mac_filter()
  • set_wlansettings()
  • set_wlansettings_base()
  • site_leds()
  • spectrum_scan()
  • spectrum_scan_state()
  • start_rolling_upgrade()
  • stat_5minutes_aps()
  • stat_5minutes_gateway()
  • stat_5minutes_site()
  • stat_5minutes_user()
  • stat_allusers()
  • stat_auths()
  • stat_client()
  • stat_daily_aps()
  • stat_daily_gateway()
  • stat_daily_site()
  • stat_daily_user()
  • stat_full_status()
  • stat_hourly_aps()
  • stat_hourly_gateway()
  • stat_hourly_site()
  • stat_hourly_user()
  • stat_ips_events()
  • stat_monthly_aps()
  • stat_monthly_gateway()
  • stat_monthly_site()
  • stat_monthly_user()
  • stat_payment()
  • stat_sessions()
  • stat_sites()
  • stat_speedtest_results()
  • stat_sta_sessions_latest()
  • stat_status()
  • stat_sysinfo()
  • stat_voucher()
  • unauthorize_guest()
  • unblock_sta()
  • unset_locate_ap() (deprecated but still available as alias)
  • upgrade_device()
  • upgrade_device_external()

Need help or have suggestions?

There is still work to be done to add functionality and further improve the usability of this class, so all suggestions/comments are welcome. Please use the GitHub Issues section or the Ubiquiti Community forums (https://community.ubnt.com/t5/UniFi-Wireless/PHP-class-to-access-the-UniFi-controller-API-updates-and/td-p/1512870) to share your suggestions and questions.

IMPORTANT NOTE:

When encountering issues with the UniFi API using other libraries, cURL or Postman, please do not open an Issue. Such issues will be closed immediately. Please use the Discussions section instead.

Contribute

If you would like to contribute code (improvements), please open an issue and include your code there or else create a pull request.

Credits

This class is based on the initial work by the following developers:

and the API as published by Ubiquiti:

Important Disclaimer

Many of the functions in this API client class are not officially supported by Ubiquiti and as such, may not be supported in future versions of the UniFi Controller API.

unifi-api-client's People

Contributors

4oo4 avatar jaspervrijbroek avatar malle-pietje avatar patrice-guillemette avatar pauloboc avatar sgrodzicki avatar smos avatar warafux 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unifi-api-client's Issues

Add IP addresses to firewall group

Is it possible to add IP addresses to firewall groups using the API? I have a group of IP addresses which are blocked from my network. I would like to be able to add addresses to this group automatically based on log files my servers generate throughout the day.

Issues with Authentication

We have been contracted with building a Guest Portal for a clients Unifi. The portal we have built runs on the "remote server" setting (but the remote server is a local address on the same computer as the AP) and uses a standard web (html, css, apache, mysql, php) environment.

This library accesses the AP and authenticates the MAC Address.

The production Unifi runs on a server and there are about 20(ish) locations that connect to the AP. Currently we are only testing the guest portal on a single location, but this gives you an idea of the setup.

Here is how the process is supposed to go:

  1. We require the customer to enter their email address & accept the terms and conditions
  2. There is a PHP script using the Unifi API Client that sends a request to the AP to allow the guest
  3. We receive a "success" response from the AP
  4. We redirect the customers device to a website
  5. They now have full access to the wifi.

This works as-expected, maybe 20-30% of the time, the customer is connected fine.

The other 70-80% of the time, at Step 4, after redirecting, the device just refreshes back to the guest authentication page. This happens even though we always receive a "success" response from the AP when trying to authenticate a customers device.

It appears there may be some sort of delay with the AP registering the guest access. I have noticed even when Unauthenticating a user manually from the server it can take up to a minute before the device is asked to authenticate again (I'm not sure if this is related, but it may be).

We have checked all of the networks, connections, etc. and everything appears to be fine. The code appears to be working as-expected as clients eventually log in fine. The issue appears to be between when the authentication is received by the AP and when it actually takes effect.

Is there something we should be doing with the API to fix this issue?

Bug in Client.php?

I was looking for a way to add mac filters via an API and I found this project, but I think there is a bug in Client.php
In function set_wlan_mac_filter there is following if statement:
if (in_array($mac_filter_policy, ['allow', 'deny'])) return false;
Shouldn't it be:
if (!in_array($mac_filter_policy, ['allow', 'deny'])) return false;

Otherwise it would return false everytime I give a legit MAC policy.

[Question] Is it possible to check Scheduled Upgrades

Good afternoon,

Basically this is just a question with the usage of your API.
I use the API for some simple scripting to get some numbers out of the system,
off line devices etc.
I spend quite some time lately adding all devices to an Scheduled Upgrade schema,
but with the change of devices / sites maybe some AP's / switches are not in the upgrade any more.

Is there a way with the API to get 'some' info regarding the scheduled upgrades?
I searched through the 'Client.php' but was not able to find anything,
the API page https://ubntwiki.com/products/software/unifi-controller/api also didnt note anything.
Also didn't find any info in the response (json) per device, or maybe i overlooked..

Hope you have some info.

Login Does not Work with API

Hi,

I have cloned the UniFi-API-client repository, loaded its libraries with composer and filled out the config appropriately with the correct username, password, https://...:8443, and my controller version.

I then created a new file 'login.php':


require_once("vendor\autoload.php");
require_once('config.php');
$unifi_connection = new UniFi_API\Client($controlleruser, $controllerpassword, $controllerurl, $site_id, $controllerversion);
$set_debug_mode = $unifi_connection->set_debug($debug);
$loginresults = $unifi_connection->login();


I do not get any errors on loading:
require_once("vendor\autoload.php");
require_once('config.php');

Contents of config.php:


$controlleruser = 'admin'; // the user name for access to the UniFi Controller
$controllerpassword = '*****'; // the password for access to the UniFi Controller
$controllerurl = 'https://
.
.
.
:8443'; // full url to the UniFi Controller, eg. 'https://22.22.11.11:8443'
$controllerversion = '5.10.23'; // the version of the Controller software, eg. '4.6.6' (must be at least 4.0.0)
$debug = false;


The login function simply returns "false", so it is not getting the $_SESSION['unificookie'] value.

I checked all of the settings on my controller's UI, and I did not find anything I needed to enable to allow calls like this.

Do you know of anything in the Controller UI that might fix this problem?

Maybe my client.php's config values?

client.php config values:


protected $baseurl            = 'https://127.0.0.1:8443';
protected $user               = 'admin';
protected $password           = '************';
protected $site               = 'https://*.*.*.*:8443';
protected $version            = '5.10.23';

Should the $baseurl be something other than my local host?

I appreciate any and all help!

Thank you,

Jack

enable/disable port forwarding

I have found it's possible to grab a list of port forwardings, but is it possible to enable/disable a port forwarding rule using the API?

list_clients() reports the wrong dBm level for clients

Calling list_clients() returns information about: signal, rssi, noise, etc... I'm trying to coordinate the dBm levels I see in the Unifi controller UI with what shows up via the API.

I have a client in the Unifi Controller which shows: "99% (-43 dBm)" but what comes back via list_clients() and the API is:

Key Value
Signal -58
RSSI 51
Noise -109

Is there a calculation I need to run to get the actual dBm?

block/unblock list of mac addresses

please add the following two scripts to your examples, I execute them from the commandline on windows via batch files so the scripts do not output json format.

unblock_list.php:

<?php
/**
 * PHP API usage example
 *
 * contributed by: Based on another Art of WiFi example
 * description: basic PHP script to unblock a list of mac addresses passed in via command line
 *
 * usage: 
 *  php unblock_list.php <list of comma seperated mac addresses>
 *
 * example:
 *  php unblock_list.php 09:09:09:09:09:09,10:10:10:10:10:10
 *
 */

/**
 * using the composer autoloader
 */
require_once('vendor/autoload.php');

/**
 * include the config file (place your credentials etc. there if not already present)
 * see the config.template.php file for an example
 */
require_once('config.php');

$debug=false;
/**
 * the MAC addresses of the device(s) to unblock
 */
$macs_to_unblock = explode(',',$argv[1]);

/**
 * The site to authorize the device with
 */
$site_id = 'MUST_DEFINE_THIS'; 
if ($site_id == "MUST_DEFINE_THIS")
{
    print 'ERROR: set the site id in your script';
	return;
}

/**
 * initialize the UniFi API connection class and log in to the controller
 */
$unifi_connection = new UniFi_API\Client($controlleruser, $controllerpassword, $controllerurl, $site_id, $controllerversion);
$set_debug_mode   = $unifi_connection->set_debug($debug);
$loginresults     = $unifi_connection->login(); // always true regardless of site id

foreach ($macs_to_unblock as &$mac) 
{
    // block_result is always true even if mac address does not exist :(
    $block_result   = $unifi_connection->unblock_sta($mac);
	
	/** NOTE:
	 * during testing I had some strange behavior where clients were not reconnecting to the network correctly, 
	 * they appeared unblocked and received a valid IP address but could not actually get any data.
	 * the clients did not come to life until I disabled the SSID and then re enabled it.
	 * I guessed maybe these commands were occurring too quickly for the controller so I have slowed them down; 
	 * since introducing the sleep I have not seen the above behavior so it might be fixed	
	 */
	sleep(1);
    
	$getid_result   = $unifi_connection->stat_client($mac);

    if (property_exists($getid_result[0], "oui")) // this field(manufacturer) seems to exist on valid mac addresses
    {
		if (property_exists($getid_result[0], "name"))
		{
			$name = $getid_result[0]->name;
		}
		else
		{
			$name = $getid_result[0]->hostname;
		}
        print 'unblocked ' . $name . PHP_EOL;
	}
    else
    {
        print 'ERROR: could not unblock ' . $mac . PHP_EOL;
		print '       check mac address is valid and part of your network' . PHP_EOL;		
    }
}

/**
 * provide feedback in json format
 */
//echo json_encode($block_result, JSON_PRETTY_PRINT);

and

block_list.php

<?php
/**
 * PHP API usage example
 *
 * contributed by: Based on another Art of WiFi example
 * description: basic PHP script to unblock a list of mac addresses passed in via command line, output is to console in non json format
 *
 * usage: 
 *  php block_list.php <list of comma seperated mac addresses>
 *
 * example:
 *  php block_list.php 09:09:09:09:09:09,10:10:10:10:10:10
 *
 */

/**
 * using the composer autoloader
 */
require_once('vendor/autoload.php');

/**
 * include the config file (place your credentials etc. there if not already present)
 * see the config.template.php file for an example
 */
require_once('config.php');

$debug=false;
/**
  * the MAC address(es) of the device(s) to block
 */
$macs_to_block = explode(',',$argv[1]);

/**
 * The site to authorize the device with
 */
$site_id = 'MUST_DEFINE_THIS';
if ($site_id == "MUST_DEFINE_THIS")
{
    print 'ERROR: set the site id in your script';
	return;
}

/**
 * initialize the UniFi API connection class and log in to the controller
 */
$unifi_connection = new UniFi_API\Client($controlleruser, $controllerpassword, $controllerurl, $site_id, $controllerversion);
$set_debug_mode   = $unifi_connection->set_debug($debug);
$loginresults     = $unifi_connection->login(); // always true regardless of site id

foreach ($macs_to_block as &$mac) 
{
    // block_result is always true even if mac address does not exist :(
    $block_result   = $unifi_connection->block_sta($mac);

	/** NOTE:
	 * during testing I had some strange behavior where clients were not reconnecting to the network correctly, 
	 * they appeared unblocked and received a valid IP address but could not actually get any data.
	 * the clients did not come to life until I disabled the SSID and then re enabled it.
	 * I guessed maybe these commands were occurring too quickly for the controller so I have slowed them down; 
	 * since introducing the sleep I have not seen the above behavior so it might be fixed	
	 */
	sleep(1); 
    
	$getid_result   = $unifi_connection->stat_client($mac);

    if (property_exists($getid_result[0], "oui")) // this field(manufacturer) seems to exist on valid mac addresses
    {
		if (property_exists($getid_result[0], "name")) // this is the alias field if it has been defined
		{
			$name = $getid_result[0]->name;
		}
		else
		{
			$name = $getid_result[0]->hostname;
		}
        print 'blocked ' . $name . PHP_EOL;
    }
    else
    {
        print 'ERROR: could not block ' . $mac . PHP_EOL;
		print '       check mac address is valid and part of your network' . PHP_EOL;		
    }
}

/**
 * No json formatted data
 */
//echo json_encode($block_result, JSON_PRETTY_PRINT);

Request: DPI app/category information

When pulling /stat/dpi a list of applications and the relevant data usage is returned. The application and the category they belong to are only identified by a number. Is there a comprehensive list that exists to identify the app/category id to a name?

Authenticate Guest clients for external portal UniFi

Can somebody share a simple PHP code of a website used in /guest/s/default to auth clients when they request to access a free open network managed with an external portal in Ubiquiti?
I looked through this repository but I found a guest auth.php but the mac address has to be inserted manually and so I wasn't able to use it for my purpose (Auth guests with a website when they access a network - External Captive Portal).
Thank you, waiting for an answer

Retrieve Speed Test Results

UNIFI Controller has capability to chedule a speedtest for checking connectity of the provider.
Is there a way to retrieve the result of last speedtest via this API?

Thanks

Feature Request: function to enable/disable SSID on a site

Title says it all: I'd like to be able to enable or disable an SSID (in my case the guest WiFi) via API call.
Reasoning: As a next step I'd like to toggle the guest WiFi from OpenHab (perhaps at some time with Alexa integration) using Art-of-WiFi.

Suggestio/question Enable/Disable fixed ip on UniFi clients

I would like to find a way to fix ips to devices, which can be done through the UI (UniFi->Clients->click on client->Configuration->Network):
image
image
I've been trying to discover the api by myself, in order to make a PUT request into a client and change that field to TRUE.
Listing all clients a "use_fixedip" boolean fields appears:
image
Also, a fixed_ip field:
image
Is there anyway to actually set the value of that field?

Thank you.

How to test if controller is Unifi OS or not

Hi,

This is a great piece of work.

I have put together a python based network display. I was having a hard time finding the new URL's for the UDM Pro (which you have!). I'm actually using the websocket connection to get events and display them.

Right now I just use a flag to set whether this is a Unifi OS device or not manually. I see that you can detect it automatically.

This is the code you use:

        /**
         * check whether we have a "regular" controller or one based on UniFi OS
         */
        if (!($ch = $this->get_curl_resource())) {
            trigger_error('$ch as returned by get_curl_resource() is not a resource');
        } else {
            curl_setopt($ch, CURLOPT_HEADER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_NOBODY, true);
            curl_setopt($ch, CURLOPT_URL, $this->baseurl . '/');

            /**
             * execute the cURL request and get the HTTP response code
             */
            curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

            if (curl_errno($ch)) {
                trigger_error('cURL error: ' . curl_error($ch));
            }

            if ($http_code === 200) {
                $this->is_unifi_os = true;
            }

Can you explain how this works? I have read it, but I'm not sure how to determine if it's a Unifi OS response (200 is obvious enough) but the baseurl just seems to be the regular access url.

Or is it just accessing the regular 8443 port, and if that fails assuming it's a Unifi OS device?

Thanks.

create_voucher does not return a voucher code

I'm creating a new voucher using create_voucher and the response only contains the creation date but no voucher code.
Tested using unifi-api-client v1.1.16 and Unifi Controller 5.5.20

Debug Output:

-------URL & PAYLOAD---------
https://192.168.254.10:8443/api/s/default/cmd/hotspot
json={"cmd":"create-voucher","expire":4320,"n":1,"quota":0,"note":"Buttonprinter: 2017.10.09"}
----------RESPONSE-----------
{ "data" : [ { "create_time" : 1507562169}] , "meta" : { "rc" : "ok"}}
-----------------------------

Port POE enable/disable

Can there be a function added to enable/disable/toggle POE setup on a port. My use case is to restart the connected POE-Device and to add a timed on/off for power savings.

How i can use Unifi-Api-client with laravel

Hello!

I'm learning to use Laravel and I would like to implement the API with laravel.
I followed the installation instructions with composer but I have not managed to make it work.
Do you have to do some additional step to the one indicated in the installation steps?

Greetings and thanks!

Sorry for my english.

Last error message: api.err.UnknownDevice

I'm using locate_ap() and power_cycle_switch_port() and I keep getting api.err.UnknownDevice, it doesn't seem to understand the MAC I'm giving it. I'm using the same format with colon separation, and I'm using the only logical MAC for the switch. Any ideas?

UniFi 5.6.16

set_wlan_group not functioning, unifi version 5.7.23

We have a script set up to automatically adopt and configure ap's. Currently the set_wlan_group function is not operating correctly and the wlan group remains on default. tested multiple ap's with multiple wlan groups and device ids and no change.

list_sites() only returns the first 2997 sites

I have what I think may be a unique problem... We're an ISP that provides Unifi WiFi to our members. Each member has their own site in our controller, so we have a rather large controller. Our controller has just about 3000 sites on it.

list_sites() only returns the first 2997 sites no matter how many sites are actually on the controller. I've tested it by adding 50 sites at a time, as soon as the total is above 2997 it stops returning all the sites. My guess is that the Unifi controller limits how many sites it returns via that API call? Do you know any way to work around this limitation?

We're currently running 5.12.35 of the Unifi controller software.

DPI Stats App/Category mapping

Hi

Can someone explain, how the mapping works?
I found my rule.xml and my categories is:

        <app_categories>
                <app_category id="128" name="Instant messengers" />
                <app_category id="129" name="Peer-to-peer networks" />
                <app_category id="131" name="File sharing services and tools" />
                <app_category id="132" name="Media streaming services" />
           ...

And an example, twitch from same file:

<application cat_id="132" app_id="19" name="Twitch.tv" />

BUT, the category indexes from the api is different:

                            [app] => 19
                            [cat] => 4

But cat should ( in my mind ) be 132.

Any ideas?

Controller version: 5.10.25

Getting device status

Hello.
Please tell me, how can i check device is blocked or not by API?
I see only block_sta() and unblock_sta().
I looked at the methods list_devices('MAC') and list_guests(), but there also I did not find anything.
In admin area there are difference between blocked and not blocked devices.
Thank you!

2019-04-11_121409

Xamp ports changing when I do a request

Hi,

When I want to make a request like ($results = $unifi_connection->list_admins();) then the XAMPP ports keep changing and my website keeps loading and finally crashes...
Do you know how to fix it or do you have an idea where the problem lies?

Thanks in advance.

set_ap_radiosettings invalid payload with 5.5.24

Hi,

I'm trying to use the set_ap_radiosettings command to change the AP channel, but it doesn't seam to work with my controller version (5.5.24): it answer me back invalidPayload

I've tried to see the what does the controller call, and I've noticed two difference:

  • There's some field missing (antenna_gain,min_rssi_enabled,min_rssi,hard_noise_floor_enabled)
  • If the AP have the 5ghz, it pass all the two radio configuration together, otherwise it answer ok, but it doesn't really apply the config to the AP

Also would be useful to have a function that read the current ap settings and only modify the one you need to touch, passing the complete setting back to the controller.

byez

All wlan reseting

Hello, i have sucessfully added scheduled task that enables and disables certain wlan network, using disable_wlan function, only issue is that when this funtion is called, controller disables all wlans for brief period and then enables them again, thus disconnecting client that are conected to those networks. Controller version is: 5.4.14.

rx_bytes incorrect, or conversion, or user/PEBKAC issue?

I'm using the client to pull the download data of a given device, and I must be missing something very simple. The goal will be "run once daily, check amount, and if amount > 100MB then do X".

Using stat_daily_user, and the following very simple code, the data seems to not match the Controller report (5.9.29, with a USG3). 5 minute data is set to 1 day retention. I did change the function to be 24 hours instead of 12 but I was seeing the same thing before. I'm rusty at PHP so I could be making a bonehead mistake. :) I did check the MAC was the right one, twice. I've replaced the actual MAC with secret_mac_here.

// ... sample code from list_user example
$result           = $unifi_connection->stat_daily_user("secret_mac_here");
// ...
for ($i=0; $i < count($result); ++$i) {
        // to_local_time($result[$i]->time);       
        $rx_bytes=$rx_bytes + $result[$i]->rx_bytes;
        echo (($result[$i]->rx_bytes)/1024) . "\n";
           //  echo $result->data->oid . "\n";
}
echo "Total kbytes rcvd " . ($rx_bytes/1024) . "\n";

returns

2222.9465717516
3717.4771168644
7594.3761160714
2127.058656754
9998.3134135585
8743.44921875
1332.3310546875
Total kbytes rcvd 35735.952148438

I read that as "35MB". The controller shows:
image-15-10-46

which is obviously quite different.

Am I missing a conversion somewhere or completely misunderstanding how the controller renders things, or any number of other newbie issues?

Thanks! This was unbelievably easy to get started with. Also having problems with understanding the conversion of the time but that's another story and quite less important I think.

Here's the json dump:

15:09 $ php stat_daily_m3.php
[
    {
        "oid": "secret_mac_here",
        "rx_bytes": 2276297.2894736845,
        "time": 1540771200000,
        "tx_bytes": 3593290.447368421,
        "user": "secret_mac_here"
    },
    {
        "oid": "secret_mac_here",
        "rx_bytes": 3806696.567669173,
        "time": 1540857600000,
        "tx_bytes": 2530428.838345865,
        "user": "secret_mac_here"
    },
    {
        "oid": "secret_mac_here",
        "rx_bytes": 7776641.142857145,
        "time": 1540944000000,
        "tx_bytes": 59276000.7142857,
        "user": "secret_mac_here"
    },
    {
        "oid": "secret_mac_here",
        "rx_bytes": 2178108.064516129,
        "time": 1541030400000,
        "tx_bytes": 2409134.870967742,
        "user": "secret_mac_here"
    },
    {
        "oid": "secret_mac_here",
        "rx_bytes": 10238272.935483873,
        "time": 1541116800000,
        "tx_bytes": 814967778.7290323,
        "user": "secret_mac_here"
    },
    {
        "oid": "secret_mac_here",
        "rx_bytes": 8953292,
        "time": 1541203200000,
        "tx_bytes": 7263091.4,
        "user": "secret_mac_here"
    },
    {
        "oid": "secret_mac_here",
        "rx_bytes": 1364307,
        "time": 1541289600000,
        "tx_bytes": 749647.0000000001,
        "user": "secret_mac_here"
    }
]

Extend Guest Connection with Time Parameter

Good Day, here's the situation:
For instance, I have a guest that is already connected to an AP, and I want to extend his/her connection. How do I do that?

I've seen this function:

public function extend_guest_validity($guest_id)
 {
     if (!$this->is_loggedin) {
         return false;
     }

     $payload  = ['_id' => $guest_id, 'cmd' => 'extend'];
     $response = $this->exec_curl('/api/s/' . $this->site . '/cmd/hotspot', $payload);

     return $this->process_response_boolean($response);
 }

How Will I use it to extend the connection with a specific time?

show log usg

Hi,
I hope you can help me out.

Im trying to figure out a way to pull the USG logs from firewall... Prefferrably real time...
same command as the SSH command "tail -f /var/log/messages"

I need to be able to import it to a database and make some queries to it, so I can dynamically update my firewall rules... I have a way to dynamically update the firewall rules, but im having a hard time pulling the logs from the USG

Does your api class support this ? err....: pull the /var/log/messages from USG

block_list / unblock_list don't exit

I've got a new UDM Pro and was looking for a way to enable/disable my kid's gaming systems so they don't overuse them. I found your scripts and they will definitely do the job if I can sole one thing.

Currently, they do block and unblock as expected, but neither script ends unless you hit ctrl-c.

I'm not a strong programmer but I've tried adding an exit after the for loop but that doesn't seem to work.

Any ideas?

ap_upgrade_firmware.php causes firmware downgrade

Finally got a chance to put this to the test, and for some reason it ended up downgrading the firmware, even though it was already on the latest, since it must have just seen that there was a different version available and ran with that.

I'm hoping there are separate API calls for upgrade/downgrade to prevent this from happening? The frustrating thing is that I can't seem to get it to find the latest firmware again, so I'll have to reinstall that manually. I'll also see if anyone has any suggestions on the Ubiquiti forums.

trigger_error instead of trow

Why for internal errors use trigger_error() instead of trow()?
Only in _constructor() - trigger_error() is on it's place.
Using of trigger_error don't allow to use 'try catch', instead you must use set_error_handler().
When remote host is not available - it's not a error, it is a 'exception'.

Portal Password Change

I am trying to change the "Guest Password" in my controller.
I can connect to it with $unifi_connection->list_settings(); no problem and get an output of all the settings.
But when I try $unifi_connection->set_guestlogin_settings() I get no response and no change in the controller
I get the [site_id] => xxxxxxxxxxxxxxxxxx from the output of list_settings(). Is this right?

Any help is greatly appreciated. Thanks

`<?PHP
require_once('Client.php');

require_once('config.php');

$unifi_connection = new UniFi_API\Client($controlleruser, $controllerpassword, $controllerurl, $siteid, $controllerversion, false);

$login = $unifi_connection->login();

$results = $unifi_connection->list_settings();

$change = $unifi_connection->set_guestlogin_settings(true,true,true,'https://www.google.ca','aaaaa','24','h','xxxxxxxxxxxxxxx');

echo $change;`

 * Update guest login settings
 * ---------------------------
 * return true on success
 * required parameter <portal_enabled>
 * required parameter <portal_customized>
 * required parameter <redirect_enabled>
 * required parameter <redirect_url>
 * required parameter <x_password>
 * required parameter <expire_number>
 * required parameter <expire_unit>
 * required parameter <site_id>

Cannot get device name

Hi, thank you for providing this API it's very useful. I have a problem retrieving the necessary fields of the device object though. When I use the list_devices method, it lists the devices but without the "name" field. Could you add the "name" field (and possibly other missing fields) in the response ? Or maybe should I retrieve this field by some other mean ?

How to create a site?

Cool API library thanks!

Do you have an API call to create a site?

An API call to create a user for a site?

Multiple issues with stats

I'm having issues with stat_daily_site, When i pass timestamps to it i do not get a response. Even when copying the same values that is generated inside of the function. Also it is not possible to get the wlan-num_sta values.

Guest Portal Access Expires Early

I'm not sure if anyone has encountered this yet, I've done a bit of digging but didn't see anything. We are running:

$unifi->authorize_guest( $request_id , 43200 , null , null , null , $request_ap );

I'm expecting this to last 30 days, but the access appears to expire within 24 hours - could something internal in Unifi be overriding this?

sitemgr not work anymore

Hi,

I am working on unify version 5.5.24 and every time that I try to use methods that use sitemgr url this fails.

I am try to create and delete some test sites and the error is always the same, api.err.NoSiteContext but if i use list_settings on a site the SiteContext works.

But in all the cases curl debug give [http_code] => 401 - UNAUTHORIZED

I tried using the code in localhost and others ways but did not find the issue that I am doing or not.

sitemgr url still its working in 5.5.24?

Best Regards

changing guest portal password

I was wondering if it is possible to change the password for the guest portal like it is possible to change the WLAN password using the API.

revoke_voucher not working

Hello,
I'm trying to handle vouchers using this API and for some reason the revoke_voucher() function doesn't seem to work.
I've created a voucher on the Hotspot Manager page. (65785-57546)
hotspot-screenshot

The vouchers are valid and I'm able to get the voucher's details using stat_voucher().

When I do:

var_dump($unifi_connection->revoke_voucher('6578557546'));

it returns true however the voucher is still listed on the Hotspot Manager and I'm able to login to the guest portal using it.

Some debugging I've tried:

  • Made sure I was logged in with $unifi_connection->login()
  • Passed the voucher code directly from stat_voucher to revoke_voucher().
  • Tried with different voucher codes and one-time use & multi-use codes.
  • Checked web server error log (no errors found).

Any ideas?
I'm using PHP 7.2.17, downloaded the project via Composer and my UniFi controller is on version 5.10.23 if that's of any help.
//Carl

How do I create a Custom code for the create_voucher function, let's say an alphanumeric code instead of a string of numbers

this is the result of the script that I ran:

[ { "_id": "5d81c805609b0e273c25796e", "site_id": "5d81a22c609b0e1278b62e9a", "create_time": 1568786437, "code": "6386473243", "for_hotspot": false, "admin_name": "admin", "quota": 0, "duration": 2000, "used": 0, "qos_overwrite": false, "note": "sadofnowe:}{:", "status": "VALID_MULTI", "status_expires": 0 } ]

How do I make a custom value/string for "code"

eg. "code":"asodoiw124"
instead of "code": "6386473243"

Can't login. Line 151 in Client.php to blame.

On my current setup, I was having problems logging in and I've traced the issue to line 151 in Client.php. The line is as follows:

preg_match_all('|Set-Cookie: (.*);|U', substr($content, 0, $header_size), $results);

In my instance, the reponse is all lowecase, so 'Set-Cookie' doesn't match 'set-cookie'

Changing the line to
preg_match_all('|set-cookie: (.*);|u', substr($content, 0, $header_size), $results);
fixed the issue in my case. But can this line to changed to accept any case?

Last seen date/time not updating

The last seen date & time seems to be different to the controller GUI, it doesn't seem to update?

using $unifi->stat_allusers(24);

Unifi 5.10.26-11685-1

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.