This commit is contained in:
Sam Latsin 2026-10-13 11:24:56 +03:00
parent 69252b63e0
commit ca0119ddb3
8 changed files with 1663 additions and 0 deletions

View File

@ -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` и переживает обновление прошивки.

53
install.sh Executable file
View File

@ -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 и войди снова)"

15
luci/acl.json Normal file
View File

@ -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" ]
}
}
}
}

608
luci/esim-tools.js Normal file
View File

@ -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 <command>); 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 ]);
}
});

21
luci/menu.json Normal file
View File

@ -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" ]
}
}
}

318
luci/rpcd.sh Executable file
View File

@ -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 <dev>: 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)"
# "<date>\t<rc>\t<command>", 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 <label> cmd args...: run it in the background, reply at once
start_job() {
job_running && reply_error "занято: $(cat "$JOB/cmd")"
label=$1
shift
rm -rf "$JOB"
mkdir -p "$JOB"
echo "$label" > "$JOB/cmd"
# detached from rpcd: all fds redirected, so the call returns at once
(
"$@"
rc=$?
echo $rc > "$JOB/rc"
printf '%s\t%s\t%s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$rc" "$label" >> "$HISTORY"
tail -n 50 "$HISTORY" > "$HISTORY.tmp" && mv "$HISTORY.tmp" "$HISTORY"
) < /dev/null > "$JOB/log" 2>&1 &
echo $! > "$JOB/pid"
json_init
json_add_string started "$label"
json_dump
}
m_job() {
json_init
json_add_string cmd "$(cat "$JOB/cmd" 2>/dev/null)"
json_add_boolean running "$(b job_running)"
[ -f "$JOB/rc" ] && json_add_int rc "$(cat "$JOB/rc")"
json_add_string log "$(tail -c 20000 "$JOB/log" 2>/dev/null)"
json_dump
}
m_at() {
input=$(cat)
cmd=$(jsonfilter -s "$input" -e '@.cmd' 2>/dev/null | tr -d '\r\n')
case "$cmd" in [Aa][Tt]*) ;; *) reply_error "команда должна начинаться с AT" ;; esac
job_running && reply_error "занято: $(cat "$JOB/cmd")"
load_config
json_init
json_add_string port "$cfg_at_port"
json_add_string output "$(esim at "$cmd" 2>&1)"
json_dump
}
m_config_set() {
input=$(cat)
at_port=$(jsonfilter -s "$input" -e '@.at_port' 2>/dev/null)
wdm=$(jsonfilter -s "$input" -e '@.wdm' 2>/dev/null)
iface=$(jsonfilter -s "$input" -e '@.iface' 2>/dev/null)
for d in "$at_port" "$wdm"; do
case "$d" in /dev/[A-Za-z0-9]*) ;; *) reply_error "bad device: $d" ;; esac
case "${d#/dev/}" in *[!A-Za-z0-9_-]*) reply_error "bad device: $d" ;; esac
done
case "$iface" in '' | *[!A-Za-z0-9_]*) reply_error "bad interface: $iface" ;; esac
job_running && reply_error "занято: $(cat "$JOB/cmd")"
mkdir -p "$KIT_DIR"
{
[ -f "$CONF" ] && grep -vE '^(AT_PORT|WDM|IFACE)=' "$CONF"
printf 'AT_PORT=%s\nWDM=%s\nIFACE=%s\n' "$at_port" "$wdm" "$iface"
} > "$CONF.tmp" && mv "$CONF.tmp" "$CONF"
json_init
json_add_boolean saved 1
json_dump
}
m_update_check() {
out=$(esim check-update 2>&1) || reply_error "$(echo "$out" | tail -n 1 | sed 's/^!! //')"
json_init
echo "$out" > /tmp/esim-tools-upd.$$
while read -r k v; do
json_add_string "$k" "$v"
done < /tmp/esim-tools-upd.$$
rm -f /tmp/esim-tools-upd.$$
json_dump
}
case "$1" in
list)
echo '{"status":{},"modem":{},"profiles":{},"job":{},"run":{"cmd":"str","a":"str","b":"str","c":"str","flag":true},"at":{"cmd":"str"},"config_set":{"at_port":"str","wdm":"str","iface":"str"},"update_check":{}}'
;;
call)
case "$2" in
status) m_status ;;
modem) m_modem ;;
profiles) m_profiles ;;
job) m_job ;;
run) m_run ;;
at) m_at ;;
config_set) m_config_set ;;
update_check) m_update_check ;;
*) reply_error "unknown method" ;;
esac
;;
esac

563
router/esim.sh Executable file
View File

@ -0,0 +1,563 @@
#!/bin/sh
# esim - управление профилями eSIM на Foxconn T99W175 / Thales MV31-W в OpenWrt
#
# Модем работает в режиме MBIM (05c6:90d5), lpac обращается к чипу через
# QMI поверх MBIM (uqmi -m). На время операций с профилями ModemManager
# останавливается, после - запускается обратно и поднимается интерфейс.
#
# Зависимости: lpac, uqmi, sms-tool, jsonfilter, curl/libcurl (одной версии)
#
# Файлы (install.sh / esim update / tools/push.sh):
# /etc/esim-tools/router/esim.sh этот скрипт (/usr/bin/esim - ссылка на него)
# /etc/esim-tools/luci/ страница LuCI: Модем -> esim-tools
# /etc/esim-tools/esim.conf AT_PORT, WDM, IFACE (страница пишет сюда)
# /etc/esim-tools/cache/ последний список профилей и данные чипа
KIT_DIR=/etc/esim-tools
CONF=$KIT_DIR/esim.conf
CACHE=$KIT_DIR/cache
KIT_URL="${KIT_URL:-https://git.sam-hub.net/sam/esim-tools/archive/main.tar.gz}"
# conf KEY -> значение из esim.conf (переменная окружения важнее)
conf() { sed -n "s/^$1=//p" "$CONF" 2>/dev/null | tail -n 1 | tr -d "'\""; }
AT_PORT="${AT_PORT:-$(conf AT_PORT)}"
AT_PORT="${AT_PORT:-/dev/ttyUSB2}"
WDM="${WDM:-$(conf WDM)}"
WDM="${WDM:-/dev/cdc-wdm0}"
IFACE="${IFACE:-$(conf IFACE)}"
IFACE="${IFACE:-modem2}"
WRAP_DIR=/tmp/esim-uqmi
LOG=/tmp/esim-last.log
# настоящий uqmi ищем до того, как подменим PATH оберткой
UQMI_BIN="$(PATH=/usr/sbin:/usr/bin:/sbin:/bin command -v uqmi)"
PREPARED=0
# зависший порт не должен вешать скрипт (и страницу LuCI)
TO=
command -v timeout >/dev/null 2>&1 && TO="timeout 5"
usage() {
cat <<'EOF'
Использование: esim <команда> [аргументы]
status состояние модема и сети
info EID и свободная память чипа
list список профилей
refresh info + list (обновляет кэш для LuCI)
add 'LPA:1$SMDP$CODE' [CC] скачать профиль (строку - в одинарных кавычках!)
add SMDP CODE [CC] то же, адрес и код отдельно
--enable / --no-enable включить сразу / не включать (без вопроса)
enable ICCID включить профиль
disable ICCID выключить профиль
delete ICCID [--yes] удалить профиль (навсегда)
rename ICCID NAME задать имя профилю
slot [esim|sim] показать или переключить слот
apn APN задать APN для интерфейса и переподключиться
at 'AT...' отправить AT-команду в AT_PORT
update скачать свежий esim-tools с git и поставить
check-update последний коммит на сервере против установленного
auto-update [on|off] ежедневное обновление через cron; без аргумента - сейчас
install (пере)установить ссылку /usr/bin/esim и страницу LuCI
CC - код подтверждения, если оператор его выдал.
Настройки: /etc/esim-tools/esim.conf или переменные окружения
AT_PORT (по умолчанию /dev/ttyUSB2), WDM (/dev/cdc-wdm0), IFACE (modem2).
EOF
exit 1
}
msg() { echo ">> $*"; }
die() { echo "!! $*" >&2; exit 1; }
need() { command -v "$1" >/dev/null 2>&1 || die "не найдено: $1 (opkg install $2)"; }
# AT-команда, на выходе только ответ без эха и пустых строк
at() {
$TO sms_tool -d "$AT_PORT" at "$1" 2>/dev/null | tr -d '\r' | grep -vxF -- "$1" | grep -v '^$'
}
wait_modem() {
i=0
while [ $i -lt 30 ]; do
at "ATI" | grep -q "Model" && return 0
sleep 3
i=$((i + 1))
done
die "модем не отвечает на $AT_PORT"
}
reset_modem() {
msg "перезагрузка модема"
at "AT+CFUN=1,1" >/dev/null
sleep 10
wait_modem
sleep 5
}
ensure_esim_slot() {
if ! at "AT^SWITCH_SLOT?" | grep -q "SIM2 ENABLE"; then
msg "переключаю модем на eSIM (SIM2)"
at "AT^SWITCH_SLOT=1" >/dev/null
reset_modem
fi
}
restore() {
[ "$PREPARED" = 1 ] || return 0
PREPARED=0
msg "запускаю ModemManager"
/etc/init.d/modemmanager start
sleep 10
ifup "$IFACE"
}
prepare() {
need sms_tool sms-tool
need lpac lpac
need jsonfilter jsonfilter
[ -n "$UQMI_BIN" ] || die "не найдено: uqmi (opkg install uqmi)"
wait_modem
ensure_esim_slot
msg "останавливаю ModemManager"
PREPARED=1
trap restore EXIT
trap 'exit 1' INT TERM
ifdown "$IFACE" 2>/dev/null
/etc/init.d/modemmanager stop 2>/dev/null
killall mbim-proxy uqmi 2>/dev/null
sleep 2
mkdir -p "$WRAP_DIR"
printf '#!/bin/sh\nexec %s -m "$@"\n' "$UQMI_BIN" > "$WRAP_DIR/uqmi"
chmod +x "$WRAP_DIR/uqmi"
export PATH="$WRAP_DIR:$PATH"
uci -q set lpac.global.apdu_backend='uqmi'
uci -q set lpac.global.apdu_debug='0'
uci -q set lpac.uqmi.device="$WDM"
uci -q commit lpac
}
run_lpac() {
lpac "$@" > "$LOG" 2>&1
tail -n1 "$LOG" | grep -q '"message":"success"'
}
lpac_err() { tail -n1 "$LOG"; }
# save_cache profiles|chip: последний успешный ответ lpac - для страницы LuCI
save_cache() {
mkdir -p "$CACHE"
tail -n1 "$LOG" > "$CACHE/$1.tmp"
if grep -q '"message":"success"' "$CACHE/$1.tmp"; then
mv "$CACHE/$1.tmp" "$CACHE/$1.json"
else
rm -f "$CACHE/$1.tmp"
fi
}
# список после смены состояния, пока модем еще не перезагружен
cache_list() {
run_lpac profile list && save_cache profiles
}
notifications() {
lpac notification process -a -r >/dev/null 2>&1
}
profile_state() {
run_lpac profile list || die "не удалось получить список: $(lpac_err)"
tail -n1 "$LOG" | jsonfilter -e "@.payload.data[@.iccid='$1'].profileState" 2>/dev/null
}
cmd_status() {
need sms_tool sms-tool
echo "слот: $(at 'AT^SWITCH_SLOT?')"
echo "SIM: $(at 'AT+CPIN?')"
echo "оператор: $(at 'AT+COPS?')"
echo "регистрация: $(at 'AT+CEREG?') (x,1 дом / x,5 роуминг / x,2 поиск / x,3 отказ / x,0 не ищет)"
echo "сигнал: $(at 'AT+CSQ')"
if command -v mmcli >/dev/null 2>&1; then
mmcli -m any 2>/dev/null | grep -E ' state:|operator name|signal quality'
fi
up="$(ifstatus "$IFACE" 2>/dev/null | jsonfilter -e '@.up' 2>/dev/null)"
echo "интерфейс $IFACE: ${up:-нет данных}"
}
# для LuCI: "ключ ответ" построчно, многострочный ответ через |
cmd_state() {
need sms_tool sms-tool
[ -e "$AT_PORT" ] || die "нет порта $AT_PORT"
ati="$(at ATI | grep -vx OK | tr '\n' '|' | sed 's/|$//')"
[ -n "$ati" ] || die "модем не отвечает на $AT_PORT"
echo "ati $ati"
for k in slot:'AT^SWITCH_SLOT?' cpin:'AT+CPIN?' cops:'AT+COPS?' cereg:'AT+CEREG?' csq:'AT+CSQ'; do
echo "${k%%:*} $(at "${k#*:}" | grep -vx OK | tr '\n' '|' | sed 's/|$//')"
done
}
cmd_at() {
[ -n "$1" ] || usage
need sms_tool sms-tool
$TO sms_tool -d "$AT_PORT" at "$1" 2>&1 | tr -d '\r' | grep -v '^$'
}
cmd_info() {
run_lpac chip info || die "чип не отвечает: $(lpac_err)"
save_cache chip
d="$(tail -n1 "$LOG")"
echo "EID: $(echo "$d" | jsonfilter -e '@.payload.data.eidValue')"
echo "свободно: $(echo "$d" | jsonfilter -e '@.payload.data.EUICCInfo2.extCardResource.freeNonVolatileMemory') байт"
echo "профилей: $(echo "$d" | jsonfilter -e '@.payload.data.EUICCInfo2.extCardResource.installedApplication')"
}
cmd_list() {
run_lpac profile list || die "не удалось получить список: $(lpac_err)"
save_cache profiles
data="$(tail -n1 "$LOG")"
n="$(echo "$data" | jsonfilter -e '@.payload.data[*].iccid' 2>/dev/null | wc -l)"
if [ "$n" -eq 0 ]; then
echo "профилей нет"
return
fi
printf '%-22s %-9s %-16s %s\n' ICCID STATE PROVIDER NAME
i=0
while [ $i -lt "$n" ]; do
printf '%-22s %-9s %-16s %s\n' \
"$(echo "$data" | jsonfilter -e "@.payload.data[$i].iccid")" \
"$(echo "$data" | jsonfilter -e "@.payload.data[$i].profileState")" \
"$(echo "$data" | jsonfilter -e "@.payload.data[$i].serviceProviderName" 2>/dev/null)" \
"$(echo "$data" | jsonfilter -e "@.payload.data[$i].profileNickname" 2>/dev/null)"
i=$((i + 1))
done
}
do_enable() {
msg "включаю профиль $1"
run_lpac profile enable "$1" || die "не удалось включить: $(lpac_err)"
notifications
cache_list
reset_modem
echo "SIM: $(at 'AT+CPIN?')"
}
cmd_add() {
# --enable / --no-enable из любого места, остальные аргументы - как раньше
auto=
for a; do
shift
case "$a" in
--enable) auto=y ;;
--no-enable) auto=n ;;
*) set -- "$@" "$a" ;;
esac
done
case "$1" in
LPA:1\$*)
code="${1#LPA:1\$}"
smdp="${code%%\$*}"
rest="${code#*\$}"
mid="${rest%%\$*}"
cc="$2"
[ "$rest" != "$code" ] || die "строку LPA нужно брать в одинарные кавычки: esim add 'LPA:1\$...\$...'"
;;
LPA:*)
die "строку LPA нужно брать в одинарные кавычки: esim add 'LPA:1\$...\$...'"
;;
*)
smdp="$1"
mid="$2"
cc="$3"
;;
esac
[ -n "$smdp" ] && [ -n "$mid" ] || usage
prepare
msg "сервер: $smdp"
set -- profile download -s "$smdp" -m "$mid"
[ -n "$cc" ] && set -- "$@" -c "$cc"
msg "скачиваю профиль, это может занять до минуты"
lpac "$@" 2>&1 | tee "$LOG" | while read -r line; do
step="$(echo "$line" | jsonfilter -e '@.payload.message' 2>/dev/null)"
[ -n "$step" ] && echo " $step"
done
tail -n1 "$LOG" | grep -q '"message":"success"' || \
die "скачивание не удалось: $(lpac_err)
Не повторяй с тем же кодом вслепую - сначала разберись с ошибкой."
new_iccid="$(grep 'adata_parse' "$LOG" | jsonfilter -e '@.payload.data.iccid' 2>/dev/null)"
notifications
msg "профиль скачан${new_iccid:+: $new_iccid}"
cmd_list
if [ -n "$new_iccid" ]; then
ans=$auto
if [ -z "$ans" ]; then
printf 'Включить этот профиль сейчас? [y/N] '
read -r ans
fi
case "$ans" in
y|Y|yes|д|да) do_enable "$new_iccid" ;;
*) echo "включить позже: esim enable $new_iccid" ;;
esac
fi
}
cmd_enable() {
[ -n "$1" ] || usage
prepare
do_enable "$1"
}
cmd_disable() {
[ -n "$1" ] || usage
prepare
msg "выключаю профиль $1"
run_lpac profile disable "$1" || die "не удалось выключить: $(lpac_err)"
notifications
cache_list
reset_modem
}
cmd_delete() {
[ -n "$1" ] || usage
prepare
state="$(profile_state "$1")"
[ -n "$state" ] || die "профиль $1 не найден"
[ "$state" != "enabled" ] || die "профиль включен - сначала: esim disable $1 (или включи другой)"
if [ "$2" = --yes ]; then
msg "удаляю профиль $1"
else
echo "Профиль $1 будет удален навсегда, повторно скачать его по тому же коду обычно нельзя."
printf 'Напиши yes для подтверждения: '
read -r ans
[ "$ans" = "yes" ] || die "отменено"
fi
run_lpac profile delete "$1" || die "не удалось удалить: $(lpac_err)"
notifications
msg "удален"
cmd_list
}
cmd_rename() {
[ -n "$1" ] && [ -n "$2" ] || usage
prepare
run_lpac profile nickname "$1" "$2" || die "не удалось переименовать: $(lpac_err)"
cmd_list
}
cmd_refresh() {
prepare
cmd_info
cmd_list
}
# после перезагрузки модема ModemManager находит его заново, интерфейс поднимаем сами
slot_switch() {
at "AT^SWITCH_SLOT=$1" >/dev/null
reset_modem
at "AT^SWITCH_SLOT?"
sleep 10
msg "поднимаю $IFACE"
ifup "$IFACE"
}
cmd_slot() {
need sms_tool sms-tool
case "$1" in
"") at "AT^SWITCH_SLOT?" ;;
esim) slot_switch 1 ;;
sim) slot_switch 0 ;;
*) usage ;;
esac
}
cmd_apn() {
[ -n "$1" ] || usage
uci set network."$IFACE".apn="$1"
uci set network."$IFACE".iptype='ipv4v6'
uci set network."$IFACE".allow_roaming='1'
uci commit network
msg "APN $1 сохранен, переподключаю $IFACE"
ifdown "$IFACE"
sleep 2
ifup "$IFACE"
}
# ---- esim-tools: установка и обновление ----
AUTO_CRON='30 4 * * * /usr/bin/esim auto-update'
AUTO_LOG=$KIT_DIR/auto-update.log
# kit_version <kit.tgz>: "<commit> <date>" в VERSION. git archive кладет id
# коммита в первый заголовок tar.
kit_version() {
sha=$(gunzip -c "$1" 2>/dev/null | head -c 1536 | tr -c 'a-z0-9=\n' '\n' |
grep '^comment=[0-9a-f]\{40\}$' | head -n 1 | cut -c9-15)
echo "${sha:-?} $(date '+%Y-%m-%d %H:%M')" > "$KIT_DIR/VERSION"
}
# Последний коммит ветки KIT_URL (Gitea/Forgejo API), строки:
# installed <sha>, latest <sha>, message <первая строка>, commit <url>, compare <url>
cmd_check_update() {
repo=${KIT_URL%/archive/*}
branch=${KIT_URL##*/archive/}
branch=${branch%.tar.gz}
host=${repo%/*/*}
json=$(wget -q -T 10 -O - "$host/api/v1/repos/${repo#"$host"/}/branches/$branch") ||
die "нет ответа от $host"
id=$(jsonfilter -s "$json" -e '@.commit.id') || die "непонятный ответ от $host"
cur=$(cut -d' ' -f1 "$KIT_DIR/VERSION" 2>/dev/null)
cur=${cur%-dirty}
echo "installed ${cur:-?}"
echo "latest $(echo "$id" | cut -c1-7)"
echo "message $(jsonfilter -s "$json" -e '@.commit.message' | head -n 1)"
echo "commit $repo/commit/$id"
case "$cur" in
'' | '?') ;;
*) echo "compare $repo/compare/$cur...$id" ;;
esac
}
cmd_update() {
tmp=$(mktemp -d)
msg "скачиваю $KIT_URL"
wget -qO "$tmp/kit.tgz" "$KIT_URL" || die "не скачалось"
tar xzf "$tmp/kit.tgz" -C "$tmp" || die "битый архив"
src=$(find "$tmp" -path '*/router/esim.sh' | head -n 1)
[ -n "$src" ] || die "в архиве нет router/esim.sh"
src=${src%/router/esim.sh}
# rm + cp: новый файл, а не перезапись того, что сейчас выполняется
for d in router luci; do
rm -rf "${KIT_DIR:?}/$d"
cp -r "$src/$d" "$KIT_DIR/$d"
done
cp "$src/install.sh" "$KIT_DIR/install.sh" 2>/dev/null
kit_version "$tmp/kit.tgz"
rm -rf "$tmp"
msg "версия $(cat "$KIT_DIR/VERSION")"
# дальше - уже новым скриптом
exec sh "$KIT_DIR/router/esim.sh" install
}
# auto_log <текст>: последние запуски для страницы LuCI (и syslog)
auto_log() {
logger -t esim-tools "auto-update: $*" 2>/dev/null
echo "$(date '+%Y-%m-%d %H:%M') $*" >> "$AUTO_LOG"
tail -n 20 "$AUTO_LOG" > "$AUTO_LOG.tmp" && mv "$AUTO_LOG.tmp" "$AUTO_LOG"
}
cmd_auto_update() {
case "$1" in
on | off)
sed -i '/esim auto-update/d' /etc/crontabs/root 2>/dev/null
[ "$1" = on ] && echo "$AUTO_CRON" >> /etc/crontabs/root
/etc/init.d/cron restart
msg "автообновление: $1"
return 0
;;
esac
export PATH=/usr/sbin:/usr/bin:/sbin:/bin:$PATH
if ! out=$(cmd_check_update 2>&1); then
auto_log "проверка не удалась: $(echo "$out" | tail -n 1)"
return 1
fi
cur=$(echo "$out" | sed -n 's/^installed //p')
new=$(echo "$out" | sed -n 's/^latest //p')
case "$cur" in
"$new"*)
auto_log "актуальная ($new)"
return 0
;;
esac
auto_log "обновляю $cur -> $new"
cmd_update
}
# Страница LuCI "Модем -> esim-tools": rpcd-плагин, ACL, меню, view.
# View кладется как view/esim-tools/v<hash>.js и меню указывает туда: LuCI
# грузит view с ?v= своей версии, и файл с постоянным именем остается в кэше браузера.
install_luci() {
src=$KIT_DIR/luci
[ -d "$src" ] && [ -d /www/luci-static/resources ] || return 0
changed=0
put() {
if ! cmp -s "$1" "$2"; then
mkdir -p "$(dirname "$2")"
cp "$1" "$2"
changed=1
fi
chmod "$3" "$2"
}
put "$src/rpcd.sh" /usr/libexec/rpcd/esim-tools 755
put "$src/acl.json" /usr/share/rpcd/acl.d/luci-app-esim-tools.json 644
# rpcd перезапускаем только ради плагина и ACL (он сбрасывает сессии LuCI)
rpcd=$changed
views=/www/luci-static/resources/view
v=v$(md5sum < "$src/esim-tools.js" | cut -c1-8)
put "$src/esim-tools.js" "$views/esim-tools/$v.js" 644
for f in "$views"/esim-tools/*.js; do
[ -f "$f" ] && [ "$f" != "$views/esim-tools/$v.js" ] && rm -f "$f" && changed=1
done
sed "s|\"path\": \"esim-tools\"|\"path\": \"esim-tools/$v\"|" "$src/menu.json" > /tmp/esim-tools-menu.json
put /tmp/esim-tools-menu.json /usr/share/luci/menu.d/luci-app-esim-tools.json 644
rm -f /tmp/esim-tools-menu.json
[ "$changed" = 1 ] || return 0
rm -rf /tmp/luci-indexcache* /tmp/luci-modulecache
msg "страница LuCI установлена: Модем -> esim-tools"
[ "$rpcd" = 1 ] || return 0
# с задержкой, чтобы job из LuCI (обновление) успел завершиться
(sleep 5; /etc/init.d/rpcd restart) < /dev/null > /dev/null 2>&1 &
}
cmd_install() {
chmod 755 "$KIT_DIR/router/esim.sh"
ln -sf "$KIT_DIR/router/esim.sh" /usr/bin/esim
if [ ! -f "$CONF" ]; then
printf 'AT_PORT=%s\nWDM=%s\nIFACE=%s\n' "$AT_PORT" "$WDM" "$IFACE" > "$CONF"
msg "настройки по умолчанию: $CONF"
fi
# настройки и кэш переживают sysupgrade
grep -qxF "$KIT_DIR/" /etc/sysupgrade.conf 2>/dev/null || echo "$KIT_DIR/" >> /etc/sysupgrade.conf
install_luci
msg "esim-tools $(cut -d' ' -f1 "$KIT_DIR/VERSION" 2>/dev/null) установлен, команда: esim"
}
# для LuCI: текущие настройки с умолчаниями
cmd_config() {
echo "at_port $AT_PORT"
echo "wdm $WDM"
echo "iface $IFACE"
}
cmd="$1"
[ $# -gt 0 ] && shift
case "$cmd" in
status) cmd_status ;;
state) cmd_state ;;
info) prepare; cmd_info ;;
list) prepare; cmd_list ;;
refresh) cmd_refresh ;;
add) cmd_add "$@" ;;
enable) cmd_enable "$@" ;;
disable) cmd_disable "$@" ;;
delete) cmd_delete "$@" ;;
rename) cmd_rename "$@" ;;
slot) cmd_slot "$@" ;;
apn) cmd_apn "$@" ;;
at) cmd_at "$@" ;;
config) cmd_config ;;
update) cmd_update ;;
check-update) cmd_check_update ;;
auto-update) cmd_auto_update "$@" ;;
install) cmd_install ;;
*) usage ;;
esac

11
tools/push.sh Executable file
View File

@ -0,0 +1,11 @@
#!/bin/sh
# Залить esim-tools на роутер без доступа к git с роутера и установить:
# tools/push.sh root@192.168.1.1
set -eu
host=${1:?usage: tools/push.sh root@<router>}
cd "$(dirname "$0")/.."
# ustar без метаданных macOS: busybox tar на OpenWrt не понимает pax/xattr
COPYFILE_DISABLE=1 tar --no-xattrs --format ustar -czf - install.sh router luci |
ssh "$host" 'mkdir -p /etc/esim-tools && rm -rf /etc/esim-tools/router /etc/esim-tools/luci && tar xzf - -C /etc/esim-tools'
ver="$(git describe --always --dirty 2>/dev/null || echo '?') push $(date '+%Y-%m-%d %H:%M')"
ssh "$host" "echo '$ver' > /etc/esim-tools/VERSION && sh /etc/esim-tools/install.sh"