diff --git a/README.md b/README.md index 19c53eb..1794d64 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,76 @@ # esim-tools +Профили eSIM и слот SIM модема Foxconn T99W175 / Thales MV31-W на OpenWrt +(проверено на Huasifei WH3000 Pro): скрипт `esim` и страница LuCI **Modem → esim-tools**. + +Модем работает в MBIM (05c6:90d5); lpac говорит с чипом через QMI поверх MBIM +(`uqmi -m`), AT-команды идут через `sms_tool` в AT-порт. На время операций с +профилями ModemManager останавливается, потом запускается и интерфейс поднимается. + +## Установка + +По ssh на роутере: + +```sh +wget -qO- https://git.sam-hub.net/sam/esim-tools/raw/branch/main/install.sh | sh +``` + +Без доступа к репозиторию с роутера — с компьютера: + +```sh +tools/push.sh root@192.168.1.1 +``` + +Установщик ставит недостающие пакеты (`lpac uqmi sms-tool jsonfilter`, через opkg или apk), +кладёт всё в `/etc/esim-tools`, делает ссылку `/usr/bin/esim` и ставит страницу LuCI. +Если пункта в меню нет — выйти из LuCI и войти снова. + +## Страница LuCI + +- **Модем** — модель, активный слот (eSIM / SIM1) с переключением, SIM, оператор и + сеть, регистрация, сигнал. +- **Профили eSIM** — EID, свободная память, список профилей: включить, выключить, + переименовать, удалить (с подтверждением последними цифрами ICCID). Список читается с + чипа кнопкой «Обновить с чипа» и после каждого действия; между этим показывается + сохранённый на роутере. +- **Добавить профиль** — строка LPA из QR (или картинка QR в Chrome/Edge), либо адрес + SM-DP+ и Matching ID отдельно, код подтверждения, «включить сразу». +- **Подключение** — куда идут AT-команды и где MBIM-устройство: путь на USB-шине, + номер интерфейса, драйвер, VID:PID, скорость; состояние интерфейса и ModemManager, APN, + AT-консоль. «Изменить порты» — выбор из найденных `/dev/ttyUSB*` и `/dev/cdc-wdm*`. +- **Вывод команды** — лог текущей операции (все долгие операции выполняются в фоне, + страницу можно перезагрузить). +- **Обслуживание** — версия и проверка обновлений, «Обновить esim-tools», + автообновление (cron, каждый день в 4:30) и последние команды. + +## Терминал + +```sh +esim status # состояние модема и сети +esim list # профили +esim add 'LPA:1$smdp.example.com$CODE' [CC] [--enable|--no-enable] +esim enable|disable ICCID +esim delete ICCID [--yes] +esim rename ICCID 'Имя' +esim slot [esim|sim] +esim apn internet +esim at 'AT+CSQ' +esim update | check-update | auto-update [on|off] +``` + +Порты и интерфейс — в `/etc/esim-tools/esim.conf` (`AT_PORT`, `WDM`, `IFACE`; страница +пишет туда же), переменные окружения с теми же именами важнее файла. +По умолчанию `/dev/ttyUSB2`, `/dev/cdc-wdm0`, `modem2`. + +## Файлы + +``` +/etc/esim-tools/router/esim.sh скрипт (/usr/bin/esim) +/etc/esim-tools/luci/ исходники страницы +/etc/esim-tools/esim.conf настройки +/etc/esim-tools/cache/ последний список профилей и данные чипа +/etc/esim-tools/history.log команды, запущенные со страницы +/etc/esim-tools/auto-update.log запуски автообновления +``` + +`/etc/esim-tools/` добавляется в `/etc/sysupgrade.conf` и переживает обновление прошивки. diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..e623342 --- /dev/null +++ b/install.sh @@ -0,0 +1,53 @@ +#!/bin/sh +# Установка esim-tools на OpenWrt, по ssh на роутере: +# wget -qO- https://git.sam-hub.net/sam/esim-tools/raw/branch/main/install.sh | sh +# или после tools/push.sh с компьютера: +# sh /etc/esim-tools/install.sh +# Ставит недостающие пакеты (lpac, uqmi, sms-tool, jsonfilter), скрипт +# /usr/bin/esim и страницу LuCI: Модем -> esim-tools. +set -eu +KIT_URL=${KIT_URL:-https://git.sam-hub.net/sam/esim-tools/archive/main.tar.gz} +KIT_DIR=/etc/esim-tools + +# пакеты: opkg (до 24.10) или apk (25.x) +missing= +for p in lpac:lpac uqmi:uqmi sms_tool:sms-tool jsonfilter:jsonfilter; do + command -v "${p%%:*}" >/dev/null 2>&1 || missing="$missing ${p#*:}" +done +if [ -n "$missing" ]; then + echo "ставлю:$missing" + if command -v apk >/dev/null 2>&1; then + apk update && apk add $missing + else + opkg update && opkg install $missing + fi +fi + +here=$(cd "$(dirname "$0")" 2>/dev/null && pwd || echo /nonexistent) +mkdir -p "$KIT_DIR" +if [ -f "$here/router/esim.sh" ]; then + [ "$here" = "$KIT_DIR" ] || cp -r "$here/router" "$here/luci" "$here/install.sh" "$KIT_DIR/" +else + tmp=/tmp/esim-tools.$$ + mkdir -p "$tmp" + echo "скачиваю $KIT_URL" + wget -qO "$tmp/kit.tgz" "$KIT_URL" + tar xzf "$tmp/kit.tgz" -C "$tmp" + src=$(find "$tmp" -path '*/router/esim.sh' | head -n 1) + [ -n "$src" ] || { echo "ошибка: в $KIT_URL нет router/esim.sh" >&2; exit 1; } + src=${src%/router/esim.sh} + for d in router luci; do + rm -rf "${KIT_DIR:?}/$d" + cp -r "$src/$d" "$KIT_DIR/" + done + cp "$src/install.sh" "$KIT_DIR/" + # id коммита из заголовка git archive (как kit_version в esim.sh) + sha=$(gunzip -c "$tmp/kit.tgz" | head -c 1536 | tr -c 'a-z0-9=\n' '\n' | + grep '^comment=[0-9a-f]\{40\}$' | head -n 1 | cut -c9-15) || true + echo "${sha:-?} $(date '+%Y-%m-%d %H:%M')" > "$KIT_DIR/VERSION" + rm -rf "$tmp" +fi +sh "$KIT_DIR/router/esim.sh" install +ip=$(uci -q get network.lan.ipaddr | cut -d/ -f1) +echo "Готово: http://${ip:-<роутер>}/cgi-bin/luci/admin/modem/esim-tools" +echo "(LuCI -> Modem -> esim-tools; если пункта нет - выйди из LuCI и войди снова)" diff --git a/luci/acl.json b/luci/acl.json new file mode 100644 index 0000000..13ed3a6 --- /dev/null +++ b/luci/acl.json @@ -0,0 +1,15 @@ +{ + "luci-app-esim-tools": { + "description": "esim-tools: eSIM profiles, SIM slot, AT port", + "read": { + "ubus": { + "esim-tools": [ "status", "modem", "profiles", "job", "update_check" ] + } + }, + "write": { + "ubus": { + "esim-tools": [ "run", "at", "config_set" ] + } + } + } +} diff --git a/luci/esim-tools.js b/luci/esim-tools.js new file mode 100644 index 0000000..329fc09 --- /dev/null +++ b/luci/esim-tools.js @@ -0,0 +1,608 @@ +'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 ]); + } +}); diff --git a/luci/menu.json b/luci/menu.json new file mode 100644 index 0000000..8d6e366 --- /dev/null +++ b/luci/menu.json @@ -0,0 +1,21 @@ +{ + "admin/modem": { + "title": "Modem", + "order": 45, + "action": { + "type": "firstchild", + "recurse": true + } + }, + "admin/modem/esim-tools": { + "title": "esim-tools", + "order": 30, + "action": { + "type": "view", + "path": "esim-tools" + }, + "depends": { + "acl": [ "luci-app-esim-tools" ] + } + } +} diff --git a/luci/rpcd.sh b/luci/rpcd.sh new file mode 100755 index 0000000..94dfc6e --- /dev/null +++ b/luci/rpcd.sh @@ -0,0 +1,318 @@ +#!/bin/sh +# rpcd plugin "esim-tools" for the LuCI page (installed as /usr/libexec/rpcd/esim-tools). +# +# status settings, where the AT/MBIM ports are (USB path, driver), interface, +# ModemManager, dependencies, kit version, auto-update, history +# modem AT state: ATI, slot, SIM, operator, registration, signal +# profiles cached lpac answers (profile list, chip info) with their age +# run start a whitelisted esim command as the background job +# job the job's command, state, exit code and output +# at one raw AT command to AT_PORT +# config_set AT_PORT / WDM / IFACE into /etc/esim-tools/esim.conf +# update_check latest commit on the git server vs the installed one +# +# rpcd kills calls after ~30 s; anything with lpac or a modem reset takes +# longer (ModemManager stop/start), hence the job. + +. /usr/share/libubox/jshn.sh +export PATH=/usr/sbin:/usr/bin:/sbin:/bin +umask 022 + +KIT_DIR=/etc/esim-tools +CONF=$KIT_DIR/esim.conf +CACHE=$KIT_DIR/cache +HISTORY=$KIT_DIR/history.log +JOB=/tmp/esim-tools-job + +b() { "$@" >/dev/null 2>&1 && echo 1 || echo 0; } + +job_running() { [ -f "$JOB/pid" ] && kill -0 "$(cat "$JOB/pid")" 2>/dev/null; } + +reply_error() { + json_init + json_add_string error "$1" + json_dump + exit 0 +} + +# AT_PORT, WDM, IFACE with the script's defaults +load_config() { + esim config > /tmp/esim-tools-cfg.$$ 2>/dev/null + while read -r k v; do + eval "cfg_$k=\$v" + done < /tmp/esim-tools-cfg.$$ + rm -f /tmp/esim-tools-cfg.$$ +} + +# port_info : fields of the current json object - which USB device and +# interface the node belongs to (the M.2 modem shows up as a USB device) +port_info() { + n=${1##*/} + case "$n" in + cdc-wdm*) s=/sys/class/usbmisc/$n/device ;; + wwan*) s=/sys/class/wwan/$n/device ;; + *) s=/sys/class/tty/$n/device ;; + esac + json_add_string dev "$1" + json_add_boolean exists "$(b test -e "$1")" + i=$(readlink -f "$s" 2>/dev/null) + while [ -n "$i" ] && [ ! -f "$i/bInterfaceNumber" ]; do + i=${i%/*} + done + [ -n "$i" ] || return 0 + u=${i%/*} + json_add_string ifnum "$(cat "$i/bInterfaceNumber")" + json_add_string driver "$(basename "$(readlink "$i/driver")" 2>/dev/null)" + json_add_string usb "${u##*/}" + json_add_string id "$(cat "$u/idVendor"):$(cat "$u/idProduct")" + json_add_string product "$(cat "$u/manufacturer" 2>/dev/null) $(cat "$u/product" 2>/dev/null)" + json_add_string speed "$(cat "$u/speed" 2>/dev/null)" +} + +m_status() { + load_config + json_init + json_add_string at_port "$cfg_at_port" + json_add_string wdm "$cfg_wdm" + json_add_string iface "$cfg_iface" + json_add_object at_info + port_info "$cfg_at_port" + json_close_object + json_add_object wdm_info + port_info "$cfg_wdm" + json_close_object + + # every modem node, for the port selects + json_add_array ports + for d in /dev/ttyUSB* /dev/ttyACM* /dev/cdc-wdm* /dev/wwan*; do + [ -e "$d" ] || continue + json_add_object "" + port_info "$d" + json_close_object + done + json_close_array + json_add_array ifaces + for n in $(uci -q show network | sed -n 's/^network\.\([^.=]*\)=interface$/\1/p'); do + json_add_object "" + json_add_string name "$n" + json_add_string proto "$(uci -q get "network.$n.proto")" + json_close_object + done + json_close_array + + st=$(ifstatus "$cfg_iface" 2>/dev/null) + json_add_boolean iface_exists "$(b test -n "$st")" + json_add_boolean iface_up "$(b test "$(jsonfilter -s "$st" -e '@.up' 2>/dev/null)" = true)" + json_add_string iface_proto "$(uci -q get "network.$cfg_iface.proto")" + json_add_string iface_ip "$(jsonfilter -s "$st" -e '@["ipv4-address"][0].address' 2>/dev/null)" + json_add_string iface_uptime "$(jsonfilter -s "$st" -e '@.uptime' 2>/dev/null)" + json_add_string iface_device "$(jsonfilter -s "$st" -e '@.l3_device' 2>/dev/null)" + json_add_string apn "$(uci -q get "network.$cfg_iface.apn")" + json_add_boolean mm_running "$(b pidof ModemManager)" + + json_add_object deps + for c in lpac uqmi sms_tool jsonfilter; do + json_add_boolean "$c" "$(b command -v "$c")" + done + json_close_object + + json_add_string version "$(cat "$KIT_DIR/VERSION" 2>/dev/null)" + json_add_boolean auto_update "$(b grep -q 'esim auto-update' /etc/crontabs/root)" + json_add_string auto_update_last "$(tail -n 1 "$KIT_DIR/auto-update.log" 2>/dev/null)" + json_add_boolean busy "$(b job_running)" + + # "\t\t", newest first + json_add_array history + tail -n 15 "$HISTORY" 2>/dev/null | sed -n '1!G;h;$p' > /tmp/esim-tools-hist.$$ + while IFS="$(printf '\t')" read -r t rc c; do + json_add_object "" + json_add_string time "$t" + json_add_int rc "$rc" + json_add_string cmd "$c" + json_close_object + done < /tmp/esim-tools-hist.$$ + rm -f /tmp/esim-tools-hist.$$ + json_close_array + json_dump +} + +m_modem() { + json_init + # the job owns the modem (resets it, lpac talks to it) + if job_running; then + json_add_boolean busy 1 + json_add_string cmd "$(cat "$JOB/cmd")" + json_dump + return + fi + out=$(esim state 2>&1) || reply_error "$(echo "$out" | tail -n 1 | sed 's/^!! //')" + echo "$out" > /tmp/esim-tools-state.$$ + while read -r k v; do + json_add_string "$k" "$v" + done < /tmp/esim-tools-state.$$ + rm -f /tmp/esim-tools-state.$$ + json_dump +} + +# lpac's last lines are JSON already: glued as is +m_profiles() { + l=$(cat "$CACHE/profiles.json" 2>/dev/null) + c=$(cat "$CACHE/chip.json" 2>/dev/null) + lt=$(date -r "$CACHE/profiles.json" +%s 2>/dev/null) + ct=$(date -r "$CACHE/chip.json" +%s 2>/dev/null) + printf '{"list":%s,"list_time":%s,"chip":%s,"chip_time":%s,"now":%s}\n' \ + "${l:-null}" "${lt:-0}" "${c:-null}" "${ct:-0}" "$(date +%s)" +} + +iccid_ok() { + case "$1" in '' | *[!0-9A-Fa-f]*) return 1 ;; esac + [ ${#1} -ge 18 ] && [ ${#1} -le 22 ] +} + +m_run() { + input=$(cat) + cmd=$(jsonfilter -s "$input" -e '@.cmd' 2>/dev/null) + a1=$(jsonfilter -s "$input" -e '@.a' 2>/dev/null) + a2=$(jsonfilter -s "$input" -e '@.b' 2>/dev/null) + a3=$(jsonfilter -s "$input" -e '@.c' 2>/dev/null) + flag=$(jsonfilter -s "$input" -e '@.flag' 2>/dev/null) + label= + case "$cmd" in + refresh) set -- esim refresh ;; + enable | disable) + iccid_ok "$a1" || reply_error "bad ICCID" + set -- esim "$cmd" "$a1" + ;; + delete) + iccid_ok "$a1" || reply_error "bad ICCID" + set -- esim delete "$a1" --yes + ;; + rename) + iccid_ok "$a1" || reply_error "bad ICCID" + a2=$(printf '%s' "$a2" | tr -d '\r\n\t') + [ -n "$a2" ] || reply_error "пустое имя" + [ ${#a2} -le 64 ] || reply_error "имя длиннее 64 символов" + set -- esim rename "$a1" "$a2" + ;; + add) + # a = SM-DP+ address, b = matching id, c = confirmation code + case "$a1" in '' | *[!A-Za-z0-9.:-]*) reply_error "bad SM-DP+ address" ;; esac + case "$a2" in '' | *[!A-Za-z0-9_.-]*) reply_error "bad matching id" ;; esac + case "$a3" in *[!A-Za-z0-9]*) reply_error "bad confirmation code" ;; esac + en=--no-enable + [ "$flag" = true ] || [ "$flag" = 1 ] && en=--enable + set -- esim add "$a1" "$a2" + [ -n "$a3" ] && set -- "$@" "$a3" + set -- "$@" "$en" + # the activation code stays out of the page and the history + label="esim add $a1 ***${a3:+ ***} $en" + ;; + slot) + case "$a1" in esim | sim) ;; *) reply_error "bad slot" ;; esac + set -- esim slot "$a1" + ;; + apn) + case "$a1" in '' | *[!A-Za-z0-9._-]*) reply_error "bad APN" ;; esac + set -- esim apn "$a1" + ;; + update) set -- esim update ;; + autoupdate-on) set -- esim auto-update on ;; + autoupdate-off) set -- esim auto-update off ;; + *) reply_error "unknown command: $cmd" ;; + esac + start_job "${label:-$*}" "$@" +} + +# start_job