完善智能称重终端界面与电子秤接入

This commit is contained in:
FinleyHsu
2026-08-06 10:48:47 +08:00
parent 839edd1e4a
commit 3b856f0c11
8 changed files with 967 additions and 181 deletions
+121 -116
View File
@@ -5,7 +5,6 @@ import {
createFileTimestamp,
evaluateStability,
formatWeight,
parseScaleMessage,
type WeightUnit,
} from "./scale-utils";
@@ -59,6 +58,9 @@ declare global {
exportLogs: (fileName: string, content: string) => boolean;
openSystemSettings: () => boolean;
openFileManager: () => boolean;
startScale: () => boolean;
stopScale: () => boolean;
scaleCommand: (command: "zero" | "tare") => boolean;
};
}
}
@@ -70,6 +72,20 @@ const DEFAULT_MATERIALS: Material[] = [
{ id: "6", name: "废锡", tone: "tin" },
];
const TEST_EMPLOYEES = [
{ name: "张伟", id: "E-0826" },
{ name: "李敏", id: "E-1038" },
{ name: "陈浩", id: "E-1172" },
];
const TEST_MACHINES = ["A01 绕线机", "A03 挤出机", "B06 注塑机", "C02 裁切机"];
const TEST_WEIGHT_RECORDS: WeightRecord[] = [
{ employeeName: "张伟", employeeId: "E-0826", machineId: "A01 绕线机", materialType: "废铜", materialTypeId: "3", weightKg: 12.48, createdAt: "2026-08-04T08:35:00.000Z" },
{ employeeName: "李敏", employeeId: "E-1038", machineId: "A03 挤出机", materialType: "废电线", materialTypeId: "4", weightKg: 8.76, createdAt: "2026-08-04T09:12:00.000Z" },
{ employeeName: "陈浩", employeeId: "E-1172", machineId: "B06 注塑机", materialType: "废铝", materialTypeId: "5", weightKg: 6.32, createdAt: "2026-08-04T10:06:00.000Z" },
];
const DEFAULT_SETTINGS: AppSettings = {
employee: "",
machines: "",
@@ -102,7 +118,7 @@ const TRANSLATIONS: Record<Language, Record<string, string>> = {
language: "界面语言", languageDesc: "切换后立即应用到操作界面", serverApi: "本地服务器接口", serverApiDesc: "接口未配置时不会生成模拟数据",
materialDict: "废料字典", materialDictDesc: "修改后将同步更新首页分类与称重数据", displayName: "显示名称",
saveAll: "保存全部设置", saveHint: "修改完成后请保存设置", passwordTitle: "管理员登录", passwordDesc: "请输入管理员密码进入应用设置", confirmLogin: "确认登录",
employeeApi: "人员信息接口", machineApi: "机台列表接口", scaleApi: "电子秤数据接口", uploadApi: "称重上传接口", apiAddressPlaceholder: "请输入完整接口地址",
employeeApi: "人员信息接口", machineApi: "机台列表接口", scaleApi: "电子秤广播服务", uploadApi: "称重上传接口", apiAddressPlaceholder: "请输入完整接口地址", modbusConfigPlaceholder: "后台电子秤服务自动连接,无需配置", modbusConfigHint: "请安装 android_hid_scale_service 后台服务;重量、皮重、单位和稳定状态会自动同步。",
peripheralTitle: "完成称重后的外设动作", peripheralDesc: "功能默认关闭,需由 Android 原生层接入 USB 设备", reserved: "预留接口", cameraTitle: "USB 摄像头拍照", cameraDesc: "提交成功后自动拍摄现场照片",
photoPath: "照片保存路径", fileName: "文件名", printTitle: "称重凭证打印", printDesc: "提交成功后调用 USB / 蓝牙打印机", scrapWeight: "废料重量", weighingTime: "称重时间",
dataTitle: "数据补传与本地备份", dataDesc: "网络异常时确保称重记录不丢失", autoProtect: "自动保护", pending: "待补传数据", localBackup: "本地备份", records: "条记录",
@@ -134,7 +150,7 @@ const TRANSLATIONS: Record<Language, Record<string, string>> = {
language: "介面語言", languageDesc: "切換後立即套用到操作介面", serverApi: "本地伺服器介面", serverApiDesc: "介面未設定時不會產生模擬資料",
materialDict: "廢料字典", materialDictDesc: "修改後將同步更新首頁分類與稱重資料", displayName: "顯示名稱",
saveAll: "儲存全部設定", saveHint: "修改完成後請儲存設定", passwordTitle: "管理員登入", passwordDesc: "請輸入管理員密碼進入應用設定", confirmLogin: "確認登入",
employeeApi: "人員資訊介面", machineApi: "機台列表介面", scaleApi: "電子秤資料介面", uploadApi: "稱重上傳介面", apiAddressPlaceholder: "請輸入完整介面地址",
employeeApi: "人員資訊介面", machineApi: "機台列表介面", scaleApi: "電子秤廣播服務", uploadApi: "稱重上傳介面", apiAddressPlaceholder: "請輸入完整介面地址", modbusConfigPlaceholder: "後台電子秤服務自動連線,無需設定", modbusConfigHint: "請安裝 android_hid_scale_service 後台服務;重量、皮重、單位和穩定狀態會自動同步。",
peripheralTitle: "完成稱重後的外設動作", peripheralDesc: "功能預設關閉,需由 Android 原生層接入 USB 設備", reserved: "預留介面", cameraTitle: "USB 攝影機拍照", cameraDesc: "提交成功後自動拍攝現場照片",
photoPath: "照片儲存路徑", fileName: "檔名", printTitle: "稱重憑證列印", printDesc: "提交成功後呼叫 USB / 藍牙印表機", scrapWeight: "廢料重量", weighingTime: "稱重時間",
dataTitle: "資料補傳與本地備份", dataDesc: "網路異常時確保稱重記錄不遺失", autoProtect: "自動保護", pending: "待補傳資料", localBackup: "本地備份", records: "條記錄",
@@ -166,7 +182,7 @@ const TRANSLATIONS: Record<Language, Record<string, string>> = {
language: "Interface language", languageDesc: "Changes are applied to the interface immediately", serverApi: "Local server APIs", serverApiDesc: "No sample data is generated when an API is not configured",
materialDict: "Scrap dictionary", materialDictDesc: "Changes update home categories and weighing records", displayName: "Display name",
saveAll: "Save all settings", saveHint: "Save after making changes", passwordTitle: "Administrator login", passwordDesc: "Enter the administrator password to open settings", confirmLogin: "Log in",
employeeApi: "Operator API", machineApi: "Machine list API", scaleApi: "Scale data API", uploadApi: "Record upload API", apiAddressPlaceholder: "Enter the complete API address",
employeeApi: "Operator API", machineApi: "Machine list API", scaleApi: "Scale broadcast service", uploadApi: "Record upload API", apiAddressPlaceholder: "Enter the complete API address", modbusConfigPlaceholder: "The scale service connects automatically", modbusConfigHint: "Install the android_hid_scale_service companion app. Weight, tare, unit, and stability are synchronized automatically.",
peripheralTitle: "Post-weighing peripheral actions", peripheralDesc: "Off by default; requires the Android native USB bridge", reserved: "Reserved", cameraTitle: "USB camera capture", cameraDesc: "Capture a site photo after successful submission",
photoPath: "Photo save path", fileName: "Filename", printTitle: "Print weighing receipt", printDesc: "Call a USB / Bluetooth printer after submission", scrapWeight: "Scrap weight", weighingTime: "Weighing time",
dataTitle: "Retry upload & local backup", dataDesc: "Protect weighing records during network failures", autoProtect: "Automatic", pending: "Pending uploads", localBackup: "Local backups", records: "records",
@@ -186,7 +202,6 @@ const CONFIG_KEY = "smart-scale-config";
const BACKUP_KEY = "smart-scale-backup-records";
const PENDING_KEY = "smart-scale-pending-records";
const LOG_KEY = "smart-scale-logs";
const PRODUCTION_DATA_KEY = "smart-scale-production-data-v1";
const IMAGE_PATH = "/sdcard/smart/image/";
const CACHE_PATH = "/sdcard/smart/cache/";
const LOG_PATH = "/sdcard/smart/logs/";
@@ -227,9 +242,10 @@ export default function Home() {
// 称重主流程状态:首页 → 人员/机台确认 → 称重 → 结果。
const [step, setStep] = useState<Step>("home");
const [employee, setEmployee] = useState({ name: "", id: "" });
const [testEmployeeIndex, setTestEmployeeIndex] = useState(0);
const [machineQuery, setMachineQuery] = useState("");
const [machine, setMachine] = useState("");
const [machineOptions, setMachineOptions] = useState<string[]>([]);
const [machineOptions, setMachineOptions] = useState<string[]>(TEST_MACHINES);
const [machineModalOpen, setMachineModalOpen] = useState(false);
const [machineKeypadOpen, setMachineKeypadOpen] = useState(false);
const [machineLoading, setMachineLoading] = useState(false);
@@ -259,7 +275,7 @@ export default function Home() {
const [numericEditor, setNumericEditor] = useState<NumericEditor | null>(null);
const [numericEditorValue, setNumericEditorValue] = useState("");
const [pendingRecords, setPendingRecords] = useState<WeightRecord[]>([]);
const [backupRecords, setBackupRecords] = useState<WeightRecord[]>([]);
const [backupRecords, setBackupRecords] = useState<WeightRecord[]>(TEST_WEIGHT_RECORDS);
const [lastRecord, setLastRecord] = useState<WeightRecord | null>(null);
const [lastUploadPending, setLastUploadPending] = useState(false);
const [logs, setLogs] = useState<LogEntry[]>([
@@ -309,18 +325,6 @@ export default function Home() {
// 延迟到首帧之后恢复配置,避免服务端渲染与本地配置产生水合差异。
const timer = window.setTimeout(() => {
try {
/*
* 早期测试版会自动生成模拟人员、机台和重量记录。
* 首次升级到正式数据模式时仅清理这些历史业务记录,
* 管理员密码、接口地址和废料字典等配置继续保留。
*/
if (window.localStorage.getItem(PRODUCTION_DATA_KEY) !== "ready") {
window.localStorage.removeItem(PENDING_KEY);
window.localStorage.removeItem(BACKUP_KEY);
window.localStorage.removeItem(LOG_KEY);
window.localStorage.setItem(PRODUCTION_DATA_KEY, "ready");
}
const savedConfig = window.localStorage.getItem(CONFIG_KEY);
if (savedConfig) {
const parsed = JSON.parse(savedConfig);
@@ -359,50 +363,53 @@ export default function Home() {
}, []);
/*
* 称重数据只接受已配置的 WebSocket 接口,不再注入任何模拟重量。
* 服务端可发送纯数字或带 weight / weightKg / value 字段的 JSON。
* 称重数据通过 Android 原生 RS-485 Modbus RTU 桥接读取。
* 前端只接收 native 事件,不生成任何模拟重量。
*/
useEffect(() => {
if (step !== "weigh") return;
if (!appSettings.weight.trim()) return;
let socket: WebSocket;
let disposed = false;
try {
socket = new WebSocket(appSettings.weight.trim());
} catch {
window.setTimeout(() => {
type ModbusEventDetail = { status?: string; message?: string; weightKg?: number };
let started = false;
const handleModbusEvent = (event: Event) => {
const detail = (event as CustomEvent<ModbusEventDetail>).detail ?? {};
if (detail.status === "connecting") setScaleStatus("connecting");
if (detail.status === "connected" || detail.status === "sample") setScaleStatus("connected");
if (detail.status === "error") setScaleStatus("error");
if (typeof detail.weightKg === "number" && Number.isFinite(detail.weightKg) && detail.weightKg >= 0) {
setRawWeight(detail.weightKg);
}
if (detail.message && detail.status !== "sample") {
addLog(detail.message, detail.status === "error" ? "error" : detail.status === "connected" ? "success" : "info");
}
};
window.addEventListener("woer-modbus", handleModbusEvent);
let errorTimer: number | undefined;
const reportModbusError = (message: string) => {
errorTimer = window.setTimeout(() => {
setScaleStatus("error");
addLog("电子秤接口地址无效", "error");
addLog(message, "error");
}, 0);
return;
};
try {
if (!window.WoerNative?.startScale) {
reportModbusError("当前运行环境不支持电子秤广播服务");
} else {
started = window.WoerNative.startScale();
if (!started) {
reportModbusError("电子秤后台服务未安装或无法启动");
}
}
} catch {
reportModbusError("电子秤后台服务启动失败");
}
socket.onopen = () => {
if (disposed) return;
setScaleStatus("connected");
addLog("电子秤数据接口连接成功", "success");
};
socket.onmessage = (event) => {
const nextWeight = parseScaleMessage(String(event.data ?? ""));
if (nextWeight !== null) setRawWeight(nextWeight);
};
socket.onerror = () => {
if (disposed) return;
setScaleStatus("error");
addLog("电子秤数据接口连接异常", "error");
};
socket.onclose = () => {
if (disposed) return;
setScaleStatus("error");
};
return () => {
disposed = true;
socket.close();
window.removeEventListener("woer-modbus", handleModbusEvent);
if (errorTimer !== undefined) window.clearTimeout(errorTimer);
if (started) window.WoerNative?.stopScale();
};
}, [appSettings.weight, step]);
}, [step]);
/*
* 按固定周期连续采样,而不是依赖 React 的重量变化事件。
@@ -451,7 +458,7 @@ export default function Home() {
setTare(0);
setStable(false);
setStableProgress(0);
setScaleStatus(appSettings.weight.trim() ? "connecting" : "unconfigured");
setScaleStatus("connecting");
setLastAccumulation(null);
setLastUploadPending(false);
setNotice("");
@@ -559,7 +566,14 @@ export default function Home() {
setLoading(true);
setNotice("");
try {
if (!appSettings.employee.trim()) throw new Error("人员接口未配置");
if (!appSettings.employee.trim()) {
const nextEmployee = TEST_EMPLOYEES[testEmployeeIndex % TEST_EMPLOYEES.length];
setEmployee(nextEmployee);
setTestEmployeeIndex((index) => (index + 1) % TEST_EMPLOYEES.length);
addLog(`已载入测试人员:${nextEmployee.name}`, "info");
setStep("identity");
return;
}
const response = await fetch(appSettings.employee.trim());
if (!response.ok) throw new Error("人员接口不可用");
const data = await response.json();
@@ -582,7 +596,11 @@ export default function Home() {
setMachineLoading(true);
setSettingsMessage("");
try {
if (!appSettings.machines.trim()) throw new Error("机台接口未配置");
if (!appSettings.machines.trim()) {
setMachineOptions(TEST_MACHINES);
addLog("已载入测试机台列表", "info");
return;
}
const response = await fetch(appSettings.machines.trim());
if (!response.ok) throw new Error("机台接口不可用");
const data = await response.json();
@@ -619,7 +637,7 @@ export default function Home() {
setStable(false);
setStableProgress(0);
stableSamples.current = [];
setScaleStatus(appSettings.weight.trim() ? "connecting" : "unconfigured");
setScaleStatus("connecting");
setNotice("");
setStep("weigh");
}
@@ -755,6 +773,14 @@ export default function Home() {
setNotice(language === "en" ? "Last accumulation canceled" : language === "zh-TW" ? "已取消上一次累計" : "已取消上一次累计");
}
function sendScaleCommand(command: "zero" | "tare") {
try {
return window.WoerNative?.scaleCommand(command) ?? false;
} catch {
return false;
}
}
async function retryPendingUploads() {
if (!pendingRecords.length) {
setSettingsMessage("当前没有需要补传的数据");
@@ -871,35 +897,9 @@ export default function Home() {
</div>
</header>
{step !== "home" && step !== "settings" && (
<div className="progress-strip" aria-label="流程进度">
{[t("progressEmployee"), t("progressWeight"), t("progressResult")].map((label, index) => {
const activeIndex = step === "identity" ? 0 : step === "weigh" ? 1 : 2;
return (
<div className={index <= activeIndex ? "progress-item active" : "progress-item"} key={label}>
<span>{index < activeIndex ? "✓" : index + 1}</span>
{label}
</div>
);
})}
</div>
)}
<div className="content">
{step === "home" && (
<div className="home-view">
<div className="home-copy">
<div className="eyebrow"><span /> {t("heroEyebrow")}</div>
<h1>{t("heroTitle1")}<br /><em>{t("heroTitle2")}</em></h1>
<p>{t("heroDesc1")}<br />{t("heroDesc2")}</p>
<div className={loading ? "home-start-hint loading" : "home-start-hint"}>
<span>{loading ? "···" : "1"}</span>
<b>{loading ? t("loadingEmployee") : t("clickMaterial")}</b>
</div>
<button className="admin-link" onClick={() => { setPassword(""); setPasswordError(""); setPasswordOpen(true); }}>⚙ {t("adminLogin")} <span>→</span></button>
{notice && <div className="notice home-notice">ⓘ {notice}</div>}
</div>
<aside className="home-material-panel">
<div className="material-panel-heading">
<span className="step-kicker">{t("prep")}</span>
@@ -925,39 +925,48 @@ export default function Home() {
{loading ? t("loadingEmployee") : material ? `${t("chooseMaterial")} · ${materialName(material)}` : t("chooseAuto")}
</div>
</aside>
<button className="admin-link-fab" onClick={() => setPasswordOpen(true)}>
{t("adminLogin")} <span>⌁</span>
</button>
</div>
)}
{step === "identity" && (
<div className="panel-view identity-view">
<button className="back-button" onClick={resetToHome}>← {t("back")}</button>
<button className="back-button identity-back" onClick={resetToHome}>← {t("back")}</button>
<div className="section-heading">
<div>
<span className="step-kicker">01 · {t("employeeMachine")}</span>
<h2>{t("confirmInfo")}</h2>
<p>{t("identityDesc")}</p>
</div>
<button className="refresh-button" onClick={() => void fetchIdentity()} disabled={loading}>↻ {t("refreshEmployee")}</button>
</div>
<div className="identity-card">
<div className="avatar">{employee.name ? employee.name.slice(-1) : "?"}</div>
<div><small>{t("currentEmployee")}</small><h3>{employee.name || "—"}</h3><p>{t("employeeId")} · {employee.id || "—"}</p></div>
<span className={employee.name ? "verified" : "verified missing"}>{employee.name ? `✓ ${t("verified")}` : "!"}</span>
<div className={`selected-material-summary ${selectedMaterial.tone} identity-material-compact`}>
<small>{t("currentMaterial")}</small><b>{materialName(selectedMaterial)}</b><em>TYPE ID · {selectedMaterial.id}</em><i>✓</i>
</div>
<label className="field-label">{t("machineNo")}</label>
<div className={machine ? "machine-select-row selected" : "machine-select-row"}>
<span className="machine-select-icon">▣</span>
<span><small>{machine ? t("selectedMachine") : t("machineNo")}</small><b>{machine || t("noMachine")}</b></span>
<button onClick={() => { setMachineQuery(""); setMachineKeypadOpen(false); setMachineModalOpen(true); }}>{t("selectMachine")}</button>
<button className="machine-refresh" onClick={() => void refreshMachines()} disabled={machineLoading}>↻ {t("refreshMachine")}</button>
<div className="identity-layout">
<section className="identity-person-panel">
<div className="identity-panel-heading">
<span>{t("currentEmployee")}</span>
<button className="refresh-button" onClick={() => void fetchIdentity()} disabled={loading}>↻ {t("refreshEmployee")}</button>
</div>
<div className="identity-card">
<div className="avatar">{employee.name ? employee.name.slice(-1) : "?"}</div>
<div><small>{t("currentEmployee")}</small><h3>{employee.name || "—"}</h3><p>{t("employeeId")} · {employee.id || "—"}</p></div>
<span className={employee.name ? "verified" : "verified missing"}>{employee.name ? `✓ ${t("verified")}` : "!"}</span>
</div>
</section>
<section className="identity-operation-panel">
<div className="identity-panel-heading"><span>{t("machineNo")}</span></div>
<div className={machine ? "machine-select-row selected" : "machine-select-row"}>
<span className="machine-select-icon">▣</span>
<span><small>{machine ? t("selectedMachine") : t("machineNo")}</small><b>{machine || t("noMachine")}</b></span>
<button onClick={() => { setMachineQuery(""); setMachineKeypadOpen(false); setMachineModalOpen(true); }}>{t("selectMachine")}</button>
<button className="machine-refresh" onClick={() => void refreshMachines()} disabled={machineLoading}>↻ {t("refreshMachine")}</button>
</div>
<button className="full-primary" disabled={!employee.name || !machine} onClick={beginWeighing}>
{t("confirmWeigh")} <span>→</span>
</button>
</section>
</div>
<button
className="full-primary"
disabled={!employee.name || !machine}
onClick={beginWeighing}
>
{t("confirmWeigh")} <span>→</span>
</button>
{notice && <div className="notice">ⓘ {notice}</div>}
</div>
)}
@@ -995,20 +1004,12 @@ export default function Home() {
</div>
<div className={lastAccumulation ? "scale-tools has-cancel" : "scale-tools"}>
<button onClick={() => { setZeroOffset(rawWeight); setTare(0); setNotice(t("zeroed")); }}>⟲<span><b>{t("zero")}</b><small>{t("zeroDesc")}</small></span></button>
<button onClick={() => { setTare(Math.max(0, rawWeight - zeroOffset)); setNotice(t("tared")); }}>▱<span><b>{t("tareAction")}</b><small>{t("tareDesc")}</small></span></button>
<button onClick={() => { const sent = sendScaleCommand("zero"); setZeroOffset(rawWeight); setTare(0); setNotice(sent ? t("zeroed") : "清零指令发送失败,请检查电子秤后台服务"); }}>⟲<span><b>{t("zero")}</b><small>{t("zeroDesc")}</small></span></button>
<button onClick={() => { const sent = sendScaleCommand("tare"); setTare(Math.max(0, rawWeight - zeroOffset)); setNotice(sent ? t("tared") : "去皮指令发送失败,请检查电子秤后台服务"); }}>▱<span><b>{t("tareAction")}</b><small>{t("tareDesc")}</small></span></button>
<button onClick={addToTotal}>+<span><b>{t("accumulate")}</b><small>{t("accumulateDesc")}</small></span></button>
{lastAccumulation && <button className="cancel-total" onClick={cancelAccumulation}>×<span><b>{t("cancelAccum")}</b><small>{t("cancelAccumDesc")}</small></span></button>}
</div>
<div className={`selected-material-summary ${selectedMaterial.tone}`}>
<span>
<small>{t("currentMaterial")}</small>
<b>{materialName(selectedMaterial)}</b>
<em>TYPE ID · {selectedMaterial.id}</em>
</span>
<i>✓ {t("confirmedHome")}</i>
</div>
{notice && <div className="notice compact">ⓘ {notice}</div>}
<button className="full-primary upload" disabled={!stable || loading} onClick={submitWeight}>
{loading ? t("uploading") : stable ? t("saveWeight") : t("waitStable")} <span>→</span>
@@ -1124,11 +1125,15 @@ export default function Home() {
<input
value={appSettings[key as keyof Pick<AppSettings, "employee" | "machines" | "weight" | "upload">] as string}
onChange={(event) => setAppSettings({ ...appSettings, [key]: event.target.value })}
placeholder={t("apiAddressPlaceholder")}
placeholder={key === "weight" ? t("modbusConfigPlaceholder") : t("apiAddressPlaceholder")}
/>
</label>
))}
</div>
<div className="path-box data-path">
<small>{t("scaleApi")}</small>
<code>{t("modbusConfigHint")}</code>
</div>
</>
)}
@@ -1263,8 +1268,8 @@ export default function Home() {
</div>
)}
</div>
<footer className="production-footer">沃尔核材 · 数字化生产</footer>
<footer><span>沃尔核材 · 数字化生产</span><span>{appSettings.deviceName} · {appSettings.deviceId} · v1.1</span></footer>
</section>
{passwordOpen && (