Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs_espressif/en/debugproject.rst
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,16 @@ For example, to add ``-c "init"`` to the OpenOCD command, set ``idf.openOcdLaunc

In Visual Studio Code select menu **View** > **Output** > **ESP-IDF**. This output information is useful to know what is happening in the extension. For example, ``OpenOCD`` communication is displayed in this output.

Using a Custom OpenOCD Path
---------------------------
Comment thread
brianignacio5 marked this conversation as resolved.
By default the extension will use the OpenOCD installed in the ESP-IDF IDF_TOOLS_PATH directory. If you want to use a custom OpenOCD, you can set ``idf.customOpenOCDPath`` in your ``<project-directory>/.vscode/settings.json``. If this setting is empty or points to a path that does not exist, the extension will fallback to searching OpenOCD in ``PATH``.

.. code-block:: JSON

{
"idf.customOpenOCDPath": "/path/to/your/openocd"
}

Setting a Custom Application Image Offset
-----------------------------------------

Expand Down
2 changes: 2 additions & 0 deletions docs_espressif/en/settings.rst
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ Debug & OpenOCD
- Launch ESP-IDF Monitor when starting an ESP-IDF debug session (default: ``false``). Scope: Resource.
* - **idf.openOcdDebugLevel**
- OpenOCD debug level 0–4 (default: 2). 0 = error only, 4 = verbose. Ignored if **idf.openOcdLaunchArgs** is set. Scope: Resource.
* - **idf.customOpenOCDPath**
- Absolute path to a custom OpenOCD executable. If empty or the path does not exist, the extension falls back to searching OpenOCD in ``PATH``. Scope: Resource.
* - **idf.openOcdLaunchArgs**
- Custom arguments for OpenOCD. If set, **idf.openOcdConfigs** and **idf.openOcdDebugLevel** are ignored. Command form otherwise: ``openocd -d${idf.openOcdDebugLevel} -f ${idf.openOcdConfigs}``. Scope: Resource.
* - **idf.svdFilePath**
Expand Down
10 changes: 10 additions & 0 deletions docs_espressif/zh_CN/debugproject.rst
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,16 @@

此适配器是 VS Code、配置的工具链 GDB 以及 OpenOCD 服务器之间的中间桥梁。可参考以下链接,查看 `乐鑫芯片调试工作原理 <https://docs.espressif.com/projects/esp-idf/zh_CN/latest/esp32/api-guides/jtag-debugging/index.html#jtag-debugging-how-it-works>`_,以及 VS Code 如何使用 `调试适配器 <https://microsoft.github.io/debug-adapter-protocol/overview>`_ 与不同调试工具进行通信。

使用自定义 OpenOCD 路径
--------------------------------
默认情况下,扩展会使用安装在 ESP-IDF IDF_TOOLS_PATH 目录中的 OpenOCD。如果你希望使用自定义 OpenOCD,可在 ``<project-directory>/.vscode/settings.json`` 中设置 ``idf.customOpenOCDPath``。如果该设置为空,或指向不存在的路径,扩展会回退为在 ``PATH`` 中查找 OpenOCD。

.. code-block:: JSON

{
"idf.customOpenOCDPath": "/path/to/your/openocd"
}

自定义应用程序镜像偏移量
------------------------

Expand Down
2 changes: 2 additions & 0 deletions docs_espressif/zh_CN/settings.rst
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ Visual Studio Code 允许你在不同级别配置设置:**全局(用户设
- 启动 ESP-IDF 调试会话时同时启动 ESP-IDF 监视器(默认:``false``)。作用域:Resource。
* - **idf.openOcdDebugLevel**
- OpenOCD 调试级别 0–4(默认:2)。0 仅错误,4 为详细。设置 **idf.openOcdLaunchArgs** 时此项无效。作用域:Resource。
* - **idf.customOpenOCDPath**
- 自定义 OpenOCD 可执行文件的绝对路径。若为空或路径不存在,扩展会回退为在 ``PATH`` 中查找 OpenOCD。作用域:Resource。
* - **idf.openOcdLaunchArgs**
- OpenOCD 自定义参数。若已设置,则 **idf.openOcdConfigs** 与 **idf.openOcdDebugLevel** 被忽略。否则命令形式为:``openocd -d${idf.openOcdDebugLevel} -f ${idf.openOcdConfigs}``。作用域:Resource。
* - **idf.svdFilePath**
Expand Down
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -977,6 +977,12 @@
"scope": "resource",
"description": "%param.openOcdDebugLevel%"
},
"idf.customOpenOCDPath": {
"type": "string",
"default": "",
"description": "%param.customOpenOCDPath%",
"scope": "resource"
},
"idf.openOcdLaunchArgs": {
"type": "array",
"default": [],
Expand Down
1 change: 1 addition & 0 deletions package.nls.es.json
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@
"param.notificationMode.silent": "No mostrar notificaciones ni enfocar la salida de tareas.",
"param.openOcdConfigFilesList": "Lista de archivos de configuración dentro del directorio de scripts de OpenOCD",
"param.openOcdDebugLevel": "Nivel de depuración del servidor OpenOCD",
"param.customOpenOCDPath": "Ruta absoluta de un ejecutable OpenOCD personalizado. Si está vacía o no es válida, la extensión buscará OpenOCD en PATH",
"param.openOcdLaunchArgs": "Argumentos para iniciar OpenOCD desde esta extensión",
"param.partialDarkTheme": "Color de fondo para líneas parcialmente cubiertas en tema oscuro para Cobertura de ESP-IDF.",
"param.partialLightTheme": "Color de fondo para líneas parcialmente cubiertas en tema claro para Cobertura de ESP-IDF.",
Expand Down
1 change: 1 addition & 0 deletions package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@
"param.notificationMode.silent": "Show no notifications and do not focus on tasks output",
"param.openOcdConfigFilesList": "List of configuration files inside OpenOCD scripts directory",
"param.openOcdDebugLevel": "OpenOCD server debug level",
"param.customOpenOCDPath": "Absolute path to a custom OpenOCD executable. If empty or invalid, the extension searches for OpenOCD in PATH",
"param.openOcdLaunchArgs": "Arguments to launch openOCD from this extension",
"param.partialDarkTheme": "Background color for partially covered lines in dark theme for ESP-IDF coverage",
"param.partialLightTheme": "Background color for partially covered lines in light theme for ESP-IDF coverage",
Expand Down
1 change: 1 addition & 0 deletions package.nls.pt.json
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@
"param.notificationMode.silent": "Não mostre notificações e não concentre a saída das tarefas.",
"param.openOcdConfigFilesList": "Lista de arquivos de configuração dentro do diretório OpenOCD Scripts",
"param.openOcdDebugLevel": "Nível de depuração do servidor OpenOCD",
"param.customOpenOCDPath": "Caminho absoluto para um executável OpenOCD personalizado. Se estiver vazio ou inválido, a extensão procurará o OpenOCD no PATH",
"param.openOcdLaunchArgs": "Argumentos para lançar o openOCD a partir desta extensão",
"param.partialDarkTheme": "Cor de fundo para linhas parcialmente cobertas no tema Escuro para Cobertura ESP-IDF.",
"param.partialLightTheme": "Cor de fundo para linhas parcialmente cobertas no tema Light para cobertura ESP-IDF.",
Expand Down
1 change: 1 addition & 0 deletions package.nls.ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@
"param.notificationMode.silent": "Не показывать уведомления и не фокусировать вывод задач",
"param.openOcdConfigFilesList": "Список файлов конфигурации в каталоге скриптов OpenOCD",
"param.openOcdDebugLevel": "Уровень отладки сервера OpenOCD",
"param.customOpenOCDPath": "Абсолютный путь к пользовательскому исполняемому файлу OpenOCD. Если путь пустой или недействительный, расширение ищет OpenOCD в PATH",
"param.openOcdLaunchArgs": "Аргументы запуска openOCD из этого расширения",
"param.partialDarkTheme": "Цвет фона для частично покрытых линий в темной теме для покрытия ESP-IDF",
"param.partialLightTheme": "Цвет фона для частично покрытых линий в светлой теме для покрытия ESP-IDF",
Expand Down
1 change: 1 addition & 0 deletions package.nls.zh-cn.json
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@
"param.notificationMode.silent": "不显示通知和任务输出",
"param.openOcdConfigFilesList": "OpenOCD 脚本目录中的配置文件列表",
"param.openOcdDebugLevel": "OpenOCD 服务器调试级别",
"param.customOpenOCDPath": "自定义 OpenOCD 可执行文件的绝对路径。若为空或无效,扩展将从 PATH 中查找 OpenOCD",
"param.openOcdLaunchArgs": "从此扩展启动 OpenOCD 的参数",
"param.partialDarkTheme": "深色主题下 ESP-IDF 代码覆盖率报告中部分覆盖行的背景颜色",
"param.partialLightTheme": "浅色主题下 ESP-IDF 代码覆盖率报告中部分覆盖行的背景颜色",
Expand Down
8 changes: 5 additions & 3 deletions src/common/prepareEnv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { getIdfTargetFromSdkconfig } from "../workspaceConfig";
import { ESP } from "../config";
import { isBinInPath } from "../utils";
import { pathExists } from "fs-extra";
import { OpenOCDManager } from "../espIdf/openOcd/openOcdManager";

/**
* Configures and prepares environment variables necessary for executing ESP-IDF tasks.
Expand Down Expand Up @@ -99,9 +100,10 @@ export async function configureEnvVariables(
}

try {
const openOcdPath = await isBinInPath("openocd", modifiedEnv, [
"openocd-esp32",
]);
const openOcdPath = await OpenOCDManager.getOpenOcdPath(
curWorkspace,
modifiedEnv
);
if (openOcdPath) {
const openOcdDir = dirname(openOcdPath);
const openOcdScriptsPath = join(
Expand Down
8 changes: 5 additions & 3 deletions src/espIdf/hints/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { isBinInPath } from "../../utils";
import { readParameter } from "../../idfConfiguration";
import { configureEnvVariables } from "../../common/prepareEnv";
import { Uri } from "vscode";
import { OpenOCDManager } from "../openOcd/openOcdManager";

/**
* Gets the path to the OpenOCD hints YAML file for the specified version.
Expand All @@ -16,9 +17,10 @@ export async function getOpenOcdHintsYmlPath(
workspace: Uri
): Promise<string | null> {
const modifiedEnv = await configureEnvVariables(workspace);
const openOcdPath = await isBinInPath("openocd", modifiedEnv, [
"openocd-esp32",
]);
const openOcdPath = await OpenOCDManager.getOpenOcdPath(
workspace,
modifiedEnv
);
if (!openOcdPath) {
Logger.warn(
"Missing OpenOCD path for getting hints path.",
Expand Down
44 changes: 37 additions & 7 deletions src/espIdf/openOcd/openOcdManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,16 @@

import { ChildProcess, spawn } from "child_process";
import { EventEmitter } from "events";
import { accessSync, constants, lstatSync } from "fs";
import * as vscode from "vscode";
import * as idfConf from "../../idfConfiguration";
import { Logger } from "../../logger/logger";
import { OutputChannel } from "../../logger/outputChannel";
import { isBinInPath, PreCheck, spawn as sspawn } from "../../utils";
import {
isBinInPath,
PreCheck,
spawn as sspawn,
} from "../../utils";
import { TCLClient, TCLConnection } from "./tcl/tclClient";
import { ESP } from "../../config";
import {
Expand All @@ -45,6 +50,29 @@ export interface IOpenOCDConfig {
}

export class OpenOCDManager extends EventEmitter {
public static async getOpenOcdPath(
workspace: vscode.Uri,
modifiedEnv: { [Key: string]: string }
): Promise<string> {
const customOpenOcdPath = (idfConf.readParameter(
"idf.customOpenOCDPath",
workspace
) as string)?.trim();
if (customOpenOcdPath) {
try {
if (lstatSync(customOpenOcdPath).isFile()) {
accessSync(customOpenOcdPath, constants.X_OK);
return customOpenOcdPath;
}
} catch (_error) {
// Fall through to PATH lookup when the configured file is invalid.
}
}
const openOcdPath = await isBinInPath("openocd", modifiedEnv, [
"openocd-esp32",
]);
return openOcdPath;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
public static init(): OpenOCDManager {
if (!OpenOCDManager.instance) {
OpenOCDManager.instance = new OpenOCDManager();
Expand All @@ -65,9 +93,10 @@ export class OpenOCDManager extends EventEmitter {

public async version(silent: boolean = false): Promise<string> {
const modifiedEnv = await configureEnvVariables(this.workspace);
const openOcdPath = await isBinInPath("openocd", modifiedEnv, [
"openocd-esp32",
]);
const openOcdPath = await OpenOCDManager.getOpenOcdPath(
this.workspace,
modifiedEnv
);
if (!openOcdPath) {
return "";
}
Expand Down Expand Up @@ -165,9 +194,10 @@ export class OpenOCDManager extends EventEmitter {
return;
}
const modifiedEnv = await configureEnvVariables(this.workspace);
const openOcdPath = await isBinInPath("openocd", modifiedEnv, [
"openocd-esp32",
]);
const openOcdPath = await OpenOCDManager.getOpenOcdPath(
this.workspace,
modifiedEnv
);
if (!openOcdPath) {
throw new Error(
"Invalid OpenOCD bin path or access is denied for the user"
Expand Down
68 changes: 32 additions & 36 deletions src/espIdf/setTarget/DevkitsCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,47 +47,42 @@ export class DevkitsCommand {
throw new Error("No workspace folder found");
}

const modifiedEnv = await configureEnvVariables(this.workspaceFolderUri);
const openOcdPath = await isBinInPath("openocd", modifiedEnv, [
"openocd-esp32",
]);

if (!openOcdPath || !openOCDVersion) {
throw new Error("Could not get toolsPath or OpenOCD version");
if (!openOCDVersion) {
throw new Error("Could not get OpenOCD version");
}

const scriptPath = join(
openOcdPath,
"..",
"..",
"share",
"openocd",
"espressif",
"tools",
"esp_detect_config.py"
);


const scriptPath = await this.getScriptPath(openOCDVersion);
if (!scriptPath) {
throw new Error(
"Could not locate esp_detect_config.py for the current OpenOCD installation"
);
}

Comment thread
coderabbitai[bot] marked this conversation as resolved.
const openOcdScriptsPath = await getOpenOcdScripts(
this.workspaceFolderUri
);
if (!openOcdScriptsPath) {
throw new Error("Could not get OpenOCD scripts path");
}

const espConfigPath = join(openOcdScriptsPath, "esp-config.json");

const notificationMode = idfConf.readParameter(
"idf.notificationMode",
this.workspaceFolderUri
) as string;

const ProgressLocation =
notificationMode === idfConf.NotificationMode.All ||
notificationMode === idfConf.NotificationMode.Notifications
? vscode.ProgressLocation.Notification
: vscode.ProgressLocation.Window;

const pythonBinPath = await getVirtualEnvPythonPath();
notificationMode === idfConf.NotificationMode.All ||
notificationMode === idfConf.NotificationMode.Notifications
? vscode.ProgressLocation.Notification
: vscode.ProgressLocation.Window;

const pythonBinPath = getVirtualEnvPythonPath();
if (!pythonBinPath) {
throw new Error("Could not get Python binary path");
}
const modifiedEnv = await configureEnvVariables(this.workspaceFolderUri);

// Remove OPENOCD_USB_ADAPTER_LOCATION from environment during device detection
// to allow scanning all available devices, not just the one at the configured location
Expand Down Expand Up @@ -139,25 +134,25 @@ export class DevkitsCommand {
vscode.window.showInformationMessage("ESP Detect Config completed");
return result;
} catch (error) {
const msg = error.message
const msg = error instanceof Error && error.message
? error.message
: "Error running ESP Detect Config";
Logger.errorNotify(msg, error, "DevkitsCommand");
Logger.errorNotify(msg, error as Error, "DevkitsCommand");
OutputChannel.appendLine(msg, "ESP Detect Config");
OutputChannel.show();
throw error;
}
}
);
} catch (error) {
const msg = error.message
const msg = error instanceof Error && error.message
? error.message
: "Error running ESP Detect Config";
if (opts?.silent) {
Logger.error(msg, error, "DevkitsCommand");
Logger.error(msg, error as Error, "DevkitsCommand");
throw error;
} else {
Logger.errorNotify(msg, error, "DevkitsCommand");
Logger.errorNotify(msg, error as Error, "DevkitsCommand");
OutputChannel.appendLine(msg, "ESP Detect Config");
OutputChannel.show();
}
Expand All @@ -167,9 +162,10 @@ export class DevkitsCommand {
public async getScriptPath(openOCDVersion: string): Promise<string | null> {
try {
const modifiedEnv = await configureEnvVariables(this.workspaceFolderUri);
const openOcdPath = await isBinInPath("openocd", modifiedEnv, [
"openocd-esp32",
]);
const openOcdPath = await OpenOCDManager.getOpenOcdPath(
this.workspaceFolderUri,
modifiedEnv
);

if (!openOcdPath || !openOCDVersion) {
return null;
Expand Down
4 changes: 3 additions & 1 deletion src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4469,7 +4469,9 @@ async function ensureEimAndLaunch(workspaceRoot: vscode.Uri) {

canLaunchGui = !shouldUseCliMode && eimSupportsGui;
Logger.info(
`EIM launch mode: ${canLaunchGui ? "gui" : "cli wizard"} (forceCliMode=${forceCliMode}, isSnapInstall=${isSnapInstall}, eimSupportsGui=${eimSupportsGui})`,
`EIM launch mode: ${
canLaunchGui ? "gui" : "cli wizard"
} (forceCliMode=${forceCliMode}, isSnapInstall=${isSnapInstall}, eimSupportsGui=${eimSupportsGui})`,
"openEIM"
);
}
Expand Down
7 changes: 7 additions & 0 deletions src/support/configurationAccess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,13 @@ export async function getConfigurationAccess(
);
}
}
if (reportedResult.configurationSettings.customOpenOcdPath) {
reportedResult.configurationAccess.customOpenOcdPath = canAccessFile(
reportedResult.configurationSettings.customOpenOcdPath,
constants.X_OK,
"CUSTOM_OPENOCD_PATH"
);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
if (process.platform !== "win32") {
const cmakePathInEnv = await isBinInPath("cmake", process.env);
reportedResult.configurationAccess.cmakeInEnv =
Expand Down
1 change: 1 addition & 0 deletions src/support/configurationSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export async function getConfigurationSettings(
espIdfPath: idfPathDir,
customTerminalExecutable: conf.get("idf.customTerminalExecutable"),
customTerminalExecutableArgs: conf.get("idf.customTerminalExecutableArgs"),
customOpenOcdPath: conf.get("idf.customOpenOCDPath"),
flashType: conf.get("idf.flashType"),
flashPartitionToUse: conf.get("idf.flashPartitionToUse"),
customExtraPaths: currentEnvVars["PATH"],
Expand Down
2 changes: 2 additions & 0 deletions src/support/initReportObj.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export function initializeReportObject() {
flashType: undefined,
flashPartitionToUse: undefined,
customExtraPaths: undefined,
customOpenOcdPath: undefined,
idfExtraVars: undefined,
userExtraVars: undefined,
customTerminalExecutable: undefined,
Expand All @@ -49,6 +50,7 @@ export function initializeReportObject() {
cmakeInEnv: undefined,
ninjaInEnv: undefined,
toolsPath: undefined,
customOpenOcdPath: undefined,
};
report.configurationSpacesValidation = {
customExtraPaths: undefined,
Expand Down
Loading
Loading