MQTT/en: различия между версиями
(Новая страница: «==== Clearing the message queue ====») |
(Новая страница: «Unnecessary retained messages may remain in the MQTT system after unused drivers are removed or any devices are disconnected. This causes nonexistent devices to a…») |
||
Строка 140: | Строка 140: | ||
==== Clearing the message queue ==== | ==== Clearing the message queue ==== | ||
Unnecessary retained messages may remain in the MQTT system after unused drivers are removed or any devices are disconnected. This causes nonexistent devices to appear in the ''Devices'' section of the web interface. | |||
Для удаления топиков можно воспользоваться командой ''mqtt-delete-retained''. Пример использования: | Для удаления топиков можно воспользоваться командой ''mqtt-delete-retained''. Пример использования: |
Версия 14:28, 11 июня 2019
MQTT - is a message queue used in the Wiren Board software. Basic information about MQTT on Wikipedia.
Drivers responsible for the hardware capabilities of the controller (digital inputs, ADC, transistor outputs, ...) and functions of external connected devices (for example, relay modules connected via RS-485) record their status in the MQTT queue as special messages. The web interface reads these messages and displays the status of the devices.
If a button is pressed in the web interface, the web interface sends a message to the MQTT queue, the device driver receives it and sends a command to the device.
1 Examples of work via the MQTT queue
Getting the value from the temperature sensor and displaying it in the web interface
Assume that a 1-Wire/en bus temperature sensor is connected to the Wiren Board. Let's see how the sensor data comes into the web interface via the message queue:
- The driver that is responsible for this hardware function (wb-homa-w1) polls the 1-Wire sensors connected to the controller.
- When a value is received, the driver queues a message that resembles the following:
/devices/wb-w1/controls/28-0115a48fcfff 23.25
It means that the 1-Wire device (ID 28-0115a48fcfff)registers a value of 23.25°C. - The web interface that receives all messages from the queue (it is subscribed to all messages) receives this message and displays the sensor value to the page.
Pressing a button in the web interface and switching the relay on the external module
![](/wiki/images/thumb/d/d2/Web-devices-serial.png/400px-Web-devices-serial.png)
Suppose that the relay module WB-MRM2 is connected to the controller via the RS-485 bus. The user presses the relay button in the web interface and switches it on. Let's see how the command from the web interface gets to the external module:
- After clicking the button, the web interface places the following message in the queue:
/devices/wb-mrm2_130/controls/Relay 1/on 1
It means that the device WB-MRM2 with the address 130 must transfer Relay 1 to the state of the logical 1 - "on". - The wb-mqtt-serial driver responsible for this hardware function receives this message (it is subscribed to all messages related to RS-485 devices) and sends a command to turn on the first relay via the RS-485 bus to the relay module.
- The WB-MRM2 relay module receives a command from the controller, switches the relay and sends back a notification ("Relay 1 is on").
- The wb-mqtt-serial driver receives this notification over RS-485 and sends the message to the queue:
/devices/wb-mrm2_130/controls/Relay 1 1
It means that the first relay on the WB-MRM2 device with address 130 is in the logical 1 state (is "on").
The principle of operation of a message queue
The MQTT message system is based on the following principle:
- there is a hierarchical system of "topics" (like on the Internet forums)
- clients (in the case of Wiren Board - device drivers and web interface) can write messages and read from these topics
- to monitor the changes of the desired topic (for example, temperature on the sensor), the client can "subscribe" to it - then it will receive all messages in this topic.
For a full description of topics and subscriptions, see http://mosquitto.org/man/mqtt-7.html.http://mosquitto.org/man/mqtt-7.html.
Displaying devices in the queue structure
The logic of the organization of topics corresponding to different devices and their parameters in the Wiren Board follows certain rules - the so-called agreements (Wiren Board MQTT Conventions).
Полный список MQTT-топиков можно увидеть на странице Settings веб-интерфейса в разделе MQTT Channels (появилось в последних версиях прошивки).
The full list of MQTT topics can be seen on the Settings page of the web interface in the MQTT Channels section (supported in the latest firmware versions).
Message queue clients
- internal hardware function drivers
- external connected device drivers
- web interface
- rules engine
- (if any) user's own programs
The structure of the message device status
Here is an example message from the 1-Wire temperature sensor driver from the example above:
/devices/wb-w1/controls/28-0115a48fcfff 23.25
The part before the space is the name of the topic, then the message itself.
The name of the topic consists of nested "subtopics":
- /devices - root topic for all "devices" - as built-in functions of Wiren Board (digital, ADC, ...) and connected external (e.g. relay modules)
- /wb-w1 - subtopics, which is filled with 1-Wire driver
- /controls - podtopit all devices in it are recorded all of their parameters are changed ("on / off", the value of the sensor ...)
- /28-0115a48fcfff - directly the "channel" ("control)" - topic, where the value is recorded from the sensor. Its name is the same as the address of the 1-Wire sensor on the bus.
Message content:
- 23.25 - temperature value
If you want to write a device driver yourself, and you want it to appear on the Devices tab and be able to use it in rules, you need to follow the same topic structure.
The example of subscription
Clients which need to monitor the temperature value, "subscribe" to this topic, and they receive new messages - changing temperature values. One such client is the web interface.
You can also subscribe to messages from the Linux console using the mosquitto_sub utility (see below for a complete description of Queuing from the command line):
root@wirenboard:~# mosquitto_sub -t '/devices/wb-w1/controls/28-0115a48fcfff' -v // receive messages from a topic of the 1-Wire device with ID: 28-0115a48fcfff
/devices/wb-w1/controls/28-0115a48fcfff 22.75 //in this line and below is the output of the utility received messages
/devices/wb-w1/controls/28-0115a48fcfff 22.75
/devices/wb-w1/controls/28-0115a48fcfff 22.75
Message structure commands to change the state of the devices
Let's subscribe to the status messages of the first relay connected via RS-485 of the WB-MRM2 relay module:
root@wirenboard:~# mosquitto_sub -t "/devices/wb-mrm2_130/controls/Relay 1/#" -v
/devices/wb-mrm2_130/controls/Relay 1/meta/type switch
/devices/wb-mrm2_130/controls/Relay 1/meta/order 1
/devices/wb-mrm2_130/controls/Relay 1 0
Note that MQTT keeps part of the messages (namely those that were marked with the flag retained when sending) forever, so after subscribing you will receive even those messages that were sent before you subscribed.
The relay module is controlled by the wb-mqtt-serial driver driver, which has a corresponding topic-"channel"("control") Relay 1. It has a value - 0 (relay off), and there are two subtopics. One of them is service: the type of "control" is written in the folder /meta/type. Here it is a switch - circuit-breaker. The second subtopic /on is more interesting: here clients write the state in which they want to set the relay. Note that it may not coincide for some time (spent on the switching process) with the state in which the relay is located. The driver behaves as follows: when receiving a message in the topic /devices/wb-mrm2_130/controls/Relay 1/on, it physically turns on the relay module, and only then writes the new state of the relay to the topic /devices/wb-mrm2_130/controls/Relay.
For example, if we now click on the relay button in the web interface (switch its state), we will receive new messages:
/devices/wb-mrm2_130/controls/Relay 1/on 1 /devices/wb-mrm2_130/controls/Relay 1 1
- the web interface first "instructs" to turn on the relay, then the driver turns it on and records the current state in the "channel"("control").
Working with message queue
The program (daemon) responsible for sending messages from one client to another is called a message broker. Wiren Board uses Mosquitto message broker. In fact, all drivers and the web interface transmit their messages to this daemon broker
Working via the command line
Managing devices from the command line
To control the device (change the channel value), you need to send a message to the topic
"/devices/<device-id>/controls/<control-id>/on" This is done using the mosquitto_pub console command. Example:
root@wirenboard:~# mosquitto_pub -t "/devices/wb-mrm2_130/controls/Relay 1/on" -m "1"
the command sends the message "1" (logical unit, "turn on") to the topic corresponding to the connected via RS-485 relay module WM-MRM2 with the address 130.
Tracking the status of the device / subscribe to topic
Customers who want to monitor the temperature value, "subscribe" to this topic, and they receive new messages - changing temperature values. One such client is the web interface.
You can also subscribe to messages from the Linux console using the mosquitto_sub utility (for a full description of the utility, see The article):
root@wirenboard:~# mosquitto_sub -t '/devices/wb-w1/controls/28-0115a48fcfff' -v //receive messages from a topic of the 1-Wire device with ID: 28-0115a48fcfff
/devices/wb-w1/controls/28-0115a48fcfff 22.75 //in this line and below is the output of the utility received messages
/devices/wb-w1/controls/28-0115a48fcfff 22.75
/devices/wb-w1/controls/28-0115a48fcfff 22.75
Metacharacters
You can subscribe not just for one topic, but for a group of topics by metasymbol. In MQTT we use two special characters: # and +. The special character # means any number of levels of nested topics. Execute the command
root@wirenboard:~# mosquitto_sub -t '/devices/wb-w1/#' -v
/devices/wb-w1/meta/name 1-wire Thermometers
/devices/wb-w1/controls/28-0115a48fcfff 22.812
/devices/wb-w1/controls/28-0115a48fcfff/meta/type temperature
/devices/wb-w1/controls/28-0115a48fcfff 22.75
As a result, we got not only the values from the control device, but also topics with metadata - the name of the device driver and the type of "control" - temperature. There is also a metacharacter +, which denotes one level, not an arbitrary number,as #:
mosquitto_sub -v -t "/config/widgets/+/name"
In this case we will get the names of all widgets.
Full description of topics and subscriptions:http://mosquitto.org/man/mqtt-7.html.
Clearing the message queue
Unnecessary retained messages may remain in the MQTT system after unused drivers are removed or any devices are disconnected. This causes nonexistent devices to appear in the Devices section of the web interface.
Для удаления топиков можно воспользоваться командой mqtt-delete-retained. Пример использования:
root@wirenboard:~# mqtt-delete-retained '/devices/noolite_tx_1234/#'
- удалит все топики, начинающиеся на '/devices/noolite_tx_1234/'
Для удаления топиков "по маске", можно циклично вызывать runShellCommand из правил. Таким образом, задача сводится к задаче работы со строками в js.
var deviceName = ['name1',.., 'nameN'];
var controlName = 'Temperature';
for (var i = 0; i<deviceName.length; i++) {
runShellCommand ('mqtt-delete-retained /devices/'+ deviceName[i] + '/controls/controlName/#');
}
Работа с очередью из внешних программ
Если вы разрабатываете собственное ПО для Wiren Board, взаимодействовать с его аппаратными ресурсами лучше всего через очередь сообщений - ваша программа передаёт сообщение в очередь, драйвер управляет устройством, и вашей программе не нужно напрямую взаимодействовать с устройством на низком уровне.
Для того, чтобы отправлять сообщения MQTT, для многих языков программирования есть библиотеки. Примеры:
Просмотр MQTT-каналов в web-интерфейсе
MQTT-названия устройств, их элементов управления и последние значения можно найти в разделе Settings web-интерфейса:
Настройка MQTT моста (bridge)
MQTT мост (bridge) - это функция MQTT-брокера, позволяющая пересылать все или часть сообщений на другой MQTT-брокер, и получать сообщения с другого брокера обратно. На контроллере эта функция настраивается в конфигурационных файлах mosquitto. Самый простой вариант конфигурации приведён ниже.
Задача: настроить пересылку всех сообщений MQTT на популярный бесплатный облачный MQTT брокер http://cloudmqtt.com/ и обратно.
Решение:
- Зарегистрируйтесь на http://cloudmqtt.com/
- Зайдите в свой аккаунт на http://cloudmqtt.com/ и посмотрите настройки: сервер, порт, логин, пароль.
- Зайдите на контроллер и добавьте в конец файла /etc/mosquitto/mosquitto.conf следующие строки:
connection cloudmqtt address m21.cloudmqtt.com:10858 remote_username fs_user_kp remote_password 5dn_pass_pm clientid pavel_test try_private false start_type automatic topic # both
- (последняя строка говорит, что нужно пересылать все сообщения (метасимвол #, смотрите описание выше) в обе (both) стороны (с брокера контроллера на облачный брокер и обратно)
- Более подробное описание всех опций смотрите на https://mosquitto.org/man/mosquitto-conf-5.html.
- Перезапустите mosquitto, выполнив в консоли
service mosquitto restart