Skip to content

Commit

Permalink
added new functions for 5-minutes stats and minor code cleanup
Browse files Browse the repository at this point in the history
- stat_5minutes_site()
- stat_5minutes_aps()
- added optional parameter to list_dashboard() to allow fetching of 5minutes stats
  • Loading branch information
malle-pietje committed Oct 10, 2017
1 parent 4611dbb commit 6fd7e6e
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 35 deletions.
18 changes: 10 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
## UniFi controller API client class

This PHP class provides access to Ubiquiti's **UniFi Controller API**. Versions 4.x.x and 5.x.x of the UniFi Controller software are supported (version 5.5.20 has been confirmed to work). It is an independent version of the class which is used in the API browser tool [here](https://github.com/Art-of-WiFi/UniFi-API-browser).
A PHP class which provides access to Ubiquiti's **UniFi Controller API**. Versions 4.x.x and 5.x.x of the UniFi Controller software are supported (version 5.6.18 has been confirmed to work). It's a standalone version of the class which is used in the API browser tool [here](https://github.com/Art-of-WiFi/UniFi-API-browser).

The class is now also installable through composer/[packagist](https://packagist.org/packages/art-of-wifi/unifi-api-client) for easy inclusion in your projects.
This class can now also be installed using composer/[packagist](https://packagist.org/packages/art-of-wifi/unifi-api-client) for easy inclusion in your projects.

### Donations

Expand All @@ -12,7 +12,7 @@ If you'd like to support further development of this PHP API client class, pleas

## Methods and functions supported

This class currently supports the following functions/methods to get/set data through the UniFi controller API:
The class currently supports the following functions/methods to get/post/put/delete data through the UniFi controller API:
- login()
- logout()
- adopt_device()
Expand Down Expand Up @@ -88,10 +88,12 @@ This class currently supports the following functions/methods to get/set data th
- stat_allusers()
- stat_auths()
- stat_client()
- stat_daily_aps()
- stat_daily_site()
- stat_5minutes_aps() (supported on controller version 5.5.* and higher)
- stat_hourly_aps()
- stat_daily_aps()
- stat_5minutes_site() (supported on controller version 5.5.* and higher)
- stat_hourly_site()
- stat_daily_site()
- stat_payment()
- stat_sessions()
- stat_sites()
Expand All @@ -113,7 +115,7 @@ Internal functions, getters/setters:
- get_last_results_raw()
- get_last_error_message()

Please refer to the source code for more details on each function/method and it's parameters.
Please refer to the source code for more details on each function/method and their parameters.

## Requirements

Expand Down Expand Up @@ -185,7 +187,7 @@ Please refer to the `examples/` directory for some more detailed examples which

### IMPORTANT NOTES:

In the example above, the last parameter (`true`, without quotes) that is passed to the constructor enables validation of the controller's SSL certificate which is **disabled** by default.
In the example above, the last parameter (`true`) that is passed to the constructor, 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, and which is associated with the FQDN of the server as used in the `controller_url` parameter. This option was added with API client version 1.1.16.

---
Expand All @@ -209,7 +211,7 @@ If you would like to contribute code (improvements), please open an issue and in
This class is largely based on the work done by the following developers:
- domwo: http://community.ubnt.com/t5/UniFi-Wireless/little-php-class-for-unifi-api/m-p/603051
- fbagnol: https://github.com/fbagnol/class.unifi.php
- and the API as published by Ubiquiti: https://www.ubnt.com/downloads/unifi/5.5.20/unifi_sh_api
- and the API as published by Ubiquiti: https://dl.ubnt.com/unifi/5.6.18-8261dc5066/unifi_sh_api

## Important Disclaimer

Expand Down
106 changes: 79 additions & 27 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ public function authorize_guest($mac, $minutes, $up = null, $down = null, $MByte
$json = ['cmd' => 'authorize-guest', 'mac' => $mac, 'minutes' => $minutes];

/**
* if we have received values for up/down/MBytes we append them to the payload array to be submitted
* if we have received values for up/down/MBytes/ap_mac we append them to the payload array to be submitted
*/
if (isset($up)) $json['up'] = $up;
if (isset($down)) $json['down'] = $down;
Expand Down Expand Up @@ -341,8 +341,8 @@ public function unblock_sta($mac)
}

/**
* Add/modify a client device note
* -------------------------------
* Add/modify/remove a client device note
* --------------------------------------
* return true on success
* required parameter <user_id> = id of the user device to be modified
* optional parameter <note> = note to be applied to the user device
Expand All @@ -360,14 +360,14 @@ public function set_sta_note($user_id, $note = null)
}

/**
* Add/modify a client device name
* -------------------------------
* Add/modify/remove a client device name
* --------------------------------------
* return true on success
* required parameter <user_id> = id of the user device to be modified
* optional parameter <name> = name to be applied to the user device
* required parameter <user_id> = id of the client device to be modified
* optional parameter <name> = name to be applied to the client device
*
* NOTES:
* - when name is empty or not set, the existing name for the user will be removed
* - when name is empty or not set, the existing name for the client device will be removed
*/
public function set_sta_name($user_id, $name = null)
{
Expand All @@ -378,24 +378,26 @@ public function set_sta_name($user_id, $name = null)
}

/**
* Daily site stats method
* ------------------------
* returns an array of daily stats objects for the current site
* 5 minutes site stats method
* ---------------------------
* returns an array of 5 minutes stats objects for the current site
* optional parameter <start> = Unix timestamp in seconds
* optional parameter <end> = Unix timestamp in seconds
*
* NOTES:
* - defaults to the past 52*7*24 hours
* - bytes" are no longer returned with controller version 4.9.1 and later
* - defaults to the past 12 hours
* - this function/method is only supported on controller versions 5.5.* and later
* - make sure that the retention policy for 5 minutes stats is set to the correct value in
* the controller settings
*/
public function stat_daily_site($start = null, $end = null)
public function stat_5minutes_site($start = null, $end = null)
{
if (!$this->is_loggedin) return false;
$end = is_null($end) ? ((time()-(time() % 3600))*1000) : $end;
$start = is_null($start) ? $end-(52*7*24*3600*1000) : $start;
$end = is_null($end) ? ((time())*1000) : $end;
$start = is_null($start) ? $end-(12*3600*1000) : $start;
$attributes = ['bytes', 'wan-tx_bytes', 'wan-rx_bytes', 'wlan_bytes', 'num_sta', 'lan-num_sta', 'wlan-num_sta', 'time'];
$json = json_encode(['attrs' => $attributes, 'start' => $start, 'end' => $end]);
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/stat/report/daily.site', 'json='.$json));
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/stat/report/5minutes.site', 'json='.$json));
return $this->process_response($content_decoded);
}

Expand All @@ -421,6 +423,54 @@ public function stat_hourly_site($start = null, $end = null)
return $this->process_response($content_decoded);
}

/**
* Daily site stats method
* ------------------------
* returns an array of daily stats objects for the current site
* optional parameter <start> = Unix timestamp in seconds
* optional parameter <end> = Unix timestamp in seconds
*
* NOTES:
* - defaults to the past 52*7*24 hours
* - bytes" are no longer returned with controller version 4.9.1 and later
*/
public function stat_daily_site($start = null, $end = null)
{
if (!$this->is_loggedin) return false;
$end = is_null($end) ? ((time()-(time() % 3600))*1000) : $end;
$start = is_null($start) ? $end-(52*7*24*3600*1000) : $start;
$attributes = ['bytes', 'wan-tx_bytes', 'wan-rx_bytes', 'wlan_bytes', 'num_sta', 'lan-num_sta', 'wlan-num_sta', 'time'];
$json = json_encode(['attrs' => $attributes, 'start' => $start, 'end' => $end]);
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/stat/report/daily.site', 'json='.$json));
return $this->process_response($content_decoded);
}

/**
* 5 minutes stats method for a single access point or all access points
* ---------------------------------------------------------------------
* returns an array of 5 minutes stats objects
* optional parameter <start> = Unix timestamp in seconds
* optional parameter <end> = Unix timestamp in seconds
* optional parameter <mac> = AP MAC address to return stats for
*
* NOTES:
* - defaults to the past 12 hours
* - this function/method is only supported on controller versions 5.5.* and later
* - make sure that the retention policy for 5 minutes stats is set to the correct value in
* the controller settings
*/
public function stat_5minutes_aps($start = null, $end = null, $mac = null)
{
if (!$this->is_loggedin) return false;
$end = is_null($end) ? ((time())*1000) : $end;
$start = is_null($start) ? $end-(12*3600*1000) : $start;
$json = ['attrs' => ['bytes', 'num_sta', 'time'], 'start' => $start, 'end' => $end];
if (!is_null($mac)) $json['mac'] = $mac;
$json = json_encode($json);
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/stat/report/5minutes.ap', 'json='.$json));
return $this->process_response($content_decoded);
}

/**
* Hourly stats method for a single access point or all access points
* ------------------------------------------------------------------
Expand Down Expand Up @@ -472,7 +522,7 @@ public function stat_daily_aps($start = null, $end = null, $mac = null)
/**
* Show all login sessions
* -----------------------
* returns an array of login session objects for all devices
* returns an array of login session objects for all devices or a single device
* optional parameter <start> = Unix timestamp in seconds
* optional parameter <end> = Unix timestamp in seconds
* optional parameter <mac> = client MAC address to return sessions for (can only be used when start and end are also provided)
Expand Down Expand Up @@ -599,8 +649,8 @@ public function list_usergroups()
}

/**
* Assign user device to another group
* -----------------------------------
* Assign client device to another group
* -------------------------------------
* return true on success
* required parameter <user_id> = id of the user device to be modified
* required parameter <group_id> = id of the user group to assign user to
Expand Down Expand Up @@ -679,18 +729,21 @@ public function list_health()
* List dashboard metrics
* ----------------------
* returns an array of dashboard metric objects (available since controller version 4.9.1.alpha)
* optional parameter <five_minutes> = boolean; if true, return stats based on 5 minute intervals,
* returns hourly stats by default (supported on controller versions 5.5.* and higher)
*/
public function list_dashboard()
public function list_dashboard($five_minutes = false)
{
if (!$this->is_loggedin) return false;
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/stat/dashboard'));
$url_suffix = $five_minutes ? '?scale=5minutes' : null;
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/stat/dashboard'.$url_suffix));
return $this->process_response($content_decoded);
}

/**
* List user devices
* -----------------
* returns an array of known user device objects
* List client devices
* -------------------
* returns an array of known client device objects
*/
public function list_users()
{
Expand Down Expand Up @@ -1894,7 +1947,6 @@ private function exec_curl($url, $data = '')
} else {
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
}

} else {
curl_setopt($ch, CURLOPT_POST, false);
if ($this->request_type === 'DELETE') curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
Expand All @@ -1917,7 +1969,7 @@ private function exec_curl($url, $data = '')
$json_decoded_content = json_decode($content, true);

if ($http_code == 401 && isset($json_decoded_content['meta']['msg']) && $json_decoded_content['meta']['msg'] === 'api.err.LoginRequired') {
if ($this->debug) error_log('cURL debug: Needed reconnect to UniFi Controller');
if ($this->debug) error_log('cURL debug: Needed to reconnect to UniFi Controller');

/**
* explicitly unset the old cookie now
Expand Down

0 comments on commit 6fd7e6e

Please sign in to comment.