PowerControl.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. """
  4. Internal use only.
  5. This file implements controlling APC PDU via telnet.
  6. """
  7. import telnetlib
  8. class Control(object):
  9. """ control APC via telnet """
  10. @classmethod
  11. def apc_telnet_make_choice(cls, telnet, choice):
  12. """ select a choice """
  13. telnet.read_until(b'Event Log')
  14. telnet.read_until(b'>')
  15. telnet.write(choice.encode() + b'\r\n')
  16. @classmethod
  17. def apc_telnet_common_action(cls, telnet, check_str, action):
  18. """ wait until a pattern and then write a line """
  19. telnet.read_until(check_str.encode())
  20. telnet.write(action.encode() + b'\r\n')
  21. @classmethod
  22. def control(cls, apc_ip, control_dict):
  23. """
  24. control APC
  25. :param apc_ip: IP of APC
  26. :param control_dict: dict with outlet ID and "ON" or "OFF"
  27. """
  28. for _outlet in control_dict:
  29. assert 0 < _outlet < 9
  30. assert control_dict[_outlet] in ['ON', 'OFF']
  31. # telnet
  32. # set timeout as 2s so that it won't waste time even can't access APC
  33. tn = telnetlib.Telnet(host=apc_ip, timeout=5)
  34. # log on
  35. cls.apc_telnet_common_action(tn, 'User Name :', 'apc')
  36. cls.apc_telnet_common_action(tn, 'Password :', 'apc')
  37. # go to Device Manager
  38. cls.apc_telnet_make_choice(tn, '1')
  39. # go to Outlet Management
  40. cls.apc_telnet_make_choice(tn, '2')
  41. # go to Outlet Control/Configuration
  42. cls.apc_telnet_make_choice(tn, '1')
  43. # do select Outlet and control
  44. for _outlet in control_dict:
  45. # choose Outlet
  46. cls.apc_telnet_make_choice(tn, str(_outlet))
  47. # choose Control Outlet
  48. cls.apc_telnet_make_choice(tn, '1')
  49. # choose action
  50. _action = control_dict[_outlet]
  51. if 'ON' in _action:
  52. cls.apc_telnet_make_choice(tn, '1')
  53. else:
  54. cls.apc_telnet_make_choice(tn, '2')
  55. # do confirm
  56. cls.apc_telnet_common_action(tn, 'cancel :', 'YES')
  57. cls.apc_telnet_common_action(tn, 'continue...', '')
  58. # return to Outlet Control/Configuration
  59. cls.apc_telnet_make_choice(tn, '\033')
  60. cls.apc_telnet_make_choice(tn, '\033')
  61. # exit to main menu and logout
  62. tn.write(b'\033\r\n')
  63. tn.write(b'\033\r\n')
  64. tn.write(b'\033\r\n')
  65. tn.write(b'4\r\n')
  66. @classmethod
  67. def control_rest(cls, apc_ip, outlet, action):
  68. outlet_list = list(range(1, 9)) # has to be a list if we want to remove from it under Python 3
  69. outlet_list.remove(outlet)
  70. cls.control(apc_ip, dict.fromkeys(outlet_list, action))