-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathunifi.py
executable file
·2617 lines (2272 loc) · 118 KB
/
unifi.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# N Waterton V 1.0.1 13th March 2019 - Major re-write to allow different screen resolutions.
# N.Waterton V 1.1.1 14th May 2019 - Added support for SFP+ ports.
# N.Waterton V 1.1.2 15th May 2019 - Added secondary port speed for aggregated ports
# N.Waterton V 1.1.3 16th May 2019 - Made 'models' a loadable file
# N.Waterton V 1.1.4 17th May 2019 - Added simulation mode
# N.Waterton V 1.1.5 24th may 2019 - Minor fix to port enabled
# N Waterton V 1.2.0 11th July 2019 - Rework of database structure to allow new devices (UDM sort of added, but not fully integrated yet).
# removed "ports" from AP definitions as not needed.
# can now read unifi data directly to draw device.
# N Waterton V 1.2.1 29th july 2019 - Fixes for Flex 5 POE Switch.
# N Waterton V 1.2.2 23 August 2019 - Add display of POE power and port name even if port is not used for data, if POE power consumption >0
# N Waterton V 1.2.3 13th February added basic support for UDM Pro
# N Waterton V 1.2.4 15th February added enhanced support for UDM Pro
# N Waterton V 1.3.0 20th February major re-write for UDM Pro, new category of device "udm"
# N Waterton V 1.3.1 21st February added api call feature to get UDMP temperature
# N Waterton V 1.3.2 4th June 2020 removed api call for UDMP temperature, and added handling for UDMP temperature in update_from_data()
__VERSION__ = '1.3.2'
import gi
gi.require_version('GLib', '2.0')
from gi.repository import GLib
gi.require_version('Grx', '3.0')
from gi.repository import Grx
import random, time
import json
import sys, os
from multiprocessing import Process, Value, Queue
import queue
from subprocess import check_output
from collections import OrderedDict
try:
import configparser
except ImportError:
import ConfigParser as configparser
#from controller import Controller
from unifi_client import UnifiClient
import logging
from logging.handlers import RotatingFileHandler
class UnifiApp(Grx.Application):
"""Base class for simple UniFi display"""
def __init__(self, arg):
super(Grx.Application, self).__init__()
self.init()
self.hold()
Grx.mouse_set_cursor(None)
#set default colors and fonts
global white, black, green, yellow, cyan, blue, red, magenta, dark_gray, default_text_opt, text_height, text_width
colors = Grx.color_get_ega_colors()
white = colors[int(Grx.EgaColorIndex.WHITE)]
black = colors[Grx.EgaColorIndex.BLACK]
green = colors[Grx.EgaColorIndex.GREEN]
yellow = Grx.color_get(204,204,0)#colors[Grx.EgaColorIndex.YELLOW] #use darker yellow
cyan = colors[Grx.EgaColorIndex.CYAN]
blue = colors[Grx.EgaColorIndex.BLUE]
magenta = colors[Grx.EgaColorIndex.MAGENTA]
red = colors[Grx.EgaColorIndex.RED]
dark_gray = Grx.color_get(47,79,79)#colors[Grx.EgaColorIndex.DARK_GRAY] #this is a slate gray
self.set_default_text_size(arg.font_size)
self.arg = arg
self.port_size=0
self.min_port_size = self.port_size
self.draw_devices = []
self.redraw_all = False #causes redraw after creation if set to True
def set_default_text_size(self, size=14):
global default_text_opt, text_height, text_width
default_text_opt = Grx.TextOptions.new_full(
# Don't want to use the dpi-aware font here so we can cram info on to small screens (font size, 8,10,12,14 etc)
Grx.Font.load_full('LucidaTypewriter', size, -1, Grx.FontWeight.REGULAR,
Grx.FontSlant.REGULAR, Grx.FontWidth.REGULAR, True, None),
white, black,
Grx.TextHAlign.LEFT, Grx.TextVAlign.TOP)
#text height/width
text_height = default_text_opt.get_font().get_text_height('0')
text_width = default_text_opt.get_font().get_text_width('0')
def set_default_positions(self):
self.draw_devices = []
self.redraw_all = True
self.port_size=0 #min port size
self.y_update_pos = self.default_update_position #where the key etc is displayed (y pos)
self.x_pos = self.default_left_margin
self.text_lines = self.default_text_lines.copy()
def duplicate_text_opts(self, text_object):
return Grx.TextOptions.new_full(text_object.get_font(),
text_object.get_fg_color(), text_object.get_bg_color(),
text_object.get_h_align(), text_object.get_v_align())
def do_event(self, event):
"""called when an input event occurs
overrides Grx.Application.do_event
"""
if Grx.Application.do_event(self, event):
return True
if event.type in (Grx.EventType.KEY_DOWN, Grx.EventType.BUTTON_PRESS,
Grx.EventType.TOUCH_DOWN):
if not self.check_touch_device(event):
self.quit()
return True
return False
def check_touch_device(self, event):
log.info('event type is: %s' % event.type)
if event.type == Grx.EventType.TOUCH_DOWN:
x = event.touch.x
y = event.touch.y
elif event.type == Grx.EventType.BUTTON_PRESS:
x = event.button.x
y = event.button.y
else:
return False
log.info('location x: %s, y: %s' % (x,y))
draw_devices = False
if self.zoomed:
#reset from zoomed
self.zoomed = False
for devices in self.all_devices:
for id in devices.copy().keys():
for current_id in self.draw_devices:
if id == current_id:
devices.pop(id) #force recreation of device with new size parameters
self.set_default_positions()
draw_devices = True
if not draw_devices:
for devices in self.all_devices:
for id, device in devices.items():
log.debug('checking device: %s, device_x: %s, right: %s, y:%s, bottom;%s' % (device.name, device.x,device.device_right,device.y,device.device_bottom))
if x >= device.x and x <= device.device_right and y >= device.y and y <= device.device_bottom:
log.info('touched device: %s' % device.name)
self.draw_devices =[id]
devices.pop(id) #force recreation of device with new size parameters
if device.type == 'usw':
self.port_size=Grx.get_height()//2#22
self.text_lines['usw'] = 2
elif device.type == 'ugw':
self.port_size=Grx.get_height()//4#140
self.text_lines['ugw'] = 8
self.x_pos = None
elif device.type == 'udm':
self.port_size=Grx.get_height()//6
self.text_lines['udm'] = 7
self.x_pos = None
else: #uap
self.port_size=Grx.get_height()//4#140
self.text_lines['uap'] = 7
self.x_pos = None
if self.update_height:
self.y_update_pos = Grx.get_height()-self.update_height - 10 #(10 margin)
else:
self.y_update_pos = 460 #where the key etc is displayed (y pos)
log.info('Update Position set to: %s, update_height: %s' % (self.y_update_pos,self.update_height))
self.zoomed = True
draw_devices = True
break
if draw_devices:
Grx.clear_context(self.black)
#self.network_switches = {}
#self.usg = {}
#self.udm = {}
#self.uap = {}
self.redraw_key = True
self.draw_all_devices(True)
return True
self.exit.value = True
while not self.q.empty():
log.info('Waiting for queue to empty')
self.devices = self.q.get()
#self.worker.terminate()
#self.worker.join()
log.info('Program Exit')
kill_text = '/usr/bin/sudo kill -9 %s' % self.worker.pid
check_output(kill_text.split())
sys.exit(0)
return False
# GLib.Application requires that we implement (override) the activate
# method.
def do_activate(self):
Grx.user_set_window(0,0,799,479) #set for 800X480 screen size (but does not seem to do anything).
self.white = white
self.black = black
self.green = green
self.yellow = yellow
self.cyan = cyan
self.red = red
self.blue = blue
self.magenta = magenta
self.dark_gray = dark_gray
self.default_text_opt = default_text_opt
#text height/width
self.text_height = text_height
self.text_width = text_width
self.x = Grx.get_width()
self.y = Grx.get_height()
self.default_text_lines = { 'usw':1,
'ugw':6,
'udm':5,
'uap':3
}
self.text_lines = self.default_text_lines.copy()
self.default_update_position = None #where the key etc is displayed (y pos) - initially None (no display) until USG is drawn, so we can position it below the USG
if self.arg.simulate:
self.default_update_position = self.y//2
self.key_height = None #Key height - gets figured out when key is drawn
self.key_spacing = 5 #y spacing between key boxes
self.update_height = None #height of update display - gets figured out when it's displayed
self.update_text_opt = self.duplicate_text_opts(default_text_opt) #text size for key can be changed
self.update_text_height = self.update_text_opt.get_font().get_text_height('0')
self.update_text_width = self.update_text_opt.get_font().get_text_width('0')
self.default_left_margin = 10 #not used for switches, switches always display 10 in from the right
self.default_top_margin = 10
self.network_switches = {}
self.usg = {}
self.udm = {}
self.uap = {}
self.ap_spacing = None #horizontal spacing of ap's
self.ap_extra_text=0 #extra text lines to fit in Ap's if possible (gets updated later)
self.all_devices = [self.network_switches, self.usg, self.udm, self.uap]
self.device_locations = {}
'''
self.line_opts = Grx.LineOptions()
self.line_opts.color = self.white
self.line_opts.width = 3
self.line_opts.n_dash_patterns = 2
self.line_opts.dash_pattern0 = 6
self.line_opts.dash_pattern1 = 4
self.line_opts0 = Grx.LineOptions()
'''
self.update = Value('i', 0) #for multiprocess
self.last_update = time.time()
self.last_update_text = time.ctime()
self.blink = True
self.devices = []
self.x_update_pos = 15
self.y_update_pos = self.default_update_position
self.x_pos = 10
self.redraw_key = True
self.zoomed = False
self.custom = None
if self.arg.custom:
self.load_config(self.arg.custom)
#multiprocess stuff
self.exit = Value('i', 0) #False
self.q = Queue()
self.send_q = Queue()
self.data_q = Queue()
self.extra_data = None
self.worker = Process(target=self.get_unifi_data)
self.worker.daemon=True
self.worker.start()
GLib.timeout_add_seconds(1,self.draw_update)
GLib.timeout_add_seconds(1,self.draw_all_devices)
#GLib.idle_add(self.draw_all_devices)
def load_config(self, file):
'''
loads custom config file
'''
self.custom = {}
config = configparser.ConfigParser(delimiters=('=', '('), interpolation=configparser.ExtendedInterpolation())
config.read(file)
#spacing of AP's (included to disable auto sizing and spacing)
self.ap_spacing = 0
self.custom_working = {}
if 'default' in config:
default = config['default']
font_size = default.getint('font_size',self.arg.font_size)
self.set_default_text_size(font_size)
self.text_height = text_height
self.text_width = text_width
self.default_text_opt = default_text_opt
#key display default location
self.x_update_pos = default.getint('x_update_pos',self.x_update_pos)
self.y_update_pos = default.getint('y_update_pos',self.default_update_position)
self.default_update_position = self.y_update_pos
update_text_size = default.getint('update_font_size', None)
if update_text_size:
self.update_text_opt = Grx.TextOptions.new_full(
# Don't want to use the dpi-aware font here so we can cram info on to small screens (font size, 8,10,12,14 etc)
Grx.Font.load_full('LucidaTypewriter', update_text_size, -1, Grx.FontWeight.REGULAR,
Grx.FontSlant.REGULAR, Grx.FontWidth.REGULAR, True, None),
white, black,
Grx.TextHAlign.LEFT, Grx.TextVAlign.TOP)
#text height/width
self.update_text_height = self.update_text_opt.get_font().get_text_height('0')
self.update_text_width = self.update_text_opt.get_font().get_text_width('0')
if 'ugw' in config:
ugw = config['ugw']
self.custom['ugw'] = {}
for usg, value in ugw.items():
if '=' in value:
value = value.split('=')[1].strip()
self.custom['ugw'][usg] = eval(value)
self.default_text_lines['ugw'] = int(self.custom['ugw'][usg][-1])
log.info('UGW custom: %s=%s' % (usg,value))
if 'udm' in config:
udm = config['udm']
self.custom['udm'] = {}
for udm, value in udm.items():
if '=' in value:
value = value.split('=')[1].strip()
self.custom['udm'][udm] = eval(value)
self.default_text_lines['udm'] = int(self.custom['udm'][udm][-1])
log.info('UDM custom: %s=%s' % (udm,value))
if 'usw' in config:
usw = config['usw']
self.custom['usw'] = {}
for switch, value in usw.items():
if '=' in value:
value = value.split('=')[1].strip()
self.custom['usw'][switch] = eval(value)
log.info('USW custom: %s=%s' % (switch,value))
if 'uap' in config:
uap = config['uap']
self.custom['uap'] = {}
for uap, value in uap.items():
if '=' in value:
value = value.split('=')[1].strip()
self.custom['uap'][uap] = eval(value)
log.info('UAP custom: %s=%s' % (uap,value))
self.text_lines = self.default_text_lines.copy()
def draw_key(self, x=30, y=182):
#x = 30
#y = 182
initial_y = y
box_size = self.update_text_height #20
spacing = self.key_spacing
key = OrderedDict( [('>= 2000 MBps', {'shape': 'square', 'color':self.magenta}),
('= 1000 MBps', {'shape': 'square', 'color':self.green}),
('= 100 MBps', {'shape': 'square', 'color':self.yellow}),
('= 10 MBps', {'shape': 'square', 'color':self.cyan}),
('= Up/DownLink', {'shape': 'circle', 'color':self.green})
])
x+=spacing*2
for text, color in key.items():
#y+= box_size + spacing
Grx.draw_filled_rounded_box(x, y, x+box_size, y+box_size, 3, color['color'])
if color['shape'] == 'circle':
Grx.draw_filled_circle(x+box_size//2, y+box_size//2, box_size//4, self.blue)
Grx.draw_text(text, x+self.update_text_width*5/2, y, self.update_text_opt)
y+= box_size + spacing
self.redraw_key = False
return y - spacing - initial_y #key height
def draw_update(self):
if self.exit.value:
return False
if self.y_update_pos is None:
return GLib.SOURCE_CONTINUE
x = self.x_update_pos
y = self.y_update_pos
update_offset = 3 #spacing from item above
key_top_offset = self.update_text_height+update_offset
#draw last update time text
Grx.draw_filled_box(max(0,x-10), y+update_offset, max(0,x-10)+self.update_text_opt.get_font().get_text_width(self.last_update_text[:19]), y+update_offset+self.update_text_height, self.black)
Grx.draw_text(self.last_update_text[:19], max(0,x-10), y+update_offset, self.update_text_opt)
if self.redraw_key:
self.key_height = self.draw_key(x+self.update_text_width, y+key_top_offset+update_offset)
min_pos = y + key_top_offset #top of bar graph
y = min_pos + self.key_height+update_offset #bottom of bar graph
line_opts = Grx.LineOptions()
line_opts.width = self.update_text_width
offset = self.key_spacing #between bars
height = self.update_text_height #of bar
#blank bar if it gets to min_pos
if y-((offset+height)*self.update.value) < min_pos-update_offset:
line_opts.color = self.black
Grx.draw_line_with_options(x,y,x,min_pos,line_opts)
self.update.value = 1
if self.blink:
if time.time() - self.last_update < 60:
line_opts.color = self.green
else:
line_opts.color = self.red
else:
line_opts.color = self.black
start = y
end = y-height
#draw bar
for seg in range(self.update.value):
Grx.draw_line_with_options(x,start,x,end,line_opts)
start= end-offset
end=start-height
if end < min_pos:
end = min_pos
self.blink = not self.blink
self.update_height = y-self.y_update_pos
return GLib.SOURCE_CONTINUE
def get_unifi_data(self):
simulate_update = True
if not self.arg.simulate:
client = UnifiClient(arg.username, arg.password, arg.IP, arg.port, ssl_verify=arg.ssl_verify)
while not self.exit.value:
try:
with self.update.get_lock():
self.update.value+=1
log.info('Refreshing Data')
if self.arg.simulate:
while not self.send_q.empty():
self.send_q.get() #empty send queue
if simulate_update:
devices = self.arg.simulate
simulate_update = False
else:
time.sleep(5)
else:
devices = client.devices() #will block here until device update is received
if not self.send_q.empty():
command = self.send_q.get()
log.info('Sending API command: %s' % command)
data = client.api(command)
self.data_q.put(data)
self.q.put(devices)
log.info('Data Updated')
except Exception as e:
log.info('Error getting data: %s' % e)
self.last_update = 0
time.sleep(5)
if log.getEffectiveLevel() == logging.DEBUG:
with open('data.json', 'w') as f:
f.write(json.dumps(devices, indent=2))
self.q.close()
self.client = None
def deduplicate_list(self, base_list):
temp=OrderedDict()
for d in base_list:
temp[d['_id']] = d
return list(temp.values())
def update_list(self, base_list, update_list):
try:
#eliminate earlier duplicates
base_list = self.deduplicate_list(base_list)
update_list = self.deduplicate_list(update_list)
for item in update_list:
for id, device in enumerate(base_list.copy()):
if device['_id'] == item['_id']:
base_list.remove(device)
base_list.insert(id,item)
break
else:
base_list.append(item)
log.debug('Total Number of Devices: %d' % len(base_list))
except Exception as e:
log.info('ERROR: %s' % e)
return base_list
def initialise_custom_dicts(self, name, devices):
if not self.custom_working.get(name):
self.custom_working[name] = {}
try:
for key in self.custom[name].copy().keys():
for device in devices:
device_id = device["device_id"]
if key == device_id:
self.custom_working[name][device_id] = self.custom[name].pop(device_id)
log.info('Custom config device_id: %s (%s) found in %s' % (device_id, device["name"], name))
except KeyError as e:
log.error('Custom Dicts: Key Error: %s' % e)
del self.custom_working[name]
return
if len(self.custom[name]) > 0:
for device in devices:
device_id = device["device_id"]
if device_id in self.custom_working[name]:
continue
try:
key = next(iter(self.custom[name]))
value = self.custom[name].pop(key, None)
if value is not None:
log.info('Custom config %s assigned to device_id: %s(%s)' % (key, device_id, device["name"]))
self.custom_working[name][device_id] = value
except StopIteration:
break
def draw_custom_device(self, name, devices, type):
if self.custom.get(name):
self.initialise_custom_dicts(name, devices)
if self.custom_working.get(name):
for custom_device_id, param in self.custom_working[name].items():
for device in devices:
device_id = device["device_id"]
if custom_device_id == device_id:
#log.info("%s(%s), Param: %s" % (device["name"], device_id, param))
if isinstance(param,tuple):
log.info('%s(%s), x: %s, y: %s port_size: %s, text_lines: %s' % (device["name"], device_id, param[0], param[1], param[2], param[3]))
self.text_lines[name] = param[3]
self.create_devices(param[0], param[1], type, [device], param[2])
def draw_all_devices(self, override=False):
if not override:
if self.q.empty():
return GLib.SOURCE_CONTINUE
devices =[]
while not self.q.empty():
devices+=self.q.get()
self.devices = self.update_list(self.devices, devices)
if not self.data_q.empty():
self.extra_data = self.data_q.get()
else:
devices = self.devices
switches = []
usgs = []
udms = []
uaps=[]
for device in devices:
if device["type"]=='usw':
switches.append(device)
elif device["type"]=='ugw':
usgs.append(device)
elif device["type"]=='udm':
udms.append(device)
elif device["type"]=='uap':
uaps.append(device)
log.info('number of usgs: %s, udms: %s, switches: %s, aps: %s' % (len(usgs),len(udms),len(switches),len(uaps)))
if self.custom and not self.zoomed:
#draw custom devices
self.draw_custom_device('ugw', usgs, self.usg)
self.draw_custom_device('udm', udms, self.udm)
self.draw_custom_device('usw', switches, self.network_switches)
self.draw_custom_device('uap', uaps, self.uap)
else:
#auto layout/zoomed layout
last_switch_pos = self.create_devices(-10, self.default_top_margin, self.network_switches, switches) #auto 10 in from the right, 10 down
if len(usgs) > 0: #can't have USG and UDM...
last_usg_position = self.create_devices(self.x_pos, self.default_top_margin, self.usg, usgs)
elif len(udms) > 0:
last_usg_position = self.create_devices(self.x_pos, self.default_top_margin, self.udm, udms)
else:
last_usg_position = last_switch_pos
if self.default_update_position is None: #set initial key position below USG/UDM
self.default_update_position = last_usg_position - self.text_height//2
self.set_default_positions()
if self.x_pos is not None:
x_pos = self.x_pos - 4 #normally 6 from left side
else:
x_pos = self.x_pos
self.create_devices(x_pos, last_switch_pos+5, self.uap, uaps)
self.update_device(self.network_switches, switches)
self.update_device(self.usg, usgs)
self.update_device(self.udm, udms)
self.update_device(self.uap, uaps)
self.last_update = time.time()
self.last_update_text = time.ctime()
log.debug('Updated time to: %s' % self.last_update_text)
self.redraw_all = False
return GLib.SOURCE_CONTINUE
def create_devices(self, x, y, devices, data, port_size=None):
last_y_pos = y
last_ap_x_pos = None
org_x = x
org_y = y
device_height = ap_ports = ap_single_ports = ap_margin = 0
if not port_size:
port_size=self.port_size
max_right = Grx.get_width()
spacing = self.ap_spacing
if spacing is None:
spacing = self.text_width//2
log.info('Drawing Devices with horizontal spacing of: %s, max_right: %s' % (spacing, max_right))
if len(data) > 0:
count = -1
#create devices
for device in data:
count +=1
id = device["device_id"]
name = device["name"]
model = device["model"]
type = device["type"]
device['zoomed']=self.zoomed #add 'zoomed' property into data
#save locations for redrawing
if not self.zoomed:
try:
x = self.device_locations[id].get('x', x)
y = self.device_locations[id].get('y', y)
except KeyError:
self.device_locations[id] = {'x':x,'y':y}
if len(self.draw_devices) > 0 and id not in self.draw_devices:
continue
if id not in devices:
ports = 0
for port in device["ethernet_table"]: #no easy way to figure out the actual number of ports (but not really needed anyway)...
ports+=port.get("num_port",0)
if type == 'usw':
log.info('creating switch: %s' % name)
devices[id]=(NetworkSwitch(x,y, ports, device, model=model, port_size=port_size, text_lines=self.text_lines[type], parent=self))
#Vertical spacing of switches increment next switch this many down
last_y_pos = y = devices[id].device_bottom + self.text_height//2
elif type == 'ugw':
log.info('creating usg: %s' % name)
devices[id]=(USG(x,y, ports, device, model=model, port_size=port_size, text_lines=self.text_lines[type], parent=self))
#Vertical spacing of usg's increment next switch this many down (of course should only be one...)
last_y_pos = y = devices[id].device_bottom + self.text_height//2
log.info('USG right: %s' % devices[id].device_right)
elif type == 'udm':
log.info('creating udm: %s' % name)
devices[id]=(UDM(x,y, ports, device, model=model, port_size=port_size, text_lines=self.text_lines[type], parent=self))
#Vertical spacing of udm's increment next switch this many down (of course should only be one...)
last_y_pos = y = devices[id].device_bottom + self.text_height//2
log.info('UDM right: %s' % devices[id].device_right)
elif type == 'uap':
#first run is always a dry run
#if self.arg.simulate:
# self.ap_spacing = 10
extra_text = self.ap_extra_text
port_size = max(port_size,self.min_port_size)
log.info('creating uap: %s at x: %s, spacing: %s port_size: %s, extra_text: %s' % (name, x, spacing, port_size, extra_text))
devices[id]=(UAP(x,y, ports, device, model=model, port_size=port_size, text_lines=self.text_lines[type]+extra_text, dry_run=self.ap_spacing is None, parent=self))
new_port_size=devices[id].port_height
ap_ports+=devices[id].num_ports
device_height=devices[id].device_height
if devices[id].num_ports == 1:
ap_single_ports+=1
device_bottom=devices[id].device_bottom
log.debug('AP info: device_right: %s, x: %s, num_ports: %s, port_width: %s, spacing: %s' % (devices[id].device_right,x,devices[id].num_ports,devices[id].port_width,spacing))
if x is not None:
ap_margin+=(devices[id].device_right-x)-(devices[id].num_ports*devices[id].port_width)+spacing
#horizontal spacing of AP's
last_ap_x_pos = devices[id].device_right
x = devices[id].device_right + spacing
#if dry run, don't save device
if self.ap_spacing is None:
devices.pop(id, None)
self.device_locations.pop(id, None)
log.info('AP Drawn at end x: %s, max pos: %s, port-size: %s, device_bottom: %s, max: %s' % (last_ap_x_pos, max_right, new_port_size, device_bottom, Grx.get_height()))
if self.ap_spacing is None and last_ap_x_pos is not None:
#just created Ap's dry run, so calculate spacing evenly across display
#fit extra text in if we have space.
#set ap_spacing in custom config to skip these sections
#find new port size that fits available space
if self.min_port_size == 0:
ap_margin-=spacing
right_target = new_port_size+(max_right-last_ap_x_pos)//ap_ports
if right_target > 100 and ap_single_ports > 0:
#if we only have 1 large port overall width is increased by port_width//2 (on either side)
last_ap_x_pos = org_x+ ap_margin + ((right_target)*ap_single_ports + right_target*ap_ports)
while last_ap_x_pos > max_right:
right_target-=1
last_ap_x_pos = org_x+ ap_margin + (right_target*ap_ports)
if right_target > 100:
last_ap_x_pos += right_target*ap_single_ports
bottom_target = new_port_size+(Grx.get_height()-device_bottom)-self.text_height//2
self.min_port_size = min(bottom_target,right_target)
self.ap_extra_text = extra_text
#if we have room for extra text
if bottom_target > right_target and self.arg.extra_text:
self.ap_extra_text = (bottom_target - right_target)//self.text_height
#minimum port size 4 chars!
if self.min_port_size < self.text_width*4:
self.text_lines[type] = 1
self.min_port_size = self.text_width*4
log.info('Recalculated Port Size: total number of ports: %s, ap_margin: %s, b_target: %s, r_target: %s, new port size: %s' % (ap_ports,ap_margin,bottom_target, right_target,self.min_port_size))
#second dry run, as now we have to calculate the spacing for the new, resized AP's
self.create_devices(org_x, org_y, devices, data, port_size)
#calculate spacing of ap's
num_aps = len(data)
min_spacing = max(0,(last_ap_x_pos - org_x)//(num_aps+1))
new_x = max_right//2 - ((last_ap_x_pos - org_x)//2)
if num_aps < 2:
self.ap_spacing = min_spacing
org_x=new_x
else:
self.ap_spacing = min(min_spacing,((max_right - org_x - last_ap_x_pos)//(num_aps-1)) + self.text_width//2)
org_x=new_x - ((self.ap_spacing-self.text_width//2)*(num_aps-1)//2)
log.info('recalculating spacing - last x pos: %s - recreating APs, new spacing: %s' % (last_ap_x_pos, self.ap_spacing))
#actually create devices for real
self.create_devices(org_x, org_y, devices, data, port_size)
return last_y_pos
def update_device(self, devices, data):
for id, device in devices.items():
if len(self.draw_devices) > 0 and id not in self.draw_devices:
continue
if self.redraw_all:
device.commit_changes(forced=True)
for device_data in data:
type = device_data["type"]
if id == device_data["device_id"]: #"device_id" is the same as "_id"
log.info('updating device: %s' % device.name)
device.store_data(device_data)
class NetworkPort():
port_mode = { 0:'normal',
1:'sfp',
2:'sfp+'}
def __init__(self, x, y, port_number=1, port_type=0, POE=False, port_width=30, port_height=30, initial_data={}, parent=None):
#colors and fonts
self.white = white
self.black = black
self.green = green
self.yellow = yellow
self.cyan = cyan
self.red = red
self.blue = blue
self.magenta = magenta
self.dark_gray = dark_gray
self.parent = parent
self.default_text_opt = self.duplicate_text_opts(default_text_opt)
self.default_text_opt.set_h_align(Grx.TextHAlign.CENTER)
self.default_text_opt.set_v_align(Grx.TextVAlign.MIDDLE)
#text height/width
self.text_height = text_height
self.text_width = text_width
self.x = x
self.y = y
#fixed things
self.port_number = port_number
self.port_width = port_width
self.port_height = port_height
self.port_type=port_type
self.port_description=self.port_mode.get(port_type,0)
self.sfp_offset = 0
if self.port_type > 0:
self.sfp_offset = 10
self.poe = POE
#things which may be updated (stored in port_params)
self.port_params=initial_data
self.clean = False
self.commit = {}
self.draw_port()
def duplicate_text_opts(self, text_object):
return Grx.TextOptions.new_full(text_object.get_font(),
text_object.get_fg_color(), text_object.get_bg_color(),
text_object.get_h_align(), text_object.get_v_align())
def draw_port(self):
if self.clean:
return
if not self.parent.enabled:
self.enabled = False
secondary_speed_text = '' if self.secondary_speed is None else '(%s)' % self.secondary_speed
log.info('Drawing Port : %d, %s, speed:%s%s, power:%s as %s' % (self.port_number, self.name, self.speed, secondary_speed_text, self.power, 'ENABLED' if self.enabled else 'DISABLED'))
port_number_text_opts = self.duplicate_text_opts(self.default_text_opt)
port_number_text_opts.set_fg_color(self.white)
port_number_text_opts.set_bg_color(self.parent.bg_color)
port_number_text_opts.set_v_align(Grx.TextVAlign.TOP)
port_text_opts = self.duplicate_text_opts(self.default_text_opt)
color = self.get_color()
port_text_opts.set_bg_color(color)
port_text_opts.set_fg_color(self.white)
port_text_opts.set_v_align(Grx.TextVAlign.MIDDLE)
Grx.draw_text(str(self.port_number), self.x+self.port_width//2, self.y-self.text_height, port_number_text_opts)
Grx.draw_filled_rounded_box(self.x, self.y, self.x+self.port_width, self.y+self.port_height, 3, color)
if color == self.black and float(self.power)==0:
#log.info("POWER: %s" % self.power)
port_color = self.white
if not self.enabled:
port_color = self.red
Grx.draw_rounded_box(self.x, self.y, self.x+self.port_width, self.y+self.port_height, 3, port_color)
else:
if self.get_secondary_color() is not None:
self.draw_secondary_color()
if self.is_downlink == -1:
self.draw_downlink()
elif self.is_downlink == 1:
self.draw_uplink()
text = [self.name[:self.port_width//self.text_width]]
poe_offset = 0
if self.poe:
if float(self.power)!=0:
text = [self.power,
self.name[:self.port_width//self.text_width]]
poe_offset = self.text_height//2
y_text = self.y+self.port_height/2 - len(text)*self.text_height + poe_offset
for line, txt in enumerate(text,1):
Grx.draw_text(txt, self.x+self.port_width/2, y_text+(line*self.text_height), port_text_opts)
self.clean = True
def draw_downlink(self):
#Downwards triangle
pt_1 = Grx.Point()
pt_2 = Grx.Point()
pt_3 = Grx.Point()
pt_1.x = self.x+self.port_width//6
pt_1.y = self.y+self.port_height//6
pt_2.x = self.x+5*self.port_width//6
pt_2.y = self.y+self.port_height//6
pt_3.x = self.x+self.port_width//2
pt_3.y = self.y+5*self.port_height//6
points = [pt_1, pt_2, pt_3, pt_1]
Grx.draw_filled_polygon(points, self.blue)
def draw_uplink(self):
#Upwards triangle
pt_1 = Grx.Point()
pt_2 = Grx.Point()
pt_3 = Grx.Point()
pt_1.x = self.x+self.port_width//2
pt_1.y = self.y+self.port_height//6
pt_2.x = self.x+5*self.port_width//6
pt_2.y = self.y+5*self.port_height//6
pt_3.x = self.x+self.port_width//6
pt_3.y = self.y+5*self.port_height//6
points = [pt_1, pt_2, pt_3, pt_1]
Grx.draw_filled_polygon(points, self.blue)
def draw_secondary_color(self):
#diagonal fill
pt_1 = Grx.Point()
pt_2 = Grx.Point()
pt_3 = Grx.Point()
pt_1.x = self.x
pt_1.y = self.y
pt_2.x = self.x+self.port_width
pt_2.y = self.y
pt_3.x = self.x
pt_3.y = self.y+self.port_height
points = [pt_1, pt_2, pt_3, pt_1]
Grx.draw_filled_polygon(points, self.get_secondary_color())
def get_color(self):
if self.speed == 0 or not self.enabled:
return self.black
elif self.speed == 10:
return self.cyan
elif self.speed == 100:
return self.yellow
elif self.speed == 1000:
return self.green
elif self.speed >= 2000:
return self.magenta
else:
return self.red
def get_secondary_color(self):
if self.secondary_speed is None or not self.speed or self.speed >= self.secondary_speed:
return None
if self.secondary_speed == 0 or not self.enabled:
return self.black
elif self.secondary_speed == 10:
return self.cyan
elif self.secondary_speed == 100:
return self.yellow
elif self.secondary_speed == 1000:
return self.green
elif self.secondary_speed >= 2000:
return self.magenta
else:
return self.red
@property
def speed(self):
return self.port_params.get('speed', 0)
@speed.setter
def speed(self, value):
self.port_params['speed'] = value
@property
def secondary_speed(self):
return self.port_params.get('secondary_speed', None)
@secondary_speed.setter
def secondary_speed(self, value):
self.port_params['secondary_speed'] = value
@property
def power(self):
return self.port_params.get('power', 0)
@power.setter
def power(self, value):
self.port_params['power'] = value
@property
def name(self):
return self.port_params.get('name', '')
@name.setter
def name(self, value):
self.port_params['name'] = value
@property
def org_name(self):
return self.port_params.get('org_name', '')
@org_name.setter
def org_name(self, value):
self.port_params['org_name'] = value
@property
def iface_name(self):
return self.port_params.get('iface_name', '')