Openwrt настройка 4g модема
NCM (Network Control Model) is ethernet over USB protocol used by some fast speed USB modems/dongles.
For more information about different protocols used:
Router Preparation
1. Install OpenWRT
Router should be turned on and connected to the Internet to get the needed packages. Please refer to: Internet Connection.
I have to issue //usbmode -l// and //usbmode -s// every time I reboot my router to detect my USB device. How can I automate it?
Include the following codes into /etc/rc.local just before exit 0:
Checking your balance
To check your balance or send any other AT commands, you need to have usb serial device like: /dev/ttyUSB0
If you have it (if not then install missing usb serial drivers), you can run in first terminal:
You should see in first terminal USSD response.
Build process
Continue selecting packages as needed. When you are done, run the build process
Faster build time can be achieved by enabling multiple build jobs. In case of quad-core cpu.
If build process is successful, your firmware images will be located on bin/target-platform/ .
If your hardware-specific image name could not be found, it's possible that you added too many packages that don't fit your hardware flash memory. Try reducing packages and restart the build process if such case happens.
- Last modified: 2018/03/03 15:25
- by 188.166.177.185
Self-registration in the wiki has been disabled.
If you want to contribute to the OpenWrt wiki, please post HERE in the forum or ask on IRC for access.
Except where otherwise noted, content on this wiki is licensed under the following license:
CC Attribution-Share Alike 4.0 International
Примечание. С моим модемом E392 разрыв соединения не работает (по невыясненной причине), поэтому, для тех, кому это принципиально в прошивке есть usbreset для сброса устройства. При этом если в модеме смонтирована карта памяти, она тоже сбросится (ФС может быть подвергнута ошибкам). Более безболезненный вариант reboot.
Required Packages
To make use of NCM protocol, package kmod-usb-net-huawei-cdc-ncm and comgt-ncm are needed.
usb-modeswitch - It will automatically issue a “special” command to the modem for switching it into the “Working” state
Installation
1. Install all the needed packages
If your have not enough space on your device - think of installing Rootfs on External Storage (extroot)
Another option is Hardware memory upgrade. Refer to your router Forum thread for possibility and instructions.
2. Reboot the router
3. Check that everything is OK and you got new device:
If you have no such device - try to find out what went wrong:
try dmesg to read kernel logs on USB init
or look info about USB devices and interfaces present in the system:
See Troubleshooting Section of this page for more information.
QMI Protocol Configuration
You can configure UCI manually using uci command line or text editor.
UCI is supporting qmi network protocol configuration.
The package uqmi must be installed to use QMI protocol.
Name | Type | Required | Default | Description |
---|---|---|---|---|
device | file path | yes | (none) | QMI device node, typically /dev/cdc-wdm0 |
apn | string | yes | (none) | Used APN |
auth | string | no | (none) | Authentication type: pap, chap, both, none |
username | string | no | (none) | Username for PAP/CHAP authentication |
password | string | no | (none) | Password for PAP/CHAP authentication |
pincode | number | no | (none) | PIN code to unlock SIM card |
delay | number | no | 0 | Seconds to wait before trying to interact with the modem (some ZTE modems require up to 30 s.) |
modes | string | no | (modem default) | Allowed network modes, comma separated list of: all, lte, umts, gsm, cdma, td-scdma |
pdptype | string | no | IP | Used IP -stack mode, IP (for IPv4 ), IPV6 (for IPv6 ) or IPV4V6 (for dual-stack) |
profile | number | no | (none) | Connection profile to use |
dhcp | boolean | no | 1 | Whether to use dhcp (default) or uqmi (0) to get IPv4 interface configuration |
dhcpv6 | boolean | no | 0 | Whether to use dhcp (1) or uqmi (default) to get IPv6 interface configuration |
autoconnect | boolean | no | 1 | |
plmn | number | no | (none) | First three digits are the mcc (mobile country code) and the last three digits are the mnc (mobile network code), for example if plmn=338020, then the mcc is 338 and the mnc is 020 |
timeout | number | no | 10 | Timeout (in seconds) to wait for SIM operations |
Here is a brief help about uqmi command line usage.
Additional Info
Some providers of the cellular internet use redirection to their pages for access activation, when you are connected first time. I.e. YOTA in Russia.
Normally this would be blocked by dnsmasq:
You have 2 options:
Allow rebind responses RFC1918 (In LUCI goto Network → DHCP and DNS and uncheck Rebind protection checkmark)
Save & apply
Additional Info
Some providers of the cellular internet use redirection to their pages for access activation, when you are connected first time. I.e. YOTA in Russia.
Normally this would be blocked by dnsmasq:
You have 2 options:
Allow rebind responses RFC1918 (In LUCI goto Network → DHCP and DNS and uncheck Rebind protection checkmark)
Save & apply
Modem Preparation
You need to switch modem to provide native NCM interface instead of Modem interface.
Please read about AT commands for your modem.
Once you've done - you can disconnect modem from the PC and connect it to the router.
My router is not detecting the dongle. What should I do?
Try the following commands:
It should respond with a message about your USB device is detected. If it does, issue the next command. If it doesn't, you might want to get help from the forum.
Then wait for the dongle to get issued an IP from your ISP .
Network configuration
Now you should add new Interface to /etc/config/network
You can do this using the vi text editor, but if you're not comfortable with that, point your browser to 192.168.1.1 again, choose Network → Interfaces and click Add new interface.
Write wwan as the name of the interface and make it cover the wwan0 interface. Choose DHCP client as the protocol.
Insert a screenshot of LUCI add Interface. I have not enought rights.
Configuration
LTE OR 5G Modem Preparation
More recent Modem default CDC_MBIM OR QMI MODE, This is example for the E20 R2.1, EM05, EM06, EM12, EM20, RM500Q and RM510Q modules
YOU CAN USE AT+QCFG=“usbnet” to CHECK USB Driver
If you want to change the USB MODE, you can set the usbnet value
AT+QCFG=“usbnet”,0 GobiNet or QMI_WWAN
Than reset the power
Configuring packages
Protocol Configuration
UCI is supporting NCM network protocol configuration.
The package comgt-ncm + modem specific driver must be installed to use NCM.
You can configure UCI manually using uci command line or text editor or with Luci package luci-proto-ncm.
If you are using option mode, an AT command setting the mode is sent to modem on every connection. Most of modems (at least all Huawei models) store this setting in internal flash. So on each connection Openwrt writes to modem flash. It is recommended to remove this option after a required mode is set once.
Interface configuration
First check that everything works correctly:
To start the internet connection - issue a command:
Where “internet” is the APN of your provider.
Many providers allow to use “any” APN, so-called “no-settings” connection. So, in many cases “internet” would be just fine
Check the status:
–autoconnect key says that you want always be connected, once dongle is inserted to the router and Cellular Network is in range. It will be kept after reboot.
In case you need additional authentication, please look at the possible arguments for the uqmi utility:
Configuration
Optional Packages
1. Add support for MBIM devices
2. Add support for PC Interface (ttyUSB0) - You need it if you want to send AT commands, for eg. to check your balance by USSD.
3. Add support for FlashCard of your dongle - refer to: USB Storage
MBIM Protocol configuration
Currently, there is not enough information about mbim protocol as it's being actively developed. If you are curious about setting up mbim protocol, you may ask OpenWrt users/devel mailing lists or OpenWrt forum
Here is a brief help about umbim command line.
Web Interface Support
If you want to control your 3g dongle with Luci web interface, go to Luci.
Installation
1. Install all the needed packages
If your have not enough space on your device - think of installing Rootfs on External Storage (extroot)
Another option is Hardware memory upgrade. Refer to your router Forum thread for possibility and instructions.
2. Reboot the router
3. Check that everything is OK and You got new device:
If you have no such device - try to find out what went wrong:
try dmesg to read kernel logs on USB init
or look info about USB devices and interfaces present in the system:
See Troubleshooting Section of this page for more information.
Troubleshooting
Everything is okay but modem doesn't establish connection. What can I try?
You may want to try adding the argument –get-client-id wds and –set-client-id when running uqmi like:
Moreover based on this article I discovered that need to reset my modem (tested on Dell Wireless 5804 413c:819b) in boot process, so you can try add the following commands in your /etc/rc.local:
My router is not detecting the dongle. What should I do?
Try the following commands:
It should respond with a message about your USB device is detected. If it does, issue the next command. If it doesn't, you might want to get help from the forum.
Then wait for the dongle to get issued an IP from your ISP .
I have to issue usbmode -l and usbmode -s every time I reboot my router to detect my USB device. How can I automate it?
Include the following codes into /etc/rc.local just before exit 0:
- Last modified: 2021/03/28 04:25
- by mwynn
Self-registration in the wiki has been disabled.
If you want to contribute to the OpenWrt wiki, please post HERE in the forum or ask on IRC for access.
Except where otherwise noted, content on this wiki is licensed under the following license:
CC Attribution-Share Alike 4.0 International
First of all, you need a complete build environment, either physical or virtual system, as described on the OpenWrt developer guide.
You need to clone OpenWrt git repository on your build system and synchronize all package feeds with your config file.
Be sure to understand the build procedure to prevent build failure.
Additional packages required for 3g functionality
ppp, chat, and uqmi
Go to Network section. Select `uqmi` to support qmi interface and `ppp` to support standard point-to-point protocol. chat is needed to establish serial communication to prepare PPP link negotiation.
Some dongles are using mbim protocol. To make use of mbim protocol, install umbim package.
comgt and usb-modeswitch
Go to Utilities section. Select comgt to provide control over 3g interface and usb-modeswitch to provide mode switching between virtual cd-rom interface to serial interface.
minicom, picocom, and screen
If you want to debug serial communication, you may want to install serial terminal. There are several choices of serial terminal, such as minicom, picocom, and screen. I recommend picocom because of its small size.
Screen can be used as persistent session manager. Minicom has a nice interface, optimized for serial communication.
For devices with 4MB flash, picocom is the only serial terminal that can be installed.
Selecting target architecture and profile
Run make menuconfig .
Select your architecture on which you would put your compiled OpenWrt image. Then select your target profile, according your hardware type.
If you have selected correct value for target system, target profile, and target images, go to next step.
Modem Preparation
You need to switch modem to provide native NDIS interface instead of Modem interface.
Please read about AT commands for your modem.
Once you've done - you can disconnect modem from the PC and connect it to the router.
Troubleshooting
Firewall configuration
The only thing that is left - Add wwan interface to WAN zone
Insert a Screen Shot from LUCI.
I am using 'huawei_cdc_ncm' module and the /dev/cdc-wdm0 does not respond. What do I do?
Some modems does not reconnect after losing connection. Here is a connection check sh script which checks if it can ping remote servers with time intervals. If all pings fail, it tries to start the network by executing /etc/init.d/ncm-network start
If your SIM receives a voice call. It will downgrade to CS network which means you will downgrade into 3G mode. To avoid this, set the stick to use only PS network by creating `/etc/hotplug.d/iface/99-ifupwwan` file with following code. Make sure to modify it to use correct serial interface and correct AT command for your device.
- Last modified: 2021/07/24 01:45
- by someothertime
Self-registration in the wiki has been disabled.
If you want to contribute to the OpenWrt wiki, please post HERE in the forum or ask on IRC for access.
Except where otherwise noted, content on this wiki is licensed under the following license:
CC Attribution-Share Alike 4.0 International
Приветствую. Данная заметка подойдёт тем, кто решил раздавать интернет со своего 4G-модема в локальную сеть посредством Ethernet или Wi-Fi. Когда-то я писал о том, как раздавать интернет с модема в локальную сеть, но тогда интернет шлюзом у нас выступал рабочий компьютер. Теперь же для этих целей будет применяться Wi-Fi маршрутизатор (роутер) с USB портом, в моём случае это TP-Link WR-842N. Преимущества такого способа очевидны: не нужно всё время держать включённым компьютер, чтобы можно было пользоваться интернетом на других устройствах, значительно меньшее потребление электроэнергии, возможность серьёзного расширения функционала и так далее. USB-модем будет работать как WAN-интерфейс, то есть как если бы к роутеру был подключён кабель от интернет-провайдера. Однако родная прошивка роутеров TP-Link весьма ограничена и убога, и я сразу заменяю её на OpenWRT. Правда в этот раз я возьму не сам OpenWRT, а его форк под названием LEDE. Об отличиях можете почитать здесь. Приступим.
Это 4G-модем от Мегафон, который я разлочил для работы с любой сим-картой (я использую МТС) и перевёл для работы в режиме Hilink. Что это значит? У подобных модемов может быть два режима работы - Stick и Hilink. В первом случае модем работает как коммутируемый интерфейс, в котором как и в обычном модеме происходит дозвон на определённый номер. В режиме Hilink модем работает как сетевая карта, и имеет встроенный роутер. В идеале вы должны перепрошить ваш модем для работы в режиме Hilink, информацию об этом можно найти здесь. Если у вас точно такой же модем как у меня - вам сюда. Данный модем сам по себе работает на Линуксе, имеет встроенный роутер с DHCP-сервером и фаерволлом (всё это можно отключить в его веб-интерфейсе). Потому схема работы будет весьма простая: наш TP-Link будет получать IP-адрес от встроенного в модем роутера, а также настройки DNS-серверов, и при этом расшаривать это подключение на все свои интерфейсы.
Первым делом необходимо поставить LEDE. Но перед этим осмотрите наклейку на задней стенке корпуса маршрутизатора. Важно узнать его версию. В моём случае это v3. Скачивайте только прошивку для этой конкретной версии! Переходим по ссылке, выбираем последнюю версию прошивки, далее в разделе targets выбираем ar71xx, затем в generic и ищем нужную прошивку. Обращаем внимание на окончание: sysupgrade - это обновление уже существующей прошивки LEDE, установленной в роутер, factory - это сама прошивка. Нам нужно factory! Скачиваем нужную версию.
Открываем в браузере веб-интерфейс нашего роутера. Для этого в адресной строке вводим 192.168.0.1 . Логин и пароль для входа по умолчанию: admin. Пока не заморачивайтесь сменой пароля, ведь скоро этой прошивки не будет)) Идём в раздел "Системные инструменты", далее "Обновление встроенного ПО". Выбираем скачанный файл с прошивкой и жмём "Обновить". Ждём.
В самом низу страницы выбираем Save&Apply. Перед подключением модема в USB-порт необходимо скачать нужные для его работы модули. Если у вас есть рабочее проводное интернет-соединение - то просто подключите кабель в синий порт на роутере. Если же нет - не беда. Маршрутизатор с OpenWRT/LEDE может работать в режиме Wi-Fi-клиента, и подключаться к любому другому роутеру. Если у вас есть смартфон или планшет с безлимитным интернетом - включите в его настройках точку доступа Wi-FI. Затем в веб-интерфейсе перейдите в "Network" - "Wireless" и нажмите на Scan.
Маршрутизатор просканирует доступные Wi-Fi-сети. Он должен обнаружить сеть, раздаваемую вашим смартфоном. Выберите её и примените. После этого переходим в "System" - "Software" и нажимаем на "Update lists".
После обновления в поле поиска находим поочерёдно пакеты usb-modeswitch (необходим для переключения модема в режим, собственно, модема, так как на многих 3G/4G модемах ещё встроен картридер) и kmod-usb-net-cdc-ether (как раз таки необходим для работы модема в режиме сетевой карты). Устанавливаем их и теперь уже подключаем модем.
Модем сразу определится в системе как сетевой интерфейс, в моём случае как устройство eth2. Переходим в "Network" - "Interfaces" и нажимаем на Add new interface. Нужно добавить наш модем и расшарить с него сеть. Имя интерфейса указываем USB, протокол DHCP, а интерфейсом Ethernet adapter: eth2. Нажимаем на Submit.
В появившемся подключении выбираем Edit, переходим на вкладку Firewall settings и указываем для него зону Wan:
Вот и всё. Остальная настройка уже индивидуальна (пароль на Wi-Fi, шифрование и так далее). Если вы хотите что-то добавить к статье - пишите в комментариях.
7 комментариев:
спасибо тебе добрый человек, на буржуйскийх сайтах всякая ересть написаны, а нужно было всего лишь два пакета поставить. Ни на одном не говорилось про пакет "kmod-usb-net-cdc-ether"
Some new 3G/4G dongles use qmi and mbim protocol to establish connection to ISP . For your information, qmi protocol is proprietary protocol by Qualcomm. In contrast to qmi, mbim is more standardized protocol for 3G/4G dongles.
This recipe explains how to setup and configure OpenWrt for using a USB LTE/3g/UMTS-modem for WAN connection, using QMI interface. You may want to checkout the Multiwan package to use this simultaneously with other connections to the internet.
All recent information is valid for Barrier Breaker release and later. Not tested on AA or elder.
Selecting kernel modules for usb networking support.
Go to Kernel Modules → USB Support .
Select the following modules by pressing y to include the modules within the compiled image.
kmod-usb-net → to support usb networking interface.
Select all subsets if you want perfect support for usb network interfaces, including Android and iPhone tethering. Some newer 4g dongles use usb network interface (rndis) instead of legacy serial protocol.
kmod-usb-serial → to support legacy 3g dongles.
Select all subsets to ensure that your dongle works. Most 3g dongles use the option driver or generic serial driver to work. Note that option driver has better capability of distinguishing between modem serial interfaces and storage interface than generic usb serial driver.
With LuCi web interface
Install the package luci-proto-qmi using Luci (System → Software) and configure the modem using LuCi (Network → Interfaces).
Firewall configuration
The only thing that is left - Add wwan interface to WAN zone
Insert a Screen Shot from LUCI.
Notes
Router Preparation
1. Install OpenWrt
Router should be turned on and connected to the Internet to get the needed packages. Please refer to: Internet Connection.
About
Many modern USB dongles could perform in different ways. If your modem provides only AT command interface - please refer to How to use 3g/UMTS USB Dongle for WAN connection. For more information about different protocols used:
If it is possible to switch your modem to provide NDIS interface - then this article if for YOU.
Add Speed and Performance test results on Modem mode and QMI mode.
Subjective, solution based on NDIS (QMI mode) works much stable. Faster reconnect. Easy to control and monitor.
Optional Packages
1. Add support for PC Interface (ttyUSB0)
3. Add support for FlashCard of your dongle - refer to: USB Storage
Network configuration
Now you should add new Interface to /etc/config/network
You can do this using the vi text editor, but if you're not comfortable with that, point your browser to 192.168.1.1 again, choose Network → Interfaces and click Add new interface.
Write wwan as the name of the interface and make it cover the wwan0 interface. Choose ncm as the protocol.
Insert a screenshot of LUCI add Interface.
My modem doesn't reconnect after it loses the connection
To achieve continuous monitoring of the connection, it must be called recurrently through a cron job as:
Required Packages
To make use of qmi protocol, package kmod-usb-net-qmi-wwan and uqmi are needed. uqmi is available on both barrier breaker and bleeding edge repository.
usb-modeswitch - It will automatically issue a “special” command to the modem for switching it into the “Working” state
Comments (21)
Hi!
Спасибо за прошивку. Очень интересно. Но у меня пока плохо работает.
У меня модем на чипе Qualcomm, в логах роутера
распознается. В Win и Lin хорошо работает, но с роутером не работает.
Я не знаю по какому протоколу. Испробовал все.
Может, что подскажите ?
Роутер А5 V11. Прошивка Бета 7.
И как посмотреть какие пакеты установлены ? (opkg list-installed) opkg — не установлено.
Тут выше указано /dev/ttyUSB0, но каталоге /dev/ нет такого устройства.
Я подключаюсь — ssh root@192.168.4.254 — правильно или нет?
Добрый день. Как он определяется? На каком чипе? Какой модем? С какой прошивкой?
В этой прошивке нет opkg. Необходимые пакеты для работы с модемами установлены в системе. По умолчанию адрес правильный. Без логов помочь не смогу.
Добрый день. не работает мтс к3806
Добрый день. Без логов системы и ядра ничем помочь не смогу.
А что нужно показать? где взять лог системы и ядра?
Воткнуть модем. Загрузить роутер. Войти в настройки. Статус-Системный журнал. Журнал ядра. Содержимое скопировать/вставить.
Модем имеет и ppp интерфейс и cdc. Поэтому можно попробовать настроить обоими способами, но не одновременно. При этом, если настраивать по ncm, то нужно пробовать с разными портами (ttyUSB0-2). Если подключение не заработает, нужно смотреть системный лог после попыток подключения. Там должна быть информация о модеме в системе.
Читайте также: