Skip to content

Commit

Permalink
style(formatting): apply black code formatter across project
Browse files Browse the repository at this point in the history
- Apply consistent formatting to setup.py, cli.py, usb_handle.py, and test_usb_handle.py
- Improve code readability by breaking long lines and adjusting indentation
- Remove unnecessary blank lines and add spacing where needed
- Standardize string quotes (use double quotes consistently)
- Adjust import order in some files

This commit improves code consistency and adheres to PEP 8 style guidelines,
making the codebase more maintainable and easier to read.
  • Loading branch information
elkanamol committed Sep 8, 2024
1 parent 5e5820f commit 276718e
Show file tree
Hide file tree
Showing 5 changed files with 108 additions and 65 deletions.
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
This setup configuration includes the package metadata, such as the name, version, description, author, license, and URLs for the project. It also specifies the required Python version, the packages to be included, and the console script entry point.
"""

from sierra_status.__version__ import __version__
from setuptools import setup, find_packages
import os
Expand Down Expand Up @@ -59,4 +60,3 @@
},
python_requires=">=3.8", # Requires Python 3.8 and above
)

2 changes: 1 addition & 1 deletion sierra_status/__version__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.1.4"
__version__ = "0.1.4"
55 changes: 45 additions & 10 deletions sierra_status/src/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

DEFAULT_BAUDRATE = 115200


def setup_logging(verbose: bool) -> None:
"""
Sets up the logging configuration based on the provided verbosity level.
Expand All @@ -21,6 +22,7 @@ def setup_logging(verbose: bool) -> None:
log_level = logging.DEBUG if verbose else logging.INFO
logging.basicConfig(level=log_level)


def validate_port(port: str) -> None:
"""
Validates that the specified USB port exists on the system.
Expand All @@ -34,6 +36,7 @@ def validate_port(port: str) -> None:
if not os.path.exists(port):
raise ValueError(f"The specified port '{port}' does not exist.")


def main() -> None:
"""
The main entry point for the Sierra Wireless EM9xxx/EM7xxx CLI tool.
Expand All @@ -53,29 +56,61 @@ def main() -> None:

parser = argparse.ArgumentParser(
description="CLI tool for Sierra Wireless EM9xxx/EM7xxx modules to query status",
formatter_class=argparse.RawTextHelpFormatter
formatter_class=argparse.RawTextHelpFormatter,
)

required = parser.add_argument_group('required arguments')
required.add_argument("-p", "--port", help="USB port to use (e.g., 'COM1' for Windows or '/dev/ttyUSB2' for Linux)", required=True)
required = parser.add_argument_group("required arguments")
required.add_argument(
"-p",
"--port",
help="USB port to use (e.g., 'COM1' for Windows or '/dev/ttyUSB2' for Linux)",
required=True,
)

optional = parser.add_argument_group('optional arguments')
optional.add_argument("--version", help="Show version", action="version", version=f"%(prog)s {__version__}")
optional.add_argument("-m", "--model", help="Model of the device to add to filename (e.g., EM9191 or EM7455)", default="")
optional.add_argument("-v", "--verbose", help="Enable verbose output", action="store_true")
optional.add_argument("-s", "--search", help="Search for network using AT!COPS=?", action="store_true")
optional.add_argument("-b", "--baudrate", help=f"Baudrate to use for serial communication (default: {DEFAULT_BAUDRATE})", default=DEFAULT_BAUDRATE, type=int)
optional = parser.add_argument_group("optional arguments")
optional.add_argument(
"--version",
help="Show version",
action="version",
version=f"%(prog)s {__version__}",
)
optional.add_argument(
"-m",
"--model",
help="Model of the device to add to filename (e.g., EM9191 or EM7455)",
default="",
)
optional.add_argument(
"-v", "--verbose", help="Enable verbose output", action="store_true"
)
optional.add_argument(
"-s", "--search", help="Search for network using AT!COPS=?", action="store_true"
)
optional.add_argument(
"-b",
"--baudrate",
help=f"Baudrate to use for serial communication (default: {DEFAULT_BAUDRATE})",
default=DEFAULT_BAUDRATE,
type=int,
)

args = parser.parse_args()

setup_logging(args.verbose)

try:
validate_port(args.port)
usb_handle.start_process(args.port, args.model.lower(), logging.getLogger().level, args.search, args.baudrate)
usb_handle.start_process(
args.port,
args.model.lower(),
logging.getLogger().level,
args.search,
args.baudrate,
)
except Exception as e:
logging.error(f"An error occurred: {str(e)}")
sys.exit(1)


if __name__ == "__main__":
main()
35 changes: 22 additions & 13 deletions sierra_status/src/usb_handle.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ def animate_spinner() -> None:
"""
Animates a simple spinner character to indicate an ongoing operation.
"""
chars = '|/-\\'
chars = "|/-\\"
for char in chars:
sys.stdout.write(f'\rReading {char}')
sys.stdout.write(f"\rReading {char}")
sys.stdout.flush()
time.sleep(0.05)

Expand Down Expand Up @@ -59,36 +59,41 @@ def send_at_command(
if "OK\r\n" in result or "ERROR\r\n" in result:
break
animate_spinner()

except serial.SerialException as e:
logging.error(f"Serial communication error: {e}")
except ValueError as e:
logging.error(f"Value error: {e}")
except Exception as e:
logging.error(f"Unexpected error: {e}")
finally:
sys.stdout.write('\r' + ' ' * 20 + '\r') # Clear the spinner line
sys.stdout.write("\r" + " " * 20 + "\r") # Clear the spinner line
sys.stdout.flush()
return "\n".join(line.strip() for line in result.splitlines() if line.strip())


def get_module_status(port: str, search: int, model: str, baudrate: int = 115200) -> str:
def get_module_status(
port: str, search: int, model: str, baudrate: int = 115200
) -> str:
"""
Retrieves the status of an module using AT commands.
Args:
port (str): The serial port to use.
search (int): A flag indicating whether to retrieve additional status information using the AT+COPS command.
model (str): The model of the module.
baudrate (int, optional): The baud rate to use for the serial connection. Defaults to 115200.
Returns:
str: The status information retrieved from the module.
"""
result = ""
try:
commands = AT_COMMANDS_HL78 if model.lower() == "hl78xx" else AT_COMMANDS
result = "\n\n".join(send_at_command(port, command, baudrate=baudrate).strip() for command in commands)
result = "\n\n".join(
send_at_command(port, command, baudrate=baudrate).strip()
for command in commands
)
if search:
result += f"\n\n{get_em_cops(port)}"
except Exception as e:
Expand All @@ -99,11 +104,11 @@ def get_module_status(port: str, search: int, model: str, baudrate: int = 115200
def get_em_cops(port: str, baudrate: int = DEFAULT_BAUDRATE) -> str:
"""
Retrieves the status of an EM9xxx module using the AT+COPS command.
Args:
port (str): The serial port to use.
baudrate (int, optional): The baud rate to use for the serial connection. Defaults to the DEFAULT_BAUDRATE.
Returns:
str: The status information retrieved from the module.
"""
Expand Down Expand Up @@ -137,9 +142,13 @@ def start_process(
"""
Main function to retrieve the status of an EM9xxx module using AT commands.
"""
logging.basicConfig(level=log_level, format='%(asctime)s - %(levelname)s - %(message)s')
logging.info(f"Starting process for port {port} with model {model} and baudrate {baudrate}")
result = get_module_status(port, search, model, baudrate)
logging.basicConfig(
level=log_level, format="%(asctime)s - %(levelname)s - %(message)s"
)
logging.info(
f"Starting process for port {port} with model {model} and baudrate {baudrate}"
)
result = get_module_status(port, search, model, baudrate)
if result:
creat_status_file(result, model)
else:
Expand Down
Loading

0 comments on commit 276718e

Please sign in to comment.