Skip to content

Commit

Permalink
Feature/venv (#145)
Browse files Browse the repository at this point in the history
adds the Python Venv environment to be setup.
  • Loading branch information
dyldonahue committed Sep 10, 2024
1 parent fdfdca7 commit cba9b75
Show file tree
Hide file tree
Showing 10 changed files with 523 additions and 1 deletion.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
.vscode/
__pycache__/
__pycache__/
*.egg-info/
10 changes: 10 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
repos:
- repo: local
hooks:
- id: clang_restage
name: Restage formatted files
entry: clang_restage
language: system
pass_filenames: false
always_run: true
stages: [pre-commit]
8 changes: 8 additions & 0 deletions aliases.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
build="docker compose run --rm ner-gcc-arm make"
cerbcon="sudo modprobe vhci_hcd && sudo usbip attach -r 192.168.100.12 -b 1-1.3"
disconnect="sudo usbip detach -p 0"
shepcon="sudo modprobe vhci_hcd && sudo usbip attach -r 192.168.100.12 -b 1-1.4"
peyton="echo \" Shut the fuck up Peyton, fucking hell\" "
flash="bash -c \"probe-rs download --verify --chip STM32F405RGTx ./build/*.elf && probe-rs reset --chip STM32F405RGTx\" "
reset-target="bash -c \"probe-rs reset --chip STM32F405RGTx\" "
debug="bash -c 'probe-rs gdb --gdb-connection-string 0.0.0.0:1337 --chip STM32F405RGTx & sleep 1; docker compose run --rm -P ner-gcc-arm "arm-none-eabi-gdb" /home/app$(ls ./build/*.elf | cut -c2-) -ex \"target remote host.docker.internal:1337\" && killall probe-rs && probe-rs reset --chip STM32F405RGTx' "
50 changes: 50 additions & 0 deletions clang_restage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import subprocess
import sys
import os

def get_staged_files():
# Run the git command to get staged files
result = subprocess.run(['git', 'diff', '--cached', '--name-only'], stdout=subprocess.PIPE, text=True)

# Get the list of staged files from stdout
staged_files = result.stdout.splitlines()

# Filter files based on their extensions
filtered_files = [f for f in staged_files if f.endswith(('.c', '.cpp', '.h'))]

return filtered_files

def restage_files(files):
if files:
subprocess.run(['git', 'add'] + files)
else:
print("No files to restage.")

def main():

current_directory = os.getcwd()

# Get a list of staged files
staged_files = get_staged_files()

# Run clang-format on staged files

if "bedded" in current_directory:
result = subprocess.run(['clang-format', '--style=file:clang-format', '-i'] + staged_files,
capture_output=True, text=True)
else:

clang_format_path = os.path.join(current_directory, 'Drivers', 'Embedded-Base', 'clang-format')
result = subprocess.run(['clang-format', f'--style=file:{clang_format_path}', '-i'] + staged_files,
capture_output=True, text=True)

if result.returncode == 0:
print("clang-format passed. Restaging files.")
restage_files(staged_files)
else:
print(current_directory)
print(f"clang-format failed. Please fix the issues and commit again.(Most likely, just try commiting again) {clang_format_path}")
sys.exit(1)

if __name__ == '__main__':
main()
115 changes: 115 additions & 0 deletions launchpad.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import subprocess
import sys
import os
import platform
import shutil

def install_platformio(venv_path):
"""Install PlatformIO package and set up aliases."""
try:
# Install the platformio package
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'platformio'])

# Define aliases
aliases = [
'lpbuild="platformio run"',
'lpflash="platformio run --target upload"',
'lpinit="platformio project init"',

]

os_type = platform.system()
if os_type == 'Windows':
activate_path = os.path.join(venv_path, 'Scripts', 'activate') # Bash script for Git Bash on Windows
else:
activate_path = os.path.join(venv_path, 'bin', 'activate') # bash script for Unix-like system


with open(activate_path, 'a') as activate_file:
activate_file.write('\n# Aliases\n')
for alias in aliases:
alias_name, alias_command = alias.strip().split('=', 1)
alias_command = alias_command.strip('"')
activate_file.write(f'alias {alias_name}="{alias_command}"\n')

print("Aliases added to the activation script successfully.")

except subprocess.CalledProcessError as e:
print(f"Failed to install PlatformIO: {e}", file=sys.stderr)
sys.exit(1)

def uninstall_platformio(venv_path):
"""Uninstall PlatformIO package and remove aliases."""
try:
# Uninstall the platformio package
subprocess.check_call([sys.executable, '-m', 'pip', 'uninstall', '-y', 'platformio'])

# Remove PlatformIO directory
remove_platformio_directory()

# Determine OS and adjust alias handling
os_type = platform.system()
if os_type == 'Windows':
activate_path = os.path.join(venv_path, 'Scripts', 'activate') # Bash script for Git Bash on Windows
else:
activate_path = os.path.join(venv_path, 'bin', 'activate') # bash script for Unix-like system

remove_aliases(activate_path)

print("PlatformIO uninstalled and aliases removed. Please restart your terminal or source your profile script.")

except subprocess.CalledProcessError as e:
print(f"Failed to uninstall PlatformIO: {e}", file=sys.stderr)
sys.exit(1)

def remove_aliases(activate_path):
"""Remove aliases from the virtual environment's activation script."""
try:
if os.path.exists(activate_path):
with open(activate_path, 'r') as f:
lines = f.readlines()
with open(activate_path, 'w') as f:
for line in lines:
if not line.startswith('alias '):
f.write(line)
print("Aliases removed from the activation script successfully.")
else:
print("Activation script not found.", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Failed to remove aliases: {e}", file=sys.stderr)
sys.exit(1)

def remove_platformio_directory():
"""Remove the PlatformIO directory."""
platformio_dir = os.path.expanduser('~/.platformio')
if os.path.isdir(platformio_dir):
try:
shutil.rmtree(platformio_dir)
print("PlatformIO directory removed.")
except OSError as e:
print(f"Failed to remove PlatformIO directory: {e}", file=sys.stderr)
sys.exit(1)
else:
print("PlatformIO directory does not exist.")
def main():
if len(sys.argv) != 2:
print("Usage: launchpad.py [install|uninstall]", file=sys.stderr)
sys.exit(1)

os_type = platform.system()
current_directory = os.path.dirname(os.path.abspath(__file__))
parent_directory = os.path.dirname(current_directory)
venv_path = os.path.join(parent_directory, 'ner-venv')

action = sys.argv[1].lower()
if action == 'install':
install_platformio(venv_path)
elif action == 'uninstall':
uninstall_platformio(venv_path)
else:
print("Invalid action. Use 'install' or 'uninstall'.", file=sys.stderr)
sys.exit(1)

if __name__ == '__main__':
main()
65 changes: 65 additions & 0 deletions load_alias.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import os
import platform
import sys

def load_aliases(venv_path, aliases_file):
os_type = platform.system()
if os_type == 'Windows':
activate_path = os.path.join(venv_path, 'Scripts', 'activate') # Bash script for Git Bash on Windows
else:
activate_path = os.path.join(venv_path, 'bin', 'activate') # bash script for Unix-like systems

try:
# Read existing aliases from the activation script
if os.path.exists(activate_path):
with open(activate_path, 'r') as activate_file:
existing_aliases = activate_file.readlines()
else:
existing_aliases = []

# Convert the existing aliases to a set for easy comparison
existing_aliases_set = set()
for line in existing_aliases:
if line.startswith('alias '):
alias_definition = line.strip()
alias_name = alias_definition.split('=')[0].replace('alias ', '')
existing_aliases_set.add(alias_name)

# Read aliases from the provided aliases file
with open(aliases_file, 'r') as f:
aliases = f.readlines()

# Prepare to write new aliases that aren't already in the activate script
new_aliases = []
for alias in aliases:
alias_name, alias_command = alias.strip().split('=', 1)
alias_name = alias_name.strip()
alias_command = alias_command.strip('"')

if alias_name not in existing_aliases_set:
new_aliases.append(f'alias {alias_name}="{alias_command}"\n')

# Append new aliases to the activation script if there are any
if new_aliases:
with open(activate_path, 'a') as activate_file:
activate_file.write('\n# Aliases\n')
activate_file.writelines(new_aliases)
print(f"Added {len(new_aliases)} new alias(es) to the activation script.")
else:
print("No new aliases to add; all are already present.")

except Exception as e:
print(f"Failed to update aliases: {e}", file=sys.stderr)
sys.exit(1)

def main():
current_directory = os.path.dirname(os.path.abspath(__file__))
parent_directory = os.path.dirname(current_directory)
venv_path = os.path.join(parent_directory, 'ner-venv')
aliases_file = os.path.join(current_directory, 'aliases.txt')

load_aliases(venv_path, aliases_file)
print("Close and reopen your terminal or the venv for changes to take effect.")

if __name__ == "__main__":
main()
62 changes: 62 additions & 0 deletions miniterm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import os
import subprocess
import platform
import sys

def list_usb_devices():
"""List available USB serial devices based on the operating system."""
os_name = platform.system()

if os_name == 'Windows':
# List COM ports on Windows
try:
result = subprocess.run(['wmic', 'path', 'Win32_SerialPort'], capture_output=True, text=True)
devices = []
for line in result.stdout.splitlines():
if 'DeviceID' in line:
devices.append(line.split()[-1])
return devices
except Exception as e:
print(f"Failed to list USB devices on Windows: {e}", file=sys.stderr)
sys.exit(1)

elif os_name == 'Linux' or os_name == 'Darwin': # Darwin is macOS
# List USB devices on Unix-like systems
try:
result = subprocess.run(['ls /dev/tty*'], shell=True, capture_output=True, text=True)

devices = [device for device in result.stdout.splitlines() if 'ttyUSB' in device or 'ttyACM' in device]
return devices
except Exception as e:
print(f"Failed to list USB devices on {os_name}: {e}", file=sys.stderr)
sys.exit(1)

else:
print(f"Unsupported operating system: {os_name}", file=sys.stderr)
sys.exit(1)

def run_miniterm(device, baudrate=115200):
"""Run pyserial-miniterm with the specified device and baudrate."""
try:
subprocess.run(['pyserial-miniterm', device, str(baudrate)], check=True)
except subprocess.CalledProcessError as e:
print(f"Failed to run pyserial-miniterm: {e}", file=sys.stderr)
sys.exit(1)

def main():
# Detect the operating system and find USB devices
devices = list_usb_devices()

if not devices:
print("No USB devices found.", file=sys.stderr)
sys.exit(1)

# Default to the first device if available
selected_device = devices[0]
print(f"Selected USB device: {selected_device}")

# Run pyserial-miniterm with the selected device
run_miniterm(selected_device)

if __name__ == '__main__':
main()
Loading

0 comments on commit cba9b75

Please sign in to comment.