ti-powerbar/app/views.py

71 lines
1.9 KiB
Python
Raw Normal View History

2023-11-19 00:07:25 +00:00
from flask import render_template, Blueprint, make_response
from app.settings import powerbars
from flask import abort
import telnetlib
routes = Blueprint('routes', __name__)
def vaild_power_bar(powerbar):
if powerbar in powerbars:
return True
else:
return False
def vaild_outlet (powerbar, outlet):
if outlet in powerbars[powerbar]['outlets']:
return True
else:
return False
@routes.route('/')
def home():
print(powerbars)
return "hello world"
@routes.route('/powerbar_control/<string:powerbar>/<int:outlet>/<string:action>')
def powerbar_control(powerbar, outlet, action):
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
if not action in ['on', 'off', 'cycle']:
2023-11-19 00:10:51 +00:00
print("Invalid action")
2023-11-19 00:07:25 +00:00
abort(404)
if not vaild_power_bar(powerbar):
2023-11-19 00:10:51 +00:00
print("Invalid powerbar")
2023-11-19 00:07:25 +00:00
abort(404)
if not vaild_outlet(powerbar, outlet):
2023-11-19 00:10:51 +00:00
print("Invalid outlet")
2023-11-19 00:07:25 +00:00
abort(404)
if action == 'on':
try:
2023-11-19 00:12:57 +00:00
print(f"Turning on powerbar {powerbar} outlet {outlet}")
2023-11-19 00:07:25 +00:00
tn = telnetlib.Telnet(powerbars[powerbar]['host'], powerbars[powerbar]['port'])
tn.write(f"on {outlet}\r\n".encode('ascii'))
tn.close()
2023-11-19 00:10:51 +00:00
print(f"Turned on powerbar {powerbar} outlet {outlet}")
2023-11-19 00:07:25 +00:00
except Exception as e:
print(f"Telnet error: {e}")
abort(500)
if action == 'off':
try:
2023-11-19 00:12:57 +00:00
print(f"Turning off powerbar {powerbar} outlet {outlet}")
2023-11-19 00:07:25 +00:00
tn = telnetlib.Telnet(powerbars[powerbar]['host'], powerbars[powerbar]['port'])
tn.write(f"off {outlet}\r\n".encode('ascii'))
tn.close()
2023-11-19 00:10:51 +00:00
print(f"Turned off powerbar {powerbar} outlet {outlet}")
2023-11-19 00:07:25 +00:00
except Exception as e:
print(f"Telnet error: {e}")
abort(500)
2023-11-19 00:16:41 +00:00
2023-11-19 00:10:51 +00:00
return "200"
2023-11-19 00:07:25 +00:00