@meteotrust/node-red 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +9 -0
- package/LICENSE +21 -0
- package/README.en.md +17 -0
- package/README.md +80 -2
- package/examples/01 Weather and forecasts.json +96 -0
- package/examples/02 Publish weather to MQTT.json +122 -0
- package/examples/03 Tablet commands.json +169 -0
- package/lib/client.js +101 -0
- package/nodes/icons/meteotrust.svg +1 -0
- package/nodes/meteotrust.html +85 -0
- package/nodes/meteotrust.js +38 -0
- package/package.json +49 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.1 — 2026-12-06
|
|
4
|
+
|
|
5
|
+
Prepare the first public npm distribution with npm installation instructions and catalog links. Runtime behavior is unchanged from the tested 0.1.0 GitHub release.
|
|
6
|
+
|
|
7
|
+
## 0.1.0 — 2026-12-06
|
|
8
|
+
|
|
9
|
+
Initial MeteoTrust integration release. See README for supported features, configuration and limitations.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 MeteoTrust
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.en.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# MeteoTrust for Node-RED
|
|
2
|
+
|
|
3
|
+
[Русский](README.md) · [API docs](https://meteotrust.ru/docs.html)
|
|
4
|
+
|
|
5
|
+
Five nodes: weather (combined current + hourly forecast), current, hourly, daily and building (smart-building data and weather-based recommendations). A shared account config node stores the API key as Node-RED credentials. Requires Node-RED 4.1+, Node.js 22+, a MeteoTrust API key and API subscription.
|
|
6
|
+
|
|
7
|
+
Install from your Node-RED user directory with `npm install @meteotrust/node-red`, or `npm install /path/to/meteotrust-node-red-0.1.1.tgz`, then restart. [npm package](https://www.npmjs.com/package/@meteotrust/node-red) · [Node-RED catalog](https://flows.nodered.org/node/@meteotrust/node-red). Once indexed in the catalog, search for `@meteotrust/node-red` under Manage Palette → Install. Catalog indexing is separate from npm publication. To install source directly, use `npm install github:darkssside/node-red-meteotrust`.
|
|
8
|
+
|
|
9
|
+
Configure the account and location coordinates. The weather/building nodes optionally accept a saved location UUID instead. Input messages trigger requests; the API's data is placed in `msg.payload`. `msg.meteotrust` contains operation, cached, received_at and API meta. Other input properties survive. Errors use standard Catch nodes and never forward raw upstream bodies or credentials. Messages cannot override URL/credentials/location.
|
|
10
|
+
|
|
11
|
+
Identical requests share an in-flight call and a 10-minute cache per account config. Each successful network request consumes API allowance; local cache hits do not. Use the combined weather node to avoid separate current/hourly/daily requests. A ten-minute interval costs about 4,464 calls in 31 days per query/location. Other screens and integrations share your allowance. HTTP 429 enforces Retry-After (default 600 seconds); no automatic retry loop is started.
|
|
12
|
+
|
|
13
|
+
Check actual observation/forecast timestamps, not received_at. Current weather older than two hours is rejected. MQTT retained data may outlive the sender: consumers must check freshness. Smart-building decisions are recommendations; equipment safety remains with the local controller.
|
|
14
|
+
|
|
15
|
+
Examples include combined weather, MQTT publishing and Android tablet commands. Tablet MQTT commands do not call the weather API. Configure broker credentials in Node-RED's standard MQTT node.
|
|
16
|
+
|
|
17
|
+
Development: `npm ci`, `npm test`, `npm pack --dry-run`, `npm pack`. Tests cover the HTTP client and actual Node-RED runtime with a mocked API. See [publishing](PUBLISHING.md) and [license](LICENSE).
|
package/README.md
CHANGED
|
@@ -1,3 +1,81 @@
|
|
|
1
|
-
#
|
|
1
|
+
# MeteoTrust для Node-RED
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[English](README.en.md) · [API MeteoTrust](https://meteotrust.ru/docs.html) · [Поддержка](https://github.com/darkssside/node-red-meteotrust/issues)
|
|
4
|
+
|
|
5
|
+
Пять погодных узлов и общий узел аккаунта. Требуются Node-RED 4.1+, Node.js 22+ и API-ключ MeteoTrust с действующей подпиской.
|
|
6
|
+
|
|
7
|
+
| Узел | Результат |
|
|
8
|
+
|---|---|
|
|
9
|
+
| `meteotrust-weather` | Текущая погода и почасовой прогноз до 168 часов одним запросом |
|
|
10
|
+
| `meteotrust-current` | Текущая погода |
|
|
11
|
+
| `meteotrust-hourly` | Почасовой прогноз на 1–168 часов |
|
|
12
|
+
| `meteotrust-daily` | Прогноз по дням, до 7 дней |
|
|
13
|
+
| `meteotrust-building` | Показатели умного здания и погодные рекомендации для полива/обогрева |
|
|
14
|
+
|
|
15
|
+
## Установка
|
|
16
|
+
|
|
17
|
+
Имя пакета — `@meteotrust/node-red`. [Страница npm](https://www.npmjs.com/package/@meteotrust/node-red) · [Каталог Node-RED](https://flows.nodered.org/node/@meteotrust/node-red).
|
|
18
|
+
|
|
19
|
+
В каталоге пользователя Node-RED (обычно `~/.node-red`):
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
npm install @meteotrust/node-red
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Либо для локального архива с сайта MeteoTrust:
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
npm install /полный/путь/meteotrust-node-red-0.1.1.tgz
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Перезапустите Node-RED. Если пакет уже отображается в Flow Library, его также можно установить через **Manage Palette → Install**, выполнив поиск `@meteotrust/node-red`. Индексация каталога выполняется отдельно от npm. Для установки исходников из GitHub используйте `npm install github:darkssside/node-red-meteotrust`.
|
|
32
|
+
|
|
33
|
+
## Настройка
|
|
34
|
+
|
|
35
|
+
1. Перетащите `MeteoTrust weather` из палитры.
|
|
36
|
+
2. Создайте общий аккаунт MeteoTrust: задайте название, API-ключ из кабинета и срок локального кэша. По умолчанию — 600 секунд.
|
|
37
|
+
3. Укажите координаты своего объекта. У узлов weather/building вместо координат можно задать UUID сохранённой локации; он имеет приоритет.
|
|
38
|
+
4. Для прогноза выберите число часов/дней. Проверьте координаты перед запуском: новая точка может занять слот локации.
|
|
39
|
+
5. Подключите Inject на 10 минут ко входу и Debug ко выходу, нажмите Deploy.
|
|
40
|
+
6. Готовые схемы находятся в **Import → Examples → @meteotrust/node-red**.
|
|
41
|
+
|
|
42
|
+
Ключ хранится механизмом credentials Node-RED и не включается в экспорт flow. Сообщения не могут менять URL, ключ или локацию: используются настройки узла. Все запросы идут только на `https://meteotrust.ru`, перенаправления запрещены.
|
|
43
|
+
|
|
44
|
+
## Сообщения
|
|
45
|
+
|
|
46
|
+
Любое входящее сообщение инициирует настроенный запрос. Его остальные поля сохраняются.
|
|
47
|
+
|
|
48
|
+
- `msg.payload` — поле `data` ответа MeteoTrust. Для weather это `current`, `forecast.hours` и `location`.
|
|
49
|
+
- `msg.meteotrust.operation` — операция.
|
|
50
|
+
- `msg.meteotrust.cached` — использован локальный кэш.
|
|
51
|
+
- `msg.meteotrust.received_at` — время получения ответа клиентом, **не время наблюдения**.
|
|
52
|
+
- `msg.meteotrust.meta` — метаданные API.
|
|
53
|
+
|
|
54
|
+
Ошибка направляется в стандартный **Catch**, а узел показывает статус. Ошибочные данные не передаются на успешный выход. Сбой сети, неверный ключ, запрет доступа, HTTP 429, некорректный JSON, слишком большой ответ и устаревшая текущая погода обрабатываются отдельно. Текст ответа сервера и ключ не включаются в ошибки.
|
|
55
|
+
|
|
56
|
+
## Кэш, лимиты и актуальность
|
|
57
|
+
|
|
58
|
+
Одинаковые запросы через один узел аккаунта используют общий кэш и объединяются, если выполняются одновременно. Кэш по умолчанию 10 минут, настраивается от 60 до 86400 секунд. Длительный кэш подходит только если допустимо более редкое обновление; текущая погода старше двух часов всё равно не принимается.
|
|
59
|
+
|
|
60
|
+
Один успешный сетевой вызов — один запрос API. Локальный кэш не обращается к серверу. Ответ из серверного кэша учитывается как обычный успешный API-запрос. Один запрос каждые 10 минут — примерно 4464 за 31 день, без дополнительных ручных проверок. Раздельные current/hourly/daily узлы делают отдельные запросы; для экономии используйте weather и разделяйте его результат дальше в flow.
|
|
61
|
+
|
|
62
|
+
При 429 новые сетевые запросы ждут `Retry-After`, по умолчанию 600 секунд. Автоматического цикла повторов нет; следующий Inject повторит запрос после паузы. Несколько экземпляров Node-RED и другие экраны используют бюджет аккаунта совместно, но не разделяют локальный кэш.
|
|
63
|
+
|
|
64
|
+
Проверяйте `observed_at`/`updated_at`, `valid_at`, состояние API и срок рекомендаций. Сохранённое в MQTT сообщение может пережить выключение Node-RED. Рекомендации полива/обогрева не исполняют команды: локальные разрешения, ручной режим, датчики и защиты остаются в логике контроллера.
|
|
65
|
+
|
|
66
|
+
## MQTT и планшет
|
|
67
|
+
|
|
68
|
+
Выход weather/building можно подключить к стандартному MQTT Out. Учётные данные брокера задаются в штатном MQTT-узле, отдельно от ключа MeteoTrust. Пример в `examples` публикует данные в `meteotrust/home/weather` без retain, чтобы не сохранять прежнее значение бессрочно.
|
|
69
|
+
|
|
70
|
+
Для Android-планшета уже существует отдельный протокол: `meteotrust/tablet/hall/command` и текст `meteotrust`, `loxone`, `screen_on`, `screen_off`, `status`, QoS 1, retain выключен. Пример `Tablet commands` использует только стандартные MQTT-узлы и не расходует погодную квоту. См. https://meteotrust.ru/downloads/android/mqtt.html .
|
|
71
|
+
|
|
72
|
+
## Разработка
|
|
73
|
+
|
|
74
|
+
```sh
|
|
75
|
+
npm ci
|
|
76
|
+
npm test
|
|
77
|
+
npm pack --dry-run
|
|
78
|
+
npm pack
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Тесты клиента и узлов запускаются в настоящем Node-RED с имитацией API, без живых ключей. Пакет не имеет сторонних runtime-зависимостей; Node-RED и test-helper используются только для разработки. [Публикация](PUBLISHING.md). Лицензия MIT.
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
[
|
|
2
|
+
{
|
|
3
|
+
"id": "mt-example",
|
|
4
|
+
"type": "tab",
|
|
5
|
+
"label": "MeteoTrust weather",
|
|
6
|
+
"disabled": false,
|
|
7
|
+
"info": "Configure your API key and location. One combined request per 10 minutes. No credentials in this example."
|
|
8
|
+
},
|
|
9
|
+
{
|
|
10
|
+
"id": "mt-account",
|
|
11
|
+
"type": "meteotrust-account",
|
|
12
|
+
"name": "MeteoTrust",
|
|
13
|
+
"cacheSeconds": 600
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
"id": "mt-trigger",
|
|
17
|
+
"type": "inject",
|
|
18
|
+
"z": "mt-example",
|
|
19
|
+
"name": "Каждые 10 минут",
|
|
20
|
+
"props": [
|
|
21
|
+
{
|
|
22
|
+
"p": "payload"
|
|
23
|
+
}
|
|
24
|
+
],
|
|
25
|
+
"repeat": "600",
|
|
26
|
+
"once": false,
|
|
27
|
+
"payloadType": "date",
|
|
28
|
+
"x": 170,
|
|
29
|
+
"y": 120,
|
|
30
|
+
"wires": [
|
|
31
|
+
[
|
|
32
|
+
"mt-weather"
|
|
33
|
+
]
|
|
34
|
+
]
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
"id": "mt-weather",
|
|
38
|
+
"type": "meteotrust-weather",
|
|
39
|
+
"z": "mt-example",
|
|
40
|
+
"account": "mt-account",
|
|
41
|
+
"name": "Погода и прогноз",
|
|
42
|
+
"latitude": 59.9386,
|
|
43
|
+
"longitude": 30.3141,
|
|
44
|
+
"hours": 168,
|
|
45
|
+
"x": 420,
|
|
46
|
+
"y": 120,
|
|
47
|
+
"wires": [
|
|
48
|
+
[
|
|
49
|
+
"mt-debug"
|
|
50
|
+
]
|
|
51
|
+
]
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"id": "mt-debug",
|
|
55
|
+
"type": "debug",
|
|
56
|
+
"z": "mt-example",
|
|
57
|
+
"name": "Погода",
|
|
58
|
+
"active": true,
|
|
59
|
+
"tosidebar": true,
|
|
60
|
+
"complete": "payload",
|
|
61
|
+
"targetType": "msg",
|
|
62
|
+
"x": 690,
|
|
63
|
+
"y": 120,
|
|
64
|
+
"wires": []
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
"id": "mt-catch",
|
|
68
|
+
"type": "catch",
|
|
69
|
+
"z": "mt-example",
|
|
70
|
+
"name": "Ошибки MeteoTrust",
|
|
71
|
+
"scope": [
|
|
72
|
+
"mt-weather"
|
|
73
|
+
],
|
|
74
|
+
"uncaught": false,
|
|
75
|
+
"x": 410,
|
|
76
|
+
"y": 220,
|
|
77
|
+
"wires": [
|
|
78
|
+
[
|
|
79
|
+
"mt-error"
|
|
80
|
+
]
|
|
81
|
+
]
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
"id": "mt-error",
|
|
85
|
+
"type": "debug",
|
|
86
|
+
"z": "mt-example",
|
|
87
|
+
"name": "Ошибка — проверить API и подписку",
|
|
88
|
+
"active": true,
|
|
89
|
+
"tosidebar": true,
|
|
90
|
+
"complete": "error.message",
|
|
91
|
+
"targetType": "msg",
|
|
92
|
+
"x": 740,
|
|
93
|
+
"y": 220,
|
|
94
|
+
"wires": []
|
|
95
|
+
}
|
|
96
|
+
]
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
[
|
|
2
|
+
{
|
|
3
|
+
"id": "mt-example",
|
|
4
|
+
"type": "tab",
|
|
5
|
+
"label": "MeteoTrust → MQTT",
|
|
6
|
+
"disabled": false,
|
|
7
|
+
"info": "Configure your API key and location. One combined request per 10 minutes. No credentials in this example."
|
|
8
|
+
},
|
|
9
|
+
{
|
|
10
|
+
"id": "mt-account",
|
|
11
|
+
"type": "meteotrust-account",
|
|
12
|
+
"name": "MeteoTrust",
|
|
13
|
+
"cacheSeconds": 600
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
"id": "mt-trigger",
|
|
17
|
+
"type": "inject",
|
|
18
|
+
"z": "mt-example",
|
|
19
|
+
"name": "Каждые 10 минут",
|
|
20
|
+
"props": [
|
|
21
|
+
{
|
|
22
|
+
"p": "payload"
|
|
23
|
+
}
|
|
24
|
+
],
|
|
25
|
+
"repeat": "600",
|
|
26
|
+
"once": false,
|
|
27
|
+
"payloadType": "date",
|
|
28
|
+
"x": 170,
|
|
29
|
+
"y": 120,
|
|
30
|
+
"wires": [
|
|
31
|
+
[
|
|
32
|
+
"mt-weather"
|
|
33
|
+
]
|
|
34
|
+
]
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
"id": "mt-weather",
|
|
38
|
+
"type": "meteotrust-weather",
|
|
39
|
+
"z": "mt-example",
|
|
40
|
+
"account": "mt-account",
|
|
41
|
+
"name": "Погода и прогноз",
|
|
42
|
+
"latitude": 59.9386,
|
|
43
|
+
"longitude": 30.3141,
|
|
44
|
+
"hours": 168,
|
|
45
|
+
"x": 420,
|
|
46
|
+
"y": 120,
|
|
47
|
+
"wires": [
|
|
48
|
+
[
|
|
49
|
+
"mt-mqtt"
|
|
50
|
+
]
|
|
51
|
+
]
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"id": "mt-debug",
|
|
55
|
+
"type": "debug",
|
|
56
|
+
"z": "mt-example",
|
|
57
|
+
"name": "Погода",
|
|
58
|
+
"active": true,
|
|
59
|
+
"tosidebar": true,
|
|
60
|
+
"complete": "payload",
|
|
61
|
+
"targetType": "msg",
|
|
62
|
+
"x": 690,
|
|
63
|
+
"y": 120,
|
|
64
|
+
"wires": []
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
"id": "mt-catch",
|
|
68
|
+
"type": "catch",
|
|
69
|
+
"z": "mt-example",
|
|
70
|
+
"name": "Ошибки MeteoTrust",
|
|
71
|
+
"scope": [
|
|
72
|
+
"mt-weather"
|
|
73
|
+
],
|
|
74
|
+
"uncaught": false,
|
|
75
|
+
"x": 410,
|
|
76
|
+
"y": 220,
|
|
77
|
+
"wires": [
|
|
78
|
+
[
|
|
79
|
+
"mt-error"
|
|
80
|
+
]
|
|
81
|
+
]
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
"id": "mt-error",
|
|
85
|
+
"type": "debug",
|
|
86
|
+
"z": "mt-example",
|
|
87
|
+
"name": "Ошибка — проверить API и подписку",
|
|
88
|
+
"active": true,
|
|
89
|
+
"tosidebar": true,
|
|
90
|
+
"complete": "error.message",
|
|
91
|
+
"targetType": "msg",
|
|
92
|
+
"x": 740,
|
|
93
|
+
"y": 220,
|
|
94
|
+
"wires": []
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
"id": "mt-broker",
|
|
98
|
+
"type": "mqtt-broker",
|
|
99
|
+
"name": "Настройте свой брокер",
|
|
100
|
+
"broker": "",
|
|
101
|
+
"port": "1883",
|
|
102
|
+
"clientid": "",
|
|
103
|
+
"autoConnect": true,
|
|
104
|
+
"usetls": false,
|
|
105
|
+
"protocolVersion": "4",
|
|
106
|
+
"keepalive": "60",
|
|
107
|
+
"cleansession": true
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
"id": "mt-mqtt",
|
|
111
|
+
"type": "mqtt out",
|
|
112
|
+
"z": "mt-example",
|
|
113
|
+
"name": "Погода в MQTT",
|
|
114
|
+
"topic": "meteotrust/home/weather",
|
|
115
|
+
"qos": "1",
|
|
116
|
+
"retain": "false",
|
|
117
|
+
"broker": "mt-broker",
|
|
118
|
+
"x": 700,
|
|
119
|
+
"y": 120,
|
|
120
|
+
"wires": []
|
|
121
|
+
}
|
|
122
|
+
]
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
[
|
|
2
|
+
{
|
|
3
|
+
"id": "mt-tablet",
|
|
4
|
+
"type": "tab",
|
|
5
|
+
"label": "MeteoTrust tablet commands",
|
|
6
|
+
"info": "Set tablet base topic to meteotrust/tablet/hall; enable command reception. Configure broker credentials in its config node. QoS 1, retain false. Sleeping tablet: screen_on, wait 2 seconds, then loxone or meteotrust. Secure PIN unlock stays manual."
|
|
7
|
+
},
|
|
8
|
+
{
|
|
9
|
+
"id": "mt-broker",
|
|
10
|
+
"type": "mqtt-broker",
|
|
11
|
+
"name": "Настройте свой брокер",
|
|
12
|
+
"broker": "",
|
|
13
|
+
"port": "1883",
|
|
14
|
+
"clientid": "",
|
|
15
|
+
"autoConnect": true,
|
|
16
|
+
"usetls": false,
|
|
17
|
+
"protocolVersion": "4",
|
|
18
|
+
"keepalive": "60",
|
|
19
|
+
"cleansession": true
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
"id": "mt-tablet-out",
|
|
23
|
+
"type": "mqtt out",
|
|
24
|
+
"z": "mt-tablet",
|
|
25
|
+
"name": "Команда планшету",
|
|
26
|
+
"topic": "meteotrust/tablet/hall/command",
|
|
27
|
+
"qos": "1",
|
|
28
|
+
"retain": "false",
|
|
29
|
+
"broker": "mt-broker",
|
|
30
|
+
"x": 650,
|
|
31
|
+
"y": 180,
|
|
32
|
+
"wires": []
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
"id": "mt-meteotrust",
|
|
36
|
+
"type": "inject",
|
|
37
|
+
"z": "mt-tablet",
|
|
38
|
+
"name": "meteotrust",
|
|
39
|
+
"props": [
|
|
40
|
+
{
|
|
41
|
+
"p": "payload"
|
|
42
|
+
}
|
|
43
|
+
],
|
|
44
|
+
"payload": "meteotrust",
|
|
45
|
+
"payloadType": "str",
|
|
46
|
+
"once": false,
|
|
47
|
+
"x": 180,
|
|
48
|
+
"y": 80,
|
|
49
|
+
"wires": [
|
|
50
|
+
[
|
|
51
|
+
"mt-tablet-out"
|
|
52
|
+
]
|
|
53
|
+
]
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
"id": "mt-loxone",
|
|
57
|
+
"type": "inject",
|
|
58
|
+
"z": "mt-tablet",
|
|
59
|
+
"name": "loxone",
|
|
60
|
+
"props": [
|
|
61
|
+
{
|
|
62
|
+
"p": "payload"
|
|
63
|
+
}
|
|
64
|
+
],
|
|
65
|
+
"payload": "loxone",
|
|
66
|
+
"payloadType": "str",
|
|
67
|
+
"once": false,
|
|
68
|
+
"x": 180,
|
|
69
|
+
"y": 140,
|
|
70
|
+
"wires": [
|
|
71
|
+
[
|
|
72
|
+
"mt-tablet-out"
|
|
73
|
+
]
|
|
74
|
+
]
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
"id": "mt-screen_on",
|
|
78
|
+
"type": "inject",
|
|
79
|
+
"z": "mt-tablet",
|
|
80
|
+
"name": "screen_on",
|
|
81
|
+
"props": [
|
|
82
|
+
{
|
|
83
|
+
"p": "payload"
|
|
84
|
+
}
|
|
85
|
+
],
|
|
86
|
+
"payload": "screen_on",
|
|
87
|
+
"payloadType": "str",
|
|
88
|
+
"once": false,
|
|
89
|
+
"x": 180,
|
|
90
|
+
"y": 200,
|
|
91
|
+
"wires": [
|
|
92
|
+
[
|
|
93
|
+
"mt-tablet-out"
|
|
94
|
+
]
|
|
95
|
+
]
|
|
96
|
+
},
|
|
97
|
+
{
|
|
98
|
+
"id": "mt-screen_off",
|
|
99
|
+
"type": "inject",
|
|
100
|
+
"z": "mt-tablet",
|
|
101
|
+
"name": "screen_off",
|
|
102
|
+
"props": [
|
|
103
|
+
{
|
|
104
|
+
"p": "payload"
|
|
105
|
+
}
|
|
106
|
+
],
|
|
107
|
+
"payload": "screen_off",
|
|
108
|
+
"payloadType": "str",
|
|
109
|
+
"once": false,
|
|
110
|
+
"x": 180,
|
|
111
|
+
"y": 260,
|
|
112
|
+
"wires": [
|
|
113
|
+
[
|
|
114
|
+
"mt-tablet-out"
|
|
115
|
+
]
|
|
116
|
+
]
|
|
117
|
+
},
|
|
118
|
+
{
|
|
119
|
+
"id": "mt-status",
|
|
120
|
+
"type": "inject",
|
|
121
|
+
"z": "mt-tablet",
|
|
122
|
+
"name": "status",
|
|
123
|
+
"props": [
|
|
124
|
+
{
|
|
125
|
+
"p": "payload"
|
|
126
|
+
}
|
|
127
|
+
],
|
|
128
|
+
"payload": "status",
|
|
129
|
+
"payloadType": "str",
|
|
130
|
+
"once": false,
|
|
131
|
+
"x": 180,
|
|
132
|
+
"y": 320,
|
|
133
|
+
"wires": [
|
|
134
|
+
[
|
|
135
|
+
"mt-tablet-out"
|
|
136
|
+
]
|
|
137
|
+
]
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
"id": "mt-tablet-state",
|
|
141
|
+
"type": "mqtt in",
|
|
142
|
+
"z": "mt-tablet",
|
|
143
|
+
"name": "Состояние и ответы",
|
|
144
|
+
"topic": "meteotrust/tablet/hall/+",
|
|
145
|
+
"qos": "1",
|
|
146
|
+
"datatype": "auto-detect",
|
|
147
|
+
"broker": "mt-broker",
|
|
148
|
+
"x": 220,
|
|
149
|
+
"y": 420,
|
|
150
|
+
"wires": [
|
|
151
|
+
[
|
|
152
|
+
"mt-tablet-debug"
|
|
153
|
+
]
|
|
154
|
+
]
|
|
155
|
+
},
|
|
156
|
+
{
|
|
157
|
+
"id": "mt-tablet-debug",
|
|
158
|
+
"type": "debug",
|
|
159
|
+
"z": "mt-tablet",
|
|
160
|
+
"name": "Ответы планшета",
|
|
161
|
+
"active": true,
|
|
162
|
+
"tosidebar": true,
|
|
163
|
+
"complete": "true",
|
|
164
|
+
"targetType": "full",
|
|
165
|
+
"x": 650,
|
|
166
|
+
"y": 420,
|
|
167
|
+
"wires": []
|
|
168
|
+
}
|
|
169
|
+
]
|
package/lib/client.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
const BASE = "https://meteotrust.ru";
|
|
3
|
+
const PATHS = Object.freeze({weather:"/v1/weather",current:"/v1/current",hourly:"/v1/hourly",daily:"/v1/daily",building:"/v1/integrations/smart-building/weather"});
|
|
4
|
+
class ApiError extends Error {
|
|
5
|
+
constructor(code, message, retryAfter=0) {super(message);this.name="MeteoTrustError";this.code=code;this.retryAfter=retryAfter;}
|
|
6
|
+
}
|
|
7
|
+
function numeric(value,min,max,label) {
|
|
8
|
+
if(value===null||value===undefined||String(value).trim()===""||typeof value==="boolean")throw new ApiError("CONFIG",label+" is required");
|
|
9
|
+
const n=Number(value);
|
|
10
|
+
if(!Number.isFinite(n)||n<min||n>max)throw new ApiError("CONFIG",label+" is outside its allowed range");
|
|
11
|
+
return n;
|
|
12
|
+
}
|
|
13
|
+
function parameters(mode,config) {
|
|
14
|
+
if(!Object.hasOwn(PATHS,mode))throw new ApiError("CONFIG","Unknown operation");
|
|
15
|
+
const params={};
|
|
16
|
+
const id=String(config.locationId||"").trim();
|
|
17
|
+
if(id&&(mode==="weather"||mode==="building")) {
|
|
18
|
+
if(!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(id))throw new ApiError("CONFIG","Saved location must be a UUID");
|
|
19
|
+
params.location_id=id;
|
|
20
|
+
}else {
|
|
21
|
+
params.lat=numeric(config.latitude,-90,90,"Latitude");
|
|
22
|
+
params.lon=numeric(config.longitude,-180,180,"Longitude");
|
|
23
|
+
}
|
|
24
|
+
if(mode==="weather"||mode==="hourly") {
|
|
25
|
+
const hours=numeric(config.hours??24,1,168,"Forecast hours");
|
|
26
|
+
if(!Number.isInteger(hours))throw new ApiError("CONFIG","Forecast hours must be an integer");
|
|
27
|
+
params[mode==="weather"?"forecast_hours":"hours"]=hours;
|
|
28
|
+
}
|
|
29
|
+
if(mode==="daily") {
|
|
30
|
+
const days=numeric(config.days??7,1,7,"Forecast days");
|
|
31
|
+
if(!Number.isInteger(days))throw new ApiError("CONFIG","Forecast days must be an integer");
|
|
32
|
+
params.days=days;
|
|
33
|
+
}
|
|
34
|
+
return params;
|
|
35
|
+
}
|
|
36
|
+
function retrySeconds(value,now=Date.now()) {
|
|
37
|
+
let seconds=value===null?600:Number(value);
|
|
38
|
+
if(!Number.isFinite(seconds))seconds=(Date.parse(value)-now)/1000;
|
|
39
|
+
return Number.isFinite(seconds)?Math.min(86400,Math.max(60,seconds)):600;
|
|
40
|
+
}
|
|
41
|
+
function validate(body,mode,now) {
|
|
42
|
+
if(!body||typeof body!=="object"||!body.data||typeof body.data!=="object"||Array.isArray(body.data))throw new ApiError("SCHEMA","Invalid API response");
|
|
43
|
+
const d=body.data, current=mode==="weather"?d.current:mode==="current"||mode==="building"?d:null;
|
|
44
|
+
if(current) {
|
|
45
|
+
const time=Date.parse(current.observed_at||current.updated_at);
|
|
46
|
+
if(!Number.isFinite(current.temperature_c)||!Number.isFinite(time)||now-time>7200000||time-now>300000)throw new ApiError("STALE","Current weather is incomplete or stale");
|
|
47
|
+
}else if(mode==="weather"||mode==="current"||mode==="building")throw new ApiError("SCHEMA","Current weather is missing");
|
|
48
|
+
if(mode==="weather"&&!Array.isArray(d.forecast?.hours))throw new ApiError("SCHEMA","Forecast is missing");
|
|
49
|
+
if(mode==="hourly"&&!Array.isArray(d.hours))throw new ApiError("SCHEMA","Hourly forecast is missing");
|
|
50
|
+
if(mode==="daily"&&!Array.isArray(d.days))throw new ApiError("SCHEMA","Daily forecast is missing");
|
|
51
|
+
return body;
|
|
52
|
+
}
|
|
53
|
+
class Client {
|
|
54
|
+
constructor(apiKey,{fetchImpl=globalThis.fetch,now=Date.now,cacheSeconds=600}={}) {
|
|
55
|
+
this.key=String(apiKey||"").trim();this.fetch=fetchImpl;this.now=now;
|
|
56
|
+
this.cacheMs=numeric(cacheSeconds,60,86400,"Cache seconds")*1000;
|
|
57
|
+
this.cache=new Map();this.pending=new Map();this.controllers=new Set();this.retryAt=0;this.closed=false;
|
|
58
|
+
}
|
|
59
|
+
close(){this.closed=true;for(const c of this.controllers)c.abort();this.cache.clear();}
|
|
60
|
+
async request(mode,config) {
|
|
61
|
+
if(this.closed)throw new ApiError("CLOSED","Connection is closed");
|
|
62
|
+
if(!this.key)throw new ApiError("AUTH","Enter a MeteoTrust API key in the account node");
|
|
63
|
+
const params=parameters(mode,config),url=BASE+PATHS[mode]+"?"+new URLSearchParams(params),key=mode+JSON.stringify(params);
|
|
64
|
+
const cached=this.cache.get(key);
|
|
65
|
+
if(cached&&cached.expires>this.now()) {
|
|
66
|
+
try {validate(cached.body,mode,this.now());return {...structuredClone(cached),cached:true};}
|
|
67
|
+
catch {this.cache.delete(key);}
|
|
68
|
+
}
|
|
69
|
+
if(this.retryAt>this.now())throw new ApiError("RATE_LIMIT","API request limit reached",Math.ceil((this.retryAt-this.now())/1000));
|
|
70
|
+
if(this.pending.has(key))return structuredClone(await this.pending.get(key));
|
|
71
|
+
const promise=this.load(url,mode).then(body=>{
|
|
72
|
+
const result={body,receivedAt:new Date(this.now()).toISOString(),expires:this.now()+this.cacheMs,cached:false};
|
|
73
|
+
if(!this.closed){if(this.cache.size>=100)this.cache.delete(this.cache.keys().next().value);this.cache.set(key,result);}
|
|
74
|
+
return result;
|
|
75
|
+
});
|
|
76
|
+
this.pending.set(key,promise);
|
|
77
|
+
try{return structuredClone(await promise);}finally{this.pending.delete(key);}
|
|
78
|
+
}
|
|
79
|
+
async load(url,mode) {
|
|
80
|
+
const controller=new AbortController();this.controllers.add(controller);
|
|
81
|
+
const timer=setTimeout(()=>controller.abort(),25000);
|
|
82
|
+
try {
|
|
83
|
+
const r=await this.fetch(url,{headers:{Authorization:"Bearer "+this.key,Accept:"application/json","User-Agent":"MeteoTrustNodeRED/0.1.0"},redirect:"error",signal:controller.signal});
|
|
84
|
+
if(r.status!==200) {
|
|
85
|
+
await r.body?.cancel();
|
|
86
|
+
if(r.status===401)throw new ApiError("AUTH","The MeteoTrust API key is invalid or revoked");
|
|
87
|
+
if(r.status===402||r.status===403)throw new ApiError("ACCESS","Subscription or location access denied");
|
|
88
|
+
if(r.status===429) {const delay=retrySeconds(r.headers.get("retry-after"),this.now());this.retryAt=this.now()+delay*1000;throw new ApiError("RATE_LIMIT","API request limit reached",delay);}
|
|
89
|
+
throw new ApiError("HTTP","MeteoTrust HTTP "+r.status);
|
|
90
|
+
}
|
|
91
|
+
let size=0;const chunks=[];
|
|
92
|
+
for await(const chunk of r.body) {size+=chunk.length;if(size>2000000){controller.abort();throw new ApiError("SIZE","API response is too large");}chunks.push(chunk);}
|
|
93
|
+
let body;try{body=JSON.parse(Buffer.concat(chunks).toString("utf8"));}catch{throw new ApiError("SCHEMA","Invalid API response");}
|
|
94
|
+
return validate(body,mode,this.now());
|
|
95
|
+
}catch(error) {
|
|
96
|
+
if(error instanceof ApiError)throw error;
|
|
97
|
+
throw new ApiError("NETWORK",this.closed?"Connection is closed":"Cannot connect to MeteoTrust");
|
|
98
|
+
}finally{clearTimeout(timer);this.controllers.delete(controller);}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
module.exports={Client,ApiError,parameters,retrySeconds,validate};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40"><circle cx="14" cy="13" r="8" fill="#ffd66b"/><path d="M10 31a7 7 0 1 1 1-14 10 10 0 0 1 19 4 5 5 0 0 1 0 10Z" fill="#fff"/></svg>
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
<script type="text/javascript">
|
|
2
|
+
RED.nodes.registerType('meteotrust-account',{category:'config',defaults:{name:{value:''},cacheSeconds:{value:600,required:true,validate:function(v){return Number(v)>=60&&Number(v)<=86400;}}},credentials:{apiKey:{type:'password'}},label:function(){return this.name||'MeteoTrust';}});
|
|
3
|
+
</script>
|
|
4
|
+
<script type="text/html" data-template-name="meteotrust-account">
|
|
5
|
+
<div class="form-row"><label for="node-config-input-name">Название / Name</label><input id="node-config-input-name"></div>
|
|
6
|
+
<div class="form-row"><label for="node-config-input-apiKey">API-ключ / API key</label><input type="password" id="node-config-input-apiKey" autocomplete="off"></div>
|
|
7
|
+
<div class="form-row"><label for="node-config-input-cacheSeconds">Кэш, секунды / Cache</label><input type="number" id="node-config-input-cacheSeconds" min="60" max="86400"></div>
|
|
8
|
+
<p>Ключ из кабинета meteotrust.ru. Один аккаунт настроек может использоваться несколькими узлами. / Get your key from meteotrust.ru. Share this account node between weather nodes.</p>
|
|
9
|
+
</script>
|
|
10
|
+
<script type="text/html" data-help-name="meteotrust-account"><p>API key is stored using Node-RED credentials and excluded from exported flows. Requests go only to https://meteotrust.ru. Identical requests share an in-flight call and a cache. HTTP 429 pauses new network requests for Retry-After (600 seconds by default). No automatic retry loops.</p></script>
|
|
11
|
+
<script type="text/javascript">
|
|
12
|
+
RED.nodes.registerType('meteotrust-weather',{category:'MeteoTrust',color:'#87cbd1',defaults:{"name": {"value": ""}, "account": {"type": "meteotrust-account", "required": true}, "latitude": {"value": "59.9386"}, "longitude": {"value": "30.3141"}, "locationId": {"value": ""}, "hours": {"value": 168}, "days": {"value": 7}},inputs:1,outputs:1,icon:'meteotrust.svg',label:function(){return this.name||'MeteoTrust weather';}});
|
|
13
|
+
</script>
|
|
14
|
+
<script type="text/html" data-template-name="meteotrust-weather">
|
|
15
|
+
<p>Погода и прогноз / weather</p>
|
|
16
|
+
<div class="form-row"><label for="node-input-name">Название / Name</label><input id="node-input-name"></div>
|
|
17
|
+
<div class="form-row"><label for="node-input-account">Аккаунт / Account</label><input id="node-input-account"></div>
|
|
18
|
+
<div class="form-row"><label for="node-input-latitude">Широта / Latitude</label><input type="number" step="any" min="-90" max="90" id="node-input-latitude"></div>
|
|
19
|
+
<div class="form-row"><label for="node-input-longitude">Долгота / Longitude</label><input type="number" step="any" min="-180" max="180" id="node-input-longitude"></div>
|
|
20
|
+
<div class="form-row"><label for="node-input-locationId">ID локации / Location ID</label><input id="node-input-locationId" placeholder="Необязательно / Optional UUID"></div><p>ID сохранённой локации имеет приоритет над координатами. / A saved location ID overrides coordinates.</p>
|
|
21
|
+
<div class="form-row"><label for="node-input-hours">Часов / Hours</label><input type="number" id="node-input-hours" min="1" max="168"></div>
|
|
22
|
+
</script><script type="text/html" data-help-name="meteotrust-weather">
|
|
23
|
+
<p>Any input message triggers the configured request. Output: <code>msg.payload</code> = API data; <code>msg.meteotrust</code> = operation, cached, received_at and API meta. Other message fields are preserved. Coordinates and account must be configured; messages cannot override credentials or URL.</p>
|
|
24
|
+
<p>Любое входящее сообщение запускает запрос. Результат — в msg.payload. Для ошибок используйте Catch. По умолчанию одинаковый запрос берётся из локального кэша 10 минут. Получение из кэша не означает новое наблюдение: проверяйте observed_at/updated_at, valid_at и сроки решений. При сбое старые данные не выдаются как успешный ответ.</p>
|
|
25
|
+
<p>One successful network response consumes one API request; a local cache hit does not. Combine weather and forecast with the weather node to avoid separate current/hourly/daily calls. Decisions are recommendations, not commands to equipment.</p>
|
|
26
|
+
</script>
|
|
27
|
+
<script type="text/javascript">
|
|
28
|
+
RED.nodes.registerType('meteotrust-current',{category:'MeteoTrust',color:'#87cbd1',defaults:{"name": {"value": ""}, "account": {"type": "meteotrust-account", "required": true}, "latitude": {"value": "59.9386"}, "longitude": {"value": "30.3141"}, "locationId": {"value": ""}, "hours": {"value": 24}, "days": {"value": 7}},inputs:1,outputs:1,icon:'meteotrust.svg',label:function(){return this.name||'MeteoTrust current';}});
|
|
29
|
+
</script>
|
|
30
|
+
<script type="text/html" data-template-name="meteotrust-current">
|
|
31
|
+
<p>Текущая погода / current</p>
|
|
32
|
+
<div class="form-row"><label for="node-input-name">Название / Name</label><input id="node-input-name"></div>
|
|
33
|
+
<div class="form-row"><label for="node-input-account">Аккаунт / Account</label><input id="node-input-account"></div>
|
|
34
|
+
<div class="form-row"><label for="node-input-latitude">Широта / Latitude</label><input type="number" step="any" min="-90" max="90" id="node-input-latitude"></div>
|
|
35
|
+
<div class="form-row"><label for="node-input-longitude">Долгота / Longitude</label><input type="number" step="any" min="-180" max="180" id="node-input-longitude"></div>
|
|
36
|
+
</script><script type="text/html" data-help-name="meteotrust-current">
|
|
37
|
+
<p>Any input message triggers the configured request. Output: <code>msg.payload</code> = API data; <code>msg.meteotrust</code> = operation, cached, received_at and API meta. Other message fields are preserved. Coordinates and account must be configured; messages cannot override credentials or URL.</p>
|
|
38
|
+
<p>Любое входящее сообщение запускает запрос. Результат — в msg.payload. Для ошибок используйте Catch. По умолчанию одинаковый запрос берётся из локального кэша 10 минут. Получение из кэша не означает новое наблюдение: проверяйте observed_at/updated_at, valid_at и сроки решений. При сбое старые данные не выдаются как успешный ответ.</p>
|
|
39
|
+
<p>One successful network response consumes one API request; a local cache hit does not. Combine weather and forecast with the weather node to avoid separate current/hourly/daily calls. Decisions are recommendations, not commands to equipment.</p>
|
|
40
|
+
</script>
|
|
41
|
+
<script type="text/javascript">
|
|
42
|
+
RED.nodes.registerType('meteotrust-hourly',{category:'MeteoTrust',color:'#87cbd1',defaults:{"name": {"value": ""}, "account": {"type": "meteotrust-account", "required": true}, "latitude": {"value": "59.9386"}, "longitude": {"value": "30.3141"}, "locationId": {"value": ""}, "hours": {"value": 24}, "days": {"value": 7}},inputs:1,outputs:1,icon:'meteotrust.svg',label:function(){return this.name||'MeteoTrust hourly';}});
|
|
43
|
+
</script>
|
|
44
|
+
<script type="text/html" data-template-name="meteotrust-hourly">
|
|
45
|
+
<p>Почасовой прогноз / hourly</p>
|
|
46
|
+
<div class="form-row"><label for="node-input-name">Название / Name</label><input id="node-input-name"></div>
|
|
47
|
+
<div class="form-row"><label for="node-input-account">Аккаунт / Account</label><input id="node-input-account"></div>
|
|
48
|
+
<div class="form-row"><label for="node-input-latitude">Широта / Latitude</label><input type="number" step="any" min="-90" max="90" id="node-input-latitude"></div>
|
|
49
|
+
<div class="form-row"><label for="node-input-longitude">Долгота / Longitude</label><input type="number" step="any" min="-180" max="180" id="node-input-longitude"></div>
|
|
50
|
+
<div class="form-row"><label for="node-input-hours">Часов / Hours</label><input type="number" id="node-input-hours" min="1" max="168"></div>
|
|
51
|
+
</script><script type="text/html" data-help-name="meteotrust-hourly">
|
|
52
|
+
<p>Any input message triggers the configured request. Output: <code>msg.payload</code> = API data; <code>msg.meteotrust</code> = operation, cached, received_at and API meta. Other message fields are preserved. Coordinates and account must be configured; messages cannot override credentials or URL.</p>
|
|
53
|
+
<p>Любое входящее сообщение запускает запрос. Результат — в msg.payload. Для ошибок используйте Catch. По умолчанию одинаковый запрос берётся из локального кэша 10 минут. Получение из кэша не означает новое наблюдение: проверяйте observed_at/updated_at, valid_at и сроки решений. При сбое старые данные не выдаются как успешный ответ.</p>
|
|
54
|
+
<p>One successful network response consumes one API request; a local cache hit does not. Combine weather and forecast with the weather node to avoid separate current/hourly/daily calls. Decisions are recommendations, not commands to equipment.</p>
|
|
55
|
+
</script>
|
|
56
|
+
<script type="text/javascript">
|
|
57
|
+
RED.nodes.registerType('meteotrust-daily',{category:'MeteoTrust',color:'#87cbd1',defaults:{"name": {"value": ""}, "account": {"type": "meteotrust-account", "required": true}, "latitude": {"value": "59.9386"}, "longitude": {"value": "30.3141"}, "locationId": {"value": ""}, "hours": {"value": 24}, "days": {"value": 7}},inputs:1,outputs:1,icon:'meteotrust.svg',label:function(){return this.name||'MeteoTrust daily';}});
|
|
58
|
+
</script>
|
|
59
|
+
<script type="text/html" data-template-name="meteotrust-daily">
|
|
60
|
+
<p>Прогноз по дням / daily</p>
|
|
61
|
+
<div class="form-row"><label for="node-input-name">Название / Name</label><input id="node-input-name"></div>
|
|
62
|
+
<div class="form-row"><label for="node-input-account">Аккаунт / Account</label><input id="node-input-account"></div>
|
|
63
|
+
<div class="form-row"><label for="node-input-latitude">Широта / Latitude</label><input type="number" step="any" min="-90" max="90" id="node-input-latitude"></div>
|
|
64
|
+
<div class="form-row"><label for="node-input-longitude">Долгота / Longitude</label><input type="number" step="any" min="-180" max="180" id="node-input-longitude"></div>
|
|
65
|
+
<div class="form-row"><label for="node-input-days">Дней / Days</label><input type="number" id="node-input-days" min="1" max="7"></div>
|
|
66
|
+
</script><script type="text/html" data-help-name="meteotrust-daily">
|
|
67
|
+
<p>Any input message triggers the configured request. Output: <code>msg.payload</code> = API data; <code>msg.meteotrust</code> = operation, cached, received_at and API meta. Other message fields are preserved. Coordinates and account must be configured; messages cannot override credentials or URL.</p>
|
|
68
|
+
<p>Любое входящее сообщение запускает запрос. Результат — в msg.payload. Для ошибок используйте Catch. По умолчанию одинаковый запрос берётся из локального кэша 10 минут. Получение из кэша не означает новое наблюдение: проверяйте observed_at/updated_at, valid_at и сроки решений. При сбое старые данные не выдаются как успешный ответ.</p>
|
|
69
|
+
<p>One successful network response consumes one API request; a local cache hit does not. Combine weather and forecast with the weather node to avoid separate current/hourly/daily calls. Decisions are recommendations, not commands to equipment.</p>
|
|
70
|
+
</script>
|
|
71
|
+
<script type="text/javascript">
|
|
72
|
+
RED.nodes.registerType('meteotrust-building',{category:'MeteoTrust',color:'#87cbd1',defaults:{"name": {"value": ""}, "account": {"type": "meteotrust-account", "required": true}, "latitude": {"value": "59.9386"}, "longitude": {"value": "30.3141"}, "locationId": {"value": ""}, "hours": {"value": 24}, "days": {"value": 7}},inputs:1,outputs:1,icon:'meteotrust.svg',label:function(){return this.name||'MeteoTrust building';}});
|
|
73
|
+
</script>
|
|
74
|
+
<script type="text/html" data-template-name="meteotrust-building">
|
|
75
|
+
<p>Умное здание / building</p>
|
|
76
|
+
<div class="form-row"><label for="node-input-name">Название / Name</label><input id="node-input-name"></div>
|
|
77
|
+
<div class="form-row"><label for="node-input-account">Аккаунт / Account</label><input id="node-input-account"></div>
|
|
78
|
+
<div class="form-row"><label for="node-input-latitude">Широта / Latitude</label><input type="number" step="any" min="-90" max="90" id="node-input-latitude"></div>
|
|
79
|
+
<div class="form-row"><label for="node-input-longitude">Долгота / Longitude</label><input type="number" step="any" min="-180" max="180" id="node-input-longitude"></div>
|
|
80
|
+
<div class="form-row"><label for="node-input-locationId">ID локации / Location ID</label><input id="node-input-locationId" placeholder="Необязательно / Optional UUID"></div><p>ID сохранённой локации имеет приоритет над координатами. / A saved location ID overrides coordinates.</p>
|
|
81
|
+
</script><script type="text/html" data-help-name="meteotrust-building">
|
|
82
|
+
<p>Any input message triggers the configured request. Output: <code>msg.payload</code> = API data; <code>msg.meteotrust</code> = operation, cached, received_at and API meta. Other message fields are preserved. Coordinates and account must be configured; messages cannot override credentials or URL.</p>
|
|
83
|
+
<p>Любое входящее сообщение запускает запрос. Результат — в msg.payload. Для ошибок используйте Catch. По умолчанию одинаковый запрос берётся из локального кэша 10 минут. Получение из кэша не означает новое наблюдение: проверяйте observed_at/updated_at, valid_at и сроки решений. При сбое старые данные не выдаются как успешный ответ.</p>
|
|
84
|
+
<p>One successful network response consumes one API request; a local cache hit does not. Combine weather and forecast with the weather node to avoid separate current/hourly/daily calls. Decisions are recommendations, not commands to equipment.</p>
|
|
85
|
+
</script>
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
const {Client}=require("../lib/client");
|
|
3
|
+
module.exports=function(RED) {
|
|
4
|
+
function Account(config) {
|
|
5
|
+
RED.nodes.createNode(this,config);
|
|
6
|
+
try{this.client=new Client(this.credentials?.apiKey,{cacheSeconds:config.cacheSeconds||600});}
|
|
7
|
+
catch(error){this.error(error.message);}
|
|
8
|
+
this.on("close",()=>this.client?.close());
|
|
9
|
+
}
|
|
10
|
+
RED.nodes.registerType("meteotrust-account",Account,{credentials:{apiKey:{type:"password"}}});
|
|
11
|
+
for(const mode of ["weather","current","hourly","daily","building"]) {
|
|
12
|
+
function WeatherNode(config) {
|
|
13
|
+
RED.nodes.createNode(this,config);
|
|
14
|
+
const account=RED.nodes.getNode(config.account);let closed=false;
|
|
15
|
+
this.on("close",()=>{closed=true;});
|
|
16
|
+
this.on("input",async(msg,send,done)=>{
|
|
17
|
+
send=send||this.send.bind(this);done=done||((err)=>{if(err)this.error(err,msg);});
|
|
18
|
+
if(!account?.client){this.status({fill:"red",shape:"ring",text:"configure account"});done(new Error("Configure the MeteoTrust account node"));return;}
|
|
19
|
+
this.status({fill:"blue",shape:"dot",text:"requesting"});
|
|
20
|
+
try {
|
|
21
|
+
const r=await account.client.request(mode,config);
|
|
22
|
+
if(!closed) {
|
|
23
|
+
msg.payload=r.body.data;
|
|
24
|
+
msg.meteotrust={operation:mode,cached:r.cached,received_at:r.receivedAt,meta:r.body.meta||{}};
|
|
25
|
+
send(msg);this.status({fill:"green",shape:r.cached?"ring":"dot",text:r.cached?"cache":"updated"});
|
|
26
|
+
}
|
|
27
|
+
done();
|
|
28
|
+
}catch(error) {
|
|
29
|
+
if(closed){done();return;}
|
|
30
|
+
this.status({fill:"red",shape:"ring",text:error.code||"error"});
|
|
31
|
+
// The client exposes only sanitized errors, never raw request/response objects.
|
|
32
|
+
done(error);
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
RED.nodes.registerType("meteotrust-"+mode,WeatherNode);
|
|
37
|
+
}
|
|
38
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@meteotrust/node-red",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "MeteoTrust weather, forecasts and smart-building API nodes for Node-RED.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "MeteoTrust",
|
|
7
|
+
"homepage": "https://meteotrust.ru/integrations-mqtt.html",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/darkssside/node-red-meteotrust.git"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/darkssside/node-red-meteotrust/issues"
|
|
14
|
+
},
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=22"
|
|
17
|
+
},
|
|
18
|
+
"keywords": [
|
|
19
|
+
"node-red",
|
|
20
|
+
"meteotrust",
|
|
21
|
+
"weather",
|
|
22
|
+
"forecast",
|
|
23
|
+
"smart-home"
|
|
24
|
+
],
|
|
25
|
+
"node-red": {
|
|
26
|
+
"version": ">=4.1.0",
|
|
27
|
+
"nodes": {
|
|
28
|
+
"meteotrust": "nodes/meteotrust.js"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"nodes/",
|
|
33
|
+
"lib/",
|
|
34
|
+
"examples/",
|
|
35
|
+
"README.md",
|
|
36
|
+
"README.en.md",
|
|
37
|
+
"LICENSE",
|
|
38
|
+
"CHANGELOG.md"
|
|
39
|
+
],
|
|
40
|
+
"scripts": {
|
|
41
|
+
"test": "node --test test/*.test.js",
|
|
42
|
+
"prepublishOnly": "npm test"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"node-red": "5.0.10",
|
|
46
|
+
"node-red-node-test-helper": "0.3.6"
|
|
47
|
+
},
|
|
48
|
+
"publishConfig": {
|
|
49
|
+
"access": "public"
|
|
50
|
+
}
|
|
51
|
+
}
|