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

Материал из Wiren Board
(Новая страница: «Install the necessary components: <syntaxhighlight lang="bash"> apt update && apt install -y nodejs git make g++ gcc build-essential </syntaxhighlight>»)
Метки: правка с мобильного устройства правка из мобильной версии
 
(не показаны 23 промежуточные версии этого же участника)
Строка 30: Строка 30:
== Creating a project ==  
== Creating a project ==  


Для автозапуска Node-RED необходимо настроить сервис. Для этого в папке <code>/etc/systemd/system/</code> создайте файл <code>nodered.service</code>:
To autostart Node-RED, you need to configure the service. To do this, in the <code>/etc/systemd/system/</code> folder, create the <code>nodered.service</code> file:


<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
Строка 36: Строка 36:
</syntaxhighlight>
</syntaxhighlight>


Затем вставьте в этот файл строки:
Then paste the lines into this file:
<pre>
<pre>
[Unit]
[Unit]
Строка 59: Строка 59:
</pre>
</pre>


Сохраните изменения и закройте файл. Теперь включите сервис и запустите его командой:
Save changes and close the file. Now enable the service and start it with the command:


<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
Строка 65: Строка 65:
</syntaxhighlight>
</syntaxhighlight>


Проверьте статус сервиса командой, в выводе должна быть строчка <code>Active: active (running)</code>:
Check the status of the service with the command, the output should contain the line <code>Active: active (running)</code>:
<syntaxhighlight lang="console">
<syntaxhighlight lang="console">
# systemctl status nodered
# systemctl status nodered
Строка 85: Строка 85:
</syntaxhighlight>
</syntaxhighlight>


== Удаление ==
== Delete ==
Если вам больше не нужен Node-RED, то его можно удалить:
If you no longer need Node-RED, then you can remove it:
# Остановите, отключите и удалите сервис:
# Stop, disable and remove the service:
#:<syntaxhighlight lang="bash">
#:<syntaxhighlight lang="bash">
systemctl stop nodered && systemctl disable nodered && rm /etc/systemd/system/nodered.service
systemctl stop nodered && systemctl disable nodered && rm /etc/systemd/system/nodered.service
</syntaxhighlight>
</syntaxhighlight>
# Удалите сам Node-RED:
# Remove Node-RED:
#:<syntaxhighlight lang="bash">
#:<syntaxhighlight lang="bash">
npm -g remove node-red && npm -g remove node-red-admin && rm -R ~/.node-red
npm -g remove node-red && npm -g remove node-red-admin && rm -R ~/.node-red
</syntaxhighlight>
</syntaxhighlight>


Node.js, тоже можно удалить, но убедитесь, что у вас не установлены другие програмы, которые его используют, например, zigbee2mqtt. Чтобы удалить node.js, выполните команду:
Node.js can also be removed, but make sure you don't have other programs installed that use it, such as zigbee2mqtt. To remove node.js run the command:
:<syntaxhighlight lang="bash">
:<syntaxhighlight lang="bash">
apt remove nodejs
apt remove nodejs
</syntaxhighlight>
</syntaxhighlight>


==Веб-интерфейс Node-RED==
==Node-RED Web Interface==
После запуска сервиса откройте браузер и введите адрес своего контроллера в сети и порт 1880.  
After starting the service, open a browser and enter the address of your controller on the network and port 1880.
Например: http://192.168.42.1:1880
For example: http://192.168.42.1:1880


Инструкции по работе c Node-RED можно найти на [https://nodered.org/docs/getting-started/ сайте nodered.org]
Instructions for working with Node-RED can be found at [https://nodered.org/docs/getting-started/ site nodered.org]


== WB Nodes ==
== WB Nodes ==
[[Файл:Installing node-red-contrib-wirenboard.PNG|500px|thumb|right| Установка WB Nodes на контроллер Wiren Board]]
[[File:Installing node-red-contrib-wirenboard.PNG|500px|thumb|right| Installing WB Nodes on a Wiren Board Controller]]
[[Image: nr+wb-settings.png |600px|thumb|right|Настройка соединения с контроллером Wiren Board]]
[[Image: nr+wb-settings.png |600px|thumb|right|Configuring the connection to the Wiren Board controller]]
Чтобы упростить взаимодействие Node-RED с контроллером Wiren Board, пользователь [https://support.wirenboard.com/t/node-red-contrib-wirenboard/2019 Andrej_Popov] написал модуль <code>node-red-contrib-wirenboard</code>.
To simplify the interaction of Node-RED with the Wiren Board controller, the user [https://support.wirenboard.com/t/node-red-contrib-wirenboard/2019 Andrej_Popov] wrote the module <code>node-red-contrib-wirenboard</code>.


=== Установка ===
=== Installation ===
Установим его через [[#Веб-интерфейс Node-RED | веб-интерфейс Node-RED]]:
Install it via Node-RED web-interface:
{{Node-RED Installing plugin
{{Node-RED Installing plugin
|search= wirenboard
|search= wirenboard
|name= node-red-contrib-wirenboard
|name= node-red-contrib-wirenboard
|en= true
}}
}}


После установки, в левой панели появится секция Wiren Board.
After installation, the Wiren Board section will appear in the left panel.
=== Настройка ===
=== Setting ===
После того как вы установили WB Nodes, вам нужно настроить соединение с MQTT-брокером контроллера Wiren Board:
After you have installed WB Nodes, you need to set up a connection to the MQTT broker of the Wiren Board controller:
# Добавьте в рабочую область ноду '''WB-input''', которая находится в левой панели, в секции '''Wiren Board'''.
# Add a '''WB-input''' node to the workspace, which is located in the left panel, in the '''Wiren Board''' section.
# Дважды кликните на ней, откроется окно '''Edit in node'''.
# Double click on it, the '''Edit in node''' window will open.
# Найдите в нём поле '''Server''' и нажмите на кнопку с карандашом. Откроется окно '''Add new wirenboard-server config node'''.
# Find the field '''Server''' and click on the pencil button. The '''Add new wirenboard-server config node''' window will open.
# Заполните поля '''Name''', '''Host''' и '''MQTT Port'''. Если Node-RED установлен на контроллере — в поле Host пропишите <code>localhost</code>. В поле '''Name''' укажите произвольное имя, а в поле '''MQTT Port''' — 1883.
# Fill in the '''Name''', '''Host''' and '''MQTT Port''' fields. If Node-RED is installed on the controller, enter <code>localhost</code> in the Host field. Enter an arbitrary name in the '''Name''' field, and 1883 in the '''MQTT Port''' field.
# Сохраните настройки сервера нажатием на кнопку '''Done'''.
# Save the server settings by clicking on the '''Done''' button.
# Закройте окно '''Edit in node''' нажатием на '''Cancel'''.
# Close the '''Edit in node''' window by clicking on '''Cancel'''.
{{note|info| После настройки подключения, примените настройку сервера нажатием кнопки '''Deploy''' справа вверху. Только после этого будет доступен список каналов контроллера Wiren Board.}}
{{note|info| After setting up the connection, apply the server setting by clicking the '''Deploy''' button on the top right. Only after that the list of channels of the Wiren Board controller will be available.}}


Вы настроили WB Nodes и можете писать автоматизации с использованием Node-RED.
You have set up WB Nodes and can write automations using Node-RED.


=== Проверка настроек ===
=== Checking settings ===
Чтобы проверить правильность настроек:
To check if the settings are correct:
# Добавьте в рабочую область любую ноду из группы Wiren Board, например, '''WB-input'''.
# Add any node from the Wiren Board group to the workspace, for example, '''WB-input'''.
# Дважды кликните на ноде '''WB-input''', откроется окно '''Edit in node'''.
# Double click on the '''WB-input''' node, the '''Edit in node''' window will open.
# В окне '''Edit in node''' нажмите кнопку '''Refresh Device List'''.
# In the '''Edit in node''' window, click the '''Refresh Device List''' button.


Если соединение настроено верно, то в выпадающем списке поля '''Сhannel''' появится список доступных для использования каналов.
If the connection is configured correctly, then the drop-down list of the '''Сhannel''' field will display a list of channels available for use.


=== Примеры ===
=== Examples ===
В комплекте с WB-Nodes есть примеры для [[Node-RED Apple HomeKit | Apple HomeKit]] и Яндекс.Алисы, найти их можно в '''Menu''' → '''Import''' → '''Examples'''.
WB-Nodes comes with examples for [[Node-RED Apple HomeKit | Apple HomeKit]] and Yandex.Alice, you can find them in '''Menu''' → '''Import''' → '''Examples'''.
<gallery mode="packed" heights="200px" caption="Примеры из комплекта WB-Nodes">
<gallery mode="packed" heights="200px" caption="Examples from WB-Nodes">
Image: WB-Nodes Examples 1.png | Список примеров
Image: WB-Nodes Examples 1.png | List of examples
Image: WB-Nodes Examples 2.png | Пример в рабочей области
Image: WB-Nodes Examples 2.png | Example in workspace
</gallery>
</gallery>


== Использование нод ''mqtt in'' и ''mqtt out'' для взаимодействия с Wiren Board ==
== Using the ''mqtt in'' and ''mqtt out'' nodes to interact with the Wiren Board ==
=== Настройка подключения ===
=== Connection setup ===
[[Image: NodeRed_mqtt_nodes.jpg |300px|thumb|right| Ноды MQTT в Node-Red ]]
[[Image: NodeRed_mqtt_nodes.jpg |300px|thumb|right| MQTT Nodes in Node-Red ]]
Альтернативный вариант — использовать ноды '''mqtt in''' и  '''mqtt out'''. Для этого вам понадобятся адреса топиков, взять их можно в веб-интерфейсе контроллера на странице [[Wiren Board Web Interface#mqtt-channels |MQTT-каналы]].
An alternative is to use the '''mqtt in''' and '''mqtt out''' nodes. To do this, you need the addresses of the topics, you can get them in the controller web interface on the [[Wiren Board Web Interface#mqtt-channels |MQTT-channels]] page.


Для настройки MQTT-соединения в Node-RED выполните следующие действия:
To set up an MQTT connection in Node-RED, follow these steps:
#Перетащите ноду '''mqtt in''' в рабочую область.  
#Drag the '''mqtt in''' node to the workspace.
#Войдите в конфигурацию ноды и нажмите на '''Карандаш''' напротив поля '''Server'''.  
#Enter the node configuration and click on the '''Pencil''' next to the '''Server''' field.
#На вкладке '''Connecting''' задайте адрес брокера и номер порта.  
#On the '''Connecting''' tab, set the broker address and port number.
#:В поле '''Name''' введите любое имя сервера.  
#:In the '''Name''' field, enter any server name.
#:На вкладке '''Security''' можно указать Имя пользователя и Пароль для подключения к брокеру. Если в качестве брокера выступает контроллер Wiren Board, это поле нужно оставить пустым.
#:On the '''Security''' tab, you can specify the Username and Password to connect to the broker. If the Wiren Board controller acts as a broker, this field must be left blank.
#После заполнения всех полей нажмите кнопку '''Update'''. Созданный брокер теперь можно использовать для настройки всех подключений.
#After filling in all the fields, click the '''Update''' button. The created broker can now be used to set up all connections.
#Выберите созданные брокер из списка в поле '''Server'''.
#Select the created broker from the list in the '''Server''' field.
#Введите адрес mqtt-топика в поле '''Topic'''.  
#Enter mqtt-topic address in the '''Topic''' field.
#Нажмите кнопку '''Done'''.
#Press the '''Done''' button.


По такому же принципу настраивается нода '''mqtt out'''.
The '''mqtt out''' node is configured according to the same principle.
<gallery mode="packed" heights="150px" caption="Настройка MQTT-брокера (Server)>
<gallery mode="packed" heights="150px" caption="Configuring MQTT Broker (Server)>
Image: NodeRed_mqtt2.jpg | Вкладка ''Connecting''
Image: NodeRed_mqtt2.jpg | ''Connecting'' tab
Image: NodeRed_mqtt3.jpg | Вкладка ''Security''
Image: NodeRed_mqtt3.jpg | Tab ''Security''
</gallery>
</gallery>


=== Отправка команд ===
=== Sending commands ===
Для отправки команды контроллеру по MQTT используется нода '''mqtt out'''. При этом в поле '''Topic''' указывается адрес mqtt-топика контроллера, в который необходимо записать параметр. Нужно учитывать, что в конце адреса ноды '''mqtt out''' нужно написать <code>/on</code>, иначе параметр в топик не запишется. Например, <code>/devices/wb-mrgbw-d-fw3_129/controls/RGB Strip/on</code>. Подробнее читайте на странице [[MQTT | MQTT]].
The '''mqtt out''' node is used to send a command to the controller via MQTT. In this case, the '''Topic''' field specifies the address of the mqtt-topic of the controller, in which the parameter must be written. Please note that at the end of the node address '''mqtt out''' you need to write <code>/on</code>, otherwise the parameter will not be written to the topic. For example, <code>/devices/wb-mrgbw-d-fw3_129/controls/RGB Strip/on</code>. Read more on the [[MQTT | MQTT]].
<gallery mode="packed" heights="150px" caption="Настройка нод для работы с MQTT">
<gallery mode="packed" heights="150px" caption="Configuring nodes to work with MQTT">
Image: NodeRed_mqtt4.jpg | Пример настройки ноды '''mqtt in'''
Image: NodeRed_mqtt4.jpg | '''mqtt in''' node configuration example
Image: mqtt_out_no.jpg | Пример настройки ноды '''mqtt out'''
Image: mqtt_out_no.jpg | '''mqtt out''' node setup example
Image: NodeRed_mqtt1.jpg | Обмен данными через MQTT в Node-Red
Image: NodeRed_mqtt1.jpg | Communication via MQTT in Node-Red
</gallery>
</gallery>
Для отправки параметра в ноду '''mqtt out''' можно использовать ноду '''inject'''.
To send a parameter to the '''mqtt out''' node, you can use the '''inject''' node.
#Перетащите ноду '''inject''' в рабочую область.
#Drag the '''inject''' node to the workspace.
#Подключите ее ко входу ноды '''mqtt out'''.
#Connect it to the input of the '''mqtt out''' node.
#Зайдите в настройки ноды '''inject''' и задайте ''Имя'' ноды, ''Тип переменной'' и ее ''Значение''. Нажмите кнопку '''Done'''.
#Go to the settings of the '''inject''' node and set the ''Name'' of the node, the ''Variable Type'' and its ''Value''. Click the '''Done''' button.
<gallery mode="packed" heights="130px">
<gallery mode="packed" heights="130px">
Image: Inject1.jpg | Пример настроек ноды '''inject''' для управления дискретным параметром
Image: Inject1.jpg | An example of '''inject''' node settings for controlling a discrete parameter
Image: Inject2.jpg | Поле настройки периодов повторения отправки ноды '''inject'''
Image: Inject2.jpg | '''inject''' node retry period setting field
</gallery>
</gallery>
<gallery mode="packed" heights="100px">
<gallery mode="packed" heights="100px">
Image: Node_inject.jpg | Пример использования ноды '''inject'''
Image: Node_inject.jpg | An example of using the '''inject''' node
</gallery>
</gallery>


После настройки ввода и вывода можно обрабатывать данные внутри Node-RED и настроить использование сторонних сервисов, например, [[Node-RED_Alice | Умный дом с Алисой]].
After setting up input and output, you can process data inside Node-RED and set up the use of third-party services, for example, [[Node-RED_Alice | Smart home with Alice]].


<gallery mode="packed" heights="150px">
<gallery mode="packed" heights="150px">
Image: NodeRed_mqtt5.jpg | Пример управления с помощью Алисы
Image: NodeRed_mqtt5.jpg | Alice control example
</gallery>
</gallery>


== Примеры использования ==
== Usage examples ==
Примеры использования Node-RED с WB-Nodes на контроллерах Wiren Board:
Examples of using Node-RED with WB-Nodes on Wiren Board controllers:
* [[Node-RED_Telegram | Настройка Telegram-бота]].
* [[Node-RED_Telegram | Telegram bot settings]].
* [[Node-RED_Alice | Настройка Алисы на контроллере Wiren Board]].
* [[Node-RED_Alice | Setting up Alice on the Wiren Board controller]].
* [[Node-RED Apple HomeKit | Настройка Apple HomeKit на контроллере Wiren Board]].
* [[Node-RED Apple HomeKit | Setting up Apple HomeKit on a Wiren Board controller]].
* [[Node-RED Dashboards|Создание панелей (Dashboards) в Node-RED]].
* [[Node-RED Dashboards|Creating Dashboards in Node-RED]].
* [https://youtu.be/cKQmU4LZo4c Видео от нашего партнёра: Wiren Board + Node-RED]
* [https://youtu.be/cKQmU4LZo4c Video from our partner: Wiren Board + Node-RED]

Текущая версия на 09:50, 21 октября 2022

Другие языки:
Node-RED on the Wiren Board controller

Description

Wiren Board Node-RED Video Tutorial by SetPoint

Node-RED is a visual programming tool based on Node.js and developed and maintained by an open community.

A detailed description, instructions and examples of use can be found on the site nodered.org, and community support in the telegram channel Node-RED.

Copy the commands from the instructions, paste them into controller console using the Shift+Insert keys and run with the Enter key. In case of errors, carefully read the output, there will be instructions and hints.

Installation

To install Node-RED 2.2 on a Wiren Board controller, connect to it via SSH and enter a few commands into the console.

Install the necessary components:

apt update && apt install -y nodejs git make g++ gcc build-essential

Run the Node-RED installation:

npm install -g --unsafe-perm node-red@2.2

If you need to upgrade your Node-RED version, run the install command again.

Creating a project

To autostart Node-RED, you need to configure the service. To do this, in the /etc/systemd/system/ folder, create the nodered.service file:

mcedit /etc/systemd/system/nodered.service

Then paste the lines into this file:

[Unit]
Description=Node-RED graphical event wiring tool
Wants=network.target

[Service]
Type=simple
User=root
Group=root
WorkingDirectory=/home

Nice=5
Environment="NODE_OPTIONS=--max_old_space_size=256"
ExecStart=/usr/bin/env node-red $NODE_OPTIONS $NODE_RED_OPTIONS
KillSignal=SIGINT
Restart=on-failure
SyslogIdentifier=Node-RED

[Install]
WantedBy=multi-user.target

Save changes and close the file. Now enable the service and start it with the command:

systemctl enable nodered && systemctl start nodered

Check the status of the service with the command, the output should contain the line Active: active (running):

# systemctl status nodered
● nodered.service - Node-RED graphical event wiring tool
   Loaded: loaded (/etc/systemd/system/nodered.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2021-12-03 06:32:25 UTC; 24s ago
 Main PID: 2757 (node)
   CGroup: /system.slice/nodered.service
           └─2757 node /usr/bin/node-red --max_old_space_size=256

Dec 03 06:32:25 wirenboard-AWQBNTYP systemd[1]: Started Node-RED graphical event wiring tool.
Dec 03 06:32:36 wirenboard-AWQBNTYP Node-RED[2757]: 3 Dec 06:32:36 - [info]
Dec 03 06:32:36 wirenboard-AWQBNTYP Node-RED[2757]: Welcome to Node-RED
Dec 03 06:32:36 wirenboard-AWQBNTYP Node-RED[2757]: ===================
Dec 03 06:32:36 wirenboard-AWQBNTYP Node-RED[2757]: 3 Dec 06:32:36 - [info] Node-RED version: v2.1.4
Dec 03 06:32:36 wirenboard-AWQBNTYP Node-RED[2757]: 3 Dec 06:32:36 - [info] Node.js  version: v12.19.0
Dec 03 06:32:36 wirenboard-AWQBNTYP Node-RED[2757]: 3 Dec 06:32:36 - [info] Linux 5.10.35-wb6 arm LE
Dec 03 06:32:41 wirenboard-AWQBNTYP Node-RED[2757]: 3 Dec 06:32:41 - [info] Loading palette nodes

Delete

If you no longer need Node-RED, then you can remove it:

  1. Stop, disable and remove the service:
    systemctl stop nodered && systemctl disable nodered && rm /etc/systemd/system/nodered.service
    
  2. Remove Node-RED:
    npm -g remove node-red && npm -g remove node-red-admin && rm -R ~/.node-red
    

Node.js can also be removed, but make sure you don't have other programs installed that use it, such as zigbee2mqtt. To remove node.js run the command:

apt remove nodejs

Node-RED Web Interface

After starting the service, open a browser and enter the address of your controller on the network and port 1880. For example: http://192.168.42.1:1880

Instructions for working with Node-RED can be found at site nodered.org

WB Nodes

Installing WB Nodes on a Wiren Board Controller
Configuring the connection to the Wiren Board controller

To simplify the interaction of Node-RED with the Wiren Board controller, the user Andrej_Popov wrote the module node-red-contrib-wirenboard.

Installation

Install it via Node-RED web-interface:

  1. Log into the Node-RED web-interface.
  2. In the upper right corner, open the menu.
  3. In the window that opens, select the Palette Management tab.
  4. Go to the Install tab, type wirenboard into the search field and press Enter on your keyboard.
  5. Install the package named node-red-contrib-wirenboard.
  6. Close the settings window. Module installation completed.

After installation, the Wiren Board section will appear in the left panel.

Setting

After you have installed WB Nodes, you need to set up a connection to the MQTT broker of the Wiren Board controller:

  1. Add a WB-input node to the workspace, which is located in the left panel, in the Wiren Board section.
  2. Double click on it, the Edit in node window will open.
  3. Find the field Server and click on the pencil button. The Add new wirenboard-server config node window will open.
  4. Fill in the Name, Host and MQTT Port fields. If Node-RED is installed on the controller, enter localhost in the Host field. Enter an arbitrary name in the Name field, and 1883 in the MQTT Port field.
  5. Save the server settings by clicking on the Done button.
  6. Close the Edit in node window by clicking on Cancel.

After setting up the connection, apply the server setting by clicking the Deploy button on the top right. Only after that the list of channels of the Wiren Board controller will be available.

You have set up WB Nodes and can write automations using Node-RED.

Checking settings

To check if the settings are correct:

  1. Add any node from the Wiren Board group to the workspace, for example, WB-input.
  2. Double click on the WB-input node, the Edit in node window will open.
  3. In the Edit in node window, click the Refresh Device List button.

If the connection is configured correctly, then the drop-down list of the Сhannel field will display a list of channels available for use.

Examples

WB-Nodes comes with examples for Apple HomeKit and Yandex.Alice, you can find them in MenuImportExamples.

Using the mqtt in and mqtt out nodes to interact with the Wiren Board

Connection setup

MQTT Nodes in Node-Red

An alternative is to use the mqtt in and mqtt out nodes. To do this, you need the addresses of the topics, you can get them in the controller web interface on the MQTT-channels page.

To set up an MQTT connection in Node-RED, follow these steps:

  1. Drag the mqtt in node to the workspace.
  2. Enter the node configuration and click on the Pencil next to the Server field.
  3. On the Connecting tab, set the broker address and port number.
    In the Name field, enter any server name.
    On the Security tab, you can specify the Username and Password to connect to the broker. If the Wiren Board controller acts as a broker, this field must be left blank.
  4. After filling in all the fields, click the Update button. The created broker can now be used to set up all connections.
  5. Select the created broker from the list in the Server field.
  6. Enter mqtt-topic address in the Topic field.
  7. Press the Done button.

The mqtt out node is configured according to the same principle.

Sending commands

The mqtt out node is used to send a command to the controller via MQTT. In this case, the Topic field specifies the address of the mqtt-topic of the controller, in which the parameter must be written. Please note that at the end of the node address mqtt out you need to write /on, otherwise the parameter will not be written to the topic. For example, /devices/wb-mrgbw-d-fw3_129/controls/RGB Strip/on. Read more on the MQTT.

To send a parameter to the mqtt out node, you can use the inject node.

  1. Drag the inject node to the workspace.
  2. Connect it to the input of the mqtt out node.
  3. Go to the settings of the inject node and set the Name of the node, the Variable Type and its Value. Click the Done button.

After setting up input and output, you can process data inside Node-RED and set up the use of third-party services, for example, Smart home with Alice.

Usage examples

Examples of using Node-RED with WB-Nodes on Wiren Board controllers: