signalk-wmo-gust 0.3.0 → 0.4.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/CHANGELOG.md CHANGED
@@ -3,6 +3,22 @@
3
3
  All notable changes to this project are documented in this file.
4
4
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
5
5
 
6
+ ## [0.4.0] - 2026-11-19
7
+
8
+ ### Added
9
+ - **Wind history web app** (Signal K Web Apps → WMO Wind): charts of the last 1, 3, 24 or 72 hours with the 10-minute mean at 10 m and at sensor height, gusts as WMO 3-second gusts, absolute maxima or both, at 10 m or at sensor height, and arrows for the mean direction. Built for Garmin chartplotters (OneHelm) as well as browsers: touch controls, night mode, and no login needed, as it reads the Signal K History API.
10
+ - `gustOverGroundPeak` (or `gustTruePeak`): the highest single wind sample in the last 10 minutes, not averaged, corrected to 10 m.
11
+ - `gustOverGroundMax1minWMO` and `gustOverGroundPeak1min` (or the `True` equivalents): the highest WMO 3-second gust and the highest single sample in the last minute, for charts. The app plots the absolute maximum of each point from the 1-minute peak, and the WMO gust as the 10-minute WMO gust.
12
+ - `environment.wind.heightFactorWMO`: the factor used to correct speeds to 10 m, so that sensor-height values can be recovered.
13
+
14
+ ### Changed
15
+ - The Web App and App Store name is now **WMO Wind**.
16
+
17
+ ## [0.3.1] - 2026-11-05
18
+
19
+ ### Added
20
+ - App icon for the Signal K App Store: a three-cup anemometer and a stopwatch showing the WMO 10-minute averaging window.
21
+
6
22
  ## [0.3.0] - 2026-11-04
7
23
 
8
24
  ### Added
@@ -29,6 +45,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
29
45
  ### Added
30
46
  - First version: WMO 10-minute mean wind and 3-second running-mean gust, with power-law height correction from a configured height or `design.airHeight`.
31
47
 
48
+ [0.3.1]: https://github.com/PiotrSol/signalk-wmo-gust/compare/v0.3.0...v0.3.1
32
49
  [0.3.0]: https://github.com/PiotrSol/signalk-wmo-gust/compare/v0.2.0...v0.3.0
33
50
  [0.2.0]: https://github.com/PiotrSol/signalk-wmo-gust/compare/v0.1.0...v0.2.0
34
51
  [0.1.0]: https://github.com/PiotrSol/signalk-wmo-gust/releases/tag/v0.1.0
package/README.md CHANGED
@@ -16,8 +16,12 @@ With the default source `environment.wind.speedOverGround`:
16
16
  | `environment.wind.gustOverGroundMax1hWMO` | Highest WMO gust in the last hour | ECMWF `10fg1`; SYNOP hourly gust |
17
17
  | `environment.wind.gustOverGroundMax3hWMO` | Highest WMO gust in the last 3 hours | ECMWF `10fg3`; GFS `GUST` at 3-hourly output |
18
18
  | `environment.wind.gustOverGroundMax6hWMO` | Highest WMO gust in the last 6 hours | ECMWF `10fg6` |
19
+ | `environment.wind.gustOverGroundPeak` | Highest single sample in the last 10 minutes, not averaged | Instrument displays' "max wind" |
20
+ | `environment.wind.gustOverGroundMax1minWMO` | Highest WMO 3-second gust in the last minute, for charts | — |
21
+ | `environment.wind.gustOverGroundPeak1min` | Highest single sample in the last minute, for charts | — |
22
+ | `environment.wind.heightFactorWMO` | Factor applied to correct speeds to 10 m; divide by it for sensor-height values | — |
19
23
 
20
- All values are in m/s, the Signal K base unit, with metadata describing the reference and the height correction applied. The names follow the source path: `environment.wind.speedTrue` (water-referenced) gives `speedTrueMeanWMO`, `gustTrueWMO`, `gustTrueMax1hWMO` and so on.
24
+ Speeds are in m/s, the Signal K base unit, with metadata describing the reference and the height correction applied. The names follow the source path: `environment.wind.speedTrue` (water-referenced) gives `speedTrueMeanWMO`, `gustTrueWMO`, `gustTrueMax1hWMO` and so on.
21
25
 
22
26
  The plugin status line shows the current values in knots, the actual input rate, and where the sensor height came from.
23
27
 
@@ -81,6 +85,20 @@ In a current the two differ by roughly the current's speed. In 2 kn of tide, the
81
85
 
82
86
  **7. Sheltering.** In a marina or close to a high shore, buildings, other masts and terrain shelter the sensor. Neither forecasts nor height correction can account for that. Use data from open water or an exposed anchorage when judging a forecast.
83
87
 
88
+ ## Wind history web app
89
+
90
+ The plugin includes a web app, **WMO Wind**, under **Web Apps** in the Signal K admin, at `/signalk-wmo-gust/`. It charts the last **1, 3, 24 or 72 hours**:
91
+
92
+ - the 10-minute **mean wind at 10 m** and **at sensor height**;
93
+ - **gusts**: the WMO 3-second gust, the absolute maximum (highest single sample), or both, at 10 m or at sensor height;
94
+ - the 10-minute **mean direction**, as arrows pointing downwind, with the direction the wind comes from in degrees.
95
+
96
+ Touch or click a chart to read the values at that moment. Units are knots or m/s, and a night mode keeps the screen dark.
97
+
98
+ The app reads the **Signal K History API**, so a history provider must record this plugin's paths, for example **signalk-questdb**. It works without logging in, so it can run on Garmin chartplotters with OneHelm, for example through **signalk-garmin-onehelm**. It uses no external libraries or fonts, so it works offline.
99
+
100
+ Points are averages (mean wind) and maxima over 1 minute for 1 and 3 hours, 5 minutes for 24 hours and 15 minutes for 72 hours. The WMO gust line is the 10-minute WMO gust, so it holds each gust for up to 10 minutes, as METAR reports do. The absolute maximum is the highest sample within each point, from `…Peak1min`. Before version 0.4.0 the plugin didn't publish it; for that time the app takes it from the recorded wind samples, which a history provider may store at a lower rate, so it can read low.
101
+
84
102
  ## Comparing with forecasts
85
103
 
86
104
  **[Wind Forecast Check](https://github.com/PiotrSol/signalk-forecast-verify)** (`signalk-forecast-verify`) is a companion Signal K web app. It charts this plugin's mean wind, gust and direction against every forecast model available at the vessel's position, and scores which model to trust where you sail.
package/icon.svg ADDED
@@ -0,0 +1,22 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128">
2
+ <title>WMO Wind</title>
3
+ <rect width="128" height="128" rx="25" fill="#e3edf1"/>
4
+ <!-- three-cup anemometer seen from above -->
5
+ <path d="M37.33 48.00L37.33 34.67" stroke="#15191c" stroke-width="5.333333333333333" stroke-linecap="round"/>
6
+ <path d="M37.33 34.67A10.31111111111111 10.31111111111111 0 0 1 37.33 14.04Z" fill="#15191c"/>
7
+ <path d="M37.33 48.00L48.88 54.67" stroke="#15191c" stroke-width="5.333333333333333" stroke-linecap="round"/>
8
+ <path d="M48.88 54.67A10.31111111111111 10.31111111111111 0 0 1 66.74 64.98Z" fill="#15191c"/>
9
+ <path d="M37.33 48.00L25.79 54.67" stroke="#15191c" stroke-width="5.333333333333333" stroke-linecap="round"/>
10
+ <path d="M25.79 54.67A10.31111111111111 10.31111111111111 0 0 1 7.93 64.98Z" fill="#15191c"/>
11
+ <circle cx="37.33" cy="48.00" r="6.3999999999999995" fill="#15191c"/>
12
+ <!-- wind -->
13
+ <path d="M78.2 23.1h24.9a7.1 7.1 0 1 0-7.1-7.1" fill="none" stroke="#1d6fa5" stroke-width="5.33" stroke-linecap="round"/>
14
+ <path d="M83.6 39.1h17.8" fill="none" stroke="#1d6fa5" stroke-width="5.33" stroke-linecap="round"/>
15
+ <!-- stopwatch with the WMO 10-minute averaging window -->
16
+ <rect x="85" y="55" width="12" height="7" rx="2.5" fill="#15191c"/>
17
+ <path d="M88 61h6v5h-6z" fill="#15191c"/>
18
+ <circle cx="91" cy="91" r="25" fill="#fbfcfa" stroke="#15191c" stroke-width="5"/>
19
+ <path d="M91 91L91.00 70.00A21 21 0 0 1 109.19 80.50Z" fill="#b0287a"/>
20
+ <path d="M91.00 69.00L91.00 74.00" stroke="#15191c" stroke-width="3" stroke-linecap="round"/><path d="M113.00 91.00L108.00 91.00" stroke="#15191c" stroke-width="3" stroke-linecap="round"/><path d="M91.00 113.00L91.00 108.00" stroke="#15191c" stroke-width="3" stroke-linecap="round"/><path d="M69.00 91.00L74.00 91.00" stroke="#15191c" stroke-width="3" stroke-linecap="round"/>
21
+ <circle cx="91" cy="91" r="3.5" fill="#15191c"/>
22
+ </svg>
package/index.js CHANGED
@@ -16,7 +16,10 @@
16
16
  * vector mean weighted by wind speed, so that 350° and 10° average to 0°.
17
17
  *
18
18
  * Speeds can be corrected from the anemometer height to the standard 10 m
19
- * with a power-law wind profile; directions are not height-corrected.
19
+ * with a power-law wind profile; directions are not height-corrected. The
20
+ * correction factor is published too, so that sensor-height values can be
21
+ * recovered, and so is the highest single sample of the last 10 minutes
22
+ * (the absolute peak, not a WMO gust).
20
23
  *
21
24
  * SPDX-License-Identifier: MIT
22
25
  */
@@ -31,8 +34,10 @@ const LONGEST_MS = Math.max(...LONG_WINDOWS_H) * 3600000
31
34
  const MS_TO_KN = 1.94384
32
35
  const DEFAULT_EXPONENT = 0.11 // near-neutral open sea (Hsu et al., 1994)
33
36
  const CALM_MS = 0.5 // below this mean speed the direction is undefined
37
+ const RECENT_MS = 60000 // short window for charting gusts and peaks
34
38
  const DIR_MAX_AGE_MS = 5000 // a direction older than this is not paired with a speed
35
39
  const TWO_PI = 2 * Math.PI
40
+ const FACTOR_PATH = 'environment.wind.heightFactorWMO'
36
41
 
37
42
  module.exports = function (app) {
38
43
  const plugin = {
@@ -50,6 +55,8 @@ module.exports = function (app) {
50
55
  * speedOverGround -> gustOverGroundWMO, speedOverGroundMeanWMO (ground)
51
56
  * speedTrue -> gustTrueWMO, speedTrueMeanWMO (water)
52
57
  * anything else -> <source>GustWMO, <source>MeanWMO
58
+ * The absolute peak is <gust>Peak (gustOverGroundPeak, gustTruePeak).
59
+ * The same over the last minute, for charts: <gust>Max1minWMO, <gust>Peak1min.
53
60
  */
54
61
  function outputPaths (src) {
55
62
  let base, ref
@@ -63,7 +70,7 @@ module.exports = function (app) {
63
70
  base = { gust: `${src}Gust`, mean: `${src}Mean`, dir: `${src}DirectionMean` }
64
71
  ref = src
65
72
  }
66
- const paths = { gust: `${base.gust}WMO`, mean: `${base.mean}WMO`, dir: `${base.dir}WMO`, ref, long: {} }
73
+ const paths = { gust: `${base.gust}WMO`, mean: `${base.mean}WMO`, dir: `${base.dir}WMO`, peak: `${base.gust}Peak`, gust1: `${base.gust}Max1minWMO`, peak1: `${base.gust}Peak1min`, factor: FACTOR_PATH, ref, long: {} }
67
74
  for (const h of LONG_WINDOWS_H) paths.long[h] = `${base.gust}Max${h}hWMO`
68
75
  return paths
69
76
  }
@@ -141,6 +148,10 @@ module.exports = function (app) {
141
148
  const meta = [
142
149
  { path: out.mean, description: `WMO mean wind (${out.ref}): 10 min average, ${correction}` },
143
150
  { path: out.gust, description: `WMO gust (${out.ref}): highest 3 s running mean in the last 10 min, ${correction}` },
151
+ { path: out.peak, description: `Highest single wind sample (${out.ref}) in the last 10 min, not averaged (not a WMO gust), ${correction}` },
152
+ { path: out.gust1, description: `Highest WMO 3 s gust (${out.ref}) in the last minute, for charts, ${correction}` },
153
+ { path: out.peak1, description: `Highest single wind sample (${out.ref}) in the last minute, not averaged, for charts, ${correction}` },
154
+ { path: out.factor, units: 'ratio', description: 'Factor applied to correct wind speeds from the anemometer height to 10 m; divide a corrected value by it for the value at sensor height (1 = no correction)' },
144
155
  { path: out.dir, units: 'rad', description: `WMO mean wind direction (${out.ref}, true north, from): speed-weighted vector mean over 10 min; not published in a calm` },
145
156
  ...LONG_WINDOWS_H.map((h) => ({
146
157
  path: out.long[h],
@@ -207,9 +218,19 @@ module.exports = function (app) {
207
218
 
208
219
  const mean = k * samples.reduce((a, s) => a + s.v, 0) / samples.length
209
220
  const gust = k * gust3s.reduce((m, g) => Math.max(m, g.v), 0)
221
+ const peak = k * samples.reduce((m, s) => Math.max(m, s.v), 0)
222
+ const recent = now - RECENT_MS
223
+ let gust1 = 0
224
+ let peak1 = 0
225
+ for (let i = gust3s.length - 1; i >= 0 && gust3s[i].t > recent; i--) gust1 = Math.max(gust1, gust3s[i].v)
226
+ for (let i = samples.length - 1; i >= 0 && samples[i].t > recent; i--) peak1 = Math.max(peak1, samples[i].v)
210
227
  const values = [
211
228
  { path: out.mean, value: mean },
212
- { path: out.gust, value: gust }
229
+ { path: out.gust, value: gust },
230
+ { path: out.peak, value: peak },
231
+ { path: out.gust1, value: k * gust1 },
232
+ { path: out.peak1, value: k * peak1 },
233
+ { path: out.factor, value: k }
213
234
  ]
214
235
  // Direction: the vector mean, undefined in a calm or without directions.
215
236
  let dirText = 'dir –'
@@ -239,7 +260,7 @@ module.exports = function (app) {
239
260
  const filling = spanS < WINDOW_MS / 1000 - 10 ? ` (10 min window filling: ${Math.round(spanS)} s)` : ''
240
261
  const warn = rateHz < 4 ? ' — WARNING: input below 4 Hz' : ''
241
262
  app.setPluginStatus(
242
- `Mean ${(mean * MS_TO_KN).toFixed(1)} kn ${dirText}, gust ${(gust * MS_TO_KN).toFixed(1)} kn, max ${longText.join(' / ')} kn; ` +
263
+ `Mean ${(mean * MS_TO_KN).toFixed(1)} kn ${dirText}, gust ${(gust * MS_TO_KN).toFixed(1)} kn, peak ${(peak * MS_TO_KN).toFixed(1)} kn, max ${longText.join(' / ')} kn; ` +
243
264
  `${rateHz.toFixed(1)} Hz, sensor ${height.h.toFixed(1)} m (${height.src})${filling}${warn}`
244
265
  )
245
266
  }, (options.publishInterval > 0 ? options.publishInterval : 1) * 1000)
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "signalk-wmo-gust",
3
- "version": "0.3.0",
4
- "description": "WMO-standard 10-minute mean wind, mean direction and 3-second gust for Signal K, with 1/3/6-hour gust maxima for comparing forecasts with measured wind",
3
+ "version": "0.4.0",
4
+ "description": "WMO-standard 10-minute mean wind, mean direction and 3-second gust for Signal K, with 1/3/6-hour gust maxima, and a web app charting the last 1, 3, 24 and 72 hours",
5
5
  "main": "index.js",
6
6
  "scripts": {
7
7
  "test": "node --check index.js && node --test"
8
8
  },
9
9
  "keywords": [
10
10
  "signalk-node-server-plugin",
11
+ "signalk-webapp",
11
12
  "signalk-category-weather",
12
13
  "wind",
13
14
  "gust",
@@ -31,9 +32,12 @@
31
32
  "index.js",
32
33
  "README.md",
33
34
  "CHANGELOG.md",
34
- "LICENSE"
35
+ "LICENSE",
36
+ "icon.svg",
37
+ "public"
35
38
  ],
36
39
  "signalk": {
37
- "displayName": "WMO Wind (10 min mean, 3 s gust)"
40
+ "displayName": "WMO Wind",
41
+ "appIcon": "./icon.svg"
38
42
  }
39
43
  }
@@ -0,0 +1,22 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128">
2
+ <title>WMO Wind</title>
3
+ <rect width="128" height="128" rx="25" fill="#e3edf1"/>
4
+ <!-- three-cup anemometer seen from above -->
5
+ <path d="M37.33 48.00L37.33 34.67" stroke="#15191c" stroke-width="5.333333333333333" stroke-linecap="round"/>
6
+ <path d="M37.33 34.67A10.31111111111111 10.31111111111111 0 0 1 37.33 14.04Z" fill="#15191c"/>
7
+ <path d="M37.33 48.00L48.88 54.67" stroke="#15191c" stroke-width="5.333333333333333" stroke-linecap="round"/>
8
+ <path d="M48.88 54.67A10.31111111111111 10.31111111111111 0 0 1 66.74 64.98Z" fill="#15191c"/>
9
+ <path d="M37.33 48.00L25.79 54.67" stroke="#15191c" stroke-width="5.333333333333333" stroke-linecap="round"/>
10
+ <path d="M25.79 54.67A10.31111111111111 10.31111111111111 0 0 1 7.93 64.98Z" fill="#15191c"/>
11
+ <circle cx="37.33" cy="48.00" r="6.3999999999999995" fill="#15191c"/>
12
+ <!-- wind -->
13
+ <path d="M78.2 23.1h24.9a7.1 7.1 0 1 0-7.1-7.1" fill="none" stroke="#1d6fa5" stroke-width="5.33" stroke-linecap="round"/>
14
+ <path d="M83.6 39.1h17.8" fill="none" stroke="#1d6fa5" stroke-width="5.33" stroke-linecap="round"/>
15
+ <!-- stopwatch with the WMO 10-minute averaging window -->
16
+ <rect x="85" y="55" width="12" height="7" rx="2.5" fill="#15191c"/>
17
+ <path d="M88 61h6v5h-6z" fill="#15191c"/>
18
+ <circle cx="91" cy="91" r="25" fill="#fbfcfa" stroke="#15191c" stroke-width="5"/>
19
+ <path d="M91 91L91.00 70.00A21 21 0 0 1 109.19 80.50Z" fill="#b0287a"/>
20
+ <path d="M91.00 69.00L91.00 74.00" stroke="#15191c" stroke-width="3" stroke-linecap="round"/><path d="M113.00 91.00L108.00 91.00" stroke="#15191c" stroke-width="3" stroke-linecap="round"/><path d="M91.00 113.00L91.00 108.00" stroke="#15191c" stroke-width="3" stroke-linecap="round"/><path d="M69.00 91.00L74.00 91.00" stroke="#15191c" stroke-width="3" stroke-linecap="round"/>
21
+ <circle cx="91" cy="91" r="3.5" fill="#15191c"/>
22
+ </svg>
@@ -0,0 +1,582 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Wind history</title>
7
+ <style>
8
+ /* Plain CSS and ES2015 only: the chartplotter's built-in browser may be old. */
9
+ :root {
10
+ --bg: #e9eef1; --panel: #ffffff; --ink: #0f2230; --muted: #5a6a76; --rule: #cfd8de;
11
+ --mean: #1c4e8a; --means: #6f97c9; --gust: #c4471a; --peak: #7b2d86; --dir: #0e6f69;
12
+ --btn: #dde5ea; --btn-on: #0f2230; --btn-on-ink: #ffffff;
13
+ }
14
+ body.night {
15
+ --bg: #000000; --panel: #0a0000; --ink: #ff4d3d; --muted: #a33326; --rule: #3a0d08;
16
+ --mean: #ff3b2f; --means: #b3261b; --gust: #ff8c42; --peak: #ffc09a; --dir: #e0473a;
17
+ --btn: #1a0402; --btn-on: #ff3b2f; --btn-on-ink: #000000;
18
+ }
19
+ * { box-sizing: border-box; }
20
+ html, body { height: 100%; margin: 0; }
21
+ body {
22
+ background: var(--bg); color: var(--ink);
23
+ font-family: Roboto, "Segoe UI", "Helvetica Neue", Arial, sans-serif;
24
+ font-variant-numeric: tabular-nums;
25
+ display: flex; flex-direction: column; overflow: hidden;
26
+ -webkit-user-select: none; user-select: none; -webkit-tap-highlight-color: transparent;
27
+ }
28
+ header { display: flex; flex-wrap: wrap; align-items: stretch; padding: 0.5rem 0.75rem 0; }
29
+ .now { background: var(--panel); border-radius: 0.375rem; padding: 0.375rem 0.75rem 0.5rem; margin: 0 0.5rem 0.5rem 0; min-width: 7.375rem; }
30
+ .now .label { font-size: 0.875rem; color: var(--muted); }
31
+ .now .value { font-size: 2.125rem; font-weight: 500; line-height: 1.1; white-space: nowrap; }
32
+ .now .value small { font-size: 0.9375rem; font-weight: 400; color: var(--muted); margin-left: 0.1875rem; }
33
+ .now.mean .value { color: var(--mean); }
34
+ .now.means .value { color: var(--means); }
35
+ .now.gust .value { color: var(--gust); }
36
+ .now.peak .value { color: var(--peak); }
37
+ .now.dir .value { color: var(--dir); }
38
+ nav { display: flex; flex-wrap: wrap; align-items: center; padding: 0 0.75rem; }
39
+ .group { display: flex; align-items: center; margin: 0 1rem 0.5rem 0; }
40
+ .group span { font-size: 0.875rem; color: var(--muted); margin-right: 0.5rem; }
41
+ button {
42
+ font: inherit; font-size: 1.0625rem; min-height: 2.75rem; min-width: 3.5rem; padding: 0 0.875rem;
43
+ border: 0; background: var(--btn); color: var(--ink); cursor: pointer;
44
+ }
45
+ .seg button { border-radius: 0; margin-right: 0.0625rem; }
46
+ .seg button:first-of-type { border-radius: 0.375rem 0 0 0.375rem; }
47
+ .seg button:last-of-type { border-radius: 0 0.375rem 0.375rem 0; margin-right: 0; }
48
+ button.on { background: var(--btn-on); color: var(--btn-on-ink); }
49
+ button:focus-visible { outline: 0.1875rem solid var(--gust); outline-offset: 0.125rem; }
50
+ #night { border-radius: 0.375rem; }
51
+ main { flex: 1; display: flex; flex-direction: column; min-height: 0; margin: 0 0.75rem; background: var(--panel); border-radius: 0.375rem; position: relative; }
52
+ .plot { position: relative; min-height: 0; }
53
+ #speedWrap { flex: 1; }
54
+ #dirWrap { height: 4.625rem; border-top: 0.0625rem solid var(--rule); }
55
+ .now .value svg { width: 1.625rem; height: 1.625rem; vertical-align: -3px; margin-left: 0.375rem; }
56
+ canvas { position: absolute; left: 0; top: 0; width: 100%; height: 100%; touch-action: none; }
57
+ #legend { position: absolute; right: 0.875rem; top: 0.5rem; font-size: 0.875rem; color: var(--muted); text-align: right; pointer-events: none; background: var(--panel); padding: 0.125rem 0.375rem; border-radius: 0.25rem; opacity: 0.92; }
58
+ #legend i { display: inline-block; width: 1.375rem; height: 0; border-top: 0.1875rem solid; vertical-align: middle; margin: 0 0.3125rem 0 0.75rem; }
59
+ #readout {
60
+ position: absolute; top: 0.5rem; display: none; background: var(--panel); border: 0.0625rem solid var(--rule);
61
+ border-radius: 0.375rem; padding: 0.375rem 0.625rem; font-size: 0.9375rem; line-height: 1.45; pointer-events: none; white-space: nowrap;
62
+ }
63
+ #readout b { font-weight: 500; }
64
+ #message { position: absolute; left: 0; right: 0; top: 40%; text-align: center; padding: 0 1.5rem; font-size: 1.125rem; color: var(--muted); }
65
+ footer { padding: 0.5rem 0.75rem 0.625rem; font-size: 0.9375rem; color: var(--muted); min-height: 2.25rem; }
66
+ footer b { color: var(--ink); font-weight: 500; }
67
+ @media (max-width: 760px), (max-height: 560px) {
68
+ header { flex-wrap: nowrap; padding: 0.375rem 0.5rem 0; }
69
+ .now { flex: 1 1 0; min-width: 0; padding: 0.1875rem 0.375rem 0.25rem; margin: 0 0.25rem 0.375rem 0; }
70
+ .now .label { font-size: 0.75rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
71
+ .now .value { font-size: 1.3125rem; }
72
+ .now .value small { font-size: 0.75rem; }
73
+ nav { padding: 0 0.5rem; }
74
+ .group { margin: 0 0.5rem 0.375rem 0; }
75
+ .group span { font-size: 0.75rem; margin-right: 0.25rem; }
76
+ button { font-size: 0.875rem; min-height: 2.5rem; min-width: 2.5rem; padding: 0 0.5rem; }
77
+ main { margin: 0 0.5rem; }
78
+ #legend, #readout { font-size: 0.75rem; }
79
+ footer { font-size: 0.8125rem; padding: 0.25rem 0.5rem 0.375rem; min-height: 0; }
80
+ }
81
+ </style>
82
+ </head>
83
+ <body>
84
+ <header>
85
+ <div class="now mean"><div class="label">Mean at 10 m</div><div class="value" id="nMean">–</div></div>
86
+ <div class="now means"><div class="label">Mean at sensor</div><div class="value" id="nMeanS">–</div></div>
87
+ <div class="now gust"><div class="label" id="nGustLabel">WMO gust</div><div class="value" id="nGust">–</div></div>
88
+ <div class="now peak"><div class="label" id="nPeakLabel">Peak, 10 min</div><div class="value" id="nPeak">–</div></div>
89
+ <div class="now dir"><div class="label">From</div><div class="value" id="nDir">–</div></div>
90
+ </header>
91
+ <nav>
92
+ <div class="group seg" data-key="range"><span>Period</span>
93
+ <button data-v="1">1 h</button><button data-v="3">3 h</button><button data-v="24">24 h</button><button data-v="72">72 h</button></div>
94
+ <div class="group seg" data-key="gust"><span>Gusts</span>
95
+ <button data-v="wmo">WMO 3 s</button><button data-v="peak">Absolute max</button><button data-v="both">Both</button></div>
96
+ <div class="group seg" data-key="gustH"><span>Gusts at</span>
97
+ <button data-v="10">10 m</button><button data-v="sensor">Sensor</button></div>
98
+ <div class="group seg" data-key="unit"><span>Units</span>
99
+ <button data-v="kn">kn</button><button data-v="ms">m/s</button></div>
100
+ <div class="group"><button id="night">Night</button></div>
101
+ </nav>
102
+ <main>
103
+ <div class="plot" id="speedWrap"><canvas id="speed"></canvas><div id="legend"></div><div id="readout"></div><div id="message">Loading wind history…</div></div>
104
+ <div class="plot" id="dirWrap"><canvas id="dir"></canvas></div>
105
+ </main>
106
+ <footer id="summary"></footer>
107
+ <script>
108
+ 'use strict'
109
+ ;(function () {
110
+ var RANGES = {
111
+ 1: { duration: 'PT1H', res: 60, tick: 10 * 60000 },
112
+ 3: { duration: 'PT3H', res: 60, tick: 30 * 60000 },
113
+ 24: { duration: 'PT24H', res: 300, tick: 3 * 3600000 },
114
+ 72: { duration: 'PT72H', res: 900, tick: 12 * 3600000 }
115
+ }
116
+ var MS_TO_KN = 1.94384
117
+ var FAMILIES = {
118
+ ground: {
119
+ mean: 'environment.wind.speedOverGroundMeanWMO', gust: 'environment.wind.gustOverGroundWMO',
120
+ peak: 'environment.wind.gustOverGroundPeak', raw: 'environment.wind.speedOverGround',
121
+ gust1: 'environment.wind.gustOverGroundMax1minWMO', peak1: 'environment.wind.gustOverGroundPeak1min',
122
+ dir: 'environment.wind.directionOverGroundMeanWMO'
123
+ },
124
+ water: {
125
+ mean: 'environment.wind.speedTrueMeanWMO', gust: 'environment.wind.gustTrueWMO',
126
+ peak: 'environment.wind.gustTruePeak', raw: 'environment.wind.speedTrue',
127
+ gust1: 'environment.wind.gustTrueMax1minWMO', peak1: 'environment.wind.gustTruePeak1min',
128
+ dir: 'environment.wind.directionTrueMeanWMO'
129
+ }
130
+ }
131
+ var FACTOR = 'environment.wind.heightFactorWMO'
132
+ var COMPASS = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']
133
+
134
+ var state = { range: '3', gust: 'wmo', gustH: '10', unit: 'kn', night: false }
135
+ try { var saved = JSON.parse(localStorage.getItem('wmo-wind-app') || '{}'); for (var k in saved) if (k in state) state[k] = saved[k] } catch (e) { /* no storage */ }
136
+ function save () { try { localStorage.setItem('wmo-wind-app', JSON.stringify(state)) } catch (e) { /* no storage */ } }
137
+
138
+ var family = FAMILIES.ground
139
+ var liveFactor = null
140
+ var points = []
141
+ var approxPeak = false
142
+ var selected = -1
143
+ var selectTimer = null
144
+ var historyTimer = null
145
+ var live = {}
146
+ var $ = function (id) { return document.getElementById(id) }
147
+
148
+ // ---- data ---------------------------------------------------------------
149
+
150
+ function getJSON (url, cb) {
151
+ var x = new XMLHttpRequest()
152
+ // Some chartplotter browsers cache XHR responses (Signal K sends no Cache-Control).
153
+ x.open('GET', url + (url.indexOf('?') < 0 ? '?' : '&') + '_=' + Date.now())
154
+ x.timeout = 20000
155
+ x.onload = function () {
156
+ if (x.status !== 200) return cb(new Error('HTTP ' + x.status))
157
+ try { cb(null, JSON.parse(x.responseText)) } catch (e) { cb(e) }
158
+ }
159
+ x.onerror = function () { cb(new Error('no connection to Signal K')) }
160
+ x.ontimeout = function () { cb(new Error('Signal K did not answer')) }
161
+ x.send()
162
+ }
163
+
164
+ function historyUrl (r, withNew) {
165
+ var p = [family.mean + ':average', family.gust + ':max', family.raw + ':max', family.dir + ':last']
166
+ if (withNew) p.push(family.peak + ':max', FACTOR + ':average', family.gust1 + ':max', family.peak1 + ':max')
167
+ return '/signalk/v2/api/history/values?paths=' + p.join(',') + '&duration=' + r.duration + '&resolution=' + r.res
168
+ }
169
+
170
+ function loadHistory () {
171
+ clearTimeout(historyTimer)
172
+ var key = state.range
173
+ var r = RANGES[key]
174
+ getJSON(historyUrl(r, true), function (err, d) {
175
+ if (!err) return gotHistory(key, r, d, true)
176
+ // Paths added in 0.4.0 may not be in the history yet.
177
+ getJSON(historyUrl(r, false), function (err2, d2) {
178
+ if (err2) return showMessage('Can’t load the wind history (' + err2.message + '). Check that the WMO Wind plugin and history recording (signalk-questdb) are running.')
179
+ gotHistory(key, r, d2, false)
180
+ })
181
+ })
182
+ historyTimer = setTimeout(loadHistory, key === '1' || key === '3' ? 60000 : 180000)
183
+ }
184
+
185
+ function gotHistory (key, r, d, withNew) {
186
+ if (key !== state.range) return
187
+ var rows = (d && d.data) || []
188
+ var half = r.res * 500
189
+ var lastF = null
190
+ for (var i = rows.length - 1; i >= 0 && lastF === null; i--) if (withNew && num(rows[i][6])) lastF = rows[i][6]
191
+ approxPeak = false
192
+ points = rows.map(function (row) {
193
+ var f = withNew && num(row[6]) ? row[6] : (lastF || liveFactor)
194
+ // WMO gust: the 10-minute WMO gust. Absolute max: the highest sample of each point,
195
+ // from the 1-minute peak, or from the stored raw samples before it was published.
196
+ var mean = val(row[1]); var raw = val(row[3]); var gust = val(row[2])
197
+ var peak = withNew ? val(row[8]) : null
198
+ var p = { t: Date.parse(row[0]) + half, mean: mean, gust: gust, dir: val(row[4]), f: f }
199
+ if (peak !== null) { p.peak = peak } else if (raw !== null) { p.peak = f ? raw * f : raw; approxPeak = true } else p.peak = null
200
+ return p
201
+ })
202
+ if (!points.some(function (p) { return p.mean !== null })) {
203
+ points = []
204
+ return showMessage('No wind data recorded in the last ' + key + ' h.')
205
+ }
206
+ showMessage('')
207
+ draw()
208
+ }
209
+
210
+ function num (v) { return typeof v === 'number' && isFinite(v) }
211
+ function val (v) { return num(v) ? v : null }
212
+
213
+ function pick (obj, path) {
214
+ var name = path.split('.').pop()
215
+ return obj && obj[name] && num(obj[name].value) ? obj[name].value : null
216
+ }
217
+
218
+ function loadLive () {
219
+ getJSON('/signalk/v1/api/vessels/self/environment/wind', function (err, w) {
220
+ setTimeout(loadLive, 3000)
221
+ if (err) return
222
+ if (pick(w, FAMILIES.ground.mean) === null && pick(w, FAMILIES.water.mean) !== null && family !== FAMILIES.water) {
223
+ family = FAMILIES.water
224
+ loadHistory()
225
+ }
226
+ var f = pick(w, FACTOR)
227
+ if (f && !liveFactor) { liveFactor = f; if (points.length) draw() } else if (f) liveFactor = f
228
+ live = { mean: pick(w, family.mean), gust: pick(w, family.gust), peak: pick(w, family.peak), dir: pick(w, family.dir) }
229
+ showLive()
230
+ })
231
+ }
232
+
233
+ function showLive () {
234
+ var mean = live.mean; var gust = live.gust; var peak = live.peak; var dir = live.dir
235
+ if (mean === undefined) return
236
+ var s = state.gustH === 'sensor' && liveFactor ? 1 / liveFactor : 1
237
+ $('nMean').innerHTML = fmt(mean, true)
238
+ $('nMeanS').innerHTML = liveFactor ? fmt(mean === null ? null : mean / liveFactor, true) : '–'
239
+ $('nGust').innerHTML = fmt(gust === null ? null : gust * s, true)
240
+ $('nPeak').innerHTML = fmt(peak === null ? null : peak * s, true)
241
+ $('nDir').innerHTML = dir === null ? '–' : pad3(deg(dir)) + '°<small>' + compass(dir) + '</small>' + arrowSvg(dir)
242
+ }
243
+
244
+ // ---- formatting ---------------------------------------------------------
245
+
246
+ function conv (ms) { return state.unit === 'kn' ? ms * MS_TO_KN : ms }
247
+ function unitName () { return state.unit === 'kn' ? 'kn' : 'm/s' }
248
+ function fmt (ms, withUnit) {
249
+ if (ms === null || ms === undefined) return '–'
250
+ return conv(ms).toFixed(1) + (withUnit ? '<small>' + unitName() + '</small>' : '')
251
+ }
252
+ function deg (rad) { return Math.round(rad * 180 / Math.PI + 360) % 360 }
253
+ function pad3 (n) { return ('00' + n).slice(-3) }
254
+ function compass (rad) { return COMPASS[Math.round(deg(rad) / 22.5) % 16] }
255
+ function two (n) { return (n < 10 ? '0' : '') + n }
256
+ function hm (t) { var d = new Date(t); return two(d.getHours()) + ':' + two(d.getMinutes()) }
257
+ function dm (t) { var d = new Date(t); return two(d.getDate()) + '/' + two(d.getMonth() + 1) }
258
+
259
+ // ---- series -------------------------------------------------------------
260
+
261
+ function series () {
262
+ var sensorGust = state.gustH === 'sensor'
263
+ var g = function (key) {
264
+ return function (p) {
265
+ var v = p[key]
266
+ if (v === null) return null
267
+ var f = p.f || liveFactor
268
+ return sensorGust ? (f ? v / f : null) : v
269
+ }
270
+ }
271
+ var gustMean = sensorGust ? 'meanS' : 'mean'
272
+ var list = [
273
+ { id: 'mean', name: 'Mean at 10 m', color: 'mean', width: 2.5, get: function (p) { return p.mean } },
274
+ { id: 'meanS', name: 'Mean at sensor', color: 'means', width: 2, dash: [7, 5], get: function (p) { var f = p.f || liveFactor; return p.mean !== null && f ? p.mean / f : null } }
275
+ ]
276
+ var h = sensorGust ? ' at sensor' : ' at 10 m'
277
+ if (state.gust !== 'peak') list.push({ id: 'gust', name: 'WMO gust' + h, color: 'gust', width: 2, fill: gustMean, get: g('gust') })
278
+ if (state.gust !== 'wmo') {
279
+ list.push({
280
+ id: 'peak', name: 'Absolute max' + h, color: 'peak', width: state.gust === 'both' ? 1.5 : 2,
281
+ dash: state.gust === 'both' ? [2, 3] : null, fill: state.gust === 'peak' ? gustMean : null, get: g('peak')
282
+ })
283
+ }
284
+ return list
285
+ }
286
+
287
+ // ---- drawing ------------------------------------------------------------
288
+
289
+ function css (name) { return getComputedStyle(document.body).getPropertyValue('--' + name).trim() }
290
+
291
+ function setup (canvas) {
292
+ var dpr = window.devicePixelRatio || 1
293
+ var w = canvas.parentNode.clientWidth; var h = canvas.parentNode.clientHeight
294
+ canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr)
295
+ var c = canvas.getContext('2d')
296
+ c.setTransform(dpr, 0, 0, dpr, 0, 0)
297
+ c.clearRect(0, 0, w, h)
298
+ return { c: c, w: w, h: h }
299
+ }
300
+
301
+ function niceStep (span, target) {
302
+ var raw = span / target
303
+ var p = Math.pow(10, Math.floor(Math.log(raw) / Math.LN10))
304
+ var m = raw / p
305
+ return (m <= 1 ? 1 : m <= 2 ? 2 : m <= 2.5 ? 2.5 : m <= 5 ? 5 : 10) * p
306
+ }
307
+
308
+ // Large chartplotter screens report a big CSS viewport: scale the whole UI to it.
309
+ var UI = 1
310
+ function applyScale () {
311
+ var w = window.innerWidth || 1280; var h = window.innerHeight || 720
312
+ UI = Math.max(1, Math.min(w / 1280, h / 720, 2.5))
313
+ document.documentElement.style.fontSize = (16 * UI) + 'px'
314
+ }
315
+ applyScale()
316
+ var PAD = { l: 46, r: 14, t: 12, b: 28 }
317
+ var geo = null
318
+
319
+ function draw () {
320
+ var r = RANGES[state.range]
321
+ var end = Date.now()
322
+ var start = end - Number(state.range) * 3600000
323
+ var list = series()
324
+ var ink = css('ink'); var muted = css('muted'); var rule = css('rule')
325
+
326
+ // Speed chart
327
+ var S = setup($('speed'))
328
+ var c = S.c
329
+ var max = 0
330
+ points.forEach(function (p) { list.forEach(function (s) { var v = s.get(p); if (v !== null && v > max) max = v }) })
331
+ var top = Math.max(conv(max) * 1.08, state.unit === 'kn' ? 10 : 5)
332
+ var step = niceStep(top, Math.max(3, Math.floor((S.h - (PAD.t + PAD.b) * UI) / (55 * UI))))
333
+ top = Math.ceil(top / step) * step
334
+ var x0 = PAD.l * UI; var x1 = S.w - PAD.r * UI; var y0 = S.h - PAD.b * UI; var y1 = PAD.t * UI
335
+ var X = function (t) { return x0 + (t - start) / (end - start) * (x1 - x0) }
336
+ var Y = function (ms) { return y0 - conv(ms) / top * (y0 - y1) }
337
+ geo = { start: start, end: end, x0: x0, x1: x1, X: X }
338
+
339
+ c.font = (13 * UI) + 'px Roboto, Arial, sans-serif'
340
+ c.lineWidth = 1
341
+ c.fillStyle = muted
342
+ c.textAlign = 'right'; c.textBaseline = 'middle'
343
+ for (var v = 0; v <= top + 1e-9; v += step) {
344
+ var y = Math.round(y0 - v / top * (y0 - y1)) + 0.5
345
+ c.strokeStyle = rule; c.beginPath(); c.moveTo(x0, y); c.lineTo(x1, y); c.stroke()
346
+ c.fillText(String(Math.round(v * 10) / 10), x0 - 6 * UI, y)
347
+ }
348
+ c.textAlign = 'left'; c.textBaseline = 'top'
349
+ c.fillText(unitName(), 4 * UI, 2 * UI)
350
+ timeAxis(c, r, start, end, X, y1, y0, rule, muted, true)
351
+
352
+ var gap = r.res * 1000 * 2.5
353
+ list.forEach(function (s) {
354
+ if (!s.fill) return
355
+ var base = s.fill === 'mean' ? list[0] : list[1]
356
+ fillBetween(c, s, base, X, Y, gap, css(s.color))
357
+ })
358
+ for (var i = list.length - 1; i >= 0; i--) line(c, list[i], X, Y, gap)
359
+
360
+ // Direction arrows, pointing downwind
361
+ var D = setup($('dir'))
362
+ var d = D.c
363
+ timeAxis(d, r, start, end, X, 0, D.h, rule, muted, false)
364
+ var slots = Math.max(4, Math.floor((x1 - x0) / (52 * UI)))
365
+ var span = (end - start) / slots
366
+ var len = Math.min(30 * UI, D.h - 30 * UI)
367
+ d.font = (12 * UI) + 'px Roboto, Arial, sans-serif'; d.textAlign = 'center'; d.textBaseline = 'bottom'
368
+ for (var k2 = 0; k2 < slots; k2++) {
369
+ var ts = start + k2 * span; var te = ts + span
370
+ var vx = 0; var vy = 0; var n = 0
371
+ points.forEach(function (p) {
372
+ if (p.dir === null || p.t < ts || p.t >= te) return
373
+ var w = p.mean || 0.1
374
+ vx += w * Math.sin(p.dir); vy += w * Math.cos(p.dir); n++
375
+ })
376
+ if (!n) continue
377
+ var from = Math.atan2(vx, vy)
378
+ arrow(d, X(ts + span / 2), 6 * UI + len / 2, len, from, css('dir'))
379
+ d.fillStyle = muted
380
+ d.fillText(pad3(deg(from)) + '°', X(ts + span / 2), D.h - 4 * UI)
381
+ }
382
+
383
+ if (selected >= 0 && points[selected]) cross(c, d, list, X, Y, S, D, ink)
384
+ legend(list)
385
+ summary(list)
386
+ }
387
+
388
+ function timeAxis (c, r, start, end, X, yTop, yBottom, rule, muted, labels) {
389
+ var off = -new Date(start).getTimezoneOffset() * 60000
390
+ var t = Math.ceil((start + off) / r.tick) * r.tick - off
391
+ c.textAlign = 'center'; c.textBaseline = 'top'
392
+ for (; t <= end; t += r.tick) {
393
+ var x = Math.round(X(t)) + 0.5
394
+ var midnight = ((t + off) % 86400000) === 0
395
+ c.strokeStyle = rule; c.lineWidth = (midnight ? 2 : 1) * UI
396
+ c.beginPath(); c.moveTo(x, yTop); c.lineTo(x, yBottom); c.stroke()
397
+ if (labels) { c.fillStyle = muted; c.fillText(midnight && r.tick >= 3600000 ? dm(t) : hm(t), x, yBottom + 7 * UI) }
398
+ }
399
+ }
400
+
401
+ function line (c, s, X, Y, gap) {
402
+ c.strokeStyle = css(s.color); c.lineWidth = s.width * UI
403
+ c.lineJoin = 'round'; c.lineCap = 'round'
404
+ if (c.setLineDash) c.setLineDash((s.dash || []).map(function (v) { return v * UI }))
405
+ c.beginPath()
406
+ var prev = null
407
+ points.forEach(function (p) {
408
+ var v = s.get(p)
409
+ if (v === null) { prev = null; return }
410
+ if (prev === null || p.t - prev > gap) c.moveTo(X(p.t), Y(v)); else c.lineTo(X(p.t), Y(v))
411
+ prev = p.t
412
+ })
413
+ c.stroke()
414
+ if (c.setLineDash) c.setLineDash([])
415
+ }
416
+
417
+ function fillBetween (c, s, base, X, Y, gap, color) {
418
+ c.fillStyle = color
419
+ c.globalAlpha = 0.14
420
+ var run = []
421
+ var flush = function () {
422
+ if (run.length > 1) {
423
+ c.beginPath()
424
+ run.forEach(function (q, i) { if (i) c.lineTo(X(q.t), Y(q.hi)); else c.moveTo(X(q.t), Y(q.hi)) })
425
+ for (var i = run.length - 1; i >= 0; i--) c.lineTo(X(run[i].t), Y(run[i].lo))
426
+ c.closePath(); c.fill()
427
+ }
428
+ run = []
429
+ }
430
+ points.forEach(function (p) {
431
+ var hi = s.get(p); var lo = base.get(p)
432
+ if (hi === null || lo === null || (run.length && p.t - run[run.length - 1].t > gap)) flush()
433
+ if (hi !== null && lo !== null) run.push({ t: p.t, hi: hi, lo: lo })
434
+ })
435
+ flush()
436
+ c.globalAlpha = 1
437
+ }
438
+
439
+ function arrow (c, x, y, len, from, color) {
440
+ var a = from + Math.PI // the way the wind blows
441
+ var ux = Math.sin(a); var uy = -Math.cos(a)
442
+ var hx = x + ux * len / 2; var hy = y + uy * len / 2
443
+ var head = Math.max(6 * UI, len * 0.32)
444
+ c.strokeStyle = color; c.fillStyle = color; c.lineWidth = 2.5 * UI; c.lineCap = 'round'
445
+ c.beginPath(); c.moveTo(x - ux * len / 2, y - uy * len / 2); c.lineTo(hx - ux * head * 0.6, hy - uy * head * 0.6); c.stroke()
446
+ c.beginPath()
447
+ c.moveTo(hx, hy)
448
+ c.lineTo(hx - ux * head + uy * head * 0.55, hy - uy * head - ux * head * 0.55)
449
+ c.lineTo(hx - ux * head - uy * head * 0.55, hy - uy * head + ux * head * 0.55)
450
+ c.closePath(); c.fill()
451
+ }
452
+
453
+ function arrowSvg (from) {
454
+ return '<svg viewBox="-12 -12 24 24" aria-hidden="true"><g transform="rotate(' + (deg(from) + 180) + ')">' +
455
+ '<line x1="0" y1="9" x2="0" y2="-3" stroke="currentColor" stroke-width="2.6" stroke-linecap="round"/>' +
456
+ '<path d="M0 -11 L6 -2 L-6 -2 Z" fill="currentColor"/></g></svg>'
457
+ }
458
+
459
+ function cross (c, d, list, X, Y, S, D, ink) {
460
+ var p = points[selected]
461
+ var x = Math.round(X(p.t)) + 0.5
462
+ ;[[c, S.h], [d, D.h]].forEach(function (a) {
463
+ a[0].strokeStyle = ink; a[0].lineWidth = UI
464
+ a[0].beginPath(); a[0].moveTo(x, 0); a[0].lineTo(x, a[1]); a[0].stroke()
465
+ })
466
+ var rows = ['<b>' + (state.range === '72' ? dm(p.t) + ' ' : '') + hm(p.t) + '</b>']
467
+ list.forEach(function (s) {
468
+ var v = s.get(p)
469
+ if (v === null) return
470
+ c.fillStyle = css(s.color)
471
+ c.beginPath(); c.arc(x, Y(v), 4 * UI, 0, 2 * Math.PI); c.fill()
472
+ rows.push(s.name + ' <b style="color:' + css(s.color) + '">' + fmt(v) + '</b> ' + unitName())
473
+ })
474
+ if (p.dir !== null) {
475
+ rows.push('From <b>' + pad3(deg(p.dir)) + '° ' + compass(p.dir) + '</b>')
476
+ }
477
+ var el = $('readout')
478
+ el.innerHTML = rows.join('<br>')
479
+ el.style.display = 'block'
480
+ var w = el.offsetWidth
481
+ var left = x + 14 + w > S.w - 8 ? x - 14 - w : x + 14
482
+ el.style.left = Math.max(4, left) + 'px'
483
+ }
484
+
485
+ function legend (list) {
486
+ $('legend').innerHTML = list.map(function (s) {
487
+ var style = s.dash ? (s.dash[0] < 4 ? 'dotted' : 'dashed') : 'solid'
488
+ return '<i style="border-top-color:' + css(s.color) + ';border-top-style:' + style + '"></i>' + s.name
489
+ }).join('<br>')
490
+ }
491
+
492
+ function summary (list) {
493
+ var start = Date.now() - Number(state.range) * 3600000
494
+ var inRange = points.filter(function (p) { return p.t >= start })
495
+ var parts = []
496
+ list.slice(2).forEach(function (s) {
497
+ var best = null
498
+ inRange.forEach(function (p) { var v = s.get(p); if (v !== null && (!best || v > best.v)) best = { v: v, t: p.t } })
499
+ if (best) parts.push('Highest ' + s.name.replace('Absolute', 'absolute') + ' <b>' + fmt(best.v) + ' ' + unitName() + '</b> at ' + (state.range === '72' ? dm(best.t) + ' ' : '') + hm(best.t) + '.')
500
+ })
501
+ var sum = 0; var n = 0
502
+ inRange.forEach(function (p) { if (p.mean !== null) { sum += p.mean; n++ } })
503
+ if (n) parts.push('Average wind at 10 m <b>' + fmt(sum / n) + ' ' + unitName() + '</b>.')
504
+ if (approxPeak && state.gust !== 'wmo') parts.push('Absolute max before the plugin recorded it is taken from the stored samples and may read low.')
505
+ $('summary').innerHTML = parts.join(' ')
506
+ }
507
+
508
+ function showMessage (text) {
509
+ $('message').textContent = text
510
+ $('message').style.display = text ? 'block' : 'none'
511
+ if (text) { $('summary').innerHTML = ''; $('legend').innerHTML = '' }
512
+ }
513
+
514
+ // ---- interaction --------------------------------------------------------
515
+
516
+ function selectAt (clientX) {
517
+ if (!geo || !points.length) return
518
+ var rect = $('speed').getBoundingClientRect()
519
+ var x = clientX - rect.left
520
+ if (x < geo.x0 - 10 || x > geo.x1 + 10) return clear()
521
+ var t = geo.start + (x - geo.x0) / (geo.x1 - geo.x0) * (geo.end - geo.start)
522
+ var best = -1; var bd = Infinity
523
+ points.forEach(function (p, i) { var dd = Math.abs(p.t - t); if (dd < bd) { bd = dd; best = i } })
524
+ selected = best
525
+ clearTimeout(selectTimer)
526
+ selectTimer = setTimeout(clear, 10000)
527
+ draw()
528
+ }
529
+ function clear () { selected = -1; $('readout').style.display = 'none'; draw() }
530
+
531
+ ;['speed', 'dir'].forEach(function (id) {
532
+ var el = $(id)
533
+ el.addEventListener('touchstart', function (e) { e.preventDefault(); selectAt(e.touches[0].clientX) }, { passive: false })
534
+ el.addEventListener('touchmove', function (e) { e.preventDefault(); selectAt(e.touches[0].clientX) }, { passive: false })
535
+ el.addEventListener('mousedown', function (e) { selectAt(e.clientX) })
536
+ el.addEventListener('mousemove', function (e) { if (e.buttons) selectAt(e.clientX) })
537
+ })
538
+
539
+ function syncButtons () {
540
+ var groups = document.querySelectorAll('.seg')
541
+ for (var i = 0; i < groups.length; i++) {
542
+ var key = groups[i].getAttribute('data-key')
543
+ var bs = groups[i].querySelectorAll('button')
544
+ for (var j = 0; j < bs.length; j++) bs[j].className = bs[j].getAttribute('data-v') === state[key] ? 'on' : ''
545
+ }
546
+ $('night').className = state.night ? 'on' : ''
547
+ document.body.className = state.night ? 'night' : ''
548
+ $('nGustLabel').textContent = 'WMO gust' + (state.gustH === 'sensor' ? ', sensor' : ', 10 m')
549
+ $('nPeakLabel').textContent = 'Peak, 10 min' + (state.gustH === 'sensor' ? ', sensor' : '')
550
+ showLive()
551
+ }
552
+
553
+ document.querySelector('nav').addEventListener('click', function (e) {
554
+ var b = e.target
555
+ if (b.tagName !== 'BUTTON') return
556
+ if (b.id === 'night') state.night = !state.night
557
+ else {
558
+ var key = b.parentNode.getAttribute('data-key')
559
+ var changed = state[key] !== b.getAttribute('data-v')
560
+ state[key] = b.getAttribute('data-v')
561
+ if (key === 'range' && changed) { points = []; selected = -1; $('readout').style.display = 'none'; showMessage('Loading wind history…'); draw(); loadHistory() }
562
+ }
563
+ save(); syncButtons(); draw()
564
+ })
565
+
566
+ var resizeTimer = null
567
+ window.addEventListener('resize', function () { clearTimeout(resizeTimer); resizeTimer = setTimeout(function () { applyScale(); draw() }, 150) })
568
+ setInterval(function () { if (selected < 0) draw() }, 30000)
569
+ // Coming back to the app (OneHelm keeps it in the background): reload at once.
570
+ function wake () { if (!document.hidden) loadHistory() }
571
+ document.addEventListener('visibilitychange', wake)
572
+ window.addEventListener('focus', wake)
573
+ window.addEventListener('pageshow', function (e) { if (e.persisted) loadHistory() })
574
+
575
+ syncButtons()
576
+ draw()
577
+ loadLive()
578
+ loadHistory()
579
+ })()
580
+ </script>
581
+ </body>
582
+ </html>