-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathunifi.js
3199 lines (2822 loc) · 107 KB
/
unifi.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable max-params, camelcase */
/**
*
* UniFi controller class (NodeJS)
*
* This nodejs class provides functionality to query a UniFi controller (www.ubnt.com) through
* its Web-API. The functionality implemented here had been gathered through different
* souces, namely:
*
* UniFi-API-client: https://github.com/Art-of-WiFi/UniFi-API-client/blob/master/src/Client.php
* UniFi-API sh: https://dl.ui.com/unifi/5.12.35/unifi_sh_api
* 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
*
* The majority of the functions in here are actually based on the PHP UniFi-API-client class
* which defines compatibility to UniFi-Controller versions v4 and v5+
*
* Based/Compatible to UniFi-API-client class: v1.1.80
*
* Copyright (c) 2017-2023 Jens Maus <[email protected]>
*
* The source code is distributed under the MIT license
*
*/
'use strict';
const EventEmitter = require('eventemitter2').EventEmitter2;
const WebSocket = require('ws');
const axios = require('axios');
const {CookieJar} = require('tough-cookie');
const {HttpCookieAgent, HttpsCookieAgent} = require('http-cookie-agent/http');
/// ///////////////////////////////////////////////////////////
// PUBLIC CLASS
class Controller extends EventEmitter {
/** CONSTRUCTOR */
constructor(options) {
super({
wildcard: true
});
// Parse opts
this.opts = options || {};
this.opts.host = (typeof (this.opts.host) === 'undefined' ? 'unifi' : this.opts.host);
this.opts.port = (typeof (this.opts.port) === 'undefined' ? 8443 : this.opts.port);
this.opts.username = (typeof (this.opts.username) === 'undefined' ? 'admin' : this.opts.username);
this.opts.password = (typeof (this.opts.password) === 'undefined' ? 'ubnt' : this.opts.password);
this.opts.token2FA = (typeof (this.opts.token2FA) === 'undefined' ? null : this.opts.token2FA);
this.opts.site = (typeof (this.opts.site) === 'undefined' ? 'default' : this.opts.site);
this.opts.sslverify = (typeof (this.opts.sslverify) === 'undefined' ? true : this.opts.sslverify);
this.opts.timeout = (typeof (this.opts.timeout) === 'undefined' ? 5000 : this.opts.timeout);
this.opts.rememberMe = (typeof (this.opts.rememberMe) === 'undefined' ? true : this.opts.rememberMe);
this._baseurl = new URL(`https://${options.host}:${options.port}`);
this._cookieJar = new CookieJar();
this._unifios = false;
this._isClosed = true;
this._autoReconnectInterval = 5 * 1000; // Ms
this._pingPongInterval = 3 * 1000; // Ms
this._isInit = false;
}
/** PUBLIC METHODS */
/**
* Login to the UniFi controller - login()
*
* returns true upon success
*/
async login(username = null, password = null, token2FA = null) {
// Allows to override username+password
if (username !== null) {
this.opts.username = username;
}
if (password !== null) {
this.opts.password = password;
}
if (token2FA !== null) {
this.opts.token2FA = token2FA;
}
// Make sure init() was called
const result = await this._init();
// If init() was already called
// resolve immediately
if (result === 2) {
return true;
}
let endpointUrl = `${this._baseurl.href}api/login`;
if (this._unifios) {
endpointUrl = `${this._baseurl.href}api/auth/login`;
}
// Prepare payload data
const data = {
username: this.opts.username,
password: this.opts.password,
rememberMe: this.opts.rememberMe
};
// Add 2FA token to payload
if (this.opts.token2FA) {
// On UniFiOS 2FA is in 'token' field, else in 'ubic_2fa_token'
data[this._unifios ? 'token' : 'ubic_2fa_token'] = this.opts.token2FA;
}
// Perform the login to the Unifi controller
const response = await this._instance.post(endpointUrl, data, {
timeout: this.opts.timeout
});
// Catch x-csrf-token if supplied in response
if (response.headers['x-csrf-token']) {
this._xcsrftoken = response.headers['x-csrf-token'];
this._instance.defaults.headers.common['x-csrf-token'] = this._xcsrftoken;
}
return true;
}
/**
* Logout from the UniFi controller - logout()
*
* returns true upon success
*/
async logout() {
if (this._unifios === true) {
return this._request('/api/auth/logout', null, 'POST');
}
return this._request('/logout');
}
/**
* Authorize a client device - authorize_guest()
*
* required parameter <mac> = client MAC address
* optional parameter <minutes> = minutes (from now) until authorization expires
* optional parameter <up> = upload speed limit in kbps
* optional parameter <down> = download speed limit in kbps
* optional parameter <megabytes>= data transfer limit in MB
* optional parameter <ap_mac> = AP MAC address to which client is connected, should result in faster authorization
*/
authorizeGuest(mac, minutes = null, up = null, down = null, megabytes = null, ap_mac = null) {
const payload = {cmd: 'authorize-guest', mac: mac.toLowerCase()};
if (minutes !== null) {
payload.minutes = minutes;
}
if (up !== null) {
payload.up = up;
}
if (down !== null) {
payload.down = down;
}
if (megabytes !== null) {
payload.bytes = megabytes;
}
if (ap_mac !== null) {
payload.ap_mac = ap_mac.toLowerCase();
}
return this._request('/api/s/<SITE>/cmd/stamgr', payload);
}
/**
* Unauthorize a client device - unauthorize_guest()
*
* required parameter <mac> = client MAC address
*/
unauthorizeGuest(mac) {
return this._request('/api/s/<SITE>/cmd/stamgr', {cmd: 'unauthorize-guest', mac: mac.toLowerCase()});
}
/**
* Reconnect a client device - reconnect_sta()
*
* required parameter <mac> = client MAC address
*/
reconnectClient(mac) {
return this._request('/api/s/<SITE>/cmd/stamgr', {cmd: 'kick-sta', mac: mac.toLowerCase()});
}
/**
* Block a client device - block_sta()
*
* required parameter <mac> = client MAC address
*/
blockClient(mac) {
return this._request('/api/s/<SITE>/cmd/stamgr', {cmd: 'block-sta', mac: mac.toLowerCase()});
}
/**
* Unblock a client device - unblock_sta()
*
* required parameter <mac> = client MAC address
*/
unblockClient(mac) {
return this._request('/api/s/<SITE>/cmd/stamgr', {cmd: 'unblock-sta', mac: mac.toLowerCase()});
}
/**
* Forget one or more client devices - forget_sta()
*
* return true on success
* required parameter <macs> = array of client MAC addresses
*
* NOTE:
* only supported with controller versions 5.9.X and higher, can be
* slow (up to 5 minutes) on larger controllers
*/
forgetClient(macs) {
return this._request('/api/s/<SITE>/cmd/stamgr', {cmd: 'forget-sta', macs});
}
/**
* Create a new user/client-device - create_user()
*
* return an array with a single object containing details of the new user/client-device on success, else return false
* required parameter <mac> = client MAC address
* required parameter <user_group_id> = _id value for the user group the new user/client-device should belong to which
* can be obtained from the output of list_usergroups()
* optional parameter <name> = name to be given to the new user/client-device
* optional parameter <note> = note to be applied to the new user/client-device
* optional parameter <is_guest> = boolean; defines whether the new user/client-device is a guest or not
* optional parameter <is_wired> = boolean; defines whether the new user/client-device is wi red or not
*/
createUser(mac, user_group_id, name = null, note = null, is_guest = null, is_wired = null) {
const new_user = {mac: mac.toLowerCase(),
user_group_id
};
if (name !== null) {
new_user.name = name;
}
if (note !== null) {
new_user.note = note;
}
if (is_guest !== null) {
new_user.is_guest = is_guest;
}
if (is_wired !== null) {
new_user.is_wired = is_wired;
}
return this._request('/api/s/<SITE>/group/user', {objects: [{data: new_user}]});
}
/**
* Add/modify/remove a client device note - set_sta_note()
*
* required parameter <user_id> = id of the client-device to be modified
* optional parameter <note> = note to be applied to the client-device
*
* NOTES:
* - when note is empty or not set, the existing note for the client-device is removed and "noted" attribute set to false
*/
setClientNote(user_id, note = '') {
return this._request('/api/s/<SITE>/upd/user/' + user_id.trim(), {note});
}
/**
* Add/modify/remove a client device name - set_sta_name()
*
* 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 client device is removed
*/
setClientName(user_id, name = '') {
return this._request('/api/s/<SITE>/upd/user/' + user_id.trim(), {name});
}
/**
* Fetch 5 minutes site stats method - stat_5minutes_site()
*
* returns an array of 5-minute stats objects for the current site
* optional parameter <start> = Unix timestamp in milliseconds
* optional parameter <end> = Unix timestamp in milliseconds
*
* 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
*/
get5minSiteStats(start = null, end = null) {
if (end === null) {
end = Date.now();
}
if (start === null) {
start = end - (12 * 3600 * 1000);
}
const payload = {attrs: ['bytes',
'wan-tx_bytes',
'wan-rx_bytes',
'wan2-tx_bytes',
'wan2-rx_bytes',
'wlan_bytes',
'num_sta',
'lan-num_sta',
'wlan-num_sta',
'time'],
start,
end};
return this._request('/api/s/<SITE>/stat/report/5minutes.site', payload);
}
/**
* Fetch Hourly site stats method - stat_hourly_site()
*
* optional parameter <start> = Unix timestamp in milliseconds
* optional parameter <end> = Unix timestamp in milliseconds
*
* NOTES:
* - defaults to the past 7*24 hours
* - "bytes" are no longer returned with controller version 4.9.1 and later
*/
getHourlySiteStats(start = null, end = null) {
if (end === null) {
end = Date.now();
}
if (start === null) {
start = end - (7 * 24 * 3600 * 1000);
}
const payload = {attrs: ['bytes',
'wan-tx_bytes',
'wan-rx_bytes',
'wan2-tx_bytes',
'wan2-rx_bytes',
'wlan_bytes',
'num_sta',
'lan-num_sta',
'wlan-num_sta',
'time'],
start,
end};
return this._request('/api/s/<SITE>/stat/report/hourly.site', payload);
}
/**
* Fetch Daily site stats method - stat_daily_site()
*
* optional parameter <start> = Unix timestamp in milliseconds
* optional parameter <end> = Unix timestamp in milliseconds
*
* NOTES:
* - defaults to the past 52*7*24 hours
* - "bytes" are no longer returned with controller version 4.9.1 and later
*/
getDailySiteStats(start = null, end = null) {
if (end === null) {
end = Date.now();
}
if (start === null) {
start = end - (52 * 7 * 24 * 3600 * 1000);
}
const payload = {attrs: ['bytes',
'wan-tx_bytes',
'wan-rx_bytes',
'wan2-tx_bytes',
'wan2-rx_bytes',
'wlan_bytes',
'num_sta',
'lan-num_sta',
'wlan-num_sta',
'time'],
start,
end};
return this._request('/api/s/<SITE>/stat/report/daily.site', payload);
}
/**
* Fetch monthly site stats - stat_monthly_site()
*
* @param int $start optional, Unix timestamp in milliseconds
* @param int $end optional, Unix timestamp in milliseconds
* @return array returns an array of monthly stats objects for the current site
*
* NOTES:
* - defaults to the past 52 weeks (52*7*24 hours)
* - "bytes" are no longer returned with controller version 4.9.1 and later
*/
getMonthlySiteStats(start = null, end = null) {
if (end === null) {
end = Date.now();
}
if (start === null) {
start = end - (52 * 7 * 24 * 3600 * 1000);
}
const payload = {attrs: ['bytes',
'wan-tx_bytes',
'wan-rx_bytes',
'wan2-tx_bytes',
'wan2-rx_bytes',
'wlan_bytes',
'num_sta',
'lan-num_sta',
'wlan-num_sta',
'time'],
start,
end};
return this._request('/api/s/<SITE>/stat/report/monthly.site', payload);
}
/**
* Fetch 5 minutes stats method for a single access point or all access points - stat_5minutes_aps()
*
* returns an array of 5-minute stats objects
* optional parameter <start> = Unix timestamp in milliseconds
* optional parameter <end> = Unix timestamp in milliseconds
* 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
*/
get5minApStats(start = null, end = null, mac = null) {
if (end === null) {
end = Date.now();
}
if (start === null) {
start = end - (12 * 3600 * 1000);
}
const payload = {attrs: ['bytes',
'num_sta',
'time'],
start,
end};
if (mac !== null) {
payload.mac = mac.toLowerCase();
}
return this._request('/api/s/<SITE>/stat/report/5minutes.ap', payload);
}
/**
* Fetch Hourly stats method for a single access point or all access points - stat_hourly_aps()
*
* optional parameter <start> = Unix timestamp in milliseconds
* optional parameter <end> = Unix timestamp in milliseconds
* optional parameter <mac> = AP MAC address to return stats for
*
* NOTES:
* - defaults to the past 7*24 hours
* - UniFi controller does not keep these stats longer than 5 hours with versions < 4.6.6
*/
getHourlyApStats(start = null, end = null, mac = null) {
if (end === null) {
end = Date.now();
}
if (start === null) {
start = end - (7 * 24 * 3600 * 1000);
}
const payload = {attrs: ['bytes',
'num_sta',
'time'],
start,
end};
if (mac !== null) {
payload.mac = mac.toLowerCase();
}
return this._request('/api/s/<SITE>/stat/report/hourly.ap', payload);
}
/**
* Fetch Daily stats method for a single access point or all access points - stat_daily_aps()
*
* optional parameter <start> = Unix timestamp in milliseconds
* optional parameter <end> = Unix timestamp in milliseconds
* optional parameter <mac> = AP MAC address to return stats for
*
* NOTES:
* - defaults to the past 7*24 hours
* - UniFi controller does not keep these stats longer than 5 hours with versions < 4.6.6
*/
getDailyApStats(start = null, end = null, mac = null) {
if (end === null) {
end = Date.now();
}
if (start === null) {
start = end - (7 * 24 * 3600 * 1000);
}
const payload = {attrs: ['bytes',
'num_sta',
'time'],
start,
end};
if (mac !== null) {
payload.mac = mac.toLowerCase();
}
return this._request('/api/s/<SITE>/stat/report/daily.ap', payload);
}
/**
* Fetch monthly stats for a single access point or all access points - stat_monthly_aps()
*
* NOTES:
* - defaults to the past 52 weeks (52*7*24 hours)
* - make sure that the retention policy for hourly stats is set to the correct value in
* the controller settings
*
* @param int $start optional, Unix timestamp in milliseconds
* @param int $end optional, Unix timestamp in milliseconds
* @param string $mac optional, AP MAC address to return stats for, when empty,
* stats for all APs are returned
* @return array returns an array of monthly stats objects
*/
getMonthlyApStats(start = null, end = null, mac = null) {
if (end === null) {
end = Date.now();
}
if (start === null) {
start = end - (52 * 7 * 24 * 3600 * 1000);
}
const payload = {attrs: ['bytes',
'num_sta',
'time'],
start,
end};
if (mac !== null) {
payload.mac = mac.toLowerCase();
}
return this._request('/api/s/<SITE>/stat/report/monthly.ap', payload);
}
/**
* Fetch 5 minutes stats method for a single user/client device - stat_5minutes_user()
*
* returns an array of 5-minute stats objects
* required parameter <mac> = MAC address of user/client device to return stats for
* optional parameter <start> = Unix timestamp in milliseconds
* optional parameter <end> = Unix timestamp in milliseconds
* optional parameter <attribs> = array containing attributes (strings) to be returned, valid values are:
* rx_bytes, tx_bytes, signal, rx_rate, tx_rate, rx_retries, tx_retries, rx_packets, tx_packets
* default is ['rx_bytes', 'tx_bytes']
*
* NOTES:
* - defaults to the past 12 hours
* - only supported with UniFi controller versions 5.8.X and higher
* - make sure that the retention policy for 5 minutes stats is set to the correct value in
* the controller settings
* - make sure that "Clients Historical Data" has been enabled in the UniFi controller settings in the Maintenance section
*/
get5minUserStats(mac, start = null, end = null, attribs = null) {
if (end === null) {
end = Date.now();
}
if (start === null) {
start = end - (12 * 3600 * 1000);
}
attribs = attribs === null ? ['time',
'rx_bytes',
'tx_bytes'] : ['time', ...attribs];
const payload = {attrs: attribs,
start,
end,
mac: mac.toLowerCase()};
return this._request('/api/s/<SITE>/stat/report/5minutes.user', payload);
}
/**
* Fetch Hourly stats method for a a single user/client device - stat_hourly_user()
*
* returns an array of hourly stats objects
* required parameter <mac> = MAC address of user/client device to return stats for
* optional parameter <start> = Unix timestamp in milliseconds
* optional parameter <end> = Unix timestamp in milliseconds
* optional parameter <attribs> = array containing attributes (strings) to be returned, valid values are:
* rx_bytes, tx_bytes, signal, rx_rate, tx_rate, rx_retries, tx_retries, rx_packets, tx_packets
* default is ['rx_bytes', 'tx_bytes']
*
* NOTES:
* - defaults to the past 7*24 hours
* - only supported with UniFi controller versions 5.8.X and higher
* - make sure that "Clients Historical Data" has been enabled in the UniFi controller settings in the Maintenance section
*/
getHourlyUserStats(mac, start = null, end = null, attribs = null) {
if (end === null) {
end = Date.now();
}
if (start === null) {
start = end - (7 * 24 * 3600 * 1000);
}
attribs = attribs === null ? ['time',
'rx_bytes',
'tx_bytes'] : ['time', ...attribs];
const payload = {attrs: attribs,
start,
end,
mac: mac.toLowerCase()};
return this._request('/api/s/<SITE>/stat/report/hourly.user', payload);
}
/**
* Fetch Daily stats method for a single user/client device - stat_daily_user()
*
* returns an array of daily stats objects
* required parameter <mac> = MAC address of user/client device to return stats for
* optional parameter <start> = Unix timestamp in milliseconds
* optional parameter <end> = Unix timestamp in milliseconds
* optional parameter <attribs> = array containing attributes (strings) to be returned, valid values are:
* rx_bytes, tx_bytes, signal, rx_rate, tx_rate, rx_retries, tx_retries, rx_packets, tx_packets
* default is ['rx_bytes', 'tx_bytes']
*
* NOTES:
* - defaults to the past 7*24 hours
* - only supported with UniFi controller versions 5.8.X and higher
* - make sure that the retention policy for daily stats is set to the correct value in
* the controller settings
* - make sure that "Clients Historical Data" has been enabled in the UniFi controller settings in the Maintenance section
*/
getDailyUserStats(mac, start = null, end = null, attribs = null) {
if (end === null) {
end = Date.now();
}
if (start === null) {
start = end - (7 * 24 * 3600 * 1000);
}
attribs = attribs === null ? ['time',
'rx_bytes',
'tx_bytes'] : ['time', ...attribs];
const payload = {attrs: attribs,
start,
end,
mac: mac.toLowerCase()};
return this._request('/api/s/<SITE>/stat/report/daily.user', payload);
}
/**
* Fetch monthly stats for a single user/client device - stat_monthly_user()
*
* NOTES:
* - defaults to the past 13 weeks (52*7*24 hours)
* - only supported with UniFi controller versions 5.8.X and higher
* - make sure that the retention policy for monthly stats is set to the correct value in
* the controller settings
* - make sure that "Clients Historical Data" has been enabled in the UniFi controller settings in the Maintenance section
*
* @param string $mac MAC address of user/client device to return stats for
* @param int $start optional, Unix timestamp in milliseconds
* @param int $end optional, Unix timestamp in milliseconds
* @param array $attribs array containing attributes (strings) to be returned, valid values are:
* rx_bytes, tx_bytes, signal, rx_rate, tx_rate, rx_retries, tx_retries, rx_packets, tx_packets
* default is ['rx_bytes', 'tx_bytes']
* @return array returns an array of monthly stats objects
*/
getMonthlyUserStats(mac, start = null, end = null, attribs = null) {
if (end === null) {
end = Date.now();
}
if (start === null) {
start = end - (13 * 7 * 24 * 3600 * 1000);
}
attribs = attribs === null ? ['time',
'rx_bytes',
'tx_bytes'] : ['time', ...attribs];
const payload = {attrs: attribs,
start,
end,
mac: mac.toLowerCase()};
return this._request('/api/s/<SITE>/stat/report/monthly.user', payload);
}
/**
* Fetch 5 minutes gateway stats method - stat_5minutes_gateway()
*
* returns an array of 5-minute stats objects for the gateway belonging to the current site
* optional parameter <start> = Unix timestamp in milliseconds
* optional parameter <end> = Unix timestamp in milliseconds
* optional parameter <attribs> = array containing attributes (strings) to be returned, valid val ues are:
* mem, cpu, loadavg_5, lan-rx_errors, lan-tx_errors, lan-rx_bytes ,
* lan-tx_bytes, lan-rx_packets, lan-tx_packets, lan-rx_dropped, l an-tx_dropped
* default is ['time', 'mem', 'cpu', 'loadavg_5']
*
* 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
* - requires a USG
*/
get5minGatewayStats(start = null, end = null, attribs = null) {
if (end === null) {
end = Date.now();
}
if (start === null) {
start = end - (12 * 3600 * 1000);
}
attribs = attribs === null ? ['time',
'mem',
'cpu',
'loadavg_5'] : ['time', ...attribs];
const payload = {attrs: attribs,
start,
end};
return this._request('/api/s/<SITE>/stat/report/5minutes.gw', payload);
}
/**
* Fetch Hourly gateway stats method - stat_hourly_gateway()
*
* returns an array of hourly stats objects for the gateway belonging to the current site
* optional parameter <start> = Unix timestamp in milliseconds
* optional parameter <end> = Unix timestamp in milliseconds
* optional parameter <attribs> = array containing attributes (strings) to be returned, valid val ues are:
* mem, cpu, loadavg_5, lan-rx_errors, lan-tx_errors, lan-rx_bytes ,
* lan-tx_bytes, lan-rx_packets, lan-tx_packets, lan-rx_dropped, l an-tx_dropped
* default is ['time', 'mem', 'cpu', 'loadavg_5']
*
* NOTES:
* - defaults to the past 7*24 hours
* - requires a USG
*/
getHourlyGatewayStats(start = null, end = null, attribs = null) {
if (end === null) {
end = Date.now();
}
if (start === null) {
start = end - (7 * 24 * 3600 * 1000);
}
attribs = attribs === null ? ['time',
'mem',
'cpu',
'loadavg_5'] : ['time', ...attribs];
const payload = {attrs: attribs,
start,
end};
return this._request('/api/s/<SITE>/stat/report/hourly.gw', payload);
}
/**
* Fetch Daily gateway stats method - stat_daily_gateway()
*
* returns an array of daily stats objects for the gateway belonging to the current site
* optional parameter <start> = Unix timestamp in milliseconds
* optional parameter <end> = Unix timestamp in milliseconds
* optional parameter <attribs> = array containing attributes (strings) to be returned, valid val ues are:
* mem, cpu, loadavg_5, lan-rx_errors, lan-tx_errors, lan-rx_bytes ,
* lan-tx_bytes, lan-rx_packets, lan-tx_packets, lan-rx_dropped, l an-tx_dropped
* default is ['time', 'mem', 'cpu', 'loadavg_5']
*
* NOTES:
* - defaults to the past 52 weeks (52*7*24 hours)
* - requires a USG
*/
getDailyGatewayStats(start = null, end = null, attribs = null) {
if (end === null) {
end = Date.now();
}
if (start === null) {
start = end - (52 * 7 * 24 * 3600 * 1000);
}
attribs = attribs === null ? ['time',
'mem',
'cpu',
'loadavg_5'] : ['time', ...attribs];
const payload = {attrs: attribs,
start,
end};
return this._request('/api/s/<SITE>/stat/report/daily.gw', payload);
}
/**
* Fetch monthly gateway stats - stat_monthly_gateway()
*
* NOTES:
* - defaults to the past 52 weeks (52*7*24 hours)
* - requires a USG
*
* @param int $start optional, Unix timestamp in milliseconds
* @param int $end optional, Unix timestamp in milliseconds
* @param array $attribs array containing attributes (strings) to be returned, valid values are:
* mem, cpu, loadavg_5, lan-rx_errors, lan-tx_errors, lan-rx_bytes,
* lan-tx_bytes, lan-rx_packets, lan-tx_packets, lan-rx_dropped, lan-tx_dropped
* default is ['time', 'mem', 'cpu', 'loadavg_5']
* @return array returns an array of monthly stats objects for the gateway belonging to the current site
*/
getMonthlyGatewayStats(start = null, end = null, attribs = null) {
if (end === null) {
end = Date.now();
}
if (start === null) {
start = end - (52 * 7 * 24 * 3600 * 1000);
}
attribs = attribs === null ? ['time',
'mem',
'cpu',
'loadavg_5'] : ['time', ...attribs];
const payload = {attrs: attribs,
start,
end};
return this._request('/api/s/<SITE>/stat/report/monthly.gw', payload);
}
/**
* Fetch speed test results method - stat_speedtest_results()
*
* returns an array of speed test result objects
* optional parameter <start> = Unix timestamp in milliseconds
* optional parameter <end> = Unix timestamp in milliseconds
*
* NOTES:
* - defaults to the past 24 hours
* - requires a USG
*/
getSpeedTestResults(start = null, end = null) {
if (end === null) {
end = Date.now();
}
if (start === null) {
start = end - (24 * 3600 * 1000);
}
const payload = {
attrs: ['xput_download',
'xput_upload',
'latency',
'time'],
start,
end};
return this._request('/api/s/<SITE>/stat/report/archive.speedtest', payload);
}
/**
* Fetch IPS/IDS events methods - stat_ips_events
*
* returns an array of IPS/IDS event objects
* optional parameter <start> = Unix timestamp in milliseconds
* optional parameter <end> = Unix timestamp in milliseconds
* optional parameter <limit> = Maximum number of events to return, defaults to 10000
*
* NOTES:
* - defaults to the past 24 hours
* - requires a USG
* - supported in UniFi controller versions 5.9.X and higher
*/
getIPSEvents(start = null, end = null, limit = 10_000) {
if (end === null) {
end = Date.now();
}
if (start === null) {
start = end - (24 * 3600 * 1000);
}
const payload = {start,
end,
_limit: limit};
return this._request('/api/s/<SITE>/stat/ips/event', payload);
}
/**
* Fetch login sessions - stat_sessions()
*
* 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)
* optional parameter <type> = client type to return sessions for, can be 'all', 'guest' or 'user'; default value is 'all'
*
* NOTES:
* - defaults to the past 7*24 hours
*/
getSessions(start = null, end = null, mac = null, type = 'all') {
if (end === null) {
end = Math.floor(Date.now() / 1000);
}
if (start === null) {
start = end - (7 * 24 * 3600);
}
const payload = {type,
start,
end};
if (mac !== null) {
payload.mac = mac.toLowerCase();
}
return this._request('/api/s/<SITE>/stat/session', payload);
}
/**
* Fetch latest 'n' login sessions for a single client device - stat_sta_sessions_latest()
*
* required parameter <mac> = client MAC address
* optional parameter <limit> = maximum number of sessions to get (defaults to 5)
*
*/
getLatestSessions(mac, limit = 5) {
const payload = {mac: mac.toLowerCase(),
_limit: limit,
_sort: '-assoc_time'};
return this._request('/api/s/<SITE>/stat/session', payload);
}
/**
* Fetch authorizations - stat_auths()
*
* optional parameter <start> = Unix timestamp in seconds
* optional parameter <end> = Unix timestamp in seconds
*
* NOTES:
* - defaults to the past 7*24 hours
*/
getAllAuthorizations(start = null, end = null) {
if (end === null) {
end = Math.floor(Date.now() / 1000);
}
if (start === null) {
start = end - (7 * 24 * 3600);
}
return this._request('/api/s/<SITE>/stat/authorization', {start, end});
}
/**
* Fetch client devices that connected to the site within given timeframe - stat_allusers()