Skip to content

Adding radio metrics in Prometheus format to the web server at the "/metrics" path#264

Open
omgiafs wants to merge 1 commit into
e2002:mainfrom
omgiafs:add-prometheus-metrics
Open

Adding radio metrics in Prometheus format to the web server at the "/metrics" path#264
omgiafs wants to merge 1 commit into
e2002:mainfrom
omgiafs:add-prometheus-metrics

Conversation

@omgiafs

@omgiafs omgiafs commented Jun 13, 2026

Copy link
Copy Markdown

English

Good day!

Why is this necessary?

Due to network and other errors, the radio may stop playing, switch to another network, etc. To automatically resume playback, you need to send the "play" command. However, before this patch, there was no way to easily (for example, using curl) check the stream's playback status remotely.

I honestly tried to write a script to automate this—connect to telnet, send the cli.info command, and then exit. But I can't send the command via nc (BusyBox), netcat, or ncat.
Using MQTT for this task is overhead. Of course, not if you already have smart home infrastructure, but like many others, I don't.
There is no information about the player's status on the web page.

Based on the above, code was generated using a neural network that adds Prometheus-like metrics. The code doesn't seem to load the CPU; essentially, it writes the values ​​of other variables from memory to a string variable using a timer, without any computation.

Now it is possible to quickly find out the radio status using curl and send the necessary commands using the same curl.

What's added

This patch adds radio metrics in Prometheus format to the /metrics web page.
Metric values ​​are periodically collected into a string variable, and the string containing the metrics is displayed on the web page. The process is asynchronous, meaning metric values ​​are not requested during the page request; the web server returns cached data.
The default metrics update interval is 5 seconds. I don't see the point in doing it more often than that.

‼️The code was generated using a neural network. With many code fixes applied made by human... 😰
Nevertheless, the code has been tested to the extent that someone with a superficial knowledge of C++ can. The code has been compiled, deployed, and works. And, importantly, it doesn't appear to break anything that was previously working.

Metrics and their values ​​(example)

# HELP yoradio_free_heap_bytes Free System Heap Memory.
# TYPE yoradio_free_heap_bytes gauge
yoradio_free_heap_bytes 113320

# HELP yoradio_uptime_seconds System Uptime Monitor.
# TYPE yoradio_uptime_seconds counter
yoradio_uptime_seconds 1321

# HELP yoradio_wifi_status Current raw WiFi status code enum value (0=IDLE, 1=NO_SSID, 2=SCAN_COMPLETED, 3=CONNECTED, 4=CONNECT_FAILED, 5=CONNECTION_LOST, 6=DISCONNECTED).
# TYPE yoradio_wifi_status gauge
yoradio_wifi_status 3

# HELP yoradio_wifi_rssi_dbm WiFi signal strength intensity.
# TYPE yoradio_wifi_rssi_dbm gauge
yoradio_wifi_rssi_dbm -38

# HELP yoradio_wifi_ap_info Connected Wi-Fi AP Access Point Name details.
# TYPE yoradio_wifi_ap_info gauge
yoradio_wifi_ap_info{ssid="uncbot-wln"} 1

# HELP yoradio_volume Current audio playback volume level.
# TYPE yoradio_volume gauge
yoradio_volume 18

# HELP yoradio_current_station_index Active playlist index item sequence.
# TYPE yoradio_current_station_index gauge
yoradio_current_station_index 15

# HELP yoradio_playing_status Active playback flag (1=STREAMING/PLAYING, 0=IDLE/STOPPED).
# TYPE yoradio_playing_status gauge
yoradio_playing_status 1

# HELP yoradio_station_info Current radio profile metadata. Mode labels define audio input sources (0=Radio Stream, 1=Bluetooth Receiver, 2=SD Card Playback, 3=Line-In/Aux).
# TYPE yoradio_station_info gauge
yoradio_station_info{name="Европа +",mode="0"} 1

Screenshot of the browser window with metrics page


Русский

Добрый день!

Зачем это нужно

Из-за сетевых и прочих ошибок радио может останавливать воспроизведение, переключаться на другую сеть и т.д. Для автоматического восстановления воспроизведения нужно послать команду "play". Но до этого патча не было возможности легко (например, при помощи curl) удалённо узнать состояние воспроизведения потока.

Я честно пытался скриптом написать автоматизацию - подключиться к telnet, послать команду cli.info и уйти. Но команду послать не получается ни через nc (BusyBox), ни через netcat, ни через ncat.
MQTT использовать для такой задачи - оверхед. Естественно не в том случае, если у вас уже используется инфраструктура умного дома, но у меня, как и у многих, её нет.
В веб-странице нет информации о статусе проигрывателя.

Исходя из вышеперечисленного ‼️с помощью нейросети‼️ был сгенерирован код, который добавляет Prometheus-like метрики. Код вроде бы ЦПУ не нагружает, по сути - по таймеру пишет в переменную типа string значения других переменных из памяти, вычислений никаких.

Теперь возможно с помощью curl быстро узнать статус радио и тем же curl отправить нужные команды.

Что добавлено

Данный патч добавляет метрики радио в формате Prometheus на веб-странице /metrics.
Значения метрик периодически собираются в строковую переменную, строка с метриками отображается на веб-странице. Процесс асинхронный. т.е. значения метрик не запрашиваются во время запроса страницы, веб-сервер отдаёт кешированные данные.
По умолчанию интервал обновления метрик - 5 секунд. Чаще не вижу смысла.

‼️Код сгенерирован с помощью нейросети. Со многими исправлениями кода последней... 😰
Тем не менее код проверен настолько, насколько его может их проверить человек с поверхностным знанием C++. Код скомпилирован, залит в железку и работает. И, что важно, судя по всему ничего ранее работающего не ломает.

Метрики и их значения (пример)

# HELP yoradio_free_heap_bytes Free System Heap Memory.
# TYPE yoradio_free_heap_bytes gauge
yoradio_free_heap_bytes 113320

# HELP yoradio_uptime_seconds System Uptime Monitor.
# TYPE yoradio_uptime_seconds counter
yoradio_uptime_seconds 1321

# HELP yoradio_wifi_status Current raw WiFi status code enum value (0=IDLE, 1=NO_SSID, 2=SCAN_COMPLETED, 3=CONNECTED, 4=CONNECT_FAILED, 5=CONNECTION_LOST, 6=DISCONNECTED).
# TYPE yoradio_wifi_status gauge
yoradio_wifi_status 3

# HELP yoradio_wifi_rssi_dbm WiFi signal strength intensity.
# TYPE yoradio_wifi_rssi_dbm gauge
yoradio_wifi_rssi_dbm -38

# HELP yoradio_wifi_ap_info Connected Wi-Fi AP Access Point Name details.
# TYPE yoradio_wifi_ap_info gauge
yoradio_wifi_ap_info{ssid="uncbot-wln"} 1

# HELP yoradio_volume Current audio playback volume level.
# TYPE yoradio_volume gauge
yoradio_volume 18

# HELP yoradio_current_station_index Active playlist index item sequence.
# TYPE yoradio_current_station_index gauge
yoradio_current_station_index 15

# HELP yoradio_playing_status Active playback flag (1=STREAMING/PLAYING, 0=IDLE/STOPPED).
# TYPE yoradio_playing_status gauge
yoradio_playing_status 1

# HELP yoradio_station_info Current radio profile metadata. Mode labels define audio input sources (0=Radio Stream, 1=Bluetooth Receiver, 2=SD Card Playback, 3=Line-In/Aux).
# TYPE yoradio_station_info gauge
yoradio_station_info{name="Европа +",mode="0"} 1

Скриншот окна браузера с метриками

@omgiafs omgiafs changed the title Добавление метрик радио в формате Prometheus в веб-сервере по пути "/metrics" Adding radio metrics in Prometheus format to the web server at the "/metrics" path Jun 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant