Бюджетный мониторинг температуры: Arduino + Zabbix
У нас в организации развёрнут сервер Zabbix для мониторинга работоспособности серверов и АРМов. Из-за особенностей техпроцесса оборудование «размазано» по нескольким помещениям и разнесено по территории предприятия. Естественно, вместе с основными параметрами компьютеров (работает/не работает) хочется контролировать и микроклимат в серверных. При этом, как обычно, возможности весьма ограничены, и «выбить» значительные средства на сложные системы мониторинга температуры (к ним я отношу и платы управления с термодатчиками для стоечных ИБП APC) — это отдельный квест.
В основной серверной всё просто — установлена одна такая плата (закуплена давным-давно предшественником вместе с основным оборудованием), воткнут APC-шный термодатчик, заведён агент в Заббиксе, всё работает по SNMP. Скучно :) На мониторинг удалённой аппаратной оборудования нет, средств тоже — см. выше. Поэтому было решено проявить смекалку, сэкономить бюджет и заодно прокачать новый навык путём конструирования простого и дешёвого «наколенного» решения, вписывающегося, тем не менее, в существующую инфраструктуру мониторинга Zabbix.
Необходимые компоненты:
- Основа системы — Arduino Nano V3
- Модуль локальной сети (ethernet-shield)
- И, собственно, цифровой датчик температуры на базе DS18B20
Общая стоимость компонентов — $10 с доставкой.
Сборка устройства не составляет труда. Сетевой модуль надевается на основную плату «бутербродом», термодатчик припаивается к его пинам. Подключение датчика: красный +5 В, чёрный — земля, жёлтый — данные; между +5V и Data припаиваем подтягивающий резистор 4,7 кОм.
Пин для данных выбирается с учётом пинов, используемых сетевым модулем (D10 – SS; D11 – MOSI; D12 – MISO; D13 – SCK; D2 – IRQ).
Грабли: в прототипе устройства столкнулся с конфликтом — данные о температуре выдавались случайным образом, «через два на третий». Причиной оказалось то, что я прицепил термодатчик на пин 2, который, как потом нашёл на просторах интернета, используется сетевым модулем для генерации прерывания при поступлении пакета. Переставил на 4-й — заработало как часы.
После сборки аппаратной части переходим к программной.
Устройство будет работать в сети и притворяться заббикс-агентом, для этого ему нужен MAC и IP-адрес. Решаем, как удобнее — жёстко зашить при программировании, генерировать MAC из адреса температурного датчика и получать IP по DHCP, и т.д. Я пошёл по простейшему пути и захардкодил оба параметра.
Протокол обмена с заббикс-сервером описан в документации. Наше устройство будет откликаться на две команды — agent.ping и env.temp (здесь оставлен простор для дальнейшего творчества, можно привязать любой из модулей расширения, доступных для ардуино — хоть датчик влажности, хоть освещённости — да что душе угодно). На все остальные команды оно будет ругаться отвечать стандартным ответом, понятным заббикс-серверу.
Для тех, кто начинает с нуля (как я) — программирование Arduino выполняется с помощью Arduino IDE, установка и настройка которой элементарны. Для работы компонентов необходимы библиотеки UIPEthernet и OneWire, которые устанавливаются и подключаются к проекту через меню Скетч — Подключить библиотеку — Управлять библиотеками…
Если у вас будут другие компоненты (например, сетевой модуль не на enc28j60, а на другом чипе) — понадобятся и другие библиотеки!
Код работы с сетевым модулем и с датчиком температуры — типовой, из интернета, с некоторыми допущениями и упрощениями.
После заливки кода в контроллер и подключения ethernet-кабеля проверяем из консоли:
Грабли: выложенная на zabbix.com скомпилированная версия zabbix_get для Windows устарела и использует другой протокол (с заголовком ZBXD\x01 в запросе сервера). Линуксовая версия актуальна и протокол соответствует приведенному коду.
Всё работает, как и задумано. В админке заббикса создаём новый хост с выбранным IP, в нём — два ключа, Numeric (unsigned) agent.ping и Numeric (float) env.temp, наслаждаемся работой. Графики, триггеры — всё как обычно.
Питание устройства — через родной USB. Корпус — по желанию: подходящая пластиковая коробочка, термоусадка, синяя изолента.
Разрешение датчика — примерно 0.06 (точнее, 1/16) °С, точность — при погружении в таящий снег показал 0.19 °С (может, опустился бы и ниже, но снега было мало и он весь быстро растаял). Считаю, для устройства стоимостью 10 долларов и описанных целей — более чем достаточно.
UPD: В связи с незначительными изменениями протокола Zabbix, данный скетч не работает. Исправленная версия на Google Drive (поддерживает новый протокол, получает IP-адрес по DHCP).
zbx-sadman/zabbuino
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
An Zabbix agent firmware for Arduino
Actual release is v1.4 (AVR only).
Testing release is v1.5 (AVR & ESP8266 & ESP32 here.
Compilation tested on Arduino IDE 1.6.11 (from https://www.arduino.cc/) and above.
Note: Zabbuino is not any kind of Arduino library. It is a «ready-to-use» project. Rename «zabbuino-master» dir to «zabbuino» just after cloning/downloading/unzipping/etc. to avoid compilation error.
All new features can be found on experimental branch. Old releases placed in old_releases branch.
See change log before update.
You can help to the project by providing new ideas and/or hardware to testing and integrating. Or yoг can just donate for further development. Contact to me via email or use Yandex.Money service.
- A few Zabbix agent commands;
- Wraps a lot of Arduino Language functions;
- OneWire and I2C bus scaning to detect sensors ID or adresses;
- Network DHCP and static IP support;
- Remote configuring & rebooting, system protection;
- Storing system setting in EEPROM;
- AVR WatchDog feature support;
- MCU and runtime metrics (current/min/max VCC, current/min RAM, uptime, MCU name) obtaining;
- Support W5100 and ENC28J60 network modules, drivers is implemented to source code;
- Support one or more DS18X20 thermometer;
- Support MLX90614 infrared thermometer;
- Support MAX6675 termocoupler ADC;
- Support DHT11/21/22/33/44 or AM2301/2302 humidity and temperature sensors;
- Support SHT2X humidity and temperature sensors serie;
- Support BMP180/085, BMP280/BME280 pressure and temperature sensors;
- Support BH1750, MAX44009, TSL2561 light sensors;
- Support ADPS9960 light/color sensor;
- Support Telaire T67xx family CO2 sensor;
- Support Winsen MH-Z14/MH-Z19/MH-Z19B, ZE08-CH2O, ZE14-O3 (ZE25-O3, ZE27-O3), ZP14 (ZC05), ZE15-CO, ZE16-CO sensor modules;
- Support VEML6070 ultraviolet sensor;
- Support DS3231 & PCF8563 RTC I2C module;
- Support incremental encoder (on interrupt’s pin);
- Support any devices that need to use hardware interrupt — tilt switches, dry contacts, water flow sensor, and so;
- Support INA219 power/current monitor;
- Support HC-SR04 ultrasonic ranging module;
- Support any other analog or digital sensor via analogread / digitalread commands;
- Support indicators, that connected to MAX7219, 8×8 Led matrix for example;
- Support simple I2C devices (expanders, digital linear potentiometers, etc.);
- Support One- or Two- (and maybe Four-) lines LCD Character displays with PC8574 I2C expander;
- Support any actuators or indicators via digitalwrite command;
- Support simple operations with digital servos and relays;
- Support PCA9685 16 channel PWM controller;
- Support WS2801 Led stripe and any indicators on shift registers via extended shiftout command;
- Support WS2812 Led stripe;
- Support Plantower PMS-A003 (and similar) dust sensors;
- Support Nova Fitness SDS011 (and similar) dust sensors;
- Support Wuhan Cubic PM2012 (and similar) dust sensors;
- Support DFPlayer Mini;
- Support PZEM-004 energy meter;
- Support APC Smart UPS (with RS232 interface);
- Support Megatec UPS’s (with RS232 interface);
- Simulate various vendor’s IR transmitters.
- Arduino board with ATMega328 & ENC28J60 or W5100 Ethernet Module.
- Arduino Mini Pro / Nano / Duemilanove (ATmega328 MCU, 5V), Arduino Micro (ATmega32u4);
- ENC28J60 mini module & ENC28J60 shield for Arduino Nano (5V both), Ethernet Shield (W5100), Mini Red W5100 Ethernet Module (5V), WIZ811MJ Ethernet module (3.3V);
- SW-520D sensors, encoders (EC11), buttons & etc;
- Sensors: DS18B20, AM2302 (DHT22), AM2320, BMP180, BME280, SHT21 (SI7021), BH1750, MAX44009, TSL2561, ADPS9960, MH-Z19B, ZE08-CH2O, ZE15-CO, T6703, VEML6070, INA219, HC-SR04, Plantower PMS-A003, PM2012, SDS011, MLX90614, MAX6675;
- MAX7219 8×8 LED module & 8-Digit LED Display Module;
- LCD 2002 (Winstar) & 2004 (Generic) displays with PC8574 I2C convertor;
- PCF8574 I2C expander;
- MCP4725 I2C module;
- PCF8591 I2C module;
- WS2801, WS2812 pixel modules
- PZEM-004 energy meter;
- DFPlayer Mini;
- RS-232 module;
- Smart-UPS 1500, APC Smart-UPS 2200 RM;
- may be i forget someting.
You can also download templates for Zabbix 2.4.x
Zabbix и Arduino
В этом материале я обещал показать как можно использовать данные из Arduino в Zabbix.
Будем считать, что Arduino у вас прошита примером из предыдущей статьи и подключена к вашему компьютеру в моем случае это порт COM3.
Так же у вас настроен сервер Zabbix и на вашем компьютере настроен Zabbix Agent и эта связка работает.
Для реализации задумки нам потребуется Python, если у вас не установлен данный интерпретатор, то скачиваем и устанавливаем отсюда.
Т.к. Python мультиплатформенный, то данный материал легко реализуем на любых операционных системах (кроме мобильных) я же буду все проделывать в Windows.
Из Arduino в серийный порт мы получаем значения влажности и температуры как
Итак, все настроено Python установлен, доустановим модуль pySerial с помощью pip в консоли, если pip отсутствует (касается например FreeBSD, где он автоматом не устанавливается).
Устанавливаем:
Создадим директорию для нашего скрипта:
Напишем скрипт, который будет опрашивать наш серийный порт и получать значения из Arduino, обращаем внимание на переменную «ser«, если у вас другой номер серийного порта, укажите свой (посмотреть можно в Windows в устройствах, в Linux можно посмотреть dmesg)
И сохраним данный скрипт под именем dh22.py в директории С:\Program Files\Zabbix Agent\scripts\
Для теста можно попробовать запустить скрипт с аргументами:
В первом случае вернет температуру, во втором влажность.
Теперь нам нужно научить Zabbix Agent отдавать серверу эти значения.
Данные будем отдавать через пользовательские данные (UserParametr).
Открываем конфигурационный файл Zabbix Agent.
В Windows используйте для редактирования программу notepad++, она замечательно работает с различными символами переноса строк.
В самый низ файла вписываем пользовательский параметр:
- dh22[*] – название параметра (ключа), [*] — для аргументов (humidity или temperature)
- C:\Users\vino\AppData\Local\Programs\Python\Python37\python.exe — путь до интерпретатора Python
- C:\Program Files\Zabbix Agent\scripts\dh22.py — путь до скрипта
- $1 — здесь будет возвращаемое значение
Рестартуем сервис Zabbix Agent:
На Zabbix сервере создаем два элемента данных для нашего хоста (Настройка->Узлы сети->Выбираем наш узел и переходим в его Элементы данных), один для температуры, второй для влажности (Сделал принтскринами, картинки кликабельные) :
Далее можем добавить график, там же где добавляли элементы данных
interlegis/Arduino-Zabbix-Agent
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Using an Arduino Uno v3 and a Zabbix Server to monitor a data center environment.
It’s a Zabbix Agent tested and running successfully.
- Arduino Uno v3
- Ethernet Shield
- Arduino Sensor Shield*
- DHT11 (or similar) and one 10k resistor
- DS18b20 (or similar) and one 4.7k resistor
- PIR (Passive infrared sensor/Motion detector)
- Soil humidity sensor
- One led and one 1k resistor
*A new shield may be built by yourself.
Schematic done using Fritzing.
This sensor can measure the air temperature and humidity. It doesn’t need to be calibrated. It is recommended to take 1 sample per second or less. It returns one int for each data. The temperature is in Celsius. A 10k resistor must be connected to pins Vcc and Signal.
This sensor is responsible for measuring the air temperature and returning a float . It is fast enough to take one sample for each Arduino cpu clock. It doesn’t need to be calibrated and is water-proof. The library OneWire is used for reading its data. This means it is possible to connect multiple DS18b20 sensors on a single Arduino port. The temperature is in Celsius. A single 4.7k resistor must be conected between Vcc and the pin connected to one or more sensor.
Plug and play sensor. Doesn’t need resistor or adjustments. Its signal must be connected to an Arduino port and that’s all. Returns 1 when detects motion and 0 when nothing is detected.
Soil humidity sensor
Tricky sensor. It returns 1 when it’s dry and 0 when it detects humidity. Its output is digital. The sensibility must be adjusted by turning a small screwdriver on the sensor.
Be careful! Leds are extremely fragile. It needs a 1k resistor in series to make it work. The brightness may vary depending on the model and color. In this project, the led is turned on when the Arduino receives a command and is turned off when the value is returned to the server.
Some results are kept for a few seconds to avoid oscillations from the sensors. For example, PIR may get a positive (motion) result and then a null (motion stopped) before Zabbix check. So its value is kept for a few seconds on 1 to allow Zabbix to have enough time to read it.
DS18b20 function is checked on every loop, but the sensors are read only once every 15 seconds. If the request is made on less than 15 seconds after the last one, it simply replies the variable value, making the response much faster.
All temperature are in Celsius. To convert to Fahrenheit:
Check pins used. Upload the code to the Arduino. Add an item on Zabbix Server.
- Type: Zabbix agent.
- Key: The key for each sensor ( q , w , e , r , t etc).
- It is recommended to check each item on not less than once a minute.
Keys used on Zabbix:
- q — soil humidity
- w — air temperature on DHT11
- e — air humidity on DHT11
- r — air temperature on DS18b20 with serial number ending with 17
- f — air temperature on DS18b20 with serial number ending with B6
- v — air temperature on DS18b20 with serial number ending with D3
- t — motion detector
Set the IP address, the gateway and the MAC address to be used by the agent.
Check how many sensors will be used and add them to the code if necessary. To do this:
- Set a pin using #define .
- Write a function to read the sensor if necessary.
- Choose a letter to be used as a command for each sensor function. Make sure the letter is not used anywhere else!
- On parseCommand , add the function to be executed when receiving the command defined on the step before.
Pins 10, 11, 12 and 13 cannot be used. They are used by the ethernet shield.
Pin 3 is the led.
Pin 4 is the DHT11.
Pin 5 is one or more DS18b20 (using OneWire).