The simplest Internet radio column "Kodi" or the salvation of the "Raspberry" brick

The simplest Internet radio column "Kodi" or the salvation of the "Raspberry" brick

Basic prerequisites:

  1. There is an old unused first generation Raspberry Pi board;
  2. The board lies on the cabinet as a dead weight and is not used - the “Brick” board;

What would you like to receive:

  1. At a certain point in time (for example, by mood)
    the board ceases to be a "Brick", and a magic memory card is inserted into it;
  2. An Ethernet cable and a plug from a regular household speaker or headphones are connected to the board;
  3. After energizing the former "Brick" - sings

Main idea:

  1. The minimum number of gestures for any setting, in the most ideal case, we connect only the "Ethernet" cable, power and speakers, and do nothing else, from the word "at all";
  2. For example, we support the former “Brick” out of the box, for example, 20 Internet radio stations, the switching of which in a circle can be hung up by pressing the mouse wheel or on a specific GPIO pin (connect two wires and close them (my dream from childhood));
  3. Control is carried out via a radio channel, and this radio channel can be an ordinary radio mouse;
  4. Take a ready-made system, assemble the distribution kit in the "Yocto Project"
    those. As usual, we will not do anything with you, since everything has already been done.
    (it is enough just to place an outside observer on the other side "TV");

Description

The simplest Internet Radio column "KODI"
Assembly designed for old Raspberry Pi 1 boards
(collecting dust somewhere on the closet, but who are ready to work more)

The m3u8 list of 12 Internet radio stations is used by default.

It is assumed that the board works without an HDMI output, and to turn it off, just unplug the power adapter from the outlet. And as an ultra modern wireless remote control, you can use your super radio mouse (well, or connect a regular gray one with a tail).

When turned on, the network interface is configured by default via the DHCP protocol and the last memorized radio station from the list is played, playback volume is controlled by a regular mouse:
(finally appoint your mouse as "head of management", and congratulate her, she deserves it)

  колесико вперед  - увеличение громкости звука
  колесико назад   - уменьшение громкости звука
  длительное нажатие (3сек и более) на правую кнопку мыши
                   - выбор следующий радиостанции
  длительное нажатие (3сек и более) на левую кнопку мыши
                   - выбор предыдущей радиостанции

To add your own list of Internet radio stations
you can always connect an HDMI cable from your TV
and use the stock Kodi 17.6 GUI
(turn off the board, connect the HDMI and turn on the power adapter)

Kodi main menu => "Add-ons" => "My add-ons"
          => "PVR Clients" => "PVR IPTV Simple Client"

Initial implementation

(possible)
Initially, when I decided to make an "Internet Radio Column", I planned the following:

  • Minimalist console distribution in the Yocto Project;
  • The audio stream is played through GStreamer;
  • The network interface is configured via DHCP;

And this solution has a number of advantages:

  1. Fast enough (exit to the operating mode from power supply 30-40 seconds);
  2. Reliable enough (fewer programs, fewer points of failure);
  3. The console distribution is much easier to put into read-only mode
    those. programs do not write anything to the root filesystem
    (a file system on SDHC media is in my opinion the first candidate for failures);

Note:

    В Yocto перевести корневую файловую систему (rootfs) 
    в режим только чтение можно сделать достаточно просто, 
    изменив один параметр во время сборки 

    Из коробки Yocto предлагает два варианта:
    1) Работа файловой системы в обычном режиме чтение/запись 
    (так работают все дистрибутивы общего назначения, например Ubuntu)
    2) Работа файловой системы в режиме только чтение
    (так работают специализированные дистрибутивы, например в маршрутизаторах)

    В режиме только чтение все каталоги, в которые обычно 
    записываются данные приложений и сервисов во время работы монтируются 
    в оперативную память (например каталог /var/log и т.п.)
    Данные актуальны только для текущего сеанса работы и после сброса питания
    данные теряются.

    Если в Yocto Project вы укажете при сборке использовать "read only", 
    то после сборки ваш дистрибутив будет настроен только на чтение, 
    но вы всегда можете добавить возможность динамического перевода 
    из "read only"  в "read/write", но это уже совсем другая история ...
    

And one major drawback:

"It must be done" i.e. I need to spend N number of evenings
(usually after work, and this is the most inefficient time, at this time the brain no longer thinks, it usually sleeps)

And yet, I wrote my previous article on Habré about the multimedia center Kodi and Yocto project
and the opportunity to continue in the same vein, overcame my exploratory impulse. More on this in the next chapter.

Turning Kodi into an internet radio speaker

To implement the functionality I need, I will add one more method to the distribution build recipe described in the previous article see file berserk-image.bb

GUI_SETTINGS = "home/root/.kodi/userdata/guisettings.xml"

# конфигурация запуска последнего выбранного ТВ канала (1-фон 2-передний план)
F1_LINE = "<startlast default="true">0</startlast>"
R1_LINE = "<startlast>1</startlast>"
# конфигурация вывода звука, всегда подключен только аналоговый аудио выход
F2_LINE = "<audiodevice default="true">PI:HDMI</audiodevice>"
R2_LINE = "<audiodevice>PI:Analogue</audiodevice>"
# так как HDMI по умолчанию не используется отключаю автоматическое обновление
# а то может получиться что питание уехало, а данные остались не записанными
F3_LINE = "<addonupdates default="true">0</addonupdates>"
R3_LINE = "<addonupdates>2</addonupdates>"


# метод отвечает за добавление конфигурации:
# которая превращает "Умный телевизор" в "простую Интернет Радио колонку"
add_radio_guisettings() {
    sed -i "s|${F1_LINE}|${R1_LINE}|" ${IMAGE_ROOTFS}/${GUI_SETTINGS}
    sed -i "s|${F2_LINE}|${R2_LINE}|" ${IMAGE_ROOTFS}/${GUI_SETTINGS}
    sed -i "s|${F3_LINE}|${R3_LINE}|" ${IMAGE_ROOTFS}/${GUI_SETTINGS}
}


FIND_STR = "touch ./tmp/.FIRST_RUN."
SCRIPT_FIRST_RUN = "etc/init.d/first-run.sh"
# так как HDMI выход может не использоваться, 
# то необходимо отключить "стартовое приветствие"
off_kodi_welcome() {
    sed -i "s|${FIND_STR}|#&|" ${IMAGE_ROOTFS}/${SCRIPT_FIRST_RUN}
}

The methods are intended for modifying the root file system before forming the distribution image in the form of a single raw file, which is written to the memory card by the command dd

This is done in this way:
ROOTFS_POSTPROCESS_COMMAND += "add_radio_guisettings; off_kodi_welcome;"

In short, in the main configuration file of Kodi 17.6, “three points” change

  • Launch configuration of the last selected TV channel;
  • Audio output configuration, only analog audio output is always connected;
  • Disabling automatic updates;
  • Note:
        Единственное с чем у меня возникли сложности, 
        это то, что пришлось еще подтащить файл базы данных 
        в формате sqlite => TV29.db, в котором указывается 
        текущий проигрываемый ТВ канал 
        (так как по умолчанию никакой из каналов не выбран), 
        а через xml конфигурацию в Kodi этого не сделать.
        

a more detailed sequence of actions for each item:

1) Click on the "gear" icon in the upper left corner of the screen
and select "PVR and TV settings" (image of a TV with two horns)
further on the left side of the menu, select the "Playback" item, and in the central section "General"
select "Continue from the last channel on startup" in the drop-down list
selecting the "Foreground" setting

or more clearly:

      "Настройки PVR и ТВ" 
       => "Воспроизведение" 
       => "Продолжить с последнего канала при запуске" => "Передний план"

2) Click on the "gear" icon in the upper left corner of the screen and select the item:

       "Системные настройки"  
       => "Дополнения" => "Обновления" => "Никогда не проверять обновления"

3) Click on the "gear" icon in the upper left corner of the screen and select the item:

       "Системные настройки" 
       => "Аудио" => "Устройство вывода звука" => "PI: Analogue"

How I've been watching TV wrong for two years.

I must confess to you that in two years I have not learned how to watch TV properly.

I usually watch TV in the kitchen. A Raspberry Pi 2B board is connected to the TV, and Ethernet and HDMI connectors are connected to the board. The board is powered via a regular USB cable, which is plugged into the TV's USB port. in fact, turning on the TV using the stock remote control also supplies power to the Raspberry Pi board, and turning off the TV from the remote control also immediately resets the power from the Raspberry Pi board.

Yes, I am well aware that this cannot be done, because the root file system of the Kodi multimedia center (ext3) functions in my normal read / write mode. But I'm a lazy person, and for starters, I decided to check how long it takes to turn off the system, until it stops loading at all, but unfortunately for two years I haven't been able to do this (maybe I was just lucky, I don't know ).

And in my opinion, if this mode is suitable for my TV, then it is also suitable for a “simple Internet Radio speaker”, and since I forcibly turned off the automatic updating of Kodi plugins, the probability of a file system failure will become even less. So far I don't see a problem with it.

Note:

    Но вы всегда при желании можете с помощью одной yocto команды 
    IMAGE_FEATURES += "read-only-rootfs"

    и определенной магии перевести ваш дистрибутив в режим "read only"
    

The distribution kit "Internet radio speakers" described in the article is a household one, and what is most important for a household distribution kit is a beautiful GUI. In my opinion, it is very difficult or almost impossible to teach an ordinary user to drive in any incomprehensible magic commands in the console, and he doesn’t even know a word like that. And here is the GUI, please.

And this is perhaps my main argument in favor of a non-console distribution. Kodi's warm lamp GUI, it's not really needed, but it's there.
(I also completely forgot to mention that Kodi can be controlled remotely, for example from a smartphone by installing the Yatse application, and perhaps for someone, this will be a plus)

Kodi configuration, for mouse control

and now rocket

<keymap>
    <global>
        <mouse>
          <wheelup>VolumeUp</wheelup>
          <wheeldown>VolumeDown</wheeldown>
          <middleclick>ChannelDown</middleclick>
          <longclick id="0">ChannelDown</longclick>
          <longclick id="1">ChannelUp</longclick>
          <!-- конфигурационный rocket -->
        </mouse>
    </global>
</keymap>

The configuration overrides global events for the following elements:

  • mouse wheel scroll forward
  • mouse wheel scroll back
  • pressing the middle mouse button
  • processing of a long mouse click (3 seconds or more),
    0 right button id, 1 left button id

more information on configuring mouse events:

kodi.wiki/view/Alternative_keymaps_for_mice
kodi.wiki/view/Action_IDs
kodi.wiki/view/Window_IDs

What to do if the cable system did not come to you

“But I don’t have free Ethernet ports at home (or never had),” some of the happy owners of old Raspberry Pi 1 boards may exclaim (maybe the board was bought for research and remained lying on the closet)

And since there is no built-in Wifi on the board, without an Ethernet connection, it is not very functional.

Of course, the possibility of using the Raspberry Pi 1 board without Ethernet exists, but it will require some effort from you. Usually such things are interesting to do only as part of the study of something new, i.e. this is not a custom job.

So, let's consider a hypothetical use case for a board without Ethernet:

You can connect an external USB - Wifi adapter, guided by the consideration
that the adapter should work well under Linux

Note:

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

    я проверял только следующии модели:
    - WiFi адаптер на чипсете Atheros D-Link DWA-126 802.11n (AR9271)
    - WiFi адаптер NetGear WNDA3200
    - WiFi адаптер NetGear WNA1100
    - WiFi адаптер TP-Link TL-WN722N (AR9271)
    - WiFi адаптер TL-WN322G v3
    - WiFi адаптер TL-WN422G
    - Wifi адаптер Asus USB-N53 chipset Ralink RT3572 
    

If you already have a usb Wifi adapter, you can check if it works well under Linux like this:

  • Install some popular Linux distribution
    general purpose, such as "Ubuntu Desktop"
  • Boot the system
  • Connect your Wifi usb adapter
  • Launch network manager and try to connect to your WiFi hotspot
  • If everything works well and your Internet connection is stable, then your adapter is well supported and you can continue your work on connecting this adapter in a specialized distribution and possibly with other kernel versions
    (if not, then no, alas - it's better not to even try)

Support for external Wifi adapter in "Raspberry PI"

For the WiFi adapter to work correctly in Linux: we need two things:
1) Linux kernel support for specific Wifi adapter
2) The presence in the system of a kernel module for a specific Wifi adapter

Let's take the TP-Link TL-WN722N adapter as an example. He has a great antenna.
Let's find the chipset on which the board works - I have it "AR9271", note:

    что самое интересное, это то, что для одной и той же модели
    одного и того же производителя, чипсет Wifi может отличаться.
    Я например сталкивался с тем, что для TL-WN722N версии 2, 
    используется уже другой чипсет Realtek RTL8188, а он уже 
    плохо работал под Linux (на тот момент), увы такие вот дела, 
    т.е. иногда нужно еще приглядываться к маленьким цифрам 
    версии на обратной (темной) стороне адаптера.    
    

Now let's find the name of the parameter in the kernel configuration responsible for the AR9271 chipset driver, it's best to look for a combination of the words "AR9271 cateee.net"
     where "cateee.net" is a cool site describing Linux kernel module configurations

We immediately find the name of the kernel configuration - CONFIG_ATH9K_HTC
and the name of the kernel module we need ath9k_htc

and then just specify the name of the desired module in the configuration fragment file
Linux kernel => recipes-kernel/linux/files/rbpi.cfg, add the line:
CONFIG_ATH9K_HTC=m

Thus, in the future, you can connect any additional equipment to your system (well, if, of course, it is already supported in the Linux kernel)

What to do if you are a habra geek - constructor

And you create the coolest things like here or you are a student and dream of creating something similar.

Then offhand, you can take some kind of Touch Screen screen for RPI on aliexpress, order a suitable battery there, connect it all to the Raspberry Pi 1,2 or 3 board (better to 3, since it has built-in Wifi), select a graphic design theme interface in Kodi, designed for touch screen and voila => you can get a simple audio player. Of course, it will be quite bulky, but it will be yours.

  Примечание:
  A для того, чтобы собрать Мультимедиа центр Kodi для самой бюджетной платы 
  Raspberry Pi Zero Wifi в yocto вам достаточно изменить две строки:

  конфигурационный файл => build/conf/local.conf
      MACHINE = 'raspberrypi0-wifi'

  рецепт сборки Kodi  => recipes-mediacentre/kodi/kodi_17.bbappend
      EXTRA_OECONF_append = "${@bb.utils.contains('MACHINE', 
                            'raspberrypi0-wifi', '${BS_RPI}',  '', d)}"

  If the responsiveness of the Kodi 17.6 GUI due to one processor core in Zero seems mysterious to you, then you can make a feint with your ears and build an older, but very fast version, for example Kodi 15.2, it is more "friendly" in this regard (sometimes legacy decides everything)

Unfortunately, I don’t have a board, so I can’t check it, but according to my feelings it should work.

Brief Assembly Instructions

    1) Установите зависимости Yocto Project (например в Ubuntu): 
    sudo apt-get install -y --no-install-suggests --no-install-recommends 
        gawk wget git-core diffstat unzip texinfo gcc-multilib build-essential 
        chrpath socat cpio python python3 python3-pip python3-pexpect 
        xz-utils debianutils iputils-ping python3-git python3-jinja2 
        libegl1-mesa libsdl1.2-dev xterm

    2) Скачайте и установите Repo:
        mkdir ~/bin
        curl http://commondatastorage.googleapis.com/git-repo-downloads/repo > ~/bin/repo
        chmod a+x ~/bin/repo

    3) Загрузите проект с github:
        PATH=${PATH}:~/bin
        mkdir radio
        cd radio
        repo init -u https://github.com/berserktv/bs-manifest 
                  -m raspberry/rocko/radio-rpi-0.2.8.xml
        repo sync

    4) Соберите проект:
        ./shell.sh
        bitbake berserk-image
        
    можно тоже самое собрать для плат Raspberry Pi 3B Plus, 3B и 2B:
    repo init -u https://github.com/berserktv/bs-manifest 
              -m raspberry/rocko/radio-0.2.8.xml
    

more detailed assembly instructions
and recording to a microSDHC card, see in the previous article

Postscript

Of course, the idea of ​​​​the Internet radio column is typical, it is known to everyone and on Habré you will find many articles on this subject, for example here

And you might also think that I just adjusted the requirements for a ready-made solution. To this I can retort and say no, honestly honestly.

Mr Ervey's Story

    Хотите верьте, хотите нет, а дело было так:

    Наш рабочий офис граничит с фирмой по производству разного звукового
    оборудования, и однажды директор этой фирмы, назовем его мистер "Эрви"
    подошел к нашему заместителю директора филиала мистеру "Арсению"
    и спросил у него, насколько сложно повесить на плату Raspberry Pi 
    проигрывание звукового потока т.е. плата подключается к сети 
    и колонкам, и "слышен характерный звук".

    После этого мистер Арсений подошел к заместителю моего 
    начальника - мистеру "Борису" и переадресовал вопрос ему, 
    ну а я, как сторонний наблюдатель случайно эту идею запомнил
    и назвал ее "Задача трех начальников".

    В общем хотели как лучше, 
    а получилось, цитата - "Но мистер Эрви, как всегда, помог."

    Через некоторое время я поинтересовался у мистера "Бориса" 
    его мнением по поводу написания небольшой заметки на эту тему 
    на "Хабре", на что "Борис" ответил, что изменение 
    "трех пунктов меню" в Kodi, особо не привносит никакой 
    новой информации и не заслуживает отдельного упоминания. 
    Конечно я с ним полностью согласен и поэтому, я не расскажу ему, 
    что что-то написал по этому поводу.

    Статья написана исключительно для платы "Raspberry Pi 1" 
    взятой у мистера "Бориса" на время эксперимента, 
    совпадения со всеми другими платами "Raspberry Pi 1" случайны.
    

More good and different assemblies for you, and let even the former brick sing for you this year.

Source: habr.com

Add a comment