### Install Jupyter and Launch Notebooks Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/car_porting/README.md Instructions for installing Jupyter and its kernel within the Openpilot virtual environment, and how to launch the Jupyter notebook server. ```bash uv pip install jupyter ipykernel jupyter notebook ``` -------------------------------- ### Clone and Install Openpilot Dependencies Source: https://github.com/sunnypilot/sunnypilot/blob/master/docs/how-to/turn-the-speed-blue.md This script clones the openpilot repository and installs all necessary dependencies for development. It automates the setup process for a new development environment. ```bash bash <(curl -fsSL openpilot.comma.ai) ``` -------------------------------- ### Start Route Replay and UI - Bash Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/CTF.md This snippet demonstrates how to start the route replay tool and the user interface for the SunnyPilot CTF. It requires navigating to the 'tools/replay' directory and executing the replay command with a specific route, followed by starting the UI in a separate terminal. ```bash cd tools/replay ./replay '0c7f0c7f0c7f0c7f|2021-10-13--13-00-00' --dcam --ecam # start the UI in another terminal selfdrive/ui/ui ``` -------------------------------- ### Build Example Executable Source: https://github.com/sunnypilot/sunnypilot/blob/master/third_party/acados/acados_template/c_templates_tera/CMakeLists.in.txt Conditionally builds an example executable if BUILD_EXAMPLE is enabled. The executable is linked with model, OCP, and simulation object files, depending on the integrator type. ```cmake if(${BUILD_EXAMPLE}) add_executable(${EX_EXE} ${EX_SRC} $ $ {%- if solver_options.integrator_type != "DISCRETE" %} $ {%- endif -%} ) install(TARGETS ${EX_EXE} DESTINATION ${CMAKE_INSTALL_PREFIX}) endif(${BUILD_EXAMPLE}) ``` -------------------------------- ### Install Docs Dependencies with uv Source: https://github.com/sunnypilot/sunnypilot/blob/master/docs/README.md Installs the necessary Python dependencies for the documentation site, including mkdocs and its plugins, using the uv package manager. This command should be run in the root directory of the openpilot project. ```bash uv pip install .[docs] ``` -------------------------------- ### Build Simulation Example Executable Source: https://github.com/sunnypilot/sunnypilot/blob/master/third_party/acados/acados_template/c_templates_tera/CMakeLists.in.txt Conditionally builds a simulation example executable if BUILD_SIM_EXAMPLE is enabled. This is only done when the integrator type is not DISCRETE. ```cmake if(${BUILD_SIM_EXAMPLE}) set(EX_SIM_SRC main_sim_{{ model.name }}.c) set(EX_SIM_EXE main_sim_{{ model.name }}) add_executable(${EX_SIM_EXE} ${EX_SIM_SRC} $ $) install(TARGETS ${EX_SIM_EXE} DESTINATION ${CMAKE_INSTALL_PREFIX}) endif(${BUILD_SIM_EXAMPLE}) ``` -------------------------------- ### Launch sunnypilot with Webcam Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/webcam/README.md Starts the sunnypilot manager process with webcam support enabled. This command assumes the environment is correctly configured and hardware is connected. ```bash USE_WEBCAM=1 system/manager/manager.py ``` -------------------------------- ### Install PlotJuggler and openpilot Plugins Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/plotjuggler/README.md This command downloads and installs PlotJuggler along with custom plugins for parsing openpilot logs. Ensure you have the openpilot environment set up before running. ```bash cd tools/plotjuggler && ./juggle.py --install ``` -------------------------------- ### Run Openpilot Camera Services Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/camerastream/README.md Starts the necessary services (bridge, encorderd, camerad) on the openpilot device to enable camera streaming. These services handle message bridging, video encoding, and camera data acquisition. Ensure both the device and PC are on the same openpilot commit. ```bash ( cd /data/openpilot/cereal/messaging/ ./bridge & cd /data/openpilot/system/camerad/ ./camerad & cd /data/openpilot/system/loggerd/ ./encoderd & wait ) ; trap 'kill $(jobs -p)' SIGINT ``` -------------------------------- ### Run Openpilot UI with Demo Route Source: https://github.com/sunnypilot/sunnypilot/blob/master/docs/how-to/turn-the-speed-blue.md Launches the openpilot UI in one terminal and starts replaying a demo route in another. This is used for testing UI modifications without live driving data. ```bash # in terminal 1 tools/replay/replay --demo # in terminal 2 ./selfdrive/ui/ui.py ``` -------------------------------- ### Install Forked Openpilot on Comma Device Source: https://github.com/sunnypilot/sunnypilot/blob/master/docs/how-to/turn-the-speed-blue.md Instructions to uninstall the current openpilot version on a comma device and then reinstall it using a custom GitHub fork. This allows testing your modified version in a real car. ```bash installer.comma.ai//master ``` -------------------------------- ### Parameters System - Python Source: https://context7.com/sunnypilot/sunnypilot/llms.txt Provides persistent key-value storage for configuration, vehicle parameters, and runtime state. Supports string, boolean, and byte parameters with lifecycle flags (e.g., cleared on boot). Includes methods for getting, putting, removing, and clearing parameters, as well as command-line utility for debugging. ```python from openpilot.common.params import Params, ParamKeyFlag # Initialize params instance params = Params() # Get and set string parameters car_params_bytes = params.get("CarParams", block=True) # Block until available params.put("GitBranch", "master") # Boolean parameters is_metric = params.get_bool("IsMetric") params.put_bool("IsLdwEnabled", True) # Check if a key exists if params.get("DongleId") is not None: dongle_id = params.get("DongleId").decode('utf-8') # Remove a parameter params.remove("ExperimentalMode") # Clear parameters by flag params.clear_all(ParamKeyFlag.CLEAR_ON_MANAGER_START) params.clear_all(ParamKeyFlag.CLEAR_ON_ONROAD_TRANSITION) # Get default value for a parameter default_value = params.get_default_value("LongitudinalPersonality") if params.get("LongitudinalPersonality") is None and default_value is not None: params.put("LongitudinalPersonality", default_value) # Command-line usage for debugging # python -m openpilot.common.params GitBranch # GET # python -m openpilot.common.params GitBranch master # SET ``` -------------------------------- ### Implement Longitudinal Control Loop Source: https://context7.com/sunnypilot/sunnypilot/llms.txt Shows the initialization and update cycle of the longitudinal controller. It manages acceleration targets and state transitions for stopping, starting, and cruising. ```python long_control = LongControl(CP, CP_SP) def update_longitudinal(active, CS, long_plan): output_accel = long_control.update( active=active, CS=CS, a_target=long_plan.aTarget, should_stop=long_plan.shouldStop, accel_limits=CI.get_pid_accel_limits(CP, CP_SP, CS.vEgo, CS.vCruise) ) return output_accel ``` -------------------------------- ### CMake Build Configuration (CMake) Source: https://github.com/sunnypilot/sunnypilot/blob/master/third_party/acados/acados_template/c_templates_tera/CMakeLists.in.txt This snippet configures the CMake build system for the project. It sets the minimum CMake version, project name, and defines options for building solver libraries, OCP solvers, and examples. It also handles platform-specific library suffix adjustments. ```cmake cmake_minimum_required(VERSION 3.13) project({{ model.name }}) # build options. option(BUILD_ACADOS_SOLVER_LIB "Should the solver library acados_solver_{{ model.name }} be build?" OFF) option(BUILD_ACADOS_OCP_SOLVER_LIB "Should the OCP solver library acados_ocp_solver_{{ model.name }} be build?" OFF) option(BUILD_EXAMPLE "Should the example main_{{ model.name }} be build?" OFF) {%- if solver_options.integrator_type != "DISCRETE" %} option(BUILD_SIM_EXAMPLE "Should the simulation example main_sim_{{ model.name }} be build?" OFF) option(BUILD_ACADOS_SIM_SOLVER_LIB "Should the simulation solver library acados_sim_solver_{{ model.name }} be build?" OFF) {%- endif %} if(CMAKE_CXX_COMPILER_ID MATCHES "GNU" AND CMAKE_SYSTEM_NAME MATCHES "Windows") # MinGW, change to .lib such that mex recognizes it set(CMAKE_SHARED_LIBRARY_SUFFIX ".lib") set(CMAKE_SHARED_LIBRARY_PREFIX "") endif() # object target names set(MODEL_OBJ model_{{ model.name }}) set(OCP_OBJ ocp_{{ model.name }}) set(SIM_OBJ sim_{{ model.name }}) ``` -------------------------------- ### Analyze Subaru Steering Faults with Jupyter Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/car_porting/README.md A Jupyter notebook example demonstrating how to search a segment database for specific conditions and plot the results, using a Subaru steering temperature fault as a case study. ```python # This is a conceptual representation as the actual notebook code is not provided. # The notebook would contain Python code for data querying and plotting. # Example: Plotting steer_warning vs steering angle. ``` -------------------------------- ### Read and Replay Driving Logs Source: https://context7.com/sunnypilot/sunnypilot/llms.txt Provides methods for loading route logs, iterating through messages, filtering by type, and saving processed data. Includes examples for command-line replay tools. ```python from openpilot.tools.lib.logreader import LogReader, save_log from openpilot.tools.lib.route import Route route = Route("a]b]c|2024-01-15--12-30-00") lr = LogReader(route.log_paths()[0]) for msg in lr: if msg.which() == 'carState': print(f"Speed: {msg.carState.vEgo}") filtered_msgs = [msg for msg in lr if msg.which() == 'carState'] save_log('/tmp/filtered.bz2', filtered_msgs, compress=True) ``` -------------------------------- ### Plot Actuator Response with Jupyter Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/car_porting/README.md A Jupyter notebook example showing how to plot the response of a car actuator when it is active, illustrated with a plot of brake pressure versus acceleration for Subaru vehicles. ```python # This is a conceptual representation as the actual notebook code is not provided. # The notebook would contain Python code for data querying and plotting. # Example: Plotting brake_pressure vs acceleration. ``` -------------------------------- ### Display Camera Stream with watch3.py Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/camerastream/README.md A Python script used to display the decoded video stream on the PC. It works in conjunction with compressed_vipc.py to visualize the camera feed from the openpilot device. Run this in a separate terminal after starting the stream decoding. ```python cd ~/openpilot/selfdrive/ui/ && ./watch3.py ``` -------------------------------- ### Stream Live Data with PlotJuggler Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/plotjuggler/README.md This command enables PlotJuggler to stream live data from a comma device or a PC replay. It requires enabling wifi tethering on the device and running a bridge script, or starting a cereal subscriber on the PC. ```bash ZMQ=1 ./juggle.py --stream ``` ```bash ./juggle.py --stream ``` -------------------------------- ### Athena JSON-RPC Methods for Remote Control (Python) Source: https://context7.com/sunnypilot/sunnypilot/llms.txt Implements JSON-RPC methods for Athena, a remote access daemon for the comma device. It allows for remote SSH, file uploads, and vehicle monitoring. Key functions include getting messages from services, listing data directories, queuing file uploads, and setting navigation destinations. Dependencies include openpilot's athenad, jsonrpc, and cereal.messaging. ```python from openpilot.system.athena.athenad import ( UploadFile, UploadItem, upload_queue, recv_queue, send_queue ) from jsonrpc import dispatcher import cereal.messaging as messaging import time import uuid from openpilot.common.params import Params import json # Athena exposes JSON-RPC methods for remote control @dispatcher.add_method def getMessage(service: str): """Get latest message from a service""" # Returns serialized message pass @dispatcher.add_method def listDataDirectory(): """List files in data directory""" # Returns list of route directories pass @dispatcher.add_method def uploadFileToUrl(fn: str, url: str, headers: dict): """Queue a file for upload""" upload_item = UploadItem( path=fn, url=url, headers=headers, created_at=int(time.time()), id=str(uuid.uuid4()), allow_cellular=False ) upload_queue.put(upload_item) return {'success': True} @dispatcher.add_method def setNavDestination(latitude: float, longitude: float, place_name: str = ""): """Set navigation destination""" params = Params() dest = { 'latitude': latitude, 'longitude': longitude, 'place_name': place_name } params.put("NavDestination", json.dumps(dest)) return {'success': True} # WebSocket connection to comma servers # ATHENA_HOST = 'wss://athena.comma.ai' # Connection is authenticated via device dongle ID ``` -------------------------------- ### Serve MkDocs Site Locally Source: https://github.com/sunnypilot/sunnypilot/blob/master/docs/README.md Runs a local development server to preview the documentation site. This allows for live reloading as changes are made. The command must be executed in the root directory of the openpilot project. ```bash mkdocs serve ``` -------------------------------- ### Initialize Vehicle Interface and Access Car Parameters Source: https://context7.com/sunnypilot/sunnypilot/llms.txt Demonstrates how to initialize the car interface using a fingerprint and access essential vehicle capabilities, tuning parameters, and real-time sensor data from the CarState. ```python CI = interfaces[CP.carFingerprint](CP) print(f"Brand: {CP.brand}") print(f"Car Model: {CP.carFingerprint}") CS = sm['carState'] print(f"Speed: {CS.vEgo} m/s") pid_accel_limits = CI.get_pid_accel_limits(CP, CS.vEgo, CS.vCruise) ``` -------------------------------- ### Initialize and Read Route Logs with LogReader (Python) Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/lib/README.md Demonstrates how to initialize a Route object, retrieve log paths, and use LogReader to iterate through messages in rlog and qlog files. It also shows how to extract specific data like steering angles. ```python from openpilot.tools.lib.route import Route from openpilot.tools.lib.logreader import LogReader r = Route("a2a0ccea32023010|2023-07-27--13-01-19") # get a list of paths for the route's rlog files print(r.log_paths()) # and road camera (fcamera.hevc) files print(r.camera_paths()) # setup a LogReader to read the route's first rlog lr = LogReader(r.log_paths()[0]) # print out all the messages in the log import codecs codecs.register_error("strict", codecs.backslashreplace_errors) for msg in lr: print(msg) # setup a LogReader for the route's second qlog lr = LogReader(r.log_paths()[1]) # print all the steering angles values from the log for msg in lr: if msg.which() == "carState": print(msg.carState.steeringAngleDeg) ``` -------------------------------- ### Build MkDocs Site Source: https://github.com/sunnypilot/sunnypilot/blob/master/docs/README.md Builds the static HTML files for the documentation site. This command generates the final output that can be deployed or served locally. It should be executed from the root directory of the openpilot project. ```bash mkdocs build ``` -------------------------------- ### Running Cabana with CLI Options Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/cabana/README.md Various command-line interface commands to launch Cabana with different configurations, such as demo mode, specific routes, or camera settings. ```bash cabana --demo cabana "5beb9b58bd12b691/0000010a--a51155e496" cabana "5beb9b58bd12b691/0000010a--a51155e496" --dcam --ecam cabana ``` -------------------------------- ### Identify Ford Vehicle Model from VIN Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/car_porting/examples/ford_vin_fingerprint.ipynb Parses a VIN string to identify the specific Ford vehicle platform. It checks the start of the VIN and specific character positions to distinguish between models like the F-150, Lightning, and Mustang Mach-E. ```python MODEL_YEAR_CODES = {'M': 2021, 'N': 2022, 'P': 2023, 'R': 2024, 'S': 2025} F150_CODES = ['F1C', 'F1E', 'W1C', 'W1E', 'X1C', 'X1E', 'W1R', 'W1P', 'W1S', 'W1T'] LIGHTNING_CODES = ['L', 'V'] MACHE_CODES = ['K1R', 'K1S', 'K2S', 'K3R', 'K3S', 'K4S'] FORD_VIN_START = ['1FT', '3FM', '5LM'] def ford_vin_fingerprint(vin): vin_positions_567 = vin[4:7] if vin.startswith('1FT'): if vin_positions_567 in F150_CODES: if vin[7] in LIGHTNING_CODES: return f"FORD F-150 LIGHTNING 1ST GEN" else: return f"FORD F-150 14TH GEN" elif vin.startswith('3FM'): if vin_positions_567 in MACHE_CODES: return f"FORD MUSTANG MACH-E 1ST GEN" elif vin.startswith('5LM'): pass return "mock" ``` -------------------------------- ### Activate Python Virtual Environment and Compile Openpilot Source: https://github.com/sunnypilot/sunnypilot/blob/master/docs/how-to/turn-the-speed-blue.md Navigates to the openpilot directory, activates the Python virtual environment, and then compiles the openpilot project using scons. This prepares the codebase for running. ```bash cd openpilot source .venv/bin/activate scons -j$(nproc) ``` -------------------------------- ### Initialize and Synchronize UI Diff Videos Source: https://github.com/sunnypilot/sunnypilot/blob/master/selfdrive/ui/tests/diff/diff_template.html This script dynamically injects video elements into a table and attaches event listeners to ensure playback synchronization. It calculates the minimum current time across all videos to align them and handles looping when all videos finish. ```javascript const videoDefs = [{ id: 'video1', title: 'Video 1', src: '$VIDEO1_SRC', sync: true }, { id: 'video2', title: 'Video 2', src: '$VIDEO2_SRC', sync: true }, { id: 'diffVideo', title: 'Pixel Diff', src: '$DIFF_SRC', sync: false }]; const row = document.getElementById('videoTable').insertRow(); videoDefs.forEach(({ id, title, src, sync }) => { const td = row.insertCell(); td.width = '33%'; td.innerHTML = `

${title}

`; }); const videos = videoDefs.map(({ id }) => document.getElementById(id)); const isEnded = (v) => v.ended || (Number.isFinite(v.duration) && v.currentTime >= (v.duration - 0.05)); const playAll = () => videos.forEach((v) => v.play()); function syncVideos() { const t = Math.min(...videos.map((v) => v.currentTime)); videos.forEach((v) => { v.currentTime = t; }); playAll(); } function handleEnded(endedVideo) { endedVideo.pause(); if (videos.every(isEnded)) { videos.forEach((v) => { v.currentTime = 0; }); playAll(); } } videos.forEach((v) => { v.addEventListener('timeupdate', () => { videos.forEach((other) => { if (other !== v && !isEnded(other) && Math.abs(v.currentTime - other.currentTime) > 0.1) { other.currentTime = v.currentTime; if (other.paused) other.play(); } }); }); v.addEventListener('ended', () => handleEnded(v)); }); ``` -------------------------------- ### Initialize Log Reader for CAN Search Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/car_porting/examples/find_segments_with_message.ipynb Sets up the environment for searching CAN ignition messages across specific vehicle buses, utilizing tqdm for progress tracking. ```python from openpilot.tools.lib.logreader import LogReader, comma_car_segments_source from tqdm.notebook import tqdm, tnrange BUSES_TO_SEARCH = [0, 1, 2] ``` -------------------------------- ### Select Model Source Files (Casadi) Source: https://github.com/sunnypilot/sunnypilot/blob/master/third_party/acados/acados_template/c_templates_tera/CMakeLists.in.txt Dynamically selects C source files for model integration based on the CasADi solver type (ERK, IRK, LIFTED_IRK, GNSF, DISCRETE) and Hessian approximation. It includes specific files for ODE functions, VDE functions, Jacobian calculations, and Hessian computations as needed. If a generic source is specified, it uses that instead. ```cmake set(MODEL_SRC {%- if model.dyn_ext_fun_type == "casadi" %} {%- if solver_options.integrator_type == "ERK" %} {{ model.name }}_model/{{ model.name }}_expl_ode_fun.c {{ model.name }}_model/{{ model.name }}_expl_vde_forw.c {{ model.name }}_model/{{ model.name }}_expl_vde_adj.c {%- if hessian_approx == "EXACT" %} {{ model.name }}_model/{{ model.name }}_expl_ode_hess.c {%- endif %} {%- elif solver_options.integrator_type == "IRK" %} {{ model.name }}_model/{{ model.name }}_impl_dae_fun.c {{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_z.c {{ model.name }}_model/{{ model.name }}_impl_dae_jac_x_xdot_u_z.c {%- if hessian_approx == "EXACT" %} {{ model.name }}_model/{{ model.name }}_impl_dae_hess.c {%- endif %} {%- elif solver_options.integrator_type == "LIFTED_IRK" %} {{ model.name }}_model/{{ model.name }}_impl_dae_fun.c {{ model.name }}_model/{{ model.name }}_impl_dae_fun_jac_x_xdot_u.c {%- if hessian_approx == "EXACT" %} {{ model.name }}_model/{{ model.name }}_impl_dae_hess.c {%- endif %} {%- elif solver_options.integrator_type == "GNSF" %} {% if model.gnsf.purely_linear != 1 %} {{ model.name }}_model/{{ model.name }}_gnsf_phi_fun.c {{ model.name }}_model/{{ model.name }}_gnsf_phi_fun_jac_y.c {{ model.name }}_model/{{ model.name }}_gnsf_phi_jac_y_uhat.c {% if model.gnsf.nontrivial_f_LO == 1 %} {{ model.name }}_model/{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz.c {%- endif %} {%- endif %} {{ model.name }}_model/{{ model.name }}_gnsf_get_matrices_fun.c {%- elif solver_options.integrator_type == "DISCRETE" %} {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun.c {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac.c {%- if hessian_approx == "EXACT" %} {{ model.name }}_model/{{ model.name }}_dyn_disc_phi_fun_jac_hess.c {%- endif %} {%- endif -%} {%- else %} {{ model.name }}_model/{{ model.dyn_generic_source }} {%- endif %} ) add_library(${MODEL_OBJ} OBJECT ${MODEL_SRC} ) ``` -------------------------------- ### Initialize and Manage MADS in Python Source: https://context7.com/sunnypilot/sunnypilot/llms.txt Initializes the Modular Assistive Driving System (MADS) and integrates it into the main driving loop. It allows MADS to handle its own event processing and checks its enabled state to control lateral activation. The code also includes examples of configuring MADS parameters using the Params system. ```python from openpilot.sunnypilot.mads.mads import ModularAssistiveDrivingSystem from openpilot.sunnypilot.mads.state import StateMachine from cereal import custom State = custom.ModularAssistiveDrivingSystem.ModularAssistiveDrivingSystemState # States: disabled, enabled, paused class SelfdriveD: def __init__(self): # Initialize MADS self.mads = ModularAssistiveDrivingSystem(self) def update(self, CS): # MADS handles its own event processing self.mads.update(CS) # Check MADS state if self.mads.enabled: # Lateral control is active lat_active = True else: lat_active = False # MADS can be in 'paused' state (steering temporarily disabled) if self.mads.state_machine.state == State.paused: # Handle paused state - e.g., brake pressed pass # MADS Configuration via Params from openpilot.common.params import Params params = Params() # Enable/disable MADS feature params.put_bool("Mads", True) # Allow MADS activation via cruise main button params.put_bool("MadsMainCruiseAllowed", True) # Unified Engagement Mode - single button controls both systems params.put_bool("MadsUnifiedEngagementMode", False) # Steering behavior when brake is pressed: ``` -------------------------------- ### Cereal Messaging: Subscribe to Sensor Events (Python) Source: https://github.com/sunnypilot/sunnypilot/blob/master/cereal/README.md Demonstrates how to subscribe to 'sensorEvents' using the cereal messaging library. It initializes a SubMaster, continuously updates, and prints received sensor event data. ```python import cereal.messaging as messaging # in subscriber sm = messaging.SubMaster(['sensorEvents']) while 1: sm.update() print(sm['sensorEvents']) ``` -------------------------------- ### Streaming CAN Data from comma Device Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/cabana/README.md Instructions for setting up a bridge on a comma device via SSH and connecting Cabana to stream live CAN messages over ZMQ. ```bash cd /data/openpilot/cereal/messaging/ ./bridge & cabana --zmq ``` -------------------------------- ### Multi-Camera Replay with watch3 Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/replay/README.md Simultaneously replays driver and wide road camera feeds for visualization using the watch3 utility. ```bash cd tools/replay && ./replay --demo --dcam --ecam cd selfdrive/ui && ./watch3.py ``` -------------------------------- ### Replay Processes with Custom Parameters Source: https://github.com/sunnypilot/sunnypilot/blob/master/selfdrive/test/process_replay/README.md Inject custom parameters into a process replay to simulate state persistence across segments. Useful for processes like calibrationd that rely on previous segment data. ```python from openpilot.selfdrive.test.process_replay import replay_process_with_name, get_custom_params_from_lr custom_params = get_custom_params_from_lr(previous_segment_lr, 'last') output_logs = replay_process_with_name('calibrationd', lr, custom_params=custom_params) ``` -------------------------------- ### Configure Replay Messaging and Visualization Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/replay/README.md Configures replay to use ZMQ for messaging or integrates with external tools like the openpilot UI and PlotJuggler. ```bash ZMQ=1 tools/replay/replay # UI Visualization tools/replay/replay cd selfdrive/ui && ./ui.py # PlotJuggler Streaming tools/replay/replay tools/plotjuggler/juggle.py --stream ``` -------------------------------- ### Include Directories Configuration Source: https://github.com/sunnypilot/sunnypilot/blob/master/third_party/acados/acados_template/c_templates_tera/CMakeLists.in.txt Specifies include directories for the project, including paths for ACADOS, its submodules (acados, blasfeo, hpipm), and conditionally for QP solver headers based on the selected solver. ```cmake include_directories( ${ACADOS_INCLUDE_PATH} ${ACADOS_INCLUDE_PATH}/acados ${ACADOS_INCLUDE_PATH}/blasfeo/include ${ACADOS_INCLUDE_PATH}/hpipm/include {%- if qp_solver == \"FULL_CONDENSING_QPOASES\" %} ${ACADOS_INCLUDE_PATH}/qpOASES_e/ {%- endif %} {%- if qp_solver == \"FULL_CONDENSING_DAQP\" %} ${ACADOS_INCLUDE_PATH}/daqp/include {%- endif %} ) ``` -------------------------------- ### Initialize Subaru Car Data Structures (Python) Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/car_porting/examples/subaru_fuzzy_fingerprint.ipynb Initializes data structures for Subaru car parameters, including platform identification, ECU firmware versions, and mapping them to car models. It filters out pre-global platforms and organizes firmware data by ECU. ```python from opendbc.car import structs from opendbc.car.subaru.values import CAR, SubaruFlags from opendbc.car.subaru.fingerprints import FW_VERSIONS TEST_PLATFORMS = set(CAR) - CAR.with_flags(SubaruFlags.PREGLOBAL) Ecu = structs.CarParams.Ecu FW_BY_ECU = {platform: {ecu: versions for (ecu, addr, sub_addr), versions in fw_versions.items()} for platform, fw_versions in FW_VERSIONS.items()} ``` -------------------------------- ### Cereal Messaging: Publish Sensor Events (Python) Source: https://github.com/sunnypilot/sunnypilot/blob/master/cereal/README.md Illustrates how to publish 'sensorEvents' using the cereal messaging library. It initializes a PubMaster, creates a new message, populates it with gyro data, and sends it. ```python # in publisher pm = messaging.PubMaster(['sensorEvents']) dat = messaging.new_message('sensorEvents', size=1) dat.sensorEvents[0] = {"gyro": {"v": [0.1, -0.1, 0.1]}} pm.send('sensorEvents', dat) ``` -------------------------------- ### Configure Smart Cruise Control Source: https://context7.com/sunnypilot/sunnypilot/llms.txt Demonstrates initializing the Smart Cruise Control module, updating speed limits based on map and vision data, and configuring parameters via the Params interface. ```python from openpilot.sunnypilot.selfdrive.controls.lib.smart_cruise_control.smart_cruise_control import SmartCruiseControl import cereal.messaging as messaging from openpilot.common.params import Params scc = SmartCruiseControl() params = Params() def update_speed_limit(sm, long_enabled, v_ego, v_cruise): scc.update(sm=sm, long_enabled=long_enabled, long_override=False, v_ego=v_ego, a_ego=sm['carState'].aEgo, v_cruise=v_cruise) return min(v_cruise, scc.map.speed_limit, scc.vision.get_speed_limit()) params.put_bool("SpeedLimitControl", True) params.put("SpeedLimitOffset", "5") ``` -------------------------------- ### Replay VisionIPC Processes Source: https://github.com/sunnypilot/sunnypilot/blob/master/selfdrive/test/process_replay/README.md Configure and replay processes that require camera input by providing a dictionary of FrameReader objects. ```python from openpilot.tools.lib.framereader import FrameReader frs = { 'roadCameraState': FrameReader('path/to/road_camera'), 'driverCameraState': FrameReader('path/to/driver_camera') } output_logs = replay_process_with_name(['modeld'], lr, frs=frs) ``` -------------------------------- ### Sample Segments from Database Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/car_porting/examples/find_segments_with_message.ipynb Iterates through available platforms to randomly sample a defined number of segments per platform, merging them with any manually defined extra segments. ```python import random from openpilot.tools.lib.comma_car_segments import get_comma_car_segments_database MAX_SEGS_PER_PLATFORM = 3 database = get_comma_car_segments_database() TEST_SEGMENTS = [] for platform in TEST_PLATFORMS: if platform in database: all_segments = database[platform] NUM_SEGMENTS = min(len(all_segments), MAX_SEGS_PER_PLATFORM) TEST_SEGMENTS.extend(random.sample(all_segments, NUM_SEGMENTS)) TEST_SEGMENTS.extend(EXTRA_SEGMENTS) ``` -------------------------------- ### Messaging System (Cereal) - Python Source: https://context7.com/sunnypilot/sunnypilot/llms.txt Implements high-performance inter-process communication using Cap'n Proto and ZeroMQ/MSGQ. Enables publish-subscribe patterns for data sharing between Sunnypilot processes, including frequency monitoring and validity checks. Supports both high-level SubMaster/PubMaster and low-level socket access. ```python import cereal.messaging as messaging from cereal import car, log # Create a SubMaster to subscribe to multiple services # The poll parameter specifies which service to block on sm = messaging.SubMaster(['carState', 'modelV2', 'controlsState'], poll='carState', ignore_alive=['modelV2']) # Create a PubMaster to publish messages pm = messaging.PubMaster(['carControl', 'controlsState']) # Main loop pattern while True: # Update all subscriptions, blocking on the polled service sm.update(timeout=100) # 100ms timeout # Check if specific service was updated this cycle if sm.updated['carState']: car_state = sm['carState'] v_ego = car_state.vEgo # Vehicle speed in m/s steering_angle = car_state.steeringAngleDeg # Check all services are alive and valid if sm.all_alive() and sm.all_valid(): # Create and send a new message msg = messaging.new_message('carControl') msg.carControl.enabled = True msg.carControl.actuators.steer = 0.5 msg.carControl.actuators.accel = 1.0 pm.send('carControl', msg) # Low-level socket access for simple use cases pub = messaging.pub_sock('myService') sub = messaging.sub_sock('carState', conflate=True, timeout=100) # Receive single message with automatic deserialization msg = messaging.recv_one(sub) if msg is not None: print(f"Vehicle speed: {msg.carState.vEgo}") ``` -------------------------------- ### Configure Solver Options (Jinja2) Source: https://github.com/sunnypilot/sunnypilot/blob/master/third_party/acados/acados_template/c_templates_tera/CMakeLists.in.txt This snippet configures solver options like QP solver, Hessian approximation, and constraint types using Jinja2 templating. It sets default values if specific options are not provided, ensuring a robust configuration. ```jinja2 {%- if solver_options.qp_solver %} {%- set qp_solver = solver_options.qp_solver %} {%- else %} {%- set qp_solver = "FULL_CONDENSING_HPIPM" %} {%- endif %} {%- if solver_options.hessian_approx %} {%- set hessian_approx = solver_options.hessian_approx %} {%- elif solver_options.sens_hess %} {%- set hessian_approx = "EXACT" %} {%- else %} {%- set hessian_approx = "GAUSS_NEWTON" %} {%- endif %} {%- if constraints.constr_type %} {%- set constr_type = constraints.constr_type %} {%- else %} {%- set constr_type = "NONE" %} {%- endif %} {%- if constraints.constr_type_e %} {%- set constr_type_e = constraints.constr_type_e %} {%- else %} {%- set constr_type_e = "NONE" %} {%- endif %} {%- if cost.cost_type %} {%- set cost_type = cost.cost_type %} {%- else %} {%- set cost_type = "NONE" %} {%- endif %} {%- if cost.cost_type_e %} {%- set cost_type_e = cost.cost_type_e %} {%- else %} {%- set cost_type_e = "NONE" %} {%- endif %} {%- if cost.cost_type_0 %} {%- set cost_type_0 = cost.cost_type_0 %} {%- else %} {%- set cost_type_0 = "NONE" %} {%- endif %} {%- if dims.nh %} {%- set dims_nh = dims.nh %} {%- else %} {%- set dims_nh = 0 %} {%- endif %} {%- if dims.nphi %} {%- set dims_nphi = dims.nphi %} {%- else %} {%- set dims_nphi = 0 %} {%- endif %} {%- if dims.nh_e %} {%- set dims_nh_e = dims.nh_e %} {%- else %} {%- set dims_nh_e = 0 %} {%- endif %} {%- if dims.nphi_e %} {%- set dims_nphi_e = dims.nphi_e %} {%- else %} {%- set dims_nphi_e = 0 %} {%- endif %} {%- if solver_options.model_external_shared_lib_dir %} {%- set model_external_shared_lib_dir = solver_options.model_external_shared_lib_dir %} {%- endif %} {%- if solver_options.model_external_shared_lib_name %} {%- set model_external_shared_lib_name = solver_options.model_external_shared_lib_name %} {%- endif %} {#- control operator #} {%- if os and os == "pc" %} {%- set control = "&" %} {%- else %} {%- set control = ";" %} {%- endif %} {%- if acados_link_libs and os and os == "pc" %}{# acados linking libraries and flags #} {%- set link_libs = acados_link_libs.qpoases ~ " " ~ acados_link_libs.hpmpc ~ " " ~ acados_link_libs.osqp -%} {%- set openmp_flag = acados_link_libs.openmp %} {%- else %} {%- set openmp_flag = " " %} {%- if qp_solver == "FULL_CONDENSING_QPOASES" %} {%- set link_libs = "-lqpOASES_e" %} {%- elif qp_solver == "FULL_CONDENSING_DAQP" %} {%- set link_libs = "-ldaqp" %} {%- else %} {%- set link_libs = "" %} {%- endif %} {%- endif %} ``` -------------------------------- ### Replay Driving Routes Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/replay/README.md Commands to initiate a replay of driving routes. Supports remote routes, local data directories, and demo modes. ```bash tools/replay/replay tools/replay/replay --demo tools/replay/replay --data_dir="/path_to/route" ``` -------------------------------- ### Run Process Replay via CLI Source: https://github.com/sunnypilot/sunnypilot/blob/master/selfdrive/test/process_replay/README.md Execute the regression test suite locally using the command line interface. Supports filtering processes and cars, as well as updating reference logs. ```bash DISABLE_FILEREADER_CACHE='1' ./test_processes.py --whitelist-procs controlsd --update-refs ``` -------------------------------- ### Connect to comma device via proxy Source: https://github.com/sunnypilot/sunnypilot/blob/master/docs/how-to/connect-to-comma.md A one-off command to establish an SSH connection to a specific comma device using the dongle ID and the ssh.comma.ai proxy. ```bash ssh -i ~/.ssh/my_github_key -o ProxyCommand="ssh -i ~/.ssh/my_github_key -W %h:%p -p %p %h@ssh.comma.ai" comma@ffffffffffffffff ``` -------------------------------- ### Streaming CAN Data from Panda Hardware Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/cabana/README.md Command to initialize Cabana to read raw CAN messages directly from a connected Panda hardware device. ```bash cabana --panda ``` -------------------------------- ### Push Fork to GitHub Source: https://github.com/sunnypilot/sunnypilot/blob/master/docs/how-to/turn-the-speed-blue.md Commands to remove the default origin, set a new origin to your personal GitHub fork, stage all changes, commit them with a message, and push to your master branch. ```bash git remote rm origin git remote add origin git@github.com:/openpilot.git git add . git commit -m "Make the speed display blue" git push --set-upstream origin master ``` -------------------------------- ### Specify LogReader Segments and Types (Python) Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/lib/README.md Illustrates how to use segment ranges and query types to selectively load logs using the LogReader. This allows for more granular access to specific parts or types of route data. ```python # lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/4") # 4th segment # lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/4:6") # 4th and 5th segment # lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/-1") # last segment # lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/:5") # first 5 segments # lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/1:") # all except first segment # lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/4/q") # get qlogs # lr = LogReader("a2a0ccea32023010|2023-07-27--13-01-19/4/r") # get rlogs (default) ``` -------------------------------- ### Manage System Processes Source: https://context7.com/sunnypilot/sunnypilot/llms.txt Orchestrates the lifecycle of sunnypilot processes including initialization, monitoring via SubMaster, and graceful shutdown. ```python from openpilot.system.manager.manager import manager_init, manager_cleanup from openpilot.system.manager.process_config import managed_processes from openpilot.system.manager.process import ensure_running import cereal.messaging as messaging manager_init() sm = messaging.SubMaster(['deviceState', 'carParams'], poll='deviceState') while True: sm.update(1000) ensure_running(managed_processes.values(), started=sm['deviceState'].started) if params.get_bool("DoShutdown"): break manager_cleanup() ``` -------------------------------- ### Car Interface - Python Source: https://context7.com/sunnypilot/sunnypilot/llms.txt Provides a unified API for interacting with different vehicle makes and models. Each vehicle implementation handles CAN message parsing, control command generation, and safety limit enforcement. This snippet shows loading car parameters from persistent storage. ```python from cereal import car import cereal.messaging as messaging from opendbc.car.car_helpers import interfaces from openpilot.common.params import Params # Load car parameters from persistent storage params = Params() CP = messaging.log_from_bytes(params.get("CarParams", block=True), car.CarParams) ``` -------------------------------- ### Automate FW Fingerprint Insertion Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/car_porting/README.md This Python script automatically inserts firmware (FW) fingerprints for a given car platform into the fingerprints.py file. It requires a route and the platform name as input. ```python python3 tools/car_porting/auto_fingerprint.py '1bbe6bf2d62f58a8|2022-07-14--17-11-43' 'OUTBACK' Attempting to add fw version for: OUTBACK ``` -------------------------------- ### SunnyPilot Service Definitions (Python) Source: https://context7.com/sunnypilot/sunnypilot/llms.txt Defines inter-process communication (IPC) channels for SunnyPilot, specifying frequency, logging behavior, and queue sizes for various services. This includes core openpilot services and SunnyPilot-specific extensions. The code iterates through the SERVICE_LIST to print properties of each defined service. ```python from cereal.services import SERVICE_LIST, Service # Service definition format # Service(should_log, frequency, decimation, queue_size) # Core services SERVICE_LIST['carState'] # 100 Hz - Vehicle sensor data SERVICE_LIST['carControl'] # 100 Hz - Control commands to vehicle SERVICE_LIST['controlsState'] # 100 Hz - Controller internal state SERVICE_LIST['modelV2'] # 20 Hz - Driving model output SERVICE_LIST['radarState'] # 20 Hz - Radar detections SERVICE_LIST['longitudinalPlan'] # 20 Hz - Speed planning SERVICE_LIST['liveCalibration'] # 4 Hz - Camera calibration SERVICE_LIST['deviceState'] # 2 Hz - Device health/thermal # Sunnypilot-specific services SERVICE_LIST['selfdriveStateSP'] # 100 Hz - SP state extensions SERVICE_LIST['longitudinalPlanSP'] # 20 Hz - SP long planning SERVICE_LIST['modelDataV2SP'] # 20 Hz - SP model data SERVICE_LIST['liveMapDataSP'] # 1 Hz - Map data for SCC # Check service properties for name, service in SERVICE_LIST.items(): print(f"{name}:") print(f" Frequency: {service.frequency} Hz") print(f" Should log: {service.should_log}") print(f" Decimation: {service.decimation}") print(f" Queue size: {service.queue_size}") ``` -------------------------------- ### Specify Webcam Indices Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/webcam/README.md Configures specific video device indices for the road camera using environment variables. This is useful when multiple cameras are connected to the host system. ```bash USE_WEBCAM=1 ROAD_CAM=1 system/manager/manager.py ``` -------------------------------- ### Authenticate with Comma Account Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/replay/README.md Authenticates the local environment with a comma account to enable access to remote driving routes. ```bash python3 tools/lib/auth.py ``` -------------------------------- ### Linker Directories Configuration Source: https://github.com/sunnypilot/sunnypilot/blob/master/third_party/acados/acados_template/c_templates_tera/CMakeLists.in.txt Sets the directories where the linker should search for libraries. ```cmake link_directories(${ACADOS_LIB_PATH}) ``` -------------------------------- ### Capture Process Output Source: https://github.com/sunnypilot/sunnypilot/blob/master/selfdrive/test/process_replay/README.md Capture the stdout and stderr of replayed processes by passing a dictionary to the captured_output_store parameter. ```python output_store = dict() output_logs = replay_process_with_name(['radard'], lr, captured_output_store=output_store) print(output_store['radard']['out']) ``` -------------------------------- ### Decode and Stream Camera Data with compressed_vipc.py Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/camerastream/README.md Decodes video streams from a remote openpilot device and republishes them over VisionIPC. This script requires the IP address of the device and can be configured to use NVIDIA for decoding and to specify which cameras to decode. It's a Python script that facilitates the camera stream. ```python cd ~/openpilot/tools/camerastream && ./compressed_vipc.py comma-ffffffff --cams 0 ``` ```python python3 compressed_vipc.py -h ``` -------------------------------- ### Stream CAN Messages via Panda Jungle Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/replay/README.md Replays recorded CAN messages to connected hardware devices using the can_replay.py utility. ```bash ./can_replay.py -h ``` -------------------------------- ### Cap'n Proto: Update log.capnp for Steering Info (Cap'n Proto) Source: https://github.com/sunnypilot/sunnypilot/blob/master/cereal/README.md Modifies the 'log.capnp' file to include 'steeringInfo' as a new field, replacing 'customReservedRawData0'. This change maps the custom 'SteeringInfo' struct to a specific event ID, ensuring proper serialization and deserialization. ```capnp rawCanData @124 :Data; customReservedRawData1 @125 :Data; customReservedRawData2 @126 :Data; # DO change the name of the field and struct # DON'T change the ID (e.g. @107) # DON'T change which struct it points to steeringInfo @107 :Custom.SteeringInfo; customReserved1 @108 :Custom.CustomReserved1; customReserved2 @109 :Custom.CustomReserved2; customReserved3 @110 :Custom.CustomReserved3; ``` -------------------------------- ### Retrieve Ford Vehicle Platforms from Database Source: https://github.com/sunnypilot/sunnypilot/blob/master/tools/car_porting/examples/ford_vin_fingerprint.ipynb This script initializes the comma car segments database and extracts all supported Ford vehicle platforms defined in opendbc. It serves as a utility to verify the availability of vehicle data for fingerprinting research. ```python from openpilot.tools.lib.logreader import LogReader, comma_car_segments_source from openpilot.tools.lib.comma_car_segments import get_comma_car_segments_database from opendbc.car.ford.values import CAR database = get_comma_car_segments_database() platforms = [c.value for c in CAR] print(f"Got {len(platforms)} Ford cars from opendbc") ``` -------------------------------- ### Configure SSH Proxy for comma devices Source: https://github.com/sunnypilot/sunnypilot/blob/master/docs/how-to/connect-to-comma.md This configuration allows users to connect to their comma device via the ssh.comma.ai proxy using a custom SSH host alias. It requires a valid SSH key and a comma prime subscription. ```ssh Host comma-* Port 22 User comma IdentityFile ~/.ssh/my_github_key ProxyCommand ssh %h@ssh.comma.ai -W %h:%p Host ssh.comma.ai Hostname ssh.comma.ai Port 22 IdentityFile ~/.ssh/my_github_key ```