-
Notifications
You must be signed in to change notification settings - Fork 0
/
currentcommander.py
1502 lines (1234 loc) · 54.4 KB
/
currentcommander.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/python3
from os.path import expanduser, exists
import getopt
import sys
import time
import socket
import configparser
import urwid
import threading
from datetime import datetime
from pysnmp.hlapi import *
from pysnmp.proto import rfc1902
# for ANEL NetPwr REST API
import httplib2
# IPMI/Redfish BMC support
from pyghmi.ipmi import command as ipmi_command
from pyghmi.redfish import command as redfish_command
#from pyghmi.ipmi.command import Housekeeper
from pyghmi.ipmi.command import Command
# TODO/Ideas:
# - ATEN PDU support
# - edit outlet names
# - display configured outlet power on/off delays
# - edit outlet power on/off delays
# - display overcurrent protection status
# - power usage plot
# - SNMP PoE switch support
# - HP procurve PoE switch 2530 works
# - show error conditions
# - show traffic counter
# - reset traffic counter
# - IPMI support
# - display sensor data
# - set device for next boot
# - display event log
# - implement edit dialog
# - fix toggling of outlets with pointer devices
# - change outlet selection with single click
# - provide config option to select if single or double click is required to toggle power
# - handle double click (done)
# - add optional (config) confirmation dialog for power toggle
# - add event log showing status changes and device communication
#
#
# Bugs
#
# - fix/test presets
# - fix error when ipmi device is not reachable
#
# Higher priority features
# - create an indicator bar showing previous and next devices
# - rename outlets
# - set/unset ipmi bootdevice for next boot
# - ipmi sensor data when on
# - switch traffic data
# - a generic way to display arbitrary snmp tables
# - confirmation dialog for switching outlets
# - global setting: no confirmation / only confirm off / confirm on/off
#
#
# Low priority / new features
#
# - reduce code duplication in SNMP device classes
# - auto refresh
# - introduce global settings section and dialog
# - toggling between needs to be modified for this, because we rely on every config section being a device config
# - switch_on_delay (may be better as device option?)
# - refresh (may also be better as device option? That would simplify it at least for now)
# -> use default or device config option and be done with it
# - manage crontab to send on/off commands at scheduled times (apt: python-crontab, from crontab import CronTab)
# - allow to create dependency rules
# - switch on outlet 1 and 2, of they were off, when outlet 3 is toggled (to reduce amp popping, when mixer is powered on)
# - create config file if none exists
# - open powerstrip edit dialog, save, then reload ui
# - Support running configured shell commands on selected outlet, with device/outlet/config attributes usable in the command string
# - example command definition in config: cmd1= /usr/sbin/xdg_open $outlet.current $outlet.voltage $device.ip
# - add bar graph for selectable metric V, A, W, Wh, state
# - manually paint the lower half of the window. x: time, y: value
# - add way to toggle view mode for ATEN PDU
# - mode 1: outlets, outlet details and presets
# - mode 2: outlets, outlet details and power graph for PDU
# - use threads for all device communication - not really required, but a nice exercise
#
# Done
#
# - toggle between powerstrips (done)
# - add outlet detail view (done)
# - improve resize behaviour (done - switched back from raw display mode, because i'm not drawing freely (yet))
# - this also solved exceptions causing the console to stay in a state that required a 'reset' before it could be used after ^C
# - fix selected list position is kept and fails to be applied when the next or previous powerstrip doesn't have enough items for a valid position (done)
# - remove old checkbox view (done)
# - implement toggling with new list view (done)
# - fix selected line changes to first line after reload (done)
# - fix ipmi connection timeout (done)
# - fix ipmi Housekeeper thread preventing clean shutdown (return to console without ^C after quit) (done)
# - ATEN PDU support
# - make NetPwrCtrl and AtenPDU inherit same subclass (done) i think it was not required and i was too much in the java world
# - it turned out it was a good decision, because the need to generalizes some functions arose
# it is even required, because it contains the list of outlets in a single place to be used in generic form in the ui
# - display states and names (done)
# - toggle states (done)
# - display power usage (done)
# - display voltage (done)
# - strictly use pysnmp.hlapi and no other modules from pysnmp (done) with one exception which is good
# - SNMP PoE switch support
# - display PoE port alias and status (done)
# - toggle PoE admin enabled status on/off per port (done)
# - display IP/MAC addresses detected on the port (done, MACs)
# - IPMI support
# - diplay state (done)
# - toggle power (done)
# - display boot device (done)
# - Redfish REST API support
# - toggle power (done)
#
#_TABLE_COL_DEFS = [
# ['{:<13}', 'Name'],
# ['{:>6}', ,
# '': '{:<13}',
#]
class ListItem(urwid.WidgetWrap):
text = None
def __init__ (self, o):
urwid.register_signal(self.__class__, ['item_activated'])
self.data = o
#name = '{:<10}{:>6s}{:>7}{:>10}{:>11}'.format(
state = 'off'
if o['state'] == 1:
state = 'on'
name = '{:<20}{:<6s} '.format(o['name'], state)
#if 'last_on' in o:
# name += '{:>12s}'.format(str(o['last_on'].strftime('%H:%M:%S')))
#if 'last_off' in o:
# name += '{:>12s}'.format(str(o['last_off'].strftime('%H:%M:%S')))
if 'on_delay' in o:
name += '{:>9s}'.format(o['on_delay'])
if 'off_delay' in o:
name += '{:>10s}'.format(o['off_delay'])
for column in ['voltage', 'current', 'power', 'powerDissipation']:
if column in o:
name += '{:>8.2f}'.format(float(o[column]))
if 'type' in o:
name += '{:<14s}'.format(o['type'])
if 'mac_addrs' in o:
if len(o['mac_addrs']) > 0:
name += '{:>18s}'.format(o['mac_addrs'][0])
else:
name += '{:>18s}'.format(' ')
if 'bootdev' in o:
name += '{:>18s}'.format(o['bootdev'])
self.text = name
text = urwid.Text(name)
t = urwid.AttrWrap(text, "outlet", "outlet_selected")
urwid.WidgetWrap.__init__(self, t)
def keypress(self, size, key):
return key
last_click_time = 0
# prevents three successive clicks being detected as two double clicks
clicks_since_last_double_click = 0
def mouse_event(self, size, event, button, col, row, focus):
"""
Send 'click' signal on button 1 press.
"""
if button != 1 or not urwid.util.is_mouse_press(event):
return False
now = time.time()
self.clicks_since_last_double_click += 1
if now - self.last_click_time < 0.5 and self.clicks_since_last_double_click >= 2:
self._emit('item_activated')
self.clicks_since_last_double_click = 0
self.last_click_time = now
self._emit('click')
return True
def selectable (self):
return True
class ListView(urwid.WidgetWrap):
def __init__(self):
urwid.register_signal(self.__class__, ['show_details', 'item_activated'])
self.walker = urwid.SimpleFocusListWalker([])
self.lb = urwid.ListBox(self.walker)
urwid.WidgetWrap.__init__(self, self.lb)
def modified(self):
focus_w, _ = self.walker.get_focus()
urwid.emit_signal(self, 'show_details', focus_w.data, [])
def set_data(self, outlets):
outlets_widgets = [ListItem(o) for o in outlets]
urwid.disconnect_signal(self.walker, 'modified', self.modified)
while len(self.walker) > 0:
w = self.walker.pop()
urwid.disconnect_signal(w, "item_activated", self.item_activated)
self.walker.extend(outlets_widgets)
urwid.connect_signal(self.walker, "modified", self.modified)
for w in outlets_widgets:
urwid.connect_signal(w, "item_activated", self.item_activated)
self.walker.set_focus(0)
# throw up
def item_activated(self, item):
urwid.emit_signal(self, 'item_activated', 1, [])
class PowerStripController(object):
cfg = None
last_refresh = None
multi_power_on_delay = 2
def __init__(self, cfg):
self.cfg = cfg
self.outlets = []
True
def get_last_refresh(self):
return self.last_refresh
def _apply_on_state(self, outlets, outlet_id):
self.outlets[outlet_id-1]['state'] = 1
self.outlets[outlet_id-1]['last_on'] = datetime.now()
def _apply_off_state(self, outlets, outlet_id):
self.outlets[outlet_id-1]['state'] = 0
self.outlets[outlet_id-1]['last_off'] = datetime.now()
class IPMISessionKeepaliveThread(threading.Thread):
def __init__(self, stop_event):
self.stop_event = stop_event
def run(self):
Command.eventloop()
class IPMIDevice(PowerStripController):
timeout = 3000
cmd = None
power_state = 'unknown'
last_session_usage = 0
def __init__(self, cfg):
super(IPMIDevice, self).__init__(cfg)
self.cmd = self.get_cmd()
def get_cmd(self):
# create new ipmi session to prevent running into timeouts
#if not self.last_session_usage == 0:
# print(time.time() - self.last_session_usage)
#if self.cmd == None or time.time() - self.last_session_usage > 20:
cmd = None
if self.cmd == None:
try:
port = 623
if 'port' in self.cfg:
port = int(self.cfg['port'])
cmd = ipmi_command.Command(
bmc=self.cfg['host'], userid=self.cfg['user'], password=self.cfg['pwd'], port=port
)
self.cmd = cmd
self.event_thread = IPMISessionKeepaliveThread(None)
self.event_thread.start()
except Exception as e:
#urwid.ExitMainLoop()
print(e)
#self.last_session_usage = time.time()
return self.cmd
def refresh_status(self):
# state
state = self.get_cmd().get_power()
iState = 0
if "on" in state['powerstate']:
iState = 1
# bootdev
bootdev = self.get_cmd().get_bootdev()
bootdevstr = 'bootdev: ' + bootdev['bootdev']
if bootdev['persistent']:
bootdevstr += ', persistent'
else:
bootdevstr += ', temporary'
# sensor data
#sensor_data = {}
#for x in self.get_cmd().get_sensor_data():
# sensor_data['name'] = x.name
# sensor_data['value'] = x.value
# sensor_data['unit'] = x.units
# sensor_data['health'] = x.health
outlets = [{
'name': self.cfg.name,
'state': iState,
'preset1': 0,
'preset2': 0,
'preset3': 0,
'bootdev': bootdevstr,
# 'sensor_data': sensor_data
}]
if len(self.outlets) == 0:
self.outlets = outlets
else:
for key in outlets[0]:
self.outlets[0][key] = outlets[0][key]
#self.outlets = outlets
def get_event_log():
return self.get_cmd().get_event_log()
def _switch(self, state):
self.get_cmd().set_power(state, wait=2000)
def switch_on(self, outlet_id):
self._switch("on")
self._apply_on_state(self.outlets, outlet_id)
def switch_off(self, outlet_id):
self._switch("off")
self._apply_off_state(self.outlets, outlet_id)
def toggle_outlet(self, outlet_id):
if self.outlets[outlet_id-1]['state'] == 0:
self.switch_on(outlet_id)
else:
self.switch_off(outlet_id)
class RedfishDevice(PowerStripController):
timeout = 3000
cmd = None
def __init__(self, cfg):
super(RedfishDevice, self).__init__(cfg)
power_state = 'unknown'
try:
port = 623
if 'port' in self.cfg:
port = int(self.cfg['port'])
self.cmd = redfish_command.Command(
bmc=self.cfg['host'], userid=self.cfg['user'], password=self.cfg['pwd'], port=port, verifycallback=self.verify_callback
)
#print(self.cmd)
except Exception as e:
print(e)
def verify_callback(self, x):
# ssl?!
return True
def get_power_state(self):
return self.cmd.get_power()
def refresh_status(self):
state = self.cmd.get_power()
# bootdev
bootdev = self.cmd.get_bootdev()
bootdevstr = 'bootdev: ' + bootdev['bootdev']
if bootdev['persistent']:
bootdevstr += ', persistent'
else:
bootdevstr += ', temporary'
outlet = {
'name': self.cfg.name,
'state': 0,
'preset1': 0,
'preset2': 0,
'preset3': 0,
'bootdev': bootdevstr
}
if len(self.outlets) == 1:
for key in outlet:
self.outlets[0][key] = outlet[key]
else:
self.outlets.append(outlet)
def _switch(self, state):
self.cmd.set_power(state, wait=2000)
def switch_on(self, outlet_id):
self._switch("on")
self._apply_on_state(self.outlets, outlet_id)
def switch_off(self, outlet_id):
self._switch("off")
self._apply_off_state(self.outlets, outlet_id)
def toggle_outlet(self, outlet_id):
if self.outlets[outlet_id-1]['state'] == 0:
self.switch_on(outlet_id)
else:
self.switch_off(outlet_id)
'''
Power over Ethernet Power Sourcing Equipment
Uses standard SNMP OIDs and should be compatible with most PoE devices with SNMP
'''
class PoEPSE(PowerStripController):
oids = {
# single values
'sysName': ObjectIdentity('.1.3.6.1.2.1.1.5.0'),
}
bulk_cmd_oids = {
# start oids
# pethPsePortAdminEnable: .1.3.6.1.2.1.105.1.1.1.3
'ifAlias': ObjectIdentity('.1.3.6.1.2.1.31.1.1.1.18'),
'ifAdminStatus': ObjectIdentity('.1.3.6.1.2.1.2.2.1.7'),
'ifOperStatus': ObjectIdentity('.1.3.6.1.2.1.2.2.1.8'),
'ifMtu': ObjectIdentity('.1.3.6.1.2.1.2.2.1.4'),
'ifJackType': ObjectIdentity('.1.3.6.1.2.1.26.2.2.1.2'),
'pethPsePortAdminEnable': ObjectIdentity('.1.3.6.1.2.1.105.1.1.1.3.1'),
'macAddresses': ObjectIdentity('.1.3.6.1.2.1.17.4.3.1.2'),
}
# key is bulk_cmd_oids key
bulk_cmds = {}
# for received data. key is same as in bulk_cmd_oids, value is an array with the value for each outlet
data = {}
mac_addresses = {}
def __init__(self, cfg):
super(PoEPSE, self).__init__(cfg)
self._configure_connection()
# pull into snmp client super class
def _get_bulk_cmd(self, first_oid_key):
return bulkCmd(self.snmpEngine, self.userData, self.transport, ContextData(), 0, 7, self._getObjectType(first_oid_key))
def _get_mac_addresses(self):
self.mac_addresses.clear()
for i in range(0, 8):
self._parse_mac_addresses(self.bulkCmdMacAddresses)
def oid2mac(self, oid):
return "%0.2X:%0.2X:%0.2X:%0.2X:%0.2X:%0.2X" % (int(oid[0]), int(oid[1]), int(oid[2]), int(oid[3]), int(oid[4]), int(oid[5]))
# pull into snmp client super class
def _configure_connection(self):
self.snmpEngine = SnmpEngine()
authProtocol = usmHMACMD5AuthProtocol
privProtocol = usmAesCfb128Protocol
if self.cfg['auth_protocol'] == 'SHA':
authProtocol = usmHMACSHAAuthProtocol
if self.cfg['priv_protocol'] == 'DES':
privProtocol = usmDESPrivProtocol
self.userData = UsmUserData(self.cfg['user'], self.cfg['authkey'], self.cfg['privkey'], authProtocol=authProtocol, privProtocol=privProtocol)
port = 161
if not self.cfg['port'] == None:
port = int(self.cfg['port'])
self.transport = UdpTransportTarget((self.cfg['host'], port), timeout=0.5, retries=1)
# pull into snmp client super class
def _getObjectType(self, oidKey):
if oidKey in self.oids:
objectType = ObjectType(self.oids[oidKey]) #.addAsn1MibSource( 'file:///home/gobuki/bin/snmp/PE_MIB_1.1.115')
else:
objectType = ObjectType(self.bulk_cmd_oids[oidKey]) #.addAsn1MibSource( 'file:///home/gobuki/bin/snmp/PE_MIB_1.1.115')
return objectType
def _parse_mac_addresses(self, iterator):
errorIndication, errorStatus, errorIndex, varBinds = next(iterator)
if errorIndication:
print(errorIndication)
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
for varBind in varBinds:
# cut off the prefix, so only 6 values separated by dots should remain
mac_as_oid = str(varBind[0]).replace('1.3.6.1.2.1.17.4.3.1.2.','')
split_oid = mac_as_oid.split('.')
if len(split_oid) == 6:
iPort = varBind[1]
if iPort <= 8:
if not str(iPort) in self.mac_addresses:
self.mac_addresses[str(iPort)] = [self.oid2mac(split_oid)]
else:
self.mac_addresses[str(iPort)].append(self.oid2mac(split_oid))
#print(self.oid2mac(split_oid) + " found at port " + str(varBind[1]))
def _append_result(self, iterator, listvar):
errorIndication, errorStatus, errorIndex, varBinds = next(iterator)
if errorIndication:
print(errorIndication)
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
for varBind in varBinds:
listvar.append(str(varBind[1]))
def refresh_status(self):
for key in self.bulk_cmd_oids:
self.bulk_cmds[key] = self._get_bulk_cmd(key)
if key not in self.data:
self.data[key] = []
for key in self.data:
self.data[key].clear()
self.bulkCmdMacAddresses = bulkCmd(self.snmpEngine, self.userData, self.transport, ContextData(), 0, 7, self._getObjectType('macAddresses'))
self._get_mac_addresses()
for i in range(0, 8):
for key in self.bulk_cmds:
self._append_result(self.bulk_cmds[key], self.data[key])
self.data["pethPsePortAdminEnable"][i] = int(self.data["pethPsePortAdminEnable"][i])
itype = int(self.data['ifJackType'][i])
stype = ""
slink = ""
link_status = int(self.data['ifOperStatus'][i])
if link_status == 1:
slink = "up"
elif link_status == 2:
slink = "down"
if itype == 2:
stype = "RJ45 PoE, " + slink
else:
stype = '<unsupported>'
mac_addrs = []
if str(i+1) in self.mac_addresses:
mac_addrs = self.mac_addresses[str(i+1)]
outlet = {
'name': self.data['ifAlias'][i],
'state': int(self.data['pethPsePortAdminEnable'][i]) - 1,
'preset1': 0,
'preset2': 0,
'preset3': 0,
'type': stype,
'mac_addrs': mac_addrs
}
if i < len(self.outlets):
for key in outlet:
self.outlets[i][key] = outlet[key]
else:
self.outlets.append(outlet)
def switch_on(self, outlet_id):
self._switch(outlet_id, 2)
self._apply_on_state(self.outlets, outlet_id)
def switch_off(self, outlet_id):
self._switch(outlet_id, 1)
self._apply_off_state(self.outlets, outlet_id)
def toggle_outlet(self, outlet_id):
if self.outlets[outlet_id-1]['state'] == 0:
self.switch_on(outlet_id)
else:
self.switch_off(outlet_id)
def _switch(self, outlet_id, status):
g = setCmd(
self.snmpEngine,
self.userData,
self.transport,
ContextData(),
((1, 3, 6, 1, 2, 1, 105, 1, 1, 1, 3, 1, outlet_id), rfc1902.Integer(status))
)
next(g)
'''
Controls ATEN PDUs using SNMP. Support is specific to ATEN devices.
I developed it for PE8108G, but it should be compatible with PE8104G for example and mabye even others
'''
class AtenPDU(PowerStripController):
oids = {
# single values
'sysName': ObjectIdentity('.1.3.6.1.2.1.1.5.0'),
'modelName': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.2.1.1.0'),
'uptime': ObjectIdentity('.1.3.6.1.2.1.1.3.0'),
'time': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.3.4.8.2.2.0'),
'date': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.3.4.8.2.1.0'),
'deviceMAC': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.3.4.1.0'),
'deviceIP': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.3.4.2.0'),
'deviceFWVersion': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.3.4.3.0'),
'devicePower': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.2.1.3.1.4.1'),
'devicePowerDissipation': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.2.1.3.1.5.1'),
'deviceVoltage': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.2.1.3.1.3.1'),
'deviceCurrent': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.2.1.3.1.2.1'),
'inputMaxVoltage': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.2.1.3.1.6.1'),
'inputMaxCurrent': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.2.1.3.1.7.1'),
}
# start oids
bulk_cmd_oids = {
'outletName': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.2.2.10.1.2'),
'displayOutletStatus': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.2.1.5.1.2'),
'outletVoltage': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.2.2.1.1.3'),
'outletCurrent': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.2.2.1.1.2'),
'outletPower': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.2.2.1.1.4'),
'outletPowerDissipation': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.2.2.1.1.5'),
'outletValueEntry': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.2.2.1'),
'deviceValueEntry': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.2.2.1'),
'outletOnDelayTime': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.2.2.10.1.4'),
'outletOffDelayTime': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.2.2.10.1.5'),
'outletMaxCurrent': ObjectIdentity('.1.3.6.1.4.1.21317.1.3.2.2.2.2.1.1.6')
}
# key is bulk_cmd_oids key
bulk_cmds = {}
# for received data
data = {}
def __init__(self, cfg):
super(AtenPDU, self).__init__(cfg)
self._configure_connection()
def _get_bulk_cmd(self, first_oid_key):
return bulkCmd(self.snmpEngine, self.userData, self.transport, ContextData(), 0, 7, self._getObjectType(first_oid_key))
def _configure_connection(self):
self.snmpEngine = SnmpEngine()
authProtocol = usmHMACMD5AuthProtocol
privProtocol = usmAesCfb128Protocol
if self.cfg['auth_protocol'] == 'SHA':
authProtocol = usmHMACSHAAuthProtocol
if self.cfg['priv_protocol'] == 'DES':
privProtocol = usmDESPrivProtocol
self.userData = UsmUserData(self.cfg['user'], self.cfg['authkey'], self.cfg['privkey'], authProtocol=authProtocol, privProtocol=privProtocol)
#self.userData = UsmUserData(self.cfg['user'], self.cfg['authkey'], self.cfg['privkey'], authProtocol=usmHMACMD5AuthProtocol, privProtocol=usmAesCfb128Protocol)
port = 161
if not self.cfg['port'] == None:
port = int(self.cfg['port'])
self.transport = UdpTransportTarget((self.cfg['host'], port), timeout=0.5, retries=1)
def _getObjectType(self, oidKey):
if oidKey in self.oids:
objectType = ObjectType(self.oids[oidKey]) #.addAsn1MibSource( 'file:///home/gobuki/bin/snmp/PE_MIB_1.1.115')
else:
objectType = ObjectType(self.bulk_cmd_oids[oidKey]) #.addAsn1MibSource( 'file:///home/gobuki/bin/snmp/PE_MIB_1.1.115')
return objectType
def _append_result(self, iterator, listvar):
errorIndication, errorStatus, errorIndex, varBinds = next(iterator)
if errorIndication:
print(errorIndication)
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
for varBind in varBinds:
listvar.append(str(varBind[1]))
def get_result(self, iterator):
listvar = []
errorIndication, errorStatus, errorIndex, varBinds = next(iterator)
if errorIndication:
print(errorIndication)
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
for varBind in varBinds:
listvar.append(str(varBind[1]))
return listvar
def get_pdu_info(self):
return self.get_result(
self.getGetCmd(['sysName','modelName','uptime','time','date','deviceMAC','deviceIP','deviceFWVersion','deviceVoltage','deviceCurrent','devicePower','devicePowerDissipation'])
)
def switch_on(self, outlet_id):
self._switch(outlet_id, 2)
self._apply_on_state(self.outlets, outlet_id)
def switch_off(self, outlet_id):
self._switch(outlet_id, 1)
self._apply_off_state(self.outlets, outlet_id)
def toggle_outlet(self, outlet_id):
if self.outlets[outlet_id-1]['state'] != 1:
self.switch_on(outlet_id)
else:
self.switch_off(outlet_id)
def _switch(self, outlet_id, status):
g = setCmd(
self.snmpEngine,
self.userData,
self.transport,
ContextData(),
((1, 3, 6, 1, 4, 1, 21317, 1, 3, 2, 2, 2, 2, outlet_id + 1, 0), rfc1902.Integer(status))
)
next(g)
def refresh_status(self):
for key in self.bulk_cmd_oids:
self.bulk_cmds[key] = self._get_bulk_cmd(key)
if key not in self.data:
self.data[key] = []
for key in self.data:
self.data[key].clear()
for i in range(0, 8):
for key in self.bulk_cmds:
self._append_result(self.bulk_cmds[key], self.data[key])
if key == "displayOutletStatus":
self.data[key][i] = int(self.data[key][i])
outlet = {
'name': self.data['outletName'][i],
'state': int(self.data['displayOutletStatus'][i]) - 1,
'preset1': 0,
'preset2': 0,
'preset3': 0,
'power': self.data['outletPower'][i],
'powerDissipation': self.data['outletPowerDissipation'][i],
'current': self.data['outletCurrent'][i],
'max_current': self.data['outletMaxCurrent'][i],
'voltage': self.data['outletVoltage'][i],
'on_delay': self.data['outletOnDelayTime'][i],
'off_delay': self.data['outletOffDelayTime'][i],
}
if i < len(self.outlets):
for key in outlet:
self.outlets[i][key] = outlet[key]
else:
self.outlets.append(outlet)
def getGetCmd(self, oidKey):
if isinstance(oidKey, str):
return getCmd(self.snmpEngine, self.userData, self.transport, ContextData(), self._getObjectType(oidKey))
else:
object_types = [self._getObjectType(key) for key in oidKey]
return getCmd(self.snmpEngine, self.userData, self.transport, ContextData(), *object_types)
class SignalWrap(urwid.WidgetWrap):
def __init__(self, w, is_preemptive=False):
urwid.WidgetWrap.__init__(self, w)
self.event_listeners = []
self.is_preemptive = is_preemptive
def listen(self, mask, handler):
self.event_listeners.append((mask, handler))
def keypress(self, size, key):
result = key
if self.is_preemptive:
for mask, handler in self.event_listeners:
if mask is None or mask == key:
result = handler(self, size, key)
break
if result is not None:
result = self._w.keypress(size, key)
if result is not None and not self.is_preemptive:
for mask, handler in self.event_listeners:
if mask is None or mask == key:
return handler(self, size, key)
return result
'''
Controls Anel NET-PwrCtrl powerstrips
'''
class NetPwrCtrl(PowerStripController):
def __init__(self, cfg):
super(NetPwrCtrl, self).__init__(cfg)
def is_outlet_configured(self, outlet_index):
is_configured = False
# try to get outlet name from config, could be unconfigured
# in this case access to cfg entry fails in if condition
try:
is_configured = not self.cfg[str(outlet_index)] == None
except Exception as e:
print(e)
return is_configured
def refresh_status(self):
outlet_data = self._fetch_outlet_states()
outlet_index = 1
for od in outlet_data:
if self.is_outlet_configured(outlet_index):
name = od[1]
outlet = {
'name': self.cfg[str(outlet_index)],
'state': int(od[1]),
'preset1': 0,
'preset2': 0,
'preset3': 0,
}
if outlet_index-1 < len(self.outlets):
for key in outlet:
self.outlets[outlet_index-1][key] = outlet[key]
else:
self.outlets.append(outlet)
outlet_index += 1
def _fetch_outlet_states(self):
h = httplib2.Http()
h.add_credentials(self.cfg['user'], self.cfg['pwd'])
(resp_headers, content) = h.request("http://" + self.cfg['host'] + "/?Stat=" + self.cfg['user'] + self.cfg['pwd'], "GET")
values = content.decode().split(';')
# the first 8 fields of the array can be ignored for the state
# from index 8 (field 9) on the socket states are found,
# with 3 fields per socket: name, state integer, another integer
i = 8
outlet_data = []
while (i + 2 < len(values)):
outlet_data.append([values[i], values[i+1], values[i+2]])
i+=3
self.last_refresh = values[3]
return outlet_data;
def _switch(self, outlet_id, command):
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.sendto((command + str(outlet_id) + self.cfg['user'] + self.cfg['pwd'] +"\n").encode(), (self.cfg['host'], int(self.cfg['port'])))
def switch_on(self, outlet_id):
self._switch(outlet_id, "Sw_on")
self._apply_on_state(self.outlets, outlet_id)
def switch_off(self, outlet_id):
self._switch(outlet_id, "Sw_off")
self._apply_off_state(self.outlets, outlet_id)
def toggle_outlet(self, outlet_id):
if self.outlets[outlet_id-1]['state'] == 0:
self.switch_on(outlet_id)
else:
self.switch_off(outlet_id)
def activate_preset(self, preset_index):
outlet_id = 1
outlets_switched_on = 0
for outlet in self.outlets:
preset_value = outlet['preset'+ str(preset_index)]
if preset_value != outlet['state']:
# sleep before toggling the next outlet
if outlets_switched_on > 0:
time.sleep(self.multi_power_on_delay)
self.toggle_outlet(outlet_id)
if preset_value == 1:
outlets_switched_on += 1
outlet_id += 1
class OutletDetailView(urwid.WidgetWrap):
def __init__ (self):
t = urwid.Text("")
urwid.WidgetWrap.__init__(self, t)
def set_outlet(self, o):
s = f'Name: {o["name"]}\n'
if 'power' in o:
s += f'Power: {o["power"]}\n'
if 'current' in o:
s += f'Current: {o["current"]}'
if 'sensor_data' in o:
s += self.format_sensor_data(o['sensor_data'])
self._w.set_text(s)
def format_sensor_data(self, sensor_data):
if not sensor_data:
return ""
print(sensor_data)
class CursesUI:
# activated powerstrip config index
selected_powerstrip = 0
# checkbox lists
content = []
preset1_content = []
preset2_content = []
preset3_content = []
# Set up color scheme
palette = [
('titlebar', 'light green', ''),
('hotkey', 'dark green,bold', ''),
('quit', 'dark red,bold', ''),
('quit button', 'dark red', ''),
('headers', 'white,bold', ''),
('outlets_header', 'light blue', ''),
('outlet_selected', 'black', 'light green'),
('button', 'white', 'light blue'),
('button_selected', 'black', 'yellow'),
('normal', 'white', ''),
('selected', 'black', 'light green')]
instances = {}
def __init__(self):
self.cfg = ConfigManager()
self.quit_event_loop = False
if self.cfg.config_exists():
self.load_config(self.selected_powerstrip)
def load_config(self, selected_powerstrip_index):
cfg_sectionname = self.cfg.get_sections()[selected_powerstrip_index]
cfg_section = self.cfg.get_section(cfg_sectionname)
self.load_controller_instance(cfg_section)
def load_controller_instance(self, cfg_section):
if cfg_section['device'] == "anel_powerstrip":
if not cfg_section.name in self.instances:
self.instances[cfg_section.name] = NetPwrCtrl(cfg_section)
self.active_powerstrip = self.instances[cfg_section.name]
elif cfg_section['device'] == "aten_pdu":
if not cfg_section.name in self.instances:
self.instances[cfg_section.name] = AtenPDU(cfg_section)
self.active_powerstrip = self.instances[cfg_section.name]
elif cfg_section['device'] == "poe_pse":
if not cfg_section.name in self.instances:
self.instances[cfg_section.name] = PoEPSE(cfg_section)
self.active_powerstrip = self.instances[cfg_section.name]
elif cfg_section['device'] == "ipmi":
if not cfg_section.name in self.instances:
self.instances[cfg_section.name] = IPMIDevice(cfg_section)
self.active_powerstrip = self.instances[cfg_section.name]
elif cfg_section['device'] == "redfish":
if not cfg_section.name in self.instances:
self.instances[cfg_section.name] = RedfishDevice(cfg_section)
self.active_powerstrip = self.instances[cfg_section.name]
def next_powerstrip(self, w, size, key):
next_index = self.selected_powerstrip + 1
if next_index > len(self.cfg.get_sections())-1:
next_index = 0
try:
#print("loading config", file=sys.stderr)
self.load_config(next_index)
#print ("after loading config", file=sys.stderr)
except:
print("exception", file=sys.stderr)
return
#print("after loading config", file=sys.stderr)