English Version | Русская Версия
This module is specially designed to work with the Yandex.Dialogs service.
It is a bridge between the smart home service from Yandex and the MQTT server. The module can be used as main, and can also be installed as auxiliary in another project.
To work, you need to create and configure a skill in the developer console, and then link accounts, indicating correct links implemented in this module.
The essence of the module is that upon command, for example, "Alice, turn on the light", the required value is sent to the required MQTT topic, which can then be processed depending on the needs and capabilities. For example, you can have your own devices that work with MQTT, or you can run the script in a program like Node-RED, etc.
- Authorization in the skill.
- Protocol for the operation of the smart home platform.
- Devices configuration.
- Users configuration.
- Configuration of MQTT topics.
- Clone the project.
git clone git@github.com:di-zed/yandex-smart-home.git
- SSL certificate. For this module, Yandex requires an SSL certificate. Generate it (self-signed certificates will not work) and put it in the ./volumes/etc/ssl folder.
- Copy the ./.env.sample file to the ./.env file. Check it and edit some parameters if necessary.
- Mosquitto. Copy the ./volumes/etc/mosquitto/passwd.sample file to the ./volumes/etc/mosquitto/passwd file to configure Mosquitto users.
- Mosquitto. The default user in the passwd file is root, password is 123456.
-
Optional If you want to add a new user to Mosquitto:
docker-compose exec eclipse-mosquitto mosquitto_passwd -c /etc/mosquitto/passwd new_user_name
-
Optional. If you get an error like Warning: File /etc/mosquitto/passwd has world readable permissions. Future versions will refuse to load this file. Please do:
chmod 0700 volumes/etc/mosquitto/passwd
- Configure devices, users and MQTT topics.
-
Launch. The project is wrapped in Docker. To start, you need to do:
If the .env file contains the SSL_KEY and SSL_CERT parameters, then the module will try to use the SSL_PORT port, otherwise - SERVER_PORT (may be needed for testing and development).docker-compose stop && docker-compose up -d
- Installing the module in the project.
npm install @di-zed/yandex-smart-home
- From the ./node_modules/@di-zed/yandex-smart-home folder, copy the following folders and files into the project:
- config
- .env.sample
- If you plan to use Docker, you can also copy:
- Review all the points (starting from 2) from the section Installing and launching the module as the main one. Apply as required.
- Before initializing the server, import and pass all the necessary parameters to the module.
The full list of parameters can be found in the file src/interfaces/configInterface.ts .
import express, { Application } from 'express'; import yandexSmartHome from '@di-zed/yandex-smart-home'; const app: Application = express(); yandexSmartHome(app, { // ... configFileDevices: './config/devices.json', configFileUsers: './config/users.json', configFileMqtt: './config/mqtt.json', // ... });
- How authorization works: /auth/login, /auth/token.
- Checking the provider's Endpoint URL availability: /v1.0.
- Notification of unlinked accounts: /v1.0/user/unlink.
- Information about user devices: /v1.0/user/devices.
- Information about the states of user devices: /v1.0/user/devices/query.
- Change device state: /v1.0/user/devices/action.
In the root of the module, in the config folder, you need to copy the file devices.sample.json into the same folder named devices.json.
Next, describe the available devices by analogy.
On the Yandex Dialogs website you can familiarize yourself with device types, skills and properties.
Information about the user's devices will be taken from this file.
As an alternative, special hooks can be used if the module has been installed in the project, and not used as the main one.
In the root of the module, in the config folder, you need to copy the file users.sample.json into the same folder named users.json.
Next, by analogy, describe the existing users.
Authorization in the skill will target users from this file.
As an alternative, special hooks can be used if the module has been installed in the project, and not used as the main one.
In the root of the module, in the config folder, you need to copy the file mqtt.sample.json into the same folder named mqtt.json.
Next, by analogy, describe the existing topics.
The module will listen to topics described in this file.
As an alternative, special hooks can be used if the module has been installed in the project, and not used as the main one.
Данный модуль специально разработан для работы с сервисом Яндекс.Диалоги.
Он является мостом между сервисом умного дома от Яндекса и MQTT-сервером. Модуль может быть использован как основной, а также может быть установлен в качестве вспомогательного в другом проекте.
Для работы необходимо создать и настроить навык в консоли разработчика, а затем связать аккаунты, указав корректные ссылки, реализованные в данном модуле.
Суть модуля заключается в том, чтобы по команде, например, "Алиса, включи свет", в требуемый топик MQTT отправлялось нужное значение, которое затем может быть обработано в зависимости от потребностей и возможностей. Например, вы можете иметь свои собственные устройства, которые работают с MQTT, или же можно обработать сценарий в программе типа Node-RED и т.д.
- Авторизация в навыке.
- Протокол работы платформы умного дома.
- Конфигурация устройств.
- Конфигурация пользователей.
- Конфигурация MQTT-топиков.
- Клонируйте проект.
git clone git@github.com:di-zed/yandex-smart-home.git
- SSL-сертификат. Для данного модуля Яндекс требует наличие SSL-сертификата. Сгенерируйте его (самоподписанные сертификаты работать не будут) и положите в папку ./volumes/etc/ssl.
- Скопируйте файл ./.env.sample в файл ./.env. Проверьте его и при необходимости отредактируйте некоторые параметры.
- Mosquitto. Скопируйте файл ./volumes/etc/mosquitto/passwd.sample в файл ./volumes/etc/mosquitto/passwd для настройки пользователей Mosquitto.
- Mosquitto. Пользователь по умолчанию в файле passwd — root, пароль — 123456.
-
Необязательно. Если вы хотите добавить нового пользователя в Mosquitto:
docker-compose exec eclipse-mosquitto mosquitto_passwd -c /etc/mosquitto/passwd new_user_name
-
Необязательно. Если у вас возникла ошибка, типа Warning: File /etc/mosquitto/passwd has world readable permissions. Future versions will refuse to load this file. Пожалуйста, выполните:
chmod 0700 volumes/etc/mosquitto/passwd
- Сконфигурируйте устройства, пользователей и MQTT-топики.
-
Запуск. Проект обернут в Docker. Для запуска, необходимо выполнить:
Если в файле .env указаны параметры SSL_KEY и SSL_CERT, то модуль будет пытаться использовать порт SSL_PORT, в противном случае - SERVER_PORT (может понадобиться для тестирования и разработки).docker-compose stop && docker-compose up -d
- Установка модуля в проект.
npm install @di-zed/yandex-smart-home
- Из папки ./node_modules/@di-zed/yandex-smart-home скопировать в проект следующие папки и файлы:
- config
- .env.sample
- Если планируете использовать Docker, так же можно скопировать:
- Просмотрите все пункты (начиная с 2), из секции Установка и запуск модуля, как основного. Примените, которые требуются.
- До инициализации сервера, подключите и передайте все необходимые параметры в модуль.
С полным списком параметров можно ознакомиться в файле src/interfaces/configInterface.ts.
import express, { Application } from 'express'; import yandexSmartHome from '@di-zed/yandex-smart-home'; const app: Application = express(); yandexSmartHome(app, { // ... configFileDevices: './config/devices.json', configFileUsers: './config/users.json', configFileMqtt: './config/mqtt.json', // ... });
- Как устроена авторизация: /auth/login, /auth/token.
- Проверка доступности Endpoint URL провайдера: /v1.0.
- Оповещение о разъединении аккаунтов: /v1.0/user/unlink.
- Информация об устройствах пользователя: /v1.0/user/devices.
- Информация о состояниях устройств пользователя: /v1.0/user/devices/query.
- Изменение состояния у устройств: /v1.0/user/devices/action.
В корне модуля, в папке config, необходимо скопировать файл devices.sample.json в ту же самую папку с именем devices.json.
Далее, по аналогии описать имеющиеся устройства.
На сайте Яндекс Диалогов можно ознакомиться с типами устройств, умениями и свойствами.
Информация об устройствах пользователя будет браться из этого файла.
Как альтернатива, могут быть использованы специальные хуки, если модуль был установлен в проект, а не используется как основной.
В корне модуля, в папке config, необходимо скопировать файл users.sample.json в ту же самую папку с именем users.json.
Далее, по аналогии описать имеющихся пользователей.
Авторизация в навыке будет ориентироваться на пользователей из этого файла.
Как альтернатива, могут быть использованы специальные хуки, если модуль был установлен в проект, а не используется как основной.
В корне модуля, в папке config, необходимо скопировать файл mqtt.sample.json в ту же самую папку с именем mqtt.json.
Далее, по аналогии описать имеющиеся топики.
Модуль будет слушать топики, описанные в этом файле.
Как альтернатива, могут быть использованы специальные хуки, если модуль был установлен в проект, а не используется как основной.
- Host: node18
- Ports: 80, 443, 3000
- URL: http://localhost:3000/
docker-compose exec node18 /bin/bash
- Host: eclipse-mosquitto
- Ports: 1883, 9001
- Host: mqtt-explorer
- Port: 4000
- URL: http://localhost:4000/