diff --git a/README.md b/README.md index 1794d64..74a4f2b 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,8 @@ tools/push.sh root@192.168.1.1 - **Модем** — модель, активный слот (eSIM / SIM1) с переключением, SIM, оператор и сеть, регистрация, сигнал. - **Профили eSIM** — EID, свободная память, список профилей: включить, выключить, - переименовать, удалить (с подтверждением последними цифрами ICCID). Список читается с + переименовать, свои настройки подключения (APN, логин/пароль, + PAP/CHAP, тип IP — обязателен только APN), удалить (с подтверждением последними цифрами ICCID). Список читается с чипа кнопкой «Обновить с чипа» и после каждого действия; между этим показывается сохранённый на роутере. - **Добавить профиль** — строка LPA из QR (или картинка QR в Chrome/Edge), либо адрес @@ -54,6 +55,10 @@ esim delete ICCID [--yes] esim rename ICCID 'Имя' esim slot [esim|sim] esim apn internet +esim profile-apn ICCID internet.op # подключение профиля: ставится само при enable +esim profile-apn sim1 plus.4g user=plus pass=4g auth=chap # физическая SIM1, при slot sim +esim profile-apn ICCID data ip=ipv4 init=ims # тип IP, APN регистрации в LTE +esim profile-apn ICCID # убрать esim at 'AT+CSQ' esim update | check-update | auto-update [on|off] ``` @@ -68,6 +73,8 @@ esim update | check-update | auto-update [on|off] /etc/esim-tools/router/esim.sh скрипт (/usr/bin/esim) /etc/esim-tools/luci/ исходники страницы /etc/esim-tools/esim.conf настройки +/etc/esim-tools/apn.map подключение профилей: ICCID|sim1, APN, логин, пароль, + авторизация, тип IP, APN регистрации (через табуляцию) /etc/esim-tools/cache/ последний список профилей и данные чипа /etc/esim-tools/history.log команды, запущенные со страницы /etc/esim-tools/auto-update.log запуски автообновления diff --git a/luci/esim-tools.js b/luci/esim-tools.js index 0000811..8be1fd6 100644 --- a/luci/esim-tools.js +++ b/luci/esim-tools.js @@ -12,7 +12,7 @@ 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 callRun = rpc.declare({ object: 'esim-tools', method: 'run', params: [ 'cmd', 'a', 'b', 'c', 'flag', 'd', 'e', 'f', 'g' ], expect: { '': {} } }); var callCancel = rpc.declare({ object: 'esim-tools', method: 'cancel', 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: { '': {} } }); @@ -139,6 +139,43 @@ function parseLpa(s) { return m ? { smdp: m[1], mid: m[2], ccRequired: m[4] == '1' } : null; } +// connection settings of a profile / SIM1 -> one line +function apnSummary(c) { + if (!c || !c.apn) + return desc('не заданы (остаётся текущий APN)'); + return [ E('code', c.apn) ].concat(desc([ c.user ? 'логин ' + c.user : '', c.pass ? 'пароль ***' : '', + c.auth ? c.auth.toUpperCase() : '', c.ip || '', c.init ? 'APN регистрации ' + c.init : '' ] + .filter(Boolean).map(function(t) { return ' · ' + t; }).join(''))); +} + +// APN the network gave to the active SIM: +CGCONTRDP (what the network assigned +// to the active bearers) first, else +CGDCONT? (what the modem has configured). +// The network may append the operator id (.mncXXX.mccYYY.gprs) - cut off. +var SERVICE_APN = /^(ims|sos|xcap|ut|hos|mms)$/i; +var PDP_IP = { 'IP': 'ipv4', 'IPV6': 'ipv6', 'IPV4V6': '' }; + +function parseNetApn(contrdp, cgdcont) { + var strip = function(a) { return String(a || '').trim().replace(/\.mnc\d+\.mcc\d+\.gprs$/i, ''); }; + var types = {}, configured = []; + String(cgdcont || '').split('\n').forEach(function(l) { + var m = l.match(/\+CGDCONT:\s*(\d+)\s*,\s*"?([^",]*)"?\s*,\s*"?([^",]*)"?/); + if (!m) + return; + types[m[1]] = m[2].toUpperCase(); + var apn = strip(m[3]); + if (apn && !SERVICE_APN.test(apn)) + configured.push({ apn: apn, ip: PDP_IP[types[m[1]]], from: 'настроен в модеме (+CGDCONT)' }); + }); + var net = []; + String(contrdp || '').split('\n').forEach(function(l) { + var m = l.match(/\+CGCONTRDP:\s*(\d+)\s*,\s*\d+\s*,\s*"?([^",]*)"?/); + var apn = m && strip(m[2]); + if (apn && !SERVICE_APN.test(apn)) + net.push({ apn: apn, ip: PDP_IP[types[m[1]]], from: 'выдан сетью (+CGCONTRDP)' }); + }); + return net[0] || configured[0] || null; +} + function readImage(input) { var f = input.files && input.files[0]; if (!f) @@ -173,6 +210,108 @@ return view.extend({ return btn; }, + // ---- Настройки подключения профиля (apn.map) ---- + + apnButton: function(label, key, title, cur, active) { + var btn = E('button', { 'class': 'btn cbi-button cbi-button-action', + 'click': ui.createHandlerFn(this, function() { this.apnDialog(key, title, cur || {}, active); }) }, label); + btn.disabled = this.busy; + this.buttons.push(btn); + return btn; + }, + + apnDialog: function(key, title, cur, active) { + var sel = function(value, opts) { + var s = E('select', { 'class': 'cbi-input-select' }, opts.map(function(o) { return E('option', { 'value': o[0] }, o[1]); })); + s.value = value || ''; + if (s.value != (value || '')) + s.appendChild(E('option', { 'value': value, 'selected': 'selected' }, value)); + return s; + }; + var f = { + apn: text(cur.apn, 'internet'), + user: text(cur.user), + pass: E('input', { 'type': 'password', 'class': 'cbi-input-password', 'value': cur.pass || '' }), + auth: sel(cur.auth, [ [ '', 'по умолчанию' ], [ 'pap', 'PAP' ], [ 'chap', 'CHAP' ], [ 'pap chap', 'PAP или CHAP' ], + [ 'mschapv2', 'MSCHAPv2' ], [ 'none', 'без авторизации' ] ]), + ip: sel(cur.ip, [ [ '', 'IPv4v6 (по умолчанию)' ], [ 'ipv4', 'только IPv4' ], [ 'ipv6', 'только IPv6' ] ]), + init: text(cur.init, 'пусто — как модем решит сам') + }; + var showPass = E('label', { 'style': 'margin-left:.5em' }, [ E('input', { 'type': 'checkbox', 'change': function(ev) { + f.pass.type = ev.target.checked ? 'text' : 'password'; + } }), ' показать' ]); + + // only the SIM that works right now can be asked + var live = this.slotNow ? (key == 'sim1' ? this.slotNow == 'sim' : active && this.slotNow == 'esim') : true; + var netOut = E('pre', { 'style': 'white-space:pre-wrap;max-height:10em;overflow:auto;margin:.4em 0 0;display:none;font-size:90%' }); + var netHint = E('span', { 'class': 'cbi-value-description', 'style': 'margin-left:.5em' }); + var netBtn = E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': ui.createHandlerFn(this, function() { + dom.content(netHint, 'спрашиваю модем…'); + return Promise.all([ callAt('AT+CGCONTRDP'), callAt('AT+CGDCONT?') ]).then(function(r) { + var err = r[0].error || r[1].error; + netOut.style.display = ''; + netOut.textContent = err ? '!! ' + err : '> AT+CGCONTRDP\n' + (r[0].output || '') + '\n> AT+CGDCONT?\n' + (r[1].output || ''); + if (err) + return dom.content(netHint, E('span', { 'style': RED }, 'модем не ответил')); + var found = parseNetApn(r[0].output, r[1].output); + if (!found) + return dom.content(netHint, E('span', { 'style': RED }, + 'APN в ответе не нашёлся — сеть не подключена или APN пустой; ответ модема ниже')); + f.apn.value = found.apn; + if (found.ip != null) + f.ip.value = found.ip; + dom.content(netHint, [ E('strong', { 'style': GREEN }, found.apn), ' — ' + found.from + + (found.ip != null ? ', тип IP подставлен' : '') + '. Логин/пароль сеть не сообщает.' ]); + }).catch(function(e) { dom.content(netHint, String(e)); }); + }) }, 'Узнать у сети'); + if (!live) { + netBtn.disabled = true; + dom.content(netHint, key == 'sim1' ? 'сейчас активна eSIM — переключи слот на SIM1' : 'сначала включи этот профиль'); + } + + var submit = L.bind(function(remove) { + var d = {}; + Object.keys(f).forEach(function(k) { d[k] = k == 'pass' ? f[k].value : f[k].value.trim(); }); + if (!remove) { + var errors = []; + if (!/^[A-Za-z0-9._-]+$/.test(d.apn)) + errors.push('APN обязателен: буквы, цифры, . - _'); + if (d.init && !/^[A-Za-z0-9._-]+$/.test(d.init)) + errors.push('APN регистрации: буквы, цифры, . - _'); + if (/[\t\r\n]/.test(d.user + d.pass)) + errors.push('логин/пароль: без табуляций и переводов строки'); + if (errors.length) + return ui.addNotification(null, errors.map(function(e) { return E('p', e); }), 'danger'); + } + ui.hideModal(); + return this.run('profile-apn', remove ? [ key ] + : [ key, d.apn, d.user, false, d.pass, d.auth, d.ip, d.init ]); + }, this); + + ui.showModal('Подключение: ' + title, [ + E('p', { 'class': 'cbi-value-description' }, 'Обязателен только APN, остальное — если оператор это указал. ' + + (active ? 'Профиль сейчас активен: интерфейс переподключится сразу.' : 'Применится при включении.')), + field('APN', [ f.apn, E('div', { 'style': 'margin-top:.3em' }, [ netBtn, netHint ]), netOut ], + '«Узнать у сети» — APN, который оператор выдал этой SIM сейчас'), + field('Логин', f.user), + field('Пароль', [ f.pass, showPass ]), + field('Авторизация', f.auth, 'PAP/CHAP — если оператор дал логин и пароль'), + field('Тип IP', f.ip, 'если не подключается с IPv4v6 — попробуй только IPv4'), + field('APN регистрации', f.init, 'initial EPS bearer: только если модем не регистрируется в LTE ' + + '(«регистрация отклонена» при нормальном сигнале)'), + E('div', { 'class': 'right' }, [ + E('button', { 'class': 'btn', 'click': ui.hideModal }, 'Отмена'), ' ', + cur.apn ? E('button', { 'class': 'btn cbi-button cbi-button-remove', 'click': ui.createHandlerFn(this, function() { + if (window.confirm('Убрать настройки подключения для ' + title + '? Интерфейс останется с текущими.')) + return submit(true); + }) }, 'Убрать') : '', ' ', + E('button', { 'class': 'btn cbi-button cbi-button-save', 'click': ui.createHandlerFn(this, function() { + return submit(false); + }) }, 'Сохранить') + ]) + ]); + }, + // ---- Модем: состояние по AT ---- renderModem: function() { @@ -222,6 +361,7 @@ return view.extend({ 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 apns = p.apns || {}; var rows = []; (Array.isArray(list) ? list : []).forEach(L.bind(function(pr) { @@ -233,7 +373,8 @@ return view.extend({ E('td', { 'class': 'td' }, on ? E('strong', { 'style': GREEN }, '● включён') : E('span', '○ выключен')), E('td', { 'class': 'td' }, [].concat(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) ] : [])), + pr.profileName && pr.profileName != pr.serviceProviderName ? [ E('br'), desc(pr.profileName) ] : [], + [ E('br'), desc('APN: ') ], apnSummary(apns[pr.iccid]))), E('td', { 'class': 'td' }, E('code', pr.iccid)), E('td', { 'class': 'td right', 'style': 'white-space:nowrap' }, [ on @@ -243,6 +384,8 @@ return view.extend({ 'Включить профиль ' + (pr.profileNickname || pr.serviceProviderName || pr.iccid) + '? Текущий выключится, модем перезагрузится, интернет пропадёт на минуту-две.'), ' ', + this.apnButton('APN', pr.iccid, pr.profileNickname || pr.serviceProviderName || pr.iccid, apns[pr.iccid], on), + ' ', this.button('Имя', 'action', 'rename', function() { var n = window.prompt('Имя профиля ' + pr.iccid + ' (до 64 символов):', pr.profileNickname || ''); return n && n.trim() ? [ pr.iccid, n.trim() ] : null; @@ -458,7 +601,11 @@ return view.extend({ } return [ v ]; }, 'Записать APN и переподключить интерфейс ' + st.iface + '?'), - E('div', { 'class': 'cbi-value-description' }, 'iptype ipv4v6 и роуминг включаются вместе с APN') ]), + E('div', { 'class': 'cbi-value-description' }, 'текущий, вручную; iptype ipv4v6 и роуминг включаются вместе с APN. ' + + 'Свой APN у каждого профиля eSIM — кнопка «APN» в списке профилей') ]), + row('Подключение физической SIM1', [].concat(apnSummary(this.apns.sim1), ' ', + this.apnButton('Задать', 'sim1', 'физическая SIM1', this.apns.sim1, false), + E('div', { 'class': 'cbi-value-description' }, 'ставится само при переключении слота на SIM1'))), 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 ]) @@ -532,7 +679,8 @@ return view.extend({ }, run: function(cmd, a) { - return callRun(cmd, a[0] || '', a[1] || '', a[2] || '', !!a[3]).then(L.bind(function(r) { + // a: [ a, b, c, flag, d, e, f, g ] - see m_run in rpcd.sh + return callRun(cmd, a[0] || '', a[1] || '', a[2] || '', !!a[3], a[4] || '', a[5] || '', a[6] || '', a[7] || '').then(L.bind(function(r) { if (r.error) { ui.addNotification(null, E('p', r.error), 'danger'); return; @@ -550,6 +698,7 @@ return view.extend({ }, renderAll: function(st, prof) { + this.apns = prof.apns || {}; this.renderConn(st, false); this.renderProfiles(prof); this.renderMaint(st); diff --git a/luci/rpcd.sh b/luci/rpcd.sh index 6b06d77..721e095 100755 --- a/luci/rpcd.sh +++ b/luci/rpcd.sh @@ -155,14 +155,37 @@ m_modem() { json_dump } +# apn.map (tab-separated: KEY APN USER PASS AUTH IPTYPE INIT_APN, or the old +# "KEY APN") -> {"": {apn, user, pass, auth, ip, init}}; \037 between +# fields so that read keeps the empty ones +apns_json() { + us=$(printf '\037') + json_init + awk -F'\t' -v us="$us" ' + NF == 1 { split($0, a, " "); $0 = a[1] "\t" a[2] } + $1 != "" { print $1 us $2 us $3 us $4 us $5 us $6 us $7 }' "$KIT_DIR/apn.map" 2>/dev/null > /tmp/esim-tools-apn.$$ + while IFS="$us" read -r k apn user pass auth ip init; do + json_add_object "$k" + json_add_string apn "$apn" + json_add_string user "$user" + json_add_string pass "$pass" + json_add_string auth "$auth" + json_add_string ip "$ip" + json_add_string init "$init" + json_close_object + done < /tmp/esim-tools-apn.$$ + rm -f /tmp/esim-tools-apn.$$ + 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)" + printf '{"list":%s,"list_time":%s,"chip":%s,"chip_time":%s,"apns":%s,"now":%s}\n' \ + "${l:-null}" "${lt:-0}" "${c:-null}" "${ct:-0}" "$(apns_json)" "$(date +%s)" } iccid_ok() { @@ -177,6 +200,10 @@ m_run() { 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) + a4=$(jsonfilter -s "$input" -e '@.d' 2>/dev/null) + a5=$(jsonfilter -s "$input" -e '@.e' 2>/dev/null) + a6=$(jsonfilter -s "$input" -e '@.f' 2>/dev/null) + a7=$(jsonfilter -s "$input" -e '@.g' 2>/dev/null) label= case "$cmd" in refresh) set -- esim refresh ;; @@ -216,6 +243,29 @@ m_run() { case "$a1" in '' | *[!A-Za-z0-9._-]*) reply_error "bad APN" ;; esac set -- esim apn "$a1" ;; + profile-apn) + # a = ICCID|sim1, b = APN (empty: remove), c = user, d = password, + # e = auth ("pap chap"), f = ipv4|ipv6|ipv4v6, g = APN for the LTE attach + [ "$a1" = sim1 ] || iccid_ok "$a1" || reply_error "bad ICCID" + case "$a2$a7" in *[!A-Za-z0-9._-]*) reply_error "bad APN" ;; esac + for v in "$a3" "$a4"; do + [ "$(printf '%s' "$v" | tr -d '\t\r\n\037')" = "$v" ] || reply_error "управляющие символы в логине/пароле" + done + for v in $a5; do + case "$v" in pap | chap | mschap | mschapv2 | eap | none) ;; *) reply_error "bad auth: $v" ;; esac + done + case "$a6" in '' | ipv4 | ipv6 | ipv4v6) ;; *) reply_error "bad IP type" ;; esac + set -- esim profile-apn "$a1" "${a2:--}" + label="esim profile-apn $a1 ${a2:--}" + if [ -n "$a2" ]; then + [ -n "$a3" ] && set -- "$@" "user=$a3" && label="$label user=$a3" + # the password stays out of the page and the history + [ -n "$a4" ] && set -- "$@" "pass=$a4" && label="$label pass=***" + [ -n "$a5" ] && set -- "$@" "auth=$a5" && label="$label auth=$a5" + [ -n "$a6" ] && set -- "$@" "ip=$a6" && label="$label ip=$a6" + [ -n "$a7" ] && set -- "$@" "init=$a7" && label="$label init=$a7" + fi + ;; update) set -- esim update ;; autoupdate-on) set -- esim auto-update on ;; autoupdate-off) set -- esim auto-update off ;; @@ -329,7 +379,7 @@ m_update_check() { case "$1" in list) - echo '{"status":{},"modem":{},"profiles":{},"job":{},"cancel":{},"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":{}}' + echo '{"status":{},"modem":{},"profiles":{},"job":{},"cancel":{},"run":{"cmd":"str","a":"str","b":"str","c":"str","flag":true,"d":"str","e":"str","f":"str","g":"str"},"at":{"cmd":"str"},"config_set":{"at_port":"str","wdm":"str","iface":"str"},"update_check":{}}' ;; call) case "$2" in diff --git a/router/esim.sh b/router/esim.sh index a3c005e..8a99875 100755 --- a/router/esim.sh +++ b/router/esim.sh @@ -16,6 +16,8 @@ KIT_DIR=/etc/esim-tools CONF=$KIT_DIR/esim.conf CACHE=$KIT_DIR/cache +# " " построчно: APN, который ставится при включении профиля +APN_MAP=$KIT_DIR/apn.map KIT_URL="${KIT_URL:-https://git.sam-hub.net/sam/esim-tools/archive/main.tar.gz}" # conf KEY -> значение из esim.conf (переменная окружения важнее) @@ -60,6 +62,9 @@ usage() { rename ICCID NAME задать имя профилю slot [esim|sim] показать или переключить слот apn APN задать APN для интерфейса и переподключиться + profile-apn ICCID|sim1 [APN] [user=..] [pass=..] [auth=pap|chap] [ip=ipv4|ipv6|ipv4v6] [init=APN] + подключение профиля (или физической SIM1): ставится + само при включении профиля / слота; без APN - убрать at 'AT...' отправить AT-команду в AT_PORT update скачать свежий esim-tools с git и поставить @@ -266,6 +271,8 @@ do_enable() { run_lpac profile enable "$1" || die "не удалось включить: $(lpac_err)" notifications cache_list + # интерфейс поднимет restore - уже с APN этого профиля + use_apn "$1" reset_modem echo "SIM: $(at 'AT+CPIN?')" } @@ -387,6 +394,11 @@ slot_switch() { at "AT^SWITCH_SLOT=$1" >/dev/null reset_modem at "AT^SWITCH_SLOT?" + if [ "$1" = 0 ]; then + use_apn sim1 + else + use_apn "$(enabled_iccid)" + fi sleep 10 msg "поднимаю $IFACE" ifup "$IFACE" @@ -402,12 +414,126 @@ cmd_slot() { esac } -cmd_apn() { - [ -n "$1" ] || usage +set_apn() { uci set network."$IFACE".apn="$1" uci set network."$IFACE".iptype='ipv4v6' uci set network."$IFACE".allow_roaming='1' uci commit network +} + +TAB="$(printf '\t')" +US="$(printf '\037')" +AUTHS='pap chap mschap mschapv2 eap none' + +# apn_entry : строка из apn.map, поля через \037 (не пробельный +# разделитель: read не схлопывает пустые поля). В файле - через табуляцию: +# KEY APN USER PASS AUTH IPTYPE INIT_APN; старый формат "KEY APN" тоже читается +apn_entry() { + [ -n "$1" ] && [ -f "$APN_MAP" ] || return 0 + awk -F'\t' -v k="$1" -v us="$US" ' + NF == 1 { split($0, a, " "); $0 = a[1] "\t" a[2] } + $1 == k { l = $2 us $3 us $4 us $5 us $6 us $7 } + END { if (l != "") print l }' "$APN_MAP" +} + +# включенный профиль по последнему списку с чипа +enabled_iccid() { + jsonfilter -i "$CACHE/profiles.json" -e "@.payload.data[@.profileState='enabled'].iccid" 2>/dev/null | head -n 1 +} + +# use_apn : настройки подключения из apn.map в интерфейс (без +# переподключения). Нет записи - интерфейс не трогаем; пустое поле - убрать опцию. +use_apn() { + l="$(apn_entry "$1")" + [ -n "$l" ] || return 0 + IFS="$US" read -r apn user pass auth ip init </dev/null + [ -n "$apn" ] && [ "$apn" != - ] && + printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$key" "$apn" "$user" "$pass" "$auth" "$ip" "$init" + } > "$APN_MAP.tmp" + mv "$APN_MAP.tmp" "$APN_MAP" + umask 022 + if [ -z "$apn" ] || [ "$apn" = - ]; then + msg "настройки подключения для $key убраны" + return 0 + fi + msg "сохранено для $key" + # если это то, что сейчас работает, - применить сразу + need sms_tool sms-tool + slot="$(at 'AT^SWITCH_SLOT?')" + if { [ "$key" = sim1 ] && echo "$slot" | grep -q "SIM1 ENABLE"; } || + { [ "$key" = "$(enabled_iccid)" ] && echo "$slot" | grep -q "SIM2 ENABLE"; }; then + use_apn "$key" + msg "переподключаю $IFACE" + ifdown "$IFACE" + sleep 2 + ifup "$IFACE" + else + msg "применится при включении $key" + fi +} + +cmd_apn() { + [ -n "$1" ] || usage + set_apn "$1" msg "APN $1 сохранен, переподключаю $IFACE" ifdown "$IFACE" sleep 2 @@ -577,6 +703,7 @@ case "$cmd" in rename) cmd_rename "$@" ;; slot) cmd_slot "$@" ;; apn) cmd_apn "$@" ;; + profile-apn) cmd_profile_apn "$@" ;; at) cmd_at "$@" ;; config) cmd_config ;; update) cmd_update ;;