yoda-sailing 0.1.0 → 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.
package/package.json CHANGED
@@ -1,9 +1 @@
1
- {
2
- "name": "yoda-sailing",
3
- "version": "0.1.0",
4
- "description": "Read-only Signal K webapp for viewing Ruuvi acceleration axes.",
5
- "keywords": ["signalk-webapp", "signalk-category-instruments", "ruuvi"],
6
- "files": ["public"],
7
- "signalk": { "displayName": "YODA Dashboard" },
8
- "license": "UNLICENSED"
9
- }
1
+ {"name":"yoda-sailing","version":"0.2.0","description":"Signal K webapp for Ruuvi trends and read-only Venus OS relay status.","keywords":["signalk-webapp","signalk-category-instruments","ruuvi"],"files":["public"],"signalk":{"displayName":"YODA Dashboard"},"license":"UNLICENSED"}
@@ -1,76 +1,266 @@
1
- const axes = ['X', 'Y', 'Z'];
2
- const readings = document.querySelector('#sensors');
3
- const status = document.querySelector('#status');
4
- const formatter = new Intl.NumberFormat('fr-FR', { maximumFractionDigits: 3 });
5
1
 
6
- function findSensors(data) {
7
- const sensors = new Map();
2
+ const sensors = [
3
+ {name:'Cockpit', color:'#62ddd0'},
4
+ {name:'Inside', color:'#ffbd72'},
5
+ {name:'Motor', color:'#bfaaff'}
6
+ ];
7
+ const groups = {
8
+ 'Ambiance': [
9
+ ['temp','Température','°C',null,null],
10
+ ['humidity','Humidité relative','%',null,null],
11
+ ['pressure','Pression','hPa',null,null]
12
+ ],
13
+ 'Accélérations': [
14
+ ['x','Accélération X','mg',null,null],
15
+ ['y','Accélération Y','mg',null,null],
16
+ ['z','Accélération Z','mg',null,null]
17
+ ],
18
+ 'Diagnostic': [
19
+ ['battery','Tension de pile','V',null,null],
20
+ ['rssi','Signal radio','dBm',null,null],
21
+ ['seq','Compteur de mesures','',null,null,'step'],
22
+ ['motion','Compteur de mouvement','',null,null,'step'],
23
+ ['reachable','Disponibilité','',null,null,'step']
24
+ ]
25
+ };
26
+ const sectionIds = ['ambiance', 'accelerations', 'diagnostic'];
27
+ const selected = new Set([0,1,2]);
28
+ const charts = document.querySelector('#charts');
29
+ const toggle = document.querySelector('fieldset');
8
30
 
9
- function walk(value, path) {
10
- if (!value || typeof value !== 'object') return;
11
- const match = /^(.*?)(?:\.)?Acc([XYZ])axis$/i.exec(path);
12
- if (match && /^ruuvi/i.test(match[1]) && Object.hasOwn(value, 'value')) {
13
- const [, sensor, axis] = match;
14
- const samples = sensors.get(sensor) ?? {};
15
- samples[axis.toUpperCase()] = value;
16
- sensors.set(sensor, samples);
17
- return;
18
- }
19
- for (const [key, child] of Object.entries(value)) {
20
- if (key !== 'meta' && key !== 'values') walk(child, path ? path + '.' + key : key);
31
+ const hour = 3600000;
32
+ const fields = {
33
+ temp: 'Temperature', humidity: 'Humidity', pressure: 'Pressure',
34
+ x: 'AccXaxis', y: 'AccYaxis', z: 'AccZaxis', battery: 'BatteryVoltage',
35
+ rssi: 'SignalStrengthdB', seq: 'SeqCounter', motion: 'MvmCounter'
36
+ };
37
+ const metrics = Object.values(groups).flat();
38
+ const history = sensors.map(() => Object.fromEntries(metrics.map(([key]) => [key, []])));
39
+ const sequences = sensors.map(() => undefined);
40
+ const painters = [];
41
+ const clock = time => new Date(time).toLocaleTimeString('fr-FR', {hour:'2-digit', minute:'2-digit', second:'2-digit'});
42
+
43
+ function at(data, path) {
44
+ return data?.[path] ?? path.split('.').reduce((value, part) => value?.[part], data);
45
+ }
46
+
47
+ function sample(data, key, sensor) {
48
+ const name = 'Ruuvi' + sensor.name;
49
+ if (key === 'reachable') {
50
+ const reachable = at(data,'sensors');
51
+ const id = Object.keys(reachable ?? {}).find(id => id.startsWith(name));
52
+ return id ? reachable[id]?.reachable : undefined;
53
+ }
54
+ return at(data,name + '.' + fields[key])
55
+ ?? (key === 'z' && sensor.name === 'Inside' ? at(data,'RuuviInsideAccZaxis') : undefined);
56
+ }
57
+
58
+ function numeric(key, value) {
59
+ if (key === 'reachable') return typeof value === 'boolean' ? Number(value) : null;
60
+ if (!Number.isFinite(value)) return null;
61
+ if (key === 'temp') return value - 273.15;
62
+ if (key === 'humidity') return value * 100;
63
+ if (key === 'pressure') return value >= 50000 && value <= 115534 ? value / 100 : null;
64
+ if (key === 'seq' && value === 65535 || key === 'motion' && value === 255) return null;
65
+ return value;
66
+ }
67
+
68
+ function record(data, now) {
69
+ sensors.forEach((sensor,i) => {
70
+ const seq = numeric('seq',sample(data,'seq',sensor)?.value);
71
+ const repeated = seq !== null && seq === sequences[i];
72
+ if (seq !== null) sequences[i] = seq;
73
+ for (const [key] of metrics) {
74
+ const points = history[i][key];
75
+ while (points.length && points[0].time < now - hour) points.shift();
76
+ if (key !== 'reachable' && repeated) continue;
77
+ const reading = sample(data,key,sensor);
78
+ const time = Date.parse(reading?.timestamp);
79
+ if (!Number.isFinite(time) || time < now - hour || time > now + 60000) continue;
80
+ if (points.length && time <= points.at(-1).time) continue;
81
+ points.push({time,value:numeric(key,reading.value)});
21
82
  }
83
+ });
84
+ }
85
+
86
+ function draw(canvas, output, metric, allPoints, cursor) {
87
+ const [key,title,unit,,,mode] = metric;
88
+ const {width,height} = canvas.getBoundingClientRect();
89
+ if (width < 125) return;
90
+ const end = Date.now();
91
+ const start = end - hour;
92
+ const series = allPoints.map(points => points.filter(point => point.time >= start && point.time <= end));
93
+ const scale = window.devicePixelRatio || 1;
94
+ canvas.width = width * scale;
95
+ canvas.height = height * scale;
96
+ const ctx = canvas.getContext('2d');
97
+ ctx.scale(scale,scale);
98
+ const left = key === 'reachable' ? 99 : 55;
99
+ const right = width-19, top = 14, bottom = height-29;
100
+ const visible = series.flatMap((values,i) => selected.has(i) ? values.map(point=>point.value).filter(Number.isFinite) : []);
101
+ const min = visible.length ? Math.min(...visible) : 0;
102
+ const max = visible.length ? Math.max(...visible) : 1;
103
+ const padding = (max-min)*.09 || .5;
104
+ const low = key === 'reachable' ? -.15 : min-padding;
105
+ const high = key === 'reachable' ? 1.15 : max+padding;
106
+ const x = time => left + (time-start) / hour * (right-left);
107
+ const y = value => bottom - (value-low)/(high-low)*(bottom-top);
108
+ const format = new Intl.NumberFormat('fr-FR',{maximumFractionDigits:key==='battery'?2:1});
109
+ ctx.font = '12px system-ui';
110
+ ctx.textAlign = 'right';
111
+ ctx.fillStyle = '#b7cbd6';
112
+ ctx.strokeStyle = '#375163';
113
+ const ticks = key === 'reachable' ? [0,1] : [low,(low+high)/2,high];
114
+ for (const tick of ticks) {
115
+ ctx.beginPath(); ctx.moveTo(left,y(tick)); ctx.lineTo(right,y(tick)); ctx.stroke();
116
+ ctx.fillText(key==='reachable' ? (tick ? 'Joignable' : 'Non joignable') : format.format(tick),left-6,y(tick)+4);
22
117
  }
118
+ ctx.textAlign = 'center';
119
+ for (const fraction of [0,.5,1]) {
120
+ const time = start + fraction * hour;
121
+ ctx.fillText(clock(time).slice(0,5),x(time),height-6);
122
+ }
123
+ series.forEach((values,i) => {
124
+ if (!selected.has(i)) return;
125
+ ctx.strokeStyle = sensors[i].color;
126
+ ctx.lineWidth = 2;
127
+ ctx.setLineDash([[],[6,4],[2,4]][i]);
128
+ ctx.beginPath();
129
+ let previous = null;
130
+ values.forEach(({time,value}) => {
131
+ if (value === null) { previous = null; return; }
132
+ if (!previous || time - previous.time > 90000) {
133
+ ctx.moveTo(x(time)-1,y(value));
134
+ ctx.lineTo(x(time)+1,y(value));
135
+ } else {
136
+ if (mode === 'step') ctx.lineTo(x(time),y(previous.value));
137
+ ctx.lineTo(x(time),y(value));
138
+ }
139
+ previous = {time,value};
140
+ });
141
+ ctx.stroke();
142
+ });
143
+ const point = cursor === null ? end : start + cursor * hour;
144
+ if (cursor !== null) {
145
+ ctx.setLineDash([3,3]); ctx.strokeStyle='#abc0cc'; ctx.lineWidth=1;
146
+ ctx.beginPath(); ctx.moveTo(x(point),top); ctx.lineTo(x(point),bottom); ctx.stroke();
147
+ }
148
+ const summaries = sensors.flatMap((sensor,i) => {
149
+ if (!selected.has(i)) return [];
150
+ const reading = series[i].findLast(sample => sample.time <= point);
151
+ const value = reading ? reading.value : null;
152
+ const label = value === null ? 'indisponible'
153
+ : key === 'reachable' ? (value ? 'joignable' : 'non joignable')
154
+ : format.format(value)+(unit?' '+unit:'');
155
+ return [sensor.name+' '+label+(reading ? ' à '+clock(reading.time) : '')];
156
+ });
157
+ output.textContent = summaries.length ? clock(point)+' · '+summaries.join(' · ') : 'Sélectionne un capteur.';
158
+ }
159
+
160
+ function render() {
161
+ charts.replaceChildren();
162
+ painters.length = 0;
163
+ Object.entries(groups).forEach(([name, metrics], index) => {
164
+ const section = document.createElement('section');
165
+ section.className = 'chart-group';
166
+ section.id = sectionIds[index];
167
+ const title = document.createElement('h2');
168
+ title.textContent = name;
169
+ const grid = document.createElement('div');
170
+ grid.className = 'grid';
171
+ section.append(title, grid);
172
+ charts.append(section);
173
+ for (const metric of metrics) {
174
+ const card = document.createElement('article');
175
+ const heading = document.createElement('h3');
176
+ heading.textContent = metric[1] + (metric[2] ? ' · '+metric[2] : '');
177
+ const canvas = document.createElement('canvas');
178
+ canvas.setAttribute('role','img');
179
+ canvas.setAttribute('aria-label',metric[1]+' des trois Ruuvi sur une heure');
180
+ const output = document.createElement('output');
181
+ const series = history.map(points=>points[metric[0]]);
182
+ card.append(heading,canvas,output);
183
+ grid.append(card);
184
+ const paint = (cursor = null)=>draw(canvas,output,metric,series,cursor);
185
+ canvas.addEventListener('pointermove',event=>{
186
+ const left = metric[0] === 'reachable' ? 99 : 55;
187
+ const ratio = (event.offsetX-left)/(canvas.clientWidth-left-19);
188
+ paint(Math.max(0,Math.min(1,ratio)));
189
+ });
190
+ canvas.addEventListener('pointerleave',()=>paint());
191
+ painters.push(paint);
192
+ paint();
193
+ }
194
+ });
195
+ }
196
+ sensors.forEach((sensor,i)=>{
197
+ const label=document.createElement('label');
198
+ label.style.color=sensor.color;
199
+ const input=document.createElement('input');
200
+ input.type='checkbox';input.checked=true;
201
+ input.addEventListener('change',()=>{
202
+ if(input.checked) selected.add(i);
203
+ else selected.delete(i);
204
+ painters.forEach(paint=>paint());
205
+ });
206
+ label.append(input,' '+sensor.name);
207
+ toggle.append(label);
208
+ });
209
+ window.addEventListener('resize',()=>painters.forEach(paint=>paint()));
210
+ render();
211
+
212
+ const ruuvi = document.querySelector('#ruuvi');
213
+ const relays = document.querySelector('#relays');
214
+ const openRuuvi = document.querySelector('#open-ruuvi');
215
+ const openRelays = document.querySelector('#open-relays');
216
+ const status = document.querySelector('#connection');
217
+ const relayCards = document.querySelector('#relay-cards');
23
218
 
24
- walk(data, '');
25
- return sensors;
219
+ function showRelays(enabled) {
220
+ ruuvi.hidden = enabled;
221
+ relays.hidden = !enabled;
222
+ openRuuvi.setAttribute('aria-pressed',String(!enabled));
223
+ openRelays.setAttribute('aria-pressed',String(enabled));
224
+ if (!enabled) painters.forEach(paint=>paint());
26
225
  }
226
+ openRuuvi.addEventListener('click',()=>showRelays(false));
227
+ openRelays.addEventListener('click',()=>showRelays(true));
27
228
 
28
- function render(sensors) {
29
- readings.replaceChildren();
30
- for (const [sensor, samples] of sensors) {
31
- const card = document.createElement('section');
229
+ function updateRelays(data) {
230
+ relayCards.replaceChildren();
231
+ for (let number=1; number<=6; number++) {
232
+ const reading = at(data,'electrical.switches.gx.gxInternalRelay'+number+'.state');
233
+ const card = document.createElement('article');
32
234
  const heading = document.createElement('h2');
33
- heading.textContent = sensor;
34
- const list = document.createElement('dl');
35
- for (const axis of axes) {
36
- const sample = samples[axis];
37
- const label = document.createElement('dt');
38
- label.textContent = axis;
39
- const entry = document.createElement('dd');
40
- const units = sample?.meta?.units;
41
- entry.textContent = Number.isFinite(sample?.value)
42
- ? formatter.format(sample.value) + (units ? ' ' + units : '')
43
- : '—';
44
- list.append(label, entry);
45
- }
46
- const timestamp = Math.max(...Object.values(samples).map(sample => Date.parse(sample.timestamp)).filter(Number.isFinite));
47
- const time = document.createElement('time');
48
- time.textContent = Number.isFinite(timestamp)
49
- ? 'Dernière mesure reçue · ' + new Date(timestamp).toLocaleTimeString('fr-FR')
50
- : 'Horodatage indisponible';
51
- card.append(heading, list, time);
52
- readings.append(card);
235
+ heading.textContent = 'Relais '+number;
236
+ const state = document.createElement('p');
237
+ state.textContent = reading?.value === true ? 'On' : reading?.value === false ? 'Off' : 'Indisponible';
238
+ const time = document.createElement('small');
239
+ const timestamp = Date.parse(reading?.timestamp);
240
+ time.textContent = Number.isFinite(timestamp) ? 'État publié à '+clock(timestamp) : 'Horodatage indisponible';
241
+ card.append(heading,state,time);
242
+ relayCards.append(card);
53
243
  }
54
244
  }
55
245
 
56
246
  async function refresh() {
57
247
  try {
58
248
  const response = await fetch('/signalk/v1/api/vessels/self', {
59
- cache: 'no-store',
60
- signal: AbortSignal.timeout(10000)
249
+ cache:'no-store', signal:AbortSignal.timeout(10000)
61
250
  });
62
- if (!response.ok) throw new Error('HTTP ' + response.status);
63
- const sensors = findSensors(await response.json());
64
- render(sensors);
65
- status.textContent = sensors.size
66
- ? 'Signal K connecté'
67
- : 'Aucune accélération Ruuvi trouvée dans Signal K.';
68
- } catch (error) {
69
- status.textContent = 'Lecture Signal K indisponible. Nouvelle tentative dans 5 s.';
70
- readings.replaceChildren();
251
+ if (!response.ok) throw new Error('HTTP '+response.status);
252
+ const data = await response.json();
253
+ const now = Date.now();
254
+ record(data,now);
255
+ updateRelays(data);
256
+ status.textContent = 'Signal K connecté · dernière lecture à '+clock(now);
257
+ } catch {
258
+ status.textContent = 'Signal K indisponible · nouvelle tentative dans 5 s';
259
+ updateRelays(null);
71
260
  } finally {
72
- setTimeout(refresh, 5000);
261
+ if (!ruuvi.hidden) painters.forEach(paint=>paint());
262
+ setTimeout(refresh,5000);
73
263
  }
74
264
  }
75
-
265
+ updateRelays(null);
76
266
  refresh();
package/public/index.html CHANGED
@@ -2,13 +2,34 @@
2
2
  <html lang="fr">
3
3
  <meta charset="utf-8">
4
4
  <meta name="viewport" content="width=device-width, initial-scale=1">
5
- <title>YODA Dashboard</title>
5
+ <title>Ruuvi Cookpit-Inside-Motor (last hour)</title>
6
6
  <link rel="stylesheet" href="./style.css">
7
+ <header><strong>YODA</strong><nav aria-label="Pages">
8
+ <button type="button" id="open-ruuvi" aria-pressed="true">Ruuvi</button>
9
+ <button type="button" id="open-relays" aria-pressed="false">Relay</button>
10
+ </nav></header>
7
11
  <main>
8
- <h1>YODA Dashboard</h1>
9
- <p>Accélérations Ruuvi · repère propre à chaque capteur</p>
10
- <p id="status" role="status">Connexion à Signal K…</p>
11
- <div id="sensors"></div>
12
+ <p id="connection" role="status">Connexion à Signal K…</p>
13
+ <div id="ruuvi">
14
+ <h1>Ruuvi Cookpit-Inside-Motor (last hour)</h1>
15
+ <p>Fenêtre glissante d’une heure · collecte pendant que la WebApp est ouverte.</p>
16
+ <div class="controls">
17
+ <fieldset aria-label="Capteurs visibles"></fieldset>
18
+ </div>
19
+ <div class="layout">
20
+ <aside><nav aria-label="Familles de mesures">
21
+ <a href="#ambiance">Ambiance</a>
22
+ <a href="#accelerations">Accélérations</a>
23
+ <a href="#diagnostic">Diagnostic</a>
24
+ </nav></aside>
25
+ <div id="charts"></div>
26
+ </div>
27
+ </div>
28
+ <section id="relays" hidden>
29
+ <h1>Relais</h1>
30
+ <p>États déclarés par Venus OS · lecture seule</p>
31
+ <div class="grid" id="relay-cards"></div>
32
+ </section>
12
33
  </main>
13
34
  <script src="./dashboard.js" defer></script>
14
35
  </html>
package/public/style.css CHANGED
@@ -1,8 +1,26 @@
1
- :root { color-scheme: dark; font-family: system-ui, sans-serif; background: #101c27; color: #e8f4f6; }
2
- main { margin: 3rem auto; width: min(94%, 56rem); }
3
- #status, time { color: #adc8ce; }
4
- #sensors { display: grid; grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr)); gap: 1rem; }
5
- section { border: 1px solid #38515e; border-radius: 0.75rem; background: #172936; padding: 1rem; }
6
- h2 { margin-top: 0; }
7
- dl { display: grid; grid-template-columns: auto 1fr; gap: .55rem 1rem; font-variant-numeric: tabular-nums; }
8
- dd { margin: 0; text-align: right; }
1
+
2
+ [hidden]{display:none!important}
3
+ :root{color-scheme:dark;font:16px system-ui,sans-serif;background:#0d1923;color:#eaf3f6}
4
+ body{margin:0} header,main{max-width:1680px;margin:auto;padding:1.2rem clamp(.75rem,2vw,2rem)}
5
+ header{border-bottom:1px solid #304554;display:flex;align-items:center;gap:1.1rem}
6
+ header strong{letter-spacing:.15em} header span,small,p{color:#abc0cc}
7
+ h1{font-size:clamp(2rem,5vw,3rem);margin:.5rem 0} p{line-height:1.55}
8
+ .controls{display:flex;flex-wrap:wrap;justify-content:space-between;gap:1rem;margin:1.5rem 0}
9
+ fieldset,nav{display:flex;flex-wrap:wrap;align-items:center;gap:.65rem;border:0;padding:0;margin:0}
10
+ button,label{font:inherit;color:inherit;background:#182b39;border:1px solid #405a6b;border-radius:.5rem;padding:.55rem .8rem;cursor:pointer}
11
+ button[aria-pressed=true]{background:#a5e3d6;color:#102631;border-color:#a5e3d6}
12
+ input{accent-color:#91dfce}.grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:1rem}
13
+ article{min-width:0;background:#142632;border:1px solid #344d5c;border-radius:.8rem;padding:1rem}
14
+ h2{font-size:1.2rem;margin:.1rem 0 .4rem} canvas{display:block;width:100%;height:220px}
15
+ output{display:block;min-height:3rem;color:#c3d6df;font-size:.86rem;line-height:1.45}
16
+ .layout{display:grid;grid-template-columns:clamp(7.5rem,10vw,9rem) minmax(0,1fr);gap:clamp(.65rem,1.4vw,1.25rem)}
17
+ aside nav{position:sticky;top:1rem;display:grid;gap:.45rem;background:#142632;border:1px solid #344d5c;border-radius:.65rem;padding:.4rem}
18
+ aside a{color:#cce3eb;text-decoration:none;padding:.55rem .35rem;border-radius:.35rem;overflow-wrap:anywhere}
19
+ aside a:hover,aside a:focus-visible{background:#a5e3d6;color:#102631}
20
+ .chart-group{scroll-margin-top:1rem;margin-bottom:1.75rem}
21
+ .chart-group:target h2{color:#a5e3d6}
22
+ .chart-group h2{margin-bottom:.65rem;font-size:1.45rem}
23
+ article h3{margin:.1rem 0 .4rem;font-size:1.15rem}
24
+ @media(max-width:1050px){.grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
25
+ @media(max-width:740px){.grid{grid-template-columns:minmax(0,1fr)}}
26
+ @media(max-width:500px){.layout{grid-template-columns:5.7rem minmax(0,1fr)}aside nav{font-size:.77rem}article{padding:.5rem}}