Add files via upload

pull/431/head
JohhnGoblin 2025-01-05 01:09:21 -06:00 committed by GitHub
parent 3f66cdf977
commit f741f43508
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
37 changed files with 1654 additions and 0 deletions

View File

@ -0,0 +1,114 @@
# sandbox-fpv
Sandbox for FPV experiments. Telegram-group: `https://t.me/+BMyMoolVOpkzNWUy` | [link](https://t.me/+BMyMoolVOpkzNWUy)
## News
* `26.07.2023` - FPV link setup via 4G modem .
* `01.07.2023` - A short note about the imx335 gk7205v300 camera . About baud for telemetry .
* `22.06.2023` - Finally, the problem with the picture being jerky at 30fps was resolved .
* `06.04.2023` - Added coupler firmware for ivg-g2s with u-boot on board.
* `05.04.2023` - Added functionality to rcjoystick for displaying packet losses (link quality) in rssi.
* `04.04.2023` - OpenIPC has added the majestic streamer, now the ivg-g2s camera runs h265 cbr (constant bitrate). This gave a cleaner picture and a significant reduction in noise. At the same time, changes were made to the link launch process. The main service is now S98datalinkwith the config /etc/datalink.conf, and wfb is now launched via /usr/bin/wifibroadcast. The articles have been corrected to accommodate this innovation.
* `01.04.2023` - Due to certain circumstances, wfb-ng was replaced in my camera and recorder with an alternative from OpenHD . Here is the package for assembly in buildroot OpenIPC. The shell wrappers take into account both options, due to the presence of a parameter link_idthat is not required in the OpenHD implementation. Archive with binaries of both options.
## Notes
* [Notes on setting up the link on the gk7205v200 camera and hi3536ev100 (dv100) recorder](notes_link_gk7205v200_hi3536ev100.md)
* [Notes on camera firmware gk7205v200 on OpenIPC](notes_start_ivg-g2s.md)
* [Notes on firmware for hi3536ev100 recorder on OpenIPC](notes_start_hi3536ev100.md)
* [A note about the imx335 gk7205v300 camera](notes_imx335_gk7205v300.md)
* [Adding smoothness to video on goke/hisilicon cameras](gkrcparams.md)
* [A note about controlling the camera via RC channels from the ground](notes_cam_control.md)
* [Switch between two cameras in the air](note-two-cameras-switched.md)
* [Loader for telemetry for gk7502v200, which does not hang the camera upon reboot](gk7205v200_u-boot-7502v200-for-telemetry.md)
* [Controlling buttons from the front panel on the recorder](nvr_gpio.md)
* [Connecting and setting up a tablet or smartphone for video and OSD via USB](usb-tethering.md)
* [Connecting the tablet to the recorder via wifi via the tablet's AP](note-nvr-tab-ap.md)
* [Connecting the tablet to the recorder via ethernet-usb-device](usb-eth-modem.md)
* [Using the hardware as a joystick to transmit RC channels via mavlink](rcjoystick.md)
* [About the analogue of RSSI](rcjoystick.md#rssi)
* [SBUS-to-USB joystick for using any equipment with an sbus receiver](sbus-to-usb-joystick)
* [FPV link setup via 4G modem](lte-fpv.md)
* [Installing usb_modeswitch on a camera with fpv, lite firmware](usb-modeswitch.md)
#### Miscellaneous
* [mavfwd for inav (one way msp) for camera](user_TipoMan/mavfwd_mavlink2.tar?raw=true)
* [Displaying video on windows and MP](gstlaunch_on_windows.md)
* [Disabling watchdog on the hi3536dv100 recorder](note_nvr_wdt.md)
* [Different from 115200 baud on camera uart for telemetry](note_telemetry_baud.md)
## Road map
* ~~Starting video with transfer from the recorder to the PC.~~
* ~~Launch one- and two-way telemetry.~~
* ~~Starting video transfer via usb tethering to an Android tablet.~~
* ~~Building and testing LTE firmware on e3372h + zerotier~~
* ~~Starting telemetry routing via mavlink-router.~~
* ~~Finding ways to control the camera through mavlink.~~.
* Finding ways to output video and osd via hdmi.
* ~~~Switching between several cameras, where one is the master with wfb-ng, and the rest are slaves.~~~
* Development of expansion board for camera: bec 5v/3.3v; usb hub, uart, wifi/modem power transistor, microSD.
* Development of a zoom lens control board and a method for controlling commercially available boards.
* Development of a stabilizing gimbal controlled from the ground via wfb-ng.
## Russians:
## Новое
* `26.07.2023` - Настройка FPV-линка [через 4G модем](lte-fpv.md).
* `01.07.2023` - Короткая заметка о камере [imx335 gk7205v300](notes_imx335_gk7205v300.md). О [baud для телеметрии](note_telemetry_baud.md).
* `22.06.2023` - Наконец [решилась](gkrcparams.md) проблема с дерганностью картинки на 30fps.
* `06.04.2023` - Добавлена [прошивка coupler](notes_start_ivg-g2s.md#L33) для ivg-g2s с u-boot на борту.
* `05.04.2023` - В rcjoystick [добавлен](rcjoystick.md#rssi) функционал для целей отображения потерь пакетов (качества линка) в rssi.
* `04.04.2023` - В OpenIPC "допилили" стример majestic, теперь на камере ivg-g2s работает h265 cbr (постоянный битрейт). Это дало более чистую картинку и значительное уменьшение шума. Вместе с этим были внесены изменения в процесс запуска линка. Основным сервисом теперь является `S98datalink` с конфигом `/etc/datalink.conf`, а запуск wfb теперь производится через `/usr/bin/wifibroadcast`. Статьи были исправлены под это нововведение.
* `01.04.2023` - В связи с некоторыми обстоятельствами, wfb-ng был заменен в моих камере и регистраторе на альтернативу от [OpenHD](https://github.com/OpenHD/wifibroadcast/). [Тут](wfbopenhd.zip) пакет для сборки в buildroot OpenIPC. В шелл-обертках учтены оба варианта, по наличию параметра `link_id` который не требуется в реализации от OpenHD. [Архив](https://github.com/OpenIPC/sandbox-fpv/blob/master/wfb.zip) с бинарниками обоих вариантов.
## Заметки
* [Заметки о настройке линка на камере gk7205v200 и регистраторе hi3536ev100 (dv100)](notes_link_gk7205v200_hi3536ev100.md)
* [Заметки о прошивке камеры gk7205v200 на OpenIPC](notes_start_ivg-g2s.md)
* [Заметки о прошивке регистратора hi3536ev100 на OpenIPC](notes_start_hi3536ev100.md)
* [Заметка о камере imx335 gk7205v300](notes_imx335_gk7205v300.md)
* [Добавляем плавности видео на goke/hisilicon камерах](gkrcparams.md)
* [Заметка о управлении камерой через RC каналы с наземки](notes_cam_control.md)
* [Переключение между двумя камерами в воздухе](note-two-cameras-switched.md)
* [Загрузчик под телеметрию для gk7502v200, который не вешает камеру при ребуте](gk7205v200_u-boot-7502v200-for-telemetry.md)
* [Управление кнопками с front panel на регистраторе](nvr_gpio.md)
* [Подключение и настройка планшета или смартфона для видео и OSD по USB](usb-tethering.md)
* [Подключение планшета к регистратору по wifi через AP планшета](note-nvr-tab-ap.md)
* [Подключение планшета к регистратору через ethernet-usb-device](usb-eth-modem.md)
* [Использование аппаратуры как джойстика для передачи каналов RC через mavlink](rcjoystick.md)
* [Про аналог RSSI](rcjoystick.md#rssi)
* [SBUS-to-USB joystick для использования любой аппаратуры с sbus приемником](sbus-to-usb-joystick)
* [Настройка FPV-линка через 4G модем](lte-fpv.md)
* [Установка usb_modeswitch на камеру с прошивкой fpv, lite](usb-modeswitch.md)
#### Разное
* [mavfwd для inav (односторонний msp) для камеры](user_TipoMan/mavfwd_mavlink2.tar?raw=true)
* [Отображение видео на windows и в MP](gstlaunch_on_windows.md)
* [Отключение watchdog на регистраторе hi3536dv100](note_nvr_wdt.md)
* [Отличный от 115200 baud на uartе камеры для телеметрии](note_telemetry_baud.md)
## Дорожная карта
* ~~Запуск видео с передачей с регистратора на пк.~~
* ~~Запуск одно-и двусторонней телеметрии.~~
* ~~Запуск передачи видео через usb tethering на android-планшет.~~
* ~~Сборка и тестирование прошивки LTE на e3372h + zerotier~~
* ~~Запуск маршрутизации телеметрии через mavlink-router.~~
* ~~Поиск путей управления камерой сквозь mavlink~~.
* Поиск способов вывода видео и osd через hdmi.
* ~~~Переключение между несколькими камерами, где одна ведущая с wfb-ng, а остальные ведомые.~~~
* Разработка платы расширения для камеры: bec 5v/3.3v; usb hub, uart, транзистор питания wifi/modem, microSD.
* Разработка платы управления зум-объективом и способа управления имеющимися в продаже платами.
* Разработка стабилизирующего подвеса, управляемого с земли сквозь wfb-ng.

View File

@ -0,0 +1,56 @@
### Notes on NVR hi3536ev100 firmware on OpenIPC for FPV purposes
[RU](notes_start_hi3536ev100.md)
<details>
<summary>How memory works</summary>
To begin with, you need to figure out how the memory of the recorder (and the camera too) works and what needs to be flashed. Data is stored on spi-flash 16mb in the form of mtd blocks:
```
cat /proc/cmdline
mem=150M console=ttyAMA0,115200 panic=20 root=/dev/mtdblock3 rootfstype=squashfs init=/init mtdparts=hi_sfc:256k(boot),64k(env),2048k(kernel),8192k(rootfs),-(rootfs_data)
ls /dev/mtdb*
/dev/mtdblock0 /dev/mtdblock1 /dev/mtdblock2 /dev/mtdblock3 /dev/mtdblock4
```
As follows from the output, block zero is the u-boot bootloader; Next comes a block for storing environment variables (`printenv`, `setenv` commands are written to RAM, and `saveenv` saves it in this block); next is the uImage core; then rootfs.squashfs (immutable file system image); and finally rootfs_data or also overlay - a changeable part where differences from rootfs are written if you change any files. Thus, by clearing the overlay, we will reset the file system to default:
```
sf probe 0 #select a device
sf erase 0xA50000 0x500000 #we clean
reset #reboot nvr
```
It's even easier to reset the firmware to factory defaults using the `firstboot` command.
An address calculator for commands is available [here](https://openipc.org/tools/firmware-partitions-calculation). In our case, the rootfs partition: 8192kB, which means the start address of the overlay will be 0xA50000. For a camera with a flash of 8mB and a rootfs size of 5120kB, the addresses will be different, including environment variables!
</details>
The bootloader of this recorder does not have a password, and you can access it via uart/115200 baud by pressing Ctrl+C several times at startup while connected to the debug-uart port of the recorder via a usb-uart 3v3 adapter (ftdi, ch340). Debug uart is located opposite the VGA connector on the opposite edge of the board and is labeled gnd/tx/rx. We don't need to flash the bootloader, we don't need burn. Our ENVs (environment variables) are different from the factory ones, but they are easier to install directly from the bootloader line by line:
```
setenv ipaddr '192.168.0.222' #here is the ip in your subnet from the free ones
setenv serverip '192.168.0.107' #PC address with tftp server
setenv netmask '255.255.255.0'
setenv bootcmd 'sf probe 0; sf read 0x82000000 0x50000 0x200000; bootm 0x82000000'
setenv uk 'mw.b 0x82000000 ff 1000000;tftp 0x82000000 uImage.${soc}; sf probe 0; sf erase 0x50000 0x200000; sf write 0x82000000 0x50000 ${filesize}'
setenv ur 'mw.b 0x82000000 ff 1000000;tftp 0x82000000 rootfs.squashfs.${soc}; sf probe 0; sf erase 0x250000 0x800000; sf write 0x82000000 0x250000 ${filesize}'
setenv bootargs 'mem=192M console=ttyAMA0,115200 panic=20 root=/dev/mtdblock3 rootfstype=squashfs init=/init mtdparts=hi_sfc:256k(boot),64k(env),2048k(kernel),8192k(rootfs) ,-(rootfs_data)'
setenv osmem '192M'
setenv totalmem '256M'
setenv soc 'hi3536dv100'
#here we clear variables that are no longer needed
setenvda; setenv du; setenv dr; setenv dw; setenv dl; setenv dc; setenv up; setenv tk; setenvdd; setenv de; setenv jpeg_addr; setenv jpeg_size; setenv vobuf; setenv loadlogo; setenv appVideoStandard; setenv appSystemLanguage; setenv appCloudExAbility
saveenv #save the new variable environment
printenv #see if everything is ok
```
The original env and full dump of the chip (16mb backup of factory firmware in case of recovery) are available [here](https://github.com/OpenIPC/sandbox-fpv/tree/master/hi3536dv100/original_firmware).
As you may have noticed, the uk and ur variables store macros for the uImage and rootfs downloading them from [tftp server](https://pjo2.github.io/tftpd64/) specified in serverip variable. All addresses correspond to the bootargs variable, the contents of which specify the file system layout for the kernel at boot. The layout is different from the usual for goke/hisilicone cameras, our core is the same as lite/fpv, 2MB in size, but the file system is 8MB in size, like ultimate. The remaining ~5MB are used by the overlay (your changes to the files relative to the original rootfs). For firmware, use official builds from the releases page [openipc/firmware](https://github.com/OpenIPC/firmware/releases/download/latest/openipc.hi3536dv100-nor-fpv.tgz). The archive contains the kernel and file system.
So, after setting the variables, you can start flashing the remaining part. Start the tftpd server, put uImage.hi3536dv100 and rootfs.squashfs.hi3536dv100 in its root, select the appropriate network interface and run the macro in the bootloader: `run uk`. A series of commands must be executed, the output of which should indicate that the uImage file has been downloaded and flashed into flash. Similarly, run `run ur` to flash rootfs. If the addresses are set correctly, but the download is stuck at "Downloading", change the registrar address to a nearby free one: `setenv ipaddr '192.168.0.223'`.
If everything went without errors, do a `reset` and boot into the operating system, login root, password 12345.
The configs from the hi3536dv100 catalog are not relevant, but they may be of interest regarding connecting the tablet via usb/wifi/ethernet hotspot; you can transfer them, by analogy, to the configs of the official firmware or use separate bash scripts. Usually the essence of these changes is to determine the address of the connected tablet (which is the gateway for the registrar in cases where the tablet has a dhcp server) and specifying this address in an additional instance of wfb_rx for the video stream and for telemetry streams.
The firmware is updated via the Internet using the command `sysupgrade -r -k -n`.
<details>
<summary>Update without internet from /tmp</summary>
In the future, you can update the recorder's firmware by uploading the kernel and rootfs into the `/tmp` directory via WinSCP and running `sysupgrade --kernel=/tmp/uImage.hi3536dv100 --rootfs=/tmp/rootfs.squashfs.hi3536dv100 -z` . The `-z` parameter is needed if you do not have an Internet connection (does not update the sysupgrade script), `-n` will clear the user fs (overlay).
</details>

View File

@ -0,0 +1,17 @@
## U-Boot для телеметрии
#### только для gk7502v200!
загрузчик внесён разработчиками в релизы, и если вы прошиваетесь с инструкций на openipc.net, то этого уже делать не надо, только установить bootdelay 0.
Чтобы поток телеметрии не прерывал загрузку камеры, когда u-boot считает телеметрию "нажатием любой кнопки для входа в консоль загрузчика", нужно залить этот загрузчик
[(ССЫЛКА)](https://github.com/OpenIPC/sandbox-fpv/raw/master/gk7205v200/u-boot-gk7205v200-universal.bin):
```
# закачайте файл u-boot-gk7205v200-universal.bin в /tmp камеры через winscp ИЛИ выполните команду и УБЕДИТЕСЬ ЧТО ФАЙЛ СКАЧАЛСЯ!!!#curl -o /tmp/u-boot-gk7205v200-universal.bin http://fpv.openipc.net/u-boot-gk7205v200-universal.bin
flashcp -v /tmp/u-boot-gk7205v200-universal.bin /dev/mtd0
```
и установите нулевую задержку загрузки командой `fw_setenv bootdelay 0`.
При первой прошивке просто используйте этот файл вместо указанного на странице инструкций. Только для gk7502v200!
Данный загрузчик прерывается по комбинации клавиш Ctrl+C, а не любой. Будьте осторожны! Завалите загрузчик - придется паять и шить программатором.

View File

@ -0,0 +1,26 @@
## Добавляем плавности видео
На режимах 1080p@30fps заметно легкое подергивание видео, а при замедленной съемке таймера видно что картинка замирает на какое то время и далее обновляется. Это происходит из за неравномерности потока, который резко возрастает на ключевых кадрах.
Исправить это можно, перенастроив на камере два параметра энкодера.
Спасибо за проделанную работу TipoMan и widgetii!
Нам нужно положить файл [gkrcparams](https://github.com/OpenIPC/sandbox-fpv/raw/master/user_TipoMan/gkrcparams) в /usr/sbin, дать права на выполнение `chmod +x /usr/sbin/gkrcparams` и вставить запуск его после старта majestic в /etc/init.d/S95majestic:
```
start-stop-daemon -b -m -S -q -p "$PIDFILE" -x "/usr/bin/$DAEMON" -- $DAEMON_ARGS
sleep 1 <=== ЭТО ВСТАВИТЬ
gkrcparams --MaxQp 30 --MaxI 2 <=== ЭТО ВСТАВИТЬ
status=$?
```
После перезапуска картинка должна стать плавной. Прочие настройки в majestic.yaml для режима mcs1:
```
video0:
enabled: true
bitrate: 7168
codec: h265
rcMode: cbr
gopSize: 1.0
size: 1920x1080
```
Если же картинка все равно иногда подергивается, придется изменить mcs на 3 в `/etc/wfb.conf` потеряв в дальности либо уменьшать битрейт.

View File

@ -0,0 +1,14 @@
## Прием и отображение видео на windows
В "классическом режиме" (на камере стримит majestic, а NVR пересылает видеопоток на ПК, не забываем указать IP адрес ПК в wfb.conf регистратора) видео можно принимать в QGroundControl, Mission Planner и можно просто вывести в отдельном окне
без привязки к программам. Для этого нужно установить [GStreamer](https://gstreamer.freedesktop.org/download/) и запускать его на прием с некими параметрами, например:
```
C:\gstreamer\1.0\msvc_x86_64\bin\gst-launch-1.0.exe -v udpsrc port=5600 buffer-size=32768 ! application/x-rtp ! rtph265depay ! queue max-size-buffers=5 ! avdec_h265 ! videoconvert ! videoscale ! video/x-raw,width=1280,height=720,format=BGRA ! autovideosink sync=false
```
В данном примере размер видео изменяется до 1280x720. Для запуска видео с разрешением оригинального потока убираем из строки `videoscale ! ` и `width=1280,height=720,`.
![preview](https://github.com/OpenIPC/sandbox-fpv/raw/master/notes_files/Screenshot_2.png)
Для воспроизведения видео в окне Mission Planner нужно кликнуть правой кнопкой мыши по его окну с горизонтом и выбрать `Video > Set GStreamer source`, внести строку параметров: `udpsrc port=5600 buffer-size=32768 ! application/x-rtp ! rtph265depay ! queue max-size-buffers=5 ! avdec_h265 ! videoconvert ! video/x-raw,format=BGRA ! appsink name=outsink`, нажать Ok. Строка сохранится для будущий применений.

View File

@ -0,0 +1,89 @@
## Подключение камеры к планшету или ПК через LTE (4G) модем
Летать через 4G - крайне интересная тема для самолетов под стабилизацией или автоматическим маршрутом. Разобъем процесс настройки на задачи:
* настроить интернет через модем на камере
* настроить свой сервер zerotier (можно воспользоваться публичным)
* подключить камеру и ПК к одной сети zerotier и настроить стрим
Следуя [этим инструкциям](usb-modeswitch.md), настроим usb_modeswitch и сетевой интерфейс eth1 на камере под прошивкой OpenIPC LTE. Если у вас FPV или LITE прошивка, предварительно нужно ее сменить онлайн:
```
#тут меняем fpv на lte в файле /etc/os-release, можно это сделать вручную
sed -i 's/BUILD_OPTION=fpv/BUILD_OPTION=lte/' /etc/os-release
#а это если у вас lite версия
sed -i 's/BUILD_OPTION=lite/BUILD_OPTION=lte/' /etc/os-release
sysupgrade --force_ver -k -r -n
```
Мы получаем камеру с заводскими настройками и lte прошивкой, в которой в отличие от fpv удален wfb а взамен установлен zerotier-one клиент.
На самом деле, правильным решением будет не использовать usb_modeswitch а настроить вторичную композицию модема сразу на cdc_ethernet. Тогда модем перестанет быть универсальным и сразу будет отображаться как сетевая карта, но зато исчезнет вероятность возникновения ряда проблем.
#### zerotier
Это программное обеспечение для объединения нескольких устройств в одну локальную сеть. Существует публичный сервер для создания своей сети, но лучше поднять свой.
Для этого потребуется vps-сервер под ubuntu.
```
apt-get install -y apt-transport-https gnupg mc iftop #устанавливаем зависимости
curl -s https://install.zerotier.com | sudo bash #устанавливаем клиентскую часть
curl -O https://s3-us-west-1.amazonaws.com/key-networks/deb/ztncui/1/x86_64/ztncui_0.7.1_amd64.deb #устанавливаем панель управления
apt-get install ./ztncui_0.7.1_amd64.deb
echo 'HTTPS_PORT=6443' > /opt/key-networks/ztncui/.env #порт для вебморды управления
echo 'NODE_ENV=production' >> /opt/key-networks/ztncui/.env #режим работы
echo 'HTTPS_HOST=nn.mm.ff.dd' >> /opt/key-networks/ztncui/.env #внешний ip-адрес нашего сервера
systemctl restart ztncui
```
Входим по ссылке https://ip_addr:6443, логин admin, пароль password.
Далее создаем сеть и настраиваем параметры выдачи адресов, какие вам больше нравятся, остальные настройки по умолчанию.
В режиме private после подключения клиента требуется установить галочку Authorized чтобы разрешить ему подключение.
![ZTNCUI](https://github.com/OpenIPC/sandbox-fpv/raw/master/notes_files/ZTNCUI.png)
Существует альтернатива в виде [публичного сервера](https://my.zerotier.com/), но вопрос надежности и быстродействия остается подвешенным. Программы - клиенты для windows, android скачивать [тут](https://www.zerotier.com/download/).
Подключение к сети производится через указание Network ID, 16-значной символьной строки, которую берем из панели управления. Для камеры ее указываем в /etc/datalink.conf
```
use_zt=true
zt_netid=a8867b0bxxxxxxxxx
```
после чего перезагружаем камеру. При наличии интернет-подключения, хоть LTE хоть ethernet, камера должна подключиться к сети zerotier. Это можно проверить через веб-панель управления и на камере командой ifconfig.
```
ztuplek3wb Link encap:Ethernet HWaddr 92:31:B1:54:8B
inet addr:10.7.0.1 Bcast:10.7.0.255 Mask:255.255.255.0
inet6 addr: fe80::9031:b1ff:fe54/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:2800 Metric:1
RX packets:93 errors:0 dropped:0 overruns:0 frame:0
TX packets:1236835 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:5677 (5.5 KiB) TX bytes:1493618333 (1.3 GiB)
```
Для ПК или андроид-устройства [устанавливаем](https://www.zerotier.com/download/) программу и аналогично добавляем сеть по ее id, авторизуем устройство в веб-панели. Пробуем перекрестный ping, он должен проходить. Если имеется файервол/брендмауер, как например под windows, нужно добавить в нем разрешающее правило с нашей подсетью.
#### Настройка стрима
Остается в /etc/majestic.yaml указать ip-адрес наземки из сети zerotier и видео можно принимать. Не забудьте согласовать кодеки.
```
outgoing:
- udp://ip_from_zerotier:5600
```
#### Телеметрия
Проверку телеметрии я еще не делал, но работать все должно как то так.
Используется mavlink-routerd с конфигом /etc/mavlink.conf. Нужно указать эндпоинты для локального serial и наземки по ip-адресу zerotier:
```
[General]
TcpServerPort = 0
[UartEndpoint drone]
Device = /dev/ttyAMA0
Baud = 115200
[UdpEndpoint qgroundcontrol]
Mode = Normal
Address = gs_ip_from_zerotier
Port = 14550
```
Так как соединение является двунаправленным, автоматически получаем телеметрию в обе стороны.

View File

@ -0,0 +1,28 @@
## Подключение планшета к регистратору по wifi через AP планшета
Схема проста: в регистратор вставляется [TL-725n](https://www.tp-link.com/ru/home-networking/adapter/tl-wn725n/) или аналогичный адаптер на rtp8188eu, либо адаптер под
который есть драйвер в прошивке OpenIPC; планшет включает точку доступа; регистратор коннектится к этой точке доступа; при перезапуске сервис wfb обнаруживает указанный wlan и
настраивает трансляцию и телеметрию на планшет.
### Поднимем сеть
* Закачаем драйвер [8188eu](hi3536dv100/lib/modules/4.9.37/extra/8188eu.ko) в `/lib/modules/4.9.37/extra/`
* Настроим поднятие сети на адаптере в [`/etc/network/interfaces`](hi3536dv100/etc/network/interfaces), указывая свои ssid и password:
```
auto wlan1
iface wlan1 inet dhcp
pre-up if ! lsmod | grep 8188eu; then insmod /lib/modules/4.9.37/extra/8188eu.ko; fi
pre-up sleep 1
pre-up wpa_passphrase "ssid" "password" >/tmp/wpa_supplicant.conf
pre-up sed -i '2i \\tscan_ssid=1' /tmp/wpa_supplicant.conf
pre-up sleep 3
pre-up wpa_supplicant -B -D nl80211 -i wlan1 -c/tmp/wpa_supplicant.conf
post-down killall wpa_supplicant
```
### Поправим конфиги сервисы
* Закачаем обновленные [`/usr/bin/wifibroadcast`](hi3536dv100/usr/bin/wifibroadcast) и [`/usr/bin/telemetry`](hi3536dv100/usr/bin/telemetry) с детектированием подключения в /usr/bin.
* Добавим в [wfb.conf](hi3536dv100/etc/wfb.conf) новую строчку с параметром - наименованием интерфейса для ap
```
tab_wlan=wlan1
```
* Если мы не пользуемся отправкой потока на PC, можно закомментировать параметр `udp_addr`, это немного разгрузит регистратор.
* Включаем на планшете точку доступа и перезагружаем регистратор, либо нажимаем кнопку на [front panel](nvr_gpio.md).

View File

@ -0,0 +1,42 @@
## Несколько камер на одном линке
У камер есть сетевой интерфейс, который в случае двух камер можно использовать даже без свича, просто соединив четыре провода интерфейса друг с другом. Этот интерфейс и будем использовать для связи между камерами.
Если /etc/network/interfaces доработать примерно таким образом:
```
auto eth0
iface eth0 inet dhcp
hwaddress ether $(fw_printenv -n ethaddr || echo 00:24:B8:FF:FF:FF)
auto eth0:1
iface eth0:1 inet static
address $(fw_printenv -n ipaddr || echo 192.168.1.9)
netmask 255.255.255.0
```
то у камер появится саб-интерфейс с адресом, прописанным в переменной env `ipaddr` либо, если она пуста, указанным в address. Нам нужно, чтобы у камер были адреса из одной подсети, например пусть это будут 192.168.1.9 и 192.168.1.10 у "первой" и "второй" камер.
Первая - та, на которой расположен линк wfb и wifi-свисток. От второй нужен только поток на дополнительный порт, пусть 5601 на адрес первой камеры.
В случае, если на второй камере стоит openipc, нужно на ней отключить wfb через `daemon=0` в `datalink.conf` и настроить udp поток в majestic.yaml на 192.168.1.9:5601.
Теперь создадим на первой камере демонстрационный скрипт переключения камер `camswitch.sh`:
```
function wfb_restart {
kill -9 $(pidof wfb_tx)
. /etc/wfb.conf
wfb_tx -p ${stream} -u ${udp_port} -K /etc/drone.key -B ${bandwidth} -M ${mcs_index} -S ${stbc} -L ${ldpc} -G ${guard_interval} -k ${fec_k} -n ${fec_n} -T ${fec_timeout} -i ${link_id} ${wlan} &
}
function cam_1 {
# this is main cam, with wfb_tx
sed -i 's/udp_port=5601/udp_port=5600/' /etc/wfb.conf
wfb_restart
}
function cam_2 {
# set '- udp: cam1ip:5601' in /etc/majestic.yaml on cam2
sed -i 's/udp_port=5600/udp_port=5601/' /etc/wfb.conf
wfb_restart
}
cam_$1
```
Дадим ему права на выполнение через `chmod +x camswitch.sh` и теперь мы можем переключаться между камерами, вызывая `camswitch.sh 1` или `camswitch.sh 2`.
Скрипт останавливает wfb_tx, заменяет в его конфиге udp_port (основная камера шлет на 5600 а вторая на 5601) и запускает заново, таким образом переключаясь между потоками.
Можно подключить вызов скрипта например к [channels.sh](notes_cam_control.md) и управлять переключением с какого то канала RC.

View File

@ -0,0 +1,9 @@
## Отключение watchdog на регистраторе
Загрузчик на регистраторе запускает собаку, которая раз в полчаса перезагружает его. Для отключения копируем [`wdt.ko`](hi3536dv100/lib/wdt.ko) в `/lib` и добавляем в [`/etc/init.d/S95hisilicon`](hi3536dv100/etc/init.d/S95hisilicon) к загрузкам модулей, тут же выгружая:
```
insmod /lib/wdt.ko
rmmod /lib/wdt.ko
```
Перезагружаемся, watchdog больше не должен срабатывать.

View File

@ -0,0 +1,5 @@
## Заметка об отличной от 115200 скорости uart для телеметрии
TipoMan столкнулся с проблемой: камера зависала при подаче на uart телеметрии на скорости, отличной от 115200. Решение: установка нужной скорости в `/etc/inittab`.
![inittab](notes_files/baud38400.jpg)

View File

@ -0,0 +1,11 @@
### Управление камерой с земли
В качестве эксперимента [`mavfwd`](mavfwd) был дополнен парсером mavlink-пакета RC_CHANNELS (значения RC каналов, отправленные с любого RC-линка, например с наземной станции [(джойстика)](https://github.com/whoim2/arduremote) через [Mission Planner joystick](https://ardupilot.org/copter/docs/common-joystick.html)) или с [подключенного](rcjoystick.md) к регистратору джойстика.
Он мониторит изменения в указанном в аргументе `--channels X` или `-c X`каналах, считая после первых 4х, и при их наличии вызывает скрипт [`/root/channels.sh`](gk7205v200/root), передавая в него два параметра (номер канала и значение), и который производит необходимые операции. Например, `-c 1` будет мониторить только 5й канал, а `-c 4` будет мониторить 5,6,7,8 каналы. В текущем [примере](gk7205v200/root/channels.sh) это изменение режима работы камеры (1080p@30fsp / 720p@5-fps) на 5-м канале, смена luminance на 7м (трехпозиционный переключатель) и переключатель ircut (поляризационного фильтра). По умолчанию `-c 0`, т.е. отключен.
Для установки его на камеру замените в `/usr/sbin/` штатный mavfwd на [измененный](mavfwd/mavfwd), и добавьте параметр `-c` в [`/usr/bin/telemetry`](gk7205v200/usr/bin/telemetry#L39). Заодно получите возможность установить скорость телеметрии для связи с полетником выше чем 115200, конечно на свой страх и риск!
Приветствуются идеи и пожелания по этому поводу, которые можно высказать [здесь](https://t.me/+BMyMoolVOpkzNWUy).
upd 31.03.2023 Добавил распознавание mavlink 2 протокола.

View File

@ -0,0 +1,11 @@
## Заметки о использовании камеры gk7205v300 с сенсором imx335
В главном работа с камерой ничем не отличается от прочих камер gk. Точно так же прошивается lite или fpv, либо lite обновляется до fpv.
Наличие и расположение пинов для USB и UART нужно смотреть на странице продавца. Для примера, камера купленная по [ссылке ](https://aliexpress.ru/item/1005005492432144.html) имеет USB
на разъеме для шлейфа FPC и названы в описании WIFI_DP и WIFI_DN (USB DP/DN).
Нюансы касаются настройки разрешения. Режим 1080p (установка size: 1920x1080 в majestic.yaml) выдает 15 кадров / секунду, что конечно неприемлимо. Необходимо в файле `/etc/sensors/imx335_i2c_4M.ini`
закомментировать (через `;`) строчку `clock=27MHz` и установить `Isp_FrameRate=30`, после чего перезагрузить камеру. Исправленные файлы лежат в каталоге [imx335_gk7205v300](/imx335_gk7205v300).
Также работает режим `size: 2592x1520` и выдает 20fps, но угол обзора картинки не меняется, что наводит на мысли об интерполяции. Но неизвестно, из какого разрешения - в какое. По факту задержка в 1520p@20 ниже и составляет около 165мс, в 1080p@30 - 185мс.
Также необходим [gkrcparams](gkrcparams.md) для более плавной картинки.

View File

@ -0,0 +1,109 @@
### Заметки по постройке видеолинка с двухсторонней телеметрией mavlink
Воздушная часть линка представляет из себя камеру [gk7205v200](https://sl.aliexpress.ru/p?key=e1sTwWg) с подключенным по USB wifi-адаптером на чипе rtl8812au, например ASUS USB AC-56 или [недорогого более слабого адаптера с ali](https://sl.aliexpress.ru/p?key=8CsTwDB).
Наземная часть - это [видеорегистратор](https://sl.aliexpress.ru/p?key=L1sTwWG) на базе чипа hisilicon hi3536dv100 либо ev100, к которому точно так же подключен по USB адаптер rtl8812au или rtl8814au. Для РФ дешевле и быстрее заказать камеру и регистратор у [@ser177](https://t.me/ser177).
Данная статья описывает нюансы создания подобного линка, и является дополнением к [этой статье](https://github.com/OpenIPC/wiki/blob/master/ru/fpv.md).
![link_hw](https://github.com/OpenIPC/sandbox-fpv/raw/master/notes_files/link_hw.png)
### Возможности
Данный линк способен передавать видео
[(youtube)](https://youtu.be/ldfQ9CLE86I) с воздушной части форматом (разрешение@частота кадров) 1920x1080@30 или 1280x720@50 кодеками h264 либо h265 и телеметрию mavlink в обе стороны. Общая схема процессов для передачи видео выглядит так:
![video](https://github.com/OpenIPC/sandbox-fpv/raw/master/notes_files/video.png)
Передача видео на текущий момент возможна двумя способами. Классический - streamer `majestic` через udp порт 5600 засылает RTP/h264 или RTP/h265 поток в [wfb-ng](https://github.com/svpcom/wfb-ng) или [OpenHD-wfb](https://github.com/OpenHD/wifibroadcast) для передачи на землю, где принимается ответной частью wfb и отправляется для воспроизведения на PC или планшет / смартфон по LAN или USB ethernet (tethering). Формат RTP свободно воспроизводится программами для GS, такими как [QGroundControl](https://github.com/mavlink/qgroundcontrol), [Mission Planner](https://ardupilot.org/planner/), [QOpenHD](https://openhdfpv.org/download/) или [FPV-VR](https://github.com/Consti10/FPV_VR_OS). Но его пока невозможно вывести в порт HDMI регистратора, поскольку он построен на специализированном чипе со своим SDK и обычными способами, например через GStreamer как обычно выводят видео в случае Raspberry Pi, этого не сделать.
<sub>QGroundControl имеет баг при воспроизведении h265, проявляющийся в зависании картинки при входе в меню. Это лечится до перезапуска программы выбором потока видео h264 и назад h265.</sub>
Andrey Bezborodov из команды OpenIPC предоставил на тесты скомпилированные примеры *vencoder* и *vdecoder*, вытащенные из Hisilicon SDK и в оригинальном виде расположенные [тут](https://github.com/OpenIPC/silicon_research). `venc` запускается на камере и формирует поток h264 с фрагментацией HAL вместо `majestic`, `vdec` на регистраторе выводит этот поток в HDMI. Все работает, но естественно нет OSD и подобный нестандартный поток невозможно воспроизвести сторонними плеерами. Это очень перспективный путь, поскольку имеет возможности к снижению задержки передачи видео. На текущий момент она составляет от 110 до 130 мсек. На "классической схеме" задержки составляют обычно от 150 до 230 мсек, [вот пример 133 мсек](https://github.com/OpenIPC/sandbox-fpv/raw/master/notes_files/Screenshot_1.png), в зависимости от разрешения и наземных условий воспроизведения.
Этот вопрос можно решить, "научив" `vdec` распознавать RTP/h26[4-5] с помощью библиотеки *libavformat/avformat.h* и по прежнему "стримить" на камере через `majestic`. Для этого нужна помощь программиста C++, если вы желаете помочь проекту с этим - [обращайтесь](https://t.me/+BMyMoolVOpkzNWUy).
Пример настройки *GStreamer* на Mission Planner для воспроизведения h265: `udpsrc port=5600 buffer-size=32768 ! application/x-rtp ! rtph265depay ! avdec_h265 ! videoconvert ! video/x-raw,format=BGRA ! appsink name=outsink`
Поддерживаются частоты от 5,2ghz до 5,85ghz, на atheros 2.3 - 2.4ghz.
### Как все запускается?
При загрузке linux стартует в числе сервисов из `init.d` сервис `S98datalink`, который и является отправной точкой. Он запускает скрипт `/usr/bin/wifibroadcast`, который определяет через lsusb какой адаптер подключен, загружает его драйвер, переключает в режим монитора, стартует `wfb` на передачу или прием, для наземки определяя подключения по usb, второму адаптеру wifi или просто начиная передачу видео на `udp_addr`. Данные о настройках он берет из `/etc/wfb.conf`. Также, при включенной телеметрии, он запускает скрипт `/usr/bin/telemetry`, который занимается тем же но для телеметрийных целей, беря настройки из `/etc/telemetry.conf`.
### Нюансы на камере
Для данной камеры существует два драйвера сенсора - "медленный" 1080p@30fps и "быстрый" 720p@50fps. Их можно переключать на ходу скриптами из примеров в [root](https://github.com/OpenIPC/sandbox-fpv/tree/master/gk7205v200/root), если залить на камеру ["быстрый" драйвер](gk7205v200/lib/sensors/libsns_imx307_2l_720p.so) под отдельным именем и исправить к нему путь в его конфиге [`imx307_i2c_2l_720p_50fps.ini`](gk7205v200/etc/sensors/imx307_i2c_2l_720p_50fps.ini#L15). Все файлы по данной камере находятся в каталоге `gk7205v200`. Если запускать камеру с "быстрым" драйвером в настройках majestic, то передача видео идет рывками, поэтому при старте камеры через `S95goke` прописываются настройки "медленного" драйвера, после чего уже можно включить "быстрый". На текущий момент [ведется работа](notes_cam_control.md) по управлению подобными настройками камеры через RC каналы в mavlink.
### Нюансы на регистраторе
Так как регистратор относительно камеры имеет шикарные 16мб памяти spi flash, из которых мы можем использовать около 5мб, то нам доступен [драйвер адаптеров RTL](https://github.com/OpenIPC/sandbox-fpv/tree/master/hi3536dv100/88XXau-ko) который поддерживает rtl8814au в дополнение к популярному rtl8812au. Для этого нужно залить его поверх штатного в `lib/modules/4.9.37/extra`, не забыв переименовать.
Перекомпилирован [`mavlink-router`](https://github.com/OpenIPC/sandbox-fpv/tree/master/hi3536dv100/usr/bin), так как комплектный из прошивки собран на musl для воздушной части (где он не используется), а прошивка регистратора на glibc.
Также необходимо [отключить hisilicon watchdog](note_nvr_wdt.md).
### Нюансы телеметрии
Текущая схема работы телеметрии выглядит так:
![telemetry](https://github.com/OpenIPC/sandbox-fpv/raw/master/notes_files/telemetry.png)
~~С применением mavlink-routerd на текущий момент возможна только односторонняя телеметрия по udp, поскольку он не умеет использовать разные rx/tx udp порты в рамках одного endpoint, как того требует wfb, будучи запущенным разными процессами `telemetry_rx` и `telemetry_tx`.~~
Будучи запущенным разными процессами, `telemetry_rx` и `telemetry_tx` используют разные порты для приема и передачи данных (кстати, это просто символьные ссылки на wfb_rx и wfb_tx, создаваемые скриптом [запуска телеметрии](hi3536dv100/usr/bin/telemetry)), и mavlink-router требует в [конфигурации](hi3536dv100/etc/mavlink.conf) два UDP-endpoint, которые должны быть сгуппированны:
```
[UdpEndpoint telemetry_tx]
Group=wfb
Mode = Normal
Address = 127.0.0.1
Port = 14550
[UdpEndpoint telemetry_rx]
Group=wfb
Mode = Server
Address = 127.0.0.1
Port = 14551
```
Остальные endpoint нужны для связи с наземной станцией, например tcp:5760 для приема подключений от Mission Planner. Для [приложенного конфига](hi3536dv100/etc/mavlink.conf) в настройках UDP-линка нужно указать адрес регистратора:
![udp-qgc](notes_files/qgc-udp-settings.png)
Остается переключить в /usr/bin/telemetry на использование mavlink-routerd и подключать uart регистратора более не нужно.
```
/usr/bin/mavlink-routerd -c /etc/mavlink.conf &
#/usr/sbin/mavfwd --master ${serial} --baudrate ${baud} --out 127.0.0.1:${port_tx} --in 127.0.0.1:${port_rx} &
```
Если же вы хотите использовать uart, то можете настроить endpoint на /dev/ttyAMA0 или переключиться на mavfwd.
В таком случае необходимо отключить ssh консоль от uart в /etc/inittab, закомментировав строчку:
```
#console::respawn:/sbin/getty -L console 0 vt100 # GENERIC_SERIAL
```
Тогда телеметрия станет доступна на uart регистратора взамен или дополнительно к udp по сети, и ее можно будет использовать через usb-uart адаптер как serial port. На QGC для подключения к serial нужно отключить flow control в advanced, иначе загружает примерно половину параметров и выдает ошибку.
Я скомпилировал `mavfwd` для регистратора, поддерживающий скорости b230400, b500000, b921600 и b1500000, для поддержки более высокой скорости при работе с Mission Planner, проверил на b500000 при b115200 / b230400 на камере. Для регистратора его можно забрать [здесь](hi3536dv100/usr/sbin). Для камеры: [здесь](https://github.com/OpenIPC/sandbox-fpv/tree/master/gk7205v200/usr/sbin). [Исходник](https://github.com/OpenIPC/sandbox-fpv/tree/master/mavfwd). На камере удалось получить устойчивую связь с полетником на скорости 230400, выше stm32f4 не смог. Установка скорости полетника под ardupilot производится параметром `SERIALx_BAUD`, в моем случае: "230". Также не забывайте установить параметр `TELEM_DELAY` на 10 (секунд задержки перед началом выдачи телеметрии), иначе телеметрия может остановит загрузчик. К сожалению, если в полете камера перезапустится по какой то причине отдельно от полетника, то телеметрия ~~не даст ей загрузиться~~ может не дать ей загрузиться. ~~Необходимо доработать загрузчик u-boot, чтобы он не останавливал загрузку по любому символу.~~ ~~C [новым u-boot](gk7205v200_u-boot-7502v200-for-telemetry.md),~~ который прерывается только по Ctrl+C, и `bootdelay=0` этой проблемы по тестам нет. Этот U-boot уже включен во все FPV прошивки OpenIPC.
Также я [заложил в него](notes_cam_control.md) основы для наблюдения за выбранными каналами RC mavlink и передачи их значений при изменении в `/root/channels.sh` как параметров $1 (канал) и $2 (значение).
### Текущие проблемы
Если при загрузке камеры в majestic выбран "быстрый" драйвер 720p, то видео идёт рывками, поэтому в S95goke (автозапуск majestic) перед стартом идёт установка "обычного" драйвера 1080p. Если вы хотите использовать при загрузке камеры 720p@50 по умолчанию, вставьте после загрузки majestic вызов скрипта переключения в [`/etc/init.d/S95majestic`](gk7205v200/etc/init.d/S95majestic#L35) в функции `load_majestic`:
```
yaml-cli -s .isp.sensorConfig /etc/sensors/imx307_i2c_2l_1080p.ini
yaml-cli -s .video0.size 1920x1080
yaml-cli -s .video0.fps 30
start-stop-daemon -b -m -S -q -p "$PIDFILE" -x "/usr/bin/$DAEMON" \
-- $DAEMON_ARGS
status=$?
if [ "$status" -eq 0 ]; then
echo "OK"
else
echo "FAIL"
fi
sleep .5
/root/720.sh
return "$status"
```

View File

@ -0,0 +1,59 @@
### Заметки о прошивке NVR hi3536ev100 на OpenIPC для целей FPV
[EN](en_notes_start_hi3536ev100.md)
Данная статья неактуальна в части прошивки, используйте https://github.com/OpenIPC/wiki/blob/master/en/fpv-nvr.md, эта же статья может быть полезна отдельными моментами.
<details>
<summary>Как устроена память</summary>
Для начала, следует разобраться, как устроена память регистратора (да и камеры тоже) и что нужно прошивать. Данные хранятся на spi-flash 16mb в виде блоков mtd:
```
cat /proc/cmdline
mem=150M console=ttyAMA0,115200 panic=20 root=/dev/mtdblock3 rootfstype=squashfs init=/init mtdparts=hi_sfc:256k(boot),64k(env),2048k(kernel),8192k(rootfs),-(rootfs_data)
ls /dev/mtdb*
/dev/mtdblock0 /dev/mtdblock1 /dev/mtdblock2 /dev/mtdblock3 /dev/mtdblock4
```
Как следует из вывода, нулевой блок это загрузчик u-boot; далее идет блок для хранения переменных окружения (`printenv`, `setenv` команды пишут в ОЗУ, а `saveenv` сохраняет именно в этот блок); следом ядро uImage; потом rootfs.squashfs (неизменяемый образ файловой системы); и наконец rootfs_data или он же overlay - изменяемая часть, куда пишутся отличия от rootfs если вы изменяете какие-либо файлы. Таким образом, очистив overlay, мы "скинем" файловую систему до "дефолта":
```
sf probe 0 #выбираем устройство
sf erase 0xA50000 0x500000 #производим очистку
reset #перезагрузка
```
Еще проще сбросить до "заводских" прошивки командой `firstboot`.
Калькулятор адресов для команд доступен [здесь](https://openipc.org/tools/firmware-partitions-calculation). В нашем случае раздел rootfs: 8192kB, значит адрес начала overlay будет 0xA50000. Для камеры, у которой flash 8mB, размер rootfs 5120kB, адреса будут другие, включая переменные окружения!
</details>
Загрузчик у этого регистратора не имеет пароля, и в него можно попасть через uart/115200 бод, нажав при старте несколько раз Ctrl+C будучи подключенным к порту debug-uart регистратора через адаптер usb-uart 3v3 (ftdi, ch340). Debug uart расположен напротив разъема VGA на противоположном краю платы и подписан как gnd/tx/rx. Загрузчик нам прошивать не требуется, burn не нужен. ENV (переменные окружения) у нас отличаются от заводских, но их проще установить прямо из загрузчика построчно:
```
setenv ipaddr '192.168.0.222' #тут ip в вашей подсети из свободных
setenv serverip '192.168.0.107' #адрес ПК с tftp сервером
setenv netmask '255.255.255.0'
setenv bootcmd 'sf probe 0; sf read 0x82000000 0x50000 0x200000; bootm 0x82000000'
setenv uk 'mw.b 0x82000000 ff 1000000;tftp 0x82000000 uImage.${soc}; sf probe 0; sf erase 0x50000 0x200000; sf write 0x82000000 0x50000 ${filesize}'
setenv ur 'mw.b 0x82000000 ff 1000000;tftp 0x82000000 rootfs.squashfs.${soc}; sf probe 0; sf erase 0x250000 0x800000; sf write 0x82000000 0x250000 ${filesize}'
setenv bootargs 'mem=192M console=ttyAMA0,115200 panic=20 root=/dev/mtdblock3 rootfstype=squashfs init=/init mtdparts=hi_sfc:256k(boot),64k(env),2048k(kernel),8192k(rootfs),-(rootfs_data)'
setenv osmem '192M'
setenv totalmem '256M'
setenv soc 'hi3536dv100'
#тут очищаем ненужные далее переменные
setenv da; setenv du; setenv dr; setenv dw; setenv dl; setenv dc; setenv up; setenv tk; setenv dd; setenv de; setenv jpeg_addr; setenv jpeg_size; setenv vobuf; setenv loadlogo; setenv appVideoStandard; setenv appSystemLanguage; setenv appCloudExAbility
saveenv #сохраняем новое окружение переменных
printenv #смотрим, все ли в порядке
```
Оригинальные env и полный дамп микросхемы (бекап заводской прошивки 16mb на случай восстановления) доступны [здесь](https://github.com/OpenIPC/sandbox-fpv/tree/master/hi3536dv100/original_firmware).
Как вы могли заметить, в переменных uk и ur хранятся макросы для прошивки uImage и rootfs с загрузкой их с [tftp сервера](https://pjo2.github.io/tftpd64/), указанного в переменной serverip. Все адреса соответствуют переменной bootargs, содержимое которой и задает разметку файловой системы для ядра при загрузке. Разметка отличается от привычных для камер goke/hisilicone, ядро у нас как и у lite/fpv размером 2мб, однако файловая система размером 8мб, как у ultimate. Оставшиеся ~5мб используются оверлеем (вашими изменениями файлов относительно оригинальной rootfs). Для прошивки используйте официальные сборки со страницы релизов [openipc/firmware](https://github.com/OpenIPC/firmware/releases/download/latest/openipc.hi3536dv100-nor-fpv.tgz). Архив содержит ядро и файловую систему.
Итак, после установки переменных можно приступать к прошивке оставшейся части. Запустите tftpd сервер, положите в его корень uImage.hi3536dv100 и rootfs.squashfs.hi3536dv100, выберите соответствующий сетевой интерфейс и в загрузчике запустите макрос: `run uk`. Должен выполниться ряд команд, из вывода которых должно следовать, что файл uImage скачался и прошился во flash. Аналогично выполните `run ur` для прошивки rootfs. Если адреса установлены верно, но скачивание застревает на "Downloading", смените адрес регистратора на соседний свободный: `setenv ipaddr '192.168.0.223'`.
Если все прошло без ошибок, делайте `reset` и грузитесь в операционную систему, логин root, пароль 12345.
Конфиги из каталога hi3536dv100 неактуальны, однако могут представлять интерес касаемо подключения планшета по usb/wifi/ethernet hotspot, вы можете перенести их по аналогии в конфиги официальной прошивки или оформить отдельными bash-скриптами. Обычно суть этих изменений в определении адреса подключаемого планшета (который является для регистратора шлюзом в случаях, если планшет у нас dhcp-сервер) и указании этого адреса в дополнительном экземпляре wfb_rx для видеопотока и для телеметрийных потоков.
Обновление прошивки происходит через интернет командой `sysupgrade -r -k -n`.
<details>
<summary>Обновление без интернета из /tmp</summary>
В дальнейшем прошивку регистратора можно делать, залив в него через WinSCP ядро и rootfs в каталог `/tmp` и выполнив `sysupgrade --kernel=/tmp/uImage.hi3536dv100 --rootfs=/tmp/rootfs.squashfs.hi3536dv100 -z`. Параметр `-z` нужен если у вас нет подключения к интернету (не обновляет скрипт sysupgrade), `-n` очистит пользовательскую fs (overlay).
</details>

View File

@ -0,0 +1,117 @@
## Заметки по прошивке камеры IVG-G2S прошивкой OpenIPC.
ВНИМАНИЕ! Большая часть информации из этой статьи безнадежно устарела, все дополнительные помимо прошивки шаги уже неактуальны - они внесены в прошивку, и все работает из коробки, необходимо лишь произвести копирование ключа gs.key с камеры на наземную станцию и указать правильно каналы на обоих.
Цель этой заметки - помочь привлечь внимание к крайне перспективной теме запуска digital fpv на дешевых камерах без одноплатника на борту.
Разработчикам **ОЧЕНЬ** важны отзывы, при наличии популярности проект будет развиваться с их помощью значительно быстрее.
Переходите в специально созданный для этой темы [телеграмм-чат](https://t.me/+BMyMoolVOpkzNWUy), задавайте вопросы которые не описаны тут и по ссылкам ниже, публикуйте информацию о своих успехах и запрашивайте помощь в решении проблем.
Еще раз - фидбеки крайне важны, даже если у вас все получилось и работает - пожалуйста, не поленитесь описать свой сетап и опубликуйте в чате отзыв. Это позволит развиваться проекту с участием разработчиков.
* [Основная страница по OpenIPC + FPV теме, обязательна к прочтению](https://github.com/OpenIPC/wiki/blob/master/ru/fpv.md)
* [Основная wiki проекта](https://github.com/OpenIPC/wiki) (на текущий момент EN версия содержит больше информации)
* [Генератор инструкций на сайте](https://openipc.org/supported-hardware/featured)
### Термины
* Flash - в данном контексте SPI-flash, микросхема памяти.
* U-Boot - загрузчик. Есть "родной", есть от OpenIPC. Родной запаролен. Нам нужен скачанный из генератора инструкций.
* uImage - ядро Embedded Linux, в виде bin файла.
* Root-FS - файловая система выбранной версии (lite, ultimate, fpv), в виде squash-fs файла [https://ru.wikipedia.org/wiki/Squashfs]. uImage и rootfs нужно добывать через конструктор инструкций, раздельная прошивка u-boot и root-fs.
* Shell - командная строка linux камеры, доступна через uart и ssh (программа putty). Также есть shell загрузчика, только uart. Логин root, пароля нет.
* Majestic - утилита - стример потоков видео, из комплекта прошивки OpenIPC.
Платы оснащаются обычно spi-flash размером 8 или 16 мб. Версия ultimate требует 16, можно перепаять. Для fpv целей достаточно 8мб.
Если у вас нет кабеля ethernet для подключения камеры к вашему свичу/роутеру, его можно сделать из половинки обычного патч-корда и разъема jst xh1.25 8pin. Такие использовались в полетниках Omnibus F4 и много где еще.
Распиновки камеры и коннектора легко гуглятся, соединять необходимо 4 линии: rx+, rx-, tx+, tx- на кабеле и камере. На тот же разъем подается питание от 5 до 12в на пины 7(gnd) и 8(vcc).
Рекомендую сначала прошить lite, поскольку в ней разблокирован shell через uart (в файле /etc/inittab) и это позволит подключаться в нештатных ситуациях, например при отсутствии сети.
Существует три способа прошить камеру ivg-g2s на OpenIPC. В порядке усложнения: coupler, burn, программатор.
- Coupler [https://github.com/OpenIPC/coupler] - это загрузка ядра и rootfs одним файлом через родной веб-интерфейс камеры. Минусы - не меняется родной запароленный
загрузчик, можно выполнить только один раз, откат или смена прошивок только через прочие способы.
Алгоритм: выяснить в родном веб-интерфейсе версию, на ее основании скачать прошивку, загрузить как обновление в родном вебинтерфейсе. Для ivg-g2s/659A7 есть [прошивка с загрузчиком](gk7205v200/659A7_OpenIPC_FPV.bin).
- Burn [https://github.com/OpenIPC/burn] - загрузка незапароленного загрузчика u-boot от OpenIPC через uart камеры и uart-usb адаптер (например, ch340) и дальнейшая работа в загрузчике, согласно конструктору инструкций OpenIPC.
Минусов нет, меняется загрузчик которым в любой момент можно загрузить с tftpf сервера [https://pjo2.github.io/tftpd64/] нужный образ и прошить во flash.
Алгоритм описан видеоинструкциями на канале OpenIPC [https://www.youtube.com/@openipc/videos]. Далее, загрузив в RAM загрузчик (только [выбираем свой](gk7205v200_u-boot-7502v200-for-telemetry.md) ввиду нюансов), работаем через конструктор инструкций. uImage и root-fs распаковываем и кладем в каталог tftpd.
Я пробовал пробросить usb-uart в archlinux под virtualbox и ипользовать burn оттуда, но загрузка не проходила, связь с uart была в одну сторону, только на чтение. Из под windows 7 все прошло штатно.
Используйте короткие провода как от usb порта до адаптера, так и от адаптера до камеры. Распиновка uart на камере есть в первой статье из списка выше, соединять необходимо "накрест" - tx адаптера на rx камеры и rx адаптера на tx камеры.
Если все в порядке, но tftp не загружает файл - попробуйте сменить адрес камере на соседний свободный, `setenv ipaddr '192.168.0.223'`.
- Программатор - выпаивание флеш или одной ноги и подключение к программатору, прошивка всего через программатор.
Самый сложный способ, это единственный минус.
При первой загрузке необходимо выполнить команду firstboot.
Если камера циклично перезагружается - это срабатывает watchdog от majestic (стримера). Скорее всего нужно снять колпачок объектива и включить свет. Отключается в /etc/majestic.yaml, убить процесс быстро: `killall majestic`.
Управлять параметрами конфига с сохранением можно через утилиту cli шелла:
```
cli -s .image.contrast 50
cli -s .image.luminance 50
cli -s .video0.codec h264
cli -s .hls.enabled false
cli -s .isp.sensorConfig /etc/sensors/imx307_i2c_2l_1080p.ini
cli -s .video0.size 1920x1080
cli -s .video0.fps 30
```
Рекомендую выполнить эти команды, это настроит majestic для первоначальных попыток.
Перейти на версию FPV с обновлением. Внимание! В версии FPV отключен shell через uart (освобожден для работы телеметрии), после загрузки, остается только сетевой доступ. Сам загрузчик, конечно, работает через uart.
```
sed -i 's/BUILD_OPTION=lite/BUILD_OPTION=fpv/' /etc/os-release
sysupgrade --force_ver -k -r -n
```
Если вы не собираетесь использовать телеметрию сквозь этот видеолинк, можете включить его назад:
```
sed -i 's/#console::respawn:\/sbin\/getty/console::respawn:\/sbin\/getty/' /etc/inittab
reboot
```
Если flash заблокирована (вы как то прошили ядро предыдущих версий, которые не умеют разблокировать флеш), то эта и любые прочие команды выполнены не будут.
Пример вывода `dmesg | grep bsp-sfc` для определения блокировки флешки:
Разблокирована
```
bsp-sfc bsp_spi_nor.0: SR1:[02]->[00]
bsp-sfc bsp_spi_nor.0: SR2:[02]->[00]
bsp-sfc bsp_spi_nor.0: all blocks are unlocked.
bsp-sfc bsp_spi_nor.0: Winbond: SR1 [], SR2 [QE], SR3 [DRV0,DRV1]
```
Заблокирована
```
bsp-sfc bsp_spi_nor.0: SR1:[02]->[00]
bsp-sfc bsp_spi_nor.0: SR2:[02]->[00]
bsp-sfc bsp_spi_nor.0: all blocks are unlocked.
bsp-sfc bsp_spi_nor.0: Winbond: SR1 [TB], SR2 [QE], SR3 [WPS,DRV0,DRV1]
```
Попытка разблокировать флеш из shell (мне не помогла)
```
devmem 0x10010024 32 0x06;devmem 0x10010030 32 0;devmem 0x1001003C 32 0x81;devmem 0x14000000 16 0x0000;devmem 0x10010024 32 0x01;devmem 0x10010030 32 0;devmem 0x10010038 32 2;devmem 0x1001003C 32 0xA1
#
sysupgrade --force_ver -k -r -n
```
Путь к разблокировке flash лежит через загрузку свежего ядра, распакованного архиватором из tgz файла с ядром и rootfs, взятого из конструктора инструкций. Загрузившись, оно автоматически разблокирует flash. Делается из загрузчика, залитого в ram через burn.
```
# Устанавливаем адрес камеры и адрес сервера tftpd
setenv ipaddr 192.168.0.222; setenv serverip 192.168.0.107
# Устанавливаем аргументы окружения (env)
setenv bootargs 'mem=32M console=ttyAMA0,115200 panic=20 rootfstype=squashfs root=/dev/mtdblock3 init=/init mtdparts=sfc:256k(boot),64k(env),2048k(kernel),5120k(rootfs),-(rootfs_data)'
# Очищаем область оперативной памяти для скачивания ядра
mw.b 0x42000000 ff 1000000
# Загружаем ядро uImage.gk7205v200 с tftpd сервера
tftpboot 0x42000000 uImage.${soc}
# Запускаем ядро
bootm 0x42000000
```

View File

@ -0,0 +1,47 @@
## Настройка кнопок со своим функционалом на регистраторе
![front_panel](https://github.com/OpenIPC/sandbox-fpv/raw/master/notes_files/IMG_20230323_081622_212.jpg)
Регистратор имеет на борту разъем для подключения фронт-панели с кнопками, ir-ресивером:
![nvr-ports](notes_files/photo_2023-03-23_02-12-40.jpg)
Разъем cn5 подписан с обратной стороны. С назначением +3.3в и GND понятно, IR задействовать не удалось, остальные пины ведут на GPIO процессора:
```
Y2 ^17
Y1 ^6
X2 ^13
Y3 ^8
X1 ^7
ALARM 10
REC 11
```
Символ `^` означает подтяжку резистором к +3.3, значит кнопкой эти пины надо замыкать на GND и ловить значение 0. Это реализовано в файле [`root/gpio_monitor.sh`](hi3536dv100/root/gpio_monitor.sh).
По замыканию пина Y1 на землю он производит рестарт сервиса [wfb](hi3536dv100/etc/init.d/S98wfb), который следом рестартует [телеметрию](hi3536dv100/usr/bin/telemetry), для более удобного подключения смартфона или планшета [по USB](usb-tethering.md), или после смены wifi-адаптера. Скрипт мониторинга ведет лог нажатий, который можно наблюдать по `tail -f /tmp/gpio.log`.
Примеры использования GPIO на выход можно посмотреть в [`testgpio.sh`](hi3536dv100/root/testgpio.sh), и можно подключить пин ALARM или REC к малмощному светодиоду с резистором для индикации процессов, например перезапуска wfb-ng как сделано в `gpio_monitor.sh`.
Для запуска монитора как системного демона создадим файл [`/etc/init.d/S99gpio_monitor`](hi3536dv100/etc/init.d/S99gpio_monitor) откуда и будем запускать наш [`root/gpio_monitor.sh`](hi3536dv100/root/gpio_monitor.sh):
```
#!/bin/sh
#
# Start gpio monitor
#
case "$1" in
start)
echo "Starting gpio_monitor daemon..."
/root/gpio_monitor.sh &
;;
stop)
echo "Stopping gpio_monitor daemon..."
kill -9 $(pidof {exe} ash /root/gpio_monitor.sh)
;;
*)
echo "Usage: $0 {start|stop}"
exit 1
esac
```
Перезагружаемся без wifi адаптера и/или usb modem, активируем их уже после загрузки и убеждаемся, что по нажатию кнопки (хотя бы полсекунды подержите) сервисы запускаются.
Список запущенных процессов всегда можно посмотреть командой `ps axww`.

View File

@ -0,0 +1,46 @@
## Использование аппаратуры как джойстика для передачи каналов RC через mavlink
### Теория
Программы наземных станций, такие как Mission Planner или QGroundControl, способны распознавать подключенные джойстики либо аппаратуры в режиме usb-джойстика и
передавать на полетный контроллер значения осей в пакете RC_CHANNELS_OVERRIDE (#70). Однако, QGC передает только первые 4 канала (две оси), остальное можно назначить только на кнопки,
а MP может это делать только под Windows, что не всегда удобно. Я написал простейшее приложение для регистратора, которое распознает подключенный джойстик и отправляет пакеты [RC_CHANNELS_OVERRIDE](https://mavlink.io/en/messages/common.html#RC_CHANNELS_OVERRIDE) в версии протокола mavlink 2 для поддержки 18 каналов напрямую в порт telemetry_tx, который обычно опубликован на 127.0.0.1:14650 регистратора. Порт, адрес, время между отправками пакетов, число осей и устройство в системе можно переназначить, смотрите `rcjoystick -h`.
```
Usage:
[-v] verbose;
[-d device] default '/dev/input/js0';
[-a addr] ip address send to, default 127.0.0.1;
[-p port] udp port send to, default 14650;
[-t time] update RC_CHANNEL_OVERRIDE time in ms, default 50;
[-x axes_count] 2..9 axes, default 5, other channels mapping to js buttons from button 0;
[-r rssi_channel] store rx packets per second value to this channel, default 0 (disabled);
[-i interface] wlan interface for rx packets statistics, default wlan0;
```
Например, отправлять можно не в telemetry_tx, а в mavlink_routerd, если вам так нужно. Пакет для сборки в buildroot от OpenIPC [тут](rcjoystick).
### Запускаем
Нам необходимо ядро и rootfs с поддержкой usb-hid на регистраторе. Для этого [прошейте](notes_start_hi3536ev100) их из [`/hi3536dv100`](hi3536dv100) каталога.
~~Необходимо обеспечить запуск модуля `hid-generic.ko`, для этого добавьте `modprobe hid-generic.ko` в [`S95hisilicon`](hi3536dv100/etc/init.d/S95hisilicon).~~ В свежесобранном ядре модуль `hid-generic.ko` загружается автоматически.
Далее нужно скопировать бинарник [`rcjoystick`](hi3536dv100/usr/bin/rcjoystick) в /usr/bin регистратора, через WinSCP и назначить права на исполнение: `chmod +x /usr/bin/rcjoystick`.
Перезагружаемся, подключаем аппаратуру к регистратору по usb и пробуем в консоли запустить `rcjoystick -v`. Если все прошло хорошо, то на экране мы должны увидеть значения осей при изменении положения стиков и переключателей, а в программе телеметрии, например в QGC (analyse tools > Mavlink inspector > RC_CHANNELS_RAW) должны изменяться каналы. Для запуска на постоянную можно прописать его в отдельный сервис [`S99rcjoystick`](hi3536dv100/etc/init.d/S99rcjoystick), главное чтобы он запускался после wifibroadcast.
### RSSI
Также в rcjoystick была добавлена функция инжекции аналога rssi (числа полученных от воздушной части пакетов в секунду) для хоть какого то индикатора качества приема, так как отдельный сервис для этого заводить нет желания и смысла, учитывая невысокий уровень регистратора. В rcjoystick уже есть большая часть необходимого для инжекции.
Указываем `-r 16` и, если интерфейс wfb не wlan0, то и его `-i wlanX` и в указанный канал будет попадать число принятых наземкой пакетов в секунду. У меня оно в районе 800, вы можете увидеть свое применив ключ verbose (`-v`). Далее указываем на полетнике:
```
RSSI_TYPE 2
RSSI_CHANNEL 16
RSSI_CHAN_LOW 0
RSSI_CHAN_HIGH 800 //ваше обычное значение, примерно среднее, не максимальное и не минимальное.
```
Значение будет отправлено на полетник, где он его обработает и установит 0..99 в rssi.
Проект пока в стадии тестирования, поэтому [присылайте](https://t.me/+BMyMoolVOpkzNWUy) свои отзывы о попытках и пожелания.
### Текущие проблемы
Иногда наблюдаются кратковременные фризы, если активно долбить оба стика во всех направлениях. Дебаг говорит, что от драйвера не приходят в это время события о перемещении. Этот эффект не наблюдается, если использовать ["радиоудлинитель" джойстика](sbus-to-usb-joystick) в виде arduino pro micro, которая парсит SBUS от вашего приемника и переводит в usb-hid-joystick.

View File

@ -0,0 +1,26 @@
## Adding Smoothness to Video
In 1080p@30fps modes, slight video twitching is noticeable, and when shooting in slow motion, the timer shows that the picture freezes for some time and then refreshes. This is due to the unevenness of the stream, which increases sharply at key frames.
This can be corrected by reconfiguring two encoder parameters on the camera.
Thanks for the work done TipoMan and widgetii!
We need to put the [gkrcparams](https://github.com/OpenIPC/sandbox-fpv/raw/master/user_TipoMan/gkrcparams) file in /usr/sbin, give it execute permissions `chmod +x /usr/sbin/gkrcparams` and insert its launch after majestic startup in /etc/init.d/S95majestic:
```
start-stop-daemon -b -m -S -q -p "$PIDFILE" -x "/usr/bin/$DAEMON" -- $DAEMON_ARGS
sleep 1 <=== INSERT THIS
gkrcparams --MaxQp 30 --MaxI 2 <=== INSERT THIS
status=$?
```
After restarting the picture should become smooth. Other settings in majestic.yaml for mcs1 mode:
```
video0:
enabled: true
bitrate: 7168
codec: h265
rcMode: cbr
gopSize: 1.0
size: 1920x1080
```
If the picture still twitches sometimes, you will have to change mcs to 3 in `/etc/wfb.conf`, losing range, or reduce the bitrate.

View File

@ -0,0 +1,14 @@
## Receiving and displaying video on windows
In "classic mode" (majestic streams on the camera, and the NVR sends the video stream to the PC, do not forget to specify the IP address of the PC in the wfb.conf of the recorder) video can be received in QGroundControl, Mission Planner and can be simply displayed in a separate window
without being tied to programs. To do this, you need to install [GStreamer](https://gstreamer.freedesktop.org/download/) and launch it to receive with some parameters, for example:
```
C:\gstreamer\1.0\msvc_x86_64\bin\gst-launch-1.0.exe -v udpsrc port=5600 buffer-size=32768 ! application/x-rtp! rtph265depay! queue max-size-buffers=5 ! avdec_h265 ! videoconvert! videoscale! video/x-raw,width=1280,height=720,format=BGRA ! autovideosink sync=false
```
In this example, the video size is changed to 1280x720. To start the video with the resolution of the original stream, remove `videoscale ! ` and `width=1280,height=720,` from the line.
![preview](https://github.com/OpenIPC/sandbox-fpv/raw/master/notes_files/Screenshot_2.png)
To play a video in the Mission Planner window, right-click on its window with the horizon and select `Video > Set GStreamer source`, enter the parameter line: `udpsrc port=5600 buffer-size=32768 ! application/x-rtp ! rtph265depay ! queue max-size-buffers=5 ! avdec_h265 ! videoconvert ! video/x-raw,format=BGRA ! appsink name=outsink`, click Ok. The line will be saved for future use.

View File

@ -0,0 +1,89 @@
## Connecting the camera to a tablet or PC via LTE (4G) modem
Flying via 4G is a very interesting topic for aircraft under stabilization or automatic route. Let's break the setup process down into tasks:
* set up internet via modem on camera
* set up your own zerotier server (you can use a public one)
* connect the camera and PC to the same zerotier network and set up a stream
Following [these instructions](usb-modeswitch.md), we will configure usb_modeswitch and the eth1 network interface on the camera with OpenIPC LTE firmware. If you have FPV or LITE firmware, you will need to change it online first:
```
#here we change fpv to lte in the file /etc/os-release, you can do it manually
sed -i 's/BUILD_OPTION=fpv/BUILD_OPTION=lte/' /etc/os-release
#and this is if you have the lite version
sed -i 's/BUILD_OPTION=lite/BUILD_OPTION=lte/' /etc/os-release
sysupgrade --force_ver -k -r -n
```
We get a camera with factory settings and LTE firmware, in which, unlike FPV, WFB is removed and a Zerotier-One client is installed instead.
In fact, the correct solution would be not to use usb_modeswitch but to configure the secondary modem composition directly to cdc_ethernet. Then the modem will cease to be universal and will immediately be displayed as a network card, but the probability of a number of problems will disappear.
#### zerotier
This is software for combining multiple devices into one local network. There is a public server for creating your own network, but it is better to raise your own.
This will require a vps server running ubuntu.
```
apt-get install -y apt-transport-https gnupg mc iftop #install dependencies
curl -s https://install.zerotier.com | sudo bash #install the client part
curl -O https://s3-us-west-1.amazonaws.com/key-networks/deb/ztncui/1/x86_64/ztncui_0.7.1_amd64.deb #install the control panel
apt-get install ./ztncui_0.7.1_amd64.deb
echo 'HTTPS_PORT=6443' > /opt/key-networks/ztncui/.env #port for web interface
echo 'NODE_ENV=production' >> /opt/key-networks/ztncui/.env #operating mode
echo 'HTTPS_HOST=nn.mm.ff.dd' >> /opt/key-networks/ztncui/.env #external IP address of our server
systemctl restart ztncui
```
Log in using the link https://ip_addr:6443, login admin, password password.
Next, create a network and configure the address issuance parameters that you like best, the rest of the settings are default.
In private mode, after the client connects, you need to check the Authorized box to allow the client to connect.
![ZTNCUI](https://github.com/OpenIPC/sandbox-fpv/raw/master/notes_files/ZTNCUI.png)
There is an alternative in the form of a [public server](https://my.zerotier.com/), but the issue of reliability and speed remains suspended. Client programs for Windows, Android can be downloaded [here](https://www.zerotier.com/download/).
Connection to the network is made by specifying the Network ID, a 16-digit character string, which we take from the control panel. For the camera, we specify it in /etc/datalink.conf
```
use_zt=true
zt_netid=a8867b0bxxxxxxxxx
```
then reboot the camera. If there is an Internet connection, either LTE or Ethernet, the camera should connect to the zerotier network. This can be checked through the web control panel and on the camera with the ifconfig command.
```
ztuplek3wb Link encap:Ethernet HWaddr 92:31:B1:54:8B
inet addr:10.7.0.1 Bcast:10.7.0.255 Mask:255.255.255.0
inet6 addr: fe80::9031:b1ff:fe54/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:2800 Metric:1
RX packets:93 errors:0 dropped:0 overruns:0 frame:0
TX packets:1236835 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueue:1000
RX bytes:5677 (5.5 KiB) TX bytes:1493618333 (1.3 GiB)
```
For a PC or Android device, [install](https://www.zerotier.com/download/) the program and similarly add the network by its id, authorize the device in the web panel. Try cross ping, it should pass. If there is a firewall/brandmauer, such as under Windows, you need to add a permit rule with our subnet.
#### Setting up a stream
All that remains is to specify the IP address of the ground station from the zerotier network in /etc/majestic.yaml and the video can be received. Don't forget to agree on the codecs.
```
outgoing:
- udp://ip_from_zerotier:5600
```
#### Telemetry
I haven't checked the telemetry yet, but everything should work something like this.
Mavlink-routerd is used with the config /etc/mavlink.conf. You need to specify endpoints for local serial and ground by the zerotier IP address:
```
[General]
TcpServerPort = 0
[UartEndpoint drone]
Device = /dev/ttyAMA0
Baud = 115200
[UdpEndpoint qgroundcontrol]
Mode = Normal
Address = gs_ip_from_zerotier
Port = 14550
```
Since the connection is bidirectional, we automatically receive telemetry in both directions.

View File

@ -0,0 +1,28 @@
## Connecting the tablet to the recorder via wifi through the tablet's AP
The scheme is simple: a [TL-725n](https://www.tp-link.com/ru/home-networking/adapter/tl-wn725n/) or a similar adapter on rtp8188eu, or an adapter for
which is the driver in the OpenIPC firmware; the tablet turns on the access point; the recorder connects to this access point; when restarting, the wfb service detects the specified wlan and
Sets up broadcasting and telemetry on the tablet.
### Let's raise the network
* Download the driver [8188eu](hi3536dv100/lib/modules/4.9.37/extra/8188eu.ko) to `/lib/modules/4.9.37/extra/`
* Let's set up network raising on the adapter in [`/etc/network/interfaces`](hi3536dv100/etc/network/interfaces), specifying your ssid and password:
```
auto wlan1
iface wlan1 inet dhcp
pre-up if ! lsmod | grep 8188eu; then insmod /lib/modules/4.9.37/extra/8188eu.ko; fi
pre-up sleep 1
pre-up wpa_passphrase "ssid" "password" >/tmp/wpa_supplicant.conf
pre-up sed -i '2i \\tscan_ssid=1' /tmp/wpa_supplicant.conf
pre-up sleep 3
pre-up wpa_supplicant -B -D nl80211 -i wlan1 -c/tmp/wpa_supplicant.conf
post-down killall wpa_supplicant
```
### We will correct the service configs
* Download updated [`/usr/bin/wifibroadcast`](hi3536dv100/usr/bin/wifibroadcast) and [`/usr/bin/telemetry`](hi3536dv100/usr/bin/telemetry) with connection detection in /usr/bin.
* Add a new line to [wfb.conf](hi3536dv100/etc/wfb.conf) with a parameter - the interface name for ap
```
tab_wlan=wlan1
```
* If we do not use sending a stream to a PC, we can comment out the `udp_addr` parameter, this will unload the registrar a little.
* Turn on the access point on the tablet and reboot the recorder, or press the button on the [front panel](nvr_gpio.md).

View File

@ -0,0 +1,42 @@
## Several cameras on one link
The cameras have a network interface, which in the case of two cameras can be used even without a switch, simply by connecting the four interface wires to each other. This interface will be used for communication between the cameras.
If /etc/network/interfaces is modified in approximately the following way:
```
auto eth0
iface eth0 inet dhcp
hwaddress ether $(fw_printenv -n ethaddr || echo 00:24:B8:FF:FF:FF)
auto eth0:1
iface eth0:1 inet static
address $(fw_printenv -n ipaddr || echo 192.168.1.9)
netmask 255.255.255.0
```
then the cameras will have a sub-interface with the address specified in the env variable `ipaddr` or, if it is empty, specified in address. We need the cameras to have addresses from the same subnet, for example, let it be 192.168.1.9 and 192.168.1.10 for the "first" and "second" cameras.
The first one is the one with the wfb link and wifi-whistle. From the second one we only need a stream to an additional port, let's say 5601 to the address of the first camera.
If the second camera has openipc, you need to disable wfb on it via `daemon=0` in `datalink.conf` and configure the udp stream in majestic.yaml to 192.168.1.9:5601.
Now let's create a demo camera switching script `camswitch.sh` on the first camera:
```
function wfb_restart {
kill -9 $(pidof wfb_tx)
. /etc/wfb.conf
wfb_tx -p ${stream} -u ${udp_port} -K /etc/drone.key -B ${bandwidth} -M ${mcs_index} -S ${stbc} -L ${ldpc} -G ${guard_interval } -k ${fec_k} -n ${fec_n} -T ${fec_timeout} -i ${link_id} ${wlan} &
}
function cam_1 {
# this is main cam, with wfb_tx
sed -i 's/udp_port=5601/udp_port=5600/' /etc/wfb.conf
wfb_restart
}
function cam_2 {
# set '- udp: cam1ip:5601' in /etc/majestic.yaml on cam2
sed -i 's/udp_port=5600/udp_port=5601/' /etc/wfb.conf
wfb_restart
}
cam_$1
```
Let's give it execution rights via `chmod +x camswitch.sh` and now we can switch between cameras by calling `camswitch.sh 1` or `camswitch.sh 2`.
The script stops wfb_tx, replaces udp_port in its config (the main camera sends to 5600 and the second to 5601) and starts it again, thus switching between streams.
You can connect a script call, for example, to [channels.sh](notes_cam_control.md) and control switching from some RC channel.

View File

@ -0,0 +1,9 @@
## Disabling watchdog on the recorder
The loader on the recorder starts a dog that reboots it every half hour. To disable, copy [`wdt.ko`](hi3536dv100/lib/wdt.ko) to `/lib` and add to [`/etc/init.d/S95hisilicon`](hi3536dv100/etc/init.d/S95hisilicon) to module loads, unloading immediately:
```
insmod /lib/wdt.ko
rmmod /lib/wdt.ko
```
Reboot, watchdog should no longer trigger.

View File

@ -0,0 +1,5 @@
## Note on different uart speed for telemetry than 115200
TipoMan encountered a problem: the camera hung when sending telemetry to uart at a speed different from 115200. Solution: setting the desired speed in `/etc/inittab`.
![inittab](notes_files/baud38400.jpg)

View File

@ -0,0 +1,10 @@
### Camera control from the ground
As an experiment, [`mavfwd`](mavfwd) was supplemented with a parser for the mavlink RC_CHANNELS packet (RC channel values sent from any RC link, such as from a ground station [(joystick)](https://github.com/whoim2/arduremote) via a [Mission Planner joystick](https://ardupilot.org/copter/docs/common-joystick.html)) or from a [connected](rcjoystick.md) joystick to the recorder.
It monitors changes in channels specified in the `--channels X` or `-c X` argument, counting from the first 4, and if any, calls the [`/root/channels.sh`](gk7205v200/root) script, passing two parameters (channel number and value) to it, and which performs the necessary operations. For example, `-c 1` will monitor only channel 5, and `-c 4` will monitor channels 5,6,7,8. In the current [example](gk7205v200/root/channels.sh) this is changing the camera mode (1080p@30fsp / 720p@5-fps) on channel 5, changing luminance to 7m (three-position switch) and ircut switch (polarizing filter). By default `-c 0`, i.e. disabled.
To install it on the camera, replace the standard mavfwd in `/usr/sbin/` with the [modified](mavfwd/mavfwd), and add the `-c` parameter to [`/usr/bin/telemetry`](gk7205v200/usr/bin/telemetry#L39). At the same time, you will be able to set the telemetry speed for communication with the flight controller higher than 115200, of course at your own risk!
Ideas and suggestions on this matter are welcome and can be expressed [here](https://t.me/+BMyMoolVOpkzNWUy).
upd 31.03.2023 Added recognition of mavlink 2 protocol.

View File

@ -0,0 +1,11 @@
## Notes on using gk7205v300 camera with imx335 sensor
In the main, working with the camera is no different from other gk cameras. Lite or fpv is flashed in the same way, or lite is updated to fpv.
The presence and location of pins for USB and UART should be viewed on the seller's page. For example, the camera purchased at [link](https://aliexpress.ru/item/1005005492432144.html) has USB
on the connector for the FPC cable and are named in the description WIFI_DP and WIFI_DN (USB DP/DN).
The nuances concern the resolution settings. The 1080p mode (setting size: 1920x1080 in majestic.yaml) produces 15 frames / second, which is of course unacceptable. It is necessary in the file `/etc/sensors/imx335_i2c_4M.ini`
comment out (via `;`) the line `clock=27MHz` and set `Isp_FrameRate=30`, then reboot the camera. The corrected files are in the [imx335_gk7205v300](/imx335_gk7205v300) directory.
The `size: 2592x1520` mode also works and produces 20 fps, but the viewing angle of the picture does not change, which suggests interpolation. But it is not known from what resolution - to what. In fact, the delay in 1520p@20 is lower and is about 165 ms, in 1080p@30 - 185 ms.
Also needed is [gkrcparams](gkrcparams.md) for smoother picture.

View File

@ -0,0 +1,108 @@
### Notes on building a video link with two-way telemetry mavlink
The air part of the link is a [gk7205v200](https://sl.aliexpress.ru/p?key=e1sTwWg) camera with a connected USB wifi adapter on the rtl8812au chip, for example ASUS USB AC-56 or an [inexpensive weaker adapter from ali](https://sl.aliexpress.ru/p?key=8CsTwDB).
The ground part is a [video recorder](https://sl.aliexpress.ru/p?key=L1sTwWG) based on the hisilicon hi3536dv100 or ev100 chip, to which the rtl8812au or rtl8814au adapter is connected via USB in the same way. For the Russian Federation, it is cheaper and faster to order a camera and recorder from [@ser177](https://t.me/ser177).
This article describes the nuances of creating such a link, and is an addition to [this article](https://github.com/OpenIPC/wiki/blob/master/ru/fpv.md).
![link_hw](https://github.com/OpenIPC/sandbox-fpv/raw/master/notes_files/link_hw.png)
### Possibilities
This link is capable of transmitting video
[(youtube)](https://youtu.be/ldfQ9CLE86I) with the aerial part format (resolution@frame rate) 1920x1080@30 or 1280x720@50 codecs h264 or h265 and mavlink telemetry in both directions. The general scheme of processes for video transmission looks like this:
![video](https://github.com/OpenIPC/sandbox-fpv/raw/master/notes_files/video.png)
Video transmission is currently possible in two ways. The classic one is the `majestic` streamer via udp port 5600 sending an RTP/h264 or RTP/h265 stream to [wfb-ng](https://github.com/svpcom/wfb-ng) or [OpenHD-wfb](https://github.com/OpenHD/wifibroadcast) for transmission to the ground, where it is received by the wfb response part and sent for playback on a PC or tablet / smartphone via LAN or USB ethernet (tethering). The RTP format is freely played by programs for GS, such as [QGroundControl](https://github.com/mavlink/qgroundcontrol), [Mission Planner](https://ardupilot.org/planner/), [QOpenHD](https://openhdfpv.org/download/) or [FPV-VR](https://github.com/Consti10/FPV_VR_OS). But it is not yet possible to output it to the HDMI port of the recorder, since it is built on a specialized chip with its own SDK and in the usual ways, for example through GStreamer, as video is usually output in the case of Raspberry Pi, this cannot be done.
<sub>QGroundControl has a bug when playing h265, which manifests itself in the image freezing when entering the menu. This is treated before restarting the program by selecting the h264 video stream and back to h265.</sub>
Andrey Bezborodov from the OpenIPC team provided compiled examples of *vencoder* and *vdecoder* for testing, pulled from Hisilicon SDK and located in their original form [here](https://github.com/OpenIPC/silicon_research). `venc` runs on the camera and forms an h264 stream with HAL fragmentation instead of `majestic`, `vdec` on the recorder outputs this stream to HDMI. Everything works, but naturally there is no OSD and such a non-standard stream cannot be played by third-party players. This is a very promising way, since it has the ability to reduce video transmission delay. At the moment, it is from 110 to 130 ms. On the "classic scheme" delays are usually from 150 to 230 ms, [here is an example 133 ms](https://github.com/OpenIPC/sandbox-fpv/raw/master/notes_files/Screenshot_1.png), depending on the resolution and ground conditions of playback.
This issue can be solved by "teaching" `vdec` to recognize RTP/h26[4-5] using the *libavformat/avformat.h* library and still "streaming" on the camera via `majestic`. This requires the help of a C++ programmer, if you want to help the project with this - [contact](https://t.me/+BMyMoolVOpkzNWUy).
Example of configuring *GStreamer* on Mission Planner to play h265: `udpsrc port=5600 buffer-size=32768 ! application/x-rtp ! rtph265depay ! avdec_h265 ! videoconvert ! video/x-raw,format=BGRA ! appsink name=outsink`
Supported frequencies are from 5.2 GHz to 5.85 GHz, on atheros 2.3 - 2.4 GHz.
### How does everything start?
When booting Linux, the service `S98datalink` starts among the services from `init.d`, which is the starting point. It starts the script `/usr/bin/wifibroadcast`, which determines via lsusb which adapter is connected, loads its driver, switches to monitor mode, starts `wfb` for transmission or reception, for terrestrial it determines connections via USB, a second WiFi adapter or simply starts transmitting video to `udp_addr`. It takes data on the settings from `/etc/wfb.conf`. Also, when telemetry is enabled, it starts the script `/usr/bin/telemetry`, which does the same but for telemetry purposes, taking settings from `/etc/telemetry.conf`.
### Nuances on camera
There are two sensor drivers for this camera - "slow" 1080p@30fps and "fast" 720p@50fps. They can be switched on the fly using scripts from the examples in [root](https://github.com/OpenIPC/sandbox-fpv/tree/master/gk7205v200/root), if you upload the ["fast" driver](gk7205v200/lib/sensors/libsns_imx307_2l_720p.so) to the camera under a separate name and correct the path to it in its config [`imx307_i2c_2l_720p_50fps.ini`](gk7205v200/etc/sensors/imx307_i2c_2l_720p_50fps.ini#L15). All files for this camera are in the `gk7205v200` directory. If you run the camera with the "fast" driver in the majestic settings, the video transfer is jerky, so when you start the camera via `S95goke`, the "slow" driver settings are registered, after which you can turn on the "fast" one. At the moment, [work is underway](notes_cam_control.md) to control such camera settings via RC channels in mavlink.
### Nuances on the registrar
Since the recorder has a great 16MB of spi flash memory relative to the camera, of which we can use about 5MB, we have access to the [RTL adapter driver](https://github.com/OpenIPC/sandbox-fpv/tree/master/hi3536dv100/88XXau-ko) which supports rtl8814au in addition to the popular rtl8812au. To do this, you need to upload it over the regular one to `lib/modules/4.9.37/extra`, not forgetting to rename it.
Recompiled [`mavlink-router`](https://github.com/OpenIPC/sandbox-fpv/tree/master/hi3536dv100/usr/bin), since the complete one from the firmware is compiled on musl for the air part (where it is not used), and the recorder firmware is on glibc.
It is also necessary to [disable hisilicon watchdog](note_nvr_wdt.md).
### Nuances of telemetry
The current telemetry scheme looks like this:
![telemetry](https://github.com/OpenIPC/sandbox-fpv/raw/master/notes_files/telemetry.png)
~~Currently, using mavlink-routerd, only one-way telemetry via udp is possible, since it cannot use different rx/tx udp ports within one endpoint, as required by wfb, being launched by different processes `telemetry_rx` and `telemetry_tx`.~~
Being started by different processes, `telemetry_rx` and `telemetry_tx` use different ports for receiving and transmitting data (by the way, these are just symbolic links to wfb_rx and wfb_tx created by the [telemetry startup](hi3536dv100/usr/bin/telemetry) script), and mavlink-router requires in the [configuration](hi3536dv100/etc/mavlink.conf) two UDP endpoints, which must be grouped:
```
[UdpEndpoint telemetry_tx]
Group=wfb
Mode = Normal
Address = 127.0.0.1
Port = 14550
[UdpEndpoint telemetry_rx]
Group=wfb
Mode = Server
Address = 127.0.0.1
Port = 14551
```
The remaining endpoints are needed to communicate with the ground station, for example tcp:5760 to receive connections from Mission Planner. For the [attached config](hi3536dv100/etc/mavlink.conf) in the UDP link settings you need to specify the registrar address:
![udp-qgc](notes_files/qgc-udp-settings.png)
All that remains is to switch to /usr/bin/telemetry to use mavlink-routerd and there is no longer any need to connect the recorder's uart.
```
/usr/bin/mavlink-routerd -c /etc/mavlink.conf &
#/usr/sbin/mavfwd --master ${serial} --baudrate ${baud} --out 127.0.0.1:${port_tx} --in 127.0.0.1:${port_rx} &
```
If you want to use uart, you can set the endpoint to /dev/ttyAMA0 or switch to mavfwd.
In this case, you need to disable the ssh console from uart in /etc/inittab by commenting out the line:
```
#console::respawn:/sbin/getty -L console 0 vt100 # GENERIC_SERIAL
```
Then telemetry will be available on the uart of the recorder instead of or in addition to udp over the network, and it can be used via the usb-uart adapter as a serial port. On QGC, to connect to serial, you need to disable flow control in advanced, otherwise it loads about half of the parameters and gives an error.
I compiled `mavfwd` for the DVR, supporting b230400, b500000, b921600 and b1500000 baud rates, to support higher rates when working with Mission Planner, tested on b500000 at b115200 / b230400 on the camera. For the DVR it can be taken [here](hi3536dv100/usr/sbin). For the camera: [here](https://github.com/OpenIPC/sandbox-fpv/tree/master/gk7205v200/usr/sbin). [Source](https://github.com/OpenIPC/sandbox-fpv/tree/master/mavfwd). On the camera it was possible to get a stable connection with the flight planner at a rate of 230400, higher than stm32f4 it was not possible. Setting the flight controller speed for ardupilot is done by the `SERIALx_BAUD` parameter, in my case: "230". Also, don't forget to set the `TELEM_DELAY` parameter to 10 (seconds of delay before starting to output telemetry), otherwise telemetry may stop the bootloader. Unfortunately, if the camera is restarted for some reason during the flight separately from the flight controller, then telemetry ~~will not let it boot~~ may not let it boot. ~~It is necessary to modify the u-boot bootloader so that it does not stop booting on any character.~~ ~~With [new u-boot](gk7205v200_u-boot-7502v200-for-telemetry.md),~~ which is interrupted only by Ctrl+C, and `bootdelay=0` this problem is not present according to tests. This U-boot is already included in all OpenIPC FPV firmware.
I also [put in it](notes_cam_control.md) the basics for monitoring selected mavlink RC channels and passing their values when changed in `/root/channels.sh` as parameters $1 (channel) and $2 (value).
### Current issues
If the "fast" 720p driver is selected when loading the camera in majestic, the video is jerky, so in S95goke (majestic autostart) the "normal" 1080p driver is installed before starting. If you want to use 720p@50 by default when loading the camera, insert a call to the switching script in [`/etc/init.d/S95majestic`](gk7205v200/etc/init.d/S95majestic#L35) in the `load_majestic` function after loading majestic:
```
yaml-cli -s .isp.sensorConfig /etc/sensors/imx307_i2c_2l_1080p.ini
yaml-cli -s .video0.size 1920x1080
yaml-cli -s .video0.fps 30
start-stop-daemon -b -m -S -q -p "$PIDFILE" -x "/usr/bin/$DAEMON" \
-- $DAEMON_ARGS
status=$?
if [ "$status" -eq 0 ]; then
echo "OK"
else
echo "FAIL"
fi
sleep .5
/root/720.sh
return "$status"
```

View File

@ -0,0 +1,59 @@
### Notes on NVR hi3536ev100 firmware on OpenIPC for FPV purposes
[EN](en_notes_start_hi3536ev100.md)
This article is not relevant in terms of firmware, use https://github.com/OpenIPC/wiki/blob/master/en/fpv-nvr.md, this article may be useful in some aspects.
<details>
<summary>How memory works</summary>
First, you should understand how the recorder's memory is arranged (and the camera's too) and what needs to be flashed. The data is stored on a 16mb spi-flash in the form of mtd blocks:
```
cat /proc/cmdline
mem=150M console=ttyAMA0,115200 panic=20 root=/dev/mtdblock3 rootfstype=squashfs init=/init mtdparts=hi_sfc:256k(boot),64k(env),2048k(kernel),8192k(rootfs),-(rootfs_data)
ls /dev/mtdb*
/dev/mtdblock0 /dev/mtdblock1 /dev/mtdblock2 /dev/mtdblock3 /dev/mtdblock4
```
As follows from the output, the zero block is the u-boot bootloader; then comes the block for storing environment variables (`printenv`, `setenv` commands write to RAM, and `saveenv` saves exactly to this block); then the uImage kernel; then rootfs.squashfs (an immutable file system image); and finally rootfs_data or overlay - a variable part where differences from rootfs are written if you change any files. Thus, by clearing the overlay, we "reset" the file system to the "default":
```
sf probe 0 #select device
sf erase 0xA50000 0x500000 #perform cleaning
reset #reboot
```
It's even easier to reset to factory firmware using the `firstboot` command.
The address calculator for commands is available [here](https://openipc.org/tools/firmware-partitions-calculation). In our case, the rootfs partition is 8192kB, so the overlay start address will be 0xA50000. For a camera with 8mB flash, the rootfs size is 5120kB, the addresses will be different, including environment variables!
</details>
The bootloader of this recorder does not have a password, and you can get into it via uart/115200 baud, pressing Ctrl+C several times at startup while connected to the debug-uart port of the recorder via a usb-uart 3v3 adapter (ftdi, ch340). Debug uart is located opposite the VGA connector on the opposite edge of the board and is signed as gnd/tx/rx. We do not need to flash the bootloader, burn is not needed. ENV (environment variables) are different from the factory ones, but it is easier to install them directly from the bootloader line by line:
```
setenv ipaddr '192.168.0.222' #here is the ip in your subnet from free ones
setenv serverip '192.168.0.107' #address of PC with tftp server
setenv netmask '255.255.255.0'
setenv bootcmd 'sf probe 0; sf read 0x82000000 0x50000 0x200000; bootm 0x82000000'
setenv uk 'mw.b 0x82000000 ff 1000000;tftp 0x82000000 uImage.${soc}; sf probe 0; sf erase 0x50000 0x200000; sf write 0x82000000 0x50000 ${filesize}'
setenv ur 'mw.b 0x82000000 ff 1000000;tftp 0x82000000 rootfs.squashfs.${soc}; sf probe 0; sf erase 0x250000 0x800000; sf write 0x82000000 0x250000 ${filesize}'
setenv bootargs 'mem=192M console=ttyAMA0,115200 panic=20 root=/dev/mtdblock3 rootfstype=squashfs init=/init mtdparts=hi_sfc:256k(boot),64k(env),2048k(kernel),8192k(rootfs),-(rootfs_data)'
setenv eighth '192M'
setenv totalmem '256M'
setenv soc 'hi3536dv100'
#here we clear variables that are no longer needed
setenv da; setenv du; setenv dr; setenv dw; setenv dl; setenv dc; setenv up; setenv tk; setenv dd; setenv de; setenv jpeg_addr; setenv jpeg_size; setenv vobuf; setenv loadlogo; setenv appVideoStandard; setenv appSystemLanguage; setenv appCloudExAbility
saveenv #save the new environment of variables
printenv #check if everything is ok
```
Original env and full chip dump (16mb factory firmware backup in case of recovery) are available [here](https://github.com/OpenIPC/sandbox-fpv/tree/master/hi3536dv100/original_firmware).
As you may have noticed, the uk and ur variables store macros for flashing uImage and rootfs with loading them from the [tftp server](https://pjo2.github.io/tftpd64/), specified in the serverip variable. All addresses correspond to the bootargs variable, the contents of which specify the file system layout for the kernel during boot. The layout differs from that usual for goke/hisilicone cameras, our kernel is like lite/fpv, 2 MB in size, but the file system is 8 MB, like ultimate. The remaining ~5 MB are used by the overlay (your changes to the files relative to the original rootfs). For flashing, use the official builds from the [openipc/firmware](https://github.com/OpenIPC/firmware/releases/download/latest/openipc.hi3536dv100-nor-fpv.tgz) release page. The archive contains the kernel and file system.
So, after setting the variables, you can start flashing the rest of the firmware. Start the tftpd server, put uImage.hi3536dv100 and rootfs.squashfs.hi3536dv100 in its root, select the appropriate network interface and run the macro in the bootloader: `run uk`. A number of commands should be executed, from the output of which it should follow that the uImage file has been downloaded and flashed to the flash. Similarly, run `run ur` to flash the rootfs. If the addresses are set correctly, but the download is stuck on "Downloading", change the registrar address to a nearby free one: `setenv ipaddr '192.168.0.223'`.
If everything went without errors, do a `reset` and boot into the operating system, login root, password 12345.
The configs from the hi3536dv100 directory are not relevant, but they may be of interest regarding connecting the tablet via USB/WiFi/Ethernet hotspot, you can transfer them by analogy to the official firmware configs or format them as separate bash scripts. Usually, the essence of these changes is to determine the address of the connected tablet (which is the gateway for the recorder in cases where the tablet is a dhcp server) and specify this address in an additional instance of wfb_rx for the video stream and for telemetry streams.
The firmware update is performed via the Internet using the command `sysupgrade -r -k -n`.
<details>
<summary>Update without Internet from /tmp</summary>
In the future, you can update the firmware of the recorder by uploading the kernel and rootfs to the directory `/tmp` via WinSCP and executing `sysupgrade --kernel=/tmp/uImage.hi3536dv100 --rootfs=/tmp/rootfs.squashfs.hi3536dv100 -z`. The `-z` parameter is needed if you do not have an Internet connection (does not update the sysupgrade script), `-n` will clear the user fs (overlay).
</details>

View File

@ -0,0 +1,117 @@
## Notes on flashing the IVG-G2S camera with OpenIPC firmware.
ATTENTION! Most of the information in this article is hopelessly outdated, all additional steps besides firmware are no longer relevant - they are included in the firmware, and everything works out of the box, you only need to copy the gs.key from the camera to the ground station and specify the correct channels on both.
The purpose of this note is to help draw attention to the extremely promising topic of launching digital fpv on cheap cameras without a single-board computer on board.
Feedback is **VERY** important to developers; if the project is popular, it will develop much faster with their help.
Go to the [telegram chat](https://t.me/+BMyMoolVOpkzNWUy) specially created for this topic, ask questions that are not described here and at the links below, publish information about your successes and request help in solving problems.
Once again - feedback is extremely important, even if you have everything worked out and it works - please, do not be lazy to describe your setup and publish a review in the chat. This will allow the project to develop with the participation of developers.
* [Main page on OpenIPC + FPV topic, must read](https://github.com/OpenIPC/wiki/blob/master/ru/fpv.md)
* [Main project wiki](https://github.com/OpenIPC/wiki) (currently the EN version contains more information)
* [Online instruction generator](https://openipc.org/supported-hardware/featured)
### Terms
* Flash - in this context SPI flash, memory chip.
* U-Boot - bootloader. There is a "native" one, there is one from OpenIPC. The native one is password protected. We need the one downloaded from the instruction generator.
* uImage - Embedded Linux kernel, in the form of a bin file.
* Root-FS - file system of the selected version (lite, ultimate, fpv), in the form of a squash-fs file [https://ru.wikipedia.org/wiki/Squashfs]. uImage and rootfs must be obtained through the instruction constructor, separate firmware u-boot and root-fs.
* Shell - command line of the linux camera, accessible via uart and ssh (putty program). There is also a bootloader shell, only uart. Login root, no password.
* Majestic - utility - video streamer, from the OpenIPC firmware package.
The boards are usually equipped with spi-flash of 8 or 16 MB. The ultimate version requires 16, you can re-solder it. For fpv purposes, 8 MB is enough.
If you don't have an ethernet cable to connect the camera to your switch/router, you can make one from half of a regular patch cord and a jst xh1.25 8pin connector. These were used in Omnibus F4 flight decks and many other places.
The pinouts of the camera and connector are easy to google, you need to connect 4 lines: rx+, rx-, tx+, tx- on the cable and camera. The same connector supplies power from 5 to 12 V to pins 7 (gnd) and 8 (vcc).
I recommend flashing lite first, since it has the shell unlocked via uart (in the /etc/inittab file) and this will allow you to connect in emergency situations, such as when there is no network.
There are three ways to flash the ivg-g2s camera on OpenIPC. In order of complexity: coupler, burn, programmer.
- Coupler [https://github.com/OpenIPC/coupler] - this is loading the kernel and rootfs with one file through the camera's native web interface. Cons - the native password does not change
bootloader, can only be done once, rollback or change of firmware only through other methods.
Algorithm: find out the version in the native web interface, download the firmware based on it, download it as an update in the native web interface. For ivg-g2s/659A7 there is [firmware with bootloader](gk7205v200/659A7_OpenIPC_FPV.bin).
- Burn [https://github.com/OpenIPC/burn] - loading an unprotected u-boot bootloader from OpenIPC via the camera's uart and uart-usb adapter (for example, ch340) and further work in the bootloader, according to the OpenIPC instruction designer.
There are no downsides, the bootloader changes, which allows you to download the required image from the tftpf server [https://pjo2.github.io/tftpd64/] at any time and flash it into flash.
The algorithm is described in video instructions on the OpenIPC channel [https://www.youtube.com/@openipc/videos]. Next, having loaded the bootloader into RAM (only [choose your own](gk7205v200_u-boot-7502v200-for-telemetry.md) due to the nuances), we work through the instruction designer. Unpack uImage and root-fs and put them in the tftpd directory.
I tried to forward usb-uart to archlinux under virtualbox and use burn from there, but the loading did not work, the connection with uart was one-way, only for reading. From windows 7 everything went normally.
Use short wires both from the USB port to the adapter and from the adapter to the camera. The pinout of the uart on the camera is in the first article from the list above, you need to connect "crosswise" - tx adapter to rx camera and rx adapter to tx camera.
If everything is OK, but tftp does not download the file - try changing the camera address to a nearby free one, `setenv ipaddr '192.168.0.223'`.
- Programmer - soldering out the flash or one leg and connecting to the programmer, flashing everything through the programmer.
The most difficult method, this is the only downside.
On first boot you need to run the firstboot command.
If the camera reboots cyclically, it is the watchdog from majestic (streamer). Most likely, you need to remove the lens cap and turn on the light. It is disabled in /etc/majestic.yaml, kill the process quickly: `killall majestic`.
You can manage the config parameters with saving via the cli shell utility:
```
cli -s .image.contrast 50
cli -s .image.luminance 50
cli -s .video0.codec h264
cli -s .hls.enabled false
cli -s .isp.sensorConfig /etc/sensors/imx307_i2c_2l_1080p.ini
cli -s .video0.size 1920x1080
cli -s .video0.fps 30
```
I recommend running these commands, this will set up majestic for initial attempts.
Switch to FPV version with update. Attention! In FPV version shell via uart is disabled (freed for telemetry work), after loading, only network access remains. The bootloader itself, of course, works via uart.
```
sed -i 's/BUILD_OPTION=lite/BUILD_OPTION=fpv/' /etc/os-release
sysupgrade --force_ver -k -r -n
```
If you don't plan to use telemetry through this video link, you can turn it back on:
```
sed -i 's/#console::respawn:\/sbin\/getty/console::respawn:\/sbin\/getty/' /etc/inittab
reboot
```
If the flash is locked (you somehow flashed the kernel of previous versions that cannot unlock the flash), then this and any other commands will not be executed.
Example output of `dmesg | grep bsp-sfc` to determine if a flash drive is locked:
Unlocked
```
bsp-sfc bsp_spi_nor.0: SR1:[02]->[00]
bsp-sfc bsp_spi_nor.0: SR2:[02]->[00]
bsp-sfc bsp_spi_nor.0: all blocks are unlocked.
bsp-sfc bsp_spi_nor.0: Winbond: SR1 [], SR2 [QE], SR3 [DRV0,DRV1]
```
Blocked
```
bsp-sfc bsp_spi_nor.0: SR1:[02]->[00]
bsp-sfc bsp_spi_nor.0: SR2:[02]->[00]
bsp-sfc bsp_spi_nor.0: all blocks are unlocked.
bsp-sfc bsp_spi_nor.0: Winbond: SR1 [TB], SR2 [QE], SR3 [WPS,DRV0,DRV1]
```
Trying to unlock flash from shell (didn't help me)
```
devmem 0x10010024 32 0x06;devmem 0x10010030 32 0;devmem 0x1001003C 32 0x81;devmem 0x14000000 16 0x0000;devmem 0x10010024 32 0x01;devmem 0x10010030 32 0;devmem 0x10010038 32 2;devmem 0x1001003C 32 0xA1
#
sysupgrade --force_ver -k -r -n
```
The way to unlock flash is through loading a fresh kernel, unpacked by the archiver from a tgz file with the kernel and rootfs, taken from the instruction designer. After loading, it automatically unlocks flash. It is made from the bootloader, poured into RAM via burn.
```
# Set the camera address and the tftpd server address
setenv ipaddr 192.168.0.222; setenv serverip 192.168.0.107
# Set environment arguments (env)
setenv bootargs 'mem=32M console=ttyAMA0,115200 panic=20 rootfstype=squashfs root=/dev/mtdblock3 init=/init mtdparts=sfc:256k(boot),64k(env),2048k(kernel),5120k(rootfs) ,-(rootfs_data)'
# Clear the RAM area for kernel download
mw.b 0x42000000 ff 1000000
# Loading the uImage.gk7205v200 kernel from the tftpd server
tftpboot 0x42000000 uImage.${soc}
# Launch the kernel
bootm 0x42000000
```

View File

@ -0,0 +1,47 @@
## Setting up buttons with their own functionality on the recorder
![front_panel](https://github.com/OpenIPC/sandbox-fpv/raw/master/notes_files/IMG_20230323_081622_212.jpg)
The recorder has a connector on board for connecting a front panel with buttons, an IR receiver:
![nvr-ports](notes_files/photo_2023-03-23_02-12-40.jpg)
The cn5 connector is signed on the back. The purpose of +3.3v and GND is clear, IR could not be used, the remaining pins lead to the processor GPIO:
```
Y2 ^17
Y1 ^6
X2 ^13
Y3 ^8
X1 ^7
ALARM 10
REC 11
```
The symbol `^` means a pull-up resistor to +3.3, which means these pins need to be shorted to GND with the button and the value 0 should be caught. This is implemented in the file [`root/gpio_monitor.sh`](hi3536dv100/root/gpio_monitor.sh).
When pin Y1 is shorted to ground, it restarts the [wfb](hi3536dv100/etc/init.d/S98wfb) service, which then restarts [telemetry](hi3536dv100/usr/bin/telemetry), for more convenient connection of a smartphone or tablet [via USB](usb-tethering.md), or after changing the wifi adapter. The monitoring script keeps a log of clicks, which can be observed by `tail -f /tmp/gpio.log`.
Examples of using GPIO output can be found in [`testgpio.sh`](hi3536dv100/root/testgpio.sh), and you can connect the ALARM or REC pin to a low-power LED with a resistor to indicate processes, such as restarting wfb-ng as done in `gpio_monitor.sh`.
To run the monitor as a system daemon, we will create the file [`/etc/init.d/S99gpio_monitor`](hi3536dv100/etc/init.d/S99gpio_monitor) from where we will run our [`root/gpio_monitor.sh`](hi3536dv100/root/gpio_monitor.sh):
```
#!/bin/sh
#
# Start gpio monitor
#
case "$1" in
start)
echo "Starting gpio_monitor daemon..."
/root/gpio_monitor.sh &
;;
stop)
echo "Stopping gpio_monitor daemon..."
kill -9 $(pidof {exe} ash /root/gpio_monitor.sh)
;;
*)
echo "Usage: $0 {start|stop}"
exit 1
esac
```
We reboot without a wifi adapter and/or usb modem, activate them after booting and make sure that by pressing the button (hold it for at least half a second) the services start.
The list of running processes can always be viewed using the command `ps axww`.

View File

@ -0,0 +1,10 @@
## Connecting a tablet or phone via a USB-ethernet device.
The device is a network card connected via USB to the tablet and looks something like this:
![usb-ethernet.png](https://github.com/OpenIPC/sandbox-fpv/raw/master/notes_files/usb-ethernet.png)
It is connected to the recorder via an ethernet cable, after which in [`/etc/wfb.conf`](hi3536dv100/etc/wfb.conf) `udp_addr=auto` is specified instead of a fixed address. On the tablet itself, the "Ethernet-modem" function must be enabled
in the settings "Network and Internet > Access point and modem".
Then everything will be done by the services [`/usr/bin/wifibroadcast`](hi3536dv100/usr/bin/wifibroadcast) and [`/usr/bin/telemetry`](hi3536dv100/usr/bin/telemetry) when loading the recorder or restarting from the [front-panel](nvr_gpio.md).

View File

@ -0,0 +1,87 @@
### Installing usb_modeswitch on a camera with fpv, lite and NVR hi3536[ed]v100 firmware
We check with the e3372h modem.
Camera:
```
curl -o /usr/sbin/usb_modeswitch http://fpv.openipc.net/files/usb-modeswitch/musl/usb_modeswitch && chmod +x /usr/sbin/usb_modeswitch
curl -o /usr/lib/libusb-1.0.so.0.3.0 http://fpv.openipc.net/files/usb-modeswitch/musl/libusb-1.0.so.0.3.0 && chmod +x /usr /lib/libusb-1.0.so.0.3.0
ln -s -f /usr/lib/libusb-1.0.so.0.3.0 /usr/lib/libusb-1.0.so
ln -s -f /usr/lib/libusb-1.0.so.0.3.0 /usr/lib/libusb-1.0.so.0
```
NVR:
```
ntpd-Nnq
curl -k -L -o /usr/sbin/usb_modeswitch https://github.com/OpenIPC/sandbox-fpv/raw/master/usb-modeswitch/musl/usb_modeswitch && chmod +x /usr/sbin/usb_modeswitch
curl -k -L -o /usr/lib/libusb-1.0.so.0.3.0 https://github.com/OpenIPC/sandbox-fpv/raw/master/usb-modeswitch/musl/libusb-1.0.so .0.3.0 && chmod +x /usr/lib/libusb-1.0.so.0.3.0
ln -s -f /usr/lib/libusb-1.0.so.0.3.0 /usr/lib/libusb-1.0.so
ln -s -f /usr/lib/libusb-1.0.so.0.3.0 /usr/lib/libusb-1.0.so.0
ln -s -f /lib/libc-2.32.so /lib/libc.so
```
<details>
<summary>alternative storage</summary>
```
curl -o /usr/sbin/usb_modeswitch http://fpv.openipc.net/files/usb-modeswitch/glibc/usb_modeswitch && chmod +x /usr/sbin/usb_modeswitch
curl -o /usr/lib/libusb-1.0.so.0.3.0 http://fpv.openipc.net/files/usb-modeswitch/glibc/libusb-1.0.so.0.3.0 && chmod +x /usr /lib/libusb-1.0.so.0.3.0
ln -s -f /usr/lib/libusb-1.0.so.0.3.0 /usr/lib/libusb-1.0.so
ln -s -f /usr/lib/libusb-1.0.so.0.3.0 /usr/lib/libusb-1.0.so.0
ln -s -f /lib/libc-2.32.so /lib/libc.so
```
</details>
We enter this text for e3372h into the file `/etc/network/interfaces.d/eth1` (we will create the file if it does not exist):
```
auto eth1
iface eth1 inet dhcp
pre-up sleep 4
pre-up if [ ! -z "`lsusb | grep 12d1:1f01`" ]; then usb_modeswitch -v 0x12d1 -p 0x1f01 -J; fi
pre-up if [ ! -z "`lsusb | grep 12d1:14dc`" ]; then modprobe usbserial vendor=0x12d1 product=0x14dc; fi
pre-up modprobe rndis_host
pre-up sleep 2
```
We jerk the modem, try `ifup eth1` or reboot. If the network has risen (there is eth1 in `ip a`), in interfaces we can replace manual with auto.
#### Problems
If usb_modeswitch switched the modem to cdc_ethernet, then when rebooting the system, for example, via reboot, the interface does not come up - error ip: SIOCGIFFLAGS: No such device. Therefore, if you need to completely reboot the system for the modem to work, you need to disconnect the power supply to the modem before rebooting.
### Result
The e3372h modem with hilink firmware should be displayed as the eth1 network interface and, with a working SIM card inserted, distribute the Internet to the camera:
```
Trying to send message 1 to endpoint 0x01 ...
OK, message successfully sent
Read the response to message 1 (CSW) ...
Device seems to have vanished after reading. Good.
Device is gone, skip any further commands
-> Run lsusb to note any changes. Bye!
udhcpc: started, v1.36.0
udhcpc: broadcasting discover
udhcpc: broadcasting discover
udhcpc: broadcasting discover
udhcpc: broadcasting discover
udhcpc: broadcasting select for 192.168.8.100, server 192.168.8.1
udhcpc: lease of 192.168.8.100 obtained from 192.168.8.1, lease time 86400
deleting routers
adding dns 192.168.8.1
adding dns 192.168.8.1
OK
```
ifconfig:
```
eth1 Link encap:Ethernet HWaddr 0C:5B:8F:27:9A:64
inet addr:192.168.8.100 Bcast:192.168.8.255 Mask:255.255.255.0
inet6 addr: fe80::e5b:8fff:fe27:9a64/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:34 errors:0 dropped:0 overruns:0 frame:0
TX packets:806 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueue:1000
RX bytes:4557 (4.4 KiB) TX bytes:822513 (803.2 KiB)
```

View File

@ -0,0 +1,24 @@
## Connecting a smartphone or tablet on android for FPV-VR and other GS programs to NVR via USB
USB Tethering, also known as USB Ethernet, is an Android OS function for using a phone as a USB modem, which appears as a network card. This allows us to connect the phone and NVR with a regular USB cable and get a fast network between them. Unfortunately, in most cases, USB terhering is only available on tablets with a SIM card module. If you do not have one, and the USB modem is not activated, you will have to connect via [usb-ethernet](usb-eth-modem.md) or [wifi](note-nvr-tab-ap.md).
You need to [install](notes_start_hi3536ev100.md#L47) [kernel](hi3536dv100/uImage.hi3536dv100) and [rootfs](hi3536dv100/rootfs.squashfs.hi3536dv100) with rndis_host support and upload [`/usr/bin/wifibroadcast`](hi3536dv100/usr/bin/wifibroadcast), [`/usr/bin/telemetry`](hi3536dv100/usr/bin/telemetry), and add the following to [`interfaces`](hi3536dv100/etc/network/interfaces):
```
#USB Tethering
auto usb0
iface usb0 inet dhcp
pre-up modprobe rndis_host
pre-up sleep 4
```
To enable you need to:
* Connect your smartphone or tablet with a cable to the disconnected recorder
* Go to settings - Network and Internet - Access point and modem
* Turn on the recorder
* As soon as the USB modem item appears active in the Android menu, enable it.
* Launch FPV-VR, select the Manually (stream) section in the settings, set the video settings to the codec used (rtp/264, rtp/265) and telemetry settings to mavlink.
* Exit settings and run "Start video and osd".
Alternatively, you can use the QOpenHD application with similar functionality.
Also available [option without restarting](nvr_gpio.md) of the recorder.

View File

@ -0,0 +1,46 @@
## Using the hardware as a joystick to transmit RC channels via mavlink
### Theory
Ground station programs such as Mission Planner or QGroundControl are able to recognize connected joysticks or hardware in USB joystick mode and
transmit axis values to the flight controller in the RC_CHANNELS_OVERRIDE packet (#70). However, QGC only transmits the first 4 channels (two axes), the rest can only be assigned to buttons,
and MP can do it only under Windows, which is not always convenient. I wrote a simple application for the recorder, which recognizes the connected joystick and sends [RC_CHANNELS_OVERRIDE](https://mavlink.io/en/messages/common.html#RC_CHANNELS_OVERRIDE) packets in the mavlink protocol version 2 for supporting 18 channels directly to the telemetry_tx port, which is usually published on 127.0.0.1:14650 of the recorder. The port, address, time between sending packets, the number of axes and the device in the system can be reassigned, see `rcjoystick -h`.
```
Usage:
[-v] verbose;
[-d device] default '/dev/input/js0';
[-a addr] ip address send to, default 127.0.0.1;
[-p port] udp port send to, default 14650;
[-t time] update RC_CHANNEL_OVERRIDE time in ms, default 50;
[-x axes_count] 2..9 axes, default 5, other channels mapping to js buttons from button 0;
[-r rssi_channel] store rx packets per second value to this channel, default 0 (disabled);
[-i interface] wlan interface for rx packets statistics, default wlan0;
```
For example, you can send not to telemetry_tx, but to mavlink_routerd, if you need it that way. Package for building in buildroot from OpenIPC [here](rcjoystick).
### Let's launch
We need a kernel and rootfs with usb-hid support on the recorder. To do this, [flash](notes_start_hi3536ev100) them from the [`/hi3536dv100`](hi3536dv100) directory.
~~You need to ensure that the `hid-generic.ko` module is running, to do this, add `modprobe hid-generic.ko` to [`S95hisilicon`](hi3536dv100/etc/init.d/S95hisilicon).~~ In a freshly built kernel, the `hid-generic.ko` module is loaded automatically.
Next, you need to copy the binary [`rcjoystick`](hi3536dv100/usr/bin/rcjoystick) to the /usr/bin registrar, via WinSCP and assign execution rights: `chmod +x /usr/bin/rcjoystick`.
Reboot, connect the equipment to the recorder via USB and try to run `rcjoystick -v` in the console. If everything went well, then on the screen we should see the values of the axes when changing the position of the sticks and switches, and in the telemetry program, for example in QGC (analyse tools > Mavlink inspector > RC_CHANNELS_RAW) the channels should change. To run it permanently, you can register it in a separate service [`S99rcjoystick`](hi3536dv100/etc/init.d/S99rcjoystick), the main thing is that it starts after wifibroadcast.
### RSSI
Also in rcjoystick was added the function of injection of the analog of rssi (number of received from the air part of packets per second) for at least some indicator of reception quality, since there is no desire and sense to start a separate service for this, considering the low level of the registrar. In rcjoystick there is already most of what is necessary for injection.
We specify `-r 16` and, if the wfb interface is not wlan0, then its `-i wlanX` and the number of packets received by the ground per second will fall into the specified channel. For me it is around 800, you can see yours by using the verbose key (`-v`). Then we specify on the flight controller:
```
RSSI_TYPE 2
RSSI_CHANNEL 16
RSSI_CHAN_LOW 0
RSSI_CHAN_HIGH 800 //your normal value, roughly average, not maximum or minimum.
```
The value will be sent to the flight controller, where it will process it and set 0..99 in rssi.
The project is still in the testing stage, so [send](https://t.me/+BMyMoolVOpkzNWUy) your feedback on attempts and wishes.
### Current issues
Sometimes short freezes are observed if you actively hammer both sticks in all directions. Debug says that the driver does not receive any movement events at this time. This effect is not observed if you use a joystick "radio extender" (sbus-to-usb-joystick) in the form of an arduino pro micro, which parses SBUS from your receiver and translates it into a usb-hid-joystick.

View File

@ -0,0 +1,10 @@
## Подключение планшета или телефона по usb-ethernet устройству.
Устройство являет собой сетевую карту, подключаемую по usb к планшету, и выглядит примерно так:
![usb-ethernet.png](https://github.com/OpenIPC/sandbox-fpv/raw/master/notes_files/usb-ethernet.png)
Оно подключается к регистратору посредством ethernet-кабеля, после чего в [`/etc/wfb.conf`](hi3536dv100/etc/wfb.conf) указывается `udp_addr=auto` взамен фиксированного адреса. На самом планшете нужно включить функцию "Ethernet-modem"
в настройках "Сеть и интернет > Точка доступа и модем".
Далее все сделают сервисы [`/usr/bin/wifibroadcast`](hi3536dv100/usr/bin/wifibroadcast) и [`/usr/bin/telemetry`](hi3536dv100/usr/bin/telemetry) при загрузке регистратора или перезапуске с [front-panel](nvr_gpio.md).

View File

@ -0,0 +1,87 @@
### Установка usb_modeswitch на камеру с прошивкой fpv, lite и NVR hi3536[ed]v100
Проверяем с модемом e3372h.
Камера:
```
curl -o /usr/sbin/usb_modeswitch http://fpv.openipc.net/files/usb-modeswitch/musl/usb_modeswitch && chmod +x /usr/sbin/usb_modeswitch
curl -o /usr/lib/libusb-1.0.so.0.3.0 http://fpv.openipc.net/files/usb-modeswitch/musl/libusb-1.0.so.0.3.0 && chmod +x /usr/lib/libusb-1.0.so.0.3.0
ln -s -f /usr/lib/libusb-1.0.so.0.3.0 /usr/lib/libusb-1.0.so
ln -s -f /usr/lib/libusb-1.0.so.0.3.0 /usr/lib/libusb-1.0.so.0
```
NVR:
```
ntpd -Nnq
curl -k -L -o /usr/sbin/usb_modeswitch https://github.com/OpenIPC/sandbox-fpv/raw/master/usb-modeswitch/musl/usb_modeswitch && chmod +x /usr/sbin/usb_modeswitch
curl -k -L -o /usr/lib/libusb-1.0.so.0.3.0 https://github.com/OpenIPC/sandbox-fpv/raw/master/usb-modeswitch/musl/libusb-1.0.so.0.3.0 && chmod +x /usr/lib/libusb-1.0.so.0.3.0
ln -s -f /usr/lib/libusb-1.0.so.0.3.0 /usr/lib/libusb-1.0.so
ln -s -f /usr/lib/libusb-1.0.so.0.3.0 /usr/lib/libusb-1.0.so.0
ln -s -f /lib/libc-2.32.so /lib/libc.so
```
<details>
<summary>альтернативное хранилище</summary>
```
curl -o /usr/sbin/usb_modeswitch http://fpv.openipc.net/files/usb-modeswitch/glibc/usb_modeswitch && chmod +x /usr/sbin/usb_modeswitch
curl -o /usr/lib/libusb-1.0.so.0.3.0 http://fpv.openipc.net/files/usb-modeswitch/glibc/libusb-1.0.so.0.3.0 && chmod +x /usr/lib/libusb-1.0.so.0.3.0
ln -s -f /usr/lib/libusb-1.0.so.0.3.0 /usr/lib/libusb-1.0.so
ln -s -f /usr/lib/libusb-1.0.so.0.3.0 /usr/lib/libusb-1.0.so.0
ln -s -f /lib/libc-2.32.so /lib/libc.so
```
</details>
Вносим этот текст для e3372h в файл `/etc/network/interfaces.d/eth1` (создадим файл если отсутствует):
```
auto eth1
iface eth1 inet dhcp
pre-up sleep 4
pre-up if [ ! -z "`lsusb | grep 12d1:1f01`" ]; then usb_modeswitch -v 0x12d1 -p 0x1f01 -J; fi
pre-up if [ ! -z "`lsusb | grep 12d1:14dc`" ]; then modprobe usbserial vendor=0x12d1 product=0x14dc; fi
pre-up modprobe rndis_host
pre-up sleep 2
```
Передергиваем модем, пробуем `ifup eth1` или перезагружаем. Если сетевая поднялась (есть eth1 в `ip a`), в interfaces можем manual заменить на auto.
#### Проблемы
Если usb_modeswitch произвел переключение модема в cdc_ethernet, то при перезагрузке системы например через reboot интерфейс не поднимается - ошибка ip: SIOCGIFFLAGS: No such device. Поэтому если нужно полностью перегрузить систему чтобы модем заработал, нужно рвать питание модема перед перезагрузкой.
### Результат
Модем e3372h с прошивкой hilink должен отобразиться сетевым интерфейсом eth1 и при вставленной работоспособной sim-карте раздавать интернет на камеру:
```
Trying to send message 1 to endpoint 0x01 ...
OK, message successfully sent
Read the response to message 1 (CSW) ...
Device seems to have vanished after reading. Good.
Device is gone, skip any further commands
-> Run lsusb to note any changes. Bye!
udhcpc: started, v1.36.0
udhcpc: broadcasting discover
udhcpc: broadcasting discover
udhcpc: broadcasting discover
udhcpc: broadcasting discover
udhcpc: broadcasting select for 192.168.8.100, server 192.168.8.1
udhcpc: lease of 192.168.8.100 obtained from 192.168.8.1, lease time 86400
deleting routers
adding dns 192.168.8.1
adding dns 192.168.8.1
OK
```
ifconfig:
```
eth1 Link encap:Ethernet HWaddr 0C:5B:8F:27:9A:64
inet addr:192.168.8.100 Bcast:192.168.8.255 Mask:255.255.255.0
inet6 addr: fe80::e5b:8fff:fe27:9a64/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:34 errors:0 dropped:0 overruns:0 frame:0
TX packets:806 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:4557 (4.4 KiB) TX bytes:822513 (803.2 KiB)
```

View File

@ -0,0 +1,25 @@
## Подключение смартфона или планшета на android для FPV-VR и прочих программ GS к NVR по usb
USB Tethering, он же USB Ethernet - функция ОС Android для использования телефона в качестве USB-модема, представляющегося сетевой картой. Нам это дает возможность соединить телефон и NVR обычным usb-проводом и получить между ними быструю сеть. К сожалению, в большинстве случаев usb terhering доступен только на планшетах с модулем sim-карты. Если у вас его нет, и usb-модем не активируется, придется подключаться по [usb-ethernet](usb-eth-modem.md) или [wifi](note-nvr-tab-ap.md).
Нужно [установить](notes_start_hi3536ev100.md#L47) [ядро](hi3536dv100/uImage.hi3536dv100) и [rootfs](hi3536dv100/rootfs.squashfs.hi3536dv100) с поддержкой rndis_host и залить [`/usr/bin/wifibroadcast`](hi3536dv100/usr/bin/wifibroadcast), [`/usr/bin/telemetry`](hi3536dv100/usr/bin/telemetry), и добавить в [`interfaces`](hi3536dv100/etc/network/interfaces) следующее:
```
#USB Tethering
auto usb0
iface usb0 inet dhcp
pre-up modprobe rndis_host
pre-up sleep 4
```
Для включения нужно:
* Подключить смартфон или планшет кабелем к отключенному регистратору
* Зайти в настройки - Сеть и Интернет - Точка доступа и модем
* Включить регистратор
* Как только в меню android появится активным пункт USB-модем, включить его.
* Запустить FPV-VR, выбрать в настройках секцию Manually (stream), установить настройки видео на используемый кодек (rtp/264, rtp/265) и настройки телеметрии на mavlink.
* Выйти из настроек и запустить "Start video and osd".
Альтернативно, можно использовать приложение QOpenHD с аналогичным функционалом.
Также доступен [вариант без перезапуска](nvr_gpio.md) регистратора.