'use strict'; 'require view'; 'require rpc'; 'require ui'; 'require dom'; // Backend: /usr/libexec/rpcd/esim-tools (luci/rpcd.sh in the kit). // Everything that touches lpac or resets the modem runs as one background job // (esim ); the page polls its output. var callStatus = rpc.declare({ object: 'esim-tools', method: 'status', expect: { '': {} } }); var callModem = rpc.declare({ object: 'esim-tools', method: 'modem', expect: { '': {} } }); var callProfiles = rpc.declare({ object: 'esim-tools', method: 'profiles', expect: { '': {} } }); var callJob = rpc.declare({ object: 'esim-tools', method: 'job', expect: { '': {} } }); var callRun = rpc.declare({ object: 'esim-tools', method: 'run', params: [ 'cmd', 'a', 'b', 'c', 'flag' ], expect: { '': {} } }); var callAt = rpc.declare({ object: 'esim-tools', method: 'at', params: [ 'cmd' ], expect: { '': {} } }); var callConfigSet = rpc.declare({ object: 'esim-tools', method: 'config_set', params: [ 'at_port', 'wdm', 'iface' ], expect: { '': {} } }); var callUpdateCheck = rpc.declare({ object: 'esim-tools', method: 'update_check', expect: { '': {} } }); var GREEN = 'color:green', RED = 'color:#c00'; function wait(ms) { return new Promise(function(resolve) { window.setTimeout(resolve, ms); }); } function row(title, value) { return E('tr', { 'class': 'tr' }, [ E('td', { 'class': 'td left', 'width': '33%' }, title), E('td', { 'class': 'td left' }, value) ]); } function section(title, children) { return E('div', { 'class': 'cbi-section' }, [ E('h3', title) ].concat(children)); } function text(value, placeholder) { return E('input', { 'type': 'text', 'class': 'cbi-input-text', 'value': value || '', 'placeholder': placeholder || '' }); } function field(title, el, desc) { return E('div', { 'class': 'cbi-value' }, [ E('label', { 'class': 'cbi-value-title' }, title), E('div', { 'class': 'cbi-value-field' }, [].concat(el, desc ? [ E('div', { 'class': 'cbi-value-description' }, desc) ] : [])) ]); } function desc(t) { return E('span', { 'class': 'cbi-value-description' }, t); } function ago(then, now) { var s = Math.max(0, (now || Date.now() / 1000) - then); if (s < 90) return 'только что'; if (s < 5400) return Math.round(s / 60) + ' мин назад'; if (s < 129600) return Math.round(s / 3600) + ' ч назад'; return Math.round(s / 86400) + ' дн назад'; } function duration(sec) { sec = +sec || 0; var d = Math.floor(sec / 86400), h = Math.floor(sec % 86400 / 3600), m = Math.floor(sec % 3600 / 60); return (d ? d + ' д ' : '') + (d || h ? h + ' ч ' : '') + m + ' мин'; } // "/dev/ttyUSB2 — USB 2-1, 05c6:90d5 Foxconn T99W175, интерфейс 02, драйвер option, 5000 Мбит/с" function portText(p) { if (!p || !p.dev) return '—'; if (!p.exists) return [ E('code', p.dev), ' — ', E('strong', { 'style': RED }, 'нет такого устройства') ]; var parts = []; if (p.usb) parts.push('USB ' + p.usb); if (p.id) parts.push(p.id + (p.product && p.product.trim() ? ' ' + p.product.trim() : '')); if (p.ifnum) parts.push('интерфейс ' + p.ifnum); if (p.driver) parts.push('драйвер ' + p.driver); if (p.speed) parts.push(p.speed + ' Мбит/с'); return [ E('code', p.dev) ].concat(parts.length ? [ ' — ', desc(parts.join(', ')) ] : []); } // AT answers -> human text var ACT = { 0: 'GSM', 2: 'UMTS', 3: 'EDGE', 4: 'HSDPA', 5: 'HSUPA', 6: 'HSPA', 7: 'LTE', 10: 'LTE (5GC)', 11: 'NR 5G', 12: 'NG-RAN', 13: 'LTE+NR (EN-DC)' }; var REG = { 0: [ 'не зарегистрирован, не ищет', RED ], 1: [ 'домашняя сеть', GREEN ], 2: [ 'поиск сети…', '' ], 3: [ 'регистрация отклонена', RED ], 4: [ 'неизвестно', '' ], 5: [ 'роуминг', GREEN ] }; function parseSlot(s) { if (/SIM2\s*ENABLE/i.test(s || '')) return 'esim'; if (/SIM1\s*ENABLE/i.test(s || '')) return 'sim'; return ''; } function parseCops(s) { var m = (s || '').match(/\+COPS:\s*\d+\s*,\s*\d+\s*,\s*"([^"]*)"\s*(?:,\s*(\d+))?/); if (!m) return 'нет сети'; return m[1] + (m[2] != null && ACT[m[2]] ? ' · ' + ACT[m[2]] : ''); } function parseReg(s) { var m = (s || '').match(/\+CEREG:\s*\d+\s*,\s*(\d+)/); if (!m) return s || '—'; var r = REG[m[1]] || [ 'состояние ' + m[1], '' ]; return E('strong', { 'style': r[1] }, r[0]); } function parseCsq(s) { var m = (s || '').match(/\+CSQ:\s*(\d+)/); if (!m || m[1] == '99') return 'нет данных'; var rssi = +m[1], dbm = -113 + 2 * rssi; var bars = rssi >= 20 ? 4 : rssi >= 15 ? 3 : rssi >= 10 ? 2 : rssi >= 5 ? 1 : 0; return [ E('span', { 'style': 'font-family:monospace;letter-spacing:1px' }, '▂▄▆█'.slice(0, bars) + '····'.slice(bars)), ' ' + dbm + ' дБм (CSQ ' + rssi + ')' ]; } function parseCpin(s) { if (/READY/.test(s || '')) return E('strong', { 'style': GREEN }, 'готова'); if (/SIM PIN/.test(s || '')) return E('strong', { 'style': RED }, 'нужен PIN'); return E('strong', { 'style': RED }, s || 'нет SIM'); } // LPA:1$smdp.example.com$MATCHING-ID[$OID$1] -> { smdp, mid, cc } function parseLpa(s) { var m = String(s || '').trim().match(/^(?:LPA:)?1\$([^$]+)\$([^$]*)(?:\$([^$]*))?(?:\$([^$]*))?$/i); return m ? { smdp: m[1], mid: m[2], ccRequired: m[4] == '1' } : null; } function readImage(input) { var f = input.files && input.files[0]; if (!f) return Promise.reject(new Error('нет файла')); return createImageBitmap(f); } return view.extend({ handleSaveApply: null, handleSave: null, handleReset: null, load: function() { return Promise.all([ callStatus(), callProfiles(), callJob() ]); }, button: function(label, style, cmd, args, confirmText) { var btn = E('button', { 'class': 'btn cbi-button cbi-button-' + style, 'click': ui.createHandlerFn(this, function() { var a = typeof args == 'function' ? args() : (args || []); if (!a) return; var c = typeof confirmText == 'function' ? confirmText() : confirmText; if (c && !window.confirm(c)) return; return this.run(cmd, a); }) }, label); btn.disabled = this.busy; this.buttons.push(btn); return btn; }, // ---- Модем: состояние по AT ---- renderModem: function() { var box = this.modemBox; dom.content(box, [ E('h3', 'Модем'), E('em', 'спрашиваю модем…') ]); return callModem().then(L.bind(function(m) { var refresh = E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': ui.createHandlerFn(this, this.renderModem) }, 'Обновить'); if (m.busy) return dom.content(box, [ E('h3', 'Модем'), E('p', [ E('em', 'занят: ' + m.cmd + ' — состояние появится после окончания'), ' ', refresh ]) ]); if (m.error) return dom.content(box, [ E('h3', 'Модем'), E('div', { 'class': 'alert-message warning' }, [ 'AT-порт не отвечает: ' + m.error + '. Проверь порт в «Подключении» ниже.' ]), refresh ]); var slot = parseSlot(m.slot); var ati = (m.ati || '').split('|').filter(function(l) { return !/^(Manufacturer|OK)/i.test(l); }); this.slotNow = slot; dom.content(box, [ E('h3', 'Модем'), E('table', { 'class': 'table' }, [ row('Модель', ati.length ? ati.join(' · ') : '—'), row('Слот SIM', [ slot == 'esim' ? E('strong', 'eSIM (SIM2)') : slot == 'sim' ? E('strong', 'физическая SIM (SIM1)') : (m.slot || '—'), ' ', slot != 'esim' ? this.button('Переключить на eSIM', 'apply', 'slot', [ 'esim' ], 'Переключить модем на eSIM? Модем перезагрузится, интернет пропадёт примерно на минуту.') : '', slot != 'sim' ? this.button('Переключить на SIM1', 'apply', 'slot', [ 'sim' ], 'Переключить модем на физическую SIM (SIM1)? Модем перезагрузится, интернет пропадёт примерно на минуту.') : '' ]), row('SIM', parseCpin(m.cpin)), row('Оператор', parseCops(m.cops)), row('Регистрация (LTE)', parseReg(m.cereg)), row('Сигнал', parseCsq(m.csq)) ]), E('div', { 'class': 'right' }, refresh) ]); }, this)).catch(function(e) { dom.content(box, [ E('h3', 'Модем'), E('p', String(e)) ]); }); }, // ---- Профили eSIM (кэш последнего ответа lpac) ---- renderProfiles: function(p) { var list = p.list && p.list.payload && p.list.payload.data; var chip = p.chip && p.chip.payload && p.chip.payload.data; var res = chip && chip.EUICCInfo2 && chip.EUICCInfo2.extCardResource || {}; var refreshBtn = this.button('Обновить с чипа', 'action', 'refresh', [], null); var rows = []; (Array.isArray(list) ? list : []).forEach(L.bind(function(pr) { var on = pr.profileState == 'enabled'; var icon = pr.icon && /^image\//.test(pr.iconType || 'image/png') ? E('img', { 'src': 'data:' + (pr.iconType || 'image/png') + ';base64,' + pr.icon, 'style': 'width:24px;height:24px;vertical-align:middle;margin-right:.4em' }) : ''; rows.push(E('tr', { 'class': 'tr' }, [ E('td', { 'class': 'td' }, on ? E('strong', { 'style': GREEN }, '● включён') : E('span', '○ выключен')), E('td', { 'class': 'td' }, [ icon, E('strong', pr.profileNickname || pr.serviceProviderName || '—'), pr.profileNickname && pr.serviceProviderName ? [ E('br'), desc(pr.serviceProviderName) ] : '', pr.profileName && pr.profileName != pr.serviceProviderName ? [ E('br'), desc(pr.profileName) ] : '' ]), E('td', { 'class': 'td' }, E('code', pr.iccid)), E('td', { 'class': 'td right', 'style': 'white-space:nowrap' }, [ on ? this.button('Выключить', 'negative', 'disable', [ pr.iccid ], 'Выключить профиль ' + pr.iccid + '? Модем останется без активного профиля, интернета через eSIM не будет.') : this.button('Включить', 'positive', 'enable', [ pr.iccid ], 'Включить профиль ' + (pr.profileNickname || pr.serviceProviderName || pr.iccid) + '? Текущий выключится, модем перезагрузится, интернет пропадёт на минуту-две.'), ' ', this.button('Имя', 'action', 'rename', function() { var n = window.prompt('Имя профиля ' + pr.iccid + ' (до 64 символов):', pr.profileNickname || ''); return n && n.trim() ? [ pr.iccid, n.trim() ] : null; }), ' ', on ? '' : this.button('Удалить', 'remove', 'delete', function() { var a = window.prompt('Профиль ' + pr.iccid + ' будет удалён с чипа НАВСЕГДА — повторно скачать по ' + 'тому же коду обычно нельзя.\n\nДля подтверждения введи последние 4 цифры ICCID:'); if (a == null) return null; if (a.trim() != pr.iccid.slice(-4)) { ui.addNotification(null, E('p', 'Цифры не совпали — удаление отменено'), 'warning'); return null; } return [ pr.iccid ]; }) ]) ])); }, this)); var body; if (!Array.isArray(list)) body = E('p', [ E('em', 'Список ещё не читался. '), 'Нажми «Обновить с чипа»: ModemManager на время остановится, интернет пропадёт примерно на полминуты.' ]); else if (!rows.length) body = E('p', E('em', 'На чипе нет профилей — добавь ниже.')); else body = E('table', { 'class': 'table' }, [ E('tr', { 'class': 'tr table-titles' }, [ E('th', { 'class': 'th' }, 'Состояние'), E('th', { 'class': 'th' }, 'Профиль'), E('th', { 'class': 'th' }, 'ICCID'), E('th', { 'class': 'th right' }, '') ]) ].concat(rows)); dom.content(this.profilesBox, [ E('h3', 'Профили eSIM'), E('table', { 'class': 'table' }, [ row('EID', chip && chip.eidValue ? E('code', chip.eidValue) : '—'), row('Память чипа', res.freeNonVolatileMemory != null ? 'свободно ' + Math.round(res.freeNonVolatileMemory / 1024) + ' КБ' + (res.installedApplication != null ? ', профилей установлено: ' + res.installedApplication : '') : '—'), row('Данные', [ p.list_time ? 'прочитаны с чипа ' + ago(p.list_time, p.now) : 'ещё не читались', ' ', refreshBtn, E('div', { 'class': 'cbi-value-description' }, 'Список хранится на роутере; любое действие с профилем обновляет его само.') ]) ]), body ]); }, // ---- Добавить профиль ---- renderAdd: function() { var lpa = text('', 'LPA:1$smdp.example.com$MATCHING-ID'); lpa.style.width = '100%'; var smdp = text('', 'smdp.example.com'), mid = text('', 'XXXX-XXXX-XXXX-XXXX'), cc = text('', 'если оператор выдал'); var enable = E('input', { 'type': 'checkbox' }); var hint = E('div', { 'class': 'cbi-value-description' }); var fill = function() { var r = parseLpa(lpa.value); if (!r) { dom.content(hint, lpa.value.trim() ? E('span', { 'style': RED }, 'не похоже на строку LPA:1$адрес$код') : ''); return; } smdp.value = r.smdp; mid.value = r.mid; dom.content(hint, r.ccRequired ? E('strong', 'Этот профиль требует код подтверждения (CC) — впиши его ниже.') : 'разобрано ↓'); }; lpa.addEventListener('input', fill); var qr = ''; if ('BarcodeDetector' in window) { var file = E('input', { 'type': 'file', 'accept': 'image/*' }); file.addEventListener('change', function() { readImage(file).then(function(img) { return new window.BarcodeDetector({ formats: [ 'qr_code' ] }).detect(img); }).then(function(codes) { var c = (codes || []).map(function(x) { return x.rawValue; }).filter(function(v) { return parseLpa(v); })[0]; if (!c) return ui.addNotification(null, E('p', 'На картинке не нашёлся QR с кодом LPA'), 'warning'); lpa.value = c; fill(); }).catch(function(e) { ui.addNotification(null, E('p', 'QR: ' + e), 'warning'); }); }); qr = field('QR-код', file, 'картинка или скриншот QR от оператора — строка LPA заполнится сама'); } var addBtn = this.button('Скачать профиль', 'save', 'add', function() { var s = smdp.value.trim(), m = mid.value.trim(), c = cc.value.trim(); var errors = []; if (!/^[A-Za-z0-9.-]+(:\d+)?$/.test(s)) errors.push('адрес SM-DP+: нужен домен вроде smdp.example.com'); if (!/^[A-Za-z0-9_.-]+$/.test(m)) errors.push('Matching ID (код активации): только буквы, цифры, - _ .'); if (c && !/^[A-Za-z0-9]+$/.test(c)) errors.push('код подтверждения: только буквы и цифры'); if (errors.length) { ui.addNotification(null, errors.map(function(e) { return E('p', e); }), 'danger'); return null; } return [ s, m, c, enable.checked ]; }, function() { return 'Скачать профиль с ' + smdp.value.trim() + '?\n\nКод активации обычно одноразовый: если скачивание ' + 'упадёт, не повторяй вслепую — сначала посмотри ошибку в выводе.' + (enable.checked ? '\n\nПосле скачивания профиль включится, модем перезагрузится.' : '') + '\n\nНа время операции интернет через модем пропадёт.'; }); dom.content(this.addBox, [ E('h3', 'Добавить профиль'), field('Строка LPA', [ lpa, hint ], 'из QR-кода оператора: LPA:1$адрес$код — вставь целиком'), qr, field('Адрес SM-DP+', smdp), field('Matching ID', mid, 'код активации'), field('Код подтверждения', cc, 'CC / Confirmation Code — только если оператор его выдал'), field('Включить сразу', enable, 'после скачивания переключиться на новый профиль'), E('div', { 'class': 'cbi-page-actions' }, addBtn) ]); }, // ---- Подключение: куда идут AT-команды, интерфейс, APN, AT-консоль ---- renderConn: function(st, editing) { var deps = st.deps || {}, missing = Object.keys(deps).filter(function(k) { return !deps[k]; }); var apn = text(st.apn, 'internet'); var children = [ E('h3', 'Подключение') ]; if (missing.length) children.push(E('div', { 'class': 'alert-message warning' }, 'Не установлено: ' + missing.join(', ') + ' — opkg install ' + missing.map(function(m) { return m == 'sms_tool' ? 'sms-tool' : m; }).join(' '))); if (editing) { var portOpt = function(cur, filter) { var sel = E('select', { 'class': 'cbi-input-select' }); var seen = {}; (st.ports || []).filter(function(p) { return filter.test(p.dev); }).concat([ { dev: cur, exists: true } ]) .forEach(function(p) { if (seen[p.dev]) return; seen[p.dev] = true; sel.appendChild(E('option', { 'value': p.dev }, p.dev + (p.ifnum ? ' — интерфейс ' + p.ifnum : '') + (p.driver ? ', ' + p.driver : '') + (p.id ? ', ' + p.id : ''))); }); sel.value = cur; return sel; }; var atSel = portOpt(st.at_port, /tty|wwan/), wdmSel = portOpt(st.wdm, /cdc-wdm|wwan/); var ifSel = E('select', { 'class': 'cbi-input-select' }, (st.ifaces || []).map(function(i) { return E('option', { 'value': i.name }, i.name + (i.proto ? ' (' + i.proto + ')' : '')); })); if (!(st.ifaces || []).some(function(i) { return i.name == st.iface; })) ifSel.appendChild(E('option', { 'value': st.iface }, st.iface)); ifSel.value = st.iface; children.push( field('AT-порт', atSel, 'куда идут AT-команды (sms_tool): слот, статус, перезагрузка модема. ' + 'У T99W175 обычно /dev/ttyUSB2 (драйвер option)'), field('MBIM-устройство', wdmSel, 'через него lpac говорит с чипом eSIM (uqmi -m), обычно /dev/cdc-wdm0'), field('Интерфейс', ifSel, 'сетевой интерфейс модема: опускается на время операций, сюда пишется APN'), E('div', { 'class': 'cbi-page-actions' }, [ E('button', { 'class': 'btn cbi-button', 'click': ui.createHandlerFn(this, function() { this.renderConn(st, false); }) }, 'Отмена'), ' ', E('button', { 'class': 'btn cbi-button cbi-button-save', 'click': ui.createHandlerFn(this, function() { return callConfigSet(atSel.value, wdmSel.value, ifSel.value).then(L.bind(function(r) { if (r.error) return ui.addNotification(null, E('p', r.error), 'danger'); return this.reload(); }, this)); }) }, 'Сохранить') ])); dom.content(this.connBox, children); return; } var ifState = !st.iface_exists ? E('strong', { 'style': RED }, 'нет такого интерфейса') : st.iface_up ? [ E('strong', { 'style': GREEN }, 'поднят'), desc(' — ' + [ st.iface_ip, st.iface_device, st.iface_uptime ? 'аптайм ' + duration(st.iface_uptime) : '' ] .filter(Boolean).join(', ')) ] : E('strong', { 'style': RED }, 'опущен'); var atCmd = text('', 'AT+CSQ'); atCmd.style.fontFamily = 'monospace'; var atOut = E('pre', { 'style': 'white-space:pre-wrap;max-height:16em;overflow:auto;margin:.5em 0 0;display:none' }); var send = function() { var c = atCmd.value.trim(); if (!c) return; atOut.style.display = ''; atOut.textContent = '> ' + c + '\n…'; return callAt(c).then(function(r) { atOut.textContent = '> ' + c + ' [' + (r.port || '') + ']\n' + (r.error ? '!! ' + r.error : (r.output || '(пусто)')); }).catch(function(e) { atOut.textContent = '> ' + c + '\n!! ' + e; }); }; atCmd.addEventListener('keydown', function(ev) { if (ev.key == 'Enter') send(); }); children.push( E('table', { 'class': 'table' }, [ row('AT-порт', portText(st.at_info)), row('MBIM (lpac)', portText(st.wdm_info)), row('Интерфейс ' + st.iface, [ ifState, st.iface_proto ? desc(' (' + st.iface_proto + ')') : '' ]), row('ModemManager', st.mm_running ? 'работает' : E('strong', { 'style': RED }, st.busy ? 'остановлен на время операции' : 'остановлен')), row('APN', [ apn, ' ', this.button('Применить', 'apply', 'apn', function() { var v = apn.value.trim(); if (!/^[A-Za-z0-9._-]+$/.test(v)) { ui.addNotification(null, E('p', 'APN: только буквы, цифры, . - _'), 'danger'); return null; } return [ v ]; }, 'Записать APN и переподключить интерфейс ' + st.iface + '?'), E('div', { 'class': 'cbi-value-description' }, 'iptype ipv4v6 и роуминг включаются вместе с APN') ]), row('AT-консоль', [ E('div', { 'style': 'display:flex;gap:.5em' }, [ atCmd, E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': ui.createHandlerFn(this, send) }, 'Отправить') ]), atOut ]) ]), E('div', { 'class': 'right' }, E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': ui.createHandlerFn(this, function() { this.renderConn(st, true); }) }, 'Изменить порты')) ); dom.content(this.connBox, children); }, // ---- Обслуживание: версия, обновления, история ---- renderMaint: function(st) { var updState = E('em', 'проверяю обновления…'); callUpdateCheck().then(function(u) { if (u.error) return dom.content(updState, '— не удалось проверить: ' + u.error); var link = function(href, t) { return E('a', { 'href': href, 'target': '_blank', 'rel': 'noreferrer' }, t); }; if (u.installed && u.installed.indexOf(u.latest) == 0) return dom.content(updState, '— актуальная'); dom.content(updState, [ '— ', E('strong', 'есть обновление: '), link(u.commit, u.latest), ' ' + (u.message || '') ] .concat(u.compare ? [ ' (', link(u.compare, 'что изменилось'), ')' ] : [])); }).catch(function(e) { dom.content(updState, '— не удалось проверить: ' + e); }); var hist = (st.history || []).map(function(h) { return E('tr', { 'class': 'tr' }, [ E('td', { 'class': 'td', 'style': 'white-space:nowrap' }, h.time), E('td', { 'class': 'td' }, E('code', h.cmd)), E('td', { 'class': 'td' }, h.rc === 0 ? E('span', { 'style': GREEN }, 'ok') : E('strong', { 'style': RED }, 'ошибка ' + h.rc)) ]); }); dom.content(this.maintBox, [ E('h3', 'Обслуживание'), E('table', { 'class': 'table' }, [ row('Версия esim-tools', [ st.version || 'неизвестна', ' ', updState ]), row(this.button('Обновить esim-tools', 'action', 'update', [], 'Скачать свежий esim-tools с git и переустановить скрипт и эту страницу?'), 'скрипт esim и страница; после обновления LuCI может попросить войти заново'), row(st.auto_update ? this.button('Выключить автообновление', 'negative', 'autoupdate-off') : this.button('Включить автообновление', 'positive', 'autoupdate-on'), [ st.auto_update ? E('strong', 'включено') : 'выключено', ': каждый день в 4:30 (время роутера), если на сервере новый коммит — обновить', st.auto_update_last ? E('div', { 'class': 'cbi-value-description' }, 'последний запуск: ' + st.auto_update_last) : '' ]) ]), E('h4', 'Последние команды'), hist.length ? E('table', { 'class': 'table' }, hist) : E('p', E('em', 'пока ничего не запускалось')) ]); }, // ---- job ---- showJob: function(j) { if (!j.cmd) { this.jobBox.style.display = 'none'; return; } this.jobBox.style.display = ''; var state = j.running ? E('em', 'выполняется…') : j.rc === 0 ? E('strong', { 'style': GREEN }, 'готово') : E('strong', { 'style': RED }, 'ошибка (код ' + j.rc + ')'); dom.content(this.jobTitle, [ 'Последняя команда: ', E('code', j.cmd), ' — ', state ]); this.jobLog.textContent = j.log || ''; this.jobLog.scrollTop = this.jobLog.scrollHeight; }, setBusy: function(busy) { this.busy = busy; this.buttons.forEach(function(b) { b.disabled = busy; }); }, run: function(cmd, a) { return callRun(cmd, a[0] || '', a[1] || '', a[2] || '', !!a[3]).then(L.bind(function(r) { if (r.error) { ui.addNotification(null, E('p', r.error), 'danger'); return; } this.jobBox.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); return this.follow(); }, this)); }, reload: function() { return Promise.all([ callStatus(), callProfiles() ]).then(L.bind(function(d) { this.buttons = []; this.renderAll(d[0], d[1]); }, this)); }, renderAll: function(st, prof) { this.renderConn(st, false); this.renderProfiles(prof); this.renderMaint(st); this.renderAdd(); this.renderModem(); this.setBusy(this.busy); }, // poll the job until it ends; rpcd may restart under us (update) follow: function() { var errors = 0; this.setBusy(true); var loop = L.bind(function() { return callJob().then(L.bind(function(j) { errors = 0; this.showJob(j); if (j.running) return wait(1500).then(loop); this.setBusy(false); if (j.rc !== 0) ui.addNotification(null, E('p', j.cmd + ': ошибка, см. вывод внизу страницы'), 'danger'); return this.reload().then(function() { return j; }); }, this)).catch(L.bind(function(e) { if (++errors > 20) { this.setBusy(false); ui.addNotification(null, E('p', 'Нет связи с роутером: ' + e), 'danger'); return; } return wait(2000).then(loop); }, this)); }, this); return loop(); }, render: function(data) { this.busy = false; this.buttons = []; var box = function() { return E('div', { 'class': 'cbi-section' }); }; this.modemBox = box(); this.profilesBox = box(); this.addBox = box(); this.connBox = box(); this.maintBox = box(); this.jobTitle = E('h3'); this.jobLog = E('pre', { 'style': 'white-space:pre-wrap;max-height:24em;overflow:auto' }); this.jobBox = E('div', { 'class': 'cbi-section' }, [ this.jobTitle, this.jobLog ]); this.renderAll(data[0], data[1]); this.showJob(data[2]); if (data[2].running) this.follow(); return E([], [ E('h2', 'esim-tools'), E('div', { 'class': 'cbi-map-descr' }, 'Профили eSIM и слот SIM модема Foxconn T99W175 (скрипт esim). ' + 'Операции с профилями останавливают ModemManager — интернет через модем на это время пропадает.'), this.modemBox, this.profilesBox, this.addBox, this.connBox, this.jobBox, this.maintBox ]); } });