added exception test to update and run script in api

added test for active connection and reconnect to update and run script in api
This commit is contained in:
tomaae 2019-12-06 01:17:01 +01:00
parent 6b9e1177d4
commit 05d21d1f42

View file

@ -123,6 +123,11 @@ class MikrotikAPI:
# --------------------------- # ---------------------------
def update(self, path, param, value, mod_param, mod_value): def update(self, path, param, value, mod_param, mod_value):
"""Modify a parameter""" """Modify a parameter"""
if not self._connected or not self._connection:
if not self.connect():
return None
try:
response = self.path(path) response = self.path(path)
if response is None: if response is None:
return False return False
@ -140,6 +145,19 @@ class MikrotikAPI:
} }
response.update(**params) response.update(**params)
except librouteros.exceptions.ConnectionClosed:
_LOGGER.error("Mikrotik %s connection closed", self._host)
self._connected = False
self._connection = None
return None
except (
librouteros.exceptions.TrapError,
librouteros.exceptions.MultiTrapError,
librouteros.exceptions.ProtocolError,
librouteros.exceptions.FatalError
) as api_error:
_LOGGER.error("Mikrotik %s connection error %s", self._host, api_error)
return None
return True return True
@ -148,6 +166,11 @@ class MikrotikAPI:
# --------------------------- # ---------------------------
def run_script(self, name): def run_script(self, name):
"""Run script""" """Run script"""
if not self._connected or not self._connection:
if not self.connect():
return None
try:
response = self.path('/system/script') response = self.path('/system/script')
if response is None: if response is None:
return False return False
@ -161,5 +184,18 @@ class MikrotikAPI:
run = response('run', **{'.id': tmp['.id']}) run = response('run', **{'.id': tmp['.id']})
tuple(run) tuple(run)
except librouteros.exceptions.ConnectionClosed:
_LOGGER.error("Mikrotik %s connection closed", self._host)
self._connected = False
self._connection = None
return None
except (
librouteros.exceptions.TrapError,
librouteros.exceptions.MultiTrapError,
librouteros.exceptions.ProtocolError,
librouteros.exceptions.FatalError
) as api_error:
_LOGGER.error("Mikrotik %s connection error %s", self._host, api_error)
return None
return True return True