Files
meshcore-tth/docs/_js/power-calculator.js
T
2026-12-04 17:55:09 +01:00

692 lines
37 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* Power calculator of the docs site (docs/power-calculator.md, issue #48).
Plain JS, no framework, no build step. Loaded on every page through
extra_javascript in mkdocs.tth.yml; does nothing unless the page has
<div id="pcalc">. Every number comes from docs/power-data.json, this file
holds only the method (baseline + deltas + LoRa airtime) and the UI text.
UI: a simple view (what an operator knows), one "Advanced" section for the
rest, the result on top (sticky right column on a wide screen). */
(function () {
'use strict';
var script = document.currentScript;
var T = {
en: {
node: 'Node', settings: 'Settings', traffic: 'Traffic', battery: 'Battery',
advanced: 'Advanced', breakdown: 'Breakdown', values: 'All values of the data file',
board: 'Board', firmware: 'Firmware',
powersaving: 'powersaving', rxps: 'radio.rxps', rxgain: 'radio.rxgain', ble: 'BLE', gps: 'GPS',
mah: 'Battery (mAh)', panel_w: 'Solar panel (W)', panel_hint: '0 = no panel',
rx_override: 'received packets / h', tx_override: 'transmitted packets / h',
override_hint: 'empty = the preset (quiet 30/10, normal 120/60, busy 600/300 RX/TX per hour)',
payload: 'packet length (bytes)', sf: 'SF', bw: 'BW (kHz)', cr: 'CR (4/x)',
preamble: 'preamble (symbols)', tx_dbm: 'TX power (dBm)',
tx_ma: 'TX current (mA), estimate', rx_extra: 'extra current while receiving (mA), estimate',
usable_pct: 'usable capacity (%)', voltage: 'battery voltage (V)',
charge_eff_pct: 'charging efficiency (%), estimate', site_pct: 'real installation (% of the model)', month: 'Month', orient: 'Panel faces',
panel_w_each: 'W per panel', charger: 'charger', chem: 'battery chemistry', dark_days: 'days without sun',
dark_ok: '{d} days without sun: the battery carries them ({p} % left)',
dark_bad: '{d} days without sun: the battery lasts only {n}',
recover: 'refilled in {n} days of this month\'s balance', norecover: 'this month\'s balance does not refill it',
coldcap: 'capacity −{p} % in the cold ({t} °C)',
sensors: 'I2C sensors', sensors_hint: 'datasheet estimate for how this firmware reads them',
covers: 'panel covers it', emptyafter: 'battery empty after {n} days in {m} (starting full)',
night: 'the battery does not carry the {h} h night of {m}: it lasts {x} h',
nightshort: 'but not through the night', monthbal: 'balance per month (mAh/day)', bal_in: 'balance in', perdayu: 'mAh/day',
unavailable: 'not in this firmware',
avg: 'average current', autonomy: 'autonomy', days: 'days', perday: 'per day',
balance: 'daily balance', nosun: 'without sun', sensorline: 'I2C sensor',
measured: 'measured', estimate: 'estimate',
part_node: 'node', part_tx: 'TX', part_rx: 'RX',
base: 'whole node', borrowed: 'taken from', fwoffset: 'firmware difference measured on',
nofwoffset: 'this firmware is not measured on this board: another firmware\'s baseline is used as is',
txline: 'transmitting', rxline: 'receiving', solar: 'solar gain per day',
details: 'details', src: 'source', kind: 'kind', option: 'option', value: 'value', date: 'date',
foot: 'Airtime of one packet {a} ms. Currents of the measurement rig at {v} V; the node is assumed to draw the same from the cell.',
loadfail: 'Could not load power-data.json: '
},
cs: {
node: 'Uzel', settings: 'Nastavení', traffic: 'Provoz', battery: 'Baterie',
advanced: 'Pokročilé', breakdown: 'Rozpis', values: 'Všechny hodnoty datového souboru',
board: 'Deska', firmware: 'Firmware',
powersaving: 'powersaving', rxps: 'radio.rxps', rxgain: 'radio.rxgain', ble: 'BLE', gps: 'GPS',
mah: 'Baterie (mAh)', panel_w: 'Solární panel (W)', panel_hint: '0 = bez panelu',
rx_override: 'přijatých paketů / h', tx_override: 'odvysílaných paketů / h',
override_hint: 'prázdné = předvolba (klidný 30/10, běžný 120/60, rušný 600/300 RX/TX za hodinu)',
payload: 'délka paketu (bajty)', sf: 'SF', bw: 'BW (kHz)', cr: 'CR (4/x)',
preamble: 'preambule (symboly)', tx_dbm: 'vysílací výkon (dBm)',
tx_ma: 'proud při vysílání (mA), odhad', rx_extra: 'proud navíc při příjmu (mA), odhad',
usable_pct: 'využitelná kapacita (%)', voltage: 'napětí baterie (V)',
charge_eff_pct: 'účinnost nabíjení (%), odhad', site_pct: 'reálná instalace (% modelu)', month: 'Měsíc', orient: 'Panel míří na',
panel_w_each: 'W na jeden panel', charger: 'nabíječ', chem: 'chemie článku', dark_days: 'dny bez slunce',
dark_ok: 'po {d} dnech bez slunce zbude v baterii {p} %',
dark_bad: 'bez slunce vydrží baterie jen {n} (zadáno {d})',
recover: 'dobije se za {n} dní bilance tohoto měsíce', norecover: 'bilance tohoto měsíce ji nedobije',
coldcap: 'kapacita −{p} % zimou ({t} °C)',
sensors: 'Čidla na I2C', sensors_hint: 'odhad z datasheetu podle toho, jak je tento firmware čte',
covers: 'panel stačí', emptyafter: 'baterie prázdná po {n} dnech, měsíc {m} (z plné)',
night: 'baterie neutáhne {h} h noci (měsíc {m}): vydrží {x} h',
nightshort: 'ale noc nevydrží', monthbal: 'bilance po měsících (mAh/den)', bal_in: 'bilance, měsíc', perdayu: 'mAh/den',
unavailable: 'tento firmware nemá',
avg: 'průměrný proud', autonomy: 'výdrž', days: 'dní', perday: 'za den',
balance: 'denní bilance', nosun: 'bez slunce', sensorline: 'čidlo na I2C',
measured: 'změřeno', estimate: 'odhad',
part_node: 'uzel', part_tx: 'TX', part_rx: 'RX',
base: 'celý uzel', borrowed: 'převzato z', fwoffset: 'rozdíl firmwarů změřený na',
nofwoffset: 'tento firmware na této desce změřený není: použit základ jiného firmwaru tak, jak je',
txline: 'vysílání', rxline: 'příjem', solar: 'zisk ze soláru za den',
details: 'podrobnosti', src: 'zdroj', kind: 'druh', option: 'volba', value: 'hodnota', date: 'datum',
foot: 'Vysílání jednoho paketu trvá {a} ms. Proudy měřicí sestavy při {v} V; předpokládá se, že uzel bere z článku stejný proud.',
loadfail: 'Nepodařilo se načíst power-data.json: '
}
};
function el(tag, attrs, kids) {
var e = document.createElement(tag);
Object.keys(attrs || {}).forEach(function (k) {
if (k === 'text') e.textContent = attrs[k];
else if (attrs[k] !== false && attrs[k] != null) e.setAttribute(k, attrs[k]);
});
(kids || []).forEach(function (c) {
if (c != null) e.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
});
return e;
}
function start() {
var root = document.getElementById('pcalc');
if (!root || !script) return;
var base = new URL('../', script.src); // the script lives in <site>/_js/
fetch(new URL('power-data.json', base))
.then(function (r) {
if (!r.ok) throw new Error('HTTP ' + r.status);
return r.json();
})
.then(function (d) { new Calc(root, d, base); })
.catch(function (e) { root.textContent = T.en.loadfail + e.message; });
}
function Calc(root, d, base) {
this.root = root;
this.d = d;
this.base = base;
this.open = {};
var h = location.hash.replace('#', '');
this.lang = h === 'cs' || h === 'en' ? h :
(navigator.language || '').slice(0, 2) === 'cs' ? 'cs' : 'en';
var td = d.traffic.defaults, b = d.battery;
this.s = {
board: d.boards[0].id, firmware: d.firmwares[0].id,
preset: td.preset, rx_override: '', tx_override: '', payload: td.payload,
sf: td.sf, bw: td.bw, cr: td.cr, preamble: td.preamble, tx_dbm: td.tx_dbm,
rx_extra: d.traffic.rx_extra.value,
mah: b.mah, usable_pct: b.usable_pct, voltage: b.voltage,
panel_w: b.panel_w, charge_eff_pct: b.charge_eff_pct, site_pct: d.battery.site_pct,
month: d.solar.default_month, orient: d.solar.orientation[0].id, sensors: {},
charger: d.solar.chargers[0].id, chem: d.solar.chemistries[0].id, dark_days: d.solar.dark_days
};
this.s.tx_ma = this.txCurrent(this.s.tx_dbm);
this.applyDefaults(true);
this.build();
}
var P = Calc.prototype;
P.t = function (k) { return T[this.lang][k] || k; };
P.n = function (o) { return o[this.lang] || o.en; }; // localized name of a data object
P.fmt = function (x, dec) {
var s = x.toFixed(dec == null ? 2 : dec);
return this.lang === 'cs' ? s.replace('.', ',') : s;
};
P.board = function () { var s = this.s; return this.d.boards.filter(function (b) { return b.id === s.board; })[0]; };
P.fw = function () { var s = this.s; return this.d.firmwares.filter(function (f) { return f.id === s.firmware; })[0]; };
P.fwById = function (id) { return this.d.firmwares.filter(function (f) { return f.id === id; })[0] || { en: id }; };
P.boardById = function (id) { return this.d.boards.filter(function (f) { return f.id === id; })[0] || { en: id }; };
P.available = function (opt) {
if (opt === 'gps' && !this.board().gps) return false;
return this.fw().options.indexOf(opt) >= 0;
};
// board defaults, then what the firmware ships with; options it lacks are pinned off
// boardChanged: also the battery and panel the board ships with
P.applyDefaults = function (boardChanged) {
var self = this, def = Object.assign({}, this.board().defaults, this.fw().defaults);
if (boardChanged) {
['mah', 'panel_w'].forEach(function (k) {
self.s[k] = def[k] != null ? def[k] : self.d.battery[k];
});
if (def.charger) this.setCharger(def.charger);
if (def.chem) this.setChem(def.chem);
}
Object.keys(this.d.settings).forEach(function (k) {
var vals = self.d.settings[k];
if (!self.available(k)) self.s[k] = vals.indexOf('off') >= 0 ? 'off' : vals[0];
else if (def[k] != null) self.s[k] = def[k];
else if (vals.indexOf(self.s[k]) < 0) self.s[k] = vals[0];
});
};
// radio current in TX, linear between the points of the data file
P.txCurrent = function (dbm) {
var pts = this.d.traffic.tx_current.points.slice().sort(function (a, b) { return a.dbm - b.dbm; });
if (dbm <= pts[0].dbm) return pts[0].value;
for (var i = 1; i < pts.length; i++) {
if (dbm <= pts[i].dbm) {
var a = pts[i - 1], b = pts[i];
return Math.round(a.value + (b.value - a.value) * (dbm - a.dbm) / (b.dbm - a.dbm));
}
}
return pts[pts.length - 1].value;
};
// LoRa time on air, Semtech SX1262 datasheet / AN1200.13: explicit header, CRC on
P.airtime = function () {
var s = this.s, sf = +s.sf, bw = +s.bw * 1000, cr = +s.cr - 4;
var tsym = Math.pow(2, sf) / bw;
var de = tsym > 0.016 ? 1 : 0;
var num = 8 * s.payload - 4 * sf + 28 + 16;
var nPay = 8 + Math.max(Math.ceil(num / (4 * (sf - 2 * de))) * (cr + 4), 0);
return (+s.preamble + 4.25) * tsym + nPay * tsym;
};
// packets per hour: the explicit numbers of the advanced section, else the preset
P.traffic = function () {
var s = this.s, p = this.d.traffic.presets.filter(function (x) { return x.id === s.preset; })[0];
return {
rx: s.rx_override === '' ? p.rx_per_h : +s.rx_override,
tx: s.tx_override === '' ? p.tx_per_h : +s.tx_override
};
};
// a charger / chemistry preset sets the numbers it stands for (still overridable)
P.setCharger = function (id) {
var c = this.d.solar.chargers.filter(function (x) { return x.id === id; })[0];
if (c) { this.s.charger = id; this.s.charge_eff_pct = c.eff_pct; }
};
P.setChem = function (id) {
var c = this.d.solar.chemistries.filter(function (x) { return x.id === id; })[0];
if (c) { this.s.chem = id; this.s.usable_pct = c.usable_pct; this.s.voltage = c.voltage; }
};
// capacity lost to cold in month m, % (linear between the points of the data file)
P.coldLoss = function (m) {
var t = this.d.solar.temp_c[m - 1];
var pts = this.d.solar.cold_derate.slice().sort(function (a, b) { return a.t - b.t; });
if (t <= pts[0].t) return pts[0].loss_pct;
for (var i = 1; i < pts.length; i++) {
if (t <= pts[i].t) {
var a = pts[i - 1], b = pts[i];
return a.loss_pct + (b.loss_pct - a.loss_pct) * (t - a.t) / (b.t - a.t);
}
}
return pts[pts.length - 1].loss_pct;
};
P.usableAt = function (m) {
var s = this.s;
return s.mah * s.usable_pct / 100 * (1 - this.coldLoss(m) / 100);
};
P.orientRow = function () {
var s = this.s;
return this.d.solar.orientation.filter(function (x) { return x.id === s.orient; })[0];
};
// solar gain in mAh per day in month m (1..12)
P.solarGain = function (m) {
var s = this.s, so = this.d.solar;
var o = so.orientation.filter(function (x) { return x.id === s.orient; })[0];
var f = o.factor_month ? o.factor_month[m - 1] : o.factor;
return s.panel_w * so.sun_h[m - 1] * f * (s.charge_eff_pct / 100) * (s.site_pct / 100) / s.voltage * 1000;
};
P.monthName = function (m) {
return new Date(2026, m - 1, 15).toLocaleString(this.lang === 'cs' ? 'cs-CZ' : 'en-GB', { month: 'long' });
};
P.range = function (v) { return Array.isArray(v) ? [Math.min(v[0], v[1]), Math.max(v[0], v[1])] : [v, v]; };
P.pickBaseline = function () {
var s = this.s, keys = Object.keys(this.d.settings);
var bid = s.board, like = this.board().like;
var rows = this.d.values.filter(function (v) { return v.kind === 'baseline' && v.board === bid; });
if (!rows.length && like) rows = this.d.values.filter(function (v) { return v.kind === 'baseline' && v.board === like; });
var same = rows.filter(function (v) { return v.firmware === s.firmware; });
var pool = same.length ? same : rows;
function diff(v) { return keys.filter(function (k) { return v.settings[k] !== s[k]; }).length; }
pool.sort(function (a, b) {
return diff(a) - diff(b) || (b.measured - a.measured) || (a.firmware === 'tth' ? -1 : 1);
});
return { row: pool[0], borrowed: !same.length, boardBorrowed: pool[0].board !== bid };
};
// delta rows of one option between two values, best match first:
// same board and firmware, same board, any board
P.findDelta = function (opt, from, to) {
var s = this.s, best = null;
this.d.values.forEach(function (v) {
if (v.kind !== 'delta' || v.option !== opt) return;
var sign = v.from === from && v.to === to ? 1 : v.from === to && v.to === from ? -1 : 0;
if (!sign) return;
var fwOk = v.firmware === '*' || v.firmware === s.firmware;
var rank = (v.board === s.board ? 0 : 2) + (fwOk ? 0 : 1);
if (!best || rank < best.rank) best = { row: v, sign: sign, rank: rank };
});
return best;
};
// (chosen firmware) - (baseline's firmware) with identical settings on another board
P.fwOffset = function (b) {
var s = this.s, vals = this.d.values, found = null;
vals.forEach(function (a) {
if (found || a.kind !== 'baseline' || a.firmware !== s.firmware || a.board === b.board) return;
vals.forEach(function (c) {
if (found || c.kind !== 'baseline' || c.board !== a.board || c.firmware !== b.firmware) return;
if (JSON.stringify(a.settings) === JSON.stringify(c.settings)) found = { board: a.board, value: a.value - c.value, row: a };
});
});
return found;
};
P.cost = function (opt, to) {
return this.d.values.filter(function (v) { return v.kind === 'reception' && v.option === opt && v.to === to; })[0];
};
P.settingsText = function (row) {
var self = this;
return Object.keys(row.settings).filter(function (k) {
return k !== 'gps' || self.board().gps;
}).map(function (k) { return k + ' ' + row.settings[k]; }).join(', ');
};
// lines of the breakdown; part = node | tx | rx (the bar), lo/hi in mA
P.compute = function () {
var self = this, s = this.s, d = this.d, lines = [];
var pb = this.pickBaseline(), b = pb.row;
var u = b.uncertainty || 0, bmeas = b.measured && !pb.borrowed && !pb.boardBorrowed;
var bnote = pb.boardBorrowed ? this.t('borrowed') + ' ' + this.n(this.boardById(b.board)) :
b.firmware !== s.firmware ? this.t('borrowed') + ' ' + this.n(this.fwById(b.firmware)) : null;
lines.push({ part: 'node', label: this.t('base') + ' (' + this.settingsText(b) + ')', lo: b.value - u, hi: b.value + u,
approx: b.approx, measured: bmeas, row: b, note: bnote || (b['note_' + this.lang] || b.note_en) });
if (pb.borrowed) { // offset between the two firmwares, measured on another board
var off = this.fwOffset(b);
if (off) lines.push({ part: 'node', label: this.t('fwoffset') + ' ' + this.n(this.boardById(off.board)), lo: off.value, hi: off.value, measured: false, row: off.row });
else lines.push({ part: 'node', label: this.t('nofwoffset'), lo: 0, hi: 0, measured: false, row: null, nonum: true });
}
Object.keys(d.settings).forEach(function (k) {
var from = b.settings[k], to = s[k];
if (from === to || from == null) return;
var path = [], dd = self.findDelta(k, from, to);
if (dd) path.push(dd);
else d.settings[k].some(function (mid) { // one step through an intermediate value
var a = self.findDelta(k, from, mid), c = a && self.findDelta(k, mid, to);
if (a && c) { path.push(a, c); return true; }
return false;
});
if (!path.length) {
lines.push({ part: 'node', label: k + ': ' + from + ' → ' + to, nonum: true, measured: false, row: null, lo: 0, hi: 0, note: '?' });
return;
}
path.forEach(function (p) {
var r = self.range(p.row.value).map(function (x) { return x * p.sign; });
var meas = p.row.measured && p.rank === 0;
var note = p.rank ? self.t('borrowed') + ' ' + self.n(self.boardById(p.row.board)) +
(p.row.firmware !== '*' ? ' / ' + self.n(self.fwById(p.row.firmware)) : '') : null;
lines.push({ part: 'node', label: k + ': ' + (p.sign > 0 ? p.row.from + ' → ' + p.row.to : p.row.to + ' → ' + p.row.from),
lo: Math.min(r[0], r[1]), hi: Math.max(r[0], r[1]), approx: p.row.approx, measured: meas, row: p.row,
note: note || (p.row['note_' + self.lang] || p.row.note_en) });
});
});
d.sensors.list.forEach(function (x) {
if (!s.sensors[x.id]) return;
var v = x[s.firmware] != null ? x[s.firmware] : x['*'];
lines.push({ part: 'node', label: self.t('sensorline') + ': ' + x.name, lo: v, hi: v, measured: false,
row: { source: d.sensors.source }, note: x.how });
});
var at = this.airtime(), tr = this.traffic();
var tx = tr.tx * at / 3600 * s.tx_ma, rx = tr.rx * at / 3600 * s.rx_extra;
var ms = this.fmt(at * 1000, 0);
lines.push({ part: 'tx', label: this.t('txline') + ' (' + tr.tx + '/h × ' + ms + ' ms × ' + s.tx_ma + ' mA)', lo: tx, hi: tx, measured: false, row: null });
lines.push({ part: 'rx', label: this.t('rxline') + ' (' + tr.rx + '/h × ' + ms + ' ms × ' + s.rx_extra + ' mA)', lo: rx, hi: rx, measured: false, row: null });
var r = { lines: lines, lo: 0, hi: 0, meas: 0, est: 0, parts: { node: 0, tx: 0, rx: 0 }, airtime: at, voltage: b.voltage };
lines.forEach(function (l) {
var mid = (l.lo + l.hi) / 2;
r.lo += l.lo; r.hi += l.hi; r.parts[l.part] += mid;
if (l.measured) r.meas += mid; else r.est += mid;
});
return r;
};
P.srcLink = function (key) {
var src = this.d.sources[key];
if (!src) return document.createTextNode(key || '');
if (!src.url) return document.createTextNode(this.n(src));
var parts = src.url.split('#'), p = parts[0];
// mkdocs directory URLs: power.md -> power/, a/index.md -> a/
p = p.replace(/(^|\/)index\.md$/, '$1').replace(/\.md$/, '/');
var href = new URL(p, this.base).href + (parts[1] ? '#' + parts[1] : '');
return el('a', { href: href, text: this.n(src) });
};
P.badge = function (m) {
return el('span', { 'class': m ? 'pc-m' : 'pc-e', text: m ? this.t('measured') : this.t('estimate') });
};
// ---- UI ----
// segmented buttons; disabled = the option does not exist in this firmware
P.seg = function (key, opts, disabled) {
var s = this.s;
return el('div', { 'class': 'pc-seg', role: 'group', 'aria-label': this.t(key) }, opts.map(function (o) {
return el('button', { type: 'button', 'data-k': key, 'data-v': o.v, 'aria-pressed': String(s[key]) === String(o.v) ? 'true' : 'false',
disabled: disabled ? 'disabled' : false, text: o.t });
}));
};
P.field = function (label, input, hint) {
return el('div', { 'class': 'pc-field' }, [el('label', { 'class': 'pc-label', text: label }), input,
hint ? el('div', { 'class': 'pc-hint' }, [hint]) : null]);
};
P.num = function (key, opts) {
opts = opts || {};
return el('input', { type: 'number', name: key, value: this.s[key], step: opts.step || 'any',
min: opts.min != null ? opts.min : '0', placeholder: opts.ph || false, inputmode: 'decimal' });
};
P.select = function (key, opts) {
var s = this.s, e = el('select', { name: key });
opts.forEach(function (o) {
var op = el('option', { value: o.v, text: o.t });
if (String(s[key]) === String(o.v)) op.selected = true;
e.appendChild(op);
});
return e;
};
// reception cost of a setting, as one warning line with its source
P.warn = function (key, small) {
var c = this.cost(key, this.s[key]);
if (!c) return null;
var link = this.srcLink(c.source);
if (link.tagName === 'A') { link.textContent = this.t('details'); link.title = this.n(c); }
return el('div', { 'class': 'pc-hint', role: 'note' },
[(c['short_' + this.lang] || this.n(c)) + ' · ', link]);
};
P.settingRow = function (k, small) {
var on = this.available(k);
var hint = on ? this.warn(k, small) : el('div', { 'class': 'pc-hint', text: this.t('unavailable') });
return el('div', { 'class': 'pc-field' }, [el('span', { 'class': 'pc-label', text: this.t(k) }),
this.seg(k, this.d.settings[k].map(function (v) { return { v: v, t: v }; }), !on), hint]);
};
P.build = function () {
var self = this, s = this.s, d = this.d;
var focus = document.activeElement && this.root.contains(document.activeElement) ?
document.activeElement.getAttribute('data-k') + '=' + document.activeElement.getAttribute('data-v') : null;
this.root.textContent = '';
var langSeg = el('div', { 'class': 'pc-seg pc-lang', role: 'group', 'aria-label': 'language' }, [['cs', 'CZ'], ['en', 'EN']].map(function (l) {
return el('button', { type: 'button', 'data-lang': l[0], 'aria-pressed': self.lang === l[0] ? 'true' : 'false', text: l[1] });
}));
// simple view
var form = el('form', { 'class': 'pc-form' });
form.appendChild(el('div', { 'class': 'pc-two pc-sel' }, [
this.field(this.t('board'), this.select('board', d.boards.map(function (b) { return { v: b.id, t: self.n(b) }; }))),
this.field(this.t('firmware'), this.select('firmware', d.firmwares.map(function (f) { return { v: f.id, t: self.n(f) }; })))
]));
var sets = el('div', { 'class': 'pc-sets' });
['powersaving', 'rxps', 'ble', 'gps'].forEach(function (k) {
if (k === 'gps' && !self.board().gps) return;
sets.appendChild(self.settingRow(k));
});
form.appendChild(sets);
var presetDis = s.rx_override !== '' && s.tx_override !== '';
form.appendChild(el('div', { 'class': 'pc-field' }, [el('span', { 'class': 'pc-label', text: this.t('traffic') }),
this.seg('preset', d.traffic.presets.map(function (p) { return { v: p.id, t: self.n(p) }; }), presetDis)]));
form.appendChild(el('div', { 'class': 'pc-two' }, [
this.field(this.t('mah'), this.num('mah', { step: 100 })),
this.field(this.t(this.orientRow().per_panel ? 'panel_w_each' : 'panel_w'), this.num('panel_w', { step: 0.5 }), this.t('panel_hint'))
]));
var months = [];
for (var m = 1; m <= 12; m++) months.push({ v: m, t: this.monthName(m) });
form.appendChild(el('div', { 'class': 'pc-two' }, [
this.field(this.t('month'), this.select('month', months)),
this.field(this.t('dark_days'), this.num('dark_days', { step: 1 }))
]));
// four orientations need the full width
form.appendChild(el('div', { 'class': 'pc-field' }, [el('span', { 'class': 'pc-label', text: this.t('orient') }),
this.seg('orient', d.solar.orientation.map(function (o) { return { v: o.id, t: self.n(o) }; }))]));
var chips = el('div', { 'class': 'pc-chips' }, d.sensors.list.map(function (x) {
var cb = el('input', { type: 'checkbox', 'data-sensor': x.id });
cb.checked = !!s.sensors[x.id];
return el('label', { 'class': 'pc-chip', title: x.how }, [cb, x.name]);
}));
// collapsed: a dozen chips would take half the page; the summary says how many are picked
var nSel = d.sensors.list.filter(function (x) { return s.sensors[x.id]; }).length;
var sens = el('details', { 'class': 'pc-adv pc-sens', 'data-open': 'sens' });
if (this.open.sens) sens.open = true;
sens.appendChild(el('summary', { text: this.t('sensors') + (nSel ? ' (' + nSel + ')' : '') }));
sens.appendChild(chips);
sens.appendChild(el('div', { 'class': 'pc-hint' }, [this.t('sensors_hint') + ' ', this.badge(false)]));
form.appendChild(sens);
// advanced
var adv = el('details', { 'class': 'pc-adv', 'data-open': 'adv' });
if (this.open.adv) adv.open = true;
adv.appendChild(el('summary', { text: this.t('advanced') }));
adv.appendChild(this.settingRow('rxgain', true));
var grid = el('div', { 'class': 'pc-grid3' });
grid.appendChild(this.field(this.t('rx_override'), this.num('rx_override', { step: 1, ph: String(this.traffic().rx) })));
grid.appendChild(this.field(this.t('tx_override'), this.num('tx_override', { step: 1, ph: String(this.traffic().tx) })));
grid.appendChild(this.field(this.t('payload'), this.num('payload', { step: 1 })));
grid.appendChild(this.field(this.t('sf'), this.select('sf', [7, 8, 9, 10, 11, 12].map(function (v) { return { v: v, t: v }; }))));
grid.appendChild(this.field(this.t('bw'), this.select('bw', [62.5, 125, 250].map(function (v) { return { v: v, t: v }; }))));
grid.appendChild(this.field(this.t('cr'), this.select('cr', [5, 6, 7, 8].map(function (v) { return { v: v, t: '4/' + v }; }))));
grid.appendChild(this.field(this.t('preamble'), this.num('preamble', { step: 1 })));
grid.appendChild(this.field(this.t('tx_dbm'), this.num('tx_dbm', { step: 1, min: '-9' })));
grid.appendChild(this.field(this.t('tx_ma'), this.num('tx_ma')));
grid.appendChild(this.field(this.t('rx_extra'), this.num('rx_extra')));
grid.appendChild(this.field(this.t('chem'), this.select('chem', d.solar.chemistries.map(function (c) { return { v: c.id, t: self.n(c) }; }))));
grid.appendChild(this.field(this.t('usable_pct'), this.num('usable_pct', { step: 5 })));
grid.appendChild(this.field(this.t('voltage'), this.num('voltage', { step: 0.1 })));
grid.appendChild(this.field(this.t('charger'), this.select('charger', d.solar.chargers.map(function (c) { return { v: c.id, t: self.n(c) + ' ' + c.eff_pct + ' %' }; }))));
grid.appendChild(this.field(this.t('charge_eff_pct'), this.num('charge_eff_pct', { step: 5 })));
grid.appendChild(this.field(this.t('site_pct'), this.num('site_pct', { step: 5 })));
adv.appendChild(grid);
adv.appendChild(el('p', { 'class': 'pc-hint', text: this.t('override_hint') }));
form.appendChild(adv);
form.addEventListener('input', function (ev) {
var t = ev.target, k = t.name;
if (t.hasAttribute('data-sensor')) { s.sensors[t.getAttribute('data-sensor')] = t.checked; self.render(); return; }
if (!k) return;
if (t.tagName === 'SELECT') {
s[k] = isNaN(+t.value) ? t.value : +t.value;
if (k === 'board' || k === 'firmware') self.applyDefaults(k === 'board');
if (k === 'charger') self.setCharger(t.value);
if (k === 'chem') self.setChem(t.value);
self.build();
return;
}
if (t.value === '') {
if (k === 'rx_override' || k === 'tx_override') s[k] = '';
else return;
} else s[k] = +t.value;
if (k === 'tx_dbm') {
s.tx_ma = self.txCurrent(s[k]);
self.root.querySelector('[name=tx_ma]').value = s.tx_ma;
}
self.render();
});
form.addEventListener('submit', function (ev) { ev.preventDefault(); });
this.out = el('div', { 'class': 'pc-result', 'aria-live': 'polite' });
this.root.appendChild(el('div', { 'class': 'pc-card' }, [
el('div', { 'class': 'pc-head' }, [el('strong', { text: this.lang === 'cs' ? 'Kalkulačka spotřeby' : 'Power calculator' }), langSeg]),
el('div', { 'class': 'pc-layout' }, [this.out, form])
]));
var vals = el('details', { 'class': 'pc-values', 'data-open': 'values' }, [el('summary', { text: this.t('values') })]);
if (this.open.values) vals.open = true;
// at the end of the page when it has a place for it, else under the card
var vbox = document.getElementById('pcalc-values') || this.root;
if (vbox !== this.root) vbox.textContent = '';
vbox.appendChild(vals);
this.renderValues(vals);
this.root.addEventListener('click', this.onClick || (this.onClick = function (ev) {
var b = ev.target.closest('button');
if (!b || !self.root.contains(b)) return;
if (b.hasAttribute('data-lang')) { self.lang = b.getAttribute('data-lang'); self.build(); return; }
var k = b.getAttribute('data-k');
if (!k) return;
var v = b.getAttribute('data-v');
s[k] = isNaN(+v) ? v : +v;
self.build();
}));
this.onToggle = this.onToggle || function (ev) {
var k = ev.target.getAttribute && ev.target.getAttribute('data-open');
if (k) self.open[k] = ev.target.open;
};
this.root.addEventListener('toggle', this.onToggle, true);
vbox.addEventListener('toggle', this.onToggle, true);
this.render();
if (focus) {
var f = this.root.querySelector('[data-k="' + focus.split('=')[0] + '"][data-v="' + focus.split('=')[1] + '"]');
if (f) f.focus();
}
};
P.render = function () {
var self = this, s = this.s, r = this.compute(), out = this.out;
out.textContent = '';
var mid = (r.lo + r.hi) / 2, perDay = mid * 24, usable = this.usableAt(s.month);
var so = this.d.solar, tmon = so.temp_c[s.month - 1], cold = this.coldLoss(s.month), notes = [];
if (cold > 0.5) notes.push(this.t('coldcap').replace('{p}', this.fmt(cold, 0)).replace('{t}', this.fmt(tmon, 1)));
// the two big numbers
var rng = r.hi - r.lo > 0.005 ? this.fmt(r.lo) + ' … ' + this.fmt(r.hi) + ' mA' : '';
var autoBig, autoSub, autoLabel = this.t('autonomy'), warnNight = null, strip = null, autoBad = false, darkLine = null;
if (s.panel_w > 0) {
var mn = this.monthName(s.month), bal = this.solarGain(s.month) - perDay;
autoLabel = this.t('bal_in') + ' ' + mn;
autoBig = (bal >= 0 ? '+' : '−') + this.fmt(Math.abs(bal), 0);
autoBad = bal < 0;
autoSub = this.t('perdayu') + ' · ' + (bal >= 0 ? this.t('covers') :
this.t('emptyafter').replace('{n}', this.fmt(usable / -bal, 1)).replace('{m}', mn)) +
' · ' + this.t('nosun') + ' ' + this.fmt(usable / perDay, 1) + ' ' + this.t('days');
strip = el('div', { 'class': 'pc-strip' });
for (var m = 1; m <= 12; m++) {
var bm = this.solarGain(m) - perDay, ab = Math.abs(bm);
var txt = (bm >= 0 ? '+' : '−') + (ab >= 1000 ? this.fmt(ab / 1000, 1) + 'k' : this.fmt(ab, 0));
strip.appendChild(el('span', { 'class': (bm < 0 ? 'pc-neg' : 'pc-pos') + (m === +s.month ? ' pc-cur' : ''),
title: this.monthName(m) + ': ' + txt + ' ' + this.t('perdayu') }, [
el('b', { text: this.monthName(m).slice(0, 3) }), el('span', { text: txt })]));
}
// the cell must carry the night of that month (said only when it does not)
var nh = this.d.solar.night_h[s.month - 1], lasts = usable / mid;
if (lasts < nh) warnNight = this.t('night').replace('{h}', this.fmt(nh, 0)).replace('{m}', mn).replace('{x}', this.fmt(lasts, 1));
if (warnNight) { autoBad = true; autoSub = autoSub.replace(this.t('covers'), '⚠ ' + this.t('nightshort')); }
// a dark streak from full, then how long this month's surplus takes to refill it
var dd = +s.dark_days || 0;
if (dd > 0) {
var need = dd * perDay;
if (need <= usable) {
var dl = this.t('dark_ok').replace('{d}', dd).replace('{p}', this.fmt((usable - need) / usable * 100, 0));
dl += ' · ' + (bal > 0 ? this.t('recover').replace('{n}', this.fmt(need / bal, 1)) : this.t('norecover'));
darkLine = el('div', { 'class': 'pc-hint', text: dl });
} else {
darkLine = el('div', { 'class': 'pc-warn', text: this.t('dark_bad').replace('{d}', dd)
.replace('{n}', this.fmt(usable / perDay, 1) + ' ' + this.t('days')) });
}
}
} else {
autoBig = this.fmt(usable / perDay, 1);
autoSub = this.t('days') + ' · ' + this.fmt(perDay, 0) + ' mAh ' + this.t('perday');
}
out.appendChild(el('div', { 'class': 'pc-big' }, [
el('div', {}, [el('div', { 'class': 'pc-label', text: this.t('avg') }),
el('div', { 'class': 'pc-bignum' }, [this.fmt(mid, mid >= 10 ? 1 : 2), el('span', { 'class': 'pc-unit', text: ' mA' })]),
el('div', { 'class': 'pc-sub', text: rng || ' ' })]),
el('div', {}, [el('div', { 'class': 'pc-label', text: autoLabel }),
el('div', { 'class': 'pc-bignum' + (autoBad ? ' pc-bad' : ''), text: autoBig }),
el('div', { 'class': 'pc-sub', text: autoSub })])
]));
if (strip) {
out.appendChild(el('div', { 'class': 'pc-label pc-strip-t', text: this.t('monthbal') }));
out.appendChild(strip);
}
if (darkLine) out.appendChild(darkLine);
if (warnNight) out.appendChild(el('div', { 'class': 'pc-warn', text: '⚠ ' + warnNight }));
if (tmon < 0) notes.push(so['cold_note_' + this.lang]);
notes.forEach(function (n) { out.appendChild(el('div', { 'class': 'pc-hint', text: n })); });
// split node / TX / RX
var tot = r.parts.node + r.parts.tx + r.parts.rx || 1, bar = el('div', { 'class': 'pc-bar', role: 'img',
'aria-label': ['node', 'tx', 'rx'].map(function (p) { return self.t('part_' + p) + ' ' + self.fmt(r.parts[p]) + ' mA'; }).join(', ') });
var legend = el('div', { 'class': 'pc-legend' });
['node', 'tx', 'rx'].forEach(function (p) {
var w = Math.max(0, r.parts[p]) / tot * 100;
bar.appendChild(el('span', { 'class': 'pc-b-' + p, style: 'width:' + w.toFixed(2) + '%' }));
legend.appendChild(el('span', {}, [el('i', { 'class': 'pc-b-' + p }), self.t('part_' + p) + ' ' + self.fmt(r.parts[p]) + ' mA']));
});
out.appendChild(bar);
out.appendChild(legend);
out.appendChild(el('div', { 'class': 'pc-me' }, [
el('span', { 'class': 'pc-m-t', text: this.t('measured') + ': ' + this.fmt(r.meas) + ' mA' }), ' · ',
el('span', { 'class': 'pc-e-t', text: this.t('estimate') + ': ' + this.fmt(r.est) + ' mA' })]));
// breakdown
var det = el('details', { 'class': 'pc-bd', 'data-open': 'bd' }, [el('summary', { text: this.t('breakdown') })]);
if (this.open.bd) det.open = true;
var tb = el('tbody');
r.lines.forEach(function (l) {
var val = l.nonum ? '' : (l.approx ? '~' : '') + (l.lo === l.hi ? self.fmt(l.lo) : self.fmt(l.lo) + ' … ' + self.fmt(l.hi)) + ' mA';
var info = [l.label, ' ', self.badge(l.measured)];
var sub = [];
if (l.row && l.row.source) sub.push(self.srcLink(l.row.source));
if (l.row && l.row.date) sub.push(' (' + l.row.date + ')');
if (l.note) sub.push(' · ' + l.note);
if (sub.length) info.push(el('div', { 'class': 'pc-hint' }, sub));
tb.appendChild(el('tr', {}, [el('td', {}, info), el('td', { 'class': 'pc-num', text: val })]));
});
if (s.panel_w > 0) {
var g = this.solarGain(s.month);
tb.appendChild(el('tr', {}, [el('td', {}, [this.t('solar') + ' (' + this.monthName(s.month) + ') ', this.badge(false)]), el('td', { 'class': 'pc-num', text: this.fmt(g, 0) + ' mAh' })]));
}
det.appendChild(el('table', { 'class': 'pc-lines' }, [tb]));
det.appendChild(el('p', { 'class': 'pc-hint', text: this.t('foot').replace('{a}', this.fmt(r.airtime * 1000, 0)).replace('{v}', this.fmt(r.voltage, 2)) }));
out.appendChild(det);
};
P.renderValues = function (box) {
var self = this, d = this.d;
var head = el('tr', {}, ['kind', 'board', 'firmware', 'option', 'value', 'date', '', 'src'].map(function (k) {
return el('th', { text: k ? self.t(k) : '' });
}));
var body = el('tbody');
d.values.forEach(function (v) {
var what = v.kind === 'baseline' ? Object.keys(v.settings).map(function (k) { return k + ' ' + v.settings[k]; }).join(', ') :
v.option ? v.option + ': ' + (v.from ? v.from + ' → ' : '') + (v.to || '') : '';
if (v.kind === 'reception' || v.kind === 'info') what += (what ? ' - ' : '') + self.n(v);
var val = v.value == null ? '' : (v.approx ? '~' : '') + (Array.isArray(v.value) ? self.fmt(v.value[0]) + ' … ' + self.fmt(v.value[1]) : self.fmt(v.value)) +
(v.uncertainty ? ' ± ' + self.fmt(v.uncertainty) : '') + ' ' + (v.unit || '') + (v.voltage ? ' @ ' + self.fmt(v.voltage, 2) + ' V' : '');
body.appendChild(el('tr', {}, [
el('td', { text: v.kind }), el('td', { text: v.board || '' }), el('td', { text: v.firmware || '' }),
el('td', { text: what }), el('td', { 'class': 'pc-num', text: val }), el('td', { text: v.date || '' }),
el('td', {}, [self.badge(v.measured)]), el('td', {}, [self.srcLink(v.source)])
]));
});
box.appendChild(el('div', { 'class': 'pc-scroll' }, [el('table', {}, [el('thead', {}, [head]), body])]));
};
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start);
else start();
})();