// Manual controls for the live weight channels: the kitchen scale and the return-station bins (two, or the five // sorted bins when the school uses them). ESP32 readings take over again on their next post. import { api, live, kg, num, act, signIn, roleChip } from './core.js'; import { T, onLang, applyStatic, langToggle, FIVE_BINS, binName } from './i18n.js'; await signIn('sim'); onLang(() => location.reload()); document.getElementById('lang-slot').innerHTML = roleChip() + langToggle(); applyStatic(); const CHANNELS = { kitchen: { no: '01', title: T('เครื่องชั่งในครัว', 'Kitchen scale'), location: T('ครัว · ESP32 A', 'Kitchen · ESP32 A'), purpose: T('ชั่งหม้อก่อนและหลังตัก เพื่อรู้ว่าตักไปเท่าไร', 'Weigh pots before and after serving') }, rice: { no: '02', title: T('ถังเศษข้าว', 'Rice leftovers bin'), location: T('จุดคืนจาน · ESP32 B ช่อง 1', 'Return station · ESP32 B ch 1'), purpose: T('ชั่งเศษข้าวที่เด็กเทคืน', 'Weighs the rice kids bring back') }, dish: { no: '03', title: T('ถังเศษกับข้าว', 'Main-dish leftovers bin'), location: T('จุดคืนจาน · ESP32 B ช่อง 2', 'Return station · ESP32 B ch 2'), purpose: T('ชั่งเศษกับข้าวบนตะแกรง', 'Weighs main-dish leftovers on the strainer') }, }; FIVE_BINS.forEach((k, i) => { CHANNELS[k] = { no: String(i + 2).padStart(2, '0'), title: T(`ถัง${binName(k)}`, `${binName(k)} bin`), location: T(`จุดคืนจาน 5 ถัง · ESP32 B ช่อง ${i + 1}`, `5-bin return station · ESP32 B ch ${i + 1}`), purpose: T(`เด็กแยกทิ้ง${binName(k)}ลงถังนี้`, `Children sort ${binName(k).toLowerCase()} into this bin`) }; }); const QUICK = { kitchen: [ [T('วางหม้อกับข้าว 3 กก.', 'Main-dish pot 3 kg'), { value_g: 3000 }], [T('ตักออก 0.5 กก.', 'Serve 0.5 kg'), { delta_g: -500 }], [T('ตักออก 2.5 กก.', 'Serve 2.5 kg'), { delta_g: -2500 }], [T('วางหม้อข้าว 12 กก.', 'Rice pot 12 kg'), { value_g: 12000 }], [T('ยกหม้อออก', 'Lift the pot off'), { value_g: 0 }], [T('ตุ้ม 500 ก.', '500 g weight'), { value_g: 500.9 }], [T('ตุ้ม 500 ก. (เครื่องเพี้ยน)', '500 g weight (off)'), { value_g: 508.5 }], [T('เพิ่ม 120 ก.', 'Add 120 g'), { delta_g: 120 }], [T('เพิ่ม 30 ก.', 'Add 30 g'), { delta_g: 30 }], [T('ตุ้ม 2,000 ก.', '2,000 g weight'), { value_g: 2003 }], ], rice: [ [T('เพิ่ม 50 ก.', 'Add 50 g'), { delta_g: 50 }], [T('เพิ่ม 200 ก.', 'Add 200 g'), { delta_g: 200 }], [T('ตุ้ม 500 ก.', '500 g weight'), { value_g: 500.4 }], [T('เทถังทิ้ง', 'Empty the bin'), { value_g: 0 }], [T('ตุ้ม 2,000 ก.', '2,000 g weight'), { value_g: 1998.6 }], ], dish: [ [T('เพิ่ม 50 ก.', 'Add 50 g'), { delta_g: 50 }], [T('เพิ่ม 200 ก.', 'Add 200 g'), { delta_g: 200 }], [T('เพิ่ม 700 ก.', 'Add 700 g'), { delta_g: 700 }], [T('ตุ้ม 500 ก.', '500 g weight'), { value_g: 499.6 }], [T('เทถังทิ้ง', 'Empty the bin'), { value_g: 0 }], [T('ตุ้ม 2,000 ก.', '2,000 g weight'), { value_g: 2001.2 }], ], }; const PRIMARY = { kitchen: [0, 1, 2, 3, 4], rice: [0, 1, 3], dish: [0, 1, 2, 4] }; const EXTRA = { kitchen: [5, 9, 6, 7, 8], rice: [2, 4], dish: [3, 5] }; FIVE_BINS.forEach((k, i) => { QUICK[k] = [ [T('เพิ่ม 20 ก.', 'Add 20 g'), { delta_g: 20 }], [T('เพิ่ม 100 ก.', 'Add 100 g'), { delta_g: 100 }], [T('ตุ้ม 500 ก.', '500 g weight'), { value_g: [500.2, 499.8, 500.6, 499.7, 500.3][i] }], [T('เทถังทิ้ง', 'Empty the bin'), { value_g: 0 }], [T('ตุ้ม 2,000 ก.', '2,000 g weight'), { value_g: [1999.4, 2000.8, 2001.6, 1998.9, 2000.5][i] }], ]; PRIMARY[k] = [0, 1, 3]; EXTRA[k] = [2, 4]; }); // ---------------------------------------------------------------- kids' opinions (tapped in the app by a teacher) const REASONS = [['ate_all', T('กินหมด', 'Ate it all')], ['too_much', T('เยอะไป', 'Too much')], ['taste', T('รสชาติไม่ถูกปาก', "Didn't like the taste")], ['hard', T('แข็งหรือชิ้นใหญ่', 'Too hard or big')], ['unfamiliar', T('ไม่คุ้น ไม่เคยกิน', 'Never had it before')], ['no_time', T('กินไม่ทัน', 'Not enough time')]]; const BATCHES = { demo: [T('ห้องเรียน 18 คนตอบ', '18 kids answer'), T('ส่วนใหญ่ตอบ “แข็งหรือชิ้นใหญ่”', 'Mostly “too hard or big”'), { ate_all: 5, too_much: 1, taste: 2, hard: 8, unfamiliar: 1, no_time: 1 }], spread: [T('ห้องเรียน 10 คนตอบ', '10 kids answer'), T('คำตอบกระจาย', 'Mixed answers'), { ate_all: 3, too_much: 2, taste: 2, hard: 1, unfamiliar: 1, no_time: 1 }], }; let voiceState = null; document.getElementById('voice-buttons').innerHTML = REASONS.map(([key, label]) => `${label}${T('เด็ก 1 คน', 'one child')}`).join(''); document.getElementById('voice-batches').innerHTML = Object.entries(BATCHES).map(([key, [title, sub]]) => `${title}${sub}`).join(''); function voiceFeedback(message, error = false) { const el = document.getElementById('voice-feedback'); el.textContent = message; el.classList.toggle('error', error); } function renderVoice() { const on = voiceState?.enabled; const chip = document.getElementById('voice-state'); chip.textContent = !voiceState ? T('กำลังเชื่อมต่อ', 'Connecting') : on ? T('รอบนี้เก็บข้อคิดเห็น', 'Collecting this round') : T('รอบนี้ไม่ต้องเก็บข้อคิดเห็น', 'Not needed this round'); chip.className = `chip ${on ? 'good' : ''}`; document.querySelectorAll('[data-vote], [data-batch]').forEach((b) => { b.disabled = !on; }); } document.body.addEventListener('click', async (event) => { const v = event.target.closest('button[data-vote]'); if (v) { try { const r = await api('/api/opinion', { meal_id: voiceState.meal_id, button: v.dataset.vote }); voiceFeedback(T(`บันทึกแล้ว รอบนี้ได้ข้อคิดเห็น ${r.total} คน จาก ${r.students} คน${r.over ? ' เกินจำนวนเด็ก รอบนี้ใช้ไม่ได้' : ''}`, `Saved. ${r.total} of ${r.students} children have answered${r.over ? '. More answers than children, so this round will not count' : ''}`), r.over); } catch (e) { voiceFeedback(e.message, true); } return; } const b = event.target.closest('button[data-batch]'); if (b) { const r = await act('/api/sim/votes', { counts: BATCHES[b.dataset.batch][2] }); if (r) voiceFeedback(T(`เพิ่มข้อคิดเห็น ${r.added} คนแล้ว`, `Added ${r.added} answers`)); } }); const busy = new Set(); let scales = null; let state = null; let stateVersion = null; let stateLoading = false; let lastStateAttempt = 0; let scenarioBusy = false; function buttonsFor(channel, indices) { return indices.map((i) => { const [label, body] = QUICK[channel][i]; const kind = body.value_g === 0 ? 'reset' : 'quick'; return `${label}`; }).join(''); } // The bins on screen: an open round keeps the layout it started with, otherwise the school's setting. let shown = ['kitchen', 'rice', 'dish']; function binsInUse() { const c = state?.current; const five = c?.meal?.status === 'open' ? Object.keys(c.sorted_bins ?? {}).length > 0 : state?.settings?.return_bins === 'five'; return five ? FIVE_BINS : ['rice', 'dish']; } function renderGrid() { shown = ['kitchen', ...binsInUse()]; document.getElementById('grid').innerHTML = shown.map((channel) => [channel, CHANNELS[channel]]).map(([channel, info]) => ` ${info.no} ${info.title}${info.location} ${info.purpose} ${T("น้ำหนักตอนนี้", "Live weight")} —${T("ก.", "g")} ${T("กำลังเชื่อมต่อ", "Connecting")}${T("รอข้อมูล…", "Waiting…")} ${T("กำลังเชื่อมต่อ…", "Connecting…")} ${T("ปุ่มลัด", "Quick values")} ${T("กดแล้วส่งค่าทันที", "Sends immediately")} ${buttonsFor(channel, PRIMARY[channel])} ${T("ตุ้มตรวจเครื่องและค่าอื่น", "Reference weights & more")} ${buttonsFor(channel, EXTRA[channel])} ${T("ตั้งน้ำหนักเอง (กรัม)", "Set a weight (g)")} ${T("ตั้งค่า", "Set")} ${T("ใส่น้ำหนักรวม ไม่ใช่ค่าที่จะเพิ่ม", "Enter the total weight, not an amount to add")} `).join(''); } renderGrid(); function feedback(channel, message, style = '') { const el = document.getElementById(`feedback-${channel}`); el.textContent = message; el.className = `sim-input-feedback ${style}`.trim(); } function setBusy(channel, value) { if (value) busy.add(channel); else busy.delete(channel); document.querySelectorAll(`[data-channel="${channel}"] button`).forEach((button) => { button.disabled = value; }); document.getElementById(`in-${channel}`).disabled = value; } async function sendWeight(channel, body) { if (!CHANNELS[channel] || busy.has(channel) || scenarioBusy) return; const liveEsp32 = scales?.[channel]?.source === 'esp32' && scales[channel].online; setBusy(channel, true); feedback(channel, T('กำลังส่งค่า…', 'Sending…'), 'pending'); try { const result = await act('/api/sim', { channel, ...body }); if (!result) { feedback(channel, T('ส่งค่าไม่สำเร็จ ลองอีกครั้ง', "Couldn't send. Try again."), 'error'); return; } document.getElementById(`in-${channel}`).value = ''; feedback(channel, T(`ตั้งเป็น ${num(result.value_g, 1)} ก. แล้ว รอให้นิ่งก่อนบันทึก${liveEsp32 ? ' (ESP32 ยังส่งค่าอยู่ อาจทับค่านี้)' : ''}`, `Set to ${num(result.value_g, 1)} g. Wait for it to settle.${liveEsp32 ? ' The ESP32 is still sending and may override this.' : ''}`)); } finally { setBusy(channel, false); } } document.body.addEventListener('click', async (event) => { const quick = event.target.closest('button[data-ch]'); if (quick) { const channel = quick.dataset.ch; const item = QUICK[channel]?.[Number(quick.dataset.i)]; if (item) await sendWeight(channel, item[1]); return; } const scenario = event.target.closest('button[data-scenario]'); if (scenario) await runScenario(scenario.dataset.scenario); }); document.body.addEventListener('submit', async (event) => { const form = event.target.closest('form[data-set-form]'); if (!form) return; event.preventDefault(); const channel = form.dataset.setForm; const input = document.getElementById(`in-${channel}`); const raw = input.value.trim(); const value = Number(raw); if (raw === '' || !Number.isFinite(value) || value < 0 || !input.validity.valid) { input.setAttribute('aria-invalid', 'true'); feedback(channel, T('กรอกน้ำหนักตั้งแต่ 0 กรัมขึ้นไป', 'Enter 0 g or more'), 'error'); input.focus(); return; } input.removeAttribute('aria-invalid'); await sendWeight(channel, { value_g: value }); }); document.body.addEventListener('input', (event) => { if (!event.target.matches('input[id^="in-"]')) return; event.target.removeAttribute('aria-invalid'); const channel = event.target.id.slice(3); if (!busy.has(channel)) feedback(channel, ''); }); function scenarioFeedback(message, error = false) { const el = document.getElementById('scenario-feedback'); el.textContent = message; el.classList.toggle('error', error); } // Fill the return bins relative to their starting weights for the open meal. With five sorted bins the side dish // is shared out the way children tend to leave it: mostly vegetables when a lot comes back. const DISH_SHARE = { high: { veg: 0.7, protein: 0.22, fat: 0.08 }, normal: { veg: 0.55, protein: 0.35, fat: 0.1 } }; const BONE_SHARE = 0.03; // simulated bones and inedible bits, as a share of the main dish served async function runScenario(kind) { const current = state?.current; const rates = { high: [15, 28], normal: [13, 14] }[kind]; const bins = shown.filter((c) => c !== 'kitchen'); if (!rates || scenarioBusy || bins.some((c) => busy.has(c))) return; if (current?.meal?.status !== 'open' || !(current.metrics?.served_g > 0)) { scenarioFeedback(T('เริ่มมื้อและชั่งหม้อก่อน', 'Start a meal and weigh a pot first'), true); return; } const [ricePct, dishPct] = rates; const riceWaste = (current.metrics.rice_served_g * ricePct) / 100; const dishWaste = (current.metrics.dish_served_g * dishPct) / 100; const sorted = current.sorted_bins ?? {}; const targets = bins.length === 5 ? Object.fromEntries(FIVE_BINS.map((k) => [k, (sorted[k]?.start_g ?? 0) + (k === 'starch' ? riceWaste : k === 'bone' ? current.metrics.dish_served_g * BONE_SHARE : dishWaste * DISH_SHARE[kind][k])])) : { rice: (current.meal.return_rice_start ?? 0) + riceWaste, dish: (current.meal.return_dish_start ?? 0) + dishWaste }; scenarioBusy = true; renderScenarios(); bins.forEach((c) => setBusy(c, true)); scenarioFeedback(T('กำลังตั้งน้ำหนักถังเศษ…', 'Setting the bins…')); try { for (const [channel, value] of Object.entries(targets)) { if (!await act('/api/sim', { channel, value_g: value })) { scenarioFeedback(T(`ตั้ง${CHANNELS[channel].title}ไม่สำเร็จ`, `Couldn't set the ${CHANNELS[channel].title}`), true); return; } } scenarioFeedback(T(`ตั้งแล้ว ข้าวเหลือ ${ricePct}% กับข้าวเหลือ ${dishPct}% รอให้นิ่งก่อนจบมื้อ`, `Done. Rice ${ricePct}% left, main dish ${dishPct}% left. Wait before ending the meal.`)); } finally { scenarioBusy = false; bins.forEach((c) => setBusy(c, false)); renderScenarios(); } } function renderScenarios() { const current = state?.current; const open = current?.meal?.status === 'open' && current.metrics?.served_g > 0; document.getElementById('scenario-note').textContent = open ? T(`ตักไปแล้ว ${kg(current.metrics.served_g)} กก. เลือกว่าจะให้เหลือแบบไหน`, `${kg(current.metrics.served_g)} kg served. Choose how much comes back.`) : T('เริ่มมื้อและชั่งหม้อในหน้าครัวก่อน', 'Start a meal and weigh a pot on the kitchen screen first'); document.getElementById('scenarios').innerHTML = ` ${T("เหลือเยอะ", "High leftovers")}${T("ข้าว 15% กับข้าว 28%", "Rice 15%, main dish 28%")} ${T("เหลือปกติ", "Normal leftovers")}${T("ข้าว 13% กับข้าว 14%", "Rice 13%, main dish 14%")}`; } function refreshState(version) { if (stateLoading || (state && stateVersion === version) || (stateVersion === version && Date.now() - lastStateAttempt < 5000)) return; stateVersion = version; lastStateAttempt = Date.now(); stateLoading = true; api('/api/state').then((next) => { state = next; if (['kitchen', ...binsInUse()].join() !== shown.join()) renderGrid(); renderScenarios(); }).catch(() => { document.getElementById('scenario-note').textContent = T('โหลดไม่สำเร็จ กำลังลองใหม่…', 'Loading failed, retrying…'); }).finally(() => { stateLoading = false; }); } renderScenarios(); live((tick) => { if (!tick?.scales) return; scales = tick.scales; voiceState = tick.voice; renderVoice(); refreshState(tick.version); for (const channel of shown) { const reading = scales[channel]; if (!reading || !document.getElementById(`val-${channel}`)) continue; document.getElementById(`val-${channel}`).innerHTML = `${reading.online ? num(reading.raw, 1) : '—'}${T('ก.', 'g')}`; const source = document.getElementById(`src-${channel}`); source.textContent = reading.source === 'esp32' ? 'ESP32' : 'SIM'; source.className = `chip ${!reading.online ? 'crit' : reading.source === 'esp32' ? 'good' : 'warn'}`; const stability = document.getElementById(`stable-${channel}`); stability.textContent = !reading.online ? T('ไม่มีสัญญาณ', 'No signal') : reading.stable ? T('นิ่งแล้ว', 'Steady') : T('รอให้นิ่ง', 'Settling'); stability.className = `sim-stability ${!reading.online ? 'crit' : reading.stable ? '' : 'warn'}`; document.getElementById(`source-hint-${channel}`).textContent = !reading.online ? T('เครื่องไม่มีสัญญาณ กดปุ่มด้านล่างเพื่อใช้ค่าจำลองแทน', 'No signal. Tap a button below to simulate instead.') : reading.source === 'esp32' ? T('เครื่องจริงกำลังส่งค่า ถ้ากดค่าจำลอง ESP32 อาจทับค่าทันที', 'The real scale is sending. It may override simulated values.') : T('กำลังใช้ค่าจำลอง รอให้นิ่งก่อนบันทึก', 'Using simulated values. Wait for them to settle.'); } });
${info.purpose}
${T("กำลังเชื่อมต่อ…", "Connecting…")}
${T("กดแล้วส่งค่าทันที", "Sends immediately")}
${T("ใส่น้ำหนักรวม ไม่ใช่ค่าที่จะเพิ่ม", "Enter the total weight, not an amount to add")}