ti-powerbar/app/views.py

277 lines
10 KiB
Python
Raw Normal View History

2024-01-27 15:01:13 +00:00
from flask import render_template, Blueprint, request
2023-11-22 09:09:11 +00:00
from app.settings import powerbars, groups
2024-02-01 22:48:19 +00:00
from app.utils import run_telnet_command
2023-11-19 00:43:36 +00:00
from flask import jsonify
2023-11-19 01:08:55 +00:00
import time
2023-12-02 17:17:42 +00:00
import app
2024-02-28 19:10:53 +00:00
from app.threads import queues
2023-11-19 00:07:25 +00:00
routes = Blueprint('routes', __name__)
2023-11-24 11:48:00 +00:00
# Create a dictionary to store the active telnet connections
active_telnet_connections = {}
2023-11-22 09:09:11 +00:00
def find_group_by_name(name):
2023-11-19 12:26:12 +00:00
for group in groups:
if group["name"] == name:
return group
return None
2023-11-19 00:07:25 +00:00
def vaild_power_bar(powerbar):
if powerbar in powerbars:
return True
else:
return False
2024-02-07 17:18:33 +00:00
def vaild_outlet(powerbar, outlet):
2023-11-19 00:07:25 +00:00
if outlet in powerbars[powerbar]['outlets']:
return True
else:
return False
@routes.route('/')
def home():
2023-11-19 16:06:40 +00:00
for powerbar in powerbars:
for outlet in powerbars[powerbar]['outlets']:
powerbars[powerbar]['outlets'][outlet]['state'] = powerbars[powerbar]['outlets'][outlet].get('state', 'unknown')
2023-11-22 09:09:11 +00:00
return render_template('index.html', powerbars=powerbars, all_groups=groups)
2023-11-19 01:30:54 +00:00
2023-11-19 00:07:25 +00:00
2023-11-19 00:38:44 +00:00
@routes.route('/<string:powerbar>/<int:outlet>/<string:action>')
2023-11-19 01:00:53 +00:00
def powerbar_control(powerbar, outlet, action):
"""
Controls the powerbar outlet based on the given parameters.
2023-11-19 00:07:25 +00:00
2023-11-19 01:00:53 +00:00
Args:
powerbar (str): The name of the powerbar.
outlet (int): The outlet number.
action (str): The action to perform on the outlet ('on', 'off', 'cycle').
2023-11-19 00:43:36 +00:00
2023-11-19 01:00:53 +00:00
Returns:
dict: A JSON response containing the state of the action or an error message.
Raises:
ValueError: If the action is not valid.
ValueError: If the powerbar is not valid.
ValueError: If the outlet is not valid.
Exception: If there is a telnet error.
"""
2023-11-19 00:10:51 +00:00
print(f"powerbar: {powerbar}")
print(f"outlet: {outlet}")
print(f"action: {action}")
2023-11-19 00:07:25 +00:00
2023-11-20 11:01:18 +00:00
if not action in ['on', 'off', 'cycle', 'toggle']:
2023-11-19 00:10:51 +00:00
print("Invalid action")
2023-11-19 00:43:36 +00:00
return jsonify({'error': 'Invalid action'}), 400
2023-11-19 00:07:25 +00:00
if not vaild_power_bar(powerbar):
2023-11-19 00:10:51 +00:00
print("Invalid powerbar")
2023-11-19 00:43:36 +00:00
return jsonify({'error': 'Invalid powerbar'}), 400
2023-11-19 00:07:25 +00:00
if not vaild_outlet(powerbar, outlet):
2023-11-19 00:10:51 +00:00
print("Invalid outlet")
2023-11-19 00:43:36 +00:00
return jsonify({'error': 'Invalid outlet'}), 400
2023-11-19 00:07:25 +00:00
2024-01-27 15:01:13 +00:00
if "password" in powerbars[powerbar]['outlets'][outlet].keys():
user_password = request.args.get('password')
outlet_password = powerbars[powerbar]['outlets'][outlet]["password"]
if user_password == None:
print("Password missing")
return jsonify({'error': 'Password missing'}), 400
if user_password != outlet_password:
return jsonify({'error': 'Password incorrect'}), 400
2023-11-19 00:35:52 +00:00
if action in ['on', 'off']:
2023-11-19 00:07:25 +00:00
try:
2023-11-19 00:35:52 +00:00
print(f"Turning {action} powerbar {powerbar} outlet {outlet}")
2024-02-01 10:58:27 +00:00
if powerbars[powerbar]['method'] == "telnet":
2024-02-01 23:28:11 +00:00
command = run_telnet_command(powerbar,f"{action} {outlet}")
2024-02-01 10:58:27 +00:00
2024-02-07 17:29:54 +00:00
if powerbars[powerbar]['method'] == "batch_telnet":
2024-02-28 19:10:53 +00:00
queues[powerbar].put({"outlet": outlet, "action" : action})
2024-02-07 17:29:54 +00:00
command = True
2024-02-01 23:28:11 +00:00
if command:
powerbars[powerbar]['outlets'][outlet]['state'] = action
app.socketio.emit('power-event',{'powerbar': powerbar, 'outlet' : outlet, 'action' : action}, namespace='/powerupdates')
print(f"Turned {action} powerbar {powerbar} outlet {outlet}")
2023-11-19 12:26:12 +00:00
except Exception as E:
2024-02-01 23:28:11 +00:00
print(f"Endpoint Exception Error: {E}")
return jsonify({'error': 'Endpoint Exception Error'}), 500
2023-11-19 01:08:55 +00:00
if action == 'cycle':
2024-02-01 23:28:11 +00:00
print(f"Turning Off powerbar {powerbar} outlet {outlet}")
2024-02-01 10:58:27 +00:00
if powerbars[powerbar]['method'] == "telnet":
2024-02-01 23:28:11 +00:00
command = run_telnet_command(powerbar,f"off {outlet}")
2024-02-07 17:29:54 +00:00
if powerbars[powerbar]['method'] == "batch_telnet":
2024-02-28 19:10:53 +00:00
queues[powerbar].put({"outlet": outlet, "action" : "off"})
2024-02-07 17:29:54 +00:00
command = True
if command:
powerbars[powerbar]['outlets'][outlet]['state'] = "off"
app.socketio.emit('power-event',{'powerbar': powerbar, 'outlet' : outlet, 'action' : action}, namespace='/powerupdates')
time.sleep(5)
print(f"Turning On powerbar {powerbar} outlet {outlet}")
2024-02-01 10:58:27 +00:00
2024-02-01 23:28:11 +00:00
if powerbars[powerbar]['method'] == "telnet":
command = run_telnet_command(powerbar,f"on {outlet}")
2024-02-07 17:29:54 +00:00
if powerbars[powerbar]['method'] == "batch_telnet":
2024-02-28 19:10:53 +00:00
queues[powerbar].put({"outlet": outlet, "action" : "on"})
2024-02-07 17:29:54 +00:00
command = True
if command:
powerbars[powerbar]['outlets'][outlet]['state'] = "on"
2024-01-27 15:01:13 +00:00
2023-11-20 11:01:18 +00:00
if action == 'toggle':
print(powerbars[powerbar]['outlets'][outlet]['state'])
if powerbars[powerbar]['outlets'][outlet]['state'] == "on":
2024-02-01 10:58:27 +00:00
2023-11-20 11:01:18 +00:00
print(f"Turning Off powerbar {powerbar} outlet {outlet}")
2024-02-01 10:58:27 +00:00
if powerbars[powerbar]['method'] == "telnet":
2024-02-01 23:28:11 +00:00
command = run_telnet_command(powerbar,f"off {outlet}")
2024-02-07 17:29:54 +00:00
if powerbars[powerbar]['method'] == "batch_telnet":
2024-02-28 19:10:53 +00:00
queues[powerbar].put({"outlet": outlet, "action" : "off"})
2024-02-07 17:29:54 +00:00
command = True
2024-02-01 23:28:11 +00:00
if command:
powerbars[powerbar]['outlets'][outlet]['state'] = "off"
2024-02-01 10:58:27 +00:00
2023-11-20 11:01:18 +00:00
elif powerbars[powerbar]['outlets'][outlet]['state'] == "off":
2024-02-01 10:58:27 +00:00
2023-11-20 11:01:18 +00:00
print(f"Turning On powerbar {powerbar} outlet {outlet}")
2024-02-01 10:58:27 +00:00
if powerbars[powerbar]['method'] == "telnet":
2024-02-01 23:28:11 +00:00
command = run_telnet_command(powerbar,f"on {outlet}")
2024-02-07 17:29:54 +00:00
if powerbars[powerbar]['method'] == "batch_telnet":
2024-02-28 19:41:57 +00:00
queues[powerbar].put({"outlet": outlet, "action" : "on"})
2024-02-07 17:29:54 +00:00
command = True
2024-02-07 15:44:32 +00:00
if command:
powerbars[powerbar]['outlets'][outlet]['state'] = "on"
2023-11-19 00:16:41 +00:00
2024-02-02 12:59:17 +00:00
state = powerbars[powerbar]['outlets'][outlet].get('state', 'unknown')
app.socketio.emit('power-event',{'powerbar': powerbar, 'outlet' : outlet, 'action' : state}, namespace='/powerupdates')
2023-11-19 01:08:55 +00:00
return jsonify({'state': powerbars[powerbar]['outlets'][outlet].get('state', 'unknown')})
2023-11-19 00:07:25 +00:00
2023-11-19 00:33:11 +00:00
2023-11-19 00:38:44 +00:00
@routes.route('/<string:powerbar>/<int:outlet>/state')
2023-11-19 00:33:11 +00:00
def powerbar_state(powerbar, outlet):
print(f"powerbar: {powerbar}")
print(f"outlet: {outlet}")
if not vaild_power_bar(powerbar):
print("Invalid powerbar")
2023-11-19 00:43:36 +00:00
return jsonify({'error': 'Invalid powerbar'}), 400
2023-11-19 00:33:11 +00:00
if not vaild_outlet(powerbar, outlet):
print("Invalid outlet")
2023-11-19 00:43:36 +00:00
return jsonify({'error': 'Invalid outlet'}), 400
2023-11-19 00:33:11 +00:00
state = powerbars[powerbar]['outlets'][outlet].get('state', 'unknown')
2023-11-19 00:43:36 +00:00
return jsonify({'state': state})
2023-11-19 00:55:54 +00:00
@routes.route('/powerbars')
def powerbars_list():
2024-01-27 15:01:13 +00:00
cleaned_powerbars = {}
2023-11-19 01:00:53 +00:00
for powerbar in powerbars:
2024-01-27 15:01:13 +00:00
cleaned_powerbar = {
"name" : powerbars[powerbar]['name'],
"description" : powerbars[powerbar]['description'],
"host" : powerbars[powerbar]['host'],
"port" : powerbars[powerbar]['port'],
"type" : powerbars[powerbar]['type'],
"outlets" : {},
}
2023-11-19 01:00:53 +00:00
for outlet in powerbars[powerbar]['outlets']:
2024-01-27 15:01:13 +00:00
cleaned_outlet = {}
2023-11-19 01:00:53 +00:00
state = powerbars[powerbar]['outlets'][outlet].get('state', 'unknown')
2024-01-27 21:42:41 +00:00
cleaned_outlet['name'] = powerbars[powerbar]['outlets'][outlet]['name']
2024-01-27 15:01:13 +00:00
cleaned_outlet['state'] = state
cleaned_outlet['on_url'] = f"/{powerbar}/{outlet}/on"
cleaned_outlet['off_url'] = f"/{powerbar}/{outlet}/off"
cleaned_outlet['state_url'] = f"/{powerbar}/{outlet}/state"
cleaned_outlet['cycle_url'] = f"/{powerbar}/{outlet}/cycle"
cleaned_outlet['toggle_url'] = f"/{powerbar}/{outlet}/toggle"
cleaned_outlet['password_protected'] = True if 'password' in powerbars[powerbar]['outlets'][outlet].keys() else False
cleaned_powerbar['outlets'][outlet] = cleaned_outlet
cleaned_powerbars[powerbar] = cleaned_powerbar
return jsonify(cleaned_powerbars)
2023-11-19 00:55:54 +00:00
2023-11-19 12:26:12 +00:00
2023-11-22 09:09:11 +00:00
@routes.route('/groups/<string:group>/<string:action>')
def powebar_group_action(group, action):
2023-11-19 12:26:12 +00:00
if not action in ['on', 'off', 'cycle']:
print("Invalid action")
return jsonify({'error': 'Invalid action'}), 400
2023-11-22 09:09:11 +00:00
group = find_group_by_name(group)
2023-11-19 12:26:12 +00:00
if not group:
print("Invalid group")
return jsonify({'error': 'Invalid group'}), 400
if action in ['on', 'off']:
try:
2023-11-22 09:09:11 +00:00
for device in group["devices"]:
powerbar = device["powerbar"]
print(f"Powerbar: {powerbar}")
outlets = ",".join([str(x) for x in device['outlets']])
print(f"Turning {action} powerbar {powerbar} outlet {outlets}")
2024-02-01 10:58:27 +00:00
if powerbars[powerbar]['method'] == "telnet":
2024-02-02 12:59:17 +00:00
command = run_telnet_command(powerbar,f"{action} {outlets}")
2024-02-07 15:44:32 +00:00
2024-02-07 17:29:54 +00:00
if powerbars[powerbar]['method'] == "batch_telnet":
2024-02-28 19:52:14 +00:00
for outlet in device['outlets']:
queues[powerbar].put({"outlet": outlet, "action" : action})
2024-02-07 17:29:54 +00:00
command = True
2024-02-07 15:44:32 +00:00
if command:
for outlet in device['outlets']:
if outlet in powerbars[powerbar]['outlets']:
powerbars[powerbar]['outlets'][outlet]['state'] = action
app.socketio.emit('power-event',{'powerbar': powerbar, 'outlet' : outlet, 'action' : action}, namespace='/powerupdates')
print(f"Turned {action} powerbar {powerbar} outlet {outlet}")
return jsonify({'status': "200"})
2024-02-02 12:59:17 +00:00
return jsonify({'status': "500"})
2023-11-19 12:26:12 +00:00
except Exception as E:
2024-02-01 23:28:11 +00:00
print(f"Endpoint Exception Error: {E}")
return jsonify({'error': 'Endpoint Exception Error'}), 500
2023-11-19 12:26:12 +00:00
2023-11-22 09:09:11 +00:00
@routes.route('/groups')
def powebar_groups():
2023-11-19 12:26:12 +00:00
try:
for group in groups:
2023-11-22 09:09:11 +00:00
group['on_url'] = f"/groups/{group['name']}/on"
group['off_url'] = f"/groups/{group['name']}/off"
2023-11-19 12:26:12 +00:00
return jsonify(groups)
except Exception as E:
print(f"Telnet error: {E}")
2023-11-24 11:48:00 +00:00
return jsonify({'error': 'no groups defined for powerbar'}), 404