@meteotrust/node-red 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,219 @@
1
+ [
2
+ {
3
+ "id": "tablet-demo",
4
+ "type": "tab",
5
+ "label": "MeteoTrust — управление планшетом"
6
+ },
7
+ {
8
+ "id": "tablet-config",
9
+ "type": "meteotrust-tablet",
10
+ "name": "Планшет в прихожей",
11
+ "transport": "mqtt",
12
+ "broker": "",
13
+ "brokerPort": 1883,
14
+ "tls": false,
15
+ "baseTopic": "meteotrust/tablet/hall",
16
+ "host": "",
17
+ "port": 8765
18
+ },
19
+ {
20
+ "id": "trigger-0",
21
+ "type": "inject",
22
+ "z": "tablet-demo",
23
+ "name": "Открыть MeteoTrust",
24
+ "props": [
25
+ {
26
+ "p": "payload"
27
+ }
28
+ ],
29
+ "payload": "",
30
+ "payloadType": "str",
31
+ "once": false,
32
+ "x": 170,
33
+ "y": 80,
34
+ "wires": [
35
+ [
36
+ "action-0"
37
+ ]
38
+ ]
39
+ },
40
+ {
41
+ "id": "action-0",
42
+ "type": "meteotrust-open-meteotrust",
43
+ "z": "tablet-demo",
44
+ "tablet": "tablet-config",
45
+ "x": 430,
46
+ "y": 80,
47
+ "wires": [
48
+ [
49
+ "command-debug"
50
+ ]
51
+ ]
52
+ },
53
+ {
54
+ "id": "trigger-1",
55
+ "type": "inject",
56
+ "z": "tablet-demo",
57
+ "name": "Открыть Loxone",
58
+ "props": [
59
+ {
60
+ "p": "payload"
61
+ }
62
+ ],
63
+ "payload": "",
64
+ "payloadType": "str",
65
+ "once": false,
66
+ "x": 170,
67
+ "y": 150,
68
+ "wires": [
69
+ [
70
+ "action-1"
71
+ ]
72
+ ]
73
+ },
74
+ {
75
+ "id": "action-1",
76
+ "type": "meteotrust-open-loxone",
77
+ "z": "tablet-demo",
78
+ "tablet": "tablet-config",
79
+ "x": 430,
80
+ "y": 150,
81
+ "wires": [
82
+ [
83
+ "command-debug"
84
+ ]
85
+ ]
86
+ },
87
+ {
88
+ "id": "trigger-2",
89
+ "type": "inject",
90
+ "z": "tablet-demo",
91
+ "name": "Включить экран",
92
+ "props": [
93
+ {
94
+ "p": "payload"
95
+ }
96
+ ],
97
+ "payload": "",
98
+ "payloadType": "str",
99
+ "once": false,
100
+ "x": 170,
101
+ "y": 220,
102
+ "wires": [
103
+ [
104
+ "action-2"
105
+ ]
106
+ ]
107
+ },
108
+ {
109
+ "id": "action-2",
110
+ "type": "meteotrust-screen-on",
111
+ "z": "tablet-demo",
112
+ "tablet": "tablet-config",
113
+ "x": 430,
114
+ "y": 220,
115
+ "wires": [
116
+ [
117
+ "command-debug"
118
+ ]
119
+ ]
120
+ },
121
+ {
122
+ "id": "trigger-3",
123
+ "type": "inject",
124
+ "z": "tablet-demo",
125
+ "name": "Выключить экран",
126
+ "props": [
127
+ {
128
+ "p": "payload"
129
+ }
130
+ ],
131
+ "payload": "",
132
+ "payloadType": "str",
133
+ "once": false,
134
+ "x": 170,
135
+ "y": 290,
136
+ "wires": [
137
+ [
138
+ "action-3"
139
+ ]
140
+ ]
141
+ },
142
+ {
143
+ "id": "action-3",
144
+ "type": "meteotrust-screen-off",
145
+ "z": "tablet-demo",
146
+ "tablet": "tablet-config",
147
+ "x": 430,
148
+ "y": 290,
149
+ "wires": [
150
+ [
151
+ "command-debug"
152
+ ]
153
+ ]
154
+ },
155
+ {
156
+ "id": "command-debug",
157
+ "type": "debug",
158
+ "z": "tablet-demo",
159
+ "name": "Ответ команды",
160
+ "active": true,
161
+ "complete": "true",
162
+ "x": 710,
163
+ "y": 180,
164
+ "wires": []
165
+ },
166
+ {
167
+ "id": "tablet-state",
168
+ "type": "meteotrust-tablet-state",
169
+ "z": "tablet-demo",
170
+ "tablet": "tablet-config",
171
+ "x": 210,
172
+ "y": 400,
173
+ "wires": [
174
+ [
175
+ "state-debug"
176
+ ]
177
+ ]
178
+ },
179
+ {
180
+ "id": "state-debug",
181
+ "type": "debug",
182
+ "z": "tablet-demo",
183
+ "name": "Состояние и результат",
184
+ "active": true,
185
+ "complete": "true",
186
+ "x": 530,
187
+ "y": 400,
188
+ "wires": []
189
+ },
190
+ {
191
+ "id": "tablet-catch",
192
+ "type": "catch",
193
+ "z": "tablet-demo",
194
+ "scope": [
195
+ "action-0",
196
+ "action-1",
197
+ "action-2",
198
+ "action-3",
199
+ "tablet-state"
200
+ ],
201
+ "uncaught": false,
202
+ "x": 200,
203
+ "y": 470,
204
+ "wires": [
205
+ [
206
+ "state-debug"
207
+ ]
208
+ ]
209
+ },
210
+ {
211
+ "id": "tablet-note",
212
+ "type": "comment",
213
+ "z": "tablet-demo",
214
+ "name": "Укажите брокер или HTTP в настройках планшета. Входные Inject не запускаются при Deploy.",
215
+ "x": 400,
216
+ "y": 540,
217
+ "wires": []
218
+ }
219
+ ]
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};
package/lib/tablet.js ADDED
@@ -0,0 +1,151 @@
1
+ "use strict";
2
+ const {EventEmitter}=require("node:events");
3
+ const {randomUUID}=require("node:crypto");
4
+ const http=require("node:http");
5
+ const mqtt=require("mqtt");
6
+ const PATHS=Object.freeze({meteotrust:"/api/v1/apps/meteotrust",loxone:"/api/v1/apps/loxone",screen_on:"/api/v1/screen/on",screen_off:"/api/v1/screen/off",status:"/api/v1/status"});
7
+ const BOOLS=["screen_on","keyguard_locked","meteotrust_visible","overlay_allowed","screen_off_allowed","loxone_installed","battery_optimization_exempt"];
8
+ const CODES=new Set(["accepted","admin_required","overlay_required","screen_off","unlock_required","loxone_missing","permission_denied","command_failed","disabled","busy","ip_denied","unauthorized","rate_limited"]);
9
+ const error=(code)=>Object.assign(new Error("MeteoTrust tablet: "+code),{code});
10
+ function privateIp(host){
11
+ if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(host))return false;
12
+ const a=host.split('.').map(Number);
13
+ return a.every((n,i)=>n<=255&&String(n)===host.split('.')[i])&&(a[0]===10||(a[0]===172&&a[1]>=16&&a[1]<=31)||(a[0]===192&&a[1]===168));
14
+ }
15
+ function validate(config,credentials={}){
16
+ const c={...config,...credentials};
17
+ if(c.transport==='http'){
18
+ c.host=String(c.host||'').trim();c.port=Number(c.port||8765);
19
+ if(!privateIp(c.host)||!Number.isInteger(c.port)||c.port<1024||c.port>65535)throw error('invalid_tablet_address');
20
+ c.controlKey=String(c.controlKey||'').trim();
21
+ if(!/^[a-fA-F0-9]{64}$/.test(c.controlKey))throw error('invalid_control_key');
22
+ }else if(c.transport==='mqtt'){
23
+ c.broker=String(c.broker||'').trim();c.tls=c.tls===true;
24
+ c.brokerPort=Number(c.brokerPort||(c.tls?8883:1883));
25
+ c.baseTopic=String(c.baseTopic||'').trim().replace(/\/+$/,'');
26
+ if(!/^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/.test(c.broker)||c.broker.length>253||!Number.isInteger(c.brokerPort)||c.brokerPort<1||c.brokerPort>65535)throw error('invalid_broker');
27
+ if(!/^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/.test(c.baseTopic)||c.baseTopic.length>200)throw error('invalid_topic');
28
+ }else throw error('invalid_transport');
29
+ return c;
30
+ }
31
+ function cleanState(value){
32
+ if(!value||value.ok!==true||!BOOLS.slice(0,3).every(k=>typeof value[k]==='boolean'))throw error('invalid_state');
33
+ const result={};for(const k of BOOLS)if(typeof value[k]==='boolean')result[k]=value[k];
34
+ result.last_command=Object.hasOwn(PATHS,value.last_command)?value.last_command:'';
35
+ result.last_result=CODES.has(value.last_result)?value.last_result:'';
36
+ return result;
37
+ }
38
+ class Tablet extends EventEmitter{
39
+ constructor(config,credentials={},deps={}){
40
+ super();this.config=validate(config,credentials);this.closed=false;this.online=false;this.seen=0;this.state=null;
41
+ this.clock=deps.clock||(()=>performance.now());this.request=deps.request||http.request;
42
+ this.connect=deps.connect||mqtt.connect;this.pending=new Set();this.polling=false;
43
+ }
44
+ get ready(){return !this.closed&&this.online&&this.seen>0&&this.clock()-this.seen<90000&&(!this.mqtt||this.mqtt.connected);}
45
+ start(){
46
+ if(this.timer||this.closed)return;
47
+ this.timer=setInterval(()=>{if(this.config.transport==='http')void this.refresh();else this.emit('availability',this.ready);},this.config.transport==='http'?30000:10000);
48
+ this.timer.unref?.();
49
+ if(this.config.transport==='http'){void this.refresh();return;}
50
+ const c=this.config;
51
+ this.mqtt=this.connect({protocol:c.tls?'mqtts':'mqtt',host:c.broker,port:c.brokerPort,username:c.username||undefined,password:c.password||undefined,
52
+ clientId:'meteotrust-nr-'+randomUUID(),protocolVersion:4,clean:true,reconnectPeriod:3000,connectTimeout:8000,
53
+ queueQoSZero:false,rejectUnauthorized:true,resubscribe:false});
54
+ const offline=()=>{this.online=false;this.seen=0;this.emit('availability',false);};
55
+ this.mqtt.on('connect',()=>{
56
+ offline();
57
+ this.mqtt.subscribe(['availability','state','result'].map(s=>c.baseTopic+'/'+s),{qos:0},(err,granted)=>{
58
+ if(err||granted?.some(g=>g.qos===128)){offline();this.emit('fault',error('subscription_denied'));}
59
+ });
60
+ });
61
+ this.mqtt.on('close',offline);this.mqtt.on('offline',offline);
62
+ this.mqtt.on('error',()=>{offline();this.emit('fault',error('mqtt_connection_failed'));});
63
+ this.mqtt.on('message',(topic,buffer,packet)=>this.receive(topic,buffer,packet));
64
+ }
65
+ receive(topic,buffer,packet={}){
66
+ if(this.closed||buffer.length>8192)return;
67
+ const base=this.config.baseTopic;
68
+ if(topic===base+'/availability'){
69
+ this.online=buffer.toString()==='online';if(!this.online)this.seen=0;
70
+ this.emit('availability',this.ready);return;
71
+ }
72
+ // Retained state/result cannot establish liveness or confirm a new command.
73
+ if(packet.retain)return;
74
+ try{
75
+ const value=JSON.parse(buffer.toString('utf8'));
76
+ if(topic===base+'/state')this.update(cleanState(value));
77
+ else if(topic===base+'/result'){
78
+ if(value.ok===true&&value.status==='accepted'&&Object.hasOwn(PATHS,value.command)){
79
+ this.emit('result',{ok:true,status:'accepted',command:value.command});
80
+ }else if(value.ok===false)this.emit('result',{ok:false,error:CODES.has(value.error)?value.error:'request_rejected'});
81
+ }
82
+ }catch{ /* malformed/unrelated broker messages never affect state */ }
83
+ }
84
+ update(state){
85
+ if(this.closed)return;
86
+ this.state=state;this.seen=this.clock();if(this.config.transport==='http')this.online=true;
87
+ this.emit('state',structuredClone(state));this.emit('availability',this.ready);
88
+ }
89
+ async refresh(){
90
+ if(this.closed||this.polling)return;
91
+ this.polling=true;
92
+ try{this.update(await this.http('status'));}
93
+ catch(e){if(!this.closed){this.online=false;this.emit('availability',false);this.emit('fault',e);}}
94
+ finally{this.polling=false;}
95
+ }
96
+ async command(command){
97
+ if(!Object.hasOwn(PATHS,command))throw error('invalid_command');
98
+ if(this.closed)throw error('closed');
99
+ if(this.config.transport==='http'){
100
+ const reply=await this.http(command);
101
+ if(command==='status')this.update(reply);
102
+ return reply;
103
+ }
104
+ if(!this.ready)throw error('tablet_offline');
105
+ // QoS 0 + queueQoSZero:false: do not replay delayed controls after reconnect.
106
+ return new Promise((resolve,reject)=>{
107
+ const timer=setTimeout(()=>reject(error('publish_timeout')),5000);
108
+ this.mqtt.publish(this.config.baseTopic+'/command',command,{qos:0,retain:false},err=>{
109
+ clearTimeout(timer);
110
+ if(err||this.closed)reject(error('publish_failed'));
111
+ else resolve({command,status:'sent',confirmed:false});
112
+ });
113
+ });
114
+ }
115
+ http(command){
116
+ const c=this.config;
117
+ return new Promise((resolve,reject)=>{
118
+ let req,finished=false;
119
+ const finish=(err,value)=>{
120
+ if(finished)return;finished=true;clearTimeout(timer);this.pending.delete(req);
121
+ if(err){req?.destroy();reject(err);}else resolve(value);
122
+ };
123
+ const timer=setTimeout(()=>finish(error('request_timeout')),5000);
124
+ try{
125
+ req=this.request({hostname:c.host,port:c.port,path:PATHS[command],method:command==='status'?'GET':'POST',
126
+ headers:{'X-MeteoTrust-Key':c.controlKey},agent:false},res=>{
127
+ const chunks=[];let size=0;
128
+ res.on('data',chunk=>{size+=chunk.length;if(size>8192)finish(error('response_too_large'));else chunks.push(chunk);});
129
+ res.on('error',()=>finish(error('connection_failed')));
130
+ res.on('end',()=>{
131
+ if(finished)return;
132
+ try{
133
+ const v=JSON.parse(Buffer.concat(chunks).toString('utf8'));
134
+ if(res.statusCode!==(command==='status'?200:202)||v.ok!==true)throw error(CODES.has(v.error)?v.error:'request_rejected');
135
+ if(command==='status')finish(null,cleanState(v));
136
+ else if(v.status==='accepted'&&v.command===command)finish(null,{command,status:'accepted',confirmed:false});
137
+ else throw error('invalid_response');
138
+ }catch(e){finish(e.code&&CODES.has(e.code)?e:error('invalid_response'));}
139
+ });
140
+ });
141
+ this.pending.add(req);req.on('error',()=>finish(error('connection_failed')));req.end();
142
+ }catch{finish(error('connection_failed'));}
143
+ });
144
+ }
145
+ close(){
146
+ this.closed=true;clearInterval(this.timer);this.timer=null;
147
+ for(const req of this.pending)req.destroy();this.pending.clear();
148
+ this.mqtt?.end(true);this.removeAllListeners();
149
+ }
150
+ }
151
+ module.exports={Tablet,validate,cleanState,PATHS};
@@ -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
+ };