Bsp serial debug android

Bsp serial debug android

Serial Debug Assistant
Версия: v.6.1.1.0

Последнее обновление программы в шапке: 17.03.2020

Описание:
Профессиональное ПО для последовательной отладки.

1. Получите входящие данные из последовательного порта и отобразите их в окне.
2. Режим отображения полученных данных может быть выбран как «строка» или «HEX».
3. Вы можете изменить тип кодировки строки в настройках. Поддерживает кодирование нескольких символов «ASCII», «GB2312», «UNICODE», «UTF-8», «BIG5», «shift_jis»
4. Скорость передачи последовательного порта может быть выбрана от 300 до 1500000 бит / с (аппаратная поддержка требуется для скорости передачи> 115200).
5. Поддержка настраиваемой скорости последовательного порта.
6. Вы можете ввести строку, которую хотите отправить, в поле отправки, а также отправлять и отправлять поддержку для «String» или «HEX».
7. Поддержка расширенных команд, до 600 пользовательских команд.
8. Настройте список команд, чтобы объединить несколько команд для отправки в список. Просто нажмите один раз, чтобы отправить, автоматически выполнить список различных заказов
9. Функция автоматического разбиения кадра, если вы получаете интервал времени между двумя пакетами, будет вставлена в пакет данных после строки следующего пакета данных из новой строки для облегчения наблюдения.
10. Функция отображения формы волны. Данные, отправленные по протоколу, могут отображаться в виде сигнала. И поддерживает функцию просмотра формы волны и функцию скриншота.

Русский интерфейс: Нет

Скачать:
Архив:
Serial Debug Assistant v.6.1.1.0.rar ( 8.63 МБ )

Источник

Bsp serial debug android

Platform-tools: r31.0.3
ADB: 1.0.41 (31.0.3-7562133)
Fastboot: 31.0.3-7562133
Make_f2fs: 1.14.0 (2020-08-24)
Mke2fs: 1.46.2 (28-Feb-2021)
Последнее обновление утилит в шапке: 01.08.2021

ADB (Android Debug Bridge — Отладочный мост Android) — инструмент, который устанавливается вместе с Android-SDK и позволяет управлять устройством на базе ОС Android.
Работает на всех Android-устройствах, где данный функционал не был намеренно заблокирован производителем.
Здесь и далее: PC — ПК, компьютер к которому подключено устройство.
ADB — консольное приложение для PC, с помощью которого производится отладка Android устройств, в том числе и эмуляторов.
Работает по принципу клиент-сервер. При первом запуске ADB с любой командой создается сервер в виде системной службы (демона), которая будет прослушивать все команды, посылаемые на порт 5037.
Официальная страница
ADB позволяет:

  • Посмотреть какие устройства подключены и могут работать с ADB.
  • Просматривать логи.
  • Копировать файлы с/на аппарат.
  • Устанавливать/Удалять приложения.
  • Удалять (очищать) раздел data.
  • Прошивать (перезаписывать) раздел data.
  • Осуществлять различные скрипты управления.
  • Управлять некоторыми сетевыми параметрами.

Поставляется ADB в составе инструментария разработчика Андроид (Android SDK), который, в свою очередь входит в состав Android Studio.

Если что-то неправильно, то в списке подключенных устройств (List of devices attached) будет пусто.

Скрытые команды ADB
adb -d Команда посылается только на устройство подключенное через USB.
Внимание: Выдаст ошибку, если подключено больше одного устройства.

adb -e Команда посылается на устройство в эмуляторе.
Внимание: Выдаст ошибку, если подключено больше одного эмулятора.

adb -s Команда посылается на устройство с указанным серийным номером:

adb -p Команда посылается на устройство с указанным именем:
Если ключ -p не указан, используется значение переменной ANDROID_PRODUCT_OUT.

adb devices Список всех подсоединенных устройств.

adb connect [: ] Подсоединиться к андроид хосту по протококу TCP/IP через порт 5555 (по умолчанию, если не задан).

adb disconnect [ [: ]] Отсоединиться от андроид подключенного через TCP/IP порт 5555 (по умолчанию, если не задан).
Если не задан ни один параметр, отключиться от всех активных соединений.

adb push Копировать файл/папку PC->девайс.

adb pull [ ] Копировать файл/папку девайс->PC.

adb sync [ ] Копировать PC->девайс только новые файлы.
Ключи:
-l Не копировать, только создать список.

adb shell Запуск упрощенного unix shell.
Примеры использования

adb emu Послать команду в консоль эмулятора

adb install [-l] [-r] [-s] Послать приложение на устройство и установить его.
Пример: adb install c:/adb/app/autostarts.apk Установить файл autostarts.apk лежащий в папке /adb/app/ на диске с:
Ключи:
-l Блокировка приложения
-r Переустановить приложение, с сохранением данных
-s Установить приложение на карту памяти
Установка split apk

adb uninstall [-k] Удаление приложения с устройства.
Ключи:
-k Не удалять сохраненные данные приложения и пользователя.

adb wait-for-device Ждать подключения устройства.

adb start-server Запустить службу/демон.

adb kill-server Остановить службу/демон.

adb get-state Получить статус:
offline Выключен.
bootloader В режиме начальной загрузки.
device В режиме работы.

adb get-serialno Получить серийный номер.

adb status-window Непрерывный опрос состояния.

adb remount Перемонтировать для записи. Требуется для работы скриптов, которые изменяют данные на.

adb reboot bootloader Перезагрузка в режим bootloader.

adb reboot recovery Перезагрузка в режим recovery.

adb root Перезапуск демона с правами root

adb usb Перезапуск демона, прослушивающего USB.

adb tcpip Перезапуск демона, прослушивающего порт TCP.

adb ppp [параметры] Запуск службы через USB.
Note: you should not automatically start a PPP connection. refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1
Параметры:
defaultroute debug dump local notty usepeerdns

FastBoot — консольное приложение для PC. Используется для действий над разделами

fastboot devices Список присоединенных устройств в режиме fastboot.
fastboot flash Прошивает файл .img в раздел устройства.

fastboot erase Стереть раздел.
Разделы: boot, recovery, system, userdata, radio
Пример: fastboot erase userdata Стирание пользовательских данных.

Читайте также:  Vertu aster обновление android

fastboot update Прошивка из файла имя_файла.zip

fastboot flashall Прошивка boot + recovery + system.

fastboot getvar Показать переменные bootloader.
Пример: fastboot getvar version-bootloader Получить версию bootloader.

fastboot boot [ ] Скачать и загрузить kernel.

fastboot flash:raw boot [ ] Создать bootimage и прошить его.

fastboot devices Показать список подключенных устройств.

fastboot continue Продолжить с автозагрузкой.

fastboot reboot Перезагрузить аппарат.

f astboot reboot-bootloader Перезагрузить девайсв режим bootloader.
Перед командами fastboot можно использовать ключи:
-w стереть данные пользователя и кэш
-s Указать серийный номер устройства.
-p

Указать название устройства.
-c Переопределить kernel commandline.
-i Указать вручную USB vendor id.
-b Указать в ручную базовый адрес kernel.
-n

Указать размер страниц nand. по умолчанию 2048.

Команду logcat можно использовать с машины разработки
$ adb logcat
или из удаленного shell
# logcat Каждое сообщение лога в Android имеет тэг и приоритет
Тэг – это строка указывающая компонент системы, от которого принято сообщение (например: View для системы view)
Приоритет – имеет одно из нижеследующих значений (в порядке от меньшего к большему):
V — Verbose (Низший приоритет).
D — Debug
I — Info
W — Warning
E — Error
F — Fatal
S — Silent (Наивысший приоритет, при котором ничего не выводится).

Получить список тэгов, используемых в системе, вместе с их приоритетами можно запустив logcat. В первых двух столбцах каждого из выведенных сообщений будут указаны / .
Пример выводимого logcat сообщения:
I/ActivityManager( 585): Starting activity: Intent

Для уменьшения вывода лога до приемлемого уровня нужно использовать выражения фильтра. Выражения фильтра позволяют указать системе нужные комбинации и , остальные сообщения система не выводит.
Выражения фильтра имеют следующий формат : . где указывает нужный тэг, указывает минимальный уровень приоритета для выбранного тэга. Сообщения с выбранным тэгом и приоритетом на уровне или выше указанного записываются в лог. Можно использовать любое количество пар : в одном выражении фильтра. Для разделения пар : используется пробел.

Пример ниже выводит в лог все сообщения с тэгом «ActivityManager» с приоритетом «Info» или выше, и сообщения с тэгом «MyApp» и приоритетом «Debug» или выше:
adb logcat ActivityManager:I MyApp:D *:S
Последний элемент в выражении фильтра *:S устанавливает приоритет «silent» для всех остальных тэгов, тем самым обеспечивая вывод сообщений только для «View» и «MyApp». Использование *:S – это отличный способ для вывода в лог только явно указанных фильтров (т.е. в выражении фильтра указывается «белый список» сообщений, а *:S отправляет все остальное в «черный список»).

При помощи следующего выражения фильтра отображаются все сообщения с приоритетом «warning» или выше для всех тэгов:
adb logcat *:W

Если logcat запускается на машине разработчика (не через удаленный adb shell), можно также установить значение выражения фильтра по умолчанию задав переменную окружения ANDROID_LOG_TAGS:
export ANDROID_LOG_TAGS=»ActivityManager:I MyApp:D *:S»

Следует обратить внимание что задав переменную окружения ANDROID_LOG_TAGS она не будет работать в эмуляторе/устройстве, если вы будете использовать logcat в удаленном shell или используя adb shell logcat.
Вышеописанная команда export работает в ОС *nix и не работает в Windows.

Контроль формата вывода лога

Сообщения лога в дополнение к тэгу и приоритету содержат несколько полей метаданных. Можно изменять формат вывода сообщений показывая только конкретные поля метаданных. Для этого используется параметр -v и указывается один из ниже перечисленных форматов вывода.

brief Показывать приоритет/тэг и PID процесса (формат по умолчанию).
process Показывать только PID.
tag Показывать только приоритет/тэг.
thread Показывать только процесс:поток и приоритет/тэг.
raw Показать необработанное сообщение, без полей метаданных.
time Показывать дату, время вызова, приоритет/тэг и PID процесса.
long Показывать все поля метаданных и отдельно сообщения с пустыми строками.

При запуске logcat можно указать формат вывода используя параметр -v:
adb logcat [-v

Источник

How to debug your Linux BSP

Mar 14, 2019 · 8 min read

Getting to the U-Boot command line

Getting to the U-Boot command line is fundamental, a whole host of things must be correct to get there. Clocks, memory, serial…: these are some of the things that need to be working before you talk to your board at all.

To debug quickly, try to create an environment where you can test successive U-Boot images with a fast turnaround. Debugging is the act of gaining more information, and at this stage the only tool you have is re-compiling, re-flashing (re-loading?), and re-running U-Boot. Create a setup that does all these things efficiently.

K e ep notes of what you are doing, constantly going round the cycle of debug and not getting far can turn you stir crazy at times, and make you forget things you’ve seen. Let’s begin at the worst case:

Nothing is printed on the serial port

The first board arrives. You’ve tested that the power rails all come on OK. You connect the serial port, load U-Boot, cross your fingers and turn on the board. And… nothing, not a single character is printed.

The first thing to do is to try and turn on an LED. Find a section of code that is executed early, before the serial console is even brought up, and use it to turn on an LED (just use a raw memory access). If it works, great! If not then try moving it back through the execution chain as early as possible. If this doesn’t work, then U-Boot probably isn’t being loaded at all, and you need to consult your CPU documentation.

Читайте также:  Как ускорить планшет андроид леново

If you can turn on an LED, then maybe your serial port is not being configured correctly. Try turning your LED on after the serial port is configured, is it still turning on? Now you know your serial port initialisation isn’t crashing U-Boot entirely. Double check the serial port being used, double check rates, protocol, flow control. Get an oscilloscope or a logic analyser and test for activity on the lines.

If there is rubbish on the serial port, then perhaps there is an issue with the PLL configuration. Or the signal is inverted. Or you are just seeing noise from moving the connectors. Is the outputted signal transmitted as TTL or RS-232?
Once you have some sort of serial port communication established, things get a bit easier:

Prints stop short of reaching the command line

So there are prints occurring on the serial port, but it stops short of reaching the command prompt. Communication with your board is still a one-way street.

The only thing to do now is to determine why it stops there. The most important information is the last thing to be printed. By searching the source code, you should be able to find out where a certain string is printed. You will become adept at this skill through practise, which you will need as it is fundamental to debugging Linux BSPs (U-Boot and the Linux Kernel).

Once you have located the source of the last print, you will want to add more prints later in the execution chain. This will help you to gain more information about why the prints mysteriously stop working. The approach can almost always be used to reduce the possible location of the error to a single statement if required. It is time consuming, but this is why setting up your working environment to be efficient to this purpose is so important.

Eventually you will find the source of the issue, perhaps the memory is not being brought up correctly, or maybe a certain peripheral access causes a system wide crash. Be persistent, but remember that sometimes the mere act of adding prints to a system can cause timing changes that will artificially suppress an error. If you have time, always try to understand in full any failure modes that are observed, if you fix them without knowing why, they can sometimes come back to haunt you.

So you’ve reached the command line. But booting Linux does not work as expected. At least now, you can talk to your processor, U-Boot has many useful commands that allow you to probe memory, read filesystems and even fetch files from a network. Some of these commands will be needed to boot Linux, and they may not work for various reasons.

A peripheral needed for boot is not working

To boot Linux, U-Boot will need to find various binaries (kernel, device-tree, filesystem) from somewhere. Generally, this somewhere is some sort of internal storage on the board, but it is just as valid to fetch things off the network.

U-Boot does things a little differently to Linux; for example, U-Boot’s driver support tends to lag a few months behind its bigger brother. Sometimes, your shiny new flash chip is simply not supported in the older version of U-Boot you are using, and you don’t quite realise this until boards are in house.

When this happens, there are a few things you can try. First, check the latest U-Boot upstream source code, things move fast in the open-source world, and you might find a nice new driver to backport. Second, you can try looking at the Linux source code, a driver found here will be a little harder to backport, and it depends on which subsystem the driver is a part of. Some will be easy, some will be next to impossible.

If all else fails, try scouring the internet, it might be the case that someone has submitted a driver for the chip in question, it just hasn’t been accepted and merged in yet. Sometimes this process can take months and then stop simply due to lack of interest on both parties; I have found patches years old that have proven to be useful for my purposes.

U-Boot claims to boot Linux but nothing happens

So, you see “Starting Kernel …” on the serial port from U-Boot, but then nothing happens. Another frustrating problem and it can feel like we’re back where we started with nothing printing on the serial port. To make things worse, we’re now blurring the line between debugging the U-Boot world and debugging the Linux world.

Читайте также:  Android firebase get value

Typically, if there was obviously wrong with the images you have provided, U-Boot will complain noisily, and you will be able to debug the problem. What’s likely happened here is that Linux is booting, but it is not printing to the correct serial console. Double check the boot arguments in U-Boot (sometimes you need to set “console=ttyS0” or equivalent), double-check the kernel configuration you have used to build your kernel. If you have Ethernet enabled, plug in an Ethernet cable and see if the link lights come on, if they do then Linux is booting flawlessly and is only failing to print to the serial console.

Another thing that could be wrong is the LOADADDR specified was wrong. Some setups require you to specify this environmental variable when compiling the Linux kernel. If this is wrong, then U-Boot will quietly pass control to an improperly linked kernel, and the CPU will quickly fall over.
You may need to enable early printing, how you do this is highly dependent on your processor. On ARM you would enable CONFIG_DEBUG_LL. You’ll need to tell the configuration how to access the serial port system, and which one to use. This allow you to use the “early_print” function which should give you prints before the console is enabled. Try adding them into the start_kernel() function found in “init/main.c”.

Linux forever “waiting for root device”

Linux begins booting, you see a whole stream of boot log messages, but then it hangs forever on “Waiting for root device”. The first thing you’ll want to do is check your boot arguments in U-Boot, in a lot of cases, Linux requires U-Boot to tell it which device contains the root partition. It takes some skill and domain knowledge to know what the device will be called, but you can generally work it out either from first principles or trial and error.

For example, if you are booting from eMMC on an iMX6 device, which is attached to MMC port 4 in the hardware manual, and the root partition is number 1, then the boot arguments should contain “root=/dev/mmcblk3p1”. The way of working this out will be different dependent on your design and CPU architecture.

Any other boot problems

If there is any other sort of failure during the boot process, then try to analyse where the error is occurring. It could be a driver initialisation that fails and crashes the whole system. If you are really stuck, remove the driver from the kernel configuration entirely, returning to it at a later date.
The crash could also be occurring in the initscripts, which means your problem is now a combination of user space and kernel space. Try and determine which initscript (typically these are the scripts in /etc/init.d) is being executed as the crash happens.

Debugging drivers after boot

Once Linux is booting fully there is ordinarily still more work to be done getting all your drivers to work. You’ll want to use the same process of re-compile, re-run to find out why something isn’t working. Some drivers you can build as modules, which means you can re-run without having to reboot the board. Use this to your advantage and speed up your debug time.

Asking for help

Sometimes when you have a particularly difficult problem in your Linux BSP that you can’t solve, simply taking a break, or sleeping on it, can be enough to get you going again. Sometimes however, you will need to get help, and there are several ways you can go about this. You could ask a colleague in your organisation to look at it with you; often a second pair of eyes can solve these types of issues. Otherwise, you can look for support online: your CPU manufacturer will most likely have public forums where you can ask questions related to Linux BSP issues, if you think your problem is with the software more than with the chip, you could write an enquiry to the relevant mailing list.

If all else fails it might be worth hiring an expert to look into the issue for you. Here at ByteSnap we have many years expertise working on Linux BSP design, across a wide range of technologies and issues. Often problems can arise again and again in similar ways, and the benefit of experience allows us to identify and quickly solve these. We can also provide off-site specially tailored training on all matters Linux BSP.

Ville is a software engineer at ByteSnap Design, an award winning software and hardware consultancy. He is a graduate of Physics at Warwick University and now specialises in developing device drivers for Embedded Linux applications.

Источник

Оцените статью