def request(self, endpoint, method='POST', data=None, headers=None, cookies=None): url = '%s%s' % (self.api_host, endpoint) data = data or dict() headers = headers or dict() cookies = cookies or dict() request_kwargs = dict(method=method, url=url, headers=headers, timeout=self.timeout, cookies=cookies) if method in ('POST', 'PUT'): request_kwargs['data'] = data else: request_kwargs['params'] = data response = requests.request(**request_kwargs) self.write_log(**request_kwargs) if not str(response.status_code).startswith('2'): logger.warning('We have got response code %s with message %s' % (response.status_code, response.content)) utils.allure_attach( 'Bad status code', 'Status code:%s\n\nError message:\n%s\n' % (response.status_code, response.content)) return response
def update_geolocation(modem, immediately=False): global last_check periodically = False geolocation_data = {} old_geolocation = {} if os.path.isfile(GEOLOCATION_PATH): try: old_geolocation = read_yaml_all(GEOLOCATION_PATH) except: logger.warning("Old geolocation data in geolocation.yaml file couln't be read!") else: now = int(time.time()) if now - last_check > 24*60*60: # a day periodically = True last_check = now old_geolocation.pop("last_update", None) else: immediately = True if immediately or periodically: logger.info("Checking geolocation data...") try: modem.read_geoloc_data() except: logger.error("Error occured getting geolocation data") else: for key in modem.geolocation: geolocation_data[key] = modem.geolocation[key] if geolocation_data != old_geolocation and geolocation_data != {}: geolocation_data["last_update"] = int(time.time()) # Save ID's to file try: write_yaml_all(GEOLOCATION_PATH, geolocation_data) except Exception as error: logger.error("write_yaml_all(GEOLOCATION_PATH, geolocation_data) -> %s", error) else: logger.info("Geolocation data updated with changes.") # GEOLOCATION REPORT if conf.debug_mode and conf.verbose_mode: print("") print("********************************************************************") print("[?] GEOLOCATION REPORT") print("-------------------------") for item in geolocation_data.items(): print(f"[+] {item[0]} --> {item[1]}") print("********************************************************************") print("")
def get_interface_metrics(self): output = shell_command("ip route list") if output[2] != 0: raise RuntimeError('Error occured on "ip route list" command!') for line in output[0].splitlines(): for ifs in self.interfaces: if ifs.name in line and "default" in line: try: metric = parse_output(line, "metric", " ") ifs.actual_metric = int(metric) except Exception as error: logger.warning("Interface metrics couldn't be read! %s", error)
def get_interface_type(self): output = shell_command("lshw -C Network") if output[2] == 0: networks = output[0].split("*-network") for network in networks: for interface in self.interfaces: if network.find(interface.name) >= 0: if network.find("Ethernet interface") >= 0: if network.find("driver=cdc_ether") >= 0: interface.if_type = "C" # cellular modem.interface_name = interface.name else: interface.if_type = "E" # ethernet elif network.find("Wireless interface") >= 0: interface.if_type = "W" # wifi else: logger.warning("Error occured on --> get_interface_type")
def get_interface_type(self): output = shell_command("lshw -C Network") if output[2] == 0: networks = output[0].split("*-network") for network in networks: for interface in self.interfaces: if network.find(interface.name) >= 0: if network.find("Ethernet interface") >= 0: if network.find("driver=cdc_ether") >= 0: interface.if_type=InterfaceTypes.CELLULAR self.modem.interface_name = interface.name else: interface.if_type=InterfaceTypes.ETHERNET elif network.find("Wireless interface") >= 0: interface.if_type=InterfaceTypes.WIFI else: logger.warning("Error occured on --> get_interface_type")
def identify_modem(): global identified_module # Get old system setup if it is exist old_system_id = {} if os.path.isfile(SYSTEM_PATH): try: old_system_id = read_yaml_all(SYSTEM_PATH) except Exception as error: logger.warning("Old system_id in system.yaml file couln't be read!") system_id["modem_vendor"] = "" system_id["modem_name"] = "" system_id["modem_vendor_id"] = "" system_id["modem_product_id"] = "" logger.info("Tyring to detect modem...") output = shell_command("lsusb") if output[2] == 0: for module in modules: if output[0].find(module.pid) != -1: system_id["modem_vendor"] = module.vendor_name system_id["modem_name"] = module.module_name system_id["modem_vendor_id"] = module.vid system_id["modem_product_id"] = module.pid identified_module = module return identified_module logger.warning("Modem don't exist in list of supported modems!") for module in modules: if output[0].find(module.vid) != -1: system_id["modem_vendor"] = module.vendor_name system_id["modem_name"] = default_modules.get(str(module.vid)).module_name system_id["modem_vendor_id"] = module.vid system_id["modem_product_id"] = default_modules.get(str(module.vid)).pid identified_module = default_modules.get(str(module.vid)) return identified_module logger.warning("Modem vendor couldn't be found!") # clear modem identification data system_id["modem_vendor"] = None system_id["modem_name"] = None system_id["modem_vendor_id"] = None system_id["modem_product_id"] = None system_id["iccid"] = None system_id["imei"] = None system_id["sw_version"] = None if old_system_id.get("modem_vendor") is not None: try: write_yaml_all(SYSTEM_PATH, system_id) except Exception as error: raise RuntimeError("Save ID's to file") from error raise RuntimeError("Modem vendor couldn't be found!") else: raise RuntimeError("lsusb command error!")
def gpio_init(self, pin): pin_name = f"gpio{pin}" status = getstatusoutput(f"ls /sys/class/gpio/{pin_name}")[0] if status != 0: comm = f"echo {pin} > /sys/class/gpio/export" try: check_output(comm, shell=True) except: logger.warning("gpio_init --> export gpio") time.sleep(0.2) comm = f"echo out > /sys/class/gpio/gpio{pin}/direction" try: check_output(comm, shell=True) except: logger.exception("gpio_init -->") time.sleep(0.1)
def identify_setup(): # Get old system setup if it is exist old_system_id = {} if os.path.isfile(SYSTEM_PATH): try: old_system_id = read_yaml_all(SYSTEM_PATH) except Exception as error: logger.warning("Old system_id in system.yaml file couln't be read!") logger.info("[?] System identifying...") # Turn off AT command echo (Required) logger.debug("[+] Turning off AT command echo") try: _turn_off_echo() except Exception as error: raise error # Product Name (Optional) logger.debug("[+] Product Name") try: _identify_product_name() except Exception as error: logger.warning("Modem name identification failed!") system_id["modem_name"] = "Unknown" # IMEI (Optional) logger.debug("[+] IMEI") try: _identify_imei() except Exception as error: logger.warning("IMEI identification failed!") system_id["imei"] = "Unknown" # SW version (Optional) logger.debug("[+] Modem firmware revision") try: _identify_fw_version() except Exception as error: logger.warning("Modem firmware ver. identification failed!") system_id["sw_version"] = "Unknown" # ICCID (Optional) logger.debug("[+] SIM ICCID") try: _identify_iccid() except Exception as error: logger.warning("SIM ICCID identification failed!") system_id["iccid"] = "Unknown" # OS (Optional) logger.debug("[>] OS Identification") try: _identify_os() except Exception as error: logger.warning("OS identification failed!") # Board (Optional) logger.debug("[+] Board Identification") try: _identify_board() except Exception as error: logger.warning("Board identification failed!") try: system_id["last_update"] = int(time.time()) except Exception as error: logger.error("identify() timestamp -> %s", error) # IDENTIFICATION REPORT if conf.debug_mode and conf.verbose_mode: print("") print("********************************************************************") print("[?] IDENTIFICATION REPORT") print("-------------------------") for item in system_id.items(): print(f"[+] {item[0]} --> {item[1]}") print("********************************************************************") print("") # Save ID's to file try: write_yaml_all(SYSTEM_PATH, system_id) except Exception as error: raise error if system_id != old_system_id: logger.warning("System setup has changed!") return system_id or {}
def monitor(): # Get old system setup if it is exist old_monitor = {} if os.path.isfile(MONITOR_PATH): try: old_monitor = read_yaml_all(MONITOR_PATH) except: logger.warning( "Old monitor data in monitor.yaml file couln't be read!") monitor_data["last_update"] = old_monitor.get("last_update", int(time.time())) # Modem Manager monitoring data try: monitor_data["cellular_connection"] = modem.monitor.get( "cellular_connection") monitor_data["selected_apn"] = modem.get_apn() incident_count = monitor_data.get("fixed_incident", 0) old_incident_count = old_monitor.get("fixed_incident", 0) if incident_count >= old_incident_count: monitor_data["fixed_incident"] = modem.get_fixed_incident_count() else: monitor_data["fixed_incident"] = old_incident_count except Exception as error: logger.error("monitor() @modem -> %s", error) try: monitor_data["signal_quality"] = modem.get_signal_quality() except Exception as error: logger.error("monitor() @modem -> %s", error) try: monitor_data["roaming_operator"] = modem.get_roaming_operator() except Exception as error: logger.error("monitor() @modem -> %s", error) try: monitor_data["active_lte_tech"] = modem.get_active_lte_tech() except Exception as error: logger.error("monitor() @modem -> %s", error) # Network Manager monitoring data try: monitor_data["usable_interfaces"] = network.find_usable_interfaces() monitor_data["active_interface"] = network.find_active_interface() monitor_data["ifs_status"] = network.monitor except Exception as error: logger.error("monitor() @network -> %s", error) if monitor_data != old_monitor: monitor_data["last_update"] = int(time.time()) # Save ID's to file try: write_yaml_all(MONITOR_PATH, monitor_data) except Exception as error: logger.error("write_yaml_all(MONITOR_PATH, modem.monitor) -> %s", error) else: logger.info("Monitoring data updated with changes.") # MONITOR REPORT if conf.debug_mode and conf.verbose_mode: print("") print( "********************************************************************" ) print("[?] MONITOR REPORT") print("-------------------------") for item in monitor_data.items(): print(f"[+] {item[0]} --> {item[1]}") print( "********************************************************************" ) print("") # END OF MONITOR REPORT else: # logger.debug("No change on monitoring data.") pass
def configure_modem(self, recheck_delay=20): force_reset = 0 logger.info("Modem configuration started.") try: self.enable_auto_network_registeration() except Exception as error: raise error try: self.configure_apn() except Exception as error: raise error try: self.set_modem_eps_data_centric() except Exception as error: raise error logger.info("Checking the mode of modem...") output = send_at_com(self.mode_status_command, self.ecm_mode_response) if output[2] != 0: logger.info( "Modem mode is not set. ECM mode will be activated soon.") output = send_at_com(self.ecm_mode_setter_command, "OK") if output[2] == 0: logger.info("ECM mode is activating...") logger.info("The modem will reboot to apply changes.") else: raise ModemNotReachable( "Error occured while setting mode configuration!") try: self.wait_until_modem_turned_off() except Exception as error: logger.warning("wait_until_modem_turned_off() -> %s", error) force_reset = 1 else: try: self.wait_until_modem_started() except Exception as error: logger.warning("wait_until_modem_started() -> %s", error) force_reset = 2 if force_reset == 1: force_reset = 0 try: self.reset_modem_softly() except Exception as error: raise error elif force_reset == 2: force_reset = 0 try: self.reset_modem_hardly() except Exception as error: raise error time.sleep(recheck_delay) # delay until modem being functional logger.info("Re-checking the mode of modem...") output = send_at_com(self.mode_status_command, self.ecm_mode_response) if output[2] != 0: logger.error("Activation of ECM mode is failed!") raise RuntimeError else: logger.info("ECM mode activation is successful.")
def gpio_del(self): comm = f"echo {self.disable_pin} > /sys/class/gpio/unexport" try: check_output(comm, shell=True) except: logger.warning("gpio_del --> unexport gpio")
import usb.core from helpers.config_parser import conf from helpers.logger import logger from helpers.commander import shell_command, send_at_com from helpers.yamlio import read_yaml_all, write_yaml_all, DIAG_FOLDER_PATH, MONITOR_PATH from helpers.exceptions import * from helpers.sbc_support import supported_sbcs from helpers.modem_support.modem_support import DefaultModule old_monitor = {} if os.path.isfile(MONITOR_PATH): try: old_monitor = read_yaml_all(MONITOR_PATH) except: logger.warning("Old monitor data in monitor.yaml file couln't be read!") def parse_output(output, header, end): header += " " header_size = len(header) index_of_data = output[0].find(header) + header_size end_of_data = index_of_data + output[0][index_of_data:].find(end) sig_data = output[0][index_of_data:end_of_data] return sig_data class Modem(DefaultModule): imei = "" iccid = "" sw_version = ""