signalk-tides 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright 2017 Scott Bender <scott@scottbender.net> and Joachim Bakke
4
+ * Copyright 2025 Brandon Keepers <brandon@opensoul.org>
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ var __importDefault = (this && this.__importDefault) || function (mod) {
18
+ return (mod && mod.__esModule) ? mod : { "default": mod };
19
+ };
20
+ const noaa_js_1 = __importDefault(require("./sources/noaa.js"));
21
+ const stormglass_js_1 = __importDefault(require("./sources/stormglass.js"));
22
+ const worldtides_js_1 = __importDefault(require("./sources/worldtides.js"));
23
+ module.exports = function (app) {
24
+ // Interval to update tide data
25
+ const defaultPeriod = 60; // 1 hour
26
+ let unsubscribes = [];
27
+ const sources = [
28
+ (0, noaa_js_1.default)(app),
29
+ (0, stormglass_js_1.default)(app),
30
+ (0, worldtides_js_1.default)(app),
31
+ ];
32
+ const plugin = {
33
+ id: "tides",
34
+ name: "Tides",
35
+ // @ts-expect-error: TODO[TS]: fix Plugin type upstream
36
+ description: "Tidal predictions for the vessel's position from various online sources.",
37
+ schema: () => ({
38
+ title: "Tides API",
39
+ type: "object",
40
+ properties: {
41
+ source: {
42
+ title: "Data source",
43
+ type: "string",
44
+ "anyOf": sources.map(({ id, title }) => ({
45
+ const: id,
46
+ title
47
+ })),
48
+ default: sources[0].id,
49
+ },
50
+ // Update plugin schema with sources
51
+ ...sources.reduce((properties, source) => Object.assign(properties, source.properties ?? {}), {}),
52
+ period: {
53
+ title: "Update frequency",
54
+ type: "number",
55
+ description: "How often to update tide data (minutes)",
56
+ default: 60,
57
+ minimum: 1,
58
+ },
59
+ }
60
+ }),
61
+ stop() {
62
+ unsubscribes.forEach((f) => f());
63
+ unsubscribes = [];
64
+ }
65
+ };
66
+ plugin.start = async function (props) {
67
+ app.debug("Starting tides-api: " + JSON.stringify(props));
68
+ // Use the selected source, or the first one if not specified
69
+ const source = sources.find(source => source.id === props.source) || sources[0];
70
+ // Load the selected source
71
+ const provider = await source.start(props);
72
+ // Register the source as a resource provider
73
+ app.registerResourceProvider({
74
+ type: "tides",
75
+ methods: {
76
+ async listResources(query) {
77
+ return provider(query);
78
+ },
79
+ getResource() {
80
+ throw new Error("Not implemented");
81
+ },
82
+ setResource() {
83
+ throw new Error("Not implemented");
84
+ },
85
+ deleteResource() {
86
+ throw new Error("Not implemented");
87
+ }
88
+ }
89
+ });
90
+ app.subscriptionmanager.subscribe({
91
+ context: "vessels." + app.selfId,
92
+ subscribe: [
93
+ {
94
+ path: "navigation.position",
95
+ period: (props.period ?? defaultPeriod) * 60 * 1000,
96
+ policy: "fixed",
97
+ },
98
+ ],
99
+ }, unsubscribes, (subscriptionError) => {
100
+ app.error("Error:" + subscriptionError);
101
+ }, (delta) => {
102
+ // @ts-expect-error: TODO[TS]: fix Delta type upstream
103
+ delta.updates.forEach(({ values }) => {
104
+ // @ts-expect-error: TODO[TS]: fix Delta type upstream
105
+ values.forEach(({ path }) => {
106
+ if (path === "navigation.position") {
107
+ performUpdate();
108
+ }
109
+ });
110
+ });
111
+ });
112
+ async function performUpdate() {
113
+ try {
114
+ const { extremes } = await provider();
115
+ // Use server date, or current date if not available
116
+ const now = new Date(app.getSelfPath("navigation.datetime.value") ?? Date.now());
117
+ const nextTide = {};
118
+ extremes.forEach(({ type, value, time }) => {
119
+ // Get the first tide of this type after now
120
+ if (!nextTide[type] && new Date(time) > now) {
121
+ nextTide[type] = { time, value };
122
+ }
123
+ });
124
+ const delta = {
125
+ context: "vessels." + app.selfId,
126
+ updates: [
127
+ {
128
+ timestamp: now.toISOString(),
129
+ values: Object.entries(nextTide).flatMap(([type, { time, value }]) => {
130
+ return [
131
+ { path: `environment.tide.height${type}`, value: value },
132
+ { path: `environment.tide.time${type}`, value: time },
133
+ ];
134
+ }),
135
+ },
136
+ ],
137
+ };
138
+ app.debug("Sending delta: " + JSON.stringify(delta));
139
+ app.handleMessage(plugin.id, delta);
140
+ app.setPluginStatus("Updated tide data");
141
+ }
142
+ catch (e) {
143
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
144
+ app.setPluginError(e.message);
145
+ // @ts-expect-error: TODO[TS] this accepts more than just a string: https://github.com/bkeepers/signalk-server/blob/d6845ee1f915e6b729d66d2b08b15dc2e0da8e51/src/interfaces/plugins.ts#L517-L519
146
+ app.error(e);
147
+ }
148
+ }
149
+ // Perform initial update on startup
150
+ performUpdate();
151
+ };
152
+ return plugin;
153
+ };
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.default = default_1;
7
+ const path_1 = __importDefault(require("path"));
8
+ const promises_1 = __importDefault(require("fs/promises"));
9
+ const geolib_1 = require("geolib");
10
+ const moment_1 = __importDefault(require("moment"));
11
+ const stationsUrl = `https://api.tidesandcurrents.noaa.gov/mdapi/prod/webapi/stations.json?type=tidepredictions`;
12
+ const dataGetterUrl = 'https://api.tidesandcurrents.noaa.gov/api/prod/datagetter';
13
+ const datum = 'MLLW';
14
+ function default_1(app) {
15
+ return {
16
+ id: 'noaa',
17
+ title: 'NOAA (US only)',
18
+ async start() {
19
+ const stations = await StationList.load(app);
20
+ return async ({ date } = {}) => {
21
+ const position = app.getSelfPath("navigation.position.value");
22
+ if (!position)
23
+ throw new Error("no position");
24
+ const station = stations.closestTo(position);
25
+ const endpoint = new URL(dataGetterUrl);
26
+ endpoint.search = new URLSearchParams({
27
+ product: "predictions",
28
+ application: "signalk.org/node-server",
29
+ begin_date: (0, moment_1.default)(date).format("YYYYMMDD"),
30
+ end_date: (0, moment_1.default)(date).add(7, "days").format("YYYYMMDD"),
31
+ datum,
32
+ station: station.id,
33
+ time_zone: "gmt",
34
+ units: "metric",
35
+ interval: "hilo",
36
+ format: "json",
37
+ }).toString();
38
+ app.debug(`Fetching tides from NOAA: ${endpoint}`);
39
+ try {
40
+ const res = await fetch(endpoint.toString());
41
+ if (!res.ok)
42
+ throw new Error("Failed to fetch NOAA tides: " + res.statusText);
43
+ const body = await res.json();
44
+ app.debug("NOAA response: \n" + JSON.stringify(body, null, 2));
45
+ if (body.error)
46
+ throw new Error(body.error.message);
47
+ return {
48
+ station: {
49
+ name: station.name,
50
+ position: {
51
+ latitude: station.lat,
52
+ longitude: station.lng,
53
+ },
54
+ },
55
+ extremes: body.predictions.map(({ t, v, type }) => ({
56
+ type: type === "H" ? "High" : "Low",
57
+ value: Number(v),
58
+ time: new Date(`${t}Z`).toISOString(),
59
+ })),
60
+ };
61
+ }
62
+ catch (err) {
63
+ app.setPluginError(`Failed to fetch NOAA tides: ${err}`);
64
+ // @ts-expect-error: app.error should accept more than just a string
65
+ app.error(err);
66
+ throw err;
67
+ }
68
+ };
69
+ }
70
+ };
71
+ }
72
+ ;
73
+ class StationList extends Map {
74
+ static async load(app) {
75
+ const filename = path_1.default.join(app.config.configPath, "noaastations.json");
76
+ let data;
77
+ try {
78
+ data = JSON.parse(await promises_1.default.readFile(filename, 'utf-8'));
79
+ app.debug("NOAA: Loaded cached tide stations from " + filename);
80
+ }
81
+ catch (e) {
82
+ app.debug(`NOAA: failed to load cached tide stations: ${e}`);
83
+ app.debug('NOAA: Downloading tide stations');
84
+ const res = await fetch(stationsUrl);
85
+ if (!res.ok)
86
+ throw new Error(`Failed to download stations: ${res.statusText}`);
87
+ data = await res.json();
88
+ await promises_1.default.writeFile(filename, JSON.stringify(data));
89
+ }
90
+ return new this(data.stations);
91
+ }
92
+ constructor(data) {
93
+ super(data.map((station) => [station.id, station]));
94
+ }
95
+ closestTo(position) {
96
+ return this.near(position, 1)[0];
97
+ }
98
+ near(position, limit = 10) {
99
+ const stationsWithDistances = Array.from(this.values()).map((station) => ({
100
+ ...station,
101
+ distance: (0, geolib_1.getDistance)(position, { latitude: station.lat, longitude: station.lng })
102
+ }));
103
+ return stationsWithDistances.sort((a, b) => a.distance - b.distance).slice(0, limit);
104
+ }
105
+ }
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.default = default_1;
7
+ const moment_1 = __importDefault(require("moment"));
8
+ function default_1(app) {
9
+ return {
10
+ id: 'stormglass',
11
+ title: 'StormGlass.io',
12
+ properties: {
13
+ stormglassApiKey: {
14
+ type: 'string',
15
+ title: 'StormGlass.io API key'
16
+ }
17
+ },
18
+ start({ stormglassApiKey } = {}) {
19
+ app.debug("Using StormGlass.io API");
20
+ return async (params = {}) => {
21
+ const { date = (0, moment_1.default)().subtract(1, "days").toISOString() } = params;
22
+ const endPoint = new URL("https://api.stormglass.io/v2/tide/extremes/point");
23
+ const position = app.getSelfPath("navigation.position.value");
24
+ if (!position)
25
+ throw new Error("no position");
26
+ endPoint.search = new URLSearchParams({
27
+ start: (0, moment_1.default)(date).format("YYYY-MM-DD"),
28
+ end: (0, moment_1.default)(date).add(7, "days").format("YYYY-MM-DD"),
29
+ // datum: "CD",
30
+ lat: position.latitude,
31
+ lng: position.longitude,
32
+ }).toString();
33
+ app.debug("Fetching StormGlass.io: " + endPoint.toString());
34
+ const res = await fetch(endPoint, {
35
+ headers: { Authorization: stormglassApiKey ?? '' },
36
+ });
37
+ if (!res.ok)
38
+ throw new Error('Failed to fetch StormGlass.io: ' + res.statusText);
39
+ const data = await res.json();
40
+ app.debug(JSON.stringify(data, null, 2));
41
+ return {
42
+ station: {
43
+ name: data.meta.station.name,
44
+ position: {
45
+ latitude: data.meta.station.lat,
46
+ longitude: data.meta.station.lng,
47
+ },
48
+ },
49
+ extremes: data.data.map(({ type, time, height }) => {
50
+ return {
51
+ type: type === "high" ? "High" : "Low",
52
+ value: height,
53
+ time: new Date(time).toISOString(),
54
+ };
55
+ }),
56
+ };
57
+ };
58
+ }
59
+ };
60
+ }
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.default = default_1;
7
+ const moment_1 = __importDefault(require("moment"));
8
+ function default_1(app) {
9
+ return {
10
+ id: 'WorldTides.info',
11
+ title: 'worldtides.info',
12
+ properties: {
13
+ worldtidesApiKey: {
14
+ type: 'string',
15
+ title: 'worldtides.info API key'
16
+ }
17
+ },
18
+ start({ worldtidesApiKey = '' } = {}) {
19
+ app.debug("Using WorldTides API");
20
+ return async (params = {}) => {
21
+ const { date = (0, moment_1.default)().subtract(1, "days") } = params;
22
+ const endPoint = new URL("https://www.worldtides.info/api/v3");
23
+ const position = app.getSelfPath("navigation.position.value");
24
+ if (!position)
25
+ throw new Error("no position");
26
+ endPoint.search = new URLSearchParams({
27
+ date: (0, moment_1.default)(date).format("YYYY-MM-DD"),
28
+ datum: "CD",
29
+ days: "7",
30
+ extremes: "true",
31
+ key: worldtidesApiKey,
32
+ lat: position.latitude,
33
+ lon: position.longitude,
34
+ }).toString();
35
+ app.debug("Fetching worldtides: " + endPoint.toString());
36
+ const res = await fetch(endPoint);
37
+ if (!res.ok)
38
+ throw new Error('Failed to fetch worldtides: ' + res.statusText);
39
+ const data = await res.json();
40
+ app.debug(JSON.stringify(data, null, 2));
41
+ if (data.status != 200)
42
+ throw new Error("worldtides data: " + data.error ? data.error : "none");
43
+ return {
44
+ station: {
45
+ name: "WorldTides",
46
+ position: {
47
+ latitude: data.responseLat,
48
+ longitude: data.responseLon,
49
+ },
50
+ },
51
+ extremes: data.extremes.map(({ type, dt, height }) => {
52
+ return {
53
+ type,
54
+ value: height,
55
+ time: new Date(dt * 1000).toISOString(),
56
+ };
57
+ }),
58
+ };
59
+ };
60
+ }
61
+ };
62
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "signalk-tides",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "description": "Tidal predictions for the vessel's position from various online sources.",
5
5
  "main": "./dist/index.js",
6
6
  "scripts": {