- Software, Security and Routing
- Monitoring system and LTE
- BIRD
- TRICKS
- At commands
- By the configuration file
- Connection
- Device identification
- Disable mode switching
- Fcc locking
- Fix image quality
- Libmbim
- Low connection speed
- Lte/4g/mobile support · issue #306 · jakeday/linux-surface
- Modem mode
- Modemmanager
- Modemmanager does not recognize the modem
- Monitor used bandwidth
- Netctl
- Networkmanager
- Remove the pin
- Using mmcli
- With a udev rule
- With dedicated software
- With email like web interface
- Writing sms
- Wvdial
- Yellow leaf – статьи – использование 3g/4g-модема в linux без wvdial и network manager
- Yellow leaf – статьи – использование 3g/4g-модема в linux без wvdial и network manager – huawei devices
- Узнайте больше о Huawei
Software, Security and Routing
Then, as my project is to make this modem working on a small OrangePi zero, and to connect it to my home network I will add a part of well known IP forwarding and IPTables.
sysctl.conf
Use iptables-persistent set of script to run it smoothly
iptables IPV4 ruleset
iptables IPV6 is dropping all. Will see IPV6 later.
Monitoring system and LTE
SNMP Daemon
Install SNMP daemon
Then modify /etc/snmp/snmpd.conf
The rest can be left default or adapted to your needs.
- Connectivity
I’m using munin to monitor the device through SNMP.
Use this command to discover most of SNMP sensors :
Then cut/paste the adviced ln commands.
Most will work, CPU, MEM, eth0 traffic/errors
- Temperature and Radio status
On the device temperature is not reported in the SNMP MIB. So I did a little script to get the temperature.
This the file :/usr/local/bin/opi-temp.sh
Also the quality of LTE signal can be monitored this way, with the file : /usr/local/bin/opi-signal.sh
With the extend keywork in snmpd.conf file, the values will be exposed through SNMP. The following will help to find the OIDs.
Then I had to create a specific plugin for Munin to poll for these new OIDs. The file should be placed here :
/usr/share/munin/plugins/snmp__opi_extend
Then ln it as a usual plugin.
And there we are !
BIRD
The second part of the project is to add BIRD and use OSPF protocol to advertise the default gateway and use this LTE Internet connection as a backup to my FTTH connection.
add this to bird.conf should do the trick :
I will add ospf passphrase security :
…
TRICKS
Upon restart the modem stays in an undefined status, which is due to the fact that Linux is rebooting but the modem is not because power is not removed from USB when doing a hot reboot.
So I added a small script executed on stop action (before reboot) to also reset the modem before kernel boots again.
/usr/local/bin/reload-modem
At commands
There are some useful commands:
AT^U2DIAG=0
– the device is only ModemAT^U2DIAG=1
– device is in modem mode CD ROMAT^U2DIAG=255
– the device in modem mode CD ROM Card ReaderAT^U2DIAG=256
– the device in modem mode Card ReaderAT CPIN=PIN-CODE
– enter PIN-codeAT CUSD=1,PDU-encoded-USSD-code,15
– USSD request, result can be found (probably) in/dev/ttyUSB2
.
Encode *100# to PDU format:
$ perl -e '@a=split(//,unpack("b*","*100#")); for ($i=7; $i < $#a; $i =8) { $a[$i]="" } print uc(unpack("H*", pack("b*", join("", @a))))."n"'
Decode AA180C3602 from PDU format:
$ perl -e '@a=split(//,unpack("b*", pack("H*","AA180C3602"))); for ($i=6; $i < $#a; $i =7) {$a[$i].="0" } print pack("b*", join("", @a)).""'
Answer decoding (this example is balance response: 151.25):
$ perl -e 'print pack("H*", "003100350031002C003200350020044004430431002E0020");'
Some operators return USSD result in PDU encoding, so you should check proper decoding method.
AT CSQ
– get signal quality (AT CSQ=?
)AT GMI
– get manufacturerAT GMM
– get modelAT GMR
– get revisionAT GMN
– get IMEIAT COPS?
– get operator infoAT^CARDLOCK="NCK-code"
– unlock modem. NCK-code should be calculated by IMEI. After that modem can work with any GSM-provider.AT^SYSCFG=mode, order, band, roaming, domain
– System Config
Mode:
2
Automatic search13
2G ONLY14
3G ONLY16
No change
Order:
0
Automatic search1
2G first, then 3G2
3G first, then 2G3
No change
Band:
80
GSM DCS systems100
Extended GSM 900200
Primary GSM 900200000
GSM PCS400000
WCDMA IMT 20003FFFFFFF
Any band40000000
No change of band
Roaming:
0
Not supported1
Roaming is supported2
No change
Domain:
0
CS_ONLY1
PS_ONLY2
CS_PS3
ANY4
No change
By the configuration file
/etc/usb_modeswitch.conf
DisableSwitching=1
Connection
To connect to the mobile network, use one of the following methods.
Device identification
Installusbutils.
Examine the output of:
$ lsusb
which will show the vendor and product IDs of the device. Note that some devices will show two different product IDs at different times as explained below.
Note: Mini PCIe adapters also show up in lsusb instead of lspci.
Disable mode switching
Some ways to disable usb_modeswitch from operating on a device before the device was inserted, for example to be able to read the initial flash memory (ZeroCD), are:
Fcc locking
The FCC lock is a software lock integrated in WWAN modules shipped by several different laptop manufacturers like Lenovo, Dell, or HP. This lock prevents the WWAN module from being put online until some specific unlock procedure (usually a magic command sent to the module) is performed.
Since release 1.18.4, the ModemManager daemon no longer automatically performs the FCC unlock procedure [4].
Fix image quality
If you are getting low quality images while browsing the web over a mobile broadband connection with the hints shift r improves the quality of this image and shift a improves the quality of all images on this page, follow these instructions:
Installtinyproxy.
Edit /etc/tinyproxy/tinyproxy.conf and insert the following two lines:
AddHeader "Pragma" "No-Cache" AddHeader "Cache-Control" "No-Cache"
Starttinyproxy.service
Configure your browser to use localhost:8888 as a proxy server and you are all done. This is especially useful if you are using, for example, Google Chrome which, unlike Firefox, does not allow you to modify the Pragma and Cache-Control headers.
Libmbim
Install libmbim. To bring up the modem you can use mbim-network which is a wrapper for mbimcli calls. First create a profile for mbim-network.
/etc/mbim-network.conf
APN=apn=internet.myisp.example
Now connect to the network with:
# mbim-network /dev/cdc-wdmX start
Then follow Network configuration to bring up the ww* interface and get an IP address using DHCP.
Low connection speed
Someone claims that the connection speed under Linux is lower than Windows [3]. This is a short summary for possible solutions which are not fully verified.
In most of conditions, the low speed is caused by bad receiver signals and too many people in cell. But you still could use the following method to try to improve the connection speed:
- QoS parameter can be set with the
AT CGEQMIN
andAT CGEQREQ
commands. It should also be possible to decrease and limit the connection speed. Add the followingInit
command in/etc/wvdial.conf
:
Init6 = AT CGEQMIN=1,4,64,640,64,640 Init7 = AT CGEQREQ=1,4,64,640,64,640
- Baud parameter in
/etc/wvdial.conf
could be used to increase the connection speed:
Baud = 460800
It is advisable to see the baud rate set by the official modem application for Windows (possibly 9600 on Vista).
Lte/4g/mobile support · issue #306 · jakeday/linux-surface
Modem mode
In general, at this point you should note if mode switching left you with additional /dev/ttyUSB* serial device and a ww*network interface. You can do that with journalctl or by shell commands such as:
$ ls /dev/ttyUSB* $ ip link
Modemmanager
Installmodemmanager and usb_modeswitch.
Start and enableModemManager.service.
Use mmcli(1) to communicate with the modem.
The simplest way to establish a connection is to use mmcli’s –simple-connect option.
First, list the modems and find the modem’s index:
$ mmcli -L
Look for /org/freedesktop/ModemManager1/Modem/MODEM_INDEX.
Next connect to the mobile network. For example:
$ mmcli -m MODEM_INDEX --simple-connect="apn=internet.myisp.example"
Modemmanager does not recognize the modem
In case ModemManager does not recognize the modem, check the unit status of ModemManager.service. If you get error messages such as Couldn’t check support for device and not supported by any plugin, you may have to whitelist your device using the ModemManager filter rules.
Monitor used bandwidth
Frequently a 3G connection obtained via a mobile phone operator comes with restricted bandwidth, so that you are only allowed to use a certain bandwidth per time (e.g. 1GB per month). While it is quite straight-forward to know which type of network applications are pretty bandwidth extensive (e.g. video streaming, gaming, torrent, etc.), it may be difficult to keep an overview about overall consumed bandwidth.
Netctl
Netctl can be used to establish a connection using a USB modem. An example configuration file provided by netctl is located at /etc/netctl/examples/mobile_ppp. Minimally you will probably have to specify
/etc/netctl/mobile_ppp
Interface=cdc-wdmX Connection=mobile_ppp AccessPointName=apn=internet.myisp.example
See the netctl article and netctl.profile(5) for more information.
Networkmanager
NetworkManager uses ModemManager to work with mobile broadband modems. See NetworkManager#Mobile broadband support.
Remove the pin
First of all use your SIM card in a normal phone and disable the PIN request if present. If the SIM card asks the PIN wvdial will not work.
Failing that, you can use mmcli (provided by modemmanager) or AT commands, to unlock the SIM card.
Using mmcli
First, list the modems and find the modem’s index:
$ mmcli -L
Look for /org/freedesktop/ModemManager1/Modem/MODEM_INDEX.
Find the SIM card index:
$ mmcli -m MODEM_INDEX
Just as with the modem index, look for primary sim path: /org/freedesktop/ModemManager1/SIM/SIM_INDEX.
Unlock the SIM card:
$ mmcli --sim=SIM_INDEX --pin=PIN
Remove the requirement for PIN:
$ mmcli --sim=SIM_INDEX --pin=PIN --disable-pin
With a udev rule
Masking the udev rule the package is using can be achieved with
With dedicated software
This was tested on a Huawei EM770W (GTM382E) 3g card integrated into an Acer Aspire AS3810TG laptop. Install gnokiiAUR, then:
$ mkdir -p $XDG_CONFIG_HOME/gnokii
Usually the configuration directory is ~/.config/gnokii.
$ cp /etc/gnokiirc ~/.config/gnokii/config
Edit ~/.config/gnokii/config as follows:
port = /dev/ttyUSB0
You may have to use a different port depending on your configuration, for example /dev/ttyUSB1 or something else:
model = AT connection = serial
You need to be part of the uucpgroup to use /dev/ttyUSB0.
Then launch gnokii:
$ xgnokii
Click on the “SMS” icon button, a window opens up. Then click: “messages->activate sms reading”. Your messages will show up in the window.
Command line script:
A small command line script using gnokii to read SMS on your SIM card (not phone memory) without having to start a GUI:
$ gnokii --getsms SM 0 end 2>&1|grep Text -A1 -B3|grep -v Text
What it does:
gnokii # invoke gnokii --getsms SM 0 end # read SMS from SM-memory location (=SIM card) starting at 0 and reading all occupied memory locations ("end") 2>&1 # connect STDERR to STDOUT to make sure the output from the --getsms command can be piped to grep |grep Text # pipe output from gnokii to grep, anchoring at output containing "Text" -A1 -B3 # print one line after the matched pattern and three lines before the matched pattern |grep -v Text # grep result to another grep to exclude the "Text" line (-v for inverting the pattern)
Granted this does not work very well if your SMS contains the word “Text”, but you may adapt the script to your liking.
Another option is to use mmcli
#!/bin/sh #get modem number MODEMNO=$(mmcli -L | grep -o "Modem/[0-9]" | grep -o [0-9]$) #list newest SMS SMSNO=$(mmcli -m ${MODEMNO} --messaging-list-sms | awk '/received/{split($1, ar, ///); print ar[6]; exit}') #read message mmcli -m ${MODEMNO} -s /org/freedesktop/ModemManager1/SMS/${SMSNO}
With email like web interface
Some Devices, such as some Huawei HiLink, include an email like web interface for SMS. It is included in the device internal web server, which is used for other purposes too.
Writing sms
#!/bin/sh #get modem number MODEMNO=$(mmcli -L | grep -o "Modem/[0-9]" | grep -o [0-9]$) #create sms in modem and get number SMSNO=$(mmcli -m ${MODEMNO} --messaging-create-sms="text='$1',number= $2" | grep -o [0-9]*$) #send message mmcli -s ${SMSNO} --send # delete all sent messages for i in $(mmcli -m ${MODEMNO} --messaging-list-sms | grep " (sent)" | cut -f5 -d' ') ; do mmcli -m ${MODEMNO} --messaging-delete-sms=$i done
You may need give permission by creating file with content like
Wvdial
See main article: wvdial
Yellow leaf – статьи – использование 3g/4g-модема в linux без wvdial и network manager
Про использование GSM/3G/4G-модемов в Linux написано уже много, но почти все руководства предполагают использование утилит wvdial или network manager для подключения. Эти утилиты позволяют существенно упростить процесс подключения, однако при их использовании невозможно полностью управлять опциями pppd, хотя это бывает необходимо (например при подключении нескольких модемов и/или когда надо “привязывать” подключения к конкретному ppp-интерфейсу).
Далее будет показано как можно настроить подключение к интернету с использованием GSM/3G-модема в дистрибутивах Debian/Ubutnu без использования вспомогательных утилит.
Начальные условия: сервер под управлением Ubuntu 12.04, модем Huawei E171 с симкой оператора “Мегафон”, доступный в системе как “/dev/ttyUSB0”.
Задача: подключиться к интернету используя только pppd и привязать соединение к интерфейсу ppp100.
Переходим к решению задачи. Обычно для дозвона пишут свой chat-скрипт, и почему-то не многие знают что в поставке pppd уже есть chat-скрипт для GSM/3G-модемов, доступный в большинстве дистрибутивов Linux как “/etc/chatscripts/gprs”. Поэтому часть с написанием этого скрипта можно пропустить и сразу приступить к описанию подключения в pppd. Для этого создадим файл “/etc/ppp/peers/Megafon” следующего содержания:
# Используемое для подключения устройство /dev/ttyUSB0 # chat-скрипт # В параметре "-T" передаётся имя точки доступа connect '/usr/sbin/chat -v -f /etc/chatscripts/gprs -T internet' # Надо ли менять маршрут по умолчанию # Закомментируйте если не надо defaultroute # Использовать ли DNS-сервера провайдера # Закомментируйте если не надо usepeerdns # Номер ppp-интерфейса (в данном случае будет ppp100) unit 100 # Подключаться в случае обрыва persist # Перепосылать пакеты авторизации каждые 60 секунд # Позволяет избежать обрыва соединения при отсутствии трафика chap-interval 60 # Идентификатор соединения, используемый для поиска паролей в соответствующих файлах, # А так же передаваемый ip-up и ip-down-скриптам ipparam Megafon # Имя пользователя (пароль описывается в файле "/etc/ppp/chap-secrets") user "gdata" # Отключаем любое сжатие nopcomp novjccomp nobsdcomp nodeflate noaccomp # Правильная обработка обрывов соединения lcp-echo-interval 2 lcp-echo-failure 3 # IP адрес мы будем получать от провайдера, а не назначать сами noipdefault
Теперь вписываем в файл “/etc/ppp/chap-secrets” следующие строки
"gdata" Megafon "gdata"
И подключаемся командой:
pon Megafon
Соответственно отключиться можно командой:
poff Megafon
Чтобы соедиение устанавливалось автоматически при загрузке нужно добавить запись в файл “/etc/network/interfaces”. Согласно документации она должна выглядеть вот так:
auto Megafon iface Megafon inet ppp provider Megafon
Однако в утилите ifup есть баг, который приводит к тому, что сразу после успешного подключения pppd получает SIGHUP и соединение рвётся. Ошибка эта очень древняя и судя по сообщениям на форумах и баг-трэкерам дистрибутивов надеяться на её исправление в ближайшем будущем не стоит. Поэтому используем небольшой хак: опишем интерфейс не как ppp, а как manual:
auto Megafon iface Megafon inet manual pre-up /usr/bin/pon Megafon pre-down /usr/bin/poff Megafon
На этом всё. Приятной работы!
Yellow leaf – статьи – использование 3g/4g-модема в linux без wvdial и network manager – huawei devices
Продолжение. Начало здесь.
Для тех, кто недавно присоединился к радиоканалу «Боян-FM» читателям моей уютненькой™, напомню, что затеял всё это ради того, чтобы построить достаточно скоростной IPSec-канал через «Йоту». А для этого, в свою очередь, необходимо получить прямой «честный» IP с SIM-карты на каком-либо сетевом интерфейсе, притом минуя PPP.
Конкретно я использую модем iRZ TL21, построенный на базе модуля Sierra (он же AirPrime) MC7710, в составе которого находится чип Qualcomm MDM9200. Система — стабильный дистрибутив Debian (в данном случае Wheezy).
Сразу оговорюсь, что в какой-нибудь свежей Ubuntu данный модем заработает прям «из коробки»: его хорошо понимает NetworkManager. Но мы ж реальные пацаны, у нас реальный сервак, GUI на нём нетути. Да и подниматься линк должен сам по себе при старте системы. Поэтому пойти по простому пути не получится, придётся никакой механизма всё вручную.
Итак, суём модем в USB-порт, заправшиваем «lsusb» и видим…
Bus 006 Device 002: ID 03f0:1027 Hewlett-Packard Virtual keyboard and mouse
Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 004 Device 003: ID 1199:68a2 Sierra Wireless, Inc. MC7710 Modem
Bus 004 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Ага, третья строчка — вот оно как раз самое. Выделенные жирным шрифтом цифирки нам потом ещё пригодятся. Ну что-ж, вроде как всё хорошо. Смотрим «ls /dev/ttyUSB*» и видим… а ничего мы не видим. Как говорится, «***в панама». Нету псевдотерминалов.
Иногда затык может заключаться в том, что некоторые модемы «тянут» за собой виртуальный CD-ROM, на котором типа лежат типа драйвера для этого модема. И пока не пнёшь этот модем правильной AT-командой, собственно в модем он не превратится. А будет и дальше себе с настойчивостью кретина прикидываться CD-приводом. Ну это лечится элементарной установкой пакета «usb-modeswitch»: «apt-get install usb-modeswitch«.
Ладно, установили. Но псевдотерминалы всё равно не появились. Чешем репу. И вспоминаем, что в Debian-е по умолчанию идёт довольно боянистый софт, и нужных драйверов «из коробки» нет. Чтобы не париться уж слишком сильно, можно тупо поставить свежее ядрышко из backports. На момент написания этого псто оно было версии 3.16:
Перезагрузились. Смотрим «modinfo qmi_wwan» и «modinfo sierra_net«. Если выделенные жирным циферки из выхлопа lsusb (см. выше) оказались в одном из двух списков, то всё пучком. Можем продолжать. Если же нет, увы. Идем искать драйвера к нашему «мопеду». Хорошо если найдём. А если не найдем — значит «упс». В моём случае всё ништяк:
Внезапно, и псевдотерминалы появились в большом количестве:
Дальше тыкаем каким-нибудь minicom-ом в каждый терминал по очереди («minicom -D /dev/ttyUSB0«, «minicom -D /dev/ttyUSB1» и т.п.) и смотрим который из них откликнется на какой нибудь «AT!GSTATUS?«, тот и есть нужный нам. Заодно проверим, что модем сцепился с сотовой сетью.
RSSI (dBm): -75 Tx Power: 0
RSRP (dBm): -103 TAC: 26BD (9917)
RSRQ (dB): -9 Cell ID: 0F30DB00 (254860032)
SINR (dB): 7.2
OK
Вроде работает. Тут наступает небольшая засада. В дальнейшем нам придётся из различных скриптов ссылаться на найденный псевдотерминал. Но никто не может гарантировать нам, что после очередной перезагрузки сервера имя устройства останется таким же. Поэтому придётся помучать udev для того чтобы создать символическую ссылку (symlink), дабы увековечить нашу бесценную находку. Для начала смотрим к каким атрибутам мы могли бы привязаться.
Копипаста ниже была взята с другой конфигурации оборудования, поэтому некоторые буквы-цифры там будут расходиться с моим примером. Самые внимательные, наверное, даже найдут где именно. Но общий смысл от этого не меняется. Текстовое поле можно растянуть, чтобы было удобнее читать.
Udevadm info starts with the device specified by the devpath and then
walks up the chain of parent devices. It prints for every device
found, all possible attributes in the udev rules key format.
A rule to match, can be composed by the attributes of the device
and the attributes from one single parent device.
looking at device ‘/devices/pci0000:00/0000:00:1d.7/usb4/4-5/4-5:1.3/ttyUSB3/tty/ttyUSB3’:
KERNEL==»ttyUSB3″
SUBSYSTEM==»tty»
DRIVER==»»
looking at parent device ‘/devices/pci0000:00/0000:00:1d.7/usb4/4-5/4-5:1.3/ttyUSB3’:
KERNELS==»ttyUSB3″
SUBSYSTEMS==»usb-serial»
DRIVERS==»sierra»
ATTRS{port_number}==»0″
looking at parent device ‘/devices/pci0000:00/0000:00:1d.7/usb4/4-5/4-5:1.3’:
KERNELS==»4-5:1.3″
SUBSYSTEMS==»usb»
DRIVERS==»qcserial»
ATTRS{bInterfaceClass}==»ff»
ATTRS{bInterfaceSubClass}==»ff»
ATTRS{bInterfaceProtocol}==»ff»
ATTRS{bNumEndpoints}==»03″
ATTRS{supports_autosuspend}==»1″
ATTRS{bAlternateSetting}==» 0″
ATTRS{bInterfaceNumber}==»03″
looking at parent device ‘/devices/pci0000:00/0000:00:1d.7/usb4/4-5’:
KERNELS==»4-5″
SUBSYSTEMS==»usb»
DRIVERS==»usb»
ATTRS{bDeviceSubClass}==»00″
ATTRS{bDeviceProtocol}==»00″
ATTRS{devpath}==»5″
ATTRS{idVendor}==»1199″
ATTRS{speed}==»480″
ATTRS{bNumInterfaces}==» 6″
ATTRS{bConfigurationValue}==»1″
ATTRS{bMaxPacketSize0}==»64″
ATTRS{busnum}==»4″
ATTRS{devnum}==»3″
ATTRS{configuration}==»Sierra Configuration»
ATTRS{bMaxPower}==»0mA»
ATTRS{authorized}==»1″
ATTRS{bmAttributes}==»e0″
ATTRS{bNumConfigurations}==»1″
ATTRS{maxchild}==»0″
ATTRS{bcdDevice}==»0006″
ATTRS{avoid_reset_quirk}==»0″
ATTRS{quirks}==»0x0″
ATTRS{serial}==»358178041352404″
ATTRS{version}==» 2.00″
ATTRS{urbnum}==»895″
ATTRS{ltm_capable}==»no»
ATTRS{manufacturer}==»Sierra Wireless, Incorporated»
ATTRS{removable}==»unknown»
ATTRS{idProduct}==»68a3″
ATTRS{bDeviceClass}==»00″
ATTRS{product}==»MC7710″
looking at parent device ‘/devices/pci0000:00/0000:00:1d.7/usb4’:
KERNELS==»usb4″
SUBSYSTEMS==»usb»
DRIVERS==»usb»
ATTRS{bDeviceSubClass}==»00″
ATTRS{bDeviceProtocol}==»00″
ATTRS{devpath}==»0″
ATTRS{idVendor}==»1d6b»
ATTRS{speed}==»480″
ATTRS{bNumInterfaces}==» 1″
ATTRS{bConfigurationValue}==»1″
ATTRS{bMaxPacketSize0}==»64″
ATTRS{authorized_default}==»1″
ATTRS{busnum}==»4″
ATTRS{devnum}==»1″
ATTRS{configuration}==»»
ATTRS{bMaxPower}==»0mA»
ATTRS{authorized}==»1″
ATTRS{bmAttributes}==»e0″
ATTRS{bNumConfigurations}==»1″
ATTRS{maxchild}==»8″
ATTRS{bcdDevice}==»0316″
ATTRS{avoid_reset_quirk}==»0″
ATTRS{quirks}==»0x0″
ATTRS{serial}==»0000:00:1d.7″
ATTRS{version}==» 2.00″
ATTRS{urbnum}==»61″
ATTRS{ltm_capable}==»no»
ATTRS{manufacturer}==»Linux 3.16.0-0.bpo.4-amd64 ehci_hcd»
ATTRS{removable}==»unknown»
ATTRS{idProduct}==»0002″
ATTRS{bDeviceClass}==»09″
ATTRS{product}==»EHCI Host Controller»
looking at parent device ‘/devices/pci0000:00/0000:00:1d.7’:
KERNELS==»0000:00:1d.7″
SUBSYSTEMS==»pci»
DRIVERS==»ehci-pci»
ATTRS{irq}==»16″
ATTRS{subsystem_vendor}==»0x103c»
ATTRS{broken_parity_status}==»0″
ATTRS{class}==»0x0c0320″
ATTRS{companion}==»»
ATTRS{driver_override}==»(null)»
ATTRS{consistent_dma_mask_bits}==»32″
ATTRS{dma_mask_bits}==»32″
ATTRS{local_cpus}==»00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,0000000f»
ATTRS{device}==»0x268c»
ATTRS{uframe_periodic_max}==»100″
ATTRS{enable}==»1″
ATTRS{msi_bus}==»»
ATTRS{local_cpulist}==»0-3″
ATTRS{vendor}==»0x8086″
ATTRS{subsystem_device}==»0x31fe»
ATTRS{numa_node}==»-1″
ATTRS{d3cold_allowed}==»1″
looking at parent device ‘/devices/pci0000:00’:
KERNELS==»pci0000:00″
SUBSYSTEMS==»»
DRIVERS==»»
Смотрим к каким атрибутам оборудования мы можем «привязаться». Однозначно придётся использовать критерий SUBSYSTEM==»tty» из первой секции, иначе получится ерунда. Но этого мало. Нужно что-то ещё. Большой соблазн взять ATTRS{product}==»MC7710″, чтобы однозначно идентифицировать устройство, но… тогда мы не сможем указать номер интерфейса. Ибо udev позволяет брать параметры устройства и только одного родителя. Поэтому придётся довольствоваться ATTRS{bInterfaceNumber}==»03″ и DRIVERS==»qcserial» из третьей секции. Итоговое правило будет выглядеть так:
Записываем его куда-нибудь в «/etc/udev/rules.d/80-LTE.rules», после чего заклинаем «udevadm control —reload-rules«, «udevadm trigger«. Первое нужно, чтобы udev перечитал список правил, второе — чтобы не топать ногами в серверную и не «перевтыкать» руками модем.
Итак, у нас появилась символическая ссылка «/dev/LTE-control». Что же с ней делать дальше? А дальше надо указать модему APN и логин-пароль, если есть. Но каждый раз мы это делать руками, понятно, не будем. Поэтому имеет смысл либо написать скрипт, либо запихнуть вызов соответствующих команд прямо в «/etc/network/interfaces». У меня получилось что-то типа того.
В директиве «pre-up» описываем действия до поднятия интерфейса: указать название APN, немного подождать, запустить пакетный драйвер QMI (или как он там правильно называется). То есть софтинку, которая разбирает-собирает поток данных и контрольный канал. С этого момента всё должно заработать. Если не взлетит, то вдумчиво раскуривать мануалы по модему, искать там диагностические AT-команды и пытаться разобраться что же пошло не так. После опускания интерфейса останавливаем QMI-драйвер.
Вроде бы на этом можно и успокоиться. Но я же ж извращенец, мне этого мало. Я хочу не просто подключить модем к серваку, а стать владычицей морскою «закинуть» его вовнутрь QEMU/KVM-виртуалки. В принципе, можно потанцевать с бубном и попробовать сделать это «прям щас». Но мой модем помимо режима QMI умеет ещё Direct IP, при котором не надо запускать никакого QMI-драйвера. Поэтому я пошёл дальше.
Сперва попросил уважаемого rustedowl разобраться как именно переключить модем в другой режим. Сложность там в том, что у данного устройства есть два разных набора AT-команд. Один лоховский универсальный, который является стандартным для любых UMTS-устройств. А второй — пацанский расширенный, для того чтобы можно было трогать модем за яйца крутить всякие хитрые инженерные параметры. Спустя какое-то время поспели вот такие заклинания:
Где набор символов «A710» является… паролем. Дабы всякие ничтоже сумнящиеся не совали свои шаловливые ручки куда не просят. И что сцуко характерно, энтот пароль в официальной документации к хитропопому прибору напрочь отсутствует. Он был найден на бескрайних просторах интернета и подходит к большинству модемов от данного производителя (Sierra Wireless). Параметр второй команды — собственно режим. «68A2» — это QMI, «68A3» — Direct IP. Данные значения актуальны только для данной модели (MC7710). Но в любом случае будет очень кстати лишний раз свериться с документацией чтобы не напортачить, поскольку операция смены PID является весьма щекотливой и может привести к самым разным последствиям. Третья команда перезагружает мопед.
После перезагрузки супостат перекрашивается яки киллер из GTA2. Он теперь в lsusb виден как «Bus 004 Device 003: ID 1199:68a3 Sierra Wireless, Inc. MC8700 Modem». Обратите внимание, что поменялся ID оборудования и даже название модели. Раньше он представлялся как MC7710, а теперь внезапно стал MC8700. И драйвер теперь к нему подключился другой:
Также увеличилось количество псевдотерминалов ажно до пяти штук. И несколько изменился набор допустимых AT-команд.
Дальше всё «как обычно». Находим среди этой пачки «телетайпов» контрольный канал, фиксируем его udev-ом. Точно так же, как и в предыдущем случае, указываем точку доступа («AT CGDCONT=1,»IP»,»yota.ru»»). А вот процесс «дозвона» намного проще: «at!scact=1,1». Где последняя циферка является номером профиля, указанного в «CGDCONT». То есть, внутри модема можно создать несколько разных профилей с разными точками доступа и переключаться между ними. Теоретически это может пригодиться если нужно время от времени использовать то «честный» IP от оператора, то «серый», которые раздаются разными APN. Практически я не знаю случаев, когда такое может реально понадобиться.
Проверить, что «всё хорошо» можно командой «at!scpaddr=1», где цифра означает номер пресловутого «профиля». В ответ модем должен откликнуться полученным от оператора IP-адресом.
Но самой главной «плюшкой» режима Direct IP является то, что конкретно Sierr-овские модемы можно настроить на «автодозвон». Для этого нужно установить профиль по умолчанию: «at!scdftprof=1» и включить автодозвон в этом профиле: «at!scprof=1,»»,1,0,0,0«. Теперь после перезагрузки сервера либо отключения-включения питания модема он будет устанавливать линк автоматически. Аллилуйя!
IP-шник на системный интерфейс прилетает как обычно, по DHCP. Однако wwan0 — это всё-таки не ethernet. Попытки объединить его в bridge с другими системными интерфейсами («brctl addif br0 wwan0«) не увенчались успехом. Для того, чтобы получить беспроводной LTE-линк с честным IP-адресом внутри виртуальной машины, пришлось ещё немного поизгаляться. Как — напишу в третьей части, если когда-нибудь дойдут руки.
Какой вывод можно сделать из вышеописанных половых сношений с модемом умозаключений? Sierra Wireless делает вполне годные железки, которые довольно неплохо поддерживаются Linux-ом. Даже таким консервативным, как Debian. Собратьям по несчастью разуму могу порекомендовать брать устройства, которые понимает драйвер «sierra_net», ибо при прочих равных секса с ними будет меньше. К сожалению, таковых не так уж и много. Пока что их можно пересчитать по пальцам одной руки. Если кто будет выбирать, вот вам их VID-PID: «0f3d:68a3», «0f3d:68aa», «1199:68a3», «1199:68aa». Однако имейте в виду, что VID-PID также зависит и от режима работы и может изменяться в результате переключения последнего.
I can confirm the behavior of @katsuya-horiuchi – after suspend, the modems disappear completely.
However, I somehow managed to get everything up and working. After all, we hadn’t had much to do to getting it work properly – at least in terms of system configuration 😉
Regarding the modem initialization:
@katsuya-horiuchi This behavior is related to systemd and the point its rclocal helper unit will be initialized. It seems to be working most of the time, but sometimes needs to be done manually (or, better, writing your own systemd unit for initialization, which isn’t a backwards-backwards-compatibility thing like rclocal).
More information: https://unix.stackexchange.com/a/471871
I think I’ll be getting my surface back on Thursday. I’ll provide some further information then.
@Trinity93
Ah, as mentioned above – its working in my setup now. The ModemManager is doing some magic in the background. When I’m remembering correctly, we didn’t configure much. Basically:
Most importantly – do not enable AGPS!. This silly chip seems to hang itself up when you’re trying to use AGPS, seemingly a problem with the MS firmware you mentioned above.
And then…wait. Grab a coffee or something….a cold reset tooks quite a long time.
After that, the location service in the ModemManager seems to be working properly, and we’ll be able to retrieve the RAW gps information and NMEA data from it, using the ModemManager API or the respective Qt bindings…