signalk-sailboat-simulator 0.0.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/LICENSE +183 -0
- package/README.md +181 -2
- package/index.js +491 -0
- package/lib/angles.js +28 -0
- package/lib/geo.js +45 -0
- package/lib/plugin-schema.js +121 -0
- package/lib/simulation-engine.js +84 -0
- package/lib/state-store.js +90 -0
- package/lib/wind.js +42 -0
- package/package.json +40 -6
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [0.2.0] - 2026-08-17
|
|
4
|
+
|
|
5
|
+
- Follow `steering.autopilot.output.turnRate` from `signalk-autopilot-emulator-v2` directly instead of deriving and rate-limiting turns from autopilot target headings.
|
|
6
|
+
- Remove simulator-side heading target and wind steering logic; the autopilot emulator is now responsible for producing the turn-rate output.
|
|
7
|
+
- Keep simulator steering based on true heading and publish `navigation.headingMagnetic` only when `navigation.magneticVariation` is available.
|
|
8
|
+
|
|
9
|
+
## [0.1.0] - 2026-08-14
|
|
10
|
+
|
|
11
|
+
- Initial public release.
|
|
12
|
+
- Add a testable sailing simulation engine driven by autopilot targets and `performance.polarSpeed`.
|
|
13
|
+
- Read true wind from the Signal K Weather API at the simulated position, with observation-first and closest-forecast fallback.
|
|
14
|
+
- Publish true and apparent wind values for polar performance calculations.
|
|
15
|
+
- Add optional grounding protection from `navigation.distanceToShore` and `navigation.shore.bearingTrue`.
|
|
16
|
+
- Add persisted runtime state so the simulated vessel resumes after Signal K restarts.
|
|
17
|
+
- Keep configuration focused on initial state, wind publishing, navigation publishing, grounding protection and persistence.
|
|
18
|
+
- Recommend the companion plugins used for a complete simulation setup.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction, and
|
|
10
|
+
distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright
|
|
13
|
+
owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities
|
|
16
|
+
that control, are controlled by, or are under common control with that entity.
|
|
17
|
+
For the purposes of this definition, "control" means (i) the power, direct or
|
|
18
|
+
indirect, to cause the direction or management of such entity, whether by
|
|
19
|
+
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
20
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
21
|
+
|
|
22
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising
|
|
23
|
+
permissions granted by this License.
|
|
24
|
+
|
|
25
|
+
"Source" form shall mean the preferred form for making modifications, including
|
|
26
|
+
but not limited to software source code, documentation source, and configuration
|
|
27
|
+
files.
|
|
28
|
+
|
|
29
|
+
"Object" form shall mean any form resulting from mechanical transformation or
|
|
30
|
+
translation of a Source form, including but not limited to compiled object code,
|
|
31
|
+
generated documentation, and conversions to other media types.
|
|
32
|
+
|
|
33
|
+
"Work" shall mean the work of authorship, whether in Source or Object form,
|
|
34
|
+
made available under the License, as indicated by a copyright notice that is
|
|
35
|
+
included in or attached to the work (an example is provided in the Appendix
|
|
36
|
+
below).
|
|
37
|
+
|
|
38
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that
|
|
39
|
+
is based on (or derived from) the Work and for which the editorial revisions,
|
|
40
|
+
annotations, elaborations, or other modifications represent, as a whole, an
|
|
41
|
+
original work of authorship. For the purposes of this License, Derivative Works
|
|
42
|
+
shall not include works that remain separable from, or merely link (or bind by
|
|
43
|
+
name) to the interfaces of, the Work and Derivative Works thereof.
|
|
44
|
+
|
|
45
|
+
"Contribution" shall mean any work of authorship, including the original version
|
|
46
|
+
of the Work and any modifications or additions to that Work or Derivative Works
|
|
47
|
+
thereof, that is intentionally submitted to Licensor for inclusion in the Work
|
|
48
|
+
by the copyright owner or by an individual or Legal Entity authorized to submit
|
|
49
|
+
on behalf of the copyright owner. For the purposes of this definition,
|
|
50
|
+
"submitted" means any form of electronic, verbal, or written communication sent
|
|
51
|
+
to the Licensor or its representatives, including but not limited to
|
|
52
|
+
communication on electronic mailing lists, source code control systems, and
|
|
53
|
+
issue tracking systems that are managed by, or on behalf of, the Licensor for
|
|
54
|
+
the purpose of discussing and improving the Work, but excluding communication
|
|
55
|
+
that is conspicuously marked or otherwise designated in writing by the copyright
|
|
56
|
+
owner as "Not a Contribution."
|
|
57
|
+
|
|
58
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
|
|
59
|
+
of whom a Contribution has been received by Licensor and subsequently
|
|
60
|
+
incorporated within the Work.
|
|
61
|
+
|
|
62
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this
|
|
63
|
+
License, each Contributor hereby grants to You a perpetual, worldwide,
|
|
64
|
+
non-exclusive, no-charge, royalty-free, irrevocable copyright license to
|
|
65
|
+
reproduce, prepare Derivative Works of, publicly display, publicly perform,
|
|
66
|
+
sublicense, and distribute the Work and such Derivative Works in Source or
|
|
67
|
+
Object form.
|
|
68
|
+
|
|
69
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License,
|
|
70
|
+
each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
|
|
71
|
+
no-charge, royalty-free, irrevocable (except as stated in this section) patent
|
|
72
|
+
license to make, have made, use, offer to sell, sell, import, and otherwise
|
|
73
|
+
transfer the Work, where such license applies only to those patent claims
|
|
74
|
+
licensable by such Contributor that are necessarily infringed by their
|
|
75
|
+
Contribution(s) alone or by combination of their Contribution(s) with the Work
|
|
76
|
+
to which such Contribution(s) was submitted. If You institute patent litigation
|
|
77
|
+
against any entity (including a cross-claim or counterclaim in a lawsuit)
|
|
78
|
+
alleging that the Work or a Contribution incorporated within the Work
|
|
79
|
+
constitutes direct or contributory patent infringement, then any patent licenses
|
|
80
|
+
granted to You under this License for that Work shall terminate as of the date
|
|
81
|
+
such litigation is filed.
|
|
82
|
+
|
|
83
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or
|
|
84
|
+
Derivative Works thereof in any medium, with or without modifications, and in
|
|
85
|
+
Source or Object form, provided that You meet the following conditions:
|
|
86
|
+
|
|
87
|
+
(a) You must give any other recipients of the Work or Derivative Works a copy of
|
|
88
|
+
this License; and
|
|
89
|
+
|
|
90
|
+
(b) You must cause any modified files to carry prominent notices stating that
|
|
91
|
+
You changed the files; and
|
|
92
|
+
|
|
93
|
+
(c) You must retain, in the Source form of any Derivative Works that You
|
|
94
|
+
distribute, all copyright, patent, trademark, and attribution notices from the
|
|
95
|
+
Source form of the Work, excluding those notices that do not pertain to any part
|
|
96
|
+
of the Derivative Works; and
|
|
97
|
+
|
|
98
|
+
(d) If the Work includes a "NOTICE" text file as part of its distribution, then
|
|
99
|
+
any Derivative Works that You distribute must include a readable copy of the
|
|
100
|
+
attribution notices contained within such NOTICE file, excluding those notices
|
|
101
|
+
that do not pertain to any part of the Derivative Works, in at least one of the
|
|
102
|
+
following places: within a NOTICE text file distributed as part of the
|
|
103
|
+
Derivative Works; within the Source form or documentation, if provided along
|
|
104
|
+
with the Derivative Works; or, within a display generated by the Derivative
|
|
105
|
+
Works, if and wherever such third-party notices normally appear. The contents of
|
|
106
|
+
the NOTICE file are for informational purposes only and do not modify the
|
|
107
|
+
License. You may add Your own attribution notices within Derivative Works that
|
|
108
|
+
You distribute, alongside or as an addendum to the NOTICE text from the Work,
|
|
109
|
+
provided that such additional attribution notices cannot be construed as
|
|
110
|
+
modifying the License.
|
|
111
|
+
|
|
112
|
+
You may add Your own copyright statement to Your modifications and may provide
|
|
113
|
+
additional or different license terms and conditions for use, reproduction, or
|
|
114
|
+
distribution of Your modifications, or for any such Derivative Works as a whole,
|
|
115
|
+
provided Your use, reproduction, and distribution of the Work otherwise complies
|
|
116
|
+
with the conditions stated in this License.
|
|
117
|
+
|
|
118
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any
|
|
119
|
+
Contribution intentionally submitted for inclusion in the Work by You to the
|
|
120
|
+
Licensor shall be under the terms and conditions of this License, without any
|
|
121
|
+
additional terms or conditions. Notwithstanding the above, nothing herein shall
|
|
122
|
+
supersede or modify the terms of any separate license agreement you may have
|
|
123
|
+
executed with Licensor regarding such Contributions.
|
|
124
|
+
|
|
125
|
+
6. Trademarks. This License does not grant permission to use the trade names,
|
|
126
|
+
trademarks, service marks, or product names of the Licensor, except as required
|
|
127
|
+
for reasonable and customary use in describing the origin of the Work and
|
|
128
|
+
reproducing the content of the NOTICE file.
|
|
129
|
+
|
|
130
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
|
|
131
|
+
writing, Licensor provides the Work (and each Contributor provides its
|
|
132
|
+
Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
133
|
+
KIND, either express or implied, including, without limitation, any warranties or
|
|
134
|
+
conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
135
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
136
|
+
appropriateness of using or redistributing the Work and assume any risks
|
|
137
|
+
associated with Your exercise of permissions under this License.
|
|
138
|
+
|
|
139
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in
|
|
140
|
+
tort (including negligence), contract, or otherwise, unless required by
|
|
141
|
+
applicable law (such as deliberate and grossly negligent acts) or agreed to in
|
|
142
|
+
writing, shall any Contributor be liable to You for damages, including any
|
|
143
|
+
direct, indirect, special, incidental, or consequential damages of any character
|
|
144
|
+
arising as a result of this License or out of the use or inability to use the
|
|
145
|
+
Work (including but not limited to damages for loss of goodwill, work stoppage,
|
|
146
|
+
computer failure or malfunction, or any and all other commercial damages or
|
|
147
|
+
losses), even if such Contributor has been advised of the possibility of such
|
|
148
|
+
damages.
|
|
149
|
+
|
|
150
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or
|
|
151
|
+
Derivative Works thereof, You may choose to offer, and charge a fee for,
|
|
152
|
+
acceptance of support, warranty, indemnity, or other liability obligations
|
|
153
|
+
and/or rights consistent with this License. However, in accepting such
|
|
154
|
+
obligations, You may act only on Your own behalf and on Your sole
|
|
155
|
+
responsibility, not on behalf of any other Contributor, and only if You agree to
|
|
156
|
+
indemnify, defend, and hold each Contributor harmless for any liability incurred
|
|
157
|
+
by, or claims asserted against, such Contributor by reason of your accepting any
|
|
158
|
+
such warranty or additional liability.
|
|
159
|
+
|
|
160
|
+
END OF TERMS AND CONDITIONS
|
|
161
|
+
|
|
162
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
163
|
+
|
|
164
|
+
To apply the Apache License to your work, attach the following boilerplate
|
|
165
|
+
notice, with the fields enclosed by brackets "[]" replaced with your own
|
|
166
|
+
identifying information. Do not include the brackets. The text should be
|
|
167
|
+
enclosed in the appropriate comment syntax for the file format. We also
|
|
168
|
+
recommend that a file or class name and description of purpose be included on
|
|
169
|
+
the same "printed page" as the copyright notice for easier identification
|
|
170
|
+
within third-party archives.
|
|
171
|
+
|
|
172
|
+
Copyright 2026 Jean-Laurent Girod
|
|
173
|
+
|
|
174
|
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
|
175
|
+
this file except in compliance with the License. You may obtain a copy of the
|
|
176
|
+
License at
|
|
177
|
+
|
|
178
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
179
|
+
|
|
180
|
+
Unless required by applicable law or agreed to in writing, software distributed
|
|
181
|
+
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
|
182
|
+
CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
|
183
|
+
specific language governing permissions and limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,5 +1,184 @@
|
|
|
1
1
|
# Signal K Sailboat Simulator
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Signal K plugin that simulates a sailing boat by integrating a virtual position from data already present in Signal K: autopilot turn-rate output, weather and polar performance.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
The design goal is to keep this plugin small. It publishes only the simulated vessel state and expects specialised plugins to provide autopilot intent, weather and polar calculations.
|
|
6
|
+
|
|
7
|
+
## Quick Start
|
|
8
|
+
|
|
9
|
+
The easiest setup is to use the Signal K App Store:
|
|
10
|
+
|
|
11
|
+
1. Install these recommended plugins:
|
|
12
|
+
- `@signalk/open-meteo-provider`
|
|
13
|
+
- `signalk-autopilot-emulator-v2`
|
|
14
|
+
- `signalk-polar-performance-plugin`
|
|
15
|
+
- `signalk-derived-data`
|
|
16
|
+
- `signalk-distance-to-shore`
|
|
17
|
+
2. Configure `@signalk/open-meteo-provider` and make it the default Signal K Weather API provider. You can also leave the Signal K default as-is and set `wind.providerId` to `open-meteo` in this plugin.
|
|
18
|
+
3. Configure `signalk-polar-performance-plugin` with a polar file for the simulated boat.
|
|
19
|
+
4. Configure `signalk-derived-data` to publish `navigation.magneticVariation`, so the simulator can publish `navigation.headingMagnetic` for plugins that need magnetic heading.
|
|
20
|
+
5. Install and enable `signalk-sailboat-simulator`.
|
|
21
|
+
6. Keep the default simulator options for a first run.
|
|
22
|
+
7. Open the Signal K Data Browser or Freeboard and check that the simulated vessel position, wind and boat speed are updating.
|
|
23
|
+
|
|
24
|
+
CLI installation is also possible from the Signal K settings directory:
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
cd ~/.signalk
|
|
28
|
+
npm install signalk-sailboat-simulator
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Then restart Signal K and enable the plugin from the Server > Plugin Config page.
|
|
32
|
+
|
|
33
|
+
## Recommended Setup
|
|
34
|
+
|
|
35
|
+
Minimum capabilities for a useful simulation:
|
|
36
|
+
|
|
37
|
+
- Autopilot output: `signalk-autopilot-emulator-v2` provides `steering.autopilot.output.turnRate`, which the simulator integrates as the boat heading change.
|
|
38
|
+
- Weather: `@signalk/open-meteo-provider` can provide Weather API observations or forecasts at the simulated position.
|
|
39
|
+
- Polar performance: `signalk-polar-performance-plugin` uses the published true wind values to calculate `performance.polarSpeed`, which the simulator uses as boat speed.
|
|
40
|
+
- Derived data: enable the `signalk-derived-data` option that publishes `navigation.magneticVariation`; when this path is available, the simulator also publishes `navigation.headingMagnetic` for plugins that need magnetic heading.
|
|
41
|
+
- Shore distance: `signalk-distance-to-shore` can provide `navigation.distanceToShore` and `navigation.shore.bearingTrue` for grounding protection.
|
|
42
|
+
|
|
43
|
+
## Verify It Works
|
|
44
|
+
|
|
45
|
+
After enabling the plugin, these paths should update:
|
|
46
|
+
|
|
47
|
+
Navigation:
|
|
48
|
+
|
|
49
|
+
- `navigation.position`
|
|
50
|
+
- `navigation.headingTrue`
|
|
51
|
+
- `navigation.headingMagnetic` when magnetic variation is available
|
|
52
|
+
- `navigation.courseOverGroundTrue`
|
|
53
|
+
- `navigation.speedOverGround`
|
|
54
|
+
- `navigation.speedThroughWater`
|
|
55
|
+
|
|
56
|
+
Wind:
|
|
57
|
+
|
|
58
|
+
- `environment.wind.speedTrue`
|
|
59
|
+
- `environment.wind.directionTrue`
|
|
60
|
+
- `environment.wind.angleTrueWater`
|
|
61
|
+
- `environment.wind.speedApparent`
|
|
62
|
+
- `environment.wind.angleApparent`
|
|
63
|
+
|
|
64
|
+
Performance input expected by the simulator:
|
|
65
|
+
|
|
66
|
+
- `performance.polarSpeed`
|
|
67
|
+
|
|
68
|
+
All values are published with `$source: signalk-sailboat-simulator`.
|
|
69
|
+
|
|
70
|
+
The plugin status will show `waitingForPerformance` until `performance.polarSpeed` is available. If `steering.autopilot.output.turnRate` is missing, the simulated boat keeps its current heading. If grounding protection is enabled and `navigation.distanceToShore` is below the configured minimum, the status will show `groundingProtection` and the simulated boat will stop.
|
|
71
|
+
|
|
72
|
+
## Input contract
|
|
73
|
+
|
|
74
|
+
The simulator reads these fixed Signal K input paths:
|
|
75
|
+
|
|
76
|
+
- `steering.autopilot.output.turnRate`: desired heading change rate in rad/s
|
|
77
|
+
- `navigation.magneticVariation`: optional magnetic variation in radians, used only to publish `navigation.headingMagnetic`
|
|
78
|
+
- `performance.polarSpeed`: boat speed from the active polar in m/s
|
|
79
|
+
- `navigation.distanceToShore`: optional distance to the nearest coast in m, used for grounding protection
|
|
80
|
+
- `navigation.shore.bearingTrue`: optional bearing from the vessel to the nearest coast in radians, used to allow recovery headings away from shore
|
|
81
|
+
|
|
82
|
+
When true or apparent wind publishing is enabled, wind is read from Signal K Weather API data at the simulated position. The simulator first tries observations, then falls back to the closest point forecast when no usable observation is available.
|
|
83
|
+
|
|
84
|
+
By default the simulator uses the Signal K default weather provider. Set `wind.providerId` to a registered provider id, for example `open-meteo`, to use that provider explicitly.
|
|
85
|
+
|
|
86
|
+
When no usable weather data is available yet, for example while the weather provider is still starting up, the simulator retries faster instead of waiting for the normal polling interval.
|
|
87
|
+
|
|
88
|
+
The simulator publishes virtual wind for the rest of the Signal K stack. The publish options are grouped as true wind and apparent wind:
|
|
89
|
+
|
|
90
|
+
- `environment.wind.speedTrue`
|
|
91
|
+
- `environment.wind.directionTrue`
|
|
92
|
+
- `environment.wind.angleTrueWater`
|
|
93
|
+
- `environment.wind.speedApparent`
|
|
94
|
+
- `environment.wind.angleApparent`
|
|
95
|
+
|
|
96
|
+
This gives `signalk-polar-performance-plugin` the `environment.wind.speedTrue` and `environment.wind.angleTrueWater` inputs it needs to calculate `performance.polarSpeed`.
|
|
97
|
+
|
|
98
|
+
The first version uses `performance.polarSpeed` as the boat speed, integrates heading from `steering.autopilot.output.turnRate`, and integrates position along that simulated heading. Current, leeway, route following and manoeuvre rules are intentionally left as separate steps.
|
|
99
|
+
|
|
100
|
+
## Configuration
|
|
101
|
+
|
|
102
|
+
The plugin intentionally keeps its configuration surface small:
|
|
103
|
+
|
|
104
|
+
- `initialState`
|
|
105
|
+
What it does: sets the starting latitude, longitude and true heading for a new simulation.
|
|
106
|
+
Requires: nothing else.
|
|
107
|
+
Options: latitude, longitude and heading in degrees. These values are only used when persistence is disabled or no previous runtime state has been saved.
|
|
108
|
+
|
|
109
|
+
- `wind`
|
|
110
|
+
What it does: reads wind at the simulated position from the Signal K Weather API and publishes the selected wind values.
|
|
111
|
+
Goal: feed `signalk-polar-performance-plugin` with wind data so it can calculate `performance.polarSpeed`, which the simulator then uses as boat speed.
|
|
112
|
+
Requires: a Weather API provider. The recommended provider is `@signalk/open-meteo-provider`; the recommended polar plugin is `signalk-polar-performance-plugin`.
|
|
113
|
+
Options: publish true wind, publish apparent wind, optional provider id, and polling interval.
|
|
114
|
+
Published true wind paths: `environment.wind.speedTrue`, `environment.wind.directionTrue`, `environment.wind.angleTrueWater`.
|
|
115
|
+
Published apparent wind paths: `environment.wind.speedApparent`, `environment.wind.angleApparent`.
|
|
116
|
+
|
|
117
|
+
- `publishing`
|
|
118
|
+
What it does: publishes the simulated navigation state.
|
|
119
|
+
Requires: `steering.autopilot.output.turnRate` to steer and `performance.polarSpeed` to move. Recommended providers are `signalk-autopilot-emulator-v2`, `signalk-polar-performance-plugin`, and `signalk-derived-data` when magnetic heading output is needed.
|
|
120
|
+
Options: publish navigation state.
|
|
121
|
+
Published paths: `navigation.position`, `navigation.headingTrue`, `navigation.headingMagnetic` when `navigation.magneticVariation` is available, `navigation.courseOverGroundTrue`, `navigation.speedOverGround`, `navigation.speedThroughWater`.
|
|
122
|
+
|
|
123
|
+
- `grounding`
|
|
124
|
+
What it does: stops the simulated boat when it gets too close to shore, while still allowing headings that move away from the nearest shore.
|
|
125
|
+
Requires: `navigation.distanceToShore`; for recovery-heading detection, also `navigation.shore.bearingTrue`.
|
|
126
|
+
Recommended provider: install `signalk-distance-to-shore`.
|
|
127
|
+
Options: enable grounding protection and minimum distance to shore in meters.
|
|
128
|
+
|
|
129
|
+
- `persistence`
|
|
130
|
+
What it does: restores the last simulated position, heading and speed after Signal K restarts.
|
|
131
|
+
Requires: writable plugin data storage in Signal K.
|
|
132
|
+
Options: restore last simulated state on startup.
|
|
133
|
+
|
|
134
|
+
Signal K input paths, simulation tick timing, turn rate and persistence save timing are fixed defaults rather than UI options.
|
|
135
|
+
|
|
136
|
+
## Grounding Protection
|
|
137
|
+
|
|
138
|
+
When `grounding.enabled` is true, the simulator reads `navigation.distanceToShore` and stops the virtual boat when the value is less than or equal to `grounding.minimumDistanceToShore`, which defaults to 20 meters. If `navigation.shore.bearingTrue` is available, the simulator still allows movement when the selected heading points away from the nearest shore.
|
|
139
|
+
|
|
140
|
+
The companion [`signalk-distance-to-shore`](https://github.com/macjl/signalk-distance-to-shore) plugin publishes `navigation.distanceToShore`, `navigation.shore.closestPoint` and `navigation.shore.bearingTrue` from a separately installed coastline chart.
|
|
141
|
+
|
|
142
|
+
## Persistence
|
|
143
|
+
|
|
144
|
+
The simulator saves its latest runtime state every 10 seconds by default and restores it on startup, so restarting Signal K does not move the virtual boat back to the configured initial position.
|
|
145
|
+
|
|
146
|
+
Persisted values include:
|
|
147
|
+
|
|
148
|
+
- position
|
|
149
|
+
- true heading
|
|
150
|
+
- COG, SOG and STW
|
|
151
|
+
|
|
152
|
+
## Uninstall
|
|
153
|
+
|
|
154
|
+
From the Signal K App Store, uninstall or disable `Sailboat Simulator`.
|
|
155
|
+
|
|
156
|
+
From the CLI:
|
|
157
|
+
|
|
158
|
+
```sh
|
|
159
|
+
cd ~/.signalk
|
|
160
|
+
npm uninstall signalk-sailboat-simulator
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Then restart Signal K.
|
|
164
|
+
|
|
165
|
+
## Useful Links
|
|
166
|
+
|
|
167
|
+
- Signal K Weather Providers: https://demo.signalk.org/documentation/Developing/Plugins/Weather_Providers.html
|
|
168
|
+
- Signal K Weather API: https://demo.signalk.org/documentation/Developing/REST_APIs/Weather_API.html
|
|
169
|
+
- `@signalk/open-meteo-provider`: https://www.npmjs.com/package/@signalk/open-meteo-provider
|
|
170
|
+
- `signalk-autopilot-emulator-v2`: https://www.npmjs.com/package/signalk-autopilot-emulator-v2
|
|
171
|
+
- `signalk-autopilot-emulator-v2` source: https://github.com/macjl/signalk-autopilot-emulator-v2
|
|
172
|
+
- `signalk-polar-performance-plugin`: https://www.npmjs.com/package/signalk-polar-performance-plugin
|
|
173
|
+
- `signalk-derived-data`: https://www.npmjs.com/package/signalk-derived-data
|
|
174
|
+
- `signalk-distance-to-shore`: https://www.npmjs.com/package/signalk-distance-to-shore
|
|
175
|
+
|
|
176
|
+
## Development
|
|
177
|
+
|
|
178
|
+
Run tests with:
|
|
179
|
+
|
|
180
|
+
```sh
|
|
181
|
+
npm test
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
The core simulator is in `lib/simulation-engine.js`. Keep physics and navigation calculations there so behaviour can be tested without a Signal K server.
|
package/index.js
ADDED
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
const { createInitialState, stepSimulation } = require('./lib/simulation-engine')
|
|
4
|
+
const { buildSchema } = require('./lib/plugin-schema')
|
|
5
|
+
const { degToRad, radToDeg, wrap360Rad } = require('./lib/angles')
|
|
6
|
+
const { apparentWindFromTrue, trueWindFromDirection, windSnapshotFromObservation } = require('./lib/wind')
|
|
7
|
+
const { applyPersistedState, createStateStore, stateFromSimulation } = require('./lib/state-store')
|
|
8
|
+
|
|
9
|
+
const PLUGIN_ID = 'sailboat-simulator'
|
|
10
|
+
const PUBLISH_SOURCE = 'signalk-sailboat-simulator'
|
|
11
|
+
|
|
12
|
+
const INPUT_PATHS = {
|
|
13
|
+
turnRatePath: 'steering.autopilot.output.turnRate',
|
|
14
|
+
magneticVariationPath: 'navigation.magneticVariation',
|
|
15
|
+
performanceSpeedPath: 'performance.polarSpeed',
|
|
16
|
+
distanceToShorePath: 'navigation.distanceToShore',
|
|
17
|
+
shoreBearingTruePath: 'navigation.shore.bearingTrue'
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const DEFAULT_OPTIONS = {
|
|
21
|
+
tickIntervalMs: 1000,
|
|
22
|
+
maxStepSeconds: 5,
|
|
23
|
+
initialState: {
|
|
24
|
+
latitude: 43.63278,
|
|
25
|
+
longitude: 7.14287,
|
|
26
|
+
headingTrueDeg: 180
|
|
27
|
+
},
|
|
28
|
+
wind: {
|
|
29
|
+
trueWind: true,
|
|
30
|
+
apparentWind: true,
|
|
31
|
+
providerId: '',
|
|
32
|
+
retryIntervalSeconds: 30,
|
|
33
|
+
pollIntervalSeconds: 60,
|
|
34
|
+
maxAgeSeconds: 1800
|
|
35
|
+
},
|
|
36
|
+
fallback: {
|
|
37
|
+
speedThroughWater: 0
|
|
38
|
+
},
|
|
39
|
+
grounding: {
|
|
40
|
+
enabled: true,
|
|
41
|
+
minimumDistanceToShore: 20
|
|
42
|
+
},
|
|
43
|
+
persistence: {
|
|
44
|
+
enabled: true,
|
|
45
|
+
saveIntervalSeconds: 10
|
|
46
|
+
},
|
|
47
|
+
publishing: {
|
|
48
|
+
source: PUBLISH_SOURCE,
|
|
49
|
+
navigation: true
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
module.exports = function createPlugin (app) {
|
|
54
|
+
let options = DEFAULT_OPTIONS
|
|
55
|
+
let timer = null
|
|
56
|
+
let state = null
|
|
57
|
+
let runtime = inactiveRuntime()
|
|
58
|
+
let tickRunning = false
|
|
59
|
+
let lastWeatherFetchAt = 0
|
|
60
|
+
let lastStateSaveAt = 0
|
|
61
|
+
let weatherSnapshot = null
|
|
62
|
+
let stateStore = null
|
|
63
|
+
|
|
64
|
+
const plugin = {
|
|
65
|
+
id: PLUGIN_ID,
|
|
66
|
+
name: 'Sailboat Simulator',
|
|
67
|
+
description: 'Simulates a sailing boat position from Signal K autopilot turn-rate output, weather and polar performance data.',
|
|
68
|
+
schema: buildSchema,
|
|
69
|
+
start,
|
|
70
|
+
stop,
|
|
71
|
+
registerWithRouter
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return plugin
|
|
75
|
+
|
|
76
|
+
function start (pluginOptions) {
|
|
77
|
+
options = normalizeOptions(pluginOptions || {})
|
|
78
|
+
lastWeatherFetchAt = 0
|
|
79
|
+
lastStateSaveAt = 0
|
|
80
|
+
weatherSnapshot = null
|
|
81
|
+
stateStore = createStateStore(app, PLUGIN_ID)
|
|
82
|
+
state = createInitialState(options)
|
|
83
|
+
if (options.persistence.enabled) {
|
|
84
|
+
state = applyPersistedState(state, stateStore.load())
|
|
85
|
+
}
|
|
86
|
+
runtime = inactiveRuntime()
|
|
87
|
+
|
|
88
|
+
tick()
|
|
89
|
+
timer = setInterval(() => { tick() }, options.tickIntervalMs)
|
|
90
|
+
setStatus()
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function stop () {
|
|
94
|
+
if (timer) clearInterval(timer)
|
|
95
|
+
timer = null
|
|
96
|
+
runtime.status = 'inactive'
|
|
97
|
+
setStatus()
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function tick () {
|
|
101
|
+
if (tickRunning) return
|
|
102
|
+
tickRunning = true
|
|
103
|
+
const now = Date.now()
|
|
104
|
+
try {
|
|
105
|
+
await refreshWeather(now)
|
|
106
|
+
const inputs = readInputs()
|
|
107
|
+
state = stepSimulation(state, inputs, options, now)
|
|
108
|
+
publishState(inputs)
|
|
109
|
+
persistState(now)
|
|
110
|
+
updateRuntime(inputs)
|
|
111
|
+
setStatus()
|
|
112
|
+
} catch (error) {
|
|
113
|
+
runtime.status = 'error'
|
|
114
|
+
runtime.error = error.message
|
|
115
|
+
app.error && app.error(`Sailboat simulator tick failed: ${error.message}`)
|
|
116
|
+
setStatus()
|
|
117
|
+
} finally {
|
|
118
|
+
tickRunning = false
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function persistState (now) {
|
|
123
|
+
if (!options.persistence.enabled || !stateStore) return
|
|
124
|
+
if (now - lastStateSaveAt < options.persistence.saveIntervalSeconds * 1000) return
|
|
125
|
+
const persisted = stateFromSimulation(state)
|
|
126
|
+
if (stateStore.save(persisted)) lastStateSaveAt = now
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function readInputs () {
|
|
130
|
+
const weatherWind = freshWeatherWind()
|
|
131
|
+
return {
|
|
132
|
+
turnRate: readNumber(INPUT_PATHS.turnRatePath),
|
|
133
|
+
magneticVariation: readNumber(INPUT_PATHS.magneticVariationPath),
|
|
134
|
+
polarSpeed: readNumber(INPUT_PATHS.performanceSpeedPath),
|
|
135
|
+
windSpeedTrue: weatherWind && weatherWind.speedTrue != null
|
|
136
|
+
? weatherWind.speedTrue
|
|
137
|
+
: null,
|
|
138
|
+
windDirectionTrue: weatherWind && weatherWind.directionTrue != null
|
|
139
|
+
? weatherWind.directionTrue
|
|
140
|
+
: null,
|
|
141
|
+
distanceToShore: readNumber(INPUT_PATHS.distanceToShorePath),
|
|
142
|
+
shoreBearingTrue: readNumber(INPUT_PATHS.shoreBearingTruePath),
|
|
143
|
+
weatherObservedAt: weatherWind ? weatherWind.observedAt : null,
|
|
144
|
+
weatherDescription: weatherWind ? weatherWind.description : ''
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function readNumber (path) {
|
|
149
|
+
if (!path || typeof app.getSelfPath !== 'function') return null
|
|
150
|
+
const value = app.getSelfPath(`${path}.value`)
|
|
151
|
+
return Number.isFinite(value) ? value : null
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function publishState (inputs) {
|
|
155
|
+
if (!state || !app.handleMessage) return
|
|
156
|
+
|
|
157
|
+
const values = []
|
|
158
|
+
if (publishNavigation()) {
|
|
159
|
+
values.push({
|
|
160
|
+
path: 'navigation.position',
|
|
161
|
+
value: {
|
|
162
|
+
latitude: state.position.latitude,
|
|
163
|
+
longitude: state.position.longitude
|
|
164
|
+
}
|
|
165
|
+
})
|
|
166
|
+
values.push({ path: 'navigation.headingTrue', value: state.headingTrue })
|
|
167
|
+
const headingMagnetic = magneticHeadingFromTrue(state.headingTrue, inputs.magneticVariation)
|
|
168
|
+
if (Number.isFinite(headingMagnetic)) {
|
|
169
|
+
values.push({ path: 'navigation.headingMagnetic', value: headingMagnetic })
|
|
170
|
+
}
|
|
171
|
+
values.push({ path: 'navigation.courseOverGroundTrue', value: state.courseOverGroundTrue })
|
|
172
|
+
values.push({ path: 'navigation.speedOverGround', value: state.speedOverGround })
|
|
173
|
+
values.push({ path: 'navigation.speedThroughWater', value: state.speedThroughWater })
|
|
174
|
+
}
|
|
175
|
+
values.push(...buildWindValues(inputs))
|
|
176
|
+
|
|
177
|
+
if (values.length === 0) return
|
|
178
|
+
app.handleMessage(PLUGIN_ID, {
|
|
179
|
+
updates: [
|
|
180
|
+
{
|
|
181
|
+
$source: options.publishing.source,
|
|
182
|
+
values
|
|
183
|
+
}
|
|
184
|
+
]
|
|
185
|
+
})
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function buildWindValues (inputs) {
|
|
189
|
+
if (!publishTrueWind() && !publishApparentWind()) return []
|
|
190
|
+
if (!Number.isFinite(inputs.windSpeedTrue) || !Number.isFinite(inputs.windDirectionTrue)) return []
|
|
191
|
+
|
|
192
|
+
const windValues = []
|
|
193
|
+
const angleTrueWater = trueWindFromDirection(inputs.windDirectionTrue, state.headingTrue)
|
|
194
|
+
const apparent = apparentWindFromTrue({
|
|
195
|
+
trueWindSpeed: inputs.windSpeedTrue,
|
|
196
|
+
trueWindAngle: angleTrueWater,
|
|
197
|
+
boatSpeed: state.speedThroughWater
|
|
198
|
+
})
|
|
199
|
+
|
|
200
|
+
if (publishTrueWind()) {
|
|
201
|
+
windValues.push({ path: 'environment.wind.speedTrue', value: inputs.windSpeedTrue })
|
|
202
|
+
windValues.push({ path: 'environment.wind.directionTrue', value: inputs.windDirectionTrue })
|
|
203
|
+
if (Number.isFinite(angleTrueWater)) {
|
|
204
|
+
windValues.push({ path: 'environment.wind.angleTrueWater', value: angleTrueWater })
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
if (publishApparentWind() && apparent) {
|
|
208
|
+
windValues.push({ path: 'environment.wind.speedApparent', value: apparent.speed })
|
|
209
|
+
windValues.push({ path: 'environment.wind.angleApparent', value: apparent.angle })
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return windValues
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function publishNavigation () {
|
|
216
|
+
return options.publishing.navigation !== false
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function publishTrueWind () {
|
|
220
|
+
return options.wind.trueWind !== false
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function publishApparentWind () {
|
|
224
|
+
return options.wind.apparentWind !== false
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function publishesAnyWind () {
|
|
228
|
+
return publishTrueWind() || publishApparentWind()
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function refreshWeather (now) {
|
|
232
|
+
if (!publishesAnyWind()) return
|
|
233
|
+
const intervalSeconds = freshWeatherWind()
|
|
234
|
+
? options.wind.pollIntervalSeconds
|
|
235
|
+
: options.wind.retryIntervalSeconds
|
|
236
|
+
if (now - lastWeatherFetchAt < intervalSeconds * 1000) return
|
|
237
|
+
lastWeatherFetchAt = now
|
|
238
|
+
|
|
239
|
+
const position = state && state.position ? state.position : options.initialState
|
|
240
|
+
const weatherData = await fetchWeatherData(position, now)
|
|
241
|
+
if (weatherData) {
|
|
242
|
+
weatherSnapshot = {
|
|
243
|
+
...weatherData.snapshot,
|
|
244
|
+
type: weatherData.type,
|
|
245
|
+
providerId: weatherData.providerId,
|
|
246
|
+
fetchedAt: now
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async function fetchWeatherData (position, now) {
|
|
252
|
+
const provider = getWeatherProvider()
|
|
253
|
+
if (!provider) return null
|
|
254
|
+
|
|
255
|
+
const observation = await fetchWeatherObservation(provider, position)
|
|
256
|
+
const observationSnapshot = windSnapshotFromObservation(observation)
|
|
257
|
+
if (observationSnapshot) {
|
|
258
|
+
return {
|
|
259
|
+
type: 'observation',
|
|
260
|
+
providerId: provider.id,
|
|
261
|
+
snapshot: observationSnapshot
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const forecast = await fetchClosestWeatherForecast(provider, position, now)
|
|
266
|
+
if (forecast) {
|
|
267
|
+
return {
|
|
268
|
+
type: 'forecast',
|
|
269
|
+
providerId: provider.id,
|
|
270
|
+
snapshot: forecast.snapshot
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
return null
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function getWeatherProvider () {
|
|
278
|
+
if (!app.weatherApi) return null
|
|
279
|
+
|
|
280
|
+
const providerId = options.wind.providerId
|
|
281
|
+
if (!providerId) {
|
|
282
|
+
const defaultProviderId = currentWeatherProviderId()
|
|
283
|
+
const registeredProvider = registeredWeatherProvider(defaultProviderId)
|
|
284
|
+
if (registeredProvider) return registeredProvider
|
|
285
|
+
|
|
286
|
+
return {
|
|
287
|
+
id: defaultProviderId,
|
|
288
|
+
methods: app.weatherApi
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const configuredProvider = registeredWeatherProvider(providerId)
|
|
293
|
+
if (configuredProvider) return configuredProvider
|
|
294
|
+
|
|
295
|
+
app.error && app.error(`Weather provider not found: ${providerId}`)
|
|
296
|
+
return null
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function registeredWeatherProvider (providerId) {
|
|
300
|
+
const providers = app.weatherApi.weatherProviders
|
|
301
|
+
if (providers && typeof providers.get === 'function' && providers.has(providerId)) {
|
|
302
|
+
return {
|
|
303
|
+
id: providerId,
|
|
304
|
+
methods: providers.get(providerId).methods
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
return null
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async function fetchWeatherObservation (provider, position) {
|
|
311
|
+
if (!provider.methods || typeof provider.methods.getObservations !== 'function') return null
|
|
312
|
+
try {
|
|
313
|
+
const observations = await provider.methods.getObservations(position)
|
|
314
|
+
return Array.isArray(observations) && observations.length > 0 ? observations[0] : null
|
|
315
|
+
} catch (error) {
|
|
316
|
+
app.debug && app.debug(`Weather observations unavailable: ${error.message}`)
|
|
317
|
+
return null
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
async function fetchClosestWeatherForecast (provider, position, now) {
|
|
322
|
+
if (!provider.methods || typeof provider.methods.getForecasts !== 'function') return null
|
|
323
|
+
try {
|
|
324
|
+
const forecasts = await provider.methods.getForecasts(position, 'point', { maxCount: 24 })
|
|
325
|
+
if (!Array.isArray(forecasts) || forecasts.length === 0) return null
|
|
326
|
+
|
|
327
|
+
return forecasts
|
|
328
|
+
.map(forecast => ({
|
|
329
|
+
snapshot: windSnapshotFromObservation(forecast),
|
|
330
|
+
distanceMs: dateDistanceMs(forecast.date, now)
|
|
331
|
+
}))
|
|
332
|
+
.filter(forecast => forecast.snapshot && Number.isFinite(forecast.distanceMs))
|
|
333
|
+
.sort((a, b) => a.distanceMs - b.distanceMs)[0] || null
|
|
334
|
+
} catch (error) {
|
|
335
|
+
app.debug && app.debug(`Weather forecasts unavailable: ${error.message}`)
|
|
336
|
+
return null
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function freshWeatherWind () {
|
|
341
|
+
if (!weatherSnapshot) return null
|
|
342
|
+
if (weatherSnapshot.providerId !== currentWeatherProviderId()) return null
|
|
343
|
+
const ageSeconds = (Date.now() - weatherSnapshot.fetchedAt) / 1000
|
|
344
|
+
return ageSeconds <= options.wind.maxAgeSeconds ? weatherSnapshot : null
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function currentWeatherProviderId () {
|
|
348
|
+
if (options.wind.providerId) return options.wind.providerId
|
|
349
|
+
const defaultProviderId = app.weatherApi && app.weatherApi.defaultProviderId
|
|
350
|
+
return typeof defaultProviderId === 'string' && defaultProviderId.trim()
|
|
351
|
+
? defaultProviderId.trim()
|
|
352
|
+
: 'default'
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function updateRuntime (inputs) {
|
|
356
|
+
const headingMagnetic = magneticHeadingFromTrue(state.headingTrue, inputs.magneticVariation)
|
|
357
|
+
runtime = {
|
|
358
|
+
status: state.groundingProtectionActive
|
|
359
|
+
? 'groundingProtection'
|
|
360
|
+
: Number.isFinite(state.speedThroughWater) && state.speedThroughWater > 0 ? 'sailing' : 'waitingForPerformance',
|
|
361
|
+
position: state.position,
|
|
362
|
+
headingTrueDeg: radToDeg(state.headingTrue),
|
|
363
|
+
headingMagneticDeg: Number.isFinite(headingMagnetic) ? radToDeg(headingMagnetic) : null,
|
|
364
|
+
magneticVariationDeg: Number.isFinite(inputs.magneticVariation) ? radToDeg(inputs.magneticVariation) : null,
|
|
365
|
+
courseOverGroundTrueDeg: radToDeg(state.courseOverGroundTrue),
|
|
366
|
+
speedOverGround: state.speedOverGround,
|
|
367
|
+
speedThroughWater: state.speedThroughWater,
|
|
368
|
+
distanceToShore: Number.isFinite(inputs.distanceToShore) ? inputs.distanceToShore : null,
|
|
369
|
+
groundingProtectionActive: Boolean(state.groundingProtectionActive),
|
|
370
|
+
windAngleTrueWaterDeg: Number.isFinite(state.windAngleTrueWater) ? radToDeg(state.windAngleTrueWater) : null,
|
|
371
|
+
weather: weatherSnapshot
|
|
372
|
+
? {
|
|
373
|
+
status: freshWeatherWind() ? 'fresh' : 'stale',
|
|
374
|
+
observedAt: weatherSnapshot.observedAt,
|
|
375
|
+
fetchedAt: new Date(weatherSnapshot.fetchedAt).toISOString(),
|
|
376
|
+
type: weatherSnapshot.type,
|
|
377
|
+
providerId: weatherSnapshot.providerId,
|
|
378
|
+
description: weatherSnapshot.description
|
|
379
|
+
}
|
|
380
|
+
: { status: publishesAnyWind() ? 'missing' : 'disabled' },
|
|
381
|
+
inputs: {
|
|
382
|
+
turnRate: valueStatus(inputs.turnRate),
|
|
383
|
+
magneticVariation: valueStatus(inputs.magneticVariation),
|
|
384
|
+
performanceSpeed: valueStatus(inputs.polarSpeed),
|
|
385
|
+
distanceToShore: valueStatus(inputs.distanceToShore),
|
|
386
|
+
shoreBearingTrue: valueStatus(inputs.shoreBearingTrue),
|
|
387
|
+
windSpeedTrue: valueStatus(inputs.windSpeedTrue),
|
|
388
|
+
windDirectionTrue: valueStatus(inputs.windDirectionTrue)
|
|
389
|
+
},
|
|
390
|
+
updatedAt: new Date(state.updatedAt).toISOString()
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function setStatus () {
|
|
395
|
+
if (!app.setPluginStatus) return
|
|
396
|
+
if (runtime.status === 'sailing') {
|
|
397
|
+
app.setPluginStatus(`Sailing at ${runtime.speedOverGround.toFixed(2)} m/s, heading ${runtime.headingTrueDeg.toFixed(1)} deg`)
|
|
398
|
+
} else if (runtime.status === 'groundingProtection') {
|
|
399
|
+
app.setPluginStatus(`Stopped: distance to shore ${runtime.distanceToShore.toFixed(1)} m`)
|
|
400
|
+
} else {
|
|
401
|
+
app.setPluginStatus(runtime.status)
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function registerWithRouter (router) {
|
|
406
|
+
router.get('/api/status', (req, res) => {
|
|
407
|
+
res.json({
|
|
408
|
+
plugin: PLUGIN_ID,
|
|
409
|
+
runtime,
|
|
410
|
+
options: publicOptions()
|
|
411
|
+
})
|
|
412
|
+
})
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function publicOptions () {
|
|
416
|
+
return {
|
|
417
|
+
wind: {
|
|
418
|
+
trueWind: options.wind.trueWind,
|
|
419
|
+
apparentWind: options.wind.apparentWind,
|
|
420
|
+
providerId: options.wind.providerId,
|
|
421
|
+
pollIntervalSeconds: options.wind.pollIntervalSeconds
|
|
422
|
+
},
|
|
423
|
+
grounding: options.grounding,
|
|
424
|
+
persistence: { enabled: options.persistence.enabled },
|
|
425
|
+
publishing: { navigation: options.publishing.navigation }
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
function normalizeOptions (options) {
|
|
431
|
+
const normalized = mergeOptions(DEFAULT_OPTIONS, options || {})
|
|
432
|
+
normalized.initialState.headingTrue = degToRad(normalized.initialState.headingTrueDeg)
|
|
433
|
+
normalized.wind.providerId = typeof normalized.wind.providerId === 'string'
|
|
434
|
+
? normalized.wind.providerId.trim()
|
|
435
|
+
: ''
|
|
436
|
+
return normalized
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function inactiveRuntime () {
|
|
440
|
+
return {
|
|
441
|
+
status: 'inactive',
|
|
442
|
+
position: null,
|
|
443
|
+
headingTrueDeg: null,
|
|
444
|
+
headingMagneticDeg: null,
|
|
445
|
+
magneticVariationDeg: null,
|
|
446
|
+
courseOverGroundTrueDeg: null,
|
|
447
|
+
speedOverGround: null,
|
|
448
|
+
speedThroughWater: null,
|
|
449
|
+
distanceToShore: null,
|
|
450
|
+
groundingProtectionActive: false,
|
|
451
|
+
windAngleTrueWaterDeg: null,
|
|
452
|
+
inputs: {},
|
|
453
|
+
updatedAt: null
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function valueStatus (value) {
|
|
458
|
+
return Number.isFinite(value) ? 'present' : 'missing'
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function magneticHeadingFromTrue (headingTrue, magneticVariation) {
|
|
462
|
+
if (!Number.isFinite(headingTrue) || !Number.isFinite(magneticVariation)) return null
|
|
463
|
+
return wrap360Rad(headingTrue - magneticVariation)
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function dateDistanceMs (date, now) {
|
|
467
|
+
const time = new Date(date).getTime()
|
|
468
|
+
if (!Number.isFinite(time)) return null
|
|
469
|
+
return Math.abs(time - now)
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function mergeOptions (base, override) {
|
|
473
|
+
if (!override || typeof override !== 'object') return clone(base)
|
|
474
|
+
const result = clone(base)
|
|
475
|
+
for (const [key, value] of Object.entries(override)) {
|
|
476
|
+
if (isPlainObject(value) && isPlainObject(result[key])) {
|
|
477
|
+
result[key] = mergeOptions(result[key], value)
|
|
478
|
+
} else {
|
|
479
|
+
result[key] = value
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
return result
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
function isPlainObject (value) {
|
|
486
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
function clone (value) {
|
|
490
|
+
return JSON.parse(JSON.stringify(value))
|
|
491
|
+
}
|
package/lib/angles.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
const TWO_PI = Math.PI * 2
|
|
4
|
+
|
|
5
|
+
function degToRad (degrees) {
|
|
6
|
+
return degrees * Math.PI / 180
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function radToDeg (radians) {
|
|
10
|
+
return radians * 180 / Math.PI
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function wrap360Rad (radians) {
|
|
14
|
+
const wrapped = radians % TWO_PI
|
|
15
|
+
return wrapped < 0 ? wrapped + TWO_PI : wrapped
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function wrap180Rad (radians) {
|
|
19
|
+
const wrapped = wrap360Rad(radians + Math.PI) - Math.PI
|
|
20
|
+
return wrapped === -Math.PI ? Math.PI : wrapped
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
module.exports = {
|
|
24
|
+
degToRad,
|
|
25
|
+
radToDeg,
|
|
26
|
+
wrap180Rad,
|
|
27
|
+
wrap360Rad
|
|
28
|
+
}
|
package/lib/geo.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
const EARTH_RADIUS_METERS = 6371008.8
|
|
4
|
+
|
|
5
|
+
function destinationPoint (position, bearingRad, distanceMeters) {
|
|
6
|
+
const angularDistance = distanceMeters / EARTH_RADIUS_METERS
|
|
7
|
+
const lat1 = toRad(position.latitude)
|
|
8
|
+
const lon1 = toRad(position.longitude)
|
|
9
|
+
|
|
10
|
+
const sinLat1 = Math.sin(lat1)
|
|
11
|
+
const cosLat1 = Math.cos(lat1)
|
|
12
|
+
const sinDistance = Math.sin(angularDistance)
|
|
13
|
+
const cosDistance = Math.cos(angularDistance)
|
|
14
|
+
|
|
15
|
+
const lat2 = Math.asin(
|
|
16
|
+
sinLat1 * cosDistance +
|
|
17
|
+
cosLat1 * sinDistance * Math.cos(bearingRad)
|
|
18
|
+
)
|
|
19
|
+
const lon2 = lon1 + Math.atan2(
|
|
20
|
+
Math.sin(bearingRad) * sinDistance * cosLat1,
|
|
21
|
+
cosDistance - sinLat1 * Math.sin(lat2)
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
return {
|
|
25
|
+
latitude: toDeg(lat2),
|
|
26
|
+
longitude: normalizeLongitude(toDeg(lon2))
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function normalizeLongitude (longitude) {
|
|
31
|
+
return ((longitude + 540) % 360) - 180
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function toRad (degrees) {
|
|
35
|
+
return degrees * Math.PI / 180
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function toDeg (radians) {
|
|
39
|
+
return radians * 180 / Math.PI
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
module.exports = {
|
|
43
|
+
EARTH_RADIUS_METERS,
|
|
44
|
+
destinationPoint
|
|
45
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
function buildSchema () {
|
|
4
|
+
return {
|
|
5
|
+
type: 'object',
|
|
6
|
+
title: 'Sailboat Simulator',
|
|
7
|
+
description: 'Simulates a virtual sailboat from autopilot turn-rate output, polar performance, weather and optional shore-distance data already present in Signal K.',
|
|
8
|
+
properties: {
|
|
9
|
+
initialState: {
|
|
10
|
+
type: 'object',
|
|
11
|
+
title: 'Initial state',
|
|
12
|
+
description: 'What it does: sets the starting position and heading for a new simulation. Requires: nothing else. These values are only used when persistence is disabled or no previous runtime state has been saved.',
|
|
13
|
+
properties: {
|
|
14
|
+
latitude: {
|
|
15
|
+
type: 'number',
|
|
16
|
+
title: 'Initial latitude',
|
|
17
|
+
default: 43.63278,
|
|
18
|
+
minimum: -90,
|
|
19
|
+
maximum: 90
|
|
20
|
+
},
|
|
21
|
+
longitude: {
|
|
22
|
+
type: 'number',
|
|
23
|
+
title: 'Initial longitude',
|
|
24
|
+
default: 7.14287,
|
|
25
|
+
minimum: -180,
|
|
26
|
+
maximum: 180
|
|
27
|
+
},
|
|
28
|
+
headingTrueDeg: {
|
|
29
|
+
type: 'number',
|
|
30
|
+
title: 'Initial true heading in degrees',
|
|
31
|
+
default: 180,
|
|
32
|
+
minimum: 0,
|
|
33
|
+
maximum: 360
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
wind: {
|
|
38
|
+
type: 'object',
|
|
39
|
+
title: 'Wind',
|
|
40
|
+
description: 'What it does: reads wind at the simulated boat position from the Signal K Weather API and publishes the selected wind values. The main goal is to feed polar performance calculations so another plugin can produce performance.polarSpeed, which the simulator then uses as boat speed. Requires: a Weather API provider, preferably @signalk/open-meteo-provider, and a polar performance plugin such as signalk-polar-performance-plugin. Options: publish true wind, publish apparent wind, optionally force a provider id instead of the Signal K default, and choose the polling interval.',
|
|
41
|
+
properties: {
|
|
42
|
+
trueWind: {
|
|
43
|
+
type: 'boolean',
|
|
44
|
+
title: 'Publish true wind',
|
|
45
|
+
description: 'Publishes environment.wind.speedTrue, environment.wind.directionTrue and environment.wind.angleTrueWater. This is usually needed by polar performance plugins.',
|
|
46
|
+
default: true
|
|
47
|
+
},
|
|
48
|
+
apparentWind: {
|
|
49
|
+
type: 'boolean',
|
|
50
|
+
title: 'Publish apparent wind',
|
|
51
|
+
description: 'Publishes environment.wind.speedApparent and environment.wind.angleApparent as seen from the simulated boat.',
|
|
52
|
+
default: true
|
|
53
|
+
},
|
|
54
|
+
providerId: {
|
|
55
|
+
type: 'string',
|
|
56
|
+
title: 'Weather provider id',
|
|
57
|
+
description: 'Leave empty to use the Signal K default Weather API provider. Use open-meteo to force @signalk/open-meteo-provider.',
|
|
58
|
+
default: ''
|
|
59
|
+
},
|
|
60
|
+
pollIntervalSeconds: {
|
|
61
|
+
type: 'number',
|
|
62
|
+
title: 'Weather polling interval in seconds',
|
|
63
|
+
description: 'How often the simulator refreshes wind from the Weather API while wind publishing is enabled.',
|
|
64
|
+
default: 60,
|
|
65
|
+
minimum: 30
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
publishing: {
|
|
70
|
+
type: 'object',
|
|
71
|
+
title: 'Navigation output',
|
|
72
|
+
description: 'What it does: publishes the simulated boat navigation state. Requires steering.autopilot.output.turnRate to steer and performance.polarSpeed to move. If navigation.magneticVariation is available, navigation.headingMagnetic is also published. Recommended providers: signalk-autopilot-emulator-v2, signalk-polar-performance-plugin and signalk-derived-data with navigation.magneticVariation publishing enabled.',
|
|
73
|
+
properties: {
|
|
74
|
+
navigation: {
|
|
75
|
+
type: 'boolean',
|
|
76
|
+
title: 'Publish navigation state',
|
|
77
|
+
description: 'Publishes navigation.position, navigation.headingTrue, navigation.headingMagnetic when magnetic variation is available, navigation.courseOverGroundTrue, navigation.speedOverGround and navigation.speedThroughWater.',
|
|
78
|
+
default: true
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
grounding: {
|
|
83
|
+
type: 'object',
|
|
84
|
+
title: 'Grounding protection',
|
|
85
|
+
description: 'What it does: stops the simulated boat when it gets too close to shore, while still allowing headings that move away from the nearest shore. Requires: navigation.distanceToShore, and for recovery-heading detection navigation.shore.bearingTrue. Install signalk-distance-to-shore to provide these paths.',
|
|
86
|
+
properties: {
|
|
87
|
+
enabled: {
|
|
88
|
+
type: 'boolean',
|
|
89
|
+
title: 'Stop when too close to shore',
|
|
90
|
+
description: 'Enables the shore-distance stop logic.',
|
|
91
|
+
default: true
|
|
92
|
+
},
|
|
93
|
+
minimumDistanceToShore: {
|
|
94
|
+
type: 'number',
|
|
95
|
+
title: 'Minimum distance to shore in meters',
|
|
96
|
+
description: 'The simulator stops when navigation.distanceToShore is less than or equal to this value.',
|
|
97
|
+
default: 20,
|
|
98
|
+
minimum: 0
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
persistence: {
|
|
103
|
+
type: 'object',
|
|
104
|
+
title: 'Persistence',
|
|
105
|
+
description: 'What it does: restores the last simulated position, heading and speed after Signal K restarts. Requires: writable plugin data storage in Signal K.',
|
|
106
|
+
properties: {
|
|
107
|
+
enabled: {
|
|
108
|
+
type: 'boolean',
|
|
109
|
+
title: 'Restore last simulated state on startup',
|
|
110
|
+
description: 'When enabled, the simulator resumes from its saved runtime state instead of returning to the initial state.',
|
|
111
|
+
default: true
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
module.exports = {
|
|
120
|
+
buildSchema
|
|
121
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
const { wrap180Rad, wrap360Rad } = require('./angles')
|
|
4
|
+
const { destinationPoint } = require('./geo')
|
|
5
|
+
const { trueWindFromDirection } = require('./wind')
|
|
6
|
+
|
|
7
|
+
function createInitialState (options) {
|
|
8
|
+
return {
|
|
9
|
+
position: {
|
|
10
|
+
latitude: options.initialState.latitude,
|
|
11
|
+
longitude: options.initialState.longitude
|
|
12
|
+
},
|
|
13
|
+
headingTrue: wrap360Rad(options.initialState.headingTrue),
|
|
14
|
+
courseOverGroundTrue: wrap360Rad(options.initialState.headingTrue),
|
|
15
|
+
speedOverGround: 0,
|
|
16
|
+
speedThroughWater: 0,
|
|
17
|
+
groundingProtectionActive: false,
|
|
18
|
+
windAngleTrueWater: null,
|
|
19
|
+
updatedAt: null
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function stepSimulation (state, inputs, options, now) {
|
|
24
|
+
const previousUpdatedAt = state.updatedAt == null ? now : state.updatedAt
|
|
25
|
+
const rawStepSeconds = Math.max(0, (now - previousUpdatedAt) / 1000)
|
|
26
|
+
const stepSeconds = Math.min(rawStepSeconds, options.maxStepSeconds)
|
|
27
|
+
const requestedSpeedThroughWater = Math.max(0, firstFinite(
|
|
28
|
+
inputs.polarSpeed,
|
|
29
|
+
options.fallback.speedThroughWater,
|
|
30
|
+
0
|
|
31
|
+
))
|
|
32
|
+
const turnRate = Number.isFinite(inputs.turnRate) ? inputs.turnRate : 0
|
|
33
|
+
const headingTrue = wrap360Rad(state.headingTrue + turnRate * stepSeconds)
|
|
34
|
+
const groundingProtectionActive = shouldStopForGrounding(inputs, options, headingTrue)
|
|
35
|
+
const speedThroughWater = groundingProtectionActive
|
|
36
|
+
? 0
|
|
37
|
+
: requestedSpeedThroughWater
|
|
38
|
+
const distanceMeters = speedThroughWater * stepSeconds
|
|
39
|
+
const position = distanceMeters > 0
|
|
40
|
+
? destinationPoint(state.position, headingTrue, distanceMeters)
|
|
41
|
+
: state.position
|
|
42
|
+
|
|
43
|
+
return {
|
|
44
|
+
position,
|
|
45
|
+
headingTrue: wrap360Rad(headingTrue),
|
|
46
|
+
courseOverGroundTrue: wrap360Rad(headingTrue),
|
|
47
|
+
speedOverGround: speedThroughWater,
|
|
48
|
+
speedThroughWater,
|
|
49
|
+
groundingProtectionActive,
|
|
50
|
+
windAngleTrueWater: deriveWindAngleTrueWater(inputs.windDirectionTrue, headingTrue),
|
|
51
|
+
updatedAt: now
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function shouldStopForGrounding (inputs, options, headingTrue) {
|
|
56
|
+
const tooClose = Boolean(
|
|
57
|
+
options.grounding &&
|
|
58
|
+
options.grounding.enabled &&
|
|
59
|
+
Number.isFinite(inputs.distanceToShore) &&
|
|
60
|
+
inputs.distanceToShore <= options.grounding.minimumDistanceToShore
|
|
61
|
+
)
|
|
62
|
+
if (!tooClose) return false
|
|
63
|
+
if (!Number.isFinite(inputs.shoreBearingTrue) || !Number.isFinite(headingTrue)) return true
|
|
64
|
+
|
|
65
|
+
return !isHeadingAwayFromShore(headingTrue, inputs.shoreBearingTrue)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function isHeadingAwayFromShore (headingTrue, shoreBearingTrue) {
|
|
69
|
+
return Math.abs(wrap180Rad(headingTrue - shoreBearingTrue)) > Math.PI / 2
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function deriveWindAngleTrueWater (windDirectionTrue, headingTrue) {
|
|
73
|
+
return trueWindFromDirection(windDirectionTrue, headingTrue)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function firstFinite (...values) {
|
|
77
|
+
return values.find(Number.isFinite)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
module.exports = {
|
|
81
|
+
createInitialState,
|
|
82
|
+
deriveWindAngleTrueWater,
|
|
83
|
+
stepSimulation
|
|
84
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
const fs = require('fs')
|
|
4
|
+
const path = require('path')
|
|
5
|
+
|
|
6
|
+
function createStateStore (app, pluginId) {
|
|
7
|
+
const baseDir = app && typeof app.getDataDirPath === 'function'
|
|
8
|
+
? app.getDataDirPath()
|
|
9
|
+
: path.join(process.cwd(), 'plugin-config-data')
|
|
10
|
+
const dirPath = baseDir.endsWith(pluginId) ? baseDir : path.join(baseDir, pluginId)
|
|
11
|
+
const filePath = path.join(dirPath, 'runtime-state.json')
|
|
12
|
+
|
|
13
|
+
return {
|
|
14
|
+
load,
|
|
15
|
+
save,
|
|
16
|
+
filePath
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function load () {
|
|
20
|
+
try {
|
|
21
|
+
const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'))
|
|
22
|
+
return isValidPersistedState(parsed) ? parsed : null
|
|
23
|
+
} catch (error) {
|
|
24
|
+
if (error.code !== 'ENOENT' && app && app.debug) {
|
|
25
|
+
app.debug(`Sailboat simulator state load failed: ${error.message}`)
|
|
26
|
+
}
|
|
27
|
+
return null
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function save (state) {
|
|
32
|
+
if (!isValidPersistedState(state)) return false
|
|
33
|
+
fs.mkdirSync(dirPath, { recursive: true })
|
|
34
|
+
const tmpPath = `${filePath}.tmp`
|
|
35
|
+
fs.writeFileSync(tmpPath, `${JSON.stringify(state, null, 2)}\n`)
|
|
36
|
+
fs.renameSync(tmpPath, filePath)
|
|
37
|
+
return true
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function stateFromSimulation (state) {
|
|
42
|
+
if (!state || !state.position) return null
|
|
43
|
+
return {
|
|
44
|
+
version: 1,
|
|
45
|
+
savedAt: new Date().toISOString(),
|
|
46
|
+
position: {
|
|
47
|
+
latitude: state.position.latitude,
|
|
48
|
+
longitude: state.position.longitude
|
|
49
|
+
},
|
|
50
|
+
headingTrue: state.headingTrue,
|
|
51
|
+
courseOverGroundTrue: state.courseOverGroundTrue,
|
|
52
|
+
speedOverGround: state.speedOverGround,
|
|
53
|
+
speedThroughWater: state.speedThroughWater
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function applyPersistedState (state, persisted) {
|
|
58
|
+
if (!state || !isValidPersistedState(persisted)) return state
|
|
59
|
+
return {
|
|
60
|
+
...state,
|
|
61
|
+
position: {
|
|
62
|
+
latitude: persisted.position.latitude,
|
|
63
|
+
longitude: persisted.position.longitude
|
|
64
|
+
},
|
|
65
|
+
headingTrue: numberOr(persisted.headingTrue, state.headingTrue),
|
|
66
|
+
courseOverGroundTrue: numberOr(persisted.courseOverGroundTrue, state.courseOverGroundTrue),
|
|
67
|
+
speedOverGround: numberOr(persisted.speedOverGround, 0),
|
|
68
|
+
speedThroughWater: numberOr(persisted.speedThroughWater, 0),
|
|
69
|
+
updatedAt: null
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function isValidPersistedState (state) {
|
|
74
|
+
return Boolean(
|
|
75
|
+
state &&
|
|
76
|
+
state.position &&
|
|
77
|
+
Number.isFinite(state.position.latitude) &&
|
|
78
|
+
Number.isFinite(state.position.longitude)
|
|
79
|
+
)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function numberOr (value, fallback) {
|
|
83
|
+
return Number.isFinite(value) ? value : fallback
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
module.exports = {
|
|
87
|
+
applyPersistedState,
|
|
88
|
+
createStateStore,
|
|
89
|
+
stateFromSimulation
|
|
90
|
+
}
|
package/lib/wind.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
const { wrap180Rad } = require('./angles')
|
|
4
|
+
|
|
5
|
+
function trueWindFromDirection (windDirectionTrue, headingTrue) {
|
|
6
|
+
if (!Number.isFinite(windDirectionTrue) || !Number.isFinite(headingTrue)) return null
|
|
7
|
+
return wrap180Rad(windDirectionTrue - headingTrue)
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function apparentWindFromTrue ({ trueWindSpeed, trueWindAngle, boatSpeed }) {
|
|
11
|
+
if (!Number.isFinite(trueWindSpeed) || !Number.isFinite(trueWindAngle)) return null
|
|
12
|
+
|
|
13
|
+
const speed = Number.isFinite(boatSpeed) ? boatSpeed : 0
|
|
14
|
+
const forward = trueWindSpeed * Math.cos(trueWindAngle) + speed
|
|
15
|
+
const starboard = trueWindSpeed * Math.sin(trueWindAngle)
|
|
16
|
+
|
|
17
|
+
return {
|
|
18
|
+
speed: Math.hypot(forward, starboard),
|
|
19
|
+
angle: wrap180Rad(Math.atan2(starboard, forward))
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function windSnapshotFromObservation (observation) {
|
|
24
|
+
if (!observation || !observation.wind) return null
|
|
25
|
+
|
|
26
|
+
const speedTrue = observation.wind.speedTrue
|
|
27
|
+
const directionTrue = observation.wind.directionTrue
|
|
28
|
+
if (!Number.isFinite(speedTrue) || !Number.isFinite(directionTrue)) return null
|
|
29
|
+
|
|
30
|
+
return {
|
|
31
|
+
speedTrue,
|
|
32
|
+
directionTrue,
|
|
33
|
+
observedAt: observation.date || null,
|
|
34
|
+
description: observation.description || ''
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
module.exports = {
|
|
39
|
+
apparentWindFromTrue,
|
|
40
|
+
trueWindFromDirection,
|
|
41
|
+
windSnapshotFromObservation
|
|
42
|
+
}
|
package/package.json
CHANGED
|
@@ -1,17 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "signalk-sailboat-simulator",
|
|
3
|
-
"version": "0.0
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Signal K plugin that simulates a sailing boat from autopilot turn-rate output, weather and polar performance data.",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"test": "node --test"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"index.js",
|
|
11
|
+
"lib",
|
|
12
|
+
"README.md",
|
|
13
|
+
"CHANGELOG.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"keywords": [
|
|
17
|
+
"signalk-node-server-plugin",
|
|
18
|
+
"signalk",
|
|
19
|
+
"sailing",
|
|
20
|
+
"simulator",
|
|
21
|
+
"polar",
|
|
22
|
+
"weather",
|
|
23
|
+
"autopilot"
|
|
24
|
+
],
|
|
25
|
+
"author": "Jean-Laurent Girod (@macjl)",
|
|
5
26
|
"license": "Apache-2.0",
|
|
27
|
+
"homepage": "https://github.com/macjl/signalk-sailboat-simulator#readme",
|
|
6
28
|
"repository": {
|
|
7
29
|
"type": "git",
|
|
8
30
|
"url": "git+https://github.com/macjl/signalk-sailboat-simulator.git"
|
|
9
31
|
},
|
|
10
|
-
"homepage": "https://github.com/macjl/signalk-sailboat-simulator#readme",
|
|
11
32
|
"bugs": {
|
|
12
33
|
"url": "https://github.com/macjl/signalk-sailboat-simulator/issues"
|
|
13
34
|
},
|
|
14
|
-
"
|
|
15
|
-
"
|
|
16
|
-
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=18"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {},
|
|
39
|
+
"devDependencies": {},
|
|
40
|
+
"signalk-plugin-enabled-by-default": false,
|
|
41
|
+
"signalk": {
|
|
42
|
+
"displayName": "Sailboat Simulator",
|
|
43
|
+
"recommends": [
|
|
44
|
+
"signalk-autopilot-emulator-v2",
|
|
45
|
+
"signalk-polar-performance-plugin",
|
|
46
|
+
"signalk-derived-data",
|
|
47
|
+
"@signalk/open-meteo-provider",
|
|
48
|
+
"signalk-distance-to-shore"
|
|
49
|
+
]
|
|
50
|
+
}
|
|
17
51
|
}
|