signalk-polar-performance-plugin 1.4.0 → 2.1.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/public/index.html CHANGED
@@ -82,9 +82,7 @@
82
82
  <ul id="main-nav" class="nav">
83
83
  <li class="nav-item"><a class="nav-link active" href="#" data-page="overview">Overview</a></li>
84
84
  <li class="nav-item"><a class="nav-link" href="#" data-page="inputs">Inputs</a></li>
85
- <li class="nav-item"><a class="nav-link" href="#" data-page="settings">Polar</a></li>
86
85
  <li class="nav-item"><a class="nav-link" href="#" data-page="outputs">Outputs</a></li>
87
- <li class="nav-item"><a class="nav-link" href="#" data-page="polars">Polar management</a></li>
88
86
  </ul>
89
87
  </nav>
90
88
  <button class="sidebar-minimizer brand-minimizer" type="button" id="sidebarMinimizer"></button>
@@ -126,19 +126,12 @@
126
126
 
127
127
  <div class="settings-row">
128
128
  <span class="settings-row-label">Active polar</span>
129
- <button id="btn-polar-current" aria-label="Select polar">
130
- <span id="polar-name-display">—</span>
131
- <span class="polar-arrow">›</span>
132
- </button>
129
+ <span id="polar-name-display">—</span>
133
130
  </div>
134
131
 
135
132
  <div class="settings-row">
136
133
  <span class="settings-row-label">Performance</span>
137
- <div class="stepper">
138
- <button class="btn-step" id="btn-perf-minus" aria-label="Decrease">−</button>
139
- <span class="stepper-value" id="perf-display">100%</span>
140
- <button class="btn-step" id="btn-perf-plus" aria-label="Increase">+</button>
141
- </div>
134
+ <span id="perf-display">100%</span>
142
135
  </div>
143
136
 
144
137
  <div class="settings-row">
@@ -147,15 +140,6 @@
147
140
  </div>
148
141
  </div>
149
142
 
150
- <!-- Polar picker (opens on top of settings panel) -->
151
- <div id="polar-list-panel" class="overlay" style="z-index:30" role="dialog" aria-label="Select polar">
152
- <div class="panel-header">
153
- <button class="btn-icon" id="btn-back-from-polar" aria-label="Back">‹</button>
154
- <span class="panel-header-title">Select polar</span>
155
- </div>
156
- <div id="polar-list-items"></div>
157
- </div>
158
-
159
143
  <script src="polar-canvas.js"></script>
160
144
  <script>
161
145
  (function () {
@@ -189,10 +173,11 @@
189
173
  let libraryVersion = '' // change detector
190
174
  let liveTws = null // last fetched live TWS (m/s)
191
175
  let liveCurve = null // interpolated curve for liveTws
192
- let activePolarId = null // current active polar id
193
176
 
194
- // Settings state — kept in sync with the server
195
- let perfAdjust = 1 // multiplier (1 = 100%)
177
+ // Active polar / performance factor are read-only here — selected in a
178
+ // separate polar management webapp (e.g. signalk-polar-management).
179
+ let activePolarName = null
180
+ let performanceFactor = 1
196
181
  let showAllTwsLines = true
197
182
 
198
183
  // -----------------------------------------------------------------------
@@ -220,26 +205,16 @@
220
205
  // -----------------------------------------------------------------------
221
206
 
222
207
  async function refreshLibrary() {
223
- // Resolve active polar ID first
224
- let polarId
225
- try {
226
- const active = await fetchJSON(BASE + '/polars/active')
227
- polarId = active.id
228
- } catch (_) {
229
- return // no active polar — try again on next cycle
230
- }
231
-
232
208
  let newList
233
209
  try {
234
- newList = await fetchJSON(BASE + '/polars/' + polarId + '/axes/tws')
210
+ newList = await fetchJSON(BASE + '/polar/axes/tws')
235
211
  } catch (_) {
236
- return // polar not yet loaded — try again on next cycle
212
+ return // no active polar yet — try again on next cycle
237
213
  }
238
214
 
239
- const version = polarId + ':' + JSON.stringify(newList)
215
+ const version = JSON.stringify(newList)
240
216
  if (version === libraryVersion) return // no change
241
217
 
242
- activePolarId = polarId
243
218
  libraryVersion = version
244
219
  twsList = newList
245
220
  curves = {}
@@ -248,7 +223,7 @@
248
223
  await Promise.all(twsList.map(async (tws) => {
249
224
  try {
250
225
  curves[tws] = await fetchJSON(
251
- BASE + '/polars/' + polarId + '/queries/curve?tws=' + tws + '&step=' + STEP
226
+ BASE + '/polar/queries/curve?tws=' + tws + '&step=' + STEP
252
227
  )
253
228
  } catch (_) { /* skip individual failure */ }
254
229
  }))
@@ -272,10 +247,10 @@
272
247
  // -----------------------------------------------------------------------
273
248
 
274
249
  async function fetchCurveForTws(tws) {
275
- if (!Number.isFinite(tws) || tws <= 0 || !activePolarId) return null
250
+ if (!Number.isFinite(tws) || tws <= 0) return null
276
251
  try {
277
252
  return await fetchJSON(
278
- BASE + '/polars/' + activePolarId + '/queries/curve?tws=' + tws.toFixed(5) + '&step=' + STEP
253
+ BASE + '/polar/queries/curve?tws=' + tws.toFixed(5) + '&step=' + STEP
279
254
  )
280
255
  } catch (_) {
281
256
  return null
@@ -311,12 +286,16 @@
311
286
  async function loadSettings() {
312
287
  try {
313
288
  const s = await fetchJSON(BASE + '/settings')
314
- perfAdjust = Number.isFinite(s.perfAdjust) ? s.perfAdjust : 1
315
289
  showAllTwsLines = s.showAllTwsLines !== false
316
- updatePerfDisplay()
317
290
  updateTwsToggle()
318
291
  polar.setShowAllTwsLines(showAllTwsLines)
319
292
  } catch (_) { /* keep defaults */ }
293
+ try {
294
+ const m = await fetchJSON(BASE + '/meta')
295
+ activePolarName = m.activePolar ? (m.activePolar.name || m.activePolar.id) : null
296
+ performanceFactor = Number.isFinite(m.performanceFactor) ? m.performanceFactor : 1
297
+ updatePerfDisplay()
298
+ } catch (_) { /* keep defaults */ }
320
299
  }
321
300
 
322
301
  // -----------------------------------------------------------------------
@@ -324,14 +303,12 @@
324
303
  // -----------------------------------------------------------------------
325
304
 
326
305
  var settingsPanel = document.getElementById('settings-panel')
327
- var polarListPanel = document.getElementById('polar-list-panel')
328
306
  var perfDisplay = document.getElementById('perf-display')
329
307
  var twsToggle = document.getElementById('btn-tws-toggle')
330
308
  var polarNameEl = document.getElementById('polar-name-display')
331
- var polarListEl = document.getElementById('polar-list-items')
332
309
 
333
310
  function updatePerfDisplay() {
334
- perfDisplay.textContent = Math.round(perfAdjust * 100) + '%'
311
+ perfDisplay.textContent = Math.round(performanceFactor * 100) + '%'
335
312
  }
336
313
 
337
314
  function updateTwsToggle() {
@@ -347,14 +324,7 @@
347
324
  // Open settings: fetch fresh state first
348
325
  document.getElementById('btn-settings').addEventListener('click', function () {
349
326
  loadSettings().then(function () {
350
- // Update active polar name display
351
- if (activePolarId) {
352
- fetchJSON(BASE + '/polars/' + activePolarId)
353
- .then(function (p) { polarNameEl.textContent = p.name || activePolarId })
354
- .catch(function () { polarNameEl.textContent = activePolarId })
355
- } else {
356
- polarNameEl.textContent = '—'
357
- }
327
+ polarNameEl.textContent = activePolarName || '—'
358
328
  settingsPanel.classList.add('open')
359
329
  })
360
330
  })
@@ -363,25 +333,6 @@
363
333
  settingsPanel.classList.remove('open')
364
334
  })
365
335
 
366
- // Performance stepper — ±5%, clamped 50%–200%
367
- function applyPerfAdjust(next) {
368
- if (next === perfAdjust) return
369
- perfAdjust = next
370
- updatePerfDisplay()
371
- putJSON(BASE + '/settings', { perfAdjust: perfAdjust }).then(function () {
372
- libraryVersion = '' // force full curve reload — perfAdjust changes speeds but not the TWS list
373
- return refreshLibrary()
374
- }).catch(function () {})
375
- }
376
-
377
- document.getElementById('btn-perf-minus').addEventListener('click', function () {
378
- applyPerfAdjust(Math.max(0.5, Math.round((perfAdjust - 0.05) * 100) / 100))
379
- })
380
-
381
- document.getElementById('btn-perf-plus').addEventListener('click', function () {
382
- applyPerfAdjust(Math.min(2.0, Math.round((perfAdjust + 0.05) * 100) / 100))
383
- })
384
-
385
336
  // TWS toggle
386
337
  twsToggle.addEventListener('click', function () {
387
338
  showAllTwsLines = !showAllTwsLines
@@ -390,43 +341,6 @@
390
341
  putJSON(BASE + '/settings', { showAllTwsLines: showAllTwsLines }).catch(function () {})
391
342
  })
392
343
 
393
- // Polar picker
394
- document.getElementById('btn-polar-current').addEventListener('click', function () {
395
- polarListEl.innerHTML = ''
396
- fetchJSON(BASE + '/polars').then(function (list) {
397
- list.forEach(function (p) {
398
- var btn = document.createElement('button')
399
- btn.className = 'polar-item' + (p.id === activePolarId ? ' is-active' : '')
400
- var nameSpan = document.createElement('span')
401
- nameSpan.className = 'polar-item-name'
402
- nameSpan.textContent = p.name || p.id
403
- btn.appendChild(nameSpan)
404
- if (p.id === activePolarId) {
405
- var check = document.createElement('span')
406
- check.className = 'polar-item-check'
407
- check.textContent = '✓'
408
- btn.appendChild(check)
409
- }
410
- btn.addEventListener('click', function () {
411
- putJSON(BASE + '/polars/active', { id: p.id })
412
- .then(function () {
413
- polarNameEl.textContent = p.name || p.id
414
- polarListPanel.classList.remove('open')
415
- // Force library refresh on next cycle
416
- libraryVersion = ''
417
- })
418
- .catch(function () {})
419
- })
420
- polarListEl.appendChild(btn)
421
- })
422
- polarListPanel.classList.add('open')
423
- }).catch(function () {})
424
- })
425
-
426
- document.getElementById('btn-back-from-polar').addEventListener('click', function () {
427
- polarListPanel.classList.remove('open')
428
- })
429
-
430
344
  // -----------------------------------------------------------------------
431
345
  // Start
432
346
  // -----------------------------------------------------------------------
@@ -5,6 +5,7 @@ const assert = require('node:assert/strict')
5
5
  const fs = require('fs')
6
6
  const path = require('path')
7
7
  const os = require('os')
8
+ const { withRoutePolicies, wrapPluginRoutes } = require('./routePolicyShim')
8
9
 
9
10
  // ---------------------------------------------------------------------------
10
11
  // Minimal app shim
@@ -39,7 +40,7 @@ function makeApp(dataDir) {
39
40
 
40
41
  function freshPlugin(app) {
41
42
  delete require.cache[require.resolve('../plugin/index.js')]
42
- return require('../plugin/index.js')(app)
43
+ return wrapPluginRoutes(require('../plugin/index.js')(app))
43
44
  }
44
45
 
45
46
  // ---------------------------------------------------------------------------
@@ -106,6 +107,25 @@ describe('Plugin lifecycle — start() → stop() → start()', () => {
106
107
  assert.ok(routes.some(r => r.startsWith('GET')), 'no GET routes registered')
107
108
  })
108
109
 
110
+ it('applies readonly access only to safe live and polar metadata routes', () => {
111
+ const router = {
112
+ use: () => {},
113
+ get: () => {},
114
+ put: () => {},
115
+ }
116
+ plugin.registerWithRouter(withRoutePolicies(router))
117
+
118
+ assert.deepEqual(Object.fromEntries(router.routePolicies), {
119
+ 'GET /polar/axes/tws': 'readonly',
120
+ 'GET /polar/queries/curve': 'readonly',
121
+ 'GET /live': 'readonly',
122
+ 'GET /status': 'readonly',
123
+ 'GET /meta': 'readonly',
124
+ 'GET /settings': 'admin',
125
+ 'PUT /settings': 'admin',
126
+ })
127
+ })
128
+
109
129
  it('registerWithRouter + start() + stop() + start() does not throw', () => {
110
130
  const router = {
111
131
  use: () => {},
@@ -116,4 +136,73 @@ describe('Plugin lifecycle — start() → stop() → start()', () => {
116
136
  plugin.stop()
117
137
  assert.doesNotThrow(() => plugin.start({}))
118
138
  })
139
+
140
+ it('keeps subscriptions through silence and receives resumed wind without replay', t => {
141
+ t.mock.timers.enable({ apis: ['setTimeout', 'Date'] })
142
+ const subscribers = new Map()
143
+ let subscriptions = 0
144
+ let unsubscriptions = 0
145
+ let messages = 0
146
+ app.handleMessage = () => { messages++ }
147
+ app.subscriptionmanager.subscribe = (msg, unsubscribes, _err, callback) => {
148
+ subscriptions++
149
+ for (const { path } of msg.subscribe) {
150
+ if (!subscribers.has(path)) subscribers.set(path, new Set())
151
+ subscribers.get(path).add(callback)
152
+ }
153
+ unsubscribes.push(() => {
154
+ unsubscriptions++
155
+ for (const { path } of msg.subscribe) subscribers.get(path).delete(callback)
156
+ })
157
+ }
158
+ const routes = {}
159
+ plugin.registerWithRouter({
160
+ use: () => {}, get: (p, cb) => { routes[p] = cb },
161
+ put: (p, cb) => { routes[`PUT ${p}`] = cb }, post: () => {}, delete: () => {}
162
+ })
163
+ plugin.start({ tackTrue: true })
164
+ const deliver = (path, value) => {
165
+ for (const callback of subscribers.get(path)) {
166
+ callback({ updates: [{ values: [{ path, value }] }] })
167
+ }
168
+ }
169
+ deliver('environment.wind.speedTrue', 5)
170
+ deliver('environment.wind.angleTrueWater', 0.4)
171
+ const initialSubscriptions = subscriptions
172
+ const initialMessages = messages
173
+ t.mock.timers.tick(120000)
174
+ assert.equal(subscriptions, initialSubscriptions)
175
+ assert.equal(unsubscriptions, 0)
176
+ assert.equal(messages, initialMessages, 'silence must not publish cached inputs')
177
+ let status
178
+ routes['/status']({}, { json: value => { status = value } })
179
+ for (const id of ['wind.smoothed', 'bsp.smoothed', 'hdg.smoothed']) {
180
+ const warning = status.lifecycleWarnings.find(w => w.id === id)
181
+ assert.equal(warning?.status, 'idle', id)
182
+ assert.doesNotMatch(warning.message, /resubscrib/i)
183
+ }
184
+ assert.equal(status.inputs.smoothed.tws, null)
185
+ deliver('environment.wind.speedTrue', 6)
186
+ deliver('environment.wind.angleTrueWater', 0.5)
187
+ routes['/status']({}, { json: value => { status = value } })
188
+ assert.equal(status.lifecycleWarnings.some(w => w.id === 'wind.smoothed'), false)
189
+ assert.equal(status.inputs.smoothed.tws, 6)
190
+ assert.equal(subscriptions, initialSubscriptions)
191
+
192
+ routes['PUT /settings']({ body: { useSOG: true } }, { json: () => {} })
193
+ assert.equal(subscriptions, initialSubscriptions + 1, 'a source change must still resubscribe')
194
+ assert.equal(unsubscriptions, 1)
195
+ assert.equal(subscribers.get('navigation.speedThroughWater').size, 0)
196
+ assert.equal(subscribers.get('navigation.speedOverGround').size, 1)
197
+
198
+ routes['PUT /settings']({ body: { tackTrue: false } }, { json: () => {} })
199
+ routes['PUT /settings']({ body: { tackTrue: true } }, { json: () => {} })
200
+ const configuredSubscriptions = subscriptions
201
+ const configuredUnsubscriptions = unsubscriptions
202
+ t.mock.timers.tick(120000)
203
+ routes['/status']({}, { json: value => { status = value } })
204
+ assert.equal(status.lifecycleWarnings.find(w => w.id === 'hdg.smoothed')?.status, 'idle')
205
+ assert.equal(subscriptions, configuredSubscriptions)
206
+ assert.equal(unsubscriptions, configuredUnsubscriptions)
207
+ })
119
208
  })
@@ -0,0 +1,304 @@
1
+ 'use strict'
2
+
3
+ const { describe, it, beforeEach, afterEach } = require('node:test')
4
+ const assert = require('node:assert/strict')
5
+ const { Polar } = require('polar-math')
6
+ const { wrapPluginRoutes } = require('./routePolicyShim')
7
+
8
+ const KNOTS = 1 / 1.94384
9
+ const rad = degrees => degrees * Math.PI / 180
10
+ const target = (degrees, knots) => {
11
+ const twa = rad(degrees)
12
+ const tbs = knots * KNOTS
13
+ return { twa, tbs, vmg: tbs * Math.abs(Math.cos(twa)) }
14
+ }
15
+
16
+ const TABLE = {
17
+ kind: 'polarTable', schemaVersion: '1.0.0', name: 'Reference Polar',
18
+ units: { tws: 'm/s', twa: 'rad', boatSpeed: 'm/s' },
19
+ symmetry: { portStarboardSymmetric: true },
20
+ axes: { tws: [4, 12, 24].map(k => k * KNOTS), twa: [52, 60, 75, 90, 110, 120, 135, 150].map(rad) },
21
+ values: { boatSpeedMatrix: [
22
+ [3.66, 3.88, 4, 3.9, 3.7, 3.54, 3.12, 2.56],
23
+ [6.42, 6.58, 6.72, 6.82, 6.89, 6.83, 6.62, 6.25],
24
+ [6.69, 6.91, 7.27, 7.61, 8.04, 8.44, 8.54, 8.18]
25
+ ].map(row => row.map(k => k * KNOTS)) },
26
+ derived: { rows: [
27
+ { tws: 4 * KNOTS, beat: target(43.2, 3.24), run: target(147.5, 2.63) },
28
+ { tws: 12 * KNOTS, beat: target(39.6, 5.84), run: target(162.4, 5.83) },
29
+ { tws: 24 * KNOTS, beat: target(40.6, 6.11), run: target(178.6, 7.63) }
30
+ ] }
31
+ }
32
+
33
+ // Downwind-only polar: no beat targets exist, so upwind targets are unavailable.
34
+ const DOWNWIND_ONLY = {
35
+ kind: 'polarTable', schemaVersion: '1.0.0', name: 'Downwind Only',
36
+ units: { tws: 'm/s', twa: 'rad', boatSpeed: 'm/s' },
37
+ symmetry: { portStarboardSymmetric: true },
38
+ axes: { tws: [12 * KNOTS], twa: [90, 120, 150].map(rad) },
39
+ values: { boatSpeedMatrix: [[6.8, 6.8, 6.2].map(k => k * KNOTS)] }
40
+ }
41
+
42
+ // settingsVersion skips migration, which would otherwise force Exponential smoothing
43
+ const ALL_OUTPUTS = {
44
+ settingsVersion: 2, smootherType: 'None',
45
+ beatAngle: true, beatVMG: true, targetTWA: true, optimumWindAngle: true,
46
+ VMG: true, maxSpeed: true, polarSpeed: true, tackTrue: true, smoothedInputs: true
47
+ }
48
+
49
+ const TWS = 12 * KNOTS
50
+ const reference = Polar.fromTable(TABLE)
51
+ const targets = reference.targetsAt({ tws: TWS }).value
52
+ const close = (actual, expected, msg) =>
53
+ assert.ok(Number.isFinite(actual) && Math.abs(actual - expected) < 1e-9, `${msg}: ${actual} != ${expected}`)
54
+
55
+ function harness(table = TABLE) {
56
+ const subscribers = new Map()
57
+ const bus = new Map() // latest value per path written by the plugin
58
+ const writes = [] // every { path, value } written, in order
59
+ const app = {
60
+ debug: () => {}, error: () => {},
61
+ setPluginStatus: () => {}, setPluginError: () => {},
62
+ savePluginOptions: (_o, cb) => cb(null),
63
+ getDataDirPath: () => '.',
64
+ handleMessage: (_id, delta) => {
65
+ for (const update of delta.updates) {
66
+ for (const { path, value } of update.values || []) {
67
+ bus.set(path, value)
68
+ writes.push({ path, value })
69
+ }
70
+ }
71
+ },
72
+ resourcesApi: {
73
+ listResources: async () => ({}),
74
+ getResource: async () => table
75
+ },
76
+ subscriptionmanager: {
77
+ subscribe: (msg, unsubscribes, _err, callback) => {
78
+ for (const { path } of msg.subscribe) {
79
+ if (!subscribers.has(path)) subscribers.set(path, new Set())
80
+ subscribers.get(path).add(callback)
81
+ }
82
+ unsubscribes.push(() => {
83
+ for (const { path } of msg.subscribe) subscribers.get(path).delete(callback)
84
+ })
85
+ }
86
+ }
87
+ }
88
+ delete require.cache[require.resolve('../plugin/index.js')]
89
+ const plugin = wrapPluginRoutes(require('../plugin/index.js')(app))
90
+ const routes = {}
91
+ plugin.registerWithRouter({
92
+ use: () => {}, get: (p, cb) => { routes[p] = cb },
93
+ put: (p, cb) => { routes[`PUT ${p}`] = cb }, post: () => {}, delete: () => {}
94
+ })
95
+
96
+ const deliver = (path, value) => {
97
+ for (const callback of subscribers.get(path) || []) {
98
+ callback({ updates: [{ $source: 'test', values: [{ path, value }] }] })
99
+ }
100
+ }
101
+ return {
102
+ app, plugin, bus, writes, routes, deliver,
103
+ async start(options = ALL_OUTPUTS) {
104
+ plugin.start(options)
105
+ deliver('polars.activePolar', { href: '/resources/polars/ref' })
106
+ await new Promise(resolve => setImmediate(resolve))
107
+ },
108
+ sail({ tws = TWS, twa, bsp, hdg }) {
109
+ if (bsp !== undefined) deliver('navigation.speedThroughWater', bsp)
110
+ if (hdg !== undefined) deliver('navigation.headingTrue', hdg)
111
+ deliver('environment.wind.speedTrue', tws)
112
+ deliver('environment.wind.angleTrueWater', twa)
113
+ },
114
+ status() {
115
+ let result
116
+ routes['/status']({}, { json: value => { result = value } })
117
+ return result
118
+ }
119
+ }
120
+ }
121
+
122
+ describe('computeAndSend output validity', () => {
123
+ let h
124
+
125
+ beforeEach(() => { h = harness() })
126
+ afterEach(() => {
127
+ try { h.plugin.stop() } catch (_) {}
128
+ delete require.cache[require.resolve('../plugin/index.js')]
129
+ })
130
+
131
+ it('publishes every output while sailing normally upwind on starboard', async () => {
132
+ await h.start()
133
+ const twa = rad(50)
134
+ const bsp = 6 * KNOTS
135
+ h.sail({ twa, bsp, hdg: 1 })
136
+ const polarSpeed = reference.speedAt({ tws: TWS, twa }).value
137
+ const vmg = bsp * Math.cos(twa)
138
+ close(h.bus.get('performance.polarSpeed'), polarSpeed, 'polarSpeed')
139
+ close(h.bus.get('performance.polarSpeedRatio'), bsp / polarSpeed, 'polarSpeedRatio')
140
+ close(h.bus.get('performance.targetSpeed'), targets.beat.vmg / Math.cos(targets.beat.twa), 'targetSpeed')
141
+ close(h.bus.get('performance.targetAngle'), targets.beat.twa, 'targetAngle')
142
+ close(h.bus.get('performance.targetVelocityMadeGood'), targets.beat.vmg, 'targetVMG')
143
+ close(h.bus.get('performance.velocityMadeGood'), vmg, 'VMG')
144
+ close(h.bus.get('performance.polarVelocityMadeGood'), targets.beat.vmg, 'polarVMG')
145
+ close(h.bus.get('performance.polarVelocityMadeGoodRatio'), vmg / targets.beat.vmg, 'VMG ratio')
146
+ close(h.bus.get('performance.beatAngle'), targets.beat.twa, 'beatAngle')
147
+ close(h.bus.get('performance.gybeAngle'), targets.run.twa, 'gybeAngle')
148
+ close(h.bus.get('performance.optimumWindAngle'), twa - targets.beat.twa, 'optimumWindAngle')
149
+ close(h.bus.get('performance.tackTrue'), 1 + targets.beat.twa, 'tackTrue')
150
+ close(h.bus.get('environment.wind.angleTrueWaterDamped'), twa, 'damped TWA')
151
+ close(h.bus.get('performance.boatSpeedDamped'), bsp, 'damped BSP')
152
+ })
153
+
154
+ it('in irons clears polar values, keeps steering advice and VMG live, and restores them on leaving', async () => {
155
+ await h.start()
156
+ const bsp = 4 * KNOTS
157
+ h.sail({ twa: rad(50), bsp, hdg: 1 })
158
+ assert.ok(h.bus.get('performance.polarSpeed') > 0)
159
+
160
+ const ironsTwa = rad(20)
161
+ assert.equal(reference.speedAt({ tws: TWS, twa: ironsTwa }).state.twa, 'in_irons')
162
+ h.sail({ twa: ironsTwa, bsp, hdg: 1 })
163
+ for (const path of ['performance.polarSpeed', 'performance.polarSpeedRatio', 'performance.targetSpeed',
164
+ 'performance.targetVelocityMadeGood', 'performance.polarVelocityMadeGood',
165
+ 'performance.polarVelocityMadeGoodRatio', 'performance.beatAngle', 'performance.gybeAngle',
166
+ 'performance.beatAngleVelocityMadeGood', 'performance.gybeAngleVelocityMadeGood',
167
+ 'performance.maxSpeed', 'performance.maxSpeedAngle']) {
168
+ assert.equal(h.bus.get(path), null, path)
169
+ }
170
+ close(h.bus.get('performance.targetAngle'), targets.beat.twa, 'targetAngle in irons')
171
+ close(h.bus.get('performance.optimumWindAngle'), ironsTwa - targets.beat.twa, 'optimumWindAngle in irons')
172
+ close(h.bus.get('performance.tackTrue'), 1 + targets.beat.twa, 'tackTrue in irons')
173
+ close(h.bus.get('performance.velocityMadeGood'), bsp * Math.cos(ironsTwa), 'VMG in irons')
174
+
175
+ // VMG must keep updating while in irons, not freeze
176
+ h.sail({ twa: ironsTwa, bsp: 2 * KNOTS })
177
+ close(h.bus.get('performance.velocityMadeGood'), 2 * KNOTS * Math.cos(ironsTwa), 'VMG updates in irons')
178
+
179
+ const status = h.status()
180
+ assert.equal(status.outputs['performance.polarSpeed'], null)
181
+ assert.equal(status.outputs['performance.targetSpeed'], null)
182
+
183
+ // Pinching is not in irons, so nothing is cleared
184
+ const pinchTwa = rad(38)
185
+ assert.equal(reference.speedAt({ tws: TWS, twa: pinchTwa }).state.twa, 'pinching')
186
+ h.sail({ twa: pinchTwa, bsp })
187
+ close(h.bus.get('performance.targetSpeed'), targets.beat.vmg / Math.cos(targets.beat.twa), 'targetSpeed pinching')
188
+ close(h.bus.get('performance.targetVelocityMadeGood'), targets.beat.vmg, 'targetVMG pinching')
189
+ close(h.bus.get('performance.polarVelocityMadeGood'), targets.beat.vmg, 'polarVMG pinching')
190
+ close(h.bus.get('performance.polarVelocityMadeGoodRatio'), bsp * Math.cos(pinchTwa) / targets.beat.vmg, 'ratio pinching')
191
+ close(h.bus.get('performance.beatAngle'), targets.beat.twa, 'beatAngle pinching')
192
+ assert.ok(h.bus.get('performance.maxSpeed') > 0)
193
+
194
+ h.sail({ twa: rad(50), bsp })
195
+ const polarSpeed = reference.speedAt({ tws: TWS, twa: rad(50) }).value
196
+ close(h.bus.get('performance.polarSpeed'), polarSpeed, 'polarSpeed after irons')
197
+ close(h.bus.get('performance.polarSpeedRatio'), bsp / polarSpeed, 'ratio after irons')
198
+ close(h.bus.get('performance.targetSpeed'), targets.beat.vmg / Math.cos(targets.beat.twa), 'targetSpeed after irons')
199
+ })
200
+
201
+ it('clears unavailable outputs only once per transition', async () => {
202
+ await h.start()
203
+ h.sail({ twa: rad(50), bsp: 4 * KNOTS })
204
+ h.sail({ twa: rad(20), bsp: 4 * KNOTS })
205
+ h.sail({ twa: rad(21), bsp: 4 * KNOTS })
206
+ const polarSpeedNulls = h.writes.filter(w => w.path === 'performance.polarSpeed' && w.value === null)
207
+ assert.equal(polarSpeedNulls.length, 1)
208
+ })
209
+
210
+ it('mirrors signed angles and keeps magnitudes on port tack', async () => {
211
+ await h.start()
212
+ const twa = rad(-50)
213
+ const bsp = 6 * KNOTS
214
+ h.sail({ twa, bsp, hdg: 1 })
215
+ close(h.bus.get('performance.targetAngle'), -targets.beat.twa, 'targetAngle port')
216
+ close(h.bus.get('performance.beatAngle'), -targets.beat.twa, 'beatAngle port')
217
+ close(h.bus.get('performance.optimumWindAngle'), -(rad(50) - targets.beat.twa), 'optimumWindAngle port')
218
+ close(h.bus.get('performance.tackTrue'), 1 - targets.beat.twa, 'tackTrue port')
219
+ close(h.bus.get('performance.targetSpeed'), targets.beat.vmg / Math.cos(targets.beat.twa), 'targetSpeed port')
220
+ close(h.bus.get('performance.velocityMadeGood'), bsp * Math.cos(rad(50)), 'VMG port')
221
+
222
+ h.sail({ twa: rad(-20), bsp })
223
+ assert.equal(h.bus.get('performance.polarSpeed'), null)
224
+ assert.equal(h.bus.get('performance.targetSpeed'), null)
225
+ assert.equal(h.bus.get('performance.targetVelocityMadeGood'), null)
226
+ assert.equal(h.bus.get('performance.beatAngle'), null)
227
+ close(h.bus.get('performance.targetAngle'), -targets.beat.twa, 'targetAngle port irons')
228
+ close(h.bus.get('performance.optimumWindAngle'), -(rad(20) - targets.beat.twa), 'optimumWindAngle port irons')
229
+ close(h.bus.get('performance.tackTrue'), 1 - targets.beat.twa, 'tackTrue port irons')
230
+ })
231
+
232
+ it('selects run targets when sailing downwind', async () => {
233
+ await h.start()
234
+ const twa = rad(150)
235
+ const bsp = 6 * KNOTS
236
+ h.sail({ twa, bsp, hdg: 1 })
237
+ const vmg = bsp * Math.cos(twa)
238
+ close(h.bus.get('performance.targetAngle'), targets.run.twa, 'run targetAngle')
239
+ close(h.bus.get('performance.targetVelocityMadeGood'), targets.run.vmg, 'run targetVMG')
240
+ close(h.bus.get('performance.targetSpeed'), targets.run.vmg / Math.abs(Math.cos(targets.run.twa)), 'run targetSpeed')
241
+ close(h.bus.get('performance.velocityMadeGood'), vmg, 'downwind VMG is negative')
242
+ assert.ok(vmg < 0)
243
+ close(h.bus.get('performance.polarVelocityMadeGoodRatio'), Math.abs(vmg) / targets.run.vmg, 'downwind ratio')
244
+ close(h.bus.get('performance.optimumWindAngle'), twa - targets.run.twa, 'downwind optimumWindAngle')
245
+ close(h.bus.get('performance.tackTrue'), 1 + targets.run.twa, 'downwind tackTrue')
246
+ })
247
+
248
+ it('clears BSP-dependent outputs when boat speed is missing', async () => {
249
+ await h.start()
250
+ h.sail({ twa: rad(50), bsp: 6 * KNOTS })
251
+ assert.ok(h.bus.get('performance.velocityMadeGood') > 0)
252
+ h.sail({ twa: rad(50), bsp: null })
253
+ for (const path of ['performance.velocityMadeGood', 'performance.polarVelocityMadeGoodRatio',
254
+ 'performance.polarSpeedRatio', 'performance.boatSpeedDamped']) {
255
+ assert.equal(h.bus.get(path), null, path)
256
+ }
257
+ assert.ok(h.bus.get('performance.polarSpeed') > 0)
258
+ assert.ok(h.bus.get('performance.targetSpeed') > 0)
259
+ close(h.bus.get('performance.polarVelocityMadeGood'), targets.beat.vmg, 'polarVMG without BSP')
260
+ })
261
+
262
+ it('clears target-dependent outputs when polar targets are unavailable', async () => {
263
+ h = harness(DOWNWIND_ONLY)
264
+ await h.start()
265
+ const noBeat = Polar.fromTable(DOWNWIND_ONLY).targetsAt({ tws: TWS }).value
266
+ assert.equal(noBeat.beat, null)
267
+
268
+ h.sail({ twa: rad(150), bsp: 6 * KNOTS, hdg: 1 })
269
+ assert.ok(h.bus.get('performance.targetSpeed') > 0)
270
+ assert.ok(h.bus.get('performance.polarVelocityMadeGood') > 0)
271
+
272
+ h.sail({ twa: rad(60), bsp: 6 * KNOTS, hdg: 1 })
273
+ for (const path of ['performance.targetSpeed', 'performance.targetAngle',
274
+ 'performance.targetVelocityMadeGood', 'performance.polarVelocityMadeGood',
275
+ 'performance.polarVelocityMadeGoodRatio', 'performance.beatAngle',
276
+ 'performance.beatAngleVelocityMadeGood', 'performance.optimumWindAngle', 'performance.tackTrue']) {
277
+ assert.equal(h.bus.get(path), null, path)
278
+ }
279
+ close(h.bus.get('performance.velocityMadeGood'), 6 * KNOTS * Math.cos(rad(60)), 'actual VMG without targets')
280
+ })
281
+
282
+ it('does not publish disabled outputs and clears outputs toggled off or on stop', async () => {
283
+ await h.start({ settingsVersion: 2, smootherType: 'None', polarSpeed: true })
284
+ h.sail({ twa: rad(50), bsp: 4 * KNOTS })
285
+ const published = new Set(h.writes.map(w => w.path))
286
+ assert.deepEqual([...published].sort(),
287
+ ['performance.polarSpeed', 'performance.polarSpeedRatio', 'performance.targetSpeed'])
288
+ assert.ok(h.bus.get('performance.targetSpeed') > 0)
289
+
290
+ h.routes['PUT /settings']({ body: { polarSpeed: false } }, { json: () => {} })
291
+ assert.equal(h.bus.get('performance.targetSpeed'), null)
292
+ const before = h.writes.length
293
+ h.sail({ twa: rad(50), bsp: 4 * KNOTS })
294
+ assert.equal(h.writes.length, before, 'disabled outputs must not be written')
295
+
296
+ h.routes['PUT /settings']({ body: { polarSpeed: true } }, { json: () => {} })
297
+ h.sail({ twa: rad(50), bsp: 4 * KNOTS })
298
+ assert.ok(h.bus.get('performance.polarSpeed') > 0)
299
+ h.plugin.stop()
300
+ for (const path of ['performance.polarSpeed', 'performance.targetSpeed', 'performance.polarSpeedRatio']) {
301
+ assert.equal(h.bus.get(path), null, path)
302
+ }
303
+ })
304
+ })