Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
vitalii-wb committed Oct 25, 2024
0 parents commit 4355818
Show file tree
Hide file tree
Showing 31 changed files with 984 additions and 0 deletions.
38 changes: 38 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
*.build
*.deb
*.tar.gz
*.dsc
*.changes
*.debhelper.log
*.debhelper
*.substvars
*.o
*/debian/libmosquitto-dev/*
*/debian/libmosquitto1/*
*/debian/libmosquittopp-dev/*
*/debian/libmosquittopp1/*
*/debian/mosquitto-clients/*
*/debian/mosquitto-dbg/*
*/debian/mosquitto-dev/*
*/debian/mosquitto/*
*/debian/wb-rules-system/*
*.swp
*.un~

**/debian/files
**/debian/*.debhelper
**/debian/*.debhelper.log
**/debian/*.substvars

utils/debian/wb-utils/
wb-utils_*.deb
wb-utils_*.changes

configs/debian/wb-configs/
wb-configs_*.*
*.pyc

.tern-port
debian/wb-rules-system

node_modules/
1 change: 1 addition & 0 deletions Jenkinsfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
buildDebArchAll()
36 changes: 36 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
The WB License (MIT-WB)

Copyright (c) 2024 Contactless Devices, LLC (Wiren Board)

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

The Software shall only be used on Wiren Board controllers, that is, hardware
manufactured by Contactless Devices, LLC or its affilates.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


Copyright (c) 2024 ООО Бесконтактные устройства

Данная лицензия разрешает лицам, получившим копию данного программного обеспечения и сопутствующей документации (в дальнейшем именуемыми «Программное Обеспечение»), безвозмездно использовать Программное Обеспечение без ограничений, включая неограниченное право на использование, копирование, изменение, слияние, публикацию, распространение, сублицензирование и/или продажу копий Программного Обеспечения, а также лицам, которым предоставляется данное Программное Обеспечение, при соблюдении следующих условий:

Указанное выше уведомление об авторском праве и данные условия должны быть включены во все копии или значимые части данного Программного Обеспечения.

Программное Обеспечение должно использоваться только на контроллерах Wiren Board, т.е.
на оборудовании, произведённом компанией ООО Бесконтактные устройства или уполномоченными
компанией ООО Бесконтактные устройства лицами.

ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ», БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ, ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ ГАРАНТИИ ТОВАРНОЙ ПРИГОДНОСТИ, СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ НАЗНАЧЕНИЮ И ОТСУТСТВИЯ НАРУШЕНИЙ, НО НЕ ОГРАНИЧИВАЯСЬ ИМИ. НИ В КАКОМ СЛУЧАЕ АВТОРЫ ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ПО КАКИМ-ЛИБО ИСКАМ, ЗА УЩЕРБ ИЛИ ПО ИНЫМ ТРЕБОВАНИЯМ, В ТОМ ЧИСЛЕ, ПРИ ДЕЙСТВИИ КОНТРАКТА, ДЕЛИКТЕ ИЛИ ИНОЙ СИТУАЦИИ, ВОЗНИКШИМ ИЗ-ЗА ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ ИЛИ ИНЫХ ДЕЙСТВИЙ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ.
71 changes: 71 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# DESTDIR задается по необходимости извне
# DESTDIR=/
PREFIX=/usr

# Путь к папке со сценариями
SCENARIOS_ROOT := scenarios/

# Папка для схем и изображений в схеме
SCHEMA_DIR := schema/

# Поиск папок сценариев внутри папки scenarios
SCENARIO_DIRS := $(wildcard $(SCENARIOS_ROOT)*)

# Предварительно вычисленные списки файлов для копирования
CONFIG_FILES := $(wildcard *.conf)
IMAGE_FILES := $(wildcard $(SCHEMA_DIR)*.png)
SCHEMA_FILES := $(wildcard $(SCHEMA_DIR)*.schema.json)

.PHONY: all dummy install

all: install

clean:
@echo "This is a clean target"

dummy:
@echo "This is a dummy target"

install:
@echo "Starting installation process..."

@# Копирование всех конфигурационных файлов из корня проекта
@$(foreach file,$(CONFIG_FILES),\
echo "Copying $(file) to $(DESTDIR)/etc";\
install -Dm644 $(file) $(DESTDIR)/etc;)

@# Копирование изображений из папки schema
@$(foreach file,$(IMAGE_FILES),\
echo "Copying image $(file) to $(DESTDIR)/var/www/images";\
install -Dm644 $(file) $(DESTDIR)/var/www/images;)

@# Копирование схем из папки schema
@$(foreach file,$(SCHEMA_FILES),\
echo "Copying schema $(file) to $(DESTDIR)$(PREFIX)/share/wb-mqtt-confed/schemas";\
install -Dm644 $(file) $(DESTDIR)$(PREFIX)/share/wb-mqtt-confed/schemas;)

@# Установка каждого сценария из подпапок
@$(foreach dir,$(SCENARIO_DIRS),\
echo "Installing from directory $(dir)...";\
$(MAKE) -s install-$(dir);)

define TEMPLATE
install-$(1):
@echo " + Processing directory $(1)..."
@# Собираем все файлы .js, кроме модулей (заканчиваются на .mod.js)
$(eval RULE_FILES := $(filter-out $(wildcard $(1)/*.mod.js), $(wildcard $(1)/*.js)))
$(eval MODULE_FILES := $(wildcard $(1)/*.mod.js))

@if [ -n "$(RULE_FILES)" ]; then \
echo " - Copying rule files: $(RULE_FILES) to $(DESTDIR)$(PREFIX)/share/wb-rules-system/rules";\
install -Dm644 $(RULE_FILES) $(DESTDIR)$(PREFIX)/share/wb-rules-system/rules;\
fi
@if [ -n "$(MODULE_FILES)" ]; then \
echo " - Copying module files: $(MODULE_FILES) to $(DESTDIR)/etc/wb-rules-modules";\
install -Dm644 $(MODULE_FILES) $(DESTDIR)/etc/wb-rules-modules;\
fi

.PHONY: dummy install-$(1)
endef

$(foreach dir,$(SCENARIO_DIRS),$(eval $(call TEMPLATE,$(dir))))
94 changes: 94 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Готовые сценарии

Содержит готовые сценарии которые помогают быстрее реализовать функционал интеграторам

## Добавление нового сценария
Для добавления нового сценария нужно:
1) Создать в папке scenarios подпапку с именем вашего сценария.
Имя маленькими латинскими буквами через тире.
Тут хранятся файлы относяшиеся к конкретному сценарию:
- Модуль js
- Системный скрипт читающий конфиг
- Ридми для данного сценария - здесь должен быть внешний вид и краткая инструкция по использованию
2) Добавить описание схемы webui для вашего нового сценария
3) Поменять конфиг чтобы он корректно открывался в соответствии с вашими изменениями в схеме


## Ручная установка
Для ручной установки сценариев нужно расставить 5 файлов в контроллере

Простого сценария соединения входа на выход прямого или инверсного где указываешь входной и выходной топики switch и далее автоматом инициализируются виртуальное устройство и правило которое будет выполнять заданный в вебке функционал

Там есть всего 5 файлов которые устанавливаются следующим образом (если это со стороны пользователя делать)

Добавление происходит добавлением-изменением следующих файлов
1. Файл системных правил rules/scenarios.js
Во время отладки можно класть в пользовательские правила
```path
/etc/wb-rules/scenarios.js
```

2. Модуль modules/link-in-to-out/link-in-to-out.mod.js
```path
/etc/wb-rules-modules/link-in-to-out.mod.js
```

3. Описание схемы json-editor rules/scenarios.schema.json
```path
/usr/share/wb-mqtt-confed/schemas/scenarios.schema.json
```

4. При необходимости изображения rules/scenarios-link-in-to-out.png
```path
/var/www/images/scenarios-link-in-to-out.png
```

5. Сохраненный конфиг из вебки rules/scenarios.conf
```path
/etc/scenarios.conf
```

Файлы из папки DELETE-virtual-devices-for-tests я удалю, они просто для удобства пока там лежат

## Автоматическая установка
Клонирование на контроллер
```terminal
# cd ~
# git clone https://github.com/wirenboard/wb-scenarios
# cd wb-scenarios
```

Далее можно либо установить с помошью мейк, либо собрать деб пакет
### Установка через make
Нужно вызвать мейк - увидим что и куда копируется

```make
# make
Starting installation process...
Copying scenarios.conf to //etc
Copying image schema/scenarios-link-in-to-out.png to //var/www/images
Copying schema schema/scenarios.schema.json to //usr/share/wb-mqtt-confed/schemas
Installing from directory scenarios/link-in-to-out...
+ Processing directory scenarios/link-in-to-out...
- Copying rule files: scenarios/link-in-to-out/scenarios.js to //usr/share/wb-rules-system/rules
- Copying module files: scenarios/link-in-to-out/link-in-to-out.mod.js to //etc/wb-rules-modules
#
```

### Сборка пакета и установка через apt

Соберем пакет
```terminal
# dpkg-buildpackage -rfakeroot -us -uc
```

После успешного завершения появится файл выше в папке `../`
Установим его
```terminal
# apt install -y ./wb-scenarios_1.0.0_all.deb
```

Если нужно удалить - то выполняем
```terminal
# apt remove wb-scenarios
```
5 changes: 5 additions & 0 deletions debian/changelog
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
wb-scenarios (1.0.0) stable; urgency=medium

* Initial release

-- Vitalii Gaponov <[email protected]> Thu, 25 Oct 2024 08:00:00 +0300
1 change: 1 addition & 0 deletions debian/compat
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
9
15 changes: 15 additions & 0 deletions debian/control
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
Source: wb-scenarios
Section: misc
Priority: optional
Maintainer: Wiren Board Team <[email protected]>
Build-Depends: debhelper (>= 8.0.0)
Standards-Version: 4.5.1
Homepage: https://github.com/wirenboard/wb-scenarios
Vcs-Git: https://github.com/wirenboard/wb-scenarios

Package: wb-scenarios
Architecture: all
Depends: ${shlibs:Depends}, ${misc:Depends}, wb-rules (>= 2.20.0~~), wb-utils (>= 2.1)
Recommends: linux-image-wb2 | linux-image-wb6 (>= 4.9+wb20180729224630) | linux-image-wb7,
wb-hwconf-manager (>= 1.30.1), wb-release-info
Description: Scenarios for Wiren Board
8 changes: 8 additions & 0 deletions debian/postinst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/bin/sh
set -e

deb-systemd-invoke restart wb-rules

#DEBHELPER#

exit 0
14 changes: 14 additions & 0 deletions debian/rules
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#!/usr/bin/make -f
# -*- makefile -*-

# Uncomment this to turn on verbose mode.
export DH_VERBOSE=1

override_dh_auto_configure:
dh_auto_configure --buildsystem=makefile

override_dh_builddeb:
dh_builddeb -- -Zgzip

%:
dh $@
4 changes: 4 additions & 0 deletions debian/wb-scenarios.dirs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/usr/share/wb-rules-system/rules
/usr/share/wb-mqtt-confed/schemas
/var/www/images
/etc/wb-rules-modules
2 changes: 2 additions & 0 deletions debian/wb-scenarios/DEBIAN/conffiles
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/etc/scenarios.conf
/etc/wb-rules-modules/link-in-to-out.mod.js
11 changes: 11 additions & 0 deletions debian/wb-scenarios/DEBIAN/control
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Package: wb-scenarios
Version: 1.0.0
Architecture: all
Maintainer: Wiren Board Team <[email protected]>
Installed-Size: 48
Depends: wb-rules (>= 2.20.0~~), wb-utils (>= 2.1)
Recommends: linux-image-wb2 | linux-image-wb6 (>= 4.9+wb20180729224630) | linux-image-wb7, wb-hwconf-manager (>= 1.30.1), wb-release-info
Section: misc
Priority: optional
Homepage: https://github.com/wirenboard/wb-scenarios
Description: Scenarios for Wiren Board
4 changes: 4 additions & 0 deletions debian/wb-scenarios/DEBIAN/md5sums
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
2c1d1efd691abcbaf1ae36a30814a4ab usr/share/doc/wb-scenarios/changelog.gz
3e8e3913daade55b4964103072feaf9d usr/share/wb-mqtt-confed/schemas/scenarios.schema.json
2bce47e6f8ec8b1eb8045e407850617e usr/share/wb-rules-system/rules/scenarios.js
1dd8d4860f7ab12ddb07e5d601e9baef var/www/images/scenarios-link-in-to-out.png
8 changes: 8 additions & 0 deletions debian/wb-scenarios/DEBIAN/postinst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/bin/sh
set -e

deb-systemd-invoke restart wb-rules



exit 0
20 changes: 20 additions & 0 deletions debian/wb-scenarios/etc/scenarios.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"scenarios": [
{
"enable": true,
"inControl": "vd-wall-switch1/enabled",
"inverseLink": false,
"name": "first_link",
"outControl": "vd-pump/enabled",
"scenarioType": "linkInToOut"
},
{
"enable": true,
"inControl": "vd-wall-switch2/enabled",
"inverseLink": true,
"name": "second_link",
"outControl": "vd-pump/enabled",
"scenarioType": "linkInToOut"
}
]
}
48 changes: 48 additions & 0 deletions debian/wb-scenarios/etc/wb-rules-modules/link-in-to-out.mod.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* @file Модуль для инициализации прямой или инвертированной связи
* между двумя switch топиками MQTT
* @author Vitalii Gaponov <[email protected]>
* @link Комментарии в формате JSDoc <https://jsdoc.app/>
*/

/**
* Инициализирует виртуальное устройство и определяет правило для управления
* устройством
* @param {string} idPrefix - Префикс сценария, используемое для
* идентификации виртуального устройства
* @param {string} inControl - Идентификатор входного контроля, значение
* которого следует слушать
* Пример: "vd_wall_switch/enabled"
* @param {string} outControl - Идентификатор выходного контроля, значение
* которого следует контролировать
* Пример: "vd_pump/enabled"
* @param {boolean} inverseLink - Указывает, должна ли связь быть
* инвертированной
*/
function init(idPrefix, inControl, outControl, inverseLink) {
device = defineVirtualDevice("GenVd_" + idPrefix, {
title: "Generated VD: " + idPrefix,
cells: {
enabled: {
type: "switch",
value: false
},
}
});

defineRule("GenRule_" + idPrefix, {
whenChanged: inControl,
then: function (newValue, devName, cellName) {
// Проверка инверсии и присваивание значения в зависимости от него
if (inverseLink) {
dev[outControl] = !newValue; // Инвертирование значения
} else {
dev[outControl] = newValue; // Прямое присваивание значения
}
}
});
};

exports.init = function (idPrefix, inControl, outControl, inverseLink) {
init(idPrefix, inControl, outControl, inverseLink);
};
Binary file not shown.
Loading

0 comments on commit 4355818

Please sign in to comment.