Merge remote-tracking branch 'upstream/main' into reinlooptest
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
# 默认所有文本文件使用 Windows 换行符
|
||||
* text=auto eol=crlf
|
||||
|
||||
# server 文件夹下所有文件使用 Linux 换行符
|
||||
server/** text eol=lf
|
||||
|
||||
# 特定文件类型明确指定
|
||||
*.sh text eol=lf
|
||||
*.bash text eol=lf
|
||||
+10
-1
@@ -140,7 +140,16 @@ async function getConfig(configType, options = {}) {
|
||||
repeat: Number(values.repeat)
|
||||
};
|
||||
}
|
||||
return callServer({ type: "getFunctionConfig", configType }, options);
|
||||
const result = await callServer({
|
||||
type: "getVolumeConfigFile",
|
||||
deviceId: getDeviceId(options)
|
||||
}, options);
|
||||
if (result.found === false || !result.url) {
|
||||
throw new Error("当前产线尚无已成功提交的容积配置");
|
||||
}
|
||||
const response = await fetch(result.url);
|
||||
if (!response.ok) throw new Error(`配置文件下载失败: HTTP ${response.status}`);
|
||||
return JSON.parse(await response.text());
|
||||
}
|
||||
|
||||
async function main() {
|
||||
|
||||
@@ -6,10 +6,14 @@ const { callServer, downloadFromUrl, downloadToPath } = require("./server-client
|
||||
const { signLicense } = require("./license-manager");
|
||||
const { plotCsv } = require("./plot-csv");
|
||||
const { plotJson } = require("./plot-json");
|
||||
const { createModelHandlers } = require("./model-handlers");
|
||||
|
||||
const VOLUME_FIELDS = [
|
||||
"q_in_val", "dt", "p_max", "fit_low", "fit_high", "T_delta", "xa_full", "num_runs"
|
||||
];
|
||||
const IDENTIFICATION_FIELDS = [
|
||||
"q_in_val", "dt", "n_order", "t_c", "levels", "dead_area", "xa_full", "V_val", "repeat"
|
||||
];
|
||||
const DEFAULT_API_URL = "https://ReinLoop.dominatedconvergence.com";
|
||||
const API_URL = process.env.REINLOOP_API_URL || DEFAULT_API_URL;
|
||||
const INBOX_POLL_INTERVAL_MS = Number(process.env.POLL_INTERVAL_MS || 1000);
|
||||
@@ -35,13 +39,42 @@ function startPanelInboxPoller(window) {
|
||||
}
|
||||
|
||||
let polling = false;
|
||||
let notificationDeviceId = null;
|
||||
const deliveredNotificationIds = new Set();
|
||||
let notificationFailureReported = false;
|
||||
|
||||
async function pollNotifications(requestContext) {
|
||||
if (notificationDeviceId !== requestContext.deviceId) {
|
||||
notificationDeviceId = requestContext.deviceId;
|
||||
deliveredNotificationIds.clear();
|
||||
}
|
||||
const pending = await callServer(
|
||||
{ type: "getPendingPanelNotification", deviceId: requestContext.deviceId },
|
||||
requestContext
|
||||
);
|
||||
notificationFailureReported = false;
|
||||
const notification = pending.notification;
|
||||
if (!pending.pending || !notification?.notificationId) return;
|
||||
if (deliveredNotificationIds.has(notification.notificationId)) return;
|
||||
deliveredNotificationIds.add(notification.notificationId);
|
||||
window.webContents.send("panel:notification", notification);
|
||||
}
|
||||
|
||||
const poll = async () => {
|
||||
if (polling || window.isDestroyed()) return;
|
||||
if (!connectionState.deviceId || !connectionState.adminToken) return;
|
||||
if (pendingReview) return;
|
||||
const requestContext = { ...connectionState };
|
||||
polling = true;
|
||||
try {
|
||||
try {
|
||||
await pollNotifications(requestContext);
|
||||
} catch (error) {
|
||||
if (!notificationFailureReported) {
|
||||
console.warn(`[${new Date().toISOString()}] Panel 通知轮询不可用: ${error.message}`);
|
||||
notificationFailureReported = true;
|
||||
}
|
||||
}
|
||||
if (pendingReview) return;
|
||||
const pending = await callServer(
|
||||
{ type: "getPendingPanelFile", deviceId: requestContext.deviceId },
|
||||
requestContext
|
||||
@@ -128,7 +161,35 @@ function validateParameters(configType, parameters) {
|
||||
if (!Number.isInteger(parameters.num_runs)) {
|
||||
throw new Error("num_runs 必须是整数");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (configType === "identification") {
|
||||
const fields = Object.keys(parameters);
|
||||
const missing = IDENTIFICATION_FIELDS.filter((field) => !(field in parameters));
|
||||
const extra = fields.filter((field) => !IDENTIFICATION_FIELDS.includes(field));
|
||||
if (missing.length || extra.length) {
|
||||
throw new Error(`系统辨识配置字段不匹配。缺少: ${missing.join(", ") || "无"};多余: ${extra.join(", ") || "无"}`);
|
||||
}
|
||||
for (const field of IDENTIFICATION_FIELDS) {
|
||||
if (field === "levels") continue;
|
||||
if (typeof parameters[field] !== "number" || !Number.isFinite(parameters[field])) {
|
||||
throw new Error(`${field} 必须是有效数字`);
|
||||
}
|
||||
}
|
||||
if (!Array.isArray(parameters.levels) || parameters.levels.some((value) => typeof value !== "number" || !Number.isFinite(value))) {
|
||||
throw new Error("levels 必须是有效数字数组");
|
||||
}
|
||||
if (parameters.levels.length < 2 || (parameters.levels.length & (parameters.levels.length - 1)) !== 0) {
|
||||
throw new Error("levels 元素个数必须是不小于 2 的 2 的整数次幂");
|
||||
}
|
||||
if (!Number.isInteger(parameters.n_order) || !Number.isInteger(parameters.repeat)) {
|
||||
throw new Error("n_order 和 repeat 必须是整数");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(`不支持的配置类型: ${configType}`);
|
||||
}
|
||||
|
||||
function toDataUrl(filePath) {
|
||||
@@ -138,6 +199,7 @@ function toDataUrl(filePath) {
|
||||
}
|
||||
|
||||
function registerHandlers() {
|
||||
const modelHandlers = createModelHandlers({ callServer });
|
||||
ipcMain.handle("app:get-defaults", () => ({
|
||||
apiUrl: API_URL,
|
||||
deviceId: process.env.REINLOOP_DEVICE_ID || "",
|
||||
@@ -155,6 +217,21 @@ function registerHandlers() {
|
||||
return { success: true };
|
||||
});
|
||||
|
||||
ipcMain.handle("panel:ack-notification", (_event, request) =>
|
||||
callServer({
|
||||
type: "ackPanelNotification",
|
||||
deviceId: request.deviceId,
|
||||
notificationId: request.notificationId
|
||||
}, request.credentials));
|
||||
ipcMain.handle("panel:open-notification-file", async (_event, request) => {
|
||||
if (!request.fileID) throw new Error("该提醒未关联结果文件");
|
||||
const download = await callServer({ type: "downloadModel", fileID: request.fileID }, request.credentials);
|
||||
const sourcePath = await downloadFromUrl(download.url, download.fileName || "volume_result.json", request.credentials);
|
||||
const error = await shell.openPath(sourcePath);
|
||||
if (error) throw new Error(`无法打开结果文件: ${error}`);
|
||||
return { filePath: sourcePath };
|
||||
});
|
||||
|
||||
ipcMain.handle("connection:test", async (_event, request) => {
|
||||
const result = await callServer({ type: "listOrganizations" }, request);
|
||||
connectionState.apiUrl = String(request.apiUrl || API_URL).trim();
|
||||
@@ -256,35 +333,19 @@ function registerHandlers() {
|
||||
return result;
|
||||
});
|
||||
|
||||
ipcMain.handle("model:list", (_event, request) =>
|
||||
callServer({ type: "listModels", folder: `${request.deviceId}/model_config` }, request.credentials));
|
||||
ipcMain.handle("model:list", (_event, request) => modelHandlers.list(request));
|
||||
ipcMain.handle("model:choose-upload-file", async () => {
|
||||
const selection = await dialog.showOpenDialog({ title: "选择模型文件", properties: ["openFile"] });
|
||||
if (selection.canceled) return null;
|
||||
const sourcePath = selection.filePaths[0];
|
||||
return { sourcePath, fileName: path.basename(sourcePath) };
|
||||
});
|
||||
ipcMain.handle("model:upload", async (_event, request) => {
|
||||
if (!request.sourcePath || !request.fileName) throw new Error("请先选择模型文件");
|
||||
const sourcePath = path.resolve(request.sourcePath);
|
||||
const fileName = path.basename(request.fileName);
|
||||
await fs.promises.access(sourcePath, fs.constants.R_OK);
|
||||
const issued = await callServer({
|
||||
type: "uploadDataFile", fileName, folder: `${request.deviceId}/model_config`,
|
||||
overwrite: request.overwrite === true
|
||||
}, request.credentials);
|
||||
const form = new FormData();
|
||||
form.append("file", new Blob([await fs.promises.readFile(sourcePath)]), fileName);
|
||||
const response = await fetch(issued.uploadMetadata.url, { method: "POST", body: form });
|
||||
if (![200, 204].includes(response.status)) throw new Error(`模型上传失败: HTTP ${response.status}`);
|
||||
return { success: true, fileID: issued.fileID, fileName };
|
||||
});
|
||||
ipcMain.handle("model:upload", (_event, request) => modelHandlers.upload(request));
|
||||
ipcMain.handle("model:download", async (_event, request) => {
|
||||
const result = await callServer({ type: "downloadModel", fileID: request.fileID }, request.credentials);
|
||||
return { filePath: await downloadFromUrl(result.url, request.fileName, request.credentials) };
|
||||
});
|
||||
ipcMain.handle("model:delete", (_event, request) =>
|
||||
callServer({ type: "deleteFile", fileID: request.fileID }, request.credentials));
|
||||
ipcMain.handle("model:delete", (_event, request) => modelHandlers.delete(request));
|
||||
|
||||
ipcMain.handle("identification:list", (_event, request) =>
|
||||
callServer({
|
||||
|
||||
@@ -30,6 +30,9 @@ contextBridge.exposeInMainWorld("reinloop", {
|
||||
previewControlFile: (request) => ipcRenderer.invoke("control-data:preview", request),
|
||||
downloadControlFile: (request) => ipcRenderer.invoke("control-data:download", request),
|
||||
deleteControlFile: (request) => ipcRenderer.invoke("control-data:delete", request),
|
||||
acknowledgeNotification: (request) => ipcRenderer.invoke("panel:ack-notification", request),
|
||||
openNotificationFile: (request) => ipcRenderer.invoke("panel:open-notification-file", request),
|
||||
onCsvUpdated: (callback) => ipcRenderer.on("csv:updated", (_event, result) => callback(result)),
|
||||
onCsvWatchError: (callback) => ipcRenderer.on("csv:watch-error", (_event, message) => callback(message))
|
||||
onCsvWatchError: (callback) => ipcRenderer.on("csv:watch-error", (_event, message) => callback(message)),
|
||||
onPanelNotification: (callback) => ipcRenderer.on("panel:notification", (_event, notification) => callback(notification))
|
||||
});
|
||||
@@ -43,7 +43,7 @@
|
||||
<button class="tab active" data-target="plot-panel">绘图预览</button>
|
||||
<button class="tab" data-target="identification-data-panel">辨识数据</button>
|
||||
<button class="tab" data-target="control-data-panel">控制数据</button>
|
||||
<button class="tab" data-target="config-panel">配置发布</button>
|
||||
<button class="tab" data-target="config-panel">配置发布 <span id="config-notification-badge" class="tab-badge" hidden>0</span></button>
|
||||
<button class="tab" data-target="model-panel">模型管理</button>
|
||||
<button class="tab" data-target="license-panel">许可证</button>
|
||||
<button class="tab" data-target="organization-panel">组织管理</button>
|
||||
@@ -139,14 +139,15 @@
|
||||
<button class="segment" data-type="identification">系统辨识</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="config-notifications" class="notification-stack" aria-live="polite"></div>
|
||||
<div class="editor-layout">
|
||||
<div class="editor-column">
|
||||
<div class="editor-toolbar">
|
||||
<span id="config-label">容积测量配置</span>
|
||||
<button id="import-config" class="text-button">导入 JSON</button>
|
||||
</div>
|
||||
<textarea id="config-editor" spellcheck="false" aria-label="JSON 配置编辑器"></textarea>
|
||||
<p id="config-path" class="file-path">可直接编辑,或从本地 JSON 导入</p>
|
||||
<form id="config-form" class="config-form" aria-label="配置字段"></form>
|
||||
<p id="config-path" class="file-path">字段名称固定;可填写右侧数据或从本地 JSON 导入</p>
|
||||
</div>
|
||||
<aside class="publish-aside">
|
||||
<h3>发布检查</h3>
|
||||
@@ -171,7 +172,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="data-surface">
|
||||
<table><thead><tr><th>文件名</th><th>上传时间</th><th>大小</th><th>操作</th></tr></thead><tbody id="model-list"></tbody></table>
|
||||
<table><thead><tr><th>服务器文件名</th><th>原始文件名</th><th>上传时间</th><th>大小</th><th>操作</th></tr></thead><tbody id="model-list"></tbody></table>
|
||||
<p id="model-empty" class="empty-row">选择公司和产线后刷新模型列表</p>
|
||||
</div>
|
||||
</section>
|
||||
@@ -221,6 +222,24 @@
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<div id="action-dialog" class="action-dialog" hidden role="dialog" aria-modal="true" aria-labelledby="action-dialog-title">
|
||||
<form id="action-dialog-form" class="action-dialog-shell">
|
||||
<div class="action-dialog-head">
|
||||
<p class="section-kicker">MODEL CONTROL</p>
|
||||
<h2 id="action-dialog-title">模型操作</h2>
|
||||
</div>
|
||||
<p id="action-dialog-message" class="action-dialog-message"></p>
|
||||
<label class="action-dialog-field">
|
||||
<span>文件名</span>
|
||||
<input id="action-dialog-input" type="text" autocomplete="off" spellcheck="false">
|
||||
</label>
|
||||
<p id="action-dialog-error" class="action-dialog-error" hidden></p>
|
||||
<div class="action-dialog-actions">
|
||||
<button id="action-dialog-cancel" class="button secondary" type="button">取消</button>
|
||||
<button id="action-dialog-confirm" class="button primary" type="submit">确认</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div id="image-lightbox" class="lightbox" hidden role="dialog" aria-modal="true" aria-labelledby="lightbox-title">
|
||||
<div class="lightbox-shell">
|
||||
<div class="lightbox-toolbar"><strong id="lightbox-title">图像预览</strong><div class="lightbox-actions"><button id="zoom-out" class="button icon" title="缩小" aria-label="缩小图像">-</button><button id="zoom-in" class="button icon" title="放大" aria-label="放大图像">+</button><button id="zoom-fit" class="button secondary" type="button">适应窗口</button><button id="zoom-reset" class="button secondary" type="button">原始比例</button><button id="close-lightbox" class="button icon" title="关闭" aria-label="关闭图像预览">x</button></div></div>
|
||||
|
||||
@@ -21,6 +21,11 @@ const identificationExample = {
|
||||
repeat: 2
|
||||
};
|
||||
|
||||
const configFields = {
|
||||
volume: Object.keys(volumeExample),
|
||||
identification: Object.keys(identificationExample)
|
||||
};
|
||||
|
||||
const state = {
|
||||
configType: "volume",
|
||||
imagePaths: { csv: null, json: null },
|
||||
@@ -33,7 +38,9 @@ const state = {
|
||||
defaultDeviceId: "",
|
||||
review: null,
|
||||
retryDeviceId: null,
|
||||
notificationDeviceId: null,
|
||||
lightbox: { mediaType: null, scale: 1, fit: true, previousFocus: null },
|
||||
notifications: [],
|
||||
connected: false
|
||||
};
|
||||
|
||||
@@ -66,12 +73,14 @@ const elements = {
|
||||
openImage: document.querySelector('[data-open-plot="json"]')
|
||||
}
|
||||
},
|
||||
configEditor: document.querySelector("#config-editor"),
|
||||
configForm: document.querySelector("#config-form"),
|
||||
configLabel: document.querySelector("#config-label"),
|
||||
configPath: document.querySelector("#config-path"),
|
||||
publishTarget: document.querySelector("#publish-target"),
|
||||
publishButton: document.querySelector("#publish-config"),
|
||||
publishResult: document.querySelector("#publish-result"),
|
||||
configNotifications: document.querySelector("#config-notifications"),
|
||||
configNotificationBadge: document.querySelector("#config-notification-badge"),
|
||||
lineCompany: document.querySelector("#line-company"),
|
||||
licenseTarget: document.querySelector("#license-target"),
|
||||
licenseList: document.querySelector("#license-list"),
|
||||
@@ -87,6 +96,14 @@ const elements = {
|
||||
reviewTarget: document.querySelector("#review-target"),
|
||||
approveReview: document.querySelector("#approve-review"),
|
||||
rejectReview: document.querySelector("#reject-review"),
|
||||
actionDialog: document.querySelector("#action-dialog"),
|
||||
actionDialogForm: document.querySelector("#action-dialog-form"),
|
||||
actionDialogTitle: document.querySelector("#action-dialog-title"),
|
||||
actionDialogMessage: document.querySelector("#action-dialog-message"),
|
||||
actionDialogInput: document.querySelector("#action-dialog-input"),
|
||||
actionDialogError: document.querySelector("#action-dialog-error"),
|
||||
actionDialogCancel: document.querySelector("#action-dialog-cancel"),
|
||||
actionDialogConfirm: document.querySelector("#action-dialog-confirm"),
|
||||
lightbox: document.querySelector("#image-lightbox"),
|
||||
lightboxTitle: document.querySelector("#lightbox-title"),
|
||||
lightboxImage: document.querySelector("#lightbox-image"),
|
||||
@@ -225,6 +242,11 @@ function renderLineOptions() {
|
||||
function updateSelectedTarget() {
|
||||
const company = selectedCompany();
|
||||
const line = selectedLine();
|
||||
if (state.notificationDeviceId !== elements.deviceId.value) {
|
||||
state.notificationDeviceId = elements.deviceId.value;
|
||||
state.notifications = [];
|
||||
renderNotifications();
|
||||
}
|
||||
elements.licenseTarget.value = company && line ? `${company.name} / ${line.name}` : "";
|
||||
void syncConnection();
|
||||
}
|
||||
@@ -267,7 +289,7 @@ async function refreshModels() {
|
||||
if (!result) return;
|
||||
state.models = result.fileList;
|
||||
elements.modelList.innerHTML = state.models.map((model) => `
|
||||
<tr><td>${escapeHtml(model.fileName)}</td><td>${escapeHtml(model.uploadTime || "-")}</td>
|
||||
<tr><td>${escapeHtml(model.fileName)}</td><td>${escapeHtml(model.originalFileName || model.fileName)}</td><td>${escapeHtml(model.uploadTime || "-")}</td>
|
||||
<td>${formatSize(model.size)}</td><td><button class="table-action" data-model-download="${escapeHtml(model.fileID)}">下载</button><button class="table-action danger" data-model-delete="${escapeHtml(model.fileID)}">删除</button></td></tr>
|
||||
`).join("");
|
||||
elements.modelEmpty.hidden = state.models.length > 0;
|
||||
@@ -332,6 +354,65 @@ function showError(error) {
|
||||
elements.publishResult.dataset.tone = "error";
|
||||
}
|
||||
|
||||
let actionDialogState = null;
|
||||
|
||||
function closeActionDialog(value) {
|
||||
if (!actionDialogState) return;
|
||||
const { resolve, previousFocus } = actionDialogState;
|
||||
actionDialogState = null;
|
||||
elements.actionDialog.hidden = true;
|
||||
elements.actionDialogForm.reset();
|
||||
elements.actionDialogError.hidden = true;
|
||||
previousFocus?.focus();
|
||||
resolve(value);
|
||||
}
|
||||
|
||||
function requestModelName({ title, message, value = "", confirmLabel = "确认", danger = false, expectedValue = null }) {
|
||||
if (actionDialogState) closeActionDialog(null);
|
||||
elements.actionDialogTitle.textContent = title;
|
||||
elements.actionDialogMessage.textContent = message;
|
||||
elements.actionDialogInput.value = value;
|
||||
elements.actionDialogConfirm.textContent = confirmLabel;
|
||||
elements.actionDialogConfirm.classList.toggle("primary", !danger);
|
||||
elements.actionDialogConfirm.classList.toggle("danger", danger);
|
||||
elements.actionDialogError.hidden = true;
|
||||
elements.actionDialog.hidden = false;
|
||||
const previousFocus = document.activeElement;
|
||||
window.requestAnimationFrame(() => {
|
||||
elements.actionDialogInput.focus();
|
||||
elements.actionDialogInput.select();
|
||||
});
|
||||
return new Promise((resolve) => {
|
||||
actionDialogState = { resolve, previousFocus, expectedValue };
|
||||
});
|
||||
}
|
||||
|
||||
elements.actionDialogForm.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const value = elements.actionDialogInput.value.trim();
|
||||
const expectedValue = actionDialogState?.expectedValue;
|
||||
if (!value) {
|
||||
elements.actionDialogError.textContent = "文件名不能为空";
|
||||
elements.actionDialogError.hidden = false;
|
||||
elements.actionDialogInput.focus();
|
||||
return;
|
||||
}
|
||||
if (expectedValue !== null && value !== expectedValue) {
|
||||
elements.actionDialogError.textContent = "文件名不匹配,请输入完整文件名";
|
||||
elements.actionDialogError.hidden = false;
|
||||
elements.actionDialogInput.focus();
|
||||
return;
|
||||
}
|
||||
closeActionDialog(value);
|
||||
});
|
||||
elements.actionDialogCancel.addEventListener("click", () => closeActionDialog(null));
|
||||
elements.actionDialog.addEventListener("click", (event) => {
|
||||
if (event.target === elements.actionDialog) closeActionDialog(null);
|
||||
});
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Escape" && !elements.actionDialog.hidden) closeActionDialog(null);
|
||||
});
|
||||
|
||||
function showImage(result) {
|
||||
if (!result) return;
|
||||
const mediaType = result.mediaType === "json" || result.fileName?.toLowerCase().endsWith(".json")
|
||||
@@ -413,16 +494,91 @@ function activateTab(target) {
|
||||
}
|
||||
|
||||
function activateConfigType(configType) {
|
||||
try {
|
||||
state.configs[state.configType] = JSON.parse(elements.configEditor.value);
|
||||
} catch (_error) {
|
||||
// Keep the last valid configuration when changing views.
|
||||
}
|
||||
syncCurrentConfig();
|
||||
state.configType = configType;
|
||||
document.querySelectorAll(".segment").forEach((item) => item.classList.toggle("active", item.dataset.type === configType));
|
||||
renderConfig();
|
||||
}
|
||||
|
||||
function isPowerOfTwo(value) {
|
||||
return Number.isInteger(value) && value >= 2 && (value & (value - 1)) === 0;
|
||||
}
|
||||
|
||||
function clearConfigErrors() {
|
||||
elements.configForm.querySelectorAll("[aria-invalid]").forEach((input) => input.removeAttribute("aria-invalid"));
|
||||
elements.configForm.querySelectorAll(".config-field-error").forEach((item) => item.remove());
|
||||
}
|
||||
|
||||
function showConfigFieldError(field, message) {
|
||||
const input = elements.configForm.querySelector(`[data-config-field="${field}"]`);
|
||||
if (!input) return;
|
||||
input.setAttribute("aria-invalid", "true");
|
||||
const error = document.createElement("p");
|
||||
error.className = "config-field-error";
|
||||
error.textContent = message;
|
||||
input.closest(".config-field").append(error);
|
||||
}
|
||||
|
||||
function readConfigForm({ showErrors = false } = {}) {
|
||||
const type = state.configType;
|
||||
const parameters = {};
|
||||
let invalidField = null;
|
||||
let invalidMessage = null;
|
||||
clearConfigErrors();
|
||||
for (const field of configFields[type]) {
|
||||
const input = elements.configForm.querySelector(`[data-config-field="${field}"]`);
|
||||
const text = input?.value.trim() || "";
|
||||
if (field === "levels") {
|
||||
const values = text.split(",").map((value) => value.trim()).filter(Boolean);
|
||||
parameters[field] = values.map(Number);
|
||||
if (!values.length || parameters[field].some((value) => !Number.isFinite(value))) {
|
||||
invalidField = field;
|
||||
invalidMessage = "请输入以逗号分隔的有效数字。";
|
||||
} else if (!isPowerOfTwo(parameters[field].length)) {
|
||||
invalidField = field;
|
||||
invalidMessage = "元素个数必须是不小于 2 的 2 的整数次幂。";
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const value = Number(text);
|
||||
parameters[field] = value;
|
||||
if (!text || !Number.isFinite(value)) {
|
||||
invalidField = field;
|
||||
invalidMessage = "请输入有效数字。";
|
||||
} else if (["num_runs", "n_order", "repeat"].includes(field) && !Number.isInteger(value)) {
|
||||
invalidField = field;
|
||||
invalidMessage = "请输入整数。";
|
||||
}
|
||||
}
|
||||
if (invalidField) {
|
||||
if (showErrors) showConfigFieldError(invalidField, invalidMessage);
|
||||
throw new Error(`${invalidField}:${invalidMessage}`);
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
|
||||
function syncCurrentConfig() {
|
||||
try {
|
||||
state.configs[state.configType] = readConfigForm();
|
||||
} catch (_error) {
|
||||
// Preserve the last valid values until the user corrects the visible form.
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeImportedConfig(parameters) {
|
||||
if (!parameters || typeof parameters !== "object" || Array.isArray(parameters)) {
|
||||
throw new Error("导入配置必须是 JSON 对象");
|
||||
}
|
||||
const fields = configFields[state.configType];
|
||||
const unknown = Object.keys(parameters).filter((field) => !fields.includes(field));
|
||||
if (unknown.length) throw new Error(`导入配置包含未知字段:${unknown.join(", ")}`);
|
||||
const normalized = { ...state.configs[state.configType] };
|
||||
for (const field of fields) {
|
||||
if (parameters[field] !== undefined) normalized[field] = parameters[field];
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function switchToIdentificationConfigForRetry() {
|
||||
if (!state.review) return;
|
||||
state.retryDeviceId = state.review.deviceId;
|
||||
@@ -464,11 +620,16 @@ async function submitRetryReview() {
|
||||
|
||||
function renderConfig() {
|
||||
const isVolume = state.configType === "volume";
|
||||
elements.configEditor.value = JSON.stringify(state.configs[state.configType], null, 2);
|
||||
const config = state.configs[state.configType];
|
||||
elements.configForm.innerHTML = configFields[state.configType].map((field) => {
|
||||
const value = field === "levels" ? config[field].join(", ") : config[field];
|
||||
const integer = ["num_runs", "n_order", "repeat"].includes(field);
|
||||
return `<div class="config-field"><label for="config-${field}">${field}</label><input id="config-${field}" data-config-field="${field}" type="${field === "levels" ? "text" : "number"}"${field === "levels" ? "" : ` step="${integer ? "1" : "any"}"` } value="${escapeHtml(value)}" required></div>`;
|
||||
}).join("");
|
||||
elements.configLabel.textContent = isVolume ? "容积测量配置" : "系统辨识配置";
|
||||
elements.publishTarget.textContent = isVolume ? "Server 配置文件" : "设备辨识配置";
|
||||
elements.publishButton.textContent = isVolume ? "上传容积配置" : "发布辨识配置";
|
||||
elements.configPath.textContent = "可直接编辑,或从本地 JSON 导入";
|
||||
elements.configPath.textContent = "字段名称固定;可填写右侧数据或从本地 JSON 导入";
|
||||
elements.publishResult.textContent = "等待操作";
|
||||
delete elements.publishResult.dataset.tone;
|
||||
}
|
||||
@@ -604,20 +765,29 @@ document.querySelector("#upload-model").addEventListener("click", async () => {
|
||||
state.models = models.fileList;
|
||||
const selected = await runBusy("正在选择模型文件", () => window.reinloop.chooseModelUploadFile());
|
||||
if (!selected) return;
|
||||
const existing = state.models.find((model) => model.fileName === selected.fileName);
|
||||
const modelName = await requestModelName({
|
||||
title: "设置服务器文件名",
|
||||
message: `已选择 ${selected.fileName}。可在上传前修改模型在服务器上的文件名。`,
|
||||
value: selected.fileName,
|
||||
confirmLabel: "继续上传"
|
||||
});
|
||||
if (modelName === null) return;
|
||||
const existing = state.models.find((model) => model.fileName === modelName);
|
||||
let overwrite = false;
|
||||
if (existing) {
|
||||
if (!window.confirm(`已存在同名模型 ${selected.fileName},覆盖后无法恢复。是否继续?`)) return;
|
||||
const confirmation = window.prompt(`请输入完整文件名以确认覆盖:${selected.fileName}`);
|
||||
if (confirmation !== selected.fileName) {
|
||||
setStatus("文件名不匹配,已取消覆盖", "idle");
|
||||
return;
|
||||
}
|
||||
const confirmation = await requestModelName({
|
||||
title: "确认覆盖模型",
|
||||
message: `服务器已存在 ${modelName},覆盖后无法恢复。请输入完整文件名以确认。`,
|
||||
confirmLabel: "覆盖并上传",
|
||||
danger: true,
|
||||
expectedValue: modelName
|
||||
});
|
||||
if (confirmation === null) return;
|
||||
overwrite = true;
|
||||
}
|
||||
const result = await runBusy("正在上传模型", () => window.reinloop.uploadModel({
|
||||
deviceId: elements.deviceId.value, sourcePath: selected.sourcePath, fileName: selected.fileName,
|
||||
overwrite, credentials: credentials()
|
||||
modelName, overwrite, credentials: credentials()
|
||||
}));
|
||||
if (result) {
|
||||
setStatus(overwrite ? "模型已覆盖" : "模型已上传", "success");
|
||||
@@ -628,25 +798,33 @@ document.querySelector("#upload-model").addEventListener("click", async () => {
|
||||
}
|
||||
});
|
||||
elements.modelList.addEventListener("click", async (event) => {
|
||||
const fileID = event.target.dataset.modelDownload || event.target.dataset.modelDelete;
|
||||
const button = event.target.closest("button");
|
||||
if (!button || !elements.modelList.contains(button)) return;
|
||||
const fileID = button.dataset.modelDownload || button.dataset.modelDelete;
|
||||
if (!fileID) return;
|
||||
const model = state.models.find((item) => item.fileID === fileID);
|
||||
if (event.target.dataset.modelDownload) {
|
||||
if (!model) return showError(new Error("模型记录已变化,请刷新列表后重试"));
|
||||
if (button.dataset.modelDownload) {
|
||||
const result = await runBusy("正在下载模型", () => window.reinloop.downloadModel({ fileID, fileName: model.fileName, credentials: credentials() }));
|
||||
if (result) setStatus(`模型已下载: ${result.filePath}`, "success");
|
||||
} else {
|
||||
if (!window.confirm(`确认删除模型 ${model.fileName}?`)) return;
|
||||
const confirmation = window.prompt(`删除不可恢复。请输入完整文件名以确认:${model.fileName}`);
|
||||
if (confirmation !== model.fileName) {
|
||||
setStatus("文件名不匹配,已取消删除", "idle");
|
||||
return;
|
||||
}
|
||||
event.target.disabled = true;
|
||||
const confirmation = await requestModelName({
|
||||
title: "确认删除模型",
|
||||
message: `删除 ${model.fileName} 后无法恢复。请输入完整文件名以确认。`,
|
||||
confirmLabel: "永久删除",
|
||||
danger: true,
|
||||
expectedValue: model.fileName
|
||||
});
|
||||
if (confirmation === null) return;
|
||||
button.disabled = true;
|
||||
try {
|
||||
const result = await runBusy("正在删除模型", () => window.reinloop.deleteModel({ fileID, credentials: credentials() }));
|
||||
if (result) await refreshModels();
|
||||
if (result) {
|
||||
await refreshModels();
|
||||
setStatus("模型已删除", "success");
|
||||
}
|
||||
} finally {
|
||||
event.target.disabled = false;
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -688,8 +866,13 @@ elements.identificationFileList.addEventListener("click", async (event) => {
|
||||
document.querySelector("#import-config").addEventListener("click", async () => {
|
||||
const result = await runBusy("正在导入配置", () => window.reinloop.chooseConfig());
|
||||
if (!result) return;
|
||||
state.configs[state.configType] = result.parameters;
|
||||
elements.configEditor.value = JSON.stringify(result.parameters, null, 2);
|
||||
try {
|
||||
state.configs[state.configType] = normalizeImportedConfig(result.parameters);
|
||||
renderConfig();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return;
|
||||
}
|
||||
elements.configPath.textContent = result.filePath;
|
||||
setStatus("配置已导入", "success");
|
||||
});
|
||||
@@ -700,8 +883,13 @@ document.querySelector("#load-server").addEventListener("click", async () => {
|
||||
credentials: credentials()
|
||||
}));
|
||||
if (!parameters) return;
|
||||
state.configs[state.configType] = parameters;
|
||||
elements.configEditor.value = JSON.stringify(parameters, null, 2);
|
||||
try {
|
||||
state.configs[state.configType] = normalizeImportedConfig(parameters);
|
||||
renderConfig();
|
||||
} catch (error) {
|
||||
showError(new Error(`Server 配置无效:${error.message}`));
|
||||
return;
|
||||
}
|
||||
elements.publishResult.textContent = "已读取当前 Server 配置";
|
||||
elements.publishResult.dataset.tone = "success";
|
||||
setStatus("读取完成", "success");
|
||||
@@ -710,9 +898,9 @@ document.querySelector("#load-server").addEventListener("click", async () => {
|
||||
elements.publishButton.addEventListener("click", async () => {
|
||||
let parameters;
|
||||
try {
|
||||
parameters = JSON.parse(elements.configEditor.value);
|
||||
parameters = readConfigForm({ showErrors: true });
|
||||
} catch (error) {
|
||||
showError(new Error(`JSON 格式错误: ${error.message}`));
|
||||
showError(error);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -732,6 +920,10 @@ elements.publishButton.addEventListener("click", async () => {
|
||||
? `${result.message}: ${result.storagePath}`
|
||||
: result.message;
|
||||
elements.publishResult.dataset.tone = "success";
|
||||
if (state.configType === "volume") {
|
||||
const notification = state.notifications.find((item) => item.type === "volume_request_started");
|
||||
if (notification) void acknowledgeNotification(notification);
|
||||
}
|
||||
if (state.configType === "identification" && state.retryDeviceId) {
|
||||
await submitRetryReview();
|
||||
} else {
|
||||
@@ -831,3 +1023,71 @@ elements.controlFileList.addEventListener("click", async (event) => {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function renderNotifications() {
|
||||
elements.configNotificationBadge.hidden = state.notifications.length === 0;
|
||||
elements.configNotificationBadge.textContent = String(state.notifications.length);
|
||||
elements.configNotifications.innerHTML = state.notifications.map((notification) => {
|
||||
const action = notification.type === "volume_request_started"
|
||||
? "处理配置"
|
||||
: notification.type === "volume_result_ready"
|
||||
? "查看结果"
|
||||
: "查看绘图";
|
||||
const secondaryAction = notification.type === "identification_result_ready" ? "查看辨识数据" : "";
|
||||
return `<article class="panel-notification" data-notification-id="${escapeHtml(notification.notificationId)}" data-type="${escapeHtml(notification.type)}"><div class="notification-copy"><strong>${escapeHtml(notification.title)}</strong><span>${escapeHtml(notification.message)}</span></div><div class="notification-actions"><button class="button secondary" data-notification-action="primary" data-notification-id="${escapeHtml(notification.notificationId)}">${action}</button>${secondaryAction ? `<button class="button secondary" data-notification-action="secondary" data-notification-id="${escapeHtml(notification.notificationId)}">${secondaryAction}</button>` : ""}<button class="button icon" title="关闭提醒" aria-label="关闭提醒" data-notification-action="close" data-notification-id="${escapeHtml(notification.notificationId)}">x</button></div></article>`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
async function acknowledgeNotification(notification) {
|
||||
const result = await runBusy("正在确认提醒", () => window.reinloop.acknowledgeNotification({
|
||||
deviceId: notification.deviceId,
|
||||
notificationId: notification.notificationId,
|
||||
credentials: credentials()
|
||||
}));
|
||||
if (!result) return false;
|
||||
state.notifications = state.notifications.filter((item) => item.notificationId !== notification.notificationId);
|
||||
renderNotifications();
|
||||
return true;
|
||||
}
|
||||
|
||||
async function handleNotificationAction(notification, action) {
|
||||
if (action === "close") {
|
||||
await acknowledgeNotification(notification);
|
||||
return;
|
||||
}
|
||||
if (notification.type === "volume_request_started") {
|
||||
activateTab("config-panel");
|
||||
activateConfigType("volume");
|
||||
elements.configForm.querySelector("input")?.focus();
|
||||
return;
|
||||
}
|
||||
if (notification.type === "volume_result_ready") {
|
||||
const result = await runBusy("正在打开容积测试结果", () => window.reinloop.openNotificationFile({
|
||||
fileID: notification.fileID,
|
||||
credentials: credentials()
|
||||
}));
|
||||
if (result) setStatus(`已打开结果文件:${result.filePath}`, "success");
|
||||
return;
|
||||
}
|
||||
if (action === "primary") {
|
||||
activateTab("plot-panel");
|
||||
return;
|
||||
}
|
||||
activateTab("identification-data-panel");
|
||||
await refreshIdentificationFiles();
|
||||
}
|
||||
|
||||
elements.configNotifications.addEventListener("click", (event) => {
|
||||
const button = event.target.closest("button[data-notification-id]");
|
||||
if (!button) return;
|
||||
const notification = state.notifications.find((item) => item.notificationId === button.dataset.notificationId);
|
||||
if (notification) void handleNotificationAction(notification, button.dataset.notificationAction);
|
||||
});
|
||||
|
||||
window.reinloop.onPanelNotification((notification) => {
|
||||
if (!notification?.notificationId || notification.deviceId !== elements.deviceId.value) return;
|
||||
state.notificationDeviceId = notification.deviceId;
|
||||
if (state.notifications.some((item) => item.notificationId === notification.notificationId)) return;
|
||||
state.notifications.push(notification);
|
||||
renderNotifications();
|
||||
});
|
||||
@@ -124,6 +124,7 @@ input:focus, select:focus, textarea:focus { border-color: var(--green); box-shad
|
||||
font-weight: 700;
|
||||
}
|
||||
.tab.active { color: var(--green-dark); border-bottom-color: var(--green); }
|
||||
.tab-badge { display: inline-grid; min-width: 18px; height: 18px; place-items: center; margin-left: 5px; padding: 0 5px; border-radius: 9px; color: white; background: var(--red); font-size: 11px; }
|
||||
|
||||
.panel { display: none; padding-top: 22px; }
|
||||
.panel.active { display: block; animation: reveal 180ms ease-out; }
|
||||
@@ -189,26 +190,24 @@ input:focus, select:focus, textarea:focus { border-color: var(--green); box-shad
|
||||
.segmented { display: flex; padding: 3px; background: #dfe5e1; border: 1px solid #c6d0ca; border-radius: 4px; }
|
||||
.segment { height: 34px; padding: 0 16px; border: 0; border-radius: 3px; background: transparent; color: var(--muted); font-weight: 700; }
|
||||
.segment.active { background: white; color: var(--green-dark); box-shadow: 0 1px 3px rgba(21, 37, 31, 0.14); }
|
||||
.notification-stack { display: grid; gap: 8px; margin: 0 0 16px; }
|
||||
.panel-notification { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 16px; align-items: center; padding: 12px 14px; border: 1px solid #d6b362; border-left: 4px solid var(--amber); background: #fff8e6; }
|
||||
.panel-notification[data-type="volume_result_ready"] { border-color: #8ebba5; border-left-color: var(--green); background: #edf8f1; }
|
||||
.panel-notification[data-type="identification_result_ready"] { border-color: #9db6c8; border-left-color: #367294; background: #edf5fa; }
|
||||
.notification-copy { display: grid; gap: 3px; min-width: 0; }
|
||||
.notification-copy strong { font-size: 13px; }
|
||||
.notification-copy span { color: var(--muted); font-size: 12px; overflow-wrap: anywhere; }
|
||||
.notification-actions { display: flex; gap: 8px; }
|
||||
.editor-layout { display: grid; grid-template-columns: minmax(0, 1fr) 270px; gap: 18px; }
|
||||
.editor-column, .publish-aside { background: var(--surface); border: 1px solid var(--line); }
|
||||
.editor-toolbar { height: 46px; padding: 0 14px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--line); font-size: 13px; font-weight: 700; }
|
||||
.text-button { border: 0; background: transparent; color: var(--green); font-size: 13px; font-weight: 700; }
|
||||
textarea {
|
||||
display: block;
|
||||
width: calc(100% - 28px);
|
||||
height: calc(100vh - 385px);
|
||||
min-height: 330px;
|
||||
margin: 14px;
|
||||
padding: 16px;
|
||||
resize: vertical;
|
||||
border: 1px solid #bec9c2;
|
||||
border-radius: 3px;
|
||||
background: #f8faf8;
|
||||
color: #18392d;
|
||||
font: 14px/1.65 Consolas, "Microsoft YaHei UI", monospace;
|
||||
tab-size: 2;
|
||||
outline: none;
|
||||
}
|
||||
.config-form { display: grid; gap: 10px; padding: 14px; }
|
||||
.config-field { display: grid; grid-template-columns: minmax(160px, 0.42fr) minmax(0, 1fr); align-items: center; gap: 12px; }
|
||||
.config-field label { color: var(--muted); font: 13px Consolas, monospace; font-weight: 700; }
|
||||
.config-field input { width: 100%; }
|
||||
.config-field-error { grid-column: 2; margin: -4px 0 0; color: var(--red); font-size: 12px; }
|
||||
.config-field input[aria-invalid="true"] { border-color: var(--red); box-shadow: 0 0 0 2px rgba(173, 52, 45, 0.12); }
|
||||
.editor-column > .file-path { padding: 0 14px 12px; }
|
||||
.publish-aside { padding: 20px; align-self: start; }
|
||||
.publish-aside h3 { padding-bottom: 14px; border-bottom: 1px solid var(--line); }
|
||||
@@ -238,6 +237,16 @@ td:last-child { white-space: nowrap; }
|
||||
.empty-row { padding: 30px; color: var(--muted); text-align: center; font-size: 13px; }
|
||||
.detail-view { margin: 0; padding: 16px; max-height: 260px; overflow: auto; background: #18251f; color: #d9e9df; font: 12px/1.6 Consolas, monospace; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
|
||||
.action-dialog { position: fixed; inset: 0; z-index: 30; display: grid; place-items: center; padding: 24px; background: rgba(10, 20, 16, 0.68); }
|
||||
.action-dialog-shell { width: min(520px, 100%); padding: 24px; display: grid; gap: 17px; background: var(--surface); border: 1px solid #9aa9a1; border-top: 4px solid var(--green); box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3); }
|
||||
.action-dialog-head { display: grid; gap: 2px; }
|
||||
.action-dialog-message { color: var(--muted); font-size: 13px; line-height: 1.65; overflow-wrap: anywhere; }
|
||||
.action-dialog-field { display: grid; gap: 7px; }
|
||||
.action-dialog-field span { color: var(--muted); font-size: 12px; font-weight: 700; }
|
||||
.action-dialog-field input { width: 100%; }
|
||||
.action-dialog-error { color: var(--red); font-size: 12px; }
|
||||
.action-dialog-actions { display: flex; justify-content: end; gap: 8px; padding-top: 3px; }
|
||||
|
||||
.lightbox { position: fixed; inset: 0; z-index: 20; padding: 24px; background: rgba(10, 20, 16, 0.78); }
|
||||
.lightbox-shell { height: 100%; display: grid; grid-template-rows: auto minmax(0, 1fr); background: var(--surface); border: 1px solid #9aa9a1; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.35); }
|
||||
.lightbox-toolbar { min-height: 58px; padding: 10px 14px; display: flex; align-items: center; justify-content: space-between; gap: 16px; border-bottom: 1px solid var(--line); }
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
function createModelHandlers({ callServer, fetchImpl = fetch }) {
|
||||
return {
|
||||
list(request) {
|
||||
return callServer({
|
||||
type: "listModels",
|
||||
folder: `${request.deviceId}/model_config`
|
||||
}, request.credentials);
|
||||
},
|
||||
|
||||
async upload(request) {
|
||||
if (!request.sourcePath || !request.fileName) throw new Error("请先选择模型文件");
|
||||
const sourcePath = path.resolve(request.sourcePath);
|
||||
const fileName = path.basename(request.fileName);
|
||||
const modelName = path.basename(request.modelName || fileName);
|
||||
await fs.promises.access(sourcePath, fs.constants.R_OK);
|
||||
const issued = await callServer({
|
||||
type: "issueModelUpload",
|
||||
deviceId: request.deviceId,
|
||||
fileName,
|
||||
modelName,
|
||||
overwrite: request.overwrite === true
|
||||
}, request.credentials);
|
||||
const form = new FormData();
|
||||
form.append("file", new Blob([await fs.promises.readFile(sourcePath)]), fileName);
|
||||
const response = await fetchImpl(issued.uploadMetadata.url, { method: "POST", body: form });
|
||||
if (![200, 204].includes(response.status)) throw new Error(`模型上传失败: HTTP ${response.status}`);
|
||||
return {
|
||||
success: true,
|
||||
fileID: issued.fileID,
|
||||
fileName: issued.fileName,
|
||||
originalFileName: issued.originalFileName
|
||||
};
|
||||
},
|
||||
|
||||
delete(request) {
|
||||
return callServer({ type: "deleteModel", fileID: request.fileID }, request.credentials);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createModelHandlers };
|
||||
@@ -0,0 +1,59 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
const test = require("node:test");
|
||||
const { createModelHandlers } = require("../model-handlers");
|
||||
const { callServer } = require("../server-client");
|
||||
const { createApp } = require("../../server/src/app");
|
||||
const { JsonStore } = require("../../server/src/store");
|
||||
|
||||
test("panel model kernel renames, overwrites, lists both names, and deletes on the server", async (context) => {
|
||||
const dataDirectory = await fs.promises.mkdtemp(path.join(os.tmpdir(), "reinloop-panel-server-"));
|
||||
const store = new JsonStore(dataDirectory);
|
||||
await store.initialize();
|
||||
const app = createApp({ store, adminToken: "test-token" });
|
||||
const server = await new Promise((resolve) => {
|
||||
const listeningServer = app.listen(0, "127.0.0.1", () => resolve(listeningServer));
|
||||
});
|
||||
context.after(async () => {
|
||||
await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
|
||||
await fs.promises.rm(dataDirectory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const credentials = {
|
||||
apiUrl: `http://127.0.0.1:${server.address().port}`,
|
||||
adminToken: "test-token"
|
||||
};
|
||||
const handlers = createModelHandlers({ callServer });
|
||||
const sourcePath = path.join(dataDirectory, "controller-original.bin");
|
||||
const request = {
|
||||
deviceId: "company-a/line-1",
|
||||
sourcePath,
|
||||
fileName: "controller-original.bin",
|
||||
modelName: "pressure-controller.bin",
|
||||
credentials
|
||||
};
|
||||
|
||||
await fs.promises.writeFile(sourcePath, "first-version");
|
||||
const uploaded = await handlers.upload(request);
|
||||
assert.equal(uploaded.fileName, "pressure-controller.bin");
|
||||
assert.equal(uploaded.originalFileName, "controller-original.bin");
|
||||
|
||||
await fs.promises.writeFile(sourcePath, "second-version");
|
||||
const overwritten = await handlers.upload({ ...request, overwrite: true });
|
||||
assert.equal(overwritten.fileID, uploaded.fileID);
|
||||
|
||||
const listed = await handlers.list({ deviceId: request.deviceId, credentials });
|
||||
assert.equal(listed.fileList.length, 1);
|
||||
assert.equal(listed.fileList[0].fileName, "pressure-controller.bin");
|
||||
assert.equal(listed.fileList[0].originalFileName, "controller-original.bin");
|
||||
|
||||
const deleted = await handlers.delete({ fileID: overwritten.fileID, credentials });
|
||||
assert.equal(deleted.deletedCount, 1);
|
||||
const afterDelete = await handlers.list({ deviceId: request.deviceId, credentials });
|
||||
assert.deepEqual(afterDelete.fileList, []);
|
||||
await assert.rejects(fs.promises.access(
|
||||
path.join(dataDirectory, "models", "company-a", "line-1", "pressure-controller.bin")
|
||||
), { code: "ENOENT" });
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
const test = require("node:test");
|
||||
const { createModelHandlers } = require("../model-handlers");
|
||||
|
||||
test("panel model kernel renames, overwrites, and deletes by fileID", async (context) => {
|
||||
const directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), "reinloop-panel-model-"));
|
||||
context.after(() => fs.promises.rm(directory, { recursive: true, force: true }));
|
||||
const sourcePath = path.join(directory, "controller-original.bin");
|
||||
await fs.promises.writeFile(sourcePath, "first-version");
|
||||
|
||||
const records = new Map();
|
||||
const requests = [];
|
||||
const callServer = async (payload) => {
|
||||
requests.push(payload);
|
||||
if (payload.type === "issueModelUpload") {
|
||||
const fileID = `model://${payload.deviceId}/${payload.modelName}`;
|
||||
if (records.has(fileID) && !payload.overwrite) throw new Error("文件已存在");
|
||||
records.set(fileID, {
|
||||
fileID,
|
||||
fileName: payload.modelName,
|
||||
originalFileName: payload.fileName
|
||||
});
|
||||
return { ...records.get(fileID), uploadMetadata: { url: `memory://${encodeURIComponent(fileID)}` } };
|
||||
}
|
||||
if (payload.type === "deleteModel") {
|
||||
const deleted = records.delete(payload.fileID);
|
||||
return { success: true, deletedCount: deleted ? 1 : 0 };
|
||||
}
|
||||
throw new Error(`unexpected request: ${payload.type}`);
|
||||
};
|
||||
const handlers = createModelHandlers({
|
||||
callServer,
|
||||
fetchImpl: async () => ({ status: 204 })
|
||||
});
|
||||
const request = {
|
||||
deviceId: "company-a/line-1",
|
||||
sourcePath,
|
||||
fileName: "controller-original.bin",
|
||||
modelName: "pressure-controller.bin",
|
||||
credentials: { adminToken: "test-token" }
|
||||
};
|
||||
|
||||
const uploaded = await handlers.upload(request);
|
||||
assert.equal(uploaded.fileName, "pressure-controller.bin");
|
||||
assert.equal(uploaded.originalFileName, "controller-original.bin");
|
||||
assert.equal(records.size, 1);
|
||||
assert.equal(requests[0].deviceId, request.deviceId);
|
||||
|
||||
await fs.promises.writeFile(sourcePath, "second-version");
|
||||
const overwritten = await handlers.upload({ ...request, overwrite: true });
|
||||
assert.equal(overwritten.fileID, uploaded.fileID);
|
||||
assert.equal(records.size, 1);
|
||||
|
||||
const deleted = await handlers.delete({ fileID: overwritten.fileID, credentials: request.credentials });
|
||||
assert.equal(deleted.deletedCount, 1);
|
||||
assert.equal(records.size, 0);
|
||||
assert.equal(requests.at(-1).type, "deleteModel");
|
||||
assert.equal(requests.at(-1).fileID, overwritten.fileID);
|
||||
});
|
||||
@@ -49,14 +49,14 @@ $env:B_ADMIN_TOKEN="your-admin-token"
|
||||
npm start
|
||||
```
|
||||
|
||||
默认服务地址为 `http://127.0.0.1:3000`,健康检查为 `http://127.0.0.1:3000/health`。业务请求可使用根路径或 `/api`。跨设备部署时,应使用服务器局域网 IP 或 HTTPS 域名,而不是 `127.0.0.1`。
|
||||
默认服务地址为 `http://127.0.0.1:3000`,健康检查为 `http://127.0.0.1:3000/health`。业务请求统一使用根路径。跨设备部署时,应使用服务器局域网 IP 或 HTTPS 域名,而不是 `127.0.0.1`。
|
||||
|
||||
### ControlPanel
|
||||
|
||||
```powershell
|
||||
cd ControlPanel
|
||||
npm install
|
||||
$env:REINLOOP_API_URL="http://server-address:3000/api"
|
||||
$env:REINLOOP_API_URL="http://server-address:3000"
|
||||
$env:B_ADMIN_TOKEN="your-admin-token"
|
||||
npm run gui
|
||||
```
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ base_url = os.environ.get(
|
||||
).rstrip("/")
|
||||
server_api_url = os.environ.get(
|
||||
"REINLOOP_API_URL",
|
||||
f"{base_url}/api",
|
||||
base_url,
|
||||
)
|
||||
# Compatibility alias used by existing modules. It points to the ReinLoop
|
||||
# Express server API, not a cloud-function endpoint.
|
||||
|
||||
@@ -5,11 +5,11 @@
|
||||
## 约定
|
||||
|
||||
- 业务服务端地址由 `REINLOOP_API_URL` 指定,未设置时使用
|
||||
`REINLOOP_SERVER_URL + /api`;默认地址为
|
||||
`https://ReinLoop.dominatedconvergence.com/api`。
|
||||
`REINLOOP_SERVER_URL`;默认地址为
|
||||
`https://ReinLoop.dominatedconvergence.com`。
|
||||
- 新许可证的设备标识为 `<company_code>/<production_line_code>`,在代码中通过
|
||||
`api.the_folder` 使用。旧许可证才回退到 `REINLOOP_DEVICE_ID`。
|
||||
- 所有服务端业务请求均使用 `POST /api`,通过请求体的 `type` 字段分发。
|
||||
- 所有服务端业务请求均使用 `POST /`,通过请求体的 `type` 字段分发。
|
||||
- 公司、产线、许可证签发/撤销、模型删除、审核反馈及配置提交均为
|
||||
ControlPanel 管理端能力,客户端不提供对应的管理接口。旧微信云函数和其管理脚本
|
||||
已移除。
|
||||
@@ -148,7 +148,7 @@ RL 模式下,`ControlEngine` 使用模型根据流量、当前压力和压力
|
||||
|
||||
## 客户端服务端协议
|
||||
|
||||
所有业务请求都发送至 `POST /api`。业务成功响应应至少包含 `success: true`。
|
||||
所有业务请求都发送至 `POST /`。业务成功响应应至少包含 `success: true`。
|
||||
|
||||
| `type` | 请求关键字段 | 用途 |
|
||||
| --- | --- | --- |
|
||||
|
||||
@@ -276,7 +276,7 @@ def _api_url():
|
||||
base_url = os.environ.get(
|
||||
"REINLOOP_SERVER_URL", "https://ReinLoop.dominatedconvergence.com"
|
||||
).rstrip("/")
|
||||
return os.environ.get("REINLOOP_API_URL", f"{base_url}/api")
|
||||
return os.environ.get("REINLOOP_API_URL", base_url)
|
||||
|
||||
|
||||
def _offline_limit_seconds():
|
||||
|
||||
@@ -14,7 +14,7 @@ MODULE_PATH = Path(__file__).resolve().parents[1] / "core" / "data_collector.py"
|
||||
def load_data_collector_module():
|
||||
api = types.ModuleType("api")
|
||||
api.base_url = "https://cloud.example"
|
||||
api.data_record_url = "https://cloud.example/api"
|
||||
api.data_record_url = "https://cloud.example"
|
||||
api.the_folder = "customer-a/line-1"
|
||||
requests = types.ModuleType("requests")
|
||||
|
||||
|
||||
@@ -30,12 +30,12 @@ class DeviceHeartbeatTests(unittest.TestCase):
|
||||
|
||||
requests_module.post = post
|
||||
api_module = types.ModuleType("api")
|
||||
api_module.data_record_url = "https://server.example/api"
|
||||
api_module.data_record_url = "https://server.example"
|
||||
api_module.the_folder = "company/line"
|
||||
with patch.dict(sys.modules, {"requests": requests_module, "api": api_module}):
|
||||
timestamp = HEARTBEAT.heartbeat_device(timeout=7)
|
||||
|
||||
self.assertEqual(timestamp, "2026-07-28T00:00:00.000Z")
|
||||
self.assertEqual(calls, [("https://server.example/api", {
|
||||
self.assertEqual(calls, [("https://server.example", {
|
||||
"type": "deviceHeartbeat", "deviceId": "company/line"
|
||||
}, 7)])
|
||||
+2
-2
@@ -2,7 +2,7 @@
|
||||
|
||||
## 通用约定
|
||||
|
||||
业务接口为 `POST /api`。请求与响应均为 JSON,响应包含 `success`。
|
||||
业务接口为 `POST /`。请求与响应均为 JSON,响应包含 `success`。
|
||||
|
||||
标注为 Admin 的接口需要附加:
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
| 方法 | 路径 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `POST` | `/api` | 主业务 API |
|
||||
| `POST` | `/` | 主业务 API |
|
||||
| `POST` | `/upload/:token` | 根据上传凭证接收 multipart 文件 |
|
||||
| `GET` | `/files/:fileID` | 下载已存储文件 |
|
||||
| `GET` | `/health` | 服务存活检查 |
|
||||
|
||||
@@ -98,8 +98,28 @@ CREATE TABLE IF NOT EXISTS volume_config_requests (
|
||||
PRIMARY KEY (device_id, request_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS volume_configs (
|
||||
device_id TEXT PRIMARY KEY,
|
||||
file_id TEXT NOT NULL,
|
||||
file_name TEXT NOT NULL,
|
||||
request_id TEXT NOT NULL,
|
||||
updated_at_ms BIGINT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS panel_notifications (
|
||||
notification_id TEXT PRIMARY KEY,
|
||||
device_id TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
request_id TEXT,
|
||||
file_id TEXT,
|
||||
created_at_ms BIGINT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS licenses_status_device_expiry_idx ON licenses (status, device_id, expiry_at);
|
||||
CREATE INDEX IF NOT EXISTS file_records_folder_idx ON file_records (folder);
|
||||
CREATE INDEX IF NOT EXISTS identification_files_device_upload_idx ON identification_files (device_id, upload_time DESC);
|
||||
CREATE INDEX IF NOT EXISTS identification_files_expires_idx ON identification_files (expires_at) WHERE expires_at IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS identification_feedback_device_idx ON identification_feedback (device_id);
|
||||
CREATE INDEX IF NOT EXISTS panel_notifications_device_created_idx ON panel_notifications (device_id, created_at_ms);
|
||||
+95
-10
@@ -318,6 +318,8 @@ function createApp({
|
||||
database.fileRecords = database.fileRecords.filter((record) => record.fileID !== fileID);
|
||||
database.panelInbox = database.panelInbox.filter((record) => record.fileID !== fileID);
|
||||
database.identificationFiles = database.identificationFiles.filter((record) => record.fileID !== fileID);
|
||||
database.volumeConfigs = database.volumeConfigs.filter((record) => record.fileID !== fileID);
|
||||
database.panelNotifications = database.panelNotifications.filter((record) => record.fileID !== fileID);
|
||||
return before - database.fileRecords.length;
|
||||
}
|
||||
|
||||
@@ -341,6 +343,21 @@ function createApp({
|
||||
}
|
||||
}
|
||||
|
||||
function addPanelNotification(database, { deviceId, type, title, message, requestId = null, fileID = null }) {
|
||||
const notification = {
|
||||
notificationId: store.createId("pn"),
|
||||
deviceId,
|
||||
type,
|
||||
title,
|
||||
message,
|
||||
requestId,
|
||||
fileID,
|
||||
createdAtMs: Date.now()
|
||||
};
|
||||
database.panelNotifications.push(notification);
|
||||
return notification;
|
||||
}
|
||||
|
||||
async function purgeExpiredIdentificationFiles() {
|
||||
return store.update(async (database) => {
|
||||
backfillIdentificationFiles(database);
|
||||
@@ -594,8 +611,9 @@ function createApp({
|
||||
}
|
||||
if (!records.length) return { success: false, errMsg: "数据库中未找到对应记录" };
|
||||
let deletedCount = 0;
|
||||
for (const record of records) deletedCount += await removeFile(database, record.fileID);
|
||||
return { success: true, deletedFileID: records.map((record) => record.fileID).join(", "), deletedCount };
|
||||
const fileIDs = [...new Set(records.map((record) => record.fileID))];
|
||||
for (const fileID of fileIDs) deletedCount += await removeFile(database, fileID);
|
||||
return { success: true, deletedFileID: fileIDs.join(", "), deletedCount };
|
||||
});
|
||||
}
|
||||
case "publishIdentificationConfig": {
|
||||
@@ -623,13 +641,19 @@ function createApp({
|
||||
return { ...result, parameters: event.parameters };
|
||||
}
|
||||
case "getVolumeConfigFile": {
|
||||
const folder = process.env.VOLUME_CONFIG_FOLDER || "volume_config";
|
||||
const fileID = `local://${BASE_FOLDER}/${folder}/volume_config.json`;
|
||||
const authError = requireAdmin(event);
|
||||
if (authError) return { success: false, errMsg: authError };
|
||||
const deviceId = normalizeDeviceId(event.deviceId);
|
||||
const database = await store.read();
|
||||
if (!database.fileRecords.some((record) => record.fileID === fileID)) {
|
||||
return { success: false, notFound: true, errMsg: "容积配置文件尚未发布" };
|
||||
}
|
||||
return { success: true, fileID, cloudPath: `${BASE_FOLDER}/${folder}/volume_config.json`, url: downloadUrl(req, fileID) };
|
||||
const config = database.volumeConfigs.find((item) => item.deviceId === deviceId);
|
||||
if (!config) return { success: true, found: false, deviceId };
|
||||
const record = database.fileRecords.find((item) => item.fileID === config.fileID);
|
||||
if (!record) return { success: true, found: false, deviceId };
|
||||
return {
|
||||
success: true, found: true, deviceId, fileID: record.fileID,
|
||||
fileName: record.fileName, url: downloadUrl(req, record.fileID),
|
||||
updatedAtMs: config.updatedAtMs, requestId: config.requestId
|
||||
};
|
||||
}
|
||||
case "getFunctionConfig": {
|
||||
if (event.configType !== "volume") return { success: false, errMsg: `未知 configType: ${event.configType}` };
|
||||
@@ -668,6 +692,33 @@ function createApp({
|
||||
url: downloadUrl(req, message.fileID)
|
||||
};
|
||||
}
|
||||
case "getPendingPanelNotification": {
|
||||
const authError = requireAdmin(event);
|
||||
if (authError) return { success: false, errMsg: authError };
|
||||
const deviceId = normalizeDeviceId(event.deviceId);
|
||||
const database = await store.read();
|
||||
const notification = database.panelNotifications.find((item) => item.deviceId === deviceId);
|
||||
return notification
|
||||
? { success: true, pending: true, notification }
|
||||
: { success: true, pending: false };
|
||||
}
|
||||
case "ackPanelNotification": {
|
||||
const authError = requireAdmin(event);
|
||||
if (authError) return { success: false, errMsg: authError };
|
||||
const deviceId = normalizeDeviceId(event.deviceId);
|
||||
const notificationId = String(event.notificationId || "");
|
||||
if (!notificationId) return { success: false, errMsg: "缺少 notificationId" };
|
||||
return store.update((database) => {
|
||||
const exists = database.panelNotifications.some((item) =>
|
||||
item.deviceId === deviceId && item.notificationId === notificationId
|
||||
);
|
||||
if (!exists) return { success: false, errMsg: "Panel 通知不存在" };
|
||||
database.panelNotifications = database.panelNotifications.filter((item) =>
|
||||
!(item.deviceId === deviceId && item.notificationId === notificationId)
|
||||
);
|
||||
return { success: true, notificationId };
|
||||
});
|
||||
}
|
||||
case "ackPanelFile": {
|
||||
const authError = requireAdmin(event);
|
||||
if (authError) return { success: false, errMsg: authError };
|
||||
@@ -859,6 +910,13 @@ function createApp({
|
||||
const createdAtMs = Date.now();
|
||||
const record = { deviceId, requestId: `${createdAtMs}-${randomUUID().slice(0, 10)}`, status: "waiting_upload", createdAtMs, expiresAtMs: createdAtMs + VOLUME_REQUEST_TTL_MS, configFileID: null, configFileName: null, uploadedAtMs: null, updateTime: new Date().toISOString() };
|
||||
database.volumeConfigRequests.push(record);
|
||||
addPanelNotification(database, {
|
||||
deviceId,
|
||||
type: "volume_request_started",
|
||||
title: "产线请求容积测试配置",
|
||||
message: "请完成容积测试配置并提交。",
|
||||
requestId: record.requestId
|
||||
});
|
||||
return { success: true, requestId: record.requestId, createdAtMs, expiresAtMs: record.expiresAtMs };
|
||||
});
|
||||
}
|
||||
@@ -890,6 +948,14 @@ function createApp({
|
||||
record.configFileName = fileName;
|
||||
record.uploadedAtMs = Date.now();
|
||||
record.updateTime = new Date().toISOString();
|
||||
database.volumeConfigs = database.volumeConfigs.filter((item) => item.deviceId !== deviceId);
|
||||
database.volumeConfigs.push({
|
||||
deviceId,
|
||||
fileID: fileRecord.fileID,
|
||||
fileName: fileRecord.fileName,
|
||||
requestId: record.requestId,
|
||||
updatedAtMs: record.uploadedAtMs
|
||||
});
|
||||
return { success: true, requestId: record.requestId, uploadedAtMs: record.uploadedAtMs };
|
||||
});
|
||||
}
|
||||
@@ -910,7 +976,10 @@ function createApp({
|
||||
if (!event.requestId) return { success: false, errMsg: "缺少 deviceId 或 requestId" };
|
||||
return store.update(async (database) => {
|
||||
const records = database.volumeConfigRequests.filter((item) => item.deviceId === deviceId && item.requestId === String(event.requestId));
|
||||
for (const record of records) if (record.configFileID) await removeFile(database, record.configFileID);
|
||||
for (const record of records) {
|
||||
const isLatest = database.volumeConfigs.some((item) => item.fileID === record.configFileID);
|
||||
if (record.configFileID && !isLatest) await removeFile(database, record.configFileID);
|
||||
}
|
||||
database.volumeConfigRequests = database.volumeConfigRequests.filter((item) => !records.includes(item));
|
||||
return { success: true, deleted: records.length };
|
||||
});
|
||||
@@ -955,6 +1024,23 @@ function createApp({
|
||||
processedAt: null,
|
||||
expiresAt: null
|
||||
});
|
||||
addPanelNotification(database, {
|
||||
deviceId,
|
||||
type: "identification_result_ready",
|
||||
title: "系统辨识结果已返回",
|
||||
message: "新的系统辨识 CSV 或 JSON 数据已进入暂存。",
|
||||
fileID: pending.fileID
|
||||
});
|
||||
}
|
||||
if (folderParts.at(-1) === "V_config" && extension === ".json") {
|
||||
const deviceId = normalizeDeviceId(folderParts.slice(0, -1).join("/"));
|
||||
addPanelNotification(database, {
|
||||
deviceId,
|
||||
type: "volume_result_ready",
|
||||
title: "容积测试结果已返回",
|
||||
message: "容积测试结果 JSON 已上传,可打开查看。",
|
||||
fileID: pending.fileID
|
||||
});
|
||||
}
|
||||
if (pending.configType && pending.parameters) {
|
||||
const config = {
|
||||
@@ -1025,7 +1111,6 @@ function createApp({
|
||||
}
|
||||
};
|
||||
app.post("/", apiHandler);
|
||||
app.post("/api", apiHandler);
|
||||
|
||||
app.use((error, req, res, next) => {
|
||||
console.error(error);
|
||||
|
||||
@@ -41,6 +41,8 @@ class PostgresStore {
|
||||
const identificationFiles = await queryable.query("SELECT file_id, device_id, file_name, media_type, upload_time, size_bytes, status, processed_at, expires_at FROM identification_files");
|
||||
const feedback = await queryable.query("SELECT device_id, run_id, file_name, status, result, update_time FROM identification_feedback");
|
||||
const requests = await queryable.query("SELECT device_id, request_id, status, created_at_ms, expires_at_ms, config_file_id, config_file_name, uploaded_at_ms, update_time FROM volume_config_requests");
|
||||
const volumeConfigs = await queryable.query("SELECT device_id, file_id, file_name, request_id, updated_at_ms FROM volume_configs");
|
||||
const panelNotifications = await queryable.query("SELECT notification_id, device_id, type, title, message, request_id, file_id, created_at_ms FROM panel_notifications");
|
||||
return {
|
||||
...structuredClone(EMPTY_DATABASE),
|
||||
companies: companies.rows.map((row) => ({ id: row.id, name: row.name, code: row.code, createdAt: asIso(row.created_at) })),
|
||||
@@ -51,7 +53,9 @@ class PostgresStore {
|
||||
panelInbox: panelInbox.rows.map((row) => ({ fileID: row.file_id, deviceId: row.device_id, fileName: row.file_name, mediaType: row.media_type, uploadTime: asIso(row.upload_time) })),
|
||||
identificationFiles: identificationFiles.rows.map((row) => ({ fileID: row.file_id, deviceId: row.device_id, fileName: row.file_name, mediaType: row.media_type, uploadTime: asIso(row.upload_time), size: Number(row.size_bytes), status: row.status, processedAt: row.processed_at && asIso(row.processed_at), expiresAt: row.expires_at && asIso(row.expires_at) })),
|
||||
identificationFeedback: feedback.rows.map((row) => ({ deviceId: row.device_id, runId: row.run_id, fileName: row.file_name, status: row.status, result: row.result, updateTime: asIso(row.update_time) })),
|
||||
volumeConfigRequests: requests.rows.map((row) => ({ deviceId: row.device_id, requestId: row.request_id, status: row.status, createdAtMs: Number(row.created_at_ms), expiresAtMs: Number(row.expires_at_ms), configFileID: row.config_file_id, configFileName: row.config_file_name, uploadedAtMs: row.uploaded_at_ms && Number(row.uploaded_at_ms), updateTime: asIso(row.update_time) }))
|
||||
volumeConfigRequests: requests.rows.map((row) => ({ deviceId: row.device_id, requestId: row.request_id, status: row.status, createdAtMs: Number(row.created_at_ms), expiresAtMs: Number(row.expires_at_ms), configFileID: row.config_file_id, configFileName: row.config_file_name, uploadedAtMs: row.uploaded_at_ms && Number(row.uploaded_at_ms), updateTime: asIso(row.update_time) })),
|
||||
volumeConfigs: volumeConfigs.rows.map((row) => ({ deviceId: row.device_id, fileID: row.file_id, fileName: row.file_name, requestId: row.request_id, updatedAtMs: Number(row.updated_at_ms) })),
|
||||
panelNotifications: panelNotifications.rows.map((row) => ({ notificationId: row.notification_id, deviceId: row.device_id, type: row.type, title: row.title, message: row.message, requestId: row.request_id, fileID: row.file_id, createdAtMs: Number(row.created_at_ms) }))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -74,7 +78,7 @@ class PostgresStore {
|
||||
}
|
||||
|
||||
async writeDatabase(client, database) {
|
||||
await client.query("DELETE FROM volume_config_requests; DELETE FROM identification_feedback; DELETE FROM panel_inbox; DELETE FROM identification_files; DELETE FROM function_configs; DELETE FROM file_records; DELETE FROM licenses; DELETE FROM production_lines; DELETE FROM companies;");
|
||||
await client.query("DELETE FROM panel_notifications; DELETE FROM volume_configs; DELETE FROM volume_config_requests; DELETE FROM identification_feedback; DELETE FROM panel_inbox; DELETE FROM identification_files; DELETE FROM function_configs; DELETE FROM file_records; DELETE FROM licenses; DELETE FROM production_lines; DELETE FROM companies;");
|
||||
for (const item of database.companies) await client.query("INSERT INTO companies (id, name, code, created_at) VALUES ($1, $2, $3, $4)", [item.id, item.name, item.code, item.createdAt]);
|
||||
for (const item of database.productionLines) await client.query("INSERT INTO production_lines (id, company_id, name, code, device_id, created_at, last_seen_at) VALUES ($1, $2, $3, $4, $5, $6, $7)", [item.id, item.companyId, item.name, item.code, item.deviceId, item.createdAt, item.lastSeenAt]);
|
||||
for (const item of database.licenses) await client.query("INSERT INTO licenses (license_id, company_id, production_line_id, device_id, customer, issued_at, expiry_at, features, license, status, created_at, revoked_at, revocation_reason) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)", [item.licenseId, item.companyId, item.productionLineId, item.deviceId, item.customer, item.issuedAt, item.expiryAt, item.features, item.license, item.status, item.createdAt, item.revokedAt, item.revocationReason]);
|
||||
@@ -84,6 +88,8 @@ class PostgresStore {
|
||||
for (const item of database.identificationFiles) await client.query("INSERT INTO identification_files (file_id, device_id, file_name, media_type, upload_time, size_bytes, status, processed_at, expires_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)", [item.fileID, item.deviceId, item.fileName, item.mediaType, item.uploadTime, item.size, item.status, item.processedAt, item.expiresAt]);
|
||||
for (const item of database.identificationFeedback) await client.query("INSERT INTO identification_feedback (device_id, run_id, file_name, status, result, update_time) VALUES ($1,$2,$3,$4,$5,$6)", [item.deviceId, item.runId, item.fileName, item.status, item.result, item.updateTime]);
|
||||
for (const item of database.volumeConfigRequests) await client.query("INSERT INTO volume_config_requests (device_id, request_id, status, created_at_ms, expires_at_ms, config_file_id, config_file_name, uploaded_at_ms, update_time) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)", [item.deviceId, item.requestId, item.status, item.createdAtMs, item.expiresAtMs, item.configFileID, item.configFileName, item.uploadedAtMs, item.updateTime]);
|
||||
for (const item of database.volumeConfigs) await client.query("INSERT INTO volume_configs (device_id, file_id, file_name, request_id, updated_at_ms) VALUES ($1,$2,$3,$4,$5)", [item.deviceId, item.fileID, item.fileName, item.requestId, item.updatedAtMs]);
|
||||
for (const item of database.panelNotifications) await client.query("INSERT INTO panel_notifications (notification_id, device_id, type, title, message, request_id, file_id, created_at_ms) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)", [item.notificationId, item.deviceId, item.type, item.title, item.message, item.requestId, item.fileID, item.createdAtMs]);
|
||||
}
|
||||
|
||||
createId(prefix) {
|
||||
|
||||
@@ -39,7 +39,7 @@ async function main() {
|
||||
purgeTimer.unref();
|
||||
app.listen(port, host, () => {
|
||||
console.log(`ReinLoop server listening on http://${host}:${port}`);
|
||||
console.log(`API endpoints: http://${host}:${port} and http://${host}:${port}/api`);
|
||||
console.log(`API endpoint: http://${host}:${port}`);
|
||||
console.log(`Data directory: ${dataDirectory}`);
|
||||
console.log(`Metadata store: ${process.env.DATABASE_URL ? "PostgreSQL" : "local JSON"}`);
|
||||
});
|
||||
|
||||
@@ -9,6 +9,8 @@ const EMPTY_DATABASE = {
|
||||
identificationFiles: [],
|
||||
identificationFeedback: [],
|
||||
volumeConfigRequests: [],
|
||||
volumeConfigs: [],
|
||||
panelNotifications: [],
|
||||
userInfo: [],
|
||||
companies: [],
|
||||
productionLines: [],
|
||||
|
||||
@@ -15,7 +15,7 @@ let licensePrivateKey;
|
||||
let licensePublicKeyPath;
|
||||
|
||||
async function post(payload) {
|
||||
const response = await fetch(`${baseUrl}/api`, {
|
||||
const response = await fetch(baseUrl, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(payload)
|
||||
@@ -59,7 +59,7 @@ test("health endpoint reports ready", async () => {
|
||||
assert.deepEqual(await response.json(), { success: true, service: "reinloop-server" });
|
||||
});
|
||||
|
||||
test("root endpoint accepts API requests without the /api suffix", async () => {
|
||||
test("root endpoint accepts API requests", async () => {
|
||||
const response = await fetch(baseUrl, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
@@ -69,6 +69,15 @@ test("root endpoint accepts API requests without the /api suffix", async () => {
|
||||
assert.deepEqual(await response.json(), { success: true, companies: [] });
|
||||
});
|
||||
|
||||
test("legacy /api endpoint is unavailable", async () => {
|
||||
const response = await fetch(`${baseUrl}/api`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ type: "listOrganizations", adminToken: "test-token" })
|
||||
});
|
||||
assert.equal(response.status, 404);
|
||||
});
|
||||
|
||||
test("legacy data_record endpoint and uploadUserInfo type are unavailable", async () => {
|
||||
const legacyRoute = await fetch(`${baseUrl}/data_record`, {
|
||||
method: "POST",
|
||||
@@ -244,6 +253,19 @@ test("model upload requires explicit overwrite for an existing file", async () =
|
||||
await fs.promises.readFile(path.join(dataDirectory, "models", "company-a", "overwrite-line", "controller.bin"), "utf8"),
|
||||
"second-version"
|
||||
);
|
||||
|
||||
const deleted = await post({
|
||||
type: "deleteModel", fileID: replacement.fileID, adminToken: "test-token"
|
||||
});
|
||||
assert.equal(deleted.success, true);
|
||||
assert.equal(deleted.deletedCount, 1);
|
||||
const listed = await post({
|
||||
type: "listModels", folder: "company-a/overwrite-line/model_config"
|
||||
});
|
||||
assert.deepEqual(listed.fileList, []);
|
||||
await assert.rejects(fs.promises.access(
|
||||
path.join(dataDirectory, "models", "company-a", "overwrite-line", "controller.bin")
|
||||
), { code: "ENOENT" });
|
||||
});
|
||||
|
||||
test("panel consumes uploaded device files from an inbox without scanning folders", async () => {
|
||||
@@ -488,6 +510,65 @@ test("volume request accepts only the file uploaded for that request", async ()
|
||||
assert.deepEqual(await (await fetch(ready.url)).json(), { num_runs: 2 });
|
||||
});
|
||||
|
||||
test("panel notifications and volume configuration stay isolated by device", async () => {
|
||||
const deviceId = "notify-co/line-1";
|
||||
const otherDeviceId = "notify-co/line-2";
|
||||
const request = await post({ type: "createVolumeConfigRequest", deviceId });
|
||||
const notification = await post({
|
||||
type: "getPendingPanelNotification", deviceId, adminToken: "test-token"
|
||||
});
|
||||
assert.equal(notification.pending, true);
|
||||
assert.equal(notification.notification.type, "volume_request_started");
|
||||
assert.equal(notification.notification.requestId, request.requestId);
|
||||
assert.equal((await post({
|
||||
type: "getPendingPanelNotification", deviceId: otherDeviceId, adminToken: "test-token"
|
||||
})).pending, false);
|
||||
|
||||
const folder = `${deviceId}/volume_config_requests/${request.requestId}`;
|
||||
const issued = await post({ type: "uploadDataFile", fileName: "volume_measurement.json", folder });
|
||||
const form = new FormData();
|
||||
form.append("file", new Blob(['{"num_runs":2}'], { type: "application/json" }), "volume_measurement.json");
|
||||
assert.equal((await fetch(issued.uploadMetadata.url, { method: "POST", body: form })).status, 204);
|
||||
assert.equal((await post({
|
||||
type: "submitVolumeConfigFile", deviceId, requestId: request.requestId,
|
||||
fileID: issued.fileID, fileName: "volume_measurement.json"
|
||||
})).success, true);
|
||||
|
||||
const config = await post({ type: "getVolumeConfigFile", deviceId, adminToken: "test-token" });
|
||||
assert.equal(config.found, true);
|
||||
assert.equal(config.fileID, issued.fileID);
|
||||
assert.equal((await post({
|
||||
type: "getVolumeConfigFile", deviceId: otherDeviceId, adminToken: "test-token"
|
||||
})).found, false);
|
||||
assert.equal((await post({
|
||||
type: "ackPanelNotification", deviceId, notificationId: notification.notification.notificationId,
|
||||
adminToken: "test-token"
|
||||
})).success, true);
|
||||
|
||||
async function uploadResult(folderName, fileName, content) {
|
||||
const result = await post({ type: "uploadDataFile", fileName, folder: `${deviceId}/${folderName}` });
|
||||
const uploadForm = new FormData();
|
||||
uploadForm.append("file", new Blob([content]), fileName);
|
||||
assert.equal((await fetch(result.uploadMetadata.url, { method: "POST", body: uploadForm })).status, 204);
|
||||
}
|
||||
await uploadResult("V_config", "volume_result.json", '{"volume_L":1.2}');
|
||||
const volumeResult = await post({
|
||||
type: "getPendingPanelNotification", deviceId, adminToken: "test-token"
|
||||
});
|
||||
assert.equal(volumeResult.notification.type, "volume_result_ready");
|
||||
assert.ok(volumeResult.notification.fileID);
|
||||
await post({
|
||||
type: "ackPanelNotification", deviceId, notificationId: volumeResult.notification.notificationId,
|
||||
adminToken: "test-token"
|
||||
});
|
||||
|
||||
await uploadResult("ind_data", "identification_result.json", '{"stable_pressures":[]}');
|
||||
const identificationResult = await post({
|
||||
type: "getPendingPanelNotification", deviceId, adminToken: "test-token"
|
||||
});
|
||||
assert.equal(identificationResult.notification.type, "identification_result_ready");
|
||||
});
|
||||
|
||||
test("admin manages companies and production lines with a stable device id", async () => {
|
||||
const unauthorized = await post({
|
||||
type: "createCompany", name: "未授权公司", code: "blocked"
|
||||
|
||||
Reference in New Issue
Block a user