For the API vist '/powerbars' and '/groups' | A project brought to you by Piele & Mattronix for the code vist
code.techinc.nl
diff --git a/app/views.py b/app/views.py
index 2052426..033840f 100644
--- a/app/views.py
+++ b/app/views.py
@@ -30,6 +30,17 @@ def get_telnet_connection(powerbar):
return tn
+def run_telnet_command(powerbar, command):
+ try:
+ tn.write(f"{command}\r\n".encode('ascii'))
+ return
+ except Exception as e:
+ print(f"Telnet error: {e}")
+ active_telnet_connections.pop(powerbar)
+ tn = get_telnet_connection(powerbar)
+ tn.write(f"{command}\r\n".encode('ascii'))
+ return
+
def find_group_by_name(name):
for group in groups:
@@ -98,7 +109,7 @@ def powerbar_control(powerbar, outlet, action):
try:
print(f"Turning {action} powerbar {powerbar} outlet {outlet}")
tn = get_telnet_connection(powerbar)
- tn.write(f"{action} {outlet}\r\n".encode('ascii'))
+ run_telnet_command(powerbar,f"{action} {outlet}")
powerbars[powerbar]['outlets'][outlet]['state'] = action
print(f"Turned {action} powerbar {powerbar} outlet {outlet}")
except Exception as E:
@@ -109,10 +120,10 @@ def powerbar_control(powerbar, outlet, action):
tn = get_telnet_connection(powerbar)
print(f"Turning Off powerbar {powerbar} outlet {outlet}")
powerbars[powerbar]['outlets'][outlet]['state'] = "off"
- tn.write(f"off {outlet}\r\n".encode('ascii'))
+ run_telnet_command(powerbar,f"off {outlet}")
time.sleep(5)
print(f"Turning On powerbar {powerbar} outlet {outlet}")
- tn.write(f"on {outlet}\r\n".encode('ascii'))
+ run_telnet_command(powerbar,f"on {outlet}")
powerbars[powerbar]['outlets'][outlet]['state'] = "on"
if action == 'toggle':
@@ -121,12 +132,13 @@ def powerbar_control(powerbar, outlet, action):
if powerbars[powerbar]['outlets'][outlet]['state'] == "on":
tn = get_telnet_connection(powerbar)
print(f"Turning Off powerbar {powerbar} outlet {outlet}")
- tn.write(f"off {outlet}\r\n".encode('ascii'))
+ run_telnet_command(powerbar,f"off {outlet}")
+
powerbars[powerbar]['outlets'][outlet]['state'] = "off"
elif powerbars[powerbar]['outlets'][outlet]['state'] == "off":
tn = get_telnet_connection(powerbar)
print(f"Turning On powerbar {powerbar} outlet {outlet}")
- tn.write(f"on {outlet}\r\n".encode('ascii'))
+ run_telnet_command(powerbar,f"on {outlet}")
powerbars[powerbar]['outlets'][outlet]['state'] = "on"
return jsonify({'state': powerbars[powerbar]['outlets'][outlet].get('state', 'unknown')})
@@ -191,7 +203,7 @@ def powebar_group_action(group, action):
print(f"Powerbar: {powerbar}")
outlets = ",".join([str(x) for x in device['outlets']])
print(f"Turning {action} powerbar {powerbar} outlet {outlets}")
- tn.write(f"{action} {outlets}\r\n".encode('ascii'))
+ run_telnet_command(powerbar,f"{action} {outlets}")
for outlet in device['outlets']:
if outlet in powerbars[powerbar]['outlets']:
powerbars[powerbar]['outlets'][outlet]['state'] = action