Openwrt отключение питания usb
Automount the partition
Automount ensures that the external disk partition is automatically made available for usage when booting the OpenWrt device
to see something like this
Note the “target” entry. This is the file path, where your attached USB storage drive can be accessed from now on. E.g. you can now list files from your external disk:
The result will be:
Using Atheros' 00-button + UCI
button is the name as the button, action is the event (two values: pressed and released ), handler contains the command line to be run when the event is detected (can be a script as well).
You may need to reboot the router the make the change effective (mine would work with the simple shell script just fine but wouldn't budge when using the 00-button script — Frex 2011/03/25 22:29). If this works, you can change the handler to something more useful, and add more button handlers.
cmdpad
Another simpler application to manage buttons.
Install and verify USB drivers
This step ensures that required USB storage drivers are properly installed.
The typical OpenWrt package already has core USB device drivers installed (if your device has USB ports at all), but might not yet have an USB storage device driver installed. Install this storage driver first (if it is already installed, the following command will just say “is already installed”:
“Bus…”-Lines represent the host chip. Here, the “Driver” will be xhci for USB3.0, ehci for USB2.0 and uhci or ohci for USB1.1.
Lines with “Class=Mass Storage” represent connected USB devices. Here the “Driver” is either usb-storage for storage of type Bulk only Transport or usb-storage-uas for storage of type USB_Attached_SCSI
In step 5, verify that the output prints no error and has at least one output line for root_hub and Mass Storage and that each Driver= lists a driver name. If not, then refer to the Installing USB Drivers for more suggestions on drivers.
Продвинутый рестарт (smart reboot) 3G\4G модема Huawei E3372 в режиме Hilink через роутер с прошивкой OpenWrt
OpenWrt — встроенная операционная система, основанная на ядре Linux, и предназначенная, в первую очередь, для домашних маршрутизаторов. Основные компоненты включают в себя ядро Linux, util-linux, uClibc или musl и BusyBox. Размер всех компонентов оптимизирован в связи с тем, что в большинстве домашних маршрутизаторов сильно ограничен объём памяти.
Optional: Idle spindown timeout on disks for NAS usage
Optional step for hard disks.
If you want to use OpenWrt as a permanent NAS, you might want to spin down the harddisk motor during times of inactivity. Either because you want to have it quiet in your room during nighttime or to increase lifetime of the harddisk (e.g. when using a home-edition harddisk (instead of a 24×7-datacenter edition).
There are different options, to automatically spin down the motor of the attached harddisk after a certain time of inactivity. Both require installing optional packages on OpenWrt.
1. Option: hdparm
This tool permanently saves a spindown timer on the harddisk itself, using standardized SATA disk commands (the harddisk will then remember that spindown-timer value, even if turned off, even after a restart and even if attached to a different device). Its actually just a command line interface for a built-in harddisk function. So no OpenWrt service has to be run in the background for this and 'hdparm' could even be uninstalled after setting this parameter. Unfortunately many older USB2.0-PATA/SATA-adapters do not support the required SATA command, although even decade-old harddisks do support it. But fortunately most USB3.0-SATA-cases seem to support the required SATA command. To install the package
E.g. to set a reasonable idle timeout of 20 minutes on the harddisk, use:
if the command failed with an error message, your USB-SATA-casing sadly does not support it and you won't be able to use 'hdparm' for disk spindown as long as you use this USB-casing.
Of course you can always change the timeout or disable auto-spindown again later on. Depending on your harddisk, the value may be active until the next reset or permanently stored on the harddisk. The harddisk firmware itself manages the spindown timeout, not a OpenWrt service. For persistent changes use /etc/rc.local file, like:
2. Option: hd-idle (With LuCi integration)
This is a service than runs in the background of the OpenWrt device and maintains its own idletimeout counter. Once the defined timeout counter reaches 0, it will send a “live” spindow SATA command to the disk. Unlike the permanent spindown command from hdparm, a lot more USB2.0-SATA cases seem to support this “spindown-now” SATA command.
To install the package that even has LuCi frontend integration:
To configure it, use the “Services” menu of the LuCi web GUI of your device.
To install the CLI package (without LuCi):
To configure it, you can edit the /etc/config/hd-idle file and then autostart and run the hd-idle service service hd-idle enable && service hd-idle start .
Name | Type | Default | Description |
---|---|---|---|
disk | string | sda | Replace sda with your device's identifier |
enabled | boolean | 0 | Enable hd-idle operation |
idle_time_unit | string | minutes | The unit of time used in the idle_time_interval option |
idle_time_interval | integer | 10 | How much idle time before spindown |
Notice that you have to enable it since it isn't by default.
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
Какой командой включать отключать питание USB порта TP-LINK tl-mr3020?Подскажите пожалуйста. Роутер работает под OpenWrt.
Выключить питание определённого USB порта на ПК
Добрый день ребятки, такой вопрос к профи, кто знает как можно выключить питание на USB порту ПК.
Как в консоли отключить питание от usb порта?
Подскажите как можно отключить подачу питания от опредёлённого порта usb в mint 14. Жлателен.
Как программно отключать и включать Bluetooth?
как программно отключать и включать BlueThooth??
Как отключать и включать JPopupMenu целиком?
Не получается отключать JPopupMenu методами setVisible() и setEnabled(). Отдельные JMenuItem без.
IlyaCool, номер порта от 1 до N. Определять методом тыка, ибо даже если порт в устройстве один, это не значит, что на корневом хабе он первый и единственный.
IlyaCool, мда, как-то не по-людски на вашем роутере драйвера USB написаны. Это все файлы, или есть среди них и каталоги?
IlyaCool, я понял, но не знаю что предложить. Нестандартно там все, а может и нет возможности обесточивать порт, это же еще и от схемотехники железки зависит, не только от софта.
Доброго времени суток.
Если ещё актуально, то
Отключить: echo 0 > /sys/devices/virtual/gpio/gpio8/value
Включить: echo 1 > /sys/devices/virtual/gpio/gpio8/value
Responsivevoice как отключать и включать звук?
Responsivevoice как отключать и включать звук? подскажите кто знает пожалуйста
TP-Link TL-MR3020
Добрый день . Проблема заключается в следующем : на тп линк 3020 прописана статическая адресация .
TP-Link TL-MR3020
Ребят, живу в сельской местности, поэтому пользуюсь 3G-модемом. Думаю приобрести TP-Link TL-MR3020.
Приходится отключать и включать сетевую карту, чтобы заработал инет
Добрый день. Такая проблема - роутер настроен (d-link 300), подключен по lan к настольному пк.
Имеется роутер TP-Link WR842ND.
И имеется три интернета: ADSL через Ethernet и пара 4G-модемов.
Предисловие.
Разумеется, эти интернеты бывают нужны по очереди.
Отключаем один, подключаем другой.
Настройки приоритетов подключения не предусмотрены, однако
в руководстве сказано буквально следующее:
1. Если Вы уже установили подключение WAN, маршрутизатор не будет подключаться к 3G/4G сети до тех пор, пока Вы не нажмёте Connect (Подключить) в меню Настройки USB-3G/4G или не отключите кабель от порта WAN.
2. Если у Вас отсутствует подключение WAN, маршрутизатор будет автоматически устанавливать 3G/4G-подключение, пока Вы не подключите кабель поставщика интернет-услуг к порту WAN.
То есть, подрубили WAN - отключилось 3G/4G, отрубили WAN - подключилось 3G/4G. Замечательно.
На практике происходит так: отрубаем WAN - подхватывается 3G/4G, подрубаем WAN - ничего не происходит, даже если к этому моменту модем уже отсоединён от разъема.
Возможно, это из-за того, что модемы в Hilink, то есть притворяются сетевыми картами.
В общем, нужно либо передёргивать роутер по питанию, либо лезть в интерфейс, нажимать на кнопку.
Суть проблемы.
Для более удобного руления этими своими интернетами с надеждой на автоматизацию решил попробовать OpenWrt.
Прошил. Настроил. Всё красиво. Втыкаю модем - тишина. Погуглил, выяснил, каких пакетов недостаёт (кстати, в этом вопросе единогласия нет, советуют разные наборы пакетов), доустановил, модем определился как сетевой интерфейс, всё замечательно.
И тут вылезает проблема: модем, висящий на окне и подключенный к роутеру через кабель, отваливается несколько раз в минуту. Отваливается физически: устройство есть - устройства нет, устройство есть - устройства нет.
В логах: новое устройство - дисконнект, новое устройство - дисконнект и так примерно каждые 10-15 секунд.
Если подключить без кабеля - всё хорошо. Очевидно, проблемы по питанию.
Теперь самое интересное: на родной прошивке нет такого эффекта.
Специально перешил обратно родную прошивку - проверить (поэтому логи openwrt показать не смогу, по крайней мере, пока).
Модем всё также висит на окне, подключенный к роутеру через кабель. Кабель тот же и модем тот же. И даже роутер тот же
И сессия без перерыва вот уже 2 часа 40 минут.
Отсюда вопрос: ОС каким-либо образом рулит мощностью USB-порта?
Если рулит, можно ли где-то это подкрутить? Если не рулит, то какого чёрта с портом происходит?
Почему на одной прошивке вытягивает, на другой - нет?
И вообще, у кого есть гениальные (и не совсем) идеи по поводу происходящего?
Examples
Example 1: Toggle Wi-Fi radio with a button press
Example 2: Assign two different functions to the same button: short press VS long press. This relies on tracking the released event rather than the pressed event.
Example 3: Unmount USB storage using a long-ish press
Example 4: Restore defaults
Example 5: Toggle Wi-Fi using a script
Another option for wifionoff is this script (doesn't store the state in uci, so it remains what is set in the configuration) You can also call this script e.g. from cron, to switch off your wifi at night.
Example 5-bis: Toggle only a Wireless Network using a script without disabling the entire Wi-Fi module
This solution is heavily based on example 5. You need to figure out the name of your Wi-Fi Network configuration to make it work and replace the 3 occurrences of “default_radio0” in the script by the name of your wireless network configuration (eg. “cfg033579”). “default_radio0” is the configuration name of the initial default wireless network that existed “out of the box” (on the DIR-610-a1 at least).
One way to find out your Wireless Network configuration name in LuCi is to navigate to the “Wireless Overview” page (Network > Wireless) and edit the wireless network configuration you need to toggle. For example, change temporarily the ESSID value and then click “SAVE” (and NOT “SAVE & APPLY”). You will then see the button “UNSAVED CHANGES” in the upper right corner of the interface. Click on it and you should be able to find an entry such as “uci set wireless.cfg033579.ssid='My-Own-Wi-Fi-test'” where “cfg033579” stands for your configuration name that you need to change in the following script.
Example 6: Set transmission-daemon alt-speed, enable or disable.Short press will activate alt-speed or longer press will deactivate alt-speed and also turns on qss led about speed status on tl-wr1043nd
Edit your alt-speed limits from transmission-daemon , settings.json file.To execute script, you need to install transmission-remote package from opkg.
Verify that the OS recognizes the attached disk and partitions
This optional verification step can be used, to check that the OS can properly detect a connected external drive.
This should print at least a connected disk like “/dev/sda” or “/dev/sdb”. If no disk at all is listed, recheck USB driver installation and reboot your OpenWrt device once.
for exFAT you also need libblkid
and you should see output like this, if your disk already has partitions:
If a disk already has existing partitions, they get listed as /dev/sda1, /dev/sda2 ,/dev/sda3 and so on.
If we had connected more than one storage device we would have also a /dev/sdb1 (first partition of second device), /dev/sdc1 (first partition of third device) and so on.
Продвинутый рестарт (smart reboot) 3G\4G модема Huawei E3372 в режиме Hilink через роутер с прошивкой OpenWrt
30 авг 2019, 18:46
Об этой эпопее читайте Есть ли жизнь без Ростелекома? Есть! Прощай, Ростелеком! А сейчас расскажу как подключить 3G\4G модем в режиме Hilink к роутеру с OS OpenWrt и настроить бесперебойный доступ в интернет.
Имеется модем, разблокированный под любого оператора Huawei E3372h-153. Модем работает в режиме Hilink (определяется как сетевая карта).
Была задача подключить его к роутеру и раздавать интернет всем устройствам, подключенных к маршрутизатору. Модель роутера не имеет значения. Лишь бы был хотя бы 1 USB порт и прошивка OpenWrt. Ну и нужен доступ в интернет для скачивания необходимых пакетов. Раньше я поднимал точку доступа на смартфоне, а на роутере поднимал Wi-Fi клиента, теперь пользуюсь скриптом для создания локального репозитория пакетов для OpenWRT [WINDOWS].
Заходим по ssh (через Putty, например) в систему роутера и устанавливаем необходимые пакеты. Можно то же самое проделать через web-интерфейс.
Предварительно нужно отключить NAT в модеме. Для этого подключаем модем к компьютеру, заходим в веб-интерфейс по адресу Для просмотра ссылок Вы должны быть авторизованы на форуме. и настраиваем как на картинке:
Подключаем модем к роутеру.
Дожидаемся перезагрузки роутера и заходим в веб-морду. Нам нужно создать новый интерфейс.
Сеть --> Интерфейсы --> Добавить новый интерфейс.
- Назначаем имя интерфейсу. Имя произвольное.
- Назначаем протокол. DHCP-клиент. Модем сам выдаст роутеру IP-адрес.
- Выбираем наш модем как сетевое устройство, которое определилось в роутере. В моём случае это eth1. У меня уже создан интерфейс с именем МТС, который привязан к eth1, так что не обращайте на это внимания.
- Применяем.
- Далее нам нужно перейти на вкладку "Настройки межсетевого экрана".
- Выбрать зону wan. Она всегда красным цветом.
- Кликнуть на кнопку "Сохранить и применить"
Всё, уже можно пользоваться. Некоторое время. До первого недоумения: "КУДА ДЕЛСЯ ИНТЕРНЕТ. "
Не знаю как обстоят дела у других владельцев 3\4G модемов, но у меня иногда "отваливается интернет". Захожу в веб-морду модема, а там всё ОК. Линк есть, даже трафик бежит. Жидкий, но он есть, а интернета НЕТ.
В 99% помогает простое отключение и включение соединения. В редких случаях нужно перезагружать модем. Но проще передёрнуть модем в USB.
У меня роутер висит на стене, как раз за монитором. Каждый раз заходить в веб-морду модема (вставать и лезть за монитор) как-то лениво. Да и "толстые" торренты качаю иногда.
Что-то надо придумать для автоматического "передёргивания модема".
Что первое пришло в голову - пакет watchcat OpenWrt.
Но там, если "отвалился" интернет тупо перезагружается роутер. А это долго.
По крайней мере мой гигабитный TP-Link TD-W8970 v1.2 перезагружается довольно нерасторопно.
Приходила мысль перешить модем в Stick (классический USB-модем) и рулить им через AT-команды .
Покопал инфу в интернете и пришёл к выводу: встать и передёрнуть модем в роутере - быстрее и проще, чем прошить модем, а потом организовать автоматику через AT-команды.
Решение нашлось. У Huawei-ев в режиме Hilink есть API. Например, если в браузере перейти по ссылке Для просмотра ссылок Вы должны быть авторизованы на форуме. на экране появится ряд чисел
Потратив изрядное количество времени в поиске информации, всё-таки нашёл объяснение такого поведения API модема. Всё дело в безопасности. Чтобы не было несанкционированного доступа к API модема. То есть для нормального ответа API модема нам нужно как-то легализовать свои запросы.
Пишем команду в консоли роутера:
Чтобы API модема нормально принимала команды, нужно предварительно и перед каждой командой запрашивать данные сессии и внедрять содержимое тегов и в тело запросов.
Путём метода "научного тыка", несчётного количества проб и ошибок я написал небольшой скрипт, который позволяет управлять модемом через API.
Пока только пинг гугловского DNS и три варианта реакции на отсутствие ответа.
1. Отключение и включение линка в модеме.
2. Если не помогло - перезагрузка модема.
3. Если и это не помогло - перезагрузка роутера.
Алгоритм пока сырой. Но пользоваться уже можно.
Итак. Чтобы использовать данный скрипт, нам нужно настроить cron и создать расписание, по которому он будет запускаться.
Теперь нам нужно разместить скрипт в файловой системе роутера и создать расписание запуска сценария.
В OpenWrt по-умолчанию в целях экономии размера прошивки нет продвинутого текстового редактора. Только vi с минимальным функционалом. Так что будет проще и быстрее залить готовый файл скрипта в роутер любым удобным способом. Например, WinSCP из-под Windows
Удобнее всего размещать скрипты в каталоге /etc
После копирования файла в файловую систему роутера, нам нужно установить атрибуты скрипта на исполнение. Можно сделать тем же WinSCP.
Осталось написать и запустить задание для cron. Быстрее всего это можно сделать через консоль (Скрипт будет запускаться каждую минуту - значение "*/1").
На этом всё. Удачи!
P.S. Как я уже упоминал, скрипт написан "на коленке". Есть что оптимизировать и дополнить. Например, добавить мигание индикаторами при обрыве линка. В скрипте эти строки есть, но закомментированы. Если хотите сделать себе индикацию, пишите, указав версию прошивки и модель роутера.
There several ways for controlling buttons in OpenWrt.
Hotplug buttons, using the hotplug daemon or procd in compatibility mode (hotplug itself was phased out with r36003, circa 2013).
Kernel configuration If a target platform is known to support buttons, appropriate kernel modules are selected by default. If a platform is not known to support buttons, you are required to install various kernel modules yourself such as diag , input-gpio-buttons , gpio-button-hotplug , and others. However, installing various modules will not necessarily yield a successful result. |
Sliding switches
Some routers, for example the TP-Link TL-MR3020, have a sliding switch with three positions. These are usually implemented using two GPIOs, meaning OpenWrt interprets a switch like this as two separate push buttons.
The slide-switch package (in the packages repo) monitors these push buttons and translates the button states into switch position presses and releases. Buttons scripts, in either procd or hotplug format, can be written for switch positions directly. See the package's GitHub page for more details.
- Last modified: 2022/04/27 11:55
- by some1
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
Tip: The Quick Start for installing a USB drive solves the very common case of installing a single USB drive onto your OpenWrt device. People do this to use Samba or other programs that need to store data on an external drive. The remainder of this page provides much more information about USB devices and drivers.
Many supported devices have ports to connect storage devices, most common are USB, or Sata.
This article will describe how to configure your device to use such storage devices for storage or for sharing. If you want to expand your firmware's space (to install more packages) please read the article about Extroot configuration.
To configure external disk space, follow the procedures of this page:
Create a partition on the USB disk
if the previous chapter did not list any existing partitions (like “/dev/sda1”, “/dev/sda2”, “/dev/sdb1”…), you have to create a partition first for further storage usage.
This triggers an interactive dialogue: Use the suggested defaults for the partition creation (number, starting sector, size, Hex code)
and then confirm your choice with
Refer to the gdisk help text (write “?”) in case you need additional help. Stick to a single partition, to stay aligned to the following HowTo.
procd buttons
Native button handling in procd is handled by scripts in /etc/rc.button/* .
These scripts receive the same environment as older style hotplug buttons received.
To get the button name you can try:
Button Action | Script Environment | Script return value |
---|---|---|
Press | ACTION=“pressed” | Seconds before “timeout” |
Held “timeout” seconds | ACTION=“timeout” SEEN=“” | n/a |
Release | ACTION=“released” SEEN=“” | n/a |
“released” action is sent on release even if “timeout” has been sent.
Please consider using these kernel codes when adding support for new devices, they're mapped by the gpio-button-hotplug kernel module:
Kernel code | event |
---|---|
BTN_0 | BTN_0 |
BTN_1 | BTN_1 |
BTN_2 | BTN_2 |
BTN_3 | BTN_3 |
BTN_4 | BTN_4 |
BTN_5 | BTN_5 |
BTN_6 | BTN_6 |
BTN_7 | BTN_7 |
BTN_8 | BTN_8 |
BTN_9 | BTN_9 |
KEY_BRIGHTNESS_ZERO | brightness_zero |
KEY_CONFIG | config |
KEY_COPY | copy |
KEY_EJECTCD | eject |
KEY_HELP | help |
KEY_LIGHTS_TOGGLE | lights_toggle |
KEY_PHONE | phone |
KEY_POWER | power |
KEY_POWER2 | reboot |
KEY_RESTART | reset |
KEY_RFKILL | rfkill |
KEY_VIDEO | video |
KEY_VOLUMEDOWN | volume_down |
KEY_VOLUMEUP | volume_up |
KEY_WIMAX | wwan |
KEY_WLAN | wlan |
KEY_WPS_BUTTON | wps |
TL-WR1043ND v1.x
If you decide to use the wifitoggle package, you will need to change a few things on the default configuration. The following will work and make the QSS led blink “slowly” when wifi is on:
You can probably get similar behaviour with phy0tpt trigger.
triggerhappy
To manage the router buttons and also other HID buttons (i.e pad buttons or keys of an USB device) we can use an application like triggerhappy.
kernel modules: kmod-hid and kmod-hid-generic both should be installed
The kmod-hid-generic and supposedly also kmod-usb-hid kernel module must be installed for buttons on USB devices such as USB sound cards to work in OpenWrt trunk. Only then the /dev/input/event0 node for the buttons was created on the DIR-505 router with attached USB sound card.
Install file system drivers and create a file system in the partition
To use a partition for data storage, it needs to be formatted with a file system.
The following is the most simplest (and recommended) default configuration for OpenWrt file system usage.
For advanced users, there are further optional file system options available.
WARNING: This step deletes existing data in that partition. Ensure you have a backup of important files before starting!
For USB hard disks, install EXT4 file system and use EXT4 to format the partition (in this example '/dev/sda1'):
For SSD drives and thumb drives, install F2FS file system and use F2FS to format the partition (in this example '/dev/sda1'):
Preliminary steps
The first step is to find out the internal name of the button you want to use: some images use generic names such as BTN_1 , BTN_2 , others have more specific ones like reset , wps , etc. Run the following:
Now press the button you want to use, then run logread .
BTN_1 is the name of the button you want to use. If you want or need to use another button, replace every instance of BTN_1 in the rest of this document with the correct text. From now on, there are several possible approaches: the first uses the 00-button script from the atheros target, the other a simpler shell script.
If you want to run programs from hotplug's scripts you need to be sure PATH and the like are initialized properly, scripts invoked by hotplug only have a default env. Especially if you install stuff into nonstandard locations like /opt/usr/bin.
HID buttons
Hotplug Buttons
Note that after the introduction of procd into OpenWrt in r37132 the package hotplug2 has been removed from the default packages. However at the time of writing, r37336: procd: make old button hotplug rules work until all packages are migrated is still in effect. See also procd.buttons | |
Please read the articles wifitoggle, buttons and nslu2.hardware.button and eventually merge them into this one article |
Читайте также: