@di-zed/yandex-smart-home
TypeScript icon, indicating that this package has built-in type declarations

1.0.4 • Public • Published

English Version | Русская Версия

Node.js (Express, TypeScript)

Yandex Smart Home

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.

Implemented.

Installing and launching the module as the main one.

  1. Clone the project.
    git clone git@github.com:di-zed/yandex-smart-home.git
    
  2. 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.
  3. Copy the ./.env.sample file to the ./.env file. Check it and edit some parameters if necessary.
  4. Mosquitto. Copy the ./volumes/etc/mosquitto/passwd.sample file to the ./volumes/etc/mosquitto/passwd file to configure Mosquitto users.
  5. Mosquitto. The default user in the passwd file is root, password is 123456.
  6. 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
    
  7. 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
    
  8. Configure devices, users and MQTT topics.
  9. Launch. The project is wrapped in Docker. To start, you need to do:
    docker-compose stop && docker-compose up -d
    
    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).

Installing and configuring the module as an auxiliary one.

  1. Installing the module in the project.
    npm install @di-zed/yandex-smart-home
    
  2. From the ./node_modules/@di-zed/yandex-smart-home folder, copy the following folders and files into the project:
    • config
    • .env.sample
  3. If you plan to use Docker, you can also copy:
  4. Review all the points (starting from 2) from the section Installing and launching the module as the main one. Apply as required.
  5. Before initializing the server, import and pass all the necessary parameters to the module.
    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',
       // ...
     });
    The full list of parameters can be found in the file src/interfaces/configInterface.ts .

Authorization in the skill.

Protocol for the operation of the smart home platform.

Devices configuration.

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.

Users configuration.

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.

Configuration of MQTT topics.

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 и т.д.

Реализовано.

Установка и запуск модуля, как основного.

  1. Клонируйте проект.
    git clone git@github.com:di-zed/yandex-smart-home.git
    
  2. SSL-сертификат. Для данного модуля Яндекс требует наличие SSL-сертификата. Сгенерируйте его (самоподписанные сертификаты работать не будут) и положите в папку ./volumes/etc/ssl.
  3. Скопируйте файл ./.env.sample в файл ./.env. Проверьте его и при необходимости отредактируйте некоторые параметры.
  4. Mosquitto. Скопируйте файл ./volumes/etc/mosquitto/passwd.sample в файл ./volumes/etc/mosquitto/passwd для настройки пользователей Mosquitto.
  5. Mosquitto. Пользователь по умолчанию в файле passwdroot, пароль — 123456.
  6. Необязательно. Если вы хотите добавить нового пользователя в Mosquitto:
    docker-compose exec eclipse-mosquitto mosquitto_passwd -c /etc/mosquitto/passwd new_user_name
    
  7. Необязательно. Если у вас возникла ошибка, типа Warning: File /etc/mosquitto/passwd has world readable permissions. Future versions will refuse to load this file. Пожалуйста, выполните:
    chmod 0700 volumes/etc/mosquitto/passwd
    
  8. Сконфигурируйте устройства, пользователей и MQTT-топики.
  9. Запуск. Проект обернут в Docker. Для запуска, необходимо выполнить:
    docker-compose stop && docker-compose up -d
    
    Если в файле .env указаны параметры SSL_KEY и SSL_CERT, то модуль будет пытаться использовать порт SSL_PORT, в противном случае - SERVER_PORT (может понадобиться для тестирования и разработки).

Установка и настройка модуля, как вспомогательного.

  1. Установка модуля в проект.
    npm install @di-zed/yandex-smart-home
    
  2. Из папки ./node_modules/@di-zed/yandex-smart-home скопировать в проект следующие папки и файлы:
    • config
    • .env.sample
  3. Если планируете использовать Docker, так же можно скопировать:
  4. Просмотрите все пункты (начиная с 2), из секции Установка и запуск модуля, как основного. Примените, которые требуются.
  5. До инициализации сервера, подключите и передайте все необходимые параметры в модуль.
    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',
       // ...
     });
    С полным списком параметров можно ознакомиться в файле src/interfaces/configInterface.ts.

Авторизация в навыке.

Протокол работы платформы умного дома.

  • Проверка доступности 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.

Далее, по аналогии описать имеющихся пользователей.

Авторизация в навыке будет ориентироваться на пользователей из этого файла.

Как альтернатива, могут быть использованы специальные хуки, если модуль был установлен в проект, а не используется как основной.

Конфигурация MQTT-топиков.

В корне модуля, в папке config, необходимо скопировать файл mqtt.sample.json в ту же самую папку с именем mqtt.json.

Далее, по аналогии описать имеющиеся топики.

Модуль будет слушать топики, описанные в этом файле.

Как альтернатива, могут быть использованы специальные хуки, если модуль был установлен в проект, а не используется как основной.

Node (18.18.0)

docker-compose exec node18 /bin/bash

Eclipse Mosquitto (2.0.18)

  • Host: eclipse-mosquitto
  • Ports: 1883, 9001

MQTT Explorer (browser-1.0.3)

Package Sidebar

Install

npm i @di-zed/yandex-smart-home

Weekly Downloads

5

Version

1.0.4

License

MIT

Unpacked Size

166 kB

Total Files

82

Last publish

Collaborators

  • dima-zaichenko