按规划继续工作

结论:接入 vendored LinuxCNC tooldata_common.cc 负责刀具表解析与保存,WASM/SDK/OPFS/UI 仅做运行时边界搬运;native、WASM、OPFS 和浏览器 smoke 验证已通过。
This commit is contained in:
2026-06-08 08:31:10 +08:00
parent 5ea07606d7
commit a16f3605fa
24 changed files with 1302 additions and 53 deletions

View File

@@ -13,6 +13,7 @@
#include "canon_event_sink.hh"
#include "linuxcnc_hal_adapter.hh"
#include "linuxcnc_tool_adapter.hh"
#include "tooldata.hh"
namespace {
@@ -145,6 +146,35 @@ void append_parameter_state(std::ostringstream &output, const Interp &interp)
output << "parameter_5399=" << interp._setup.parameters[5399] << "\n";
}
void append_tool_entry(std::ostringstream &output, const char *prefix, const CANON_TOOL_TABLE &tool)
{
output << prefix << ".toolno=" << tool.toolno << "\n";
output << prefix << ".pocketno=" << tool.pocketno << "\n";
output << prefix << ".z=" << tool.offset.tran.z << "\n";
output << prefix << ".diameter=" << tool.diameter << "\n";
output << prefix << ".frontangle=" << tool.frontangle << "\n";
output << prefix << ".backangle=" << tool.backangle << "\n";
output << prefix << ".orientation=" << tool.orientation << "\n";
output << prefix << ".comment=" << tool.comment << "\n";
}
void append_tool_table_state(std::ostringstream &output)
{
output << "tooldata_last_index=" << tooldata_last_index_get() << "\n";
CANON_TOOL_TABLE tool = standalone::tool_entry_init();
if (standalone::get_tool_entry(&tool, 0) == 0) {
append_tool_entry(output, "tool_0", tool);
}
if (standalone::get_tool_entry(&tool, 1) == 0) {
append_tool_entry(output, "tool_1", tool);
}
if (standalone::get_tool_entry(&tool, 2) == 0) {
append_tool_entry(output, "tool_2", tool);
}
output << "tool_index_for_tool_2=" << standalone::find_tool_index_for_tool(2) << "\n";
}
void append_error_text(std::ostringstream &output, Interp &interp, const char *prefix, int rc)
{
if (rc > INTERP_MIN_ERROR) {
@@ -317,6 +347,30 @@ char *lcinterp_save_parameters(const char *path, const char *assignments)
return copy_result(output.str());
}
EMSCRIPTEN_KEEPALIVE
char *lcinterp_load_tool_table(const char *path)
{
standalone::reset_tool_adapter();
tooldata_init(false);
tooldata_set_db(DB_NOTUSED);
std::ostringstream output;
const int rc = tooldata_load(path);
output << "tooldata_load=" << rc << "\n";
append_tool_table_state(output);
return copy_result(output.str());
}
EMSCRIPTEN_KEEPALIVE
char *lcinterp_save_tool_table(const char *path)
{
std::ostringstream output;
const int rc = tooldata_save(path);
output << "tooldata_save=" << rc << "\n";
append_tool_table_state(output);
return copy_result(output.str());
}
EMSCRIPTEN_KEEPALIVE
void lcinterp_free_string(char *value)
{

View File

@@ -2,6 +2,8 @@
#include <array>
#include "tooldata.hh"
namespace {
std::array<CANON_TOOL_TABLE, CANON_POCKETS_MAX> &tool_table()
@@ -22,6 +24,12 @@ int &current_tool_index_ref()
return index;
}
int &last_tool_index_ref()
{
static int index = 0;
return index;
}
CANON_TOOL_TABLE empty_tool()
{
CANON_TOOL_TABLE tool{};
@@ -30,6 +38,20 @@ CANON_TOOL_TABLE empty_tool()
return tool;
}
CANON_TOOL_TABLE linuxcnc_empty_tool()
{
CANON_TOOL_TABLE tool{};
tool.toolno = -1;
tool.pocketno = -1;
tool.diameter = 0;
tool.frontangle = 0;
tool.backangle = 0;
tool.orientation = 0;
ZERO_EMC_POSE(tool.offset);
tool.comment[0] = 0;
return tool;
}
} // namespace
namespace standalone {
@@ -117,3 +139,63 @@ void change_selected_tool()
}
} // namespace standalone
extern "C" {
toolidx_t tooldata_put(CANON_TOOL_TABLE tdata, int idx)
{
if ((idx < 0) || (idx >= CANON_POCKETS_MAX)) {
return IDX_FAIL;
}
auto &tools = tool_table();
const bool is_new = tools[idx].toolno == -1;
tools[idx] = tdata;
if (idx > last_tool_index_ref()) {
last_tool_index_ref() = idx;
}
return is_new ? IDX_NEW : IDX_OK;
}
toolidx_t tooldata_get(CANON_TOOL_TABLE *pdata, int idx)
{
if ((pdata == nullptr) || (idx < 0) || (idx >= CANON_POCKETS_MAX)) {
return IDX_FAIL;
}
*pdata = tool_table()[idx];
return IDX_OK;
}
void tooldata_reset(void)
{
auto &tools = tool_table();
for (int idx = 0; idx < CANON_POCKETS_MAX; ++idx) {
tools[idx] = linuxcnc_empty_tool();
}
selected_tool_index_ref() = -1;
current_tool_index_ref() = 0;
last_tool_index_ref() = 0;
}
void tooldata_last_index_set(int idx)
{
last_tool_index_ref() = idx;
}
int tooldata_last_index_get(void)
{
return last_tool_index_ref();
}
int tooldata_find_index_for_tool(int toolno)
{
return standalone::find_tool_index_for_tool(toolno);
}
int tooldata_db_getall(void)
{
return -1;
}
} // extern "C"

View File

@@ -0,0 +1,50 @@
#pragma once
#include "emc/nml_intf/canon.hh"
extern "C" {
typedef enum {
IDX_OK = 0,
IDX_NEW,
IDX_FAIL,
} toolidx_t;
typedef enum {
DB_NOTUSED = 0,
DB_ACTIVE,
} tooldb_t;
typedef enum {
SPINDLE_LOAD,
SPINDLE_UNLOAD,
TOOL_OFFSET,
} tool_notify_t;
struct CANON_TOOL_TABLE tooldata_entry_init(void);
toolidx_t tooldata_put(struct CANON_TOOL_TABLE tdata, int idx);
toolidx_t tooldata_get(CANON_TOOL_TABLE *pdata, int idx);
void tooldata_init(bool random_tool_changer);
void tooldata_reset(void);
void tooldata_last_index_set(int idx);
int tooldata_last_index_get(void);
int tooldata_find_index_for_tool(int toolno);
void tooldata_format_toolline(int idx,
bool ignore_zero_values,
CANON_TOOL_TABLE tdata,
char formatted_line[CANON_TOOL_ENTRY_LEN]);
void tooldata_add_init(int nonrandom_start_idx);
int tooldata_read_entry(const char *input_line);
void tooldata_set_db(tooldb_t mode);
int tooldata_load(const char *filename);
int tooldata_save(const char *filename);
#define DB_SPINDLE_SAVE "./db_spindle.tbl"
int tooldata_db_getall(void);
}

View File

@@ -1,23 +1,3 @@
#pragma once
#include "emc/nml_intf/emctool.h"
#include "linuxcnc_tool_adapter.hh"
enum {
IDX_OK = 0,
};
inline CANON_TOOL_TABLE tooldata_entry_init()
{
return standalone::tool_entry_init();
}
inline int tooldata_find_index_for_tool(int toolno)
{
return standalone::find_tool_index_for_tool(toolno);
}
inline int tooldata_get(CANON_TOOL_TABLE *tool, int index)
{
return standalone::get_tool_entry(tool, index) == 0 ? IDX_OK : -1;
}
#include "../tooldata.hh"

View File

@@ -0,0 +1,59 @@
import { loadTextFile } from "./file-service.js";
import {
machineIniPath,
parameterFilePath,
toolTablePath,
} from "./path-model.js";
import { restoreMachineParametersFromOpfs } from "./linuxcnc-parameter-bridge.js";
import { loadMachineToolTableFromOpfs } from "./linuxcnc-tool-table-bridge.js";
const DEFAULT_WASM_INI_PATH = "/work/machine.ini";
const DEFAULT_WASM_PARAMETER_PATH = "/work/linuxcnc.var";
const DEFAULT_WASM_TOOL_TABLE_PATH = "/work/tool.tbl";
function requireSessionSdk(interp) {
if (typeof interp?.writeTextFile !== "function") {
throw new Error("interpreter SDK is missing writeTextFile().");
}
}
function resolveSessionPaths(machineId, options = {}) {
return {
iniOpfsPath: options.iniOpfsPath ?? machineIniPath(machineId, options.iniFilename),
iniWasmPath: options.iniWasmPath ?? DEFAULT_WASM_INI_PATH,
parameterOpfsPath:
options.parameterOpfsPath ?? parameterFilePath(machineId, options.parameterFilename),
parameterWasmPath: options.parameterWasmPath ?? DEFAULT_WASM_PARAMETER_PATH,
toolTableOpfsPath:
options.toolTableOpfsPath ?? toolTablePath(machineId, options.toolTableFilename),
toolTableWasmPath: options.toolTableWasmPath ?? DEFAULT_WASM_TOOL_TABLE_PATH,
};
}
export async function loadMachineSessionFromOpfs(interp, machineId, options = {}) {
requireSessionSdk(interp);
const paths = resolveSessionPaths(machineId, options);
const iniText = await loadTextFile(paths.iniOpfsPath, options.storage);
interp.writeTextFile(paths.iniWasmPath, iniText);
const parameters = await restoreMachineParametersFromOpfs(interp, machineId, {
storage: options.storage,
opfsPath: paths.parameterOpfsPath,
wasmPath: paths.parameterWasmPath,
});
const toolTable = await loadMachineToolTableFromOpfs(interp, machineId, {
storage: options.storage,
opfsPath: paths.toolTableOpfsPath,
wasmPath: paths.toolTableWasmPath,
});
return {
machineId,
ini: {
opfsPath: paths.iniOpfsPath,
wasmPath: paths.iniWasmPath,
},
parameters,
toolTable,
};
}

View File

@@ -0,0 +1,46 @@
import { loadTextFile, saveTextFile } from "./file-service.js";
import { toolTablePath } from "./path-model.js";
const DEFAULT_WASM_TOOL_TABLE_PATH = "/work/tool.tbl";
function requireToolTableSdk(interp) {
for (const method of ["writeTextFile", "readTextFile", "loadToolTable", "saveToolTable"]) {
if (typeof interp?.[method] !== "function") {
throw new Error(`interpreter SDK is missing ${method}().`);
}
}
}
function resolvePaths(machineId, options = {}) {
const opfsPath = options.opfsPath ?? toolTablePath(machineId, options.filename);
const wasmPath = options.wasmPath ?? DEFAULT_WASM_TOOL_TABLE_PATH;
return { opfsPath, wasmPath };
}
export async function loadMachineToolTableFromOpfs(interp, machineId, options = {}) {
requireToolTableSdk(interp);
const { opfsPath, wasmPath } = resolvePaths(machineId, options);
const text = await loadTextFile(opfsPath, options.storage);
interp.writeTextFile(wasmPath, text);
return {
opfsPath,
wasmPath,
result: interp.loadToolTable(wasmPath),
};
}
export async function saveMachineToolTableToOpfs(interp, machineId, options = {}) {
requireToolTableSdk(interp);
const { opfsPath, wasmPath } = resolvePaths(machineId, options);
const result = interp.saveToolTable(wasmPath);
const savedText = interp.readTextFile(wasmPath);
await saveTextFile(opfsPath, savedText, options.storage);
return {
opfsPath,
wasmPath,
result,
savedText,
};
}

View File

@@ -40,5 +40,7 @@ vendored LinuxCNC RS274NGC sources and exposes:
- `runFileWithIni(path, iniPath)`
- `restoreParameters(path)`
- `saveParameters(path, values)`
- `loadToolTable(path)`
- `saveToolTable(path)`
- `writeTextFile(path, text)`
- `readTextFile(path)`

View File

@@ -84,5 +84,13 @@ export async function createLinuxCncInterpSdk(moduleOptions = {}) {
.join("\n");
return callStringResult(mod, "lcinterp_save_parameters", path, assignments);
},
loadToolTable(path) {
return callStringResult(mod, "lcinterp_load_tool_table", path);
},
saveToolTable(path) {
return callStringResult(mod, "lcinterp_save_tool_table", path);
},
};
}

View File

@@ -1,18 +1,58 @@
import { createLinuxCncIniSdk } from "../../sdk/src/index.js";
import {
createLinuxCncIniSdk,
createLinuxCncInterpSdk,
} from "../../sdk/src/index.js";
import {
getOpfsRoot,
loadTextFile,
saveTextFile,
} from "../../opfs/file-service.js";
import {
loadGcodeProgram,
loadMachineTextFiles,
machineFilePaths,
saveGcodeProgram,
saveMachineTextFiles,
} from "../../opfs/machine-file-store.js";
import {
loadMachineSessionFromOpfs,
} from "../../opfs/linuxcnc-machine-session-bridge.js";
const SAMPLE_PATH =
"../../../linuxcnc/configs/sim/axis/vismach/5axis/table-dual-rotary/xyzab-tdr.ini";
const OPFS_FILE = "linuxcnc/xyzab-tdr.ini";
const MACHINE_ID = "xyzab-tdr";
const MACHINE_PATHS = machineFilePaths(MACHINE_ID);
const OPFS_FILE = MACHINE_PATHS.ini;
const WASM_FILE = "/work/xyzab-tdr.ini";
const SESSION_WASM_FILES = {
iniWasmPath: "/work/session-machine.ini",
parameterWasmPath: "/work/session-linuxcnc.var",
toolTableWasmPath: "/work/session-tool.tbl",
};
const GCODE_FILENAME = "ui-session.ngc";
const GCODE_WASM_FILE = "/work/ui-session.ngc";
const DEFAULT_TOOL_TABLE = "T2 P7 Z3.125 D1.5 I12 J34 Q4 ;ui session tool\n";
const DEFAULT_PARAMETERS = [
"5161 0.0",
"5162 0.0",
"5220 1",
"5221 0.0",
"5399 0.0",
"",
].join("\n");
const DEFAULT_GCODE = [
"G0 X1.0 Y2.0 (Comment)",
"G1 X3.0 Y4.0 F120.0",
"",
].join("\n");
const editor = document.getElementById("ini-editor");
const logNode = document.getElementById("log");
const eventNode = document.getElementById("canon-events");
const eventFilterNode = document.getElementById("event-filter");
const eventCountNode = document.getElementById("event-count");
const wasmBadge = document.getElementById("wasm-badge");
const interpBadge = document.getElementById("interp-badge");
const opfsBadge = document.getElementById("opfs-badge");
const fields = {
@@ -22,9 +62,17 @@ const fields = {
joints: document.getElementById("field-joints"),
coordinates: document.getElementById("field-coordinates"),
parameterFile: document.getElementById("field-parameter-file"),
sessionIni: document.getElementById("field-session-ini"),
sessionParameters: document.getElementById("field-session-parameters"),
sessionToolTable: document.getElementById("field-session-tool-table"),
sessionGcode: document.getElementById("field-session-gcode"),
runStatus: document.getElementById("field-run-status"),
};
let iniSdk = null;
let interpSdk = null;
let loadedSession = null;
let canonicalEventText = "";
function setBadge(node, text, className = "badge") {
node.className = className;
@@ -36,17 +84,40 @@ function setLog(message, isError = false) {
logNode.className = `log${isError ? " danger" : ""}`;
}
function setCanonicalEvents(text) {
canonicalEventText = text || "";
renderCanonicalEvents();
}
function renderCanonicalEvents() {
const lines = canonicalEventText.split("\n").filter(Boolean);
const filter = eventFilterNode.value.trim().toLowerCase();
const visibleLines = filter
? lines.filter((line) => line.toLowerCase().includes(filter))
: lines;
eventNode.textContent = visibleLines.join("\n");
eventCountNode.textContent = `${visibleLines.length} / ${lines.length}`;
}
function setField(name, value) {
fields[name].textContent = value ?? "-";
}
function requireIniSdk() {
if (!iniSdk) {
throw new Error("WASM module is not ready yet.");
throw new Error("INI WASM module is not ready yet.");
}
return iniSdk;
}
function requireInterpSdk() {
if (!interpSdk) {
throw new Error("Interpreter WASM module is not ready yet.");
}
return interpSdk;
}
function syncEditorToWasmFs() {
requireIniSdk().writeTextFile(WASM_FILE, editor.value);
}
@@ -64,10 +135,19 @@ async function loadSample() {
async function boot() {
try {
iniSdk = await createLinuxCncIniSdk();
setBadge(wasmBadge, "WASM: ready");
setBadge(wasmBadge, "INI WASM: ready");
} catch (error) {
setBadge(wasmBadge, "WASM: failed", "badge danger");
setLog(`WASM init failed: ${error.message}`, true);
setBadge(wasmBadge, "INI WASM: failed", "badge danger");
setLog(`INI WASM init failed: ${error.message}`, true);
throw error;
}
try {
interpSdk = await createLinuxCncInterpSdk();
setBadge(interpBadge, "Interpreter WASM: ready");
} catch (error) {
setBadge(interpBadge, "Interpreter WASM: failed", "badge danger");
setLog(`Interpreter WASM init failed: ${error.message}`, true);
throw error;
}
@@ -97,6 +177,78 @@ document.getElementById("save-opfs").addEventListener("click", async () => {
}
});
document.getElementById("save-machine-files").addEventListener("click", async () => {
try {
const paths = await saveMachineTextFiles(MACHINE_ID, {
ini: editor.value,
toolTable: DEFAULT_TOOL_TABLE,
parameters: DEFAULT_PARAMETERS,
});
const gcodePath = await saveGcodeProgram(GCODE_FILENAME, DEFAULT_GCODE);
setLog(
[
"Saved machine text files to OPFS.",
`INI: ${paths.ini}`,
`Tool table: ${paths.toolTable}`,
`Parameters: ${paths.parameters}`,
`G-code: ${gcodePath}`,
].join("\n"),
);
} catch (error) {
setLog(`Machine file save failed: ${error.message}`, true);
}
});
document.getElementById("load-session").addEventListener("click", async () => {
try {
loadedSession = await loadMachineSessionFromOpfs(
requireInterpSdk(),
MACHINE_ID,
SESSION_WASM_FILES,
);
setField("sessionIni", loadedSession.ini.wasmPath);
setField("sessionParameters", loadedSession.parameters.wasmPath);
setField("sessionToolTable", loadedSession.toolTable.wasmPath);
setLog(
[
"Loaded machine session into the interpreter WASM filesystem.",
`INI: ${loadedSession.ini.opfsPath} -> ${loadedSession.ini.wasmPath}`,
`Parameters: ${loadedSession.parameters.result.trim()}`,
`Tool table: ${loadedSession.toolTable.result.trim()}`,
].join("\n"),
);
} catch (error) {
setLog(`Machine session load failed: ${error.message}`, true);
}
});
document.getElementById("run-gcode").addEventListener("click", async () => {
try {
if (!loadedSession) {
throw new Error("Load a machine session before running G-code.");
}
const interp = requireInterpSdk();
const programText = await loadGcodeProgram(GCODE_FILENAME);
interp.writeTextFile(GCODE_WASM_FILE, programText);
const result = interp.runFileWithIni(GCODE_WASM_FILE, loadedSession.ini.wasmPath);
setField("sessionGcode", GCODE_WASM_FILE);
setField("runStatus", "ok");
setCanonicalEvents(result.trim());
setLog(
[
"Ran G-code through LinuxCNC interpreter WASM.",
`Program: ${GCODE_WASM_FILE}`,
`INI: ${loadedSession.ini.wasmPath}`,
result.trim(),
].join("\n"),
);
} catch (error) {
setField("runStatus", "failed");
setCanonicalEvents("");
setLog(`G-code run failed: ${error.message}`, true);
}
});
document.getElementById("load-opfs").addEventListener("click", async () => {
try {
editor.value = await loadTextFile(OPFS_FILE);
@@ -137,4 +289,25 @@ document.getElementById("query").addEventListener("click", async () => {
}
});
document.getElementById("load-machine-files").addEventListener("click", async () => {
try {
const files = await loadMachineTextFiles(MACHINE_ID);
editor.value = files.ini;
setLog(
[
"Loaded machine text files from OPFS.",
`INI bytes: ${files.ini.length}`,
`Tool table bytes: ${files.toolTable.length}`,
`Parameter bytes: ${files.parameters.length}`,
].join("\n"),
);
} catch (error) {
setLog(`Machine file load failed: ${error.message}`, true);
}
});
eventFilterNode.addEventListener("input", () => {
renderCanonicalEvents();
});
boot().catch(() => {});

View File

@@ -123,6 +123,32 @@
font: 13px/1.5 "SFMono-Regular", "Consolas", monospace;
white-space: pre-wrap;
}
.events {
border: 1px solid var(--border);
border-radius: 6px;
background: #fbfdff;
padding: 12px;
min-height: 180px;
max-height: 320px;
overflow: auto;
font: 12px/1.5 "SFMono-Regular", "Consolas", monospace;
white-space: pre-wrap;
}
.event-tools {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 8px;
align-items: center;
}
input {
border: 1px solid var(--border);
border-radius: 6px;
padding: 9px 10px;
font: 13px/1.4 "SFMono-Regular", "Consolas", monospace;
color: var(--text);
background: #fbfdff;
min-width: 0;
}
.danger { color: var(--danger); }
@media (max-width: 960px) {
.grid { grid-template-columns: 1fr; }
@@ -148,8 +174,12 @@
<button id="load-sample" class="primary">Load LinuxCNC Sample</button>
<button id="save-opfs">Save To OPFS</button>
<button id="load-opfs">Load From OPFS</button>
<button id="save-machine-files">Save Machine Files</button>
<button id="load-machine-files">Load Machine Files</button>
<button id="sync-wasm">Sync To WASM FS</button>
<button id="query" class="secondary">Query LinuxCNC Fields</button>
<button id="load-session" class="secondary">Load Machine Session</button>
<button id="run-gcode" class="secondary">Run G-code</button>
</div>
<textarea id="ini-editor" spellcheck="false"></textarea>
</section>
@@ -157,7 +187,8 @@
<section class="panel">
<h2>Control Panel</h2>
<div class="status">
<div><span id="wasm-badge" class="badge">WASM: loading</span></div>
<div><span id="wasm-badge" class="badge">INI WASM: loading</span></div>
<div><span id="interp-badge" class="badge">Interpreter WASM: loading</span></div>
<div><span id="opfs-badge" class="badge">OPFS: checking</span></div>
</div>
@@ -175,12 +206,29 @@
<dt>Parameter File</dt>
<dd id="field-parameter-file">-</dd>
<dt>OPFS Path</dt>
<dd id="field-opfs-path">linuxcnc/xyzab-tdr.ini</dd>
<dd id="field-opfs-path">linuxcnc/machines/xyzab-tdr/machine.ini</dd>
<dt>WASM Path</dt>
<dd id="field-wasm-path">/work/xyzab-tdr.ini</dd>
<dt>Session INI</dt>
<dd id="field-session-ini">-</dd>
<dt>Session Params</dt>
<dd id="field-session-parameters">-</dd>
<dt>Session Tools</dt>
<dd id="field-session-tool-table">-</dd>
<dt>Session G-code</dt>
<dd id="field-session-gcode">-</dd>
<dt>Run Status</dt>
<dd id="field-run-status">-</dd>
</dl>
<div class="log" id="log"></div>
<h2>Canonical Events</h2>
<div class="event-tools">
<input id="event-filter" type="search" placeholder="Filter event text">
<span id="event-count" class="badge">0 / 0</span>
</div>
<pre class="events" id="canon-events"></pre>
</section>
</section>
</main>