Node-RED:Введение/Установка
Содержание
Установка [1]
Перед тем, как приступить к установке Node-RED, у вас должна быть установлена рабочая версия Node.js. Рекомендуем использовать Node.js LTS 8.x или 10.x. Пользователи Node.js 6.x должны убедиться, что у них установлены самые последние обновления. Node-RED больше не поддерживает Node.js 4.x и ранее.
У нас есть специальные руководства по установке Node-RED на разных платформах и ОС:
Пользователям Linux и OSX нужно будет установить пакетную версию Node.js, соответствующую их ОС, или скачать последнюю версию Long Term Support (LTS) с сайта Node.js.
Версию своей Node.js можно узнать с помощью следующей команды:
Другие варианты загрузки Node.js смотрите по этой ссылке.
Самый простой способ установить Node-RED – при помощи пакетного менеджера npm (сокр. от англ. «node package manager»), идущего в комплекте с Node.js. Чтобы установить Node-RED в качестве глобального модуля, воспользуйтесь следующей командой:
Примечание: Команда «sudo» нужна только при установке на Linux и OS X. Если вы работаете на Windows, читайте соответствующее руководство.
Что дальше
Когда Node-RED будет установлен, вы сможете его запустить.
Другие способы установки
Скачайте нужную вам версию
Вы можете сразу скачать последнюю или любую другую версию Node-RED отсюда. В скачанном ZIP-архиве будет папка верхнего уровня под названием «node-red-X.Y.Z», где «X.Y.Z» – это номер версии Node-RED. Распаковав архив и будучи в папке верхнего уровня, запустите вот эту команду:
Скачайте с GitHub (для разработчиков)
GitHub-код предназначен только для тех, кто хочет использовать код для разработки, или для разработчиков, которые хотят внести вклад в код Node-RED. Вы можете клонировать репозиторий исходного кода прямо с GitHub:
После клонирования необходимо установить необходимые модули ядра:
Примечание: Чтобы вы могли запустить код, клонированный из Git-репозитория, вам необходимо установить все зависимости, а не только те, что непосредственно используются в проекте. Поэтому флаг «—production» использовать не нужно.
Вам также нужно будет установить Grunt CLI (grunt-cli), чтобы собрать приложение перед тем, как воспользоваться им. Это тоже нужно делать глобально.
После этого собираем и запускаем приложение:
Что дальше
Когда Node-RED будет установлен, вы сможете его запустить.
Running on Windows
This page gives specific instructions on setting up Node-RED in a Microsoft Windows environment. The instructions are specific to Windows 10 but should also work for Windows 7 and Windows Server from 2008R2. It is not advisable to use versions prior to Windows 7 or Windows Server 2008R2 due to lack of current support.
Quick Start
1. Install Node.js
Download the latest 12.x LTS version of Node.js from the official Node.js home page. It will offer you the best version for your system.
Run the downloaded MSI file. Installing Node.js requires local administrator rights; if you are not a local administrator, you will be prompted for an administrator password on install. Accept the defaults when installing. After installation completes, close any open command prompts and re-open to ensure new environment variables are picked up.
Once installed, open a command prompt and run the following command to ensure Node.js and npm are installed correctly.
Using Powershell: node —version; npm —version
Using cmd: node —version && npm —version
You should receive back output that looks similar to:
2. Install Node-RED
Installing Node-RED as a global module adds the command node-red to your system path. Execute the following at the command prompt:
3. Run Node-RED
Once installed, you are ready to run Node-RED.
Alternative Installations on Windows
In this section, we provide you with information on alternative ways to install Node.js, npm and the Windows Build Tools needed to install some Nodes for Node-RED on Windows.
Standard installations of Node.js on Windows require local administrator rights. Download the appropriate version from the official Node.js home page. It will offer you the best version. While you can use either 32 bit or 64 bit versions on 64 bit Windows, it is recommended to use the 64bit version of Node. If for some reason, you need a different installation, you can use the Downloads Page.
There are two potentially useful alternatives to installing Node.js with the MSI installer.
Using the Chocolatey package manager
Chocolatey is a package manager for Windows similar to APT or yum on Linux and brew on the Macintosh platforms. If you are already using Chocolatey, you may want to use this tool to install Node.js (e.g. using the nodejs-lts package). Note however, that many packages have uncertain management and that these packages may use different folder locations than those mentioned above.
Using a Node version manager
Using a Node.js version manager such as nvm-windows can be very helpful if you are doing Node.js development and need to test against different versions. Keep in mind that you will need to reinstall global packages and may need to re-install local packages when when you switch the version of Node you are using.
npm on Windows
When you install Node.js, you are also installing the npm package manager. You may see some instructions on the web that recommend installing later releases of npm than the one that comes with the Node.js release. This is not recommended as it is too easy to later end up with an incompatible version. Node.js releases are very regular and that is sufficient to keep npm updated.
Sharing Node-RED between Users
Node.js is installed into the Program Files folder as you would expect. However, if you install a global package like Node-RED using npm -g , it is installed into the $env:APPDATA\npm folder ( %APPDATA%\npm using cmd) for the current user. This is less than helpful if you are installing on a PC with multiple user logins or on a server and installing using an admin login rather than the login of the user that will run Node applications like Node-RED.
To fix this, either give permissions to the folder to other users and make sure that the folder is included in their path user environment variable.
Alternatively, change the global file location to somewhere accessible by other users. Make sure that you use the user that will be running Node-RED to make these changes. For example, to change the location to $env:ALLUSERSPROFILE\npmglobal using PowerShell:
You will then want to change the npm cache folder as well:
If using the above changes, you can add the new prefix folder to the PATH System variable and remove the old folder from the user’s Path variable. To change the PATH Environment variable, type environment into the start menu or Cortana and choose Edit Environment Variables.
For each of the users running Node-RED, check that the above settings for the other users are correct.
Installing Node.js Windows Build Tools
Many Node.js modules used by Node-RED or installed nodes have binary components that will need compiling before they will work on Windows. To enable npm to compile binaries on the Windows platform, install the windows-build-tools module using the command prompt as an Administrator:
If you wish to have the built-in Python v2.7 install exposed for use, use the command:
Running on Windows
Once installed, the simple way to run Node-RED is to use the node-red command in a command prompt: If you have installed Node-RED as a global npm package, you can use the node-red command:
This will output the Node-RED log to the terminal. You must keep the terminal open in order to keep Node-RED running.
Note that running Node-RED will create a new folder in your %HOMEPATH% folder called .node-red . This is your userDir folder, think of it as the home folder for Node-RED configuration for the current user. You will often see this referred to as
/.node-red in documentation.
is shorthand for the user home folder on Unix-like systems. You can use the same reference if using PowerShell as your command line as recommended. If you are using the older cmd shell, that won’t work.
You can now create your first flow.
Using PM2
If you are using Windows to develop Node-RED flows or nodes, you may find it helpful to use PM2 to run Node-RED. This can be configured to automatically restart when files change, always keep Node-RED running and manage log output.
Run Node-RED on Startup
If you want to use Windows as a production platform for Node-RED, you will want to have a Windows Task Scheduler job set up. To do so:
- Go to the start menu and type “task scheduler” and click on the result.
- Click on “Create Task…” in the right-hand menu. Follow the steps to create a new task.
Make sure that you use the user login that you’ve used to set up and do the initial run of Node-RED. You can use an “At startup” trigger to always run Node-RED at system startup. Use the Action “Start a program” with details set to C:\Users\ \AppData\Roaming\npm\node-red.cmd (replacing with your actual user name).
You may wish to make sure that it only starts if the network is available. You may also wish to restart if the job fails. Perhaps restarting every minute but only 3 times — if it won’t start by then, the error is fatal and will need some other intervention. You can check for failures by looking in the event log. If you want to access to the logs when running this way, you should amend the node-red.cmd file to redirect std and error outputs to a file (creating an alternative startup file would be better so that it isn’t overwritten on updates).
Node-RED: Low-code programming for event-driven applications.
Умный дом своими руками: установка Node-RED
Используем Node-RED вместе с Home Assistant.
Начнем с небольшой справки: что такое Node-RED.
Node-RED — это flow-based инструмент, созданный для визуального программирования, разработанный IBM для совмещения вместе: устройств, API, онлайн-сервисов и IoT, используемый также совместно с известному нами IBM Watson .
Многие задаются вопросом: зачем вообще использовать Node-red и Home Assistant вместе, ведь они по факту оба являются центрами автоматизации со своими отдельными интерфейсами и зачастую замещают друг друга во многом.
Но как и во всем (вспоминается самый простой пример: совместное использование Apache и NGINX), хотя у обоих функциональностей есть что-то схожее, но у них есть также и сильные/слабые стороны.
Так например: сильная сторона Home Assistant в огромном сообществе, количестве примеров и практически полнейшей всеядности (я не встречал еще чего-то, что нельзя было бы «затащить» в Home Assistant.
При этом слабые стороны Home Assistant, которые всем известны: автоматизации на YAML (ох, без кучи примеров и бест-кейсов из интернета даже разбираться не стоит) и ужасный проброс в HomeKit — прекрасно покрываются Node-red, который как будто создан для написания автоматизаций, и т.к. использует более продвинутый HAP-nodeJS в отличие от используемого HAP-python в Home Assistant, намного стабильнее работает с HomeKit.
Кроме этого, используя Node-red для отправки устройств в HomeKit, у нас появляется возможность самим создавать устройства и настраивать их под себя.
- У вас есть увлажнитель/очиститель, который в Home Assistant может быть проброшен в HomeKit как вентилятор. С Node-red вы можете пробросить любые параметры увлажнителя в HomeKit как вам угодно.
- Или у вас есть датчик PM2.5, датчик CO2, датчик еще чего-то. Всё это из Home Assistant будет уходить отдельными датчиками. Зачем? Когда через Node-red вы сможете создать один единственный датчик «качество воздуха» и отслеживать все эти характеристики в нем.
- Или у вашего очистителя/увлажнителя и тому подобное есть какой-то параметр, который не пробрасывается по-умолчанию в HomeKit. Не проблема, пробросьте его сами отдельно или добавьте к какому-то уже проброшенному устройству.
Вот такие поверхностные примеры — и даже они заставляют задуматься о переезде с «нативного» HomeKit от Home Assistant на Node-red.
Установка Node-RED
Благодаря тому, что Node-red не совсем opensource продукт, то его установка на наш Raspberry Pi займет буквально несколько минут и потребует всего двух команд: первой мы его устанавливаем, второй добавляем в автозапуск.
- Соответственно, для установки Node-RED вам необходимо вбить данную команду
После чего необходимо будет пройти несколько шагов, на которых вам будут задавать вопросы на тему «вы уверены?», на которые вы должны отвечать утвердительно, и подождать окончания установки. Здесь можно подробнее почитать, что именно у вас спрашивают и что делает данный «установщик».
- После чего добавляем node-red в автозапуск
sudo systemctl enable nodered.service
- И последним шагом запускаем Node-RED
Отмечу также, что закрыв этот процесс (CTRL+C) node-red не погасится, как это обычно бывает с другими службами. Очень удобно.
Ну и также несколько команд для запуска логов и остановки вам в помощь:
- После этого заходим http://yourip:1880/ и наслаждаемся установленным Node-RED
Подключение Home Assistant
После успешной установки Node-RED нам необходимо связать две системы.
- Заходим в интерфейс Node-red
- Открываем меню (справа вверху)
- Выбираем пункт Manage Palette
- Переходим на вкладку Install
- Вбиваем в поиск node-red-contrib-home-assistant-websocket
- Нажимаем на кнопку установить
После этого ждем установки данного модуля, для надежности в терминале можно открыть лог node-red для того, чтобы контролировать процесс. Пока наш новый модуль устанавливается перейдем к Home Assistant.
- Заходим в интерфейс Home Assistant http://yourip:8123/
- Нажимаем на букву около надписи Home Assistant в левом верхнем углу («буква» означает первый символ имени вашего профиля — по факту нажав на нее мы переходим в информацию о профиле)
- Проматываем в самый низ, доходим до блока «долгосрочные токены» и нажимаем на «Создать токен»
- Задаем название, допустим «node-red» и нажимаем ОК.
- После этого нам отобразится наш токен — копируем его в надежное место. Он пригодится нам дальше.
Возвращаемся обратно в Node-RED и заканчиваем настройку Home Assistant модуля.
- Слева, в колонке со всеми блоками, находим раздел «Home Assistant» — скорее всего он будет в самом низу
- Переносим блок «events:all» на пустой лист (обычным drag-n-drop) и открываем его двойным щелчком мыши
- Нажимаем на «карандашик» около Server, тем самым переходим в конфигурацию модуля
После чего обновляем страницу с Node-RED и довольствуемся тем, что теперь все события из Home Assistant будут попадать в Node-RED, а значит теперь мы сможем воспользоваться полностью его функционалом.
Подписывайтесь на канал InDaHomeKit в Telegram и Яндекс.Дзен , чтобы у вас всегда было что почитать: новости мира умного дома, обзоры новых устройств, инструкции по подключению.