def get_conf_item(self, opt_find: Enum, dev_name: str, default_val=None): # Sec - Set Default Val if default_val is None: with Switch(opt_find) as case: if case(ConfigOptions.port): val_def = self.get_conf(opt_find.name, self.__default_port) elif case(ConfigOptions.label, ConfigOptions.host, ConfigOptions.user, ConfigOptions.password): val_def = self.get_conf(opt_find.name, "") elif case(ConfigOptions.enabled): val_def = self.get_conf(opt_find.name, self.__default_enabled) else: if opt_find is None: raise ValueError("opt_find it can not be None!") else: raise TypeError("{0} is not valid option!".format( opt_find.name)) else: val_def = default_val # Sec - Get Data config value = self.get_conf_in_list(opt_find, dev_name, val_def, key_name_list="remote") # Sec - Format Return Data with Switch(opt_find) as case: if case(ConfigOptions.port): value = str(value).strip() if not value or not value.isnumeric() or int(value) <= 0: value = val_def return int(value) elif case(ConfigOptions.enabled): return bool(value) elif case(ConfigOptions.label, ConfigOptions.host, ConfigOptions.user, ConfigOptions.password): value = str(value).strip() if not value: value = val_def return str(value) else: return value
def check(self): list_url = [] for (key, value) in self.get_conf('list', {}).items(): is_enabled = self.__default_enabled with Switch(value, check_isinstance=True) as case: if case(bool): is_enabled = value elif case(dict): is_enabled = value.get("enabled", is_enabled) self.debug.print( ">> PlugIn >> {0} >> Web: {1} - Enabled: {2}".format( self.name_module, key, is_enabled), DebugLevel.info) if is_enabled: list_url.append(key) with concurrent.futures.ThreadPoolExecutor(max_workers=self.get_conf( 'threads', self._default_threads)) as executor: future_to_url = { executor.submit(self.__web_check, url): url for url in list_url } for future in concurrent.futures.as_completed(future_to_url): url = future_to_url[future] try: future.result() except Exception as exc: message = 'Web: {0} - Error: {1}'.format(url, exc) self.dict_return.set(url, False, message) super().check() return self.dict_return
def get_conf_in_list(self, opt_find, key_name_module: str, def_val=None, key_name_list: str = "list"): """ Obtenemos los datos que deseamos buscar de la sección 'list' de la configuración del modulo. :param opt_find: Opción a buscar. :param key_name_module: Nombre del modulo del que deseamos obtener la sección 'list'. :param def_val: Valor por defecto si no existe la opción que buscamos. :param key_name_list: Key de la configuración donde se almacena el listado donde vamos a buscar. :return: Valor obtenido de la configuración. """ with Switch(opt_find, check_isinstance=True) as case: if case(Enum): find_key = [opt_find.name] elif case(str): find_key = [opt_find] elif case(list): find_key = opt_find.copy() elif case(int, float): find_key = [str(opt_find)] elif case(tuple): find_key = list(opt_find) else: raise TypeError("opt_find is not valid type ({0})!".format( type(opt_find))) if key_name_module: find_key.insert(0, key_name_module) find_key.insert(0, key_name_list) value = self.get_conf(find_key, def_val) return value
def __check_get_list_hosts(self): return_list = [] for (key, value) in self.get_conf('list', {}).items(): is_enabled = self.__default_enabled with Switch(value, check_isinstance=True) as case: if case(bool): is_enabled = value elif case(dict): is_enabled = value.get("enabled", is_enabled) self.__debug("{0} - Enabled: {1}".format(key, is_enabled), DebugLevel.info) if is_enabled: if not value.get("host", None): self.__debug("{0} - Host is not defined!".format(key), DebugLevel.warning) else: new_hddtemp = self.Hddtemp_Info(key) new_hddtemp.host = value.get("host") new_hddtemp.port = value.get("port", self.__default_port) new_hddtemp.alert = self.get_conf('alert', self.__default_alert) new_hddtemp.exclude = value.get("exclude", []) return_list.append(new_hddtemp) return return_list
def __db_check(self, db): tmp_socket = self.__get_conf(ConfigOptions.socket, db) tmp_host = self.__get_conf(ConfigOptions.host, db) tmp_port = self.__get_conf(ConfigOptions.port, db) tmp_user = self.__get_conf(ConfigOptions.user, db) tmp_pass = self.__get_conf(ConfigOptions.password, db) tmp_db = self.__get_conf(ConfigOptions.db, db) status, message = self.__db_return(db, tmp_socket, tmp_host, tmp_port, tmp_user, tmp_pass, tmp_db) s_message = 'MySQL: ' if status == "OK": s_message += '*{0}* {1}'.format(db, u'\U00002705') status = True else: s_message += '{0} - *Error:* '.format(db) with Switch(status) as case: if case("1045"): # OperationalError(1045, "Access denied for user 'user'@'server' (using password: NO)") # OperationalError(1045, "Access denied for user 'user'@'server' (using password: YES)") s_message += "*Access denied* {0}".format('\U0001F510') elif case("2003"): # OperationalError(2003, "Can't connect to MySQL server on 'host1' (timed out)") # OperationalError(2003, "Can't connect to MySQL server on 'host1' ([Errno 113] No route to host)") # OperationalError(2003, "Can't connect to MySQL server on 'host1' ([Errno 111] Connection refused)" s_message += "*Can't connect to MySQL server*" with Switch(message, check_contain=True) as sub_case: if sub_case('(timed out)'): s_message += ' *(timed out)*' elif sub_case('[Errno 111]'): s_message += ' *(connection refused)*' elif sub_case('[Errno 113]'): s_message += ' *(no route to host)*' else: s_message += ' *(?????)*' s_message += '\U000026A0' # s_message += "*Can't connect to MySQL server (time out)* {0}".format('\U000026A0') else: s_message += '*{0}* {1}'.format(message, '\U000026A0') status = False other_data = {'message': message} self.dict_return.set(db, status, s_message, False, other_data) if self.check_status_custom(status, db, message): self.send_message(s_message, status)
def __get_conf(self, opt_find: Enum, dev_name: str, default_val=None): # Sec - Get Default Val if default_val is None: with Switch(opt_find) as case: if case(ConfigOptions.attempt): val_def = self.get_conf(opt_find.name, self.__default_attempt) elif case(ConfigOptions.timeout): val_def = self.get_conf(opt_find.name, self.__default_timeout) elif case(ConfigOptions.enabled): val_def = self.get_conf(opt_find.name, self.__default_enabled) else: if opt_find is None: raise ValueError("opt_find it can not be None!") else: raise TypeError("{0} is not valid option!".format( opt_find.name)) else: val_def = default_val # Sec - Get Data value = self.get_conf_in_list(opt_find, dev_name, val_def) # Sec - Format Return Data with Switch(opt_find) as case: if case(ConfigOptions.attempt, ConfigOptions.timeout): value = str(value).strip() if not value or not value.isnumeric() or int(value) <= 0: value = val_def return int(value) elif case(ConfigOptions.enabled): return bool(value) elif case(ConfigOptions.label): value = str(value).strip() if not value: value = val_def return str(value) else: return value
def addButton(self, pin, name): m = GPIO.getmode() GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, False) s = Switch() self.layout.addRow(name, s) s.clicked.connect(lambda checked, p=pin: self.onOff(checked, p)) if m: GPIO.setmode(m)
def __md_analyze(self, list_md, remote_id=None): label = self.get_label_by_id(remote_id) if len(list_md) == 0: message = "[{0}] *No RAID's* in the system. {1}".format( label, u'\U00002705') key_id = "R_{0}".format(remote_id) if remote_id else "L" self.dict_return.set(key_id, True, message) else: for (key, value) in list_md.items(): # print("key:", key, " - Val:", value) other_data = {} is_warning = True with Switch(value.get("update", '')) as case: if case(RaidMdstat.UpdateStatus.ok): is_warning = False message = "RAID *{0}/{1}* in good status. {2}".format( label, key, u'\U00002705') elif case(RaidMdstat.UpdateStatus.error): message = "*RAID {0}/{1} is degraded.* {2}".format( label, key, u'\U000026A0') elif case(RaidMdstat.UpdateStatus.recovery): other_data['percent'] = value.get("recovery", {}).get( 'percent', -1) other_data['finish'] = value.get("recovery", {}).get('finish', -1) other_data['speed'] = value.get("recovery", {}).get('speed', -1) message = "*RAID {0}/{1} is degraded, recovery status {2}%, estimate time to finish {3}.* {4}". \ format(label, key, other_data['percent'], other_data['finish'], u'\U000026A0') else: message = "*RAID {0}/{1} Unknown Error*. {2}".format( label, key, u'\U000026A0') if remote_id: key_id = "R_{0}_{1}".format(remote_id, key) else: key_id = "L_{0}".format(key) self.dict_return.set(key_id, not is_warning, message, other_data=other_data)
import lib.redpitaya_scpi as scpi import lib.Switch as Switch import lib.AgilentNA as AG import pyvisa as py import numpy as np import time from scipy.signal import find_peaks rp = scpi.scpi('192.168.137.209') zx80 = Switch.zx80(rp) NA = AG.AgilentNA() rm = py.ResourceManager() FG = rm.open_resource(rm.list_resources()[0]) PSD = np.loadtxt(open('D:\\20201109-0001.csv'), skiprows=2, delimiter=",") PSD = PSD[0:70000, :] peaks, prop = find_peaks(PSD[:, 1], prominence=5) locs = PSD[peaks, 0] locs = locs[3:] for loc in locs: zx80.RF2Off() zx80.RF1Off() NA.inst.write('BW 30') NA.inst.write('POIN 401') NA.inst.write('POWE -50') time.sleep(0.5) NA.center([loc * 1e6, 2000]) noiseFloor, noiseFloorStd = NA.getNoiseFloor([zx80]) judge = True baseAMP = 0.001
def __db_return(self, db_name, socket, host, port, user, password, db): return_status = 0 return_msg = "" connect_socket = True if len(str(socket).strip()) > 0 else False try: if connect_socket: if not os.path.exists(socket): return "SOCKET_NOT_EXIST", "Socket file is not exist!" connection = pymysql.connect( unix_socket=socket, db=db, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) else: connection = pymysql.connect( host=host, port=port, user=user, password=password, db=db, charset='utf8mb4', connect_timeout=10, cursorclass=pymysql.cursors.DictCursor) except Exception as e: connection = None self.__debug("{0} >> Exception: {1}".format(db_name, repr(e)), DebugLevel.error) return_msg = repr(e) err_array = str(e).split(",") err_code = err_array[0][1:] with Switch(err_code) as case: if case("2003") and connect_socket: return "SOCKET_ERROR", "Socket file is not work!" elif case("1045", "2003"): return_status = err_code else: return_status = "-9999" if connection is not None: try: with connection.cursor() as cursor: cursor.execute("SHOW GLOBAL STATUS") # for row in cursor: # print("ROW:", row) # result = cursor.fetchone() # print("RESULT SQL:", result) return_status = "OK" except Exception as e: self.__debug("{0} >> Exception: {1}".format(db_name, repr(e)), DebugLevel.error) return_msg = repr(e) return_status = "-9999" finally: connection.close() return return_status, return_msg