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///') def powerbar_control(powerbar, outlet, action): print(f"powerbar: {powerbar}") print(f"outlet: {outlet}") print(f"action: {action}") if not action in ['on', 'off', 'cycle']: print("Invalid action") abort(404) if not vaild_power_bar(powerbar): print("Invalid powerbar") abort(404) if not vaild_outlet(powerbar, outlet): print("Invalid outlet") abort(404) if action in ['on', 'off']: try: print(f"Turning {action} powerbar {powerbar} outlet {outlet}") tn = telnetlib.Telnet(powerbars[powerbar]['host'], powerbars[powerbar]['port']) tn.write(f"{action} {outlet}\r\n".encode('ascii')) tn.close() powerbars[powerbar]['outlets'][outlet]['state'] = action print(f"Turned {action} powerbar {powerbar} outlet {outlet}") except Exception as e: print(f"Telnet error: {e}") abort(500) return "200" @routes.route('/powerbar_state//') def powerbar_state(powerbar, outlet): print(f"powerbar: {powerbar}") print(f"outlet: {outlet}") if not vaild_power_bar(powerbar): print("Invalid powerbar") abort(404) if not vaild_outlet(powerbar, outlet): print("Invalid outlet") abort(404) state = powerbars[powerbar]['outlets'][outlet].get('state', 'unknown') return state