diff --git a/app/views.py b/app/views.py index f42b3be..0714ad8 100644 --- a/app/views.py +++ b/app/views.py @@ -70,7 +70,7 @@ def powerbar_control(powerbar, outlet, action): print(f"outlet: {outlet}") print(f"action: {action}") - if not action in ['on', 'off', 'cycle']: + if not action in ['on', 'off', 'cycle', 'toggle']: print("Invalid action") return jsonify({'error': 'Invalid action'}), 400 @@ -102,8 +102,28 @@ def powerbar_control(powerbar, outlet, action): time.sleep(5) print(f"Turning On powerbar {powerbar} outlet {outlet}") tn.write(f"on {outlet}\r\n".encode('ascii')) - powerbars[powerbar]['outlets'][outlet]['state'] = "on" tn.close() + powerbars[powerbar]['outlets'][outlet]['state'] = "on" + + if action == 'toggle': + print(powerbars[powerbar]['outlets'][outlet]['state']) + + if powerbars[powerbar]['outlets'][outlet]['state'] == "on": + tn = telnetlib.Telnet(powerbars[powerbar]['host'], powerbars[powerbar]['port']) + print(f"Turning Off powerbar {powerbar} outlet {outlet}") + tn.write(f"off {outlet}\r\n".encode('ascii')) + tn.close() + powerbars[powerbar]['outlets'][outlet]['state'] = "off" + elif powerbars[powerbar]['outlets'][outlet]['state'] == "off": + tn = telnetlib.Telnet(powerbars[powerbar]['host'], powerbars[powerbar]['port']) + print(f"Turning On powerbar {powerbar} outlet {outlet}") + tn.write(f"on {outlet}\r\n".encode('ascii')) + tn.close() + powerbars[powerbar]['outlets'][outlet]['state'] = "on" + + return jsonify({'state': powerbars[powerbar]['outlets'][outlet].get('state', 'unknown')}) + + return jsonify({'state': powerbars[powerbar]['outlets'][outlet].get('state', 'unknown')}) @@ -136,6 +156,7 @@ def powerbars_list(): powerbars[powerbar]['outlets'][outlet]['off_url'] = f"/{powerbar}/{outlet}/off" powerbars[powerbar]['outlets'][outlet]['state_url'] = f"/{powerbar}/{outlet}/state" powerbars[powerbar]['outlets'][outlet]['cycle_url'] = f"/{powerbar}/{outlet}/cycle" + powerbars[powerbar]['outlets'][outlet]['toggle_url'] = f"/{powerbar}/{outlet}/toggle" for group in powerbars[powerbar]['groups']: