Grafana

Материал из Wiren Board

Это черновик страницы. Последняя правка сделана 27.07.2021 пользователем Admin. Grafana — мультиплатформенное веб-приложение с открытым кодом, отображающее данные в виде графиков, диаграмм, индикаторов, а также другими способами. Конечные пользователи могут создавать сложные панели мониторинга с помощью интерактивного конструктора запросов. Умеет отправлять оповещения (alert). Расширяется с помощью системы плагинов.

Grafana подходит для отображения изменяющихся со временем параметров — например, показаний датчиков, подключенных к контроллеру Wiren Board. Так как Grafana сама по себе не является базой данных, для хранения данных используются time series databases, такие как InfluxDB и Prometheus.

Grafana можно установить на собственный сервер, либо использовать облачный сервис Grafana Cloud.

Как настроить отображение данных с контроллера Wiren Board в Grafana Cloud

В состав Grafana Cloud входит собственная база данных, поэтому устанавливать и настраивать базу данных не требуется.

Показания с контроллера Wiren Board будут передаваться по схеме:

MQTT-брокер на контроллере Wiren Board -> клиент Telegraf на контроллере Wiren Board -> Grafana Cloud.

Регистрация в Grafana Cloud

  1. Зарегистрируйтесь по ссылке [1].

Установка и настройка Telegraf на контроллер Wiren Board

  1. Установите и запустите Telegraf в соответствии с https://docs.influxdata.com/telegraf/v1.19/introduction/installation/:
    apt update && apt install apt-transport-https
    wget -qO- https://repos.influxdata.com/influxdb.key | sudo apt-key add -  
    source /etc/os-release  
    test $VERSION_ID = "7" && echo "deb https://repos.influxdata.com/debian wheezy stable" | sudo tee /etc/apt/sources.list.d/influxdb.list
    test $VERSION_ID = "8" && echo "deb https://repos.influxdata.com/debian jessie stable" | sudo tee /etc/apt/sources.list.d/influxdb.list
    test $VERSION_ID = "9" && echo "deb https://repos.influxdata.com/debian stretch stable" | sudo tee /etc/apt/sources.list.d/influxdb.list
    test $VERSION_ID = "10" && echo "deb https://repos.influxdata.com/debian buster stable" | sudo tee /etc/apt/sources.list.d/influxdb.list
    apt update && apt install telegraf
    systemctl start telegraf
    
  2. Добавьте в /etc/telegraf/telegraf.conf секции для получения данных из MQTT и отправки данных в Grafana Cloud. В секции отправки данных замените логин и пароль на указанные на странице https://grafana.com/orgs/wiren в разделе Prometheus - Send metrics.
    [[inputs.mqtt_consumer]]
      ## Broker URLs for the MQTT server or cluster.  To connect to multiple
      ## clusters or standalone servers, use a seperate plugin instance.
      ##   example: servers = ["tcp://localhost:1883"]
      ##            servers = ["ssl://localhost:1883"]
      ##            servers = ["ws://localhost:1883"]
      servers = ["tcp://127.0.0.1:1883"]
    
      ## Topics that will be subscribed to.
      topics = [
        "/devices/power_status/controls/Vin",
      ]
    
      ## The message topic will be stored in a tag specified by this value.  If set
      ## to the empty string no topic tag will be created.
      # topic_tag = "topic"
    
      ## QoS policy for messages
      ##   0 = at most once
      ##   1 = at least once
      ##   2 = exactly once
      ##
      ## When using a QoS of 1 or 2, you should enable persistent_session to allow
      ## resuming unacknowledged messages.
      # qos = 0
    
      ## Connection timeout for initial connection in seconds
      # connection_timeout = "30s"
    
      ## Maximum messages to read from the broker that have not been written by an
      ## output.  For best throughput set based on the number of metrics within
      ## each message and the size of the output's metric_batch_size.
      ##
      ## For example, if each message from the queue contains 10 metrics and the
      ## output metric_batch_size is 1000, setting this to 100 will ensure that a
      ## full batch is collected and the write is triggered immediately without
      ## waiting until the next flush_interval.
      # max_undelivered_messages = 1000
    
      ## Persistent session disables clearing of the client session on connection.
      ## In order for this option to work you must also set client_id to identify
      ## the client.  To receive messages that arrived while the client is offline,
      ## also set the qos option to 1 or 2 and don't forget to also set the QoS when
      ## publishing.
      # persistent_session = false
    
      ## If unset, a random client ID will be generated.
      # client_id = ""
    
      ## Username and password to connect MQTT server.
      # username = "telegraf"
      # password = "metricsmetricsmetricsmetrics"
    
      ## Optional TLS Config
      # tls_ca = "/etc/telegraf/ca.pem"
      # tls_cert = "/etc/telegraf/cert.pem"
      # tls_key = "/etc/telegraf/key.pem"
      ## Use TLS but skip chain & host verification
      # insecure_skip_verify = false
    
      ## Data format to consume.
      ## Each data format has its own unique set of configuration options, read
      ## more about them here:
      ## https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_INPUT.md
        data_format = "value"
        data_type = "float"
    
    [[outputs.http]]
      ## URL is the address to send metrics to
      url = "https://prometheus-us-central1.grafana.net/api/prom/push"
    
      ## HTTP Basic Auth credentials
      username = "xxx" # Replace
      password = "yyy" # Replace
    
      ## Data format to output.
      data_format = "prometheusremotewrite"
    
      ## Additional HTTP headers
      [outputs.http.headers]
         Content-Type = "application/x-protobuf"
         Content-Encoding = "snappy"
         X-Prometheus-Remote-Write-Version = "0.1.0"
    
  3. Проверьте, что Telegraf работает без ошибок.
    1. Остановите его и запустите вручную:
      systemctl stop telegraf
      telegraf -debug
      
    2. Если ошибок нет, запустите Telegraf:
      systemctl start telegraf
      

Создание панели с данными от контроллера Wiren Board в Grafana

Как настроить отображение данных с контроллера Wiren Board в Grafana на собственном сервере

На основе https://grafana.com/docs/grafana/latest/installation/debian/ Цель: получить удобный способ для хранения и анализа данных с контроллеров. Средства: Выделенный сервер (если планируется сбор данных с контроллеров через интернет - то с "белым" адресом).

Подготовка к установке

Используем чистый Debian, Добавляем пакеты, ключи

apt install -y apt-transport-https software-properties-common wget gnupg2 sudo python3-pip
wget -q -O - https://packages.grafana.com/gpg.key | sudo apt-key add -
echo "deb https://packages.grafana.com/oss/deb stable main" | sudo tee -a /etc/apt/sources.list.d/grafana.list
apt update

Установка

Ставим grafana и БД influxdb:

apt install -y grafana influxdb influxdb-client

Разрешаем автозапуск, запускаем и проверяем:

apt install -y grafana
systemctl enable grafana-server && systemctl start grafana-server
systemctl status grafana-server

Если статус "Active: active (running)" - то дальнейшая настройка -через веб интерфейс.

influxdb

Создаем базу данных с именем mqtt_data

echo "CREATE DATABASE mqtt_data; show databases;" | influx
Создание БД

grafana

Открываем в браузере http://<serverIP>:3000/

страница входа

Логин и пароль по умолчанию admin admin. Сразу меняем пароль.

запуск и контроль