signalk-wmo-gust 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,26 @@
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.1] - 2026-11-19
7
+
8
+ ### Added
9
+ - The onboard time zone is published as `environment.time.timezoneOffset` and `environment.time.timezoneRegion` (setting **Onboard time zone**; empty uses the server's time zone, `none` turns it off).
10
+
11
+ ### Fixed
12
+ - The wind history app shows local time on chartplotters whose browser runs on UTC, such as Garmin OneHelm: it uses the onboard time zone from Signal K.
13
+ - The app no longer shows stale data on browsers that cache requests, and reloads the charts when it comes back to the foreground.
14
+
15
+ ## [0.4.0] - 2026-11-19
16
+
17
+ ### Added
18
+ - **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.
19
+ - `gustOverGroundPeak` (or `gustTruePeak`): the highest single wind sample in the last 10 minutes, not averaged, corrected to 10 m.
20
+ - `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.
21
+ - `environment.wind.heightFactorWMO`: the factor used to correct speeds to 10 m, so that sensor-height values can be recovered.
22
+
23
+ ### Changed
24
+ - The Web App and App Store name is now **WMO Wind**.
25
+
6
26
  ## [0.3.1] - 2026-11-05
7
27
 
8
28
  ### Added
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.
@@ -112,6 +130,7 @@ Then go to **Server → Plugin Config → WMO Wind**, and enable the plugin.
112
130
  | Anemometer distance below `design.airHeight` (m) | 0.3 | Allows for the sensor sitting below the top of the mast |
113
131
  | Wind profile exponent | 0.11 | 0.11 for open sea, 0.143 for open land, 0 for no correction |
114
132
  | Publish interval (s) | 1 | How often values are published |
133
+ | Onboard time zone | empty | IANA name such as `Europe/Madrid`, published as `environment.time.timezoneOffset` and `timezoneRegion` so that displays running on UTC show local time. Empty: the server's time zone; `none`: not published |
115
134
 
116
135
  The height is re-read on every publish, so a change to `design.airHeight` takes effect without a restart.
117
136
 
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,29 @@ 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'
41
+
42
+ /** Offset of an IANA time zone from UTC at a moment, as Signal K's (-)hhmm number, e.g. 100 or -530. */
43
+ function timezoneOffset (zone, date) {
44
+ let parts
45
+ try {
46
+ parts = new Intl.DateTimeFormat('en-GB', {
47
+ timeZone: zone, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric'
48
+ }).formatToParts(date)
49
+ } catch (e) {
50
+ return null
51
+ }
52
+ const get = (t) => Number(parts.find((p) => p.type === t).value)
53
+ const local = Date.UTC(get('year'), get('month') - 1, get('day'), get('hour'), get('minute'))
54
+ const utc = Math.floor(date.getTime() / 60000) * 60000
55
+ const min = Math.round((local - utc) / 60000)
56
+ const sign = min < 0 ? -1 : 1
57
+ const a = Math.abs(min)
58
+ return sign * (Math.floor(a / 60) * 100 + (a % 60))
59
+ }
36
60
 
37
61
  module.exports = function (app) {
38
62
  const plugin = {
@@ -43,6 +67,7 @@ module.exports = function (app) {
43
67
 
44
68
  let unsubscribes = []
45
69
  let timer = null
70
+ let clockTimer = null
46
71
 
47
72
  /*
48
73
  * Published paths: the reference of the source wind, then the quantity,
@@ -50,6 +75,8 @@ module.exports = function (app) {
50
75
  * speedOverGround -> gustOverGroundWMO, speedOverGroundMeanWMO (ground)
51
76
  * speedTrue -> gustTrueWMO, speedTrueMeanWMO (water)
52
77
  * anything else -> <source>GustWMO, <source>MeanWMO
78
+ * The absolute peak is <gust>Peak (gustOverGroundPeak, gustTruePeak).
79
+ * The same over the last minute, for charts: <gust>Max1minWMO, <gust>Peak1min.
53
80
  */
54
81
  function outputPaths (src) {
55
82
  let base, ref
@@ -63,7 +90,7 @@ module.exports = function (app) {
63
90
  base = { gust: `${src}Gust`, mean: `${src}Mean`, dir: `${src}DirectionMean` }
64
91
  ref = src
65
92
  }
66
- const paths = { gust: `${base.gust}WMO`, mean: `${base.mean}WMO`, dir: `${base.dir}WMO`, ref, long: {} }
93
+ 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
94
  for (const h of LONG_WINDOWS_H) paths.long[h] = `${base.gust}Max${h}hWMO`
68
95
  return paths
69
96
  }
@@ -104,6 +131,12 @@ module.exports = function (app) {
104
131
  type: 'number',
105
132
  title: 'Publish interval (s)',
106
133
  default: 1
134
+ },
135
+ timezone: {
136
+ type: 'string',
137
+ title: 'Onboard time zone (IANA name, e.g. Europe/Madrid)',
138
+ description: 'Published as environment.time.timezoneOffset and timezoneRegion, so that displays without their own time zone, such as Garmin OneHelm, show local time. Empty: the server\'s time zone. "none": do not publish.',
139
+ default: ''
107
140
  }
108
141
  }
109
142
  }
@@ -141,6 +174,10 @@ module.exports = function (app) {
141
174
  const meta = [
142
175
  { path: out.mean, description: `WMO mean wind (${out.ref}): 10 min average, ${correction}` },
143
176
  { path: out.gust, description: `WMO gust (${out.ref}): highest 3 s running mean in the last 10 min, ${correction}` },
177
+ { path: out.peak, description: `Highest single wind sample (${out.ref}) in the last 10 min, not averaged (not a WMO gust), ${correction}` },
178
+ { path: out.gust1, description: `Highest WMO 3 s gust (${out.ref}) in the last minute, for charts, ${correction}` },
179
+ { path: out.peak1, description: `Highest single wind sample (${out.ref}) in the last minute, not averaged, for charts, ${correction}` },
180
+ { 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
181
  { 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
182
  ...LONG_WINDOWS_H.map((h) => ({
146
183
  path: out.long[h],
@@ -207,9 +244,19 @@ module.exports = function (app) {
207
244
 
208
245
  const mean = k * samples.reduce((a, s) => a + s.v, 0) / samples.length
209
246
  const gust = k * gust3s.reduce((m, g) => Math.max(m, g.v), 0)
247
+ const peak = k * samples.reduce((m, s) => Math.max(m, s.v), 0)
248
+ const recent = now - RECENT_MS
249
+ let gust1 = 0
250
+ let peak1 = 0
251
+ for (let i = gust3s.length - 1; i >= 0 && gust3s[i].t > recent; i--) gust1 = Math.max(gust1, gust3s[i].v)
252
+ for (let i = samples.length - 1; i >= 0 && samples[i].t > recent; i--) peak1 = Math.max(peak1, samples[i].v)
210
253
  const values = [
211
254
  { path: out.mean, value: mean },
212
- { path: out.gust, value: gust }
255
+ { path: out.gust, value: gust },
256
+ { path: out.peak, value: peak },
257
+ { path: out.gust1, value: k * gust1 },
258
+ { path: out.peak1, value: k * peak1 },
259
+ { path: out.factor, value: k }
213
260
  ]
214
261
  // Direction: the vector mean, undefined in a calm or without directions.
215
262
  let dirText = 'dir –'
@@ -239,18 +286,40 @@ module.exports = function (app) {
239
286
  const filling = spanS < WINDOW_MS / 1000 - 10 ? ` (10 min window filling: ${Math.round(spanS)} s)` : ''
240
287
  const warn = rateHz < 4 ? ' — WARNING: input below 4 Hz' : ''
241
288
  app.setPluginStatus(
242
- `Mean ${(mean * MS_TO_KN).toFixed(1)} kn ${dirText}, gust ${(gust * MS_TO_KN).toFixed(1)} kn, max ${longText.join(' / ')} kn; ` +
289
+ `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
290
  `${rateHz.toFixed(1)} Hz, sensor ${height.h.toFixed(1)} m (${height.src})${filling}${warn}`
244
291
  )
245
292
  }, (options.publishInterval > 0 ? options.publishInterval : 1) * 1000)
293
+
294
+ if (options.timezone !== 'none') {
295
+ const zone = options.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone
296
+ const publishClock = () => {
297
+ const off = timezoneOffset(zone, new Date())
298
+ if (off === null) return app.error(`Unknown time zone ${zone}`)
299
+ app.handleMessage(plugin.id, {
300
+ updates: [{
301
+ values: [
302
+ { path: 'environment.time.timezoneOffset', value: off },
303
+ { path: 'environment.time.timezoneRegion', value: zone }
304
+ ]
305
+ }]
306
+ })
307
+ }
308
+ publishClock()
309
+ clockTimer = setInterval(publishClock, 60000)
310
+ }
246
311
  }
247
312
 
248
313
  plugin.stop = function () {
249
314
  unsubscribes.forEach((f) => f())
250
315
  unsubscribes = []
251
316
  if (timer) clearInterval(timer)
317
+ if (clockTimer) clearInterval(clockTimer)
252
318
  timer = null
319
+ clockTimer = null
253
320
  }
254
321
 
255
322
  return plugin
256
323
  }
324
+
325
+ module.exports.timezoneOffset = timezoneOffset
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "signalk-wmo-gust",
3
- "version": "0.3.1",
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.1",
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",
@@ -32,10 +33,11 @@
32
33
  "README.md",
33
34
  "CHANGELOG.md",
34
35
  "LICENSE",
35
- "icon.svg"
36
+ "icon.svg",
37
+ "public"
36
38
  ],
37
39
  "signalk": {
38
- "displayName": "WMO Wind (10 min mean, 3 s gust)",
40
+ "displayName": "WMO Wind",
39
41
  "appIcon": "./icon.svg"
40
42
  }
41
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,596 @@
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
+ // Onboard time zone from Signal K (environment.time.timezoneOffset): chartplotter
257
+ // browsers often run on UTC. Without it, the browser's own time zone is used.
258
+ var tzMs = null
259
+ function offsetAt (t) { return tzMs !== null ? tzMs : -new Date(t).getTimezoneOffset() * 60000 }
260
+ function local (t) { return new Date(t + offsetAt(t)) }
261
+ function hm (t) { var d = local(t); return two(d.getUTCHours()) + ':' + two(d.getUTCMinutes()) }
262
+ function dm (t) { var d = local(t); return two(d.getUTCDate()) + '/' + two(d.getUTCMonth() + 1) }
263
+ function loadClock () {
264
+ getJSON('/signalk/v1/api/vessels/self/environment/time', function (err, tm) {
265
+ setTimeout(loadClock, 60000)
266
+ var v = !err && tm && tm.timezoneOffset && num(tm.timezoneOffset.value) ? tm.timezoneOffset.value : null
267
+ var ms = v === null ? null : (v < 0 ? -1 : 1) * (Math.floor(Math.abs(v) / 100) * 60 + Math.abs(v) % 100) * 60000
268
+ if (ms !== tzMs) { tzMs = ms; draw() }
269
+ })
270
+ }
271
+
272
+ // ---- series -------------------------------------------------------------
273
+
274
+ function series () {
275
+ var sensorGust = state.gustH === 'sensor'
276
+ var g = function (key) {
277
+ return function (p) {
278
+ var v = p[key]
279
+ if (v === null) return null
280
+ var f = p.f || liveFactor
281
+ return sensorGust ? (f ? v / f : null) : v
282
+ }
283
+ }
284
+ var gustMean = sensorGust ? 'meanS' : 'mean'
285
+ var list = [
286
+ { id: 'mean', name: 'Mean at 10 m', color: 'mean', width: 2.5, get: function (p) { return p.mean } },
287
+ { 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 } }
288
+ ]
289
+ var h = sensorGust ? ' at sensor' : ' at 10 m'
290
+ if (state.gust !== 'peak') list.push({ id: 'gust', name: 'WMO gust' + h, color: 'gust', width: 2, fill: gustMean, get: g('gust') })
291
+ if (state.gust !== 'wmo') {
292
+ list.push({
293
+ id: 'peak', name: 'Absolute max' + h, color: 'peak', width: state.gust === 'both' ? 1.5 : 2,
294
+ dash: state.gust === 'both' ? [2, 3] : null, fill: state.gust === 'peak' ? gustMean : null, get: g('peak')
295
+ })
296
+ }
297
+ return list
298
+ }
299
+
300
+ // ---- drawing ------------------------------------------------------------
301
+
302
+ function css (name) { return getComputedStyle(document.body).getPropertyValue('--' + name).trim() }
303
+
304
+ function setup (canvas) {
305
+ var dpr = window.devicePixelRatio || 1
306
+ var w = canvas.parentNode.clientWidth; var h = canvas.parentNode.clientHeight
307
+ canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr)
308
+ var c = canvas.getContext('2d')
309
+ c.setTransform(dpr, 0, 0, dpr, 0, 0)
310
+ c.clearRect(0, 0, w, h)
311
+ return { c: c, w: w, h: h }
312
+ }
313
+
314
+ function niceStep (span, target) {
315
+ var raw = span / target
316
+ var p = Math.pow(10, Math.floor(Math.log(raw) / Math.LN10))
317
+ var m = raw / p
318
+ return (m <= 1 ? 1 : m <= 2 ? 2 : m <= 2.5 ? 2.5 : m <= 5 ? 5 : 10) * p
319
+ }
320
+
321
+ // Large chartplotter screens report a big CSS viewport: scale the whole UI to it.
322
+ var UI = 1
323
+ function applyScale () {
324
+ var w = window.innerWidth || 1280; var h = window.innerHeight || 720
325
+ UI = Math.max(1, Math.min(w / 1280, h / 720, 2.5))
326
+ document.documentElement.style.fontSize = (16 * UI) + 'px'
327
+ }
328
+ applyScale()
329
+ var PAD = { l: 46, r: 14, t: 12, b: 28 }
330
+ var geo = null
331
+
332
+ function draw () {
333
+ var r = RANGES[state.range]
334
+ var end = Date.now()
335
+ var start = end - Number(state.range) * 3600000
336
+ var list = series()
337
+ var ink = css('ink'); var muted = css('muted'); var rule = css('rule')
338
+
339
+ // Speed chart
340
+ var S = setup($('speed'))
341
+ var c = S.c
342
+ var max = 0
343
+ points.forEach(function (p) { list.forEach(function (s) { var v = s.get(p); if (v !== null && v > max) max = v }) })
344
+ var top = Math.max(conv(max) * 1.08, state.unit === 'kn' ? 10 : 5)
345
+ var step = niceStep(top, Math.max(3, Math.floor((S.h - (PAD.t + PAD.b) * UI) / (55 * UI))))
346
+ top = Math.ceil(top / step) * step
347
+ var x0 = PAD.l * UI; var x1 = S.w - PAD.r * UI; var y0 = S.h - PAD.b * UI; var y1 = PAD.t * UI
348
+ var X = function (t) { return x0 + (t - start) / (end - start) * (x1 - x0) }
349
+ var Y = function (ms) { return y0 - conv(ms) / top * (y0 - y1) }
350
+ geo = { start: start, end: end, x0: x0, x1: x1, X: X }
351
+
352
+ c.font = (13 * UI) + 'px Roboto, Arial, sans-serif'
353
+ c.lineWidth = 1
354
+ c.fillStyle = muted
355
+ c.textAlign = 'right'; c.textBaseline = 'middle'
356
+ for (var v = 0; v <= top + 1e-9; v += step) {
357
+ var y = Math.round(y0 - v / top * (y0 - y1)) + 0.5
358
+ c.strokeStyle = rule; c.beginPath(); c.moveTo(x0, y); c.lineTo(x1, y); c.stroke()
359
+ c.fillText(String(Math.round(v * 10) / 10), x0 - 6 * UI, y)
360
+ }
361
+ c.textAlign = 'left'; c.textBaseline = 'top'
362
+ c.fillText(unitName(), 4 * UI, 2 * UI)
363
+ timeAxis(c, r, start, end, X, y1, y0, rule, muted, true)
364
+
365
+ var gap = r.res * 1000 * 2.5
366
+ list.forEach(function (s) {
367
+ if (!s.fill) return
368
+ var base = s.fill === 'mean' ? list[0] : list[1]
369
+ fillBetween(c, s, base, X, Y, gap, css(s.color))
370
+ })
371
+ for (var i = list.length - 1; i >= 0; i--) line(c, list[i], X, Y, gap)
372
+
373
+ // Direction arrows, pointing downwind
374
+ var D = setup($('dir'))
375
+ var d = D.c
376
+ timeAxis(d, r, start, end, X, 0, D.h, rule, muted, false)
377
+ var slots = Math.max(4, Math.floor((x1 - x0) / (52 * UI)))
378
+ var span = (end - start) / slots
379
+ var len = Math.min(30 * UI, D.h - 30 * UI)
380
+ d.font = (12 * UI) + 'px Roboto, Arial, sans-serif'; d.textAlign = 'center'; d.textBaseline = 'bottom'
381
+ for (var k2 = 0; k2 < slots; k2++) {
382
+ var ts = start + k2 * span; var te = ts + span
383
+ var vx = 0; var vy = 0; var n = 0
384
+ points.forEach(function (p) {
385
+ if (p.dir === null || p.t < ts || p.t >= te) return
386
+ var w = p.mean || 0.1
387
+ vx += w * Math.sin(p.dir); vy += w * Math.cos(p.dir); n++
388
+ })
389
+ if (!n) continue
390
+ var from = Math.atan2(vx, vy)
391
+ arrow(d, X(ts + span / 2), 6 * UI + len / 2, len, from, css('dir'))
392
+ d.fillStyle = muted
393
+ d.fillText(pad3(deg(from)) + '°', X(ts + span / 2), D.h - 4 * UI)
394
+ }
395
+
396
+ if (selected >= 0 && points[selected]) cross(c, d, list, X, Y, S, D, ink)
397
+ legend(list)
398
+ summary(list)
399
+ }
400
+
401
+ function timeAxis (c, r, start, end, X, yTop, yBottom, rule, muted, labels) {
402
+ var off = offsetAt(end)
403
+ var t = Math.ceil((start + off) / r.tick) * r.tick - off
404
+ c.textAlign = 'center'; c.textBaseline = 'top'
405
+ for (; t <= end; t += r.tick) {
406
+ var x = Math.round(X(t)) + 0.5
407
+ var midnight = ((t + off) % 86400000) === 0
408
+ c.strokeStyle = rule; c.lineWidth = (midnight ? 2 : 1) * UI
409
+ c.beginPath(); c.moveTo(x, yTop); c.lineTo(x, yBottom); c.stroke()
410
+ if (labels) { c.fillStyle = muted; c.fillText(midnight && r.tick >= 3600000 ? dm(t) : hm(t), x, yBottom + 7 * UI) }
411
+ }
412
+ }
413
+
414
+ function line (c, s, X, Y, gap) {
415
+ c.strokeStyle = css(s.color); c.lineWidth = s.width * UI
416
+ c.lineJoin = 'round'; c.lineCap = 'round'
417
+ if (c.setLineDash) c.setLineDash((s.dash || []).map(function (v) { return v * UI }))
418
+ c.beginPath()
419
+ var prev = null
420
+ points.forEach(function (p) {
421
+ var v = s.get(p)
422
+ if (v === null) { prev = null; return }
423
+ if (prev === null || p.t - prev > gap) c.moveTo(X(p.t), Y(v)); else c.lineTo(X(p.t), Y(v))
424
+ prev = p.t
425
+ })
426
+ c.stroke()
427
+ if (c.setLineDash) c.setLineDash([])
428
+ }
429
+
430
+ function fillBetween (c, s, base, X, Y, gap, color) {
431
+ c.fillStyle = color
432
+ c.globalAlpha = 0.14
433
+ var run = []
434
+ var flush = function () {
435
+ if (run.length > 1) {
436
+ c.beginPath()
437
+ run.forEach(function (q, i) { if (i) c.lineTo(X(q.t), Y(q.hi)); else c.moveTo(X(q.t), Y(q.hi)) })
438
+ for (var i = run.length - 1; i >= 0; i--) c.lineTo(X(run[i].t), Y(run[i].lo))
439
+ c.closePath(); c.fill()
440
+ }
441
+ run = []
442
+ }
443
+ points.forEach(function (p) {
444
+ var hi = s.get(p); var lo = base.get(p)
445
+ if (hi === null || lo === null || (run.length && p.t - run[run.length - 1].t > gap)) flush()
446
+ if (hi !== null && lo !== null) run.push({ t: p.t, hi: hi, lo: lo })
447
+ })
448
+ flush()
449
+ c.globalAlpha = 1
450
+ }
451
+
452
+ function arrow (c, x, y, len, from, color) {
453
+ var a = from + Math.PI // the way the wind blows
454
+ var ux = Math.sin(a); var uy = -Math.cos(a)
455
+ var hx = x + ux * len / 2; var hy = y + uy * len / 2
456
+ var head = Math.max(6 * UI, len * 0.32)
457
+ c.strokeStyle = color; c.fillStyle = color; c.lineWidth = 2.5 * UI; c.lineCap = 'round'
458
+ 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()
459
+ c.beginPath()
460
+ c.moveTo(hx, hy)
461
+ c.lineTo(hx - ux * head + uy * head * 0.55, hy - uy * head - ux * head * 0.55)
462
+ c.lineTo(hx - ux * head - uy * head * 0.55, hy - uy * head + ux * head * 0.55)
463
+ c.closePath(); c.fill()
464
+ }
465
+
466
+ function arrowSvg (from) {
467
+ return '<svg viewBox="-12 -12 24 24" aria-hidden="true"><g transform="rotate(' + (deg(from) + 180) + ')">' +
468
+ '<line x1="0" y1="9" x2="0" y2="-3" stroke="currentColor" stroke-width="2.6" stroke-linecap="round"/>' +
469
+ '<path d="M0 -11 L6 -2 L-6 -2 Z" fill="currentColor"/></g></svg>'
470
+ }
471
+
472
+ function cross (c, d, list, X, Y, S, D, ink) {
473
+ var p = points[selected]
474
+ var x = Math.round(X(p.t)) + 0.5
475
+ ;[[c, S.h], [d, D.h]].forEach(function (a) {
476
+ a[0].strokeStyle = ink; a[0].lineWidth = UI
477
+ a[0].beginPath(); a[0].moveTo(x, 0); a[0].lineTo(x, a[1]); a[0].stroke()
478
+ })
479
+ var rows = ['<b>' + (state.range === '72' ? dm(p.t) + ' ' : '') + hm(p.t) + '</b>']
480
+ list.forEach(function (s) {
481
+ var v = s.get(p)
482
+ if (v === null) return
483
+ c.fillStyle = css(s.color)
484
+ c.beginPath(); c.arc(x, Y(v), 4 * UI, 0, 2 * Math.PI); c.fill()
485
+ rows.push(s.name + ' <b style="color:' + css(s.color) + '">' + fmt(v) + '</b> ' + unitName())
486
+ })
487
+ if (p.dir !== null) {
488
+ rows.push('From <b>' + pad3(deg(p.dir)) + '° ' + compass(p.dir) + '</b>')
489
+ }
490
+ var el = $('readout')
491
+ el.innerHTML = rows.join('<br>')
492
+ el.style.display = 'block'
493
+ var w = el.offsetWidth
494
+ var left = x + 14 + w > S.w - 8 ? x - 14 - w : x + 14
495
+ el.style.left = Math.max(4, left) + 'px'
496
+ }
497
+
498
+ function legend (list) {
499
+ $('legend').innerHTML = list.map(function (s) {
500
+ var style = s.dash ? (s.dash[0] < 4 ? 'dotted' : 'dashed') : 'solid'
501
+ return '<i style="border-top-color:' + css(s.color) + ';border-top-style:' + style + '"></i>' + s.name
502
+ }).join('<br>')
503
+ }
504
+
505
+ function summary (list) {
506
+ var start = Date.now() - Number(state.range) * 3600000
507
+ var inRange = points.filter(function (p) { return p.t >= start })
508
+ var parts = []
509
+ list.slice(2).forEach(function (s) {
510
+ var best = null
511
+ inRange.forEach(function (p) { var v = s.get(p); if (v !== null && (!best || v > best.v)) best = { v: v, t: p.t } })
512
+ 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) + '.')
513
+ })
514
+ var sum = 0; var n = 0
515
+ inRange.forEach(function (p) { if (p.mean !== null) { sum += p.mean; n++ } })
516
+ if (n) parts.push('Average wind at 10 m <b>' + fmt(sum / n) + ' ' + unitName() + '</b>.')
517
+ if (approxPeak && state.gust !== 'wmo') parts.push('Absolute max before the plugin recorded it is taken from the stored samples and may read low.')
518
+ $('summary').innerHTML = parts.join(' ')
519
+ }
520
+
521
+ function showMessage (text) {
522
+ $('message').textContent = text
523
+ $('message').style.display = text ? 'block' : 'none'
524
+ if (text) { $('summary').innerHTML = ''; $('legend').innerHTML = '' }
525
+ }
526
+
527
+ // ---- interaction --------------------------------------------------------
528
+
529
+ function selectAt (clientX) {
530
+ if (!geo || !points.length) return
531
+ var rect = $('speed').getBoundingClientRect()
532
+ var x = clientX - rect.left
533
+ if (x < geo.x0 - 10 || x > geo.x1 + 10) return clear()
534
+ var t = geo.start + (x - geo.x0) / (geo.x1 - geo.x0) * (geo.end - geo.start)
535
+ var best = -1; var bd = Infinity
536
+ points.forEach(function (p, i) { var dd = Math.abs(p.t - t); if (dd < bd) { bd = dd; best = i } })
537
+ selected = best
538
+ clearTimeout(selectTimer)
539
+ selectTimer = setTimeout(clear, 10000)
540
+ draw()
541
+ }
542
+ function clear () { selected = -1; $('readout').style.display = 'none'; draw() }
543
+
544
+ ;['speed', 'dir'].forEach(function (id) {
545
+ var el = $(id)
546
+ el.addEventListener('touchstart', function (e) { e.preventDefault(); selectAt(e.touches[0].clientX) }, { passive: false })
547
+ el.addEventListener('touchmove', function (e) { e.preventDefault(); selectAt(e.touches[0].clientX) }, { passive: false })
548
+ el.addEventListener('mousedown', function (e) { selectAt(e.clientX) })
549
+ el.addEventListener('mousemove', function (e) { if (e.buttons) selectAt(e.clientX) })
550
+ })
551
+
552
+ function syncButtons () {
553
+ var groups = document.querySelectorAll('.seg')
554
+ for (var i = 0; i < groups.length; i++) {
555
+ var key = groups[i].getAttribute('data-key')
556
+ var bs = groups[i].querySelectorAll('button')
557
+ for (var j = 0; j < bs.length; j++) bs[j].className = bs[j].getAttribute('data-v') === state[key] ? 'on' : ''
558
+ }
559
+ $('night').className = state.night ? 'on' : ''
560
+ document.body.className = state.night ? 'night' : ''
561
+ $('nGustLabel').textContent = 'WMO gust' + (state.gustH === 'sensor' ? ', sensor' : ', 10 m')
562
+ $('nPeakLabel').textContent = 'Peak, 10 min' + (state.gustH === 'sensor' ? ', sensor' : '')
563
+ showLive()
564
+ }
565
+
566
+ document.querySelector('nav').addEventListener('click', function (e) {
567
+ var b = e.target
568
+ if (b.tagName !== 'BUTTON') return
569
+ if (b.id === 'night') state.night = !state.night
570
+ else {
571
+ var key = b.parentNode.getAttribute('data-key')
572
+ var changed = state[key] !== b.getAttribute('data-v')
573
+ state[key] = b.getAttribute('data-v')
574
+ if (key === 'range' && changed) { points = []; selected = -1; $('readout').style.display = 'none'; showMessage('Loading wind history…'); draw(); loadHistory() }
575
+ }
576
+ save(); syncButtons(); draw()
577
+ })
578
+
579
+ var resizeTimer = null
580
+ window.addEventListener('resize', function () { clearTimeout(resizeTimer); resizeTimer = setTimeout(function () { applyScale(); draw() }, 150) })
581
+ setInterval(function () { if (selected < 0) draw() }, 30000)
582
+ // Coming back to the app (OneHelm keeps it in the background): reload at once.
583
+ function wake () { if (!document.hidden) loadHistory() }
584
+ document.addEventListener('visibilitychange', wake)
585
+ window.addEventListener('focus', wake)
586
+ window.addEventListener('pageshow', function (e) { if (e.persisted) loadHistory() })
587
+
588
+ syncButtons()
589
+ draw()
590
+ loadClock()
591
+ loadLive()
592
+ loadHistory()
593
+ })()
594
+ </script>
595
+ </body>
596
+ </html>