Redoing D-Link DIR-320 to 3G Router

I am more than sure that many have already seen such headlines more than once. But every time you read them, it turns out that you need to buy some of the most proven modems in the world, and besides, luck should be favorable to you. But the most common problem is that there is no modem that does not hang after a certain time. The longest interval I've seen is 8 (eight) hours. As a result, many refuse such an idea and give up, and if there is no router, they adapt an old PC for these purposes, and even install Windows (usually XP, or whatever comes to hand).
Since the PC and even more so Windows, for me it’s not an option and I didn’t have the “modem” on hand, I had to look for a solution.
If you are interested in continuing, I ask for a "cut."

Introduction


As, probably, it became clear to many from the introduction, I was faced with the task of making a small and very stable 3G router.
What was required for this:
  • Router DIR-320 (was available)
  • 3G modem
  • External antenna

Research and goal setting


So, before doing anything myself, I started by analyzing numerous forums and communities. At each forum there were branches with a description of the very miracle of modems and an endless series of related problems. Some were mega stable, but at an unacceptably low speed, others pleased with their performance, but after 30 minutes they “hung up” tightly. All this is very upsetting.

Before going to the “bunker of the motherland” for an old PC, I decided to analyze the facts and independently investigate the problem.

For the initial experiments, I decided to use a stationary PC with Linux. Having set up a 3G connection, using the available Huawei E173, he launched a call to the ping + wget command with an interval of once every 10 minutes. The connection lasted about 4 (four) hours, after which the modem stopped responding to PPP commands, while AT worked. I conducted the same experiment with AnyDATA ADU-500A (this is a modem from the list of "those"). Oddly enough, it all ended the same, only after 5 hours.
Any attempts to revive did not bring the long-awaited result, only a complete blackout saved the situation.
Once again, I decided to restart the modem and it dawned on me, and why not just put out the USB port. No sooner said than done:
  1. We find the modem from the list of all USB devices:
    for f in `ls /sys/bus/usb/devices/*/product`; do echo -e "$f\t`cat $f`"; done
    

  2. Turn off the port for 5 seconds and then turn on:
    echo “suspend” | sudo tee /sys/bus/usb/devices/1-1/power/level
    sleep 5
    echo "on" | sudo tee /sys/bus/usb/devices/1-1/power/level
    


The experiment showed that everything restarts perfectly. And the connection can be established again. From that moment it became very clear what to do.

Having taken four firmware for the router: D-Link, Asus, OpenWRT or DD-WRT, I began to repeat the experiment, but here's a bad luck, surprisingly, none of the firmware was able to control USB power. At first, I thought it was a 2.4.x kernel problem. But the same problem with 2.6. Moreover, after rebooting the router, the modem remained initialized. The conclusion suggests itself, you need to disassemble the router.
A close inspection and the “ringing” of the board showed that the + 5V power leg is connected directly to the power source. This does not suit me and I need to upgrade the board and power supply.

The time has come to choose a distribution. This wonderful router has very little RAM and did not want unnecessary services to consume it, be it httpd, FTP, SAMBA or anything else. It was decided to build the distribution based on OpenWRT on their own, with a minimum of pre-installed packages and services.

But before proceeding with the assembly of the distribution kit and the modernization of the router, the task was to select the target modem / operator and external antenna.

Having looked at the coverage map of different operators, I came to the conclusion that MTS is the most suitable. In addition to the coverage map, I really liked the fact that they can perform all statistics and management from a fairly convenient WEB interface. Having bought their best modem, with the promised maximum of 14.7 Mbit / s and a minimum of 3 Mbit / s, he began his adventure.
Perhaps someone will be interested:

After the purchase, I started trying to connect to this modem. And as always a number of questions arose:
  1. It is persistently displayed as a CD-ROM.
  2. Not a word on the Internet about this modem, the maximum that this mention of the previous model was found (WM-D200)

The analysis of dmesg showed that the CD-ROM is mounted as SCSI, this suggested that it should be disabled just like SCSI, no usb_modeswitch works here, and in fact is not needed.
Of course, my software was immediately written that did this. But the persistent thought that this was already written by someone and most likely it already exists in the ports / portage or somewhere else, made me search. The very first pass through the folder with man'ami showed that there is a wonderful sdparm package. Having installed and checked, it became clear - this is what you need.
Since now everything has fallen into place and there are no more questions left, you can get to work.

Build openwrt


All steps are performed in the Linux console. Please note that the Backfire release is chosen because it is the latest release with the 2.4 kernel. This is very important, since the 2.6 kernel itself is very demanding both on processor performance and system resources.
  • Download the OpenWRT source:
    svn co svn://svn.openwrt.org/openwrt/branches/backfire openwrt-backfire
    
  • Go to the source folder
    cd openwrt-backfire
    
  • We update all packages
    ./scripts/feeds update -a
    
  • Add from sdparm packages
    ./scripts/feeds install sdparm
    
  • Open the setup menu
    make menuconfig
    
  • Choose the platform of interest
    Target System (Broadcom BCM947xx/953xx [2.4])
    
  • We embed packages of interest to us (by default they are not included even as modules)
    <*> sdparm........................ Read or modify SCSI or USB disk parameters
    <*> chat................................. Establish conversation with a modem
    <*> comgt............................... Option/Vodafone 3G/GPRS control tool
    <*> kmod-scsi-generic........................ Kernel support for SCSI generic
    <*> kmod-usb-core............................................ Support for USB
    <*> kmod-usb-ohci............................... Support for OHCI controllers
    <*> kmod-usb-serial..................... Support for USB-to-Serial converters
    <*> kmod-usb-storage..................................... USB Storage support
    <*> kmod-usb2................................... Support for USB2 controllers
    
  • All other items are left unchanged.
  • Exit the configurator menu with saving
  • We collect tools
    make tools/install -j`grep -c processor /proc/cpuinfo`
    make toolchain/install -j`grep -c processor /proc/cpuinfo`
    
  • Open the Linux kernel configuration menu
    make kernel_menuconfig
    
  • Customize MTD
    [*]     Support 2-chip flash interleave
    
  • Exit the configurator menu with saving
  • Build OpenWRT
    make -j`grep -c processor /proc/cpuinfo`
    
  • After the firmware is assembled, it must be flashed into the device. There are tons of instructions on this subject ( for example, on the DD-WRT website )

Firmware check


After the firmware has been “flooded” and the router has rebooted, connect a modem to it and connect the router via Ethernet to your PC. Configure the IP address on the interface (in my case eth0) of your PC by running the command:
ifconfig eth0 inet 192.168.1.2/24

Next, connect to the router via Telnet. To do this, run the following command from the console:
telnet -l root 192.168.1.1

Login will be done automatically without asking for a password. This is fundamentally wrong. To correct the situation, set the password by running the command in the console:
passwd

Run the exit command to exit the telnet session.
Log in via ssh :
ssh root@192.168.1.1

The next step is to make sure that the modem has been recognized by the kernel by running the command in the console:
grep "^P\:.*22de.*6803" /proc/bus/usb/devices

The result of this command is a string with the VID and PID of the modem. Otherwise, check that it was not done according to the instructions.

Router hardware upgrade


To control the power of the USB port, you need a free processor leg. But since this is not an engineering board, but the final product, this option is not suitable. Luckily, this router has a ton of LED indicators on the front panel. One of them we can quite adapt to our needs. In my case, the choice fell on the indicator with the printer icon, since it corresponded to the USB LED on proc-fs (/ proc / diag / led / usb).

Power management will be carried out by an additional board with the minimum necessary set of parts. Here is her diagram:

A few words about the scheme. Both transistors work as keys. When a logical unit is applied to the CTRL input, the transistor VT1 opens, which in turn will lead to the opening of the transistor VT2 and the supply voltage will be supplied to the USB port. As such, no calculations were made, therefore, the scheme cannot be considered optimal. For example, the transistor VT1, was simply the only NPN transistor in the reach field, in fact, like the resistors.

There was no time or desire to make a printed circuit board, so I spent a small piece of the circuit board on it. This is what the final version looks like:

Green labels indicate ports of the same name on the circuit. Resistor R4, soldered directly to the leg of the LED.

Step-by-step modification instructions:
  • Disconnect the router and disassemble it.
  • Remove the unnecessary R48 - this resistor connects the LED to the processor leg

  • Remove fuse F1 - this fuse should provide protection in the event of a short circuit on the USB power lines. I do not know its face value, but I applied it in my scheme (R3). Please note that yellow inscriptions indicate the connection points of the control board

  • Remove the protective coating from the conductor driving the signal from the processor to the R48 resistor. To this conductor, the CTRL port of the control board must be soldered

  • Glue the control board in the most convenient place for you. It turned out that I liked the free area, just below the antenna socket. In this case, the length of the connecting wires will be the smallest

  • Solder the resistor R4 directly to the anode of the LED, as indicated in the photo. Also pay attention to the connection of the connecting wires

  • Complete the installation of the connecting wires

  • Final result

  • Build and turn on the router

Router software upgrade


This is the last step towards "happiness." We will need to write a number of new scripts and make changes to existing ones. So, all in a row.
Connect to the router via ssh, as all of the following steps will be performed directly on it.

Creating Utilities for USB Control

Go to the / etc / ppp folder. Many will be interested in why this folder was chosen as the target. The answer is simple, so historically. I think / usr / local / sbin will be more appropriate, but this does not change the essence
cd /etc/ppp

  • Create usb-up.sh. This script will include power on the USB port.
    $ cat usb-up.sh
    #!/bin/sh
    logger -t "USB PwrCtrl" "Turn-on USB power"
    echo 1 > /proc/diag/led/usb
    
  • Create a script to reboot the USB port
    $ cat resetusb.sh
    #!/bin/sh
    logger -t "USB PwrCtrl" "Turn-off USB power"
    echo 0 > /proc/diag/led/usb
    # Sleep in 3 sec is an optional, but may be useful for some modem types
    #sleep 3
    logger -t "USB PwrCtrl" "Turn-on USB power"
    echo 1 > /proc/diag/led/usb
    
  • Create a script to verify the existence of the pppd process
    #!/bin/sh
    if ps | grep -q /usr/sbin/pppd; then
        logger -t "PPP watcher" "PPP alive"
    else
         logger -t "PPP watcher" "No PPP daemon"
         /etc/ppp/resetusb.sh
    fi
    
  • Make scripts executable
    chmod  a+x /etc/ppp/*.sh
    
  • Добавим корректную обработку подключения модема к USB. Обратите внимание на то, что в OpenWRT, по умолчанию, нет udev, а вместо этого используется hotplug «демон»
    $ cat /etc/hotplug.d/usb/11-modem
    #!/bin/sh
    # Copyright (C) 2013 Sergey Shcherbakov 
    case "$ACTION" in
            add)
                    (grep -q "^P\:.*22de.*6803" /proc/bus/usb/devices) && {
                            logger -t "WM-D300" "Detected ZeroCD of WM-D300 modem"
                            # Checking ZeroCD status
                            while [ "$(sdparm -q --command=ready /dev/scsi/host0/bus0/target0/lun0/generic)" != "Ready" ]; do
                                    logger -t "WM-D300" "ZeroCD yet not ready"
                                    # Workaround for bug with multiple calls of scripts
                                    (/usr/bin/lsusb | grep -q 22de:6801) && {
                                            logger -t "WM-D300" "Seems that script called twice and device already initialized"
                                            return 0
                                    }
                                    sleep 2
                            done
                            logger -t "WM-D300" "ZeroCD ready and will be ejected"
                            /usr/bin/sdparm --command=eject /dev/scsi/host0/bus0/target0/lun0/generic
                    }
                    (grep -q "^P\:.*22de.*6801" /proc/bus/usb/devices) && [ ! -c /dev/usb/tts/0 ] && {
                            logger -t "WM-D300" "Updating USB Serial driver with D200/D300 vendor and product ID"
                            rmmod usbserial && insmod usbserial vendor=0x22de product=0x6801
                    }
                    (grep -q "^P\:.*22de.*6801" /proc/bus/usb/devices) && [ -c /dev/usb/tts/2 ] && ! (ifconfig 3g-wan 1>/dev/null 2>/dev/null) && {
                            logger -t "WM-D300" "All modem interfaces installed, turning on WAN"
                            ifdown wan && ifup wan
                    }
                    ;;
            remove) 
                    ! (grep -q "^P\:.*22de.*6801" /proc/bus/usb/devices) && {
                            logger -t "WM-D300" "Modem disconnected, turning off WAN interface"
                            ifdown wan
                    }
                    ;;
    esac
    

Внесение изменений в существующие скрипты

  • Запретите WAN интерфейс, заданный по умолчанию, выполнив команду
    sed -i 's/interface\ wan$/interface\ wan_dflt/' /etc/config/network
    
  • Добавьте новый описатель WAN интерфейса с настройками для 3G
    $ cat /etc/config/network
    …
    config interface wan
        option ifname  ppp0
        option device  /dev/usb/tts/0
        option service evdo
        option proto  3g
        option username 'mobile'
        option password 'internet'
        option pppd_options 'noipdefault maxfail 3'
        option connect '/etc/ppp/usb-up.sh'
        option disconnect '/etc/ppp/resetusb.sh'
        option keepalive 20
    
  • Для того чтобы добавить автоматическое включение USB порта при инициализации роутера, нужно модифицировать стандартный скрипт /etc/init.d/usb, добавив в конце функции start() вызов скрипта /etc/ppp/usb-up.sh
    $ cat /etc/init.d/usb
    …
    start() {
        ...
        # Turn-on power on USB     
        /etc/ppp/usb-up.sh 
    }
    …
    
  • Дополнительно можно модифицировать, но необязательно, Chat скрипт (/etc/chatscripts/evdo.chat). На самом деле, он должен работать даже без изменений, но я предпочел немного его «причесать». Вот мой вариант:
    ABORT   BUSY
    ABORT   'NO CARRIER'
    ABORT   ERROR
    ABORT   'NO DIAL TONE'
    ABORT   'NO DIALTONE'
    ABORT   'NO ANSWER'
    REPORT  CONNECT
    TIMEOUT 10
    ''              AT
    OK              ATDT#777
    CONNECT ''
    
  • Add a task to Cron that will check for the pppd process every five minutes. To do this, call the crontab -e command and add the following line:
    */5     *       *       *       *               /etc/ppp/check.sh
    
  • Allow Cron to Run and Run It
    /etc/init.d/cron enable && /etc/init.d/cron start
    
  • I won’t give WiFi settings, since it’s standard enough and is well described on the official OpenWRT website

That's all, there will be no more changes. I recommend rebooting the router, although 3G should "come to life" in five minutes anyway.

Instead of an epilogue


Home trials lasted 41 days. As a result, not a single failure throughout the period. Expected stability achieved.
Before sending to the "fields", bandwidth tests were conducted in a Kiev apartment. The disappointment was taken by surprise, the maximum reached did not exceed 1 Mbit / s, while only on large files. The minimum ping was within 220ms. Deciding not to stop testing, he went out of town. The level was at maximum, while the CDMA Rev.B indicator was no longer on. Actually, I did not hold out hopes for 14 Mbps, but expected to see, at least, already reached 1 Mbps. But another disappointment was not long in coming, the maximum reached was already about 350 Kbps.
At this, all kinds of experiments with the modem from MTS were stopped. It was not possible to return it. But the seller traded the antenna for a model that can work in conjunction with Intertelecom and PeopleNET modems. What I was incredibly happy, and let the modem be in the collection, someday it will come in handy.

Also popular now: