Приклад Південного плагіна на Python: датчик DHT11
Спробуємо зібрати всю інформацію воєдино і написати плагін. Ми можемо продовжити на прикладі недорогого датчика DHT11, який використовується для вимірювання температури і вологості, безпосередньо підключеного до Raspberry PI. Цей плагін доступний на github під назвою DHT Repo.
По-перше, ось набір посилань, де ви можете знайти більше інформації про цей датчик:
Обладнання
Датчик DHT підключається безпосередньо до Raspberry PI 2 або 3. Ви можете купити датчик і резистор і припаяти їх самостійно, або купити готову схему, яка забезпечує правильний вихід для підключення до Raspberry PI. показує DHT11 з резистором, який ви можете купити онлайн.
Датчик можна безпосередньо підключити до GPIO Raspberry PI (General Purpose Input/Output - вхід/вихід загального призначення). Вступ до GPIO та набору контактів доступний за посиланням . У нашому випадку ви повинні підключити датчик до цих контактів:
- VCC підключено до PIN #2 (5v Power)
- GND підключено до PIN #6 (Ground)
- DATA підключено до PIN #7 (BCM 4 - GPCLK0)
показує датчик, підключений до Raspberry PI, а збільшує м асштаб використовуваних дротів.
Програмне забезпечення
Для цього плагіна ми використовуємо бібліотеку ADAFruit Python (посилання на репозиторій GitHub наведено вище). Спочатку необхідно встановити бібліотеку (в наступних версіях бібліотека буде надаватися в готовому пакеті):
$ git clone https://github.com/adafruit/Adafruit_Python_DHT.git
Cloning into 'Adafruit_Python_DHT'...
remote: Counting objects: 249, done.
remote: Total 249 (delta 0), reused 0 (delta 0), pack-reused 249
Receiving objects: 100% (249/249), 77.00 KiB | 0 bytes/s, done.
Resolving deltas: 100% (142/142), done.
$ cd Adafruit_Python_DHT
$ sudo apt-get install build-essential python-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
build-essential python-dev
...
$ sudo python3 setup.py install
running install
running bdist_egg
running egg_info
creating Adafruit_DHT.egg-info
...
Плагін
Це код плагіна:
# -*- coding: utf-8 -*-
# FLEDGE_BEGIN
# See: http://fledge-iot.readthedocs.io/
# FLEDGE_END
""" Plugin for a DHT11 temperature and humidity sensor attached directly
to the GPIO pins of a Raspberry Pi
This plugin uses the Adafruit DHT library, to install this perform
the following steps:
git clone https://github.com/adafruit/Adafruit_Python_DHT.git
cd Adafruit_Python_DHT
sudo apt-get install build-essential python-dev
sudo python setup.py install
To access the GPIO pins fledge must be able to access /dev/gpiomem,
the default access for this is owner and group read/write. Either
Fledge must be added to the group or the permissions altered to
allow Fledge access to the device.
"""
from datetime import datetime, timezone
import uuid
from fledge.common import logger
from fledge.services.south import exceptions
__author__ = "Mark Riddoch"
__copyright__ = "Copyright (c) 2017 OSIsoft, LLC"
__license__ = "Apache 2.0"
__version__ = "${VERSION}"
_DEFAULT_CONFIG = {
'plugin': {
'description': 'Python module name of the plugin to load',
'type': 'string',
'default': 'dht11'
},
'pollInterval': {
'description': 'The interval between poll calls to the device poll routine expressed in milliseconds.',
'type': 'integer',
'default': '1000'
},
'gpiopin': {
'description': 'The GPIO pin into which the DHT11 data pin is connected',
'type': 'integer',
'default': '4'
}
}
_LOGGER = logger.setup(__name__)
""" Setup the access to the logging system of Fledge """
def plugin_info():
""" Returns information about the plugin.
Args:
Returns:
dict: plugin information
Raises:
"""
return {
'name': 'DHT11 GPIO',
'version': '1.0',
'mode': 'poll',
'type': 'south',
'interface': '1.0',
'config': _DEFAULT_CONFIG
}
def plugin_init(config):
""" Initialise the plugin.
Args:
config: JSON configuration document for the device configuration category
Returns:
handle: JSON object to be used in future calls to the plugin
Raises:
"""
handle = config['gpiopin']['value']
return handle
def plugin_poll(handle):
""" Extracts data from the sensor and returns it in a JSON document as a Python dict.
Available for poll mode only.
Args:
handle: handle returned by the plugin initialisation call
Returns:
returns a sensor reading in a JSON document, as a Python dict, if it is available
None - If no reading is available
Raises:
DataRetrievalError
"""
try:
humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, handle)
if humidity is not None and temperature is not None:
time_stamp = str(datetime.now(tz=timezone.utc))
readings = {'temperature': temperature, 'humidity': humidity}
wrapper = {
'asset': 'dht11',
'timestamp': time_stamp,
'key': str(uuid.uuid4()),
'readings': readings
}
return wrapper
else:
return None
except Exception as ex:
raise exceptions.DataRetrievalError(ex)
return None
def plugin_reconfigure(handle, new_config):
""" Reconfigures the plugin, it should be called when the configuration of the plugin is changed during the
operation of the device service.
The new configuration category should be passed.
Args:
handle: handle returned by the plugin initialisation call
new_config: JSON object representing the new configuration category for the category
Returns:
new_handle: new handle to be used in the future calls
Raises:
"""
new_handle = new_config['gpiopin']['value']
return new_handle
def plugin_shutdown(handle):
""" Shutdowns the plugin doing required cleanup, to be called prior to the device service being shut down.
Args:
handle: handle returned by the plugin initialisation call
Returns:
Raises:
"""
pass
Зборка Fledge і додавання плагіна
Якщо ви ще не збирали Fledge, виконайте кроки, описані у розділі . Після збирання ви можете встановити Fledge за бажанням, виконавши ці кроки .
- Якщо ви запустили Fledge з каталогу збірки, скопіюйте структуру каталогу fledge-south-dht11/python/ до каталогу python:
$ cd ~/Fledge
$ cp -R ~/fledge-south-dht11/python/fledge/plugins/south/dht11 python/fledge/plugins/south/
- Якщо ви встановили Fledge, виконавши
sudo make install, скопіюйте структуру каталогу fledge-south-dht11/python/ у встановлений каталог python:
$ sudo cp -R ~/fledge-south-dht11/python/fledge/plugins/south/dht11 /usr/local/fledge/python/fledge/plugins/south/
Примітка
Якщо ви встановили Fledge за допомогою альтернативного DESTDIR, не забудьте додати шлях до цільового каталогу до команди
cp.
- Додавання сервісу
$ curl -sX POST http://localhost:8081/fledge/service -d '{"name": "dht11", "type": "south", "plugin": "dht11", "enabled": true}'
Примітка
Кожен репозиторій плагінів має власний скрипт пакування debian і документацію, і це рекомендований спосіб! Як зазначено вище, для встановлення залежностей linux та/або python можуть знадобитися явні дії.
Використання Плагіну
Після того, як плагін півдня буде додано як активну службу, ви готові використовувати плагін DHT11.
$ curl -X GET http://localhost:8081/fledge/service | jq
Давайте подивимося, що ми на сьогодні зібрали:
$ curl -s http://localhost:8081/fledge/asset | jq
[
{
"count": 158,
"asset_code": "dht11"
}
]
Нарешті, давайте витягнемо деякі значення:
$ curl -s http://localhost:8081/fledge/asset/dht11?limit=5 | jq
[
{
"timestamp": "2017-12-30 14:41:39.672",
"reading": {
"temperature": 19,
"humidity": 62
}
},
{
"timestamp": "2017-12-30 14:41:35.615",
"reading": {
"temperature": 19,
"humidity": 63
}
},
{
"timestamp": "2017-12-30 14:41:34.087",
"reading": {
"temperature": 19,
"humidity": 62
}
},
{
"timestamp": "2017-12-30 14:41:32.557",
"reading": {
"temperature": 19,
"humidity": 63
}
},
{
"timestamp": "2017-12-30 14:41:31.028",
"reading": {
"temperature": 19,
"humidity": 63
}
}
]
Зрозуміло, що ми не помітимо значних змін у температурі чи вологості, якщо тільки не прикладемо великий палець до датчика або не подихаємо на нього теплим повітрям :-)
$ curl -s http://localhost:8081/fledge/asset/dht11?limit=5 | jq
[
{
"timestamp": "2017-12-30 14:43:16.787",
"reading": {
"temperature": 25,
"humidity": 95
}
},
{
"timestamp": "2017-12-30 14:43:15.258",
"reading": {
"temperature": 25,
"humidity": 95
}
},
{
"timestamp": "2017-12-30 14:43:13.729",
"reading": {
"temperature": 24,
"humidity": 95
}
},
{
"timestamp": "2017-12-30 14:43:12.201",
"reading": {
"temperature": 24,
"humidity": 95
}
},
{
"timestamp": "2017-12-30 14:43:05.616",
"reading": {
"temperature": 22,
"humidity": 95
}
}
]
Зайве говорити, що північний плагін надсилатиме буферизовані дані до системи PI за допомогою плагіна OMF або будь-якої іншої північної системи за допомогою відповідного північного плагіна.
