Ubuntu 환경에서 센서 데이터를 실시간 시각화하는 대시보드(GUI) 구성 #1

개요

임베디드 환경에서 센서 데이터를 실시간으로 모니터링할 수 있다면, 디버깅과 분석이 훨씬 수월해집니다.
이번 글에서는 초음파 거리 센서를 Ubuntu에서 Python으로 제어하고, 그 데이터를 Prometheus와 Grafana를 이용해 실시간 대시보드(UI)로 시각화하는 전체 과정을 다룹니다.

센서 값이 cm 단위로 측정되며, 실시간으로 그래프에 반영됩니다.

시스템 구성 흐름

[초음파 센서 (cm)] ─> [Python Exporter] ─> [Prometheus] ─> [Grafana Dashboard]

구성 단계 요약

  1. 초음파 센서 거리 측정 코드 (Python)
  2. Prometheus Exporter로 실시간 메트릭 제공
  3. Prometheus 서버에서 exporter의 데이터를 주기적으로 Pull
  4. Grafana에서 자동 패널 구성으로 실시간 시각화

코드 구성 요소

구성 요소 역할
gpio_utils.py GPIO 핀 제어 (export/unexport, read/write)
sensor.py 초음파 센서로 거리(cm) 측정
exporter.py Prometheus metric 서버로 거리 데이터 노출
prometheus.yml Prometheus가 exporter로부터 데이터를 수집하는 설정
ultrasonic-exporter.service exporter를 부팅 시 자동 실행
prometheus.service Prometheus 서버 자동 실행
grafana-server (APT 설치 시) 자동 서비스 사용 가능

Python 코드 구성

gpio_utils.py

import os

def export_gpio(pin: int, direction: str):
    # GPIO 핀을 시스템에 export하고 입출력 방향 설정
    if os.path.exists(f"/sys/class/gpio/gpio{pin}"):
        with open("/sys/class/gpio/unexport", "w") as f:
            f.write(str(pin))
    with open("/sys/class/gpio/export", "w") as f:
        f.write(str(pin))
    with open(f"/sys/class/gpio/gpio{pin}/direction", "w") as f:
        f.write(direction)

def write_gpio_value(pin: int, value: int):
    with open(f"/sys/class/gpio/gpio{pin}/value", "w") as f:
        f.write(str(value))

def read_gpio_value(pin: int) -> str:
    with open(f"/sys/class/gpio/gpio{pin}/value", "r") as f:
        return f.read().strip()

def unexport_gpio(pin: int):
    with open("/sys/class/gpio/unexport", "w") as f:
        f.write(str(pin))

sensor.py

import time
from gpio_utils import export_gpio, unexport_gpio, write_gpio_value, read_gpio_value

TRIG_PIN = 82
ECHO_PIN = 88
SOUND_SPEED_CM_S = 34300

def initialize_sensor():
    export_gpio(TRIG_PIN, "out")
    export_gpio(ECHO_PIN, "in")

def cleanup_sensor():
    unexport_gpio(TRIG_PIN)
    unexport_gpio(ECHO_PIN)

def measure_distance_cm() -> float:
    write_gpio_value(TRIG_PIN, 0)
    time.sleep(0.00002)
    write_gpio_value(TRIG_PIN, 1)
    time.sleep(0.00001)
    write_gpio_value(TRIG_PIN, 0)

    start = time.time()
    while read_gpio_value(ECHO_PIN) == "0":
        start = time.time()
    end = start
    while read_gpio_value(ECHO_PIN) == "1":
        end = time.time()

    duration = end - start
    distance = (duration * SOUND_SPEED_CM_S) / 2
    return round(distance, 2)

exporter.py

from prometheus_client import start_http_server, Gauge
import time
from sensor import initialize_sensor, cleanup_sensor, measure_distance_cm

distance_gauge = Gauge('ultrasonic_distance_cm', 'Measured distance from ultrasonic sensor in centimeters')

def main():
    initialize_sensor()
    start_http_server(8000)
    print("Exporter started on :8000")

    try:
        while True:
            try:
                distance = measure_distance_cm()
                distance_gauge.set(distance)
                print(f"Distance: {distance} cm")
            except Exception as e:
                distance_gauge.set(-1)
            time.sleep(0.1)

    except KeyboardInterrupt:
        pass
    finally:
        cleanup_sensor()

if __name__ == "__main__":
    main()

Prometheus 설정

prometheus.yml

global:
  scrape_interval: 5s

scrape_configs:
  - job_name: 'ultrasonic_sensor'
    static_configs:
      - targets: ['localhost:8000']

실행

./prometheus --config.file=prometheus.yml

서비스 등록 (systemd)

A. exporter 서비스 등록

/etc/systemd/system/ultrasonic-exporter.service

[Unit]
Description=Ultrasonic Sensor Exporter
After=network.target

[Service]
ExecStart=/usr/bin/python3 /home/topst/20250801/exporter.py
WorkingDirectory=/home/topst/20250801
Environment=PYTHONPATH=/home/topst/.local/lib/python3.10/site-packages
Restart=on-failure

[Install]
WantedBy=multi-user.target

등록 및 실행

sudo systemctl daemon-reload
sudo systemctl enable ultrasonic-exporter
sudo systemctl start ultrasonic-exporter

B. Prometheus 서비스 등록

/etc/systemd/system/prometheus.service

[Unit]
Description=Prometheus Server
After=network.target

[Service]
ExecStart=/home/topst/prometheus-2.51.1.linux-arm64/prometheus \
  --config.file=/home/topst/prometheus-2.51.1.linux-arm64/prometheus.yml \
  --storage.tsdb.path=/home/topst/prometheus-2.51.1.linux-arm64/data
WorkingDirectory=/home/topst/prometheus-2.51.1.linux-arm64
Restart=on-failure
User=topst

[Install]
WantedBy=multi-user.target

등록 및 실행

sudo systemctl daemon-reload
sudo systemctl enable prometheus
sudo systemctl start prometheus

C. Grafana (APT 설치 시 자동 등록됨)

sudo systemctl enable grafana-server
sudo systemctl start grafana-server

4. 상태 확인 명령어 (문제 있는 경우 확인)

대상 상태 확인 로그 확인
Exporter systemctl status ultrasonic-exporter journalctl -u ultrasonic-exporter -f
Prometheus systemctl status prometheus journalctl -u prometheus -f
Grafana systemctl status grafana-server journalctl -u grafana-server -f

Grafana 대시보드 구성

  1. Prometheus를 Grafana 데이터소스로 자동 등록
  2. 초음파 센서 그래프 패널이 포함된 대시보드를 자동 생성
구성 요소 자동화 경로 또는 설정 파일
데이터 소스 등록 /etc/grafana/provisioning/datasources/prometheus.yml
대시보드 설정 등록 /etc/grafana/provisioning/dashboards/dashboards.yml
대시보드 패널 정의 /etc/grafana/provisioning/dashboards/json/ultrasonic_dashboard.json
실행 grafana-server systemd 서비스 자동 실행

디렉토리 구조

/etc/grafana/provisioning/
├── datasources/
│   └── prometheus.yml
├── dashboards/
│   ├── dashboards.yml
│   └── json/
│       └── ultrasonic_dashboard.json

1. Prometheus 데이터소스 설정

/etc/grafana/provisioning/datasources/prometheus.yml

apiVersion: 1

datasources:
  - name: Prometheus
    type: prometheus
    access: proxy
    url: http://localhost:9090
    isDefault: true

2. 대시보드 로딩 설정

/etc/grafana/provisioning/dashboards/dashboards.yml

apiVersion: 1

providers:
  - name: 'Ultrasonic Dashboard'
    folder: 'Sensor Dashboards'
    type: file
    options:
      path: /etc/grafana/provisioning/dashboards/json

3. 대시보드 JSON 파일 생성

/etc/grafana/provisioning/dashboards/json/ultrasonic_dashboard.json

{
  "id": null,
  "title": "Ultrasonic Distance Sensor",
  "timezone": "browser",
  "schemaVersion": 30,
  "version": 1,
  "refresh": "5s",
  "panels": [
    {
      "type": "graph",
      "title": "Distance (cm)",
      "targets": [
        {
          "expr": "ultrasonic_distance_cm",
          "refId": "A"
        }
      ],
      "gridPos": {
        "h": 10,
        "w": 24,
        "x": 0,
        "y": 0
      },
      "lines": true,
      "linewidth": 2,
      "nullPointMode": "null",
      "legend": {
        "show": true
      },
      "xaxis": {
        "show": true
      },
      "yaxis": {
        "show": true,
        "format": "lengthcm"
      }
    }
  ]
}

:red_exclamation_mark: JSON 파일 안의 "type": "graph"를 반드시 사용하세요. "time_series"는 일부 버전에서 인식 오류 발생.

4. Grafana 재시작

sudo systemctl restart grafana-server

5. 대시보드 확인

접속http://localhost:3000 → 로그인(admin/admin) 후

  1. 좌측 메뉴 → Dashboards

  2. → “Sensor Dashboards” 폴더 클릭

  3. → “Ultrasonic Distance Sensor” 클릭

  4. 센서 거리 데이터가 실시간 그래프로 표시

이번 구성에서는 Ubuntu 기반 시스템에서 초음파 거리 센서 데이터를 실시간으로 시각화하는 대시보드 환경을 구축해 보았습니다. Python을 통해 센서 값을 읽고, Prometheus로 수집하고, Grafana를 통해 시각화하는 흐름은 임베디드 시스템 개발 환경에서 매우 강력하고 확장성 있는 구조입니다.