vrack2-core 0.0.1 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +33 -4
  2. package/docs/Bootstrap.md +77 -0
  3. package/docs/Container.md +124 -0
  4. package/docs/Device.md +272 -0
  5. package/docs/FastStart.md +111 -0
  6. package/docs/Structure.md +148 -0
  7. package/lib/Bootstrap.d.ts +79 -0
  8. package/lib/Bootstrap.js +103 -0
  9. package/lib/Container.d.ts +202 -6
  10. package/lib/Container.js +295 -27
  11. package/lib/IServiceStructure.d.ts +8 -0
  12. package/lib/IStructureDevice.d.ts +5 -0
  13. package/lib/ImportManager.d.ts +85 -3
  14. package/lib/ImportManager.js +122 -16
  15. package/lib/MainProcess.d.ts +30 -3
  16. package/lib/MainProcess.js +28 -6
  17. package/lib/Utility.d.ts +15 -21
  18. package/lib/Utility.js +40 -40
  19. package/lib/actions/Action.d.ts +10 -0
  20. package/lib/actions/Action.js +10 -0
  21. package/lib/actions/BasicAction.d.ts +60 -0
  22. package/lib/actions/BasicAction.js +62 -0
  23. package/lib/actions/GlobalAction.d.ts +5 -0
  24. package/lib/actions/GlobalAction.js +5 -0
  25. package/lib/actions/IAction.d.ts +7 -0
  26. package/lib/actions/ILocalAction.d.ts +7 -0
  27. package/lib/boot/BootClass.d.ts +93 -0
  28. package/lib/boot/BootClass.js +101 -0
  29. package/lib/boot/DeviceFileStorage.d.ts +38 -0
  30. package/lib/boot/DeviceFileStorage.js +112 -0
  31. package/lib/boot/DeviceManager.d.ts +190 -0
  32. package/lib/boot/DeviceManager.js +311 -0
  33. package/lib/boot/DeviceMetrics.d.ts +82 -0
  34. package/lib/boot/DeviceMetrics.js +128 -0
  35. package/lib/boot/StructureStorage.d.ts +59 -0
  36. package/lib/boot/StructureStorage.js +125 -0
  37. package/lib/errors/CoreError.d.ts +42 -25
  38. package/lib/errors/CoreError.js +44 -24
  39. package/lib/errors/ErrorManager.d.ts +18 -20
  40. package/lib/errors/ErrorManager.js +23 -22
  41. package/lib/index.d.ts +20 -4
  42. package/lib/index.js +28 -4
  43. package/lib/metrics/BasicMetric.d.ts +49 -0
  44. package/lib/metrics/BasicMetric.js +79 -0
  45. package/lib/metrics/IMetricSettings.d.ts +32 -0
  46. package/lib/metrics/IMetricSettings.js +2 -0
  47. package/lib/metrics/IvMs.d.ts +9 -0
  48. package/lib/metrics/IvMs.js +22 -0
  49. package/lib/metrics/IvS.d.ts +9 -0
  50. package/lib/metrics/IvS.js +22 -0
  51. package/lib/metrics/IvUs.d.ts +9 -0
  52. package/lib/metrics/IvUs.js +22 -0
  53. package/lib/metrics/Metric.d.ts +17 -0
  54. package/lib/metrics/Metric.js +27 -0
  55. package/lib/ports/BasicPort.d.ts +39 -0
  56. package/lib/ports/BasicPort.js +39 -0
  57. package/lib/ports/ILocalPort.d.ts +7 -0
  58. package/lib/ports/IPort.d.ts +7 -0
  59. package/lib/ports/Port.d.ts +10 -0
  60. package/lib/ports/Port.js +10 -0
  61. package/lib/ports/ReturnPort.d.ts +5 -0
  62. package/lib/ports/ReturnPort.js +5 -0
  63. package/lib/service/Device.d.ts +213 -78
  64. package/lib/service/Device.js +185 -83
  65. package/lib/service/DeviceConnect.d.ts +4 -8
  66. package/lib/service/DeviceConnect.js +4 -8
  67. package/lib/service/DevicePort.d.ts +15 -6
  68. package/lib/service/DevicePort.js +29 -12
  69. package/lib/service/IDeviceEvent.d.ts +4 -1
  70. package/lib/validator/IValidationProblem.d.ts +7 -0
  71. package/lib/validator/IValidationRule.d.ts +12 -0
  72. package/lib/validator/IValidationSubrule.d.ts +2 -0
  73. package/lib/validator/Rule.d.ts +6 -2
  74. package/lib/validator/Rule.js +12 -2
  75. package/lib/validator/Validator.d.ts +48 -3
  76. package/lib/validator/Validator.js +70 -18
  77. package/lib/validator/types/AnyType.d.ts +17 -0
  78. package/lib/validator/types/AnyType.js +34 -0
  79. package/lib/validator/types/ArrayType.d.ts +37 -4
  80. package/lib/validator/types/ArrayType.js +42 -6
  81. package/lib/validator/types/BasicType.d.ts +67 -7
  82. package/lib/validator/types/BasicType.js +74 -8
  83. package/lib/validator/types/BooleanType.d.ts +23 -0
  84. package/lib/validator/types/BooleanType.js +47 -0
  85. package/lib/validator/types/FunctionType.d.ts +17 -0
  86. package/lib/validator/types/FunctionType.js +38 -0
  87. package/lib/validator/types/NumberType.d.ts +40 -5
  88. package/lib/validator/types/NumberType.js +53 -14
  89. package/lib/validator/types/ObjectType.d.ts +32 -5
  90. package/lib/validator/types/ObjectType.js +42 -8
  91. package/lib/validator/types/StringType.d.ts +30 -5
  92. package/lib/validator/types/StringType.js +33 -7
  93. package/package.json +15 -14
  94. package/src/Bootstrap.ts +122 -0
  95. package/src/Container.ts +411 -43
  96. package/src/IServiceStructure.ts +9 -0
  97. package/src/IStructureDevice.ts +5 -0
  98. package/src/ImportManager.ts +119 -11
  99. package/src/MainProcess.ts +53 -8
  100. package/src/Utility.ts +35 -36
  101. package/src/actions/Action.ts +12 -0
  102. package/src/actions/BasicAction.ts +63 -0
  103. package/src/actions/GlobalAction.ts +5 -0
  104. package/src/actions/IAction.ts +7 -0
  105. package/src/actions/ILocalAction.ts +7 -0
  106. package/src/boot/BootClass.ts +117 -0
  107. package/src/boot/DeviceFileStorage.ts +96 -0
  108. package/src/boot/DeviceManager.ts +346 -0
  109. package/src/boot/DeviceMetrics.ts +129 -0
  110. package/src/boot/StructureStorage.ts +108 -0
  111. package/src/errors/CoreError.ts +52 -26
  112. package/src/errors/ErrorManager.ts +46 -33
  113. package/src/index.ts +30 -6
  114. package/src/metrics/BasicMetric.ts +84 -0
  115. package/src/metrics/IMetricSettings.ts +38 -0
  116. package/src/metrics/IvMs.ts +18 -0
  117. package/src/metrics/IvS.ts +18 -0
  118. package/src/metrics/IvUs.ts +17 -0
  119. package/src/metrics/Metric.ts +25 -0
  120. package/src/ports/BasicPort.ts +39 -0
  121. package/src/ports/ILocalPort.ts +7 -0
  122. package/src/ports/IPort.ts +7 -0
  123. package/src/ports/Port.ts +11 -1
  124. package/src/ports/ReturnPort.ts +5 -0
  125. package/src/service/Device.ts +234 -103
  126. package/src/service/DeviceConnect.ts +4 -8
  127. package/src/service/DevicePort.ts +30 -11
  128. package/src/service/IDeviceEvent.ts +4 -1
  129. package/src/validator/IValidationProblem.ts +7 -0
  130. package/src/validator/IValidationRule.ts +12 -0
  131. package/src/validator/IValidationSubrule.ts +3 -0
  132. package/src/validator/Rule.ts +16 -2
  133. package/src/validator/Validator.ts +74 -23
  134. package/src/validator/types/AnyType.ts +32 -0
  135. package/src/validator/types/ArrayType.ts +43 -7
  136. package/src/validator/types/BasicType.ts +78 -9
  137. package/src/validator/types/BooleanType.ts +49 -0
  138. package/src/validator/types/FunctionType.ts +39 -0
  139. package/src/validator/types/NumberType.ts +53 -15
  140. package/src/validator/types/ObjectType.ts +52 -14
  141. package/src/validator/types/StringType.ts +34 -10
  142. package/docs/RU-README.md +0 -6
  143. package/lib/DeviceManager.d.ts +0 -32
  144. package/lib/DeviceManager.js +0 -143
  145. package/lib/test.d.ts +0 -1
  146. package/lib/test.js +0 -58
  147. package/src/DeviceManager.ts +0 -124
  148. package/src/test.ts +0 -82
@@ -0,0 +1,148 @@
1
+
2
+ # Структура приложения
3
+
4
+ ## 1. Базовые требования для запуска
5
+
6
+ Минимальный набор для запуска сервиса:
7
+ - [Файл запуска](#2-файл-запуска)
8
+ - [Файловая структура](#3-файловая-структура)
9
+ - [Файл сервиса](#4-файл-сервиса)
10
+
11
+
12
+ ## 2. Файл запуска
13
+
14
+ Репозиторий VRack2 является минимально настроенной готовой структурой для запуска сервиса на VRack2 Core. В VRack2 есть возможность запустить любой файл сервиса указав его после команды запуска:
15
+
16
+ Пример команды для запуска вашего файла сервиса:
17
+
18
+ ```bash
19
+ npm run start "./devices/youvendor/service.json"
20
+ ```
21
+
22
+ Таким образом можно запустить ваш файл сервиса без запуска VRack2. Вы можете сами написать или скопировать файл запуска из VRack2, но в таком случае вам необходимо будет создать нужные папки и правильно указать параметры запуска сервиса в package.json.
23
+
24
+ Рекомендуется ознакомится с оригинальным файлом запуска. Он позволяет не только запускать любой файл сервиса, но и так же запускать воркеры которые являются так же сервисами VRack2 Core.
25
+
26
+ Ниже приведена упращенная **последовательность выполнения:**
27
+
28
+ 1. Получение/формирование файла структуры сервиса
29
+ 2. Инициализация класса `MainProcess` - Упращает последовательность инициализации классов `Container` и `Bootstrap`. Это очень важно, потому что там используется сложная последовательность и линковка между друг другом.
30
+ 3. Инициализаця класса `Container` - Будет вмещать в себя все устройства/связи создавая их по списку файла структуры, а так же принимать все события внутри устройств
31
+ 4. Запуск `MainProcess.run()`
32
+ 5. Загрузка и запуск `Bootstrap` классов (это вспомогательные классы которые расширяют возможности устройств сервиса)
33
+ 1. `DeviceManager` - Класс работы с устройствами (группы/устройства/инициализация/информация)
34
+ 2. `DeviceStorage` - Класс обеспечивает сохрание и восстановление личных данных компонента (устройства)
35
+ 3. `StructureStorage` - Класс для работы со структурой сервиса
36
+ 4. `DeviceMetrics` - Класс для приема и обработки метрик устройств
37
+ 6. Запуск сервиса `Container.init()`
38
+ 1. Инициализация устройств
39
+ 2. Добавление соединений
40
+ 3. Запуск процессов устройств
41
+
42
+
43
+ ## 3. Файловая структура
44
+
45
+ Общая структура файлов проекта выглядит так:
46
+
47
+ ```
48
+ devices/ # ! Необходимо создать (директория вендоров устройств)
49
+ {vendor}/ # Директория вендора (например, "vrack2")
50
+ {Device} # Файл устройства (например, "Master")
51
+ list.json # Файл регистрации устройств
52
+ storage/ # ! Необходимо создать (файлы хранилища устройств)
53
+ {ContainerID}/ # Идентификатор контейнера (создается автоматически)
54
+ {DeviceName} # Файл данных устройства (формат: JSON) (создается при сохранении данных внутри устройства)
55
+ structure/ # ! Необходимо создать (файлы структур контейнеров)
56
+ {ContainerID} # Файл структуры (формат: JSON) (создается автоматически)
57
+ ```
58
+
59
+ ### Организация устройств
60
+
61
+ Устройства располагаются в иерархии вендоров внутри директории `devices/`. Каждый вендор представляет собой отдельный модуль (возможно, отдельный репозиторий), что обеспечивает:
62
+
63
+ - Четкое разделение зависимостей между вендорами
64
+ - Независимую версию и обновление компонентов
65
+ - Возможность включать в состав вендора дополнительные файлы (конфигурации, package.json и т.д.)
66
+
67
+ **Структура пути к устройству:**
68
+ ```
69
+ devices/
70
+ {vendor}/ # Директория вендора (например, "vrack2")
71
+ {Device} # Файл устройства (например, "Master")
72
+ list.json # Файл регистрации устройств
73
+ ```
74
+
75
+ #### Регистрация устройств
76
+
77
+ Для подключения устройств к системе необходимо зарегистрировать их в файле `list.json`. Поддерживается два формата:
78
+
79
+ 1. **Простой массив** (для устройств в корне вендора):
80
+ ```json
81
+ ["Device1", "Device2"]
82
+ ```
83
+
84
+ 2. **Объект с путями** (для сложной структуры, как в VRack2):
85
+ ```json
86
+ {
87
+ "Master": "devices/Master",
88
+ "Interval": "devices/Interval",
89
+ "System": "devices/System"
90
+ }
91
+ ```
92
+
93
+ **Важно:**
94
+ - Имена устройств всегда пишутся с заглавной буквы (прим. DeviceName)
95
+ - Пути указываются относительно директории вендора
96
+
97
+ #### Пример из VRack2
98
+
99
+ В VRack2 устройства пишуться на TypeScript и являются отдельным репозиторием. Поэтому исходные тексты лежать в директории `devices/vrack2/src` которые компилируются в JavaScript в директорию `devices/vrack2/devices`.
100
+
101
+ ```
102
+ devices/
103
+ vrack2/
104
+ devices/ # Основная директория устройств
105
+ Master # Пример устройства
106
+ System
107
+ list.json # Содержит mapping устройств
108
+ ```
109
+
110
+ ### Хранилище устройств
111
+
112
+ Устройства могут сохранять свое состояние в персистентное хранилище. Данные автоматически восстанавливаются при запуске устройства.
113
+
114
+ **Требования:**
115
+ - Директория `storage/` должна быть создана вручную
116
+ - Поддиректории и файлы создаются автоматически при сохранении данных
117
+
118
+ **Структура хранилища:**
119
+ ```
120
+ storage/
121
+ {ContainerID}/ # Идентификатор контейнера (создается автоматически)
122
+ {DeviceName} # Файл данных устройства (формат: JSON)
123
+ ```
124
+
125
+ ### Хранилище структур контейнеров
126
+
127
+ При загрузке контейнера - `StructureStorage` автоматически сохраняет полную структурную информацию которая формируется в контейнере.
128
+
129
+ **Структура содержит:**
130
+ - Полную информацию о самом устройстве без его конфигурации из файла сервиса
131
+ - Все соединения
132
+ - Визуальные параметры (цвета, расположение)
133
+
134
+ **Требования:**
135
+ - Директория `structure/` создается вручную
136
+ - Файлы обновляются автоматически при изменениях
137
+
138
+ **Расположение файлов:**
139
+ ```
140
+ structure/
141
+ {ContainerID} # Файл структуры (формат: JSON)
142
+ ```
143
+
144
+ ## 4. Файл сервиса
145
+
146
+ Файл сервсиа лучше всего расположить внутри вашего основного репозитория с устройствами. В VRack2 так и сделано - файл сервиса расположен в репозитории устройств VRack2 `devices/vrack2/service.json`.
147
+
148
+ Таким образом можно использовать один и тот же файл запуска для разных сервисов, в том числе и совместно с VRack2 без использования VRack2.
@@ -0,0 +1,79 @@
1
+ import BootClass from './boot/BootClass';
2
+ import Container from './Container';
3
+ /**
4
+ * Defines a list of bootstrap classes to load
5
+ *
6
+ * {
7
+ * 'ClassID': {
8
+ * path: 'importclass.path',
9
+ * options: {}
10
+ * }
11
+ * }
12
+ */
13
+ export interface IBootListConfig {
14
+ [key: string]: {
15
+ /** VRack-style bootclass path */
16
+ path: string;
17
+ /** Options for this bootclass */
18
+ options: {
19
+ [key: string]: any;
20
+ };
21
+ };
22
+ }
23
+ /**
24
+ * Bootstrap is a class for running bootclasses,
25
+ * which should work above Container and is required
26
+ * for Container to work.
27
+ *
28
+ * For example DeviceManager class - it is
29
+ * necessary for Container to work but it must be
30
+ * replaceable and customizable.
31
+ *
32
+ * Bootstrap handles the loading of DeviceManager and
33
+ * provides the ability to work with it from Container.
34
+ * Bootclasses are a forced exception.
35
+ *
36
+ * This is the minimum code that is needed to do everything
37
+ * else in the style of VRack service.
38
+ *
39
+ */
40
+ export default class Bootstrap {
41
+ /**
42
+ * Loaded class list
43
+ *
44
+ * ```ts
45
+ * { UniqueID: Classinstance }
46
+ * ```
47
+ */
48
+ protected loaded: {
49
+ [key: string]: BootClass;
50
+ };
51
+ /**
52
+ * List of downloadable classes and their settings
53
+ *
54
+ * @see IBootListConfig
55
+ */
56
+ protected config: IBootListConfig;
57
+ constructor(config: IBootListConfig);
58
+ /**
59
+ * Load bootclasses
60
+ *
61
+ * Bootclass has some analogy to devices within VRack services.
62
+ * They also have options, process, processPromise methods similar to devices
63
+ *
64
+ * @param Container Container for which loading is performed
65
+ */
66
+ loadBootList(Container: Container): Promise<void>;
67
+ /**
68
+ * Getting an initialized class
69
+ *
70
+ * @example
71
+ * ```ts
72
+ * this.Container.Bootstrap.getBootClass('DeviceMetrics', DeviceMetrics) as DeviceMetrics
73
+ * ```
74
+ *
75
+ * @param id class identifier that was specified in the list
76
+ * @param cs Class to be compared with when receiving
77
+ */
78
+ getBootClass(id: string, cs: any): any;
79
+ }
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright © 2024 Boris Bobylev. All rights reserved.
4
+ * Licensed under the Apache License, Version 2.0
5
+ */
6
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
7
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8
+ return new (P || (P = Promise))(function (resolve, reject) {
9
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
13
+ });
14
+ };
15
+ var __importDefault = (this && this.__importDefault) || function (mod) {
16
+ return (mod && mod.__esModule) ? mod : { "default": mod };
17
+ };
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ const _1 = require(".");
20
+ const BootClass_1 = __importDefault(require("./boot/BootClass"));
21
+ const ImportManager_1 = __importDefault(require("./ImportManager"));
22
+ _1.ErrorManager.register('Bootstrap', 'yNHeX5fwDH5P', 'BTSP_CLASS_ID_NOT_FOUND', 'Bootstrap class id not found', {
23
+ id: _1.Rule.string().description('Class identify')
24
+ });
25
+ _1.ErrorManager.register('Bootstrap', 'ack6kwHSBtcf', 'BTSP_INSTANCE_OF_INCORRECT', 'Bootstrap class id is not a class defined by check', {
26
+ id: _1.Rule.string().description('Class identify')
27
+ });
28
+ _1.ErrorManager.register('Bootstrap', 'DMloqbZG9J36', 'BTSP_MUST_BE_BOOTCLASS', 'The class must be inherited from BootClass', {
29
+ path: _1.Rule.string().description('Class path')
30
+ });
31
+ /**
32
+ * Bootstrap is a class for running bootclasses,
33
+ * which should work above Container and is required
34
+ * for Container to work.
35
+ *
36
+ * For example DeviceManager class - it is
37
+ * necessary for Container to work but it must be
38
+ * replaceable and customizable.
39
+ *
40
+ * Bootstrap handles the loading of DeviceManager and
41
+ * provides the ability to work with it from Container.
42
+ * Bootclasses are a forced exception.
43
+ *
44
+ * This is the minimum code that is needed to do everything
45
+ * else in the style of VRack service.
46
+ *
47
+ */
48
+ class Bootstrap {
49
+ constructor(config) {
50
+ /**
51
+ * Loaded class list
52
+ *
53
+ * ```ts
54
+ * { UniqueID: Classinstance }
55
+ * ```
56
+ */
57
+ this.loaded = {};
58
+ this.config = config;
59
+ }
60
+ /**
61
+ * Load bootclasses
62
+ *
63
+ * Bootclass has some analogy to devices within VRack services.
64
+ * They also have options, process, processPromise methods similar to devices
65
+ *
66
+ * @param Container Container for which loading is performed
67
+ */
68
+ loadBootList(Container) {
69
+ return __awaiter(this, void 0, void 0, function* () {
70
+ for (const cn in this.config) {
71
+ const conf = this.config[cn];
72
+ const ExClass = yield ImportManager_1.default.importClass(conf.path);
73
+ this.loaded[cn] = new ExClass(cn, ImportManager_1.default.importClassName(conf.path), Container, conf.options);
74
+ if (!(this.loaded[cn] instanceof BootClass_1.default)) {
75
+ throw _1.ErrorManager.make('BTSP_INSTANCE_OF_INCORRECT', { path: conf.path });
76
+ }
77
+ }
78
+ for (const bc in this.loaded)
79
+ this.loaded[bc].process();
80
+ for (const bc in this.loaded)
81
+ yield this.loaded[bc].processPromise();
82
+ });
83
+ }
84
+ /**
85
+ * Getting an initialized class
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * this.Container.Bootstrap.getBootClass('DeviceMetrics', DeviceMetrics) as DeviceMetrics
90
+ * ```
91
+ *
92
+ * @param id class identifier that was specified in the list
93
+ * @param cs Class to be compared with when receiving
94
+ */
95
+ getBootClass(id, cs) {
96
+ if (!this.loaded[id])
97
+ throw _1.ErrorManager.make('BTSP_CLASS_ID_NOT_FOUND', { id });
98
+ if (!(this.loaded[id] instanceof cs))
99
+ throw _1.ErrorManager.make('BTSP_INSTANCE_OF_INCORRECT', { id });
100
+ return this.loaded[id];
101
+ }
102
+ }
103
+ exports.default = Bootstrap;
@@ -1,29 +1,225 @@
1
1
  /// <reference types="node" />
2
2
  import EventEmitter from "events";
3
- import DeviceManager from "./DeviceManager";
4
3
  import IServiceStructure from "./IServiceStructure";
5
4
  import IStructureDevice from "./IStructureDevice";
6
5
  import Device from "./service/Device";
7
6
  import BasicAction from "./actions/BasicAction";
8
7
  import IPort from "./ports/IPort";
8
+ import IAction from "./actions/IAction";
9
+ import Bootstrap from "./Bootstrap";
10
+ import IMetricSettings from "./metrics/IMetricSettings";
11
+ import BasicMetric from "./metrics/BasicMetric";
12
+ /**
13
+ * Contains the structure of the service
14
+ *
15
+ * Where { DeviceID: DeviceStructure }
16
+ */
17
+ export interface IContainerStructure {
18
+ [key: string]: {
19
+ /** Device ID */
20
+ id: string;
21
+ /** Device type like a 'vendor.Device'*/
22
+ type: string;
23
+ /** Actions list @see IAction */
24
+ actions: {
25
+ [key: string]: IAction;
26
+ };
27
+ /** List of ports with their connections */
28
+ outputs: {
29
+ [key: string]: Array<{
30
+ device: string;
31
+ port: string;
32
+ }>;
33
+ };
34
+ /** List of ports with their connections */
35
+ inputs: {
36
+ [key: string]: Array<{
37
+ device: string;
38
+ port: string;
39
+ }>;
40
+ };
41
+ /** List of all ports on the device */
42
+ ports: Array<IDeviceStructurePort>;
43
+ /** A list of device metrics */
44
+ metrics: {
45
+ [key: string]: IMetricSettings;
46
+ };
47
+ /** Device display settings */
48
+ settings: {
49
+ [key: string]: any;
50
+ };
51
+ /** Personalized display settings */
52
+ display?: {
53
+ header_bg?: string;
54
+ body_bg?: string;
55
+ group_bg?: string;
56
+ is_rotated?: boolean;
57
+ row?: number;
58
+ col?: number;
59
+ };
60
+ };
61
+ }
62
+ export interface IDeviceStructurePort extends IPort {
63
+ /** Port ID */
64
+ port: string;
65
+ /** Port direct */
66
+ direct: string;
67
+ }
68
+ /**
69
+ * Service Load Class. It loads all devices in the list,
70
+ * establishes connections between them, and performs device startup.
71
+ *
72
+ * This class is a bit complicated for a simple description.
73
+ * It is recommended to familiarize yourself with the source code
74
+ */
9
75
  export default class Container extends EventEmitter {
10
- protected config: IServiceStructure;
11
- protected DeviceManager: DeviceManager;
12
- protected devices: {
76
+ /** Unique service ID */
77
+ id: string;
78
+ /** List of devices in container */
79
+ devices: {
13
80
  [key: string]: Device;
14
81
  };
82
+ /** Parent container if it exists */
83
+ parent?: Container;
84
+ /**
85
+ * Path to extended conf file for init loading
86
+ * @see fillConfFile()
87
+ * */
88
+ confFile?: string;
89
+ /**
90
+ * Container bootstrap class
91
+ *
92
+ * A different bootstrap class must be created for each container
93
+ */
94
+ Bootstrap: Bootstrap;
95
+ /** inited flag */
96
+ protected inited: boolean;
97
+ /** run flag */
98
+ protected runned: boolean;
99
+ /**
100
+ * Service structure config
101
+ *
102
+ * @see constructor
103
+ */
104
+ protected service: IServiceStructure;
105
+ /**
106
+ * List of all device actions
107
+ *
108
+ * [deviceID]: { action.name: BasicAction}
109
+ */
15
110
  protected deviceActions: {
16
111
  [key: string]: {
17
112
  [key: string]: BasicAction;
18
113
  };
19
114
  };
20
- constructor(config: IServiceStructure, dm: DeviceManager);
115
+ /**
116
+ * List of all device metrics
117
+ *
118
+ */
119
+ protected deviceMetrics: {
120
+ [key: string]: {
121
+ [key: string]: BasicMetric;
122
+ };
123
+ };
124
+ /**
125
+ * Container structure
126
+ */
127
+ protected structure: IContainerStructure;
128
+ /**
129
+ * Create container needed service structure & device manager
130
+ *
131
+ * @param service Service structure
132
+ * @param bootstrap Bootstrap class Object
133
+ *
134
+ * */
135
+ constructor(id: string, service: IServiceStructure, Bootstrap: Bootstrap, confFile?: string);
136
+ /**
137
+ * Run container
138
+ */
21
139
  run(): Promise<void>;
140
+ /**
141
+ * Extends service from config file
142
+ *
143
+ * Sometimes there is a need to override the settings of some devices.
144
+ * To do this, you can use a special configuration file of the service.
145
+ * It contains the same as the main service file and replaces with its settings
146
+ * and parameters the settings and parameters of the main service.
147
+ *
148
+ * @see init()
149
+ */
150
+ protected fillConfFile(): void;
151
+ /**
152
+ * Creates device classes. Preprocesses the device,
153
+ * then adds ports to it and creates connections between ports.
154
+ *
155
+ * When adding and creating devices, ports and connections,
156
+ * the service structure is also created
157
+ *
158
+ * 1. Init device
159
+ * 2. Init individual device connections
160
+ * 3. Init other connections
161
+ *
162
+ * @see structure
163
+ */
164
+ init(): Promise<void>;
165
+ /**
166
+ * Run process & processPromise of all devices
167
+ */
168
+ runProcess(): Promise<void>;
169
+ /**
170
+ * Check device action and run him
171
+ *
172
+ * @param device Device ID
173
+ * @param action Device action (as 'action.name')
174
+ * @param data Data for action
175
+ */
176
+ deviceAction(device: string, action: string, data: any): Promise<any>;
177
+ /**
178
+ * Return structure
179
+ */
180
+ getStructure(): Promise<IContainerStructure>;
181
+ /**
182
+ * Init one device
183
+ *
184
+ * 1. Make device class object
185
+ * 2. Fill device options
186
+ * 3. Run device prepareOptions method
187
+ * 4. Validating device options
188
+ * 5. Check device actions
189
+ * 6. make device inputs ports
190
+ * 7. make device outputs ports
191
+ **/
22
192
  protected initDevice(dconf: IStructureDevice): Promise<void>;
193
+ /**
194
+ * Check device input handler
195
+ * Make CTR_INPUT_HANDLER_NF error if not exists
196
+ * @see initDevice make inputPorts
197
+ */
23
198
  protected checkInputHandler(port: string, handler: string, device: Device): void;
24
- protected initConnection(conn: string): Promise<void>;
199
+ /**
200
+ * Init device connection
201
+ *
202
+ * @param conn Device connection string like a "DevID.port -> DevIDTO.port"
203
+ */
204
+ protected initConnection(conn: string): void;
205
+ /**
206
+ * Container Helper - parse connection string to format object
207
+ *
208
+ * @return Connection object
209
+ */
25
210
  private toConnection;
211
+ /**
212
+ * Check Port name (strict format a-zA-Z0-9.)
213
+ *
214
+ * @param port Port name
215
+ */
26
216
  protected checkPortName(port: string): void;
217
+ /**
218
+ * Convert dynamic port to ports list
219
+ *
220
+ * @param name Port name with %d symbols
221
+ * @param iPort IPort object (port settings)
222
+ */
27
223
  protected getPortList(name: string, iPort: IPort): {
28
224
  [key: string]: IPort;
29
225
  };