ti-powerbar/app/utils.py

63 lines
1.8 KiB
Python
Raw Normal View History

2023-11-20 10:33:19 +00:00
import telnetlib
import re
2024-02-01 22:48:19 +00:00
from app.settings import powerbars, groups
2023-11-20 10:33:19 +00:00
2024-02-01 22:48:19 +00:00
def check_input_error(tn):
tn.write("/\r\n".encode('ascii'))
for _ in range(3):
2024-02-01 22:55:25 +00:00
print(f"Checking for input error attempt {_}")
2024-02-01 22:48:19 +00:00
output = tn.read_until(b"Input error", timeout=3).decode('ascii')
if "Input error" in output:
return True
return False
def get_telnet_connection(powerbar):
tn = telnetlib.Telnet(powerbars[powerbar]['host'], powerbars[powerbar]['port'])
return tn
def run_telnet_command(powerbar, command):
2023-11-20 10:33:19 +00:00
try:
2024-02-01 22:48:19 +00:00
tn = get_telnet_connection(powerbar)
if check_input_error(tn):
tn.write(f"{command}\r\n".encode('ascii'))
2024-02-01 23:28:11 +00:00
tn.close()
2024-02-01 22:48:19 +00:00
return True
2024-02-01 23:28:11 +00:00
tn.close()
2024-02-01 22:48:19 +00:00
return False
except Exception as e:
2024-02-01 23:28:11 +00:00
print(f"Run Telnet Command Rrror: {e}")
2024-02-01 22:48:19 +00:00
return False
2023-11-20 10:33:19 +00:00
2024-02-01 22:48:19 +00:00
def get_baytech_status_outlet_telnet(powerbar):
try:
# Create a Telnet object and connect to the host
tn = telnetlib.Telnet(powerbars[powerbar]['host'], powerbars[powerbar]['port'])
2023-11-20 10:33:19 +00:00
# Send the command you want to execute
command = "status"
2024-02-01 22:48:19 +00:00
if check_input_error(tn):
tn.write(command.encode('ascii') + b"\r\n")
else:
2024-02-01 23:28:11 +00:00
tn.close()
2024-02-01 22:48:19 +00:00
return None
2023-11-20 10:33:19 +00:00
# Read the output until you receive the prompt or a timeout occurs
output = tn.read_until(b"<prompt>", timeout=5).decode('ascii')
# Close the Telnet connection
tn.close()
pattern = r"(\d+)\)\.\.\.Outlet\s+(\d+)\s+:\s+(\w+)"
outlets = {}
matches = re.findall(pattern, output)
for match in matches:
number = int(match[1])
status = match[2]
outlets[number] = status
return outlets
except:
return None