MQTT/en: различия между версиями

Материал из Wiren Board
(Новая страница: «In order to send MQTT messages, there are libraries for many programming languages. Examples: * Python - [https://github.com/contactless/mqtt-tools] * C - [http:/…»)
(Перевода всё равно нет, сделал переадресацию на русскую)
Метка: новое перенаправление
 
(не показано 5 промежуточных версий 2 участников)
Строка 1: Строка 1:
<languages/>
#REDIRECT [[MQTT]]
'''MQTT''' - is a message queue used in the [[Программное обеспечение Wiren Board/en|Wiren Board software]]. [http://en.wikipedia.org/wiki/MQTT 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===
[[File:Web-devices-1-wire.png|400px|thumb|Sensor readings and its unique identifier on the '''Devices''' page of 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  ([https://github.com/contactless/wb-homa-drivers/tree/master/wb-homa-w1 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: <pre>/devices/wb-w1/controls/28-0115a48fcfff 23.25</pre>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===
[[File:Web-devices-serial.png|400px|thumb|Web interface after pressing relay 1 on the relay module [[WB-MRM2/en| MRM2]] CONNECTED via RS-485]]
Suppose that the relay module WB-MRM2 is connected to the controller via the [[RS-485/en| 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:<pre>/devices/wb-mrm2_130/controls/Relay 1/on 1</pre>It means that the device WB-MRM2 with the address ''130'' must transfer Relay 1 to the state of the logical 1 - "on".
#[[Драйвер wb-mqtt-serial/en|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:<pre>/devices/wb-mrm2_130/controls/Relay 1 1</pre>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 ==
[[File:MQTT.png | thumb | 600px | Drivers of internal functions, external devices, web interface, rules system work via the MQTT 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 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 ([https://github.com/contactless/homeui/blob/master/conventions.md 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 [[Обновление прошивки/en|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:
<pre>
/devices/wb-w1/controls/28-0115a48fcfff 23.25
</pre>
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):
<syntaxhighlight lang="bash">
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
</syntaxhighlight>
 
=== 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:
<syntaxhighlight lang="bash">
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
</syntaxhighlight>
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:
<pre>
/devices/wb-mrm2_130/controls/Relay 1/on 1
/devices/wb-mrm2_130/controls/Relay 1 1
</pre>
- 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  [http://mosquitto.org/ 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:
<syntaxhighlight lang="bash">
root@wirenboard:~# mosquitto_pub -t "/devices/wb-mrm2_130/controls/Relay 1/on" -m "1"
</syntaxhighlight>
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 [http://mosquitto.org/man/mosquitto_sub-1.html The article]):
<syntaxhighlight lang="bash">
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
</syntaxhighlight>
===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
<syntaxhighlight lang="bash">
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
</syntaxhighlight>
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 '''#''':
<syntaxhighlight lang="bash">
mosquitto_sub -v -t "/config/widgets/+/name"
</syntaxhighlight>
In this case we will get the names of all widgets.
 
 
Full description of topics and subscriptions:[http://mosquitto.org/man/mqtt-7.html 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.
 
To delete topics, you can use the command ''mqtt-delete-retained''. Example of use:
<syntaxhighlight lang="bash">
root@wirenboard:~# mqtt-delete-retained '/devices/noolite_tx_1234/#'
</syntaxhighlight>
- removes all topics starting with '/devices/noolite_tx_1234/'
 
To remove the topics by the "mask", it is possible to call runShellCommand of the rules cyclically. Thus, the task is reduced to the task of working with strings in js.
<syntaxhighlight lang="bash">
var deviceName = ['name1',.., 'nameN'];
var controlName = 'Temperature';
 
for (var i = 0; i<deviceName.length; i++) {
  runShellCommand ('mqtt-delete-retained /devices/'+ deviceName[i] + '/controls/controlName/#');
}
</syntaxhighlight>
 
=== Working with queue from external programs ===
 
If you are developing your own SOFTWARE for the Wiren Board, it is best to communicate with its hardware resources through a message queue - your program sends a message to the queue, the driver controls the device, and your program does not need to communicate directly with the device at a low level.
 
In order to send MQTT messages, there are libraries for many programming languages. Examples:
* Python - [https://github.com/contactless/mqtt-tools]
* C - [http://mosquitto.org/man/libmosquitto-3.html]
 
 
=== Просмотр MQTT-каналов в web-интерфейсе ===
MQTT-названия устройств, их элементов управления и последние значения можно найти в разделе Settings web-интерфейса:
[[Файл:Wb_settings.png|900px|thumb|center|Информация об MQTT-названиях устройств]]
 
=== Настройка MQTT моста (bridge) ===
[[File:CloudMQTT.png | thumb | 400px | Настройки брокера Cloud MQTT]]
MQTT мост (bridge) - это функция MQTT-брокера, позволяющая пересылать все или часть сообщений на другой MQTT-брокер, и получать сообщения с другого брокера обратно. На контроллере эта функция настраивается в конфигурационных файлах ''mosquitto''. Самый простой вариант конфигурации приведён ниже.
 
'''Задача:''' настроить пересылку всех сообщений MQTT на популярный бесплатный облачный MQTT брокер http://cloudmqtt.com/ и обратно.
 
'''Решение:'''
# Зарегистрируйтесь на http://cloudmqtt.com/
# Зайдите в свой аккаунт на http://cloudmqtt.com/ и посмотрите настройки: сервер, порт, логин, пароль.
# Зайдите на контроллер и добавьте в конец файла ''/etc/mosquitto/mosquitto.conf'' следующие строки:
#: <syntaxhighlight lang="bash">
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
</syntaxhighlight>
#: (последняя строка говорит, что нужно пересылать все сообщения (метасимвол '''#''', смотрите описание выше) в обе ('''both''') стороны (с брокера контроллера на облачный брокер и обратно)
#: Более подробное описание всех опций смотрите на https://mosquitto.org/man/mosquitto-conf-5.html.
# Перезапустите mosquitto, выполнив в консоли
#: <syntaxhighlight lang="bash">
service mosquitto restart
</syntaxhighlight>

Текущая версия на 12:29, 4 июля 2023

Перенаправление на: