signalk-tides 1.2.0 → 1.2.2

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/src/index.ts DELETED
@@ -1,174 +0,0 @@
1
- /*
2
- * Copyright 2017 Scott Bender <scott@scottbender.net> and Joachim Bakke
3
- * Copyright 2025 Brandon Keepers <brandon@opensoul.org>
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
-
17
- import { Plugin } from '@signalk/server-api';
18
- import noaa from './sources/noaa.js';
19
- import stormglass from './sources/stormglass.js';
20
- import worldtides from './sources/worldtides.js';
21
- import type { SignalKApp, TideSource, Config, TideExtremeType } from './types.js';
22
-
23
- export = function (app: SignalKApp): Plugin {
24
- // Interval to update tide data
25
- const defaultPeriod = 60; // 1 hour
26
- let unsubscribes: (() => void)[] = [];
27
-
28
- const sources: TideSource[] = [
29
- noaa(app),
30
- stormglass(app),
31
- worldtides(app),
32
- ];
33
-
34
- const plugin: Plugin = {
35
- id: "tides",
36
- name: "Tides",
37
- // @ts-expect-error: TODO[TS]: fix Plugin type upstream
38
- description: "Tidal predictions for the vessel's position from various online sources.",
39
- schema: () => ({
40
- title: "Tides API",
41
- type: "object",
42
- properties: {
43
- source: {
44
- title: "Data source",
45
- type: "string",
46
- "anyOf": sources.map(({ id, title }) => ({
47
- const: id,
48
- title
49
- })),
50
- default: sources[0].id,
51
- },
52
- // Update plugin schema with sources
53
- ...sources.reduce((properties, source) => Object.assign(properties, source.properties ?? {}), {}),
54
- period: {
55
- title: "Update frequency",
56
- type: "number",
57
- description: "How often to update tide data (minutes)",
58
- default: 60,
59
- minimum: 1,
60
- },
61
- }
62
- }),
63
- stop() {
64
- unsubscribes.forEach((f) => f());
65
- unsubscribes = [];
66
- }
67
- };
68
-
69
- plugin.start = async function (props: Config) {
70
- app.debug("Starting tides-api: " + JSON.stringify(props));
71
-
72
- // Use the selected source, or the first one if not specified
73
- const source = sources.find(source => source.id === props.source) || sources[0];
74
-
75
- // Load the selected source
76
- const provider = await source.start(props);
77
-
78
- // Register the source as a resource provider
79
- app.registerResourceProvider({
80
- type: "tides",
81
- methods: {
82
- async listResources(query) {
83
- return provider(query)
84
- },
85
- getResource(): never {
86
- throw new Error("Not implemented");
87
- },
88
- setResource(): never {
89
- throw new Error("Not implemented");
90
- },
91
- deleteResource(): never {
92
- throw new Error("Not implemented");
93
- }
94
- }
95
- });
96
-
97
- app.subscriptionmanager.subscribe(
98
- {
99
- context: "vessels." + app.selfId,
100
- subscribe: [
101
- {
102
- path: "navigation.position",
103
- period: (props.period ?? defaultPeriod) * 60 * 1000,
104
- policy: "fixed",
105
- },
106
- ],
107
- },
108
- unsubscribes,
109
- (subscriptionError) => {
110
- app.error("Error:" + subscriptionError);
111
- },
112
- (delta) => {
113
- // @ts-expect-error: TODO[TS]: fix Delta type upstream
114
- delta.updates.forEach(({ values }) => {
115
- // @ts-expect-error: TODO[TS]: fix Delta type upstream
116
- values.forEach(({ path }) => {
117
- if (path === "navigation.position") {
118
- performUpdate();
119
- }
120
- });
121
- });
122
- }
123
- );
124
-
125
- async function performUpdate() {
126
- try {
127
- const { extremes } = await provider();
128
-
129
- // Use server date, or current date if not available
130
- const now = new Date(app.getSelfPath("navigation.datetime.value") ?? Date.now());
131
-
132
- const nextTide: Partial<Record<TideExtremeType, { time: string, value: number }>> = {};
133
-
134
- extremes.forEach(({ type, value, time }) => {
135
- // Get the first tide of this type after now
136
- if (!nextTide[type] && new Date(time) > now) {
137
- nextTide[type] = { time, value };
138
- }
139
- });
140
-
141
- const delta = {
142
- context: "vessels." + app.selfId,
143
- updates: [
144
- {
145
- timestamp: now.toISOString(),
146
- values: Object.entries(nextTide).flatMap(
147
- ([type, { time, value }]) => {
148
- return [
149
- { path: `environment.tide.height${type}`, value: value },
150
- { path: `environment.tide.time${type}`, value: time },
151
- ];
152
- }
153
- ),
154
- },
155
- ],
156
- };
157
-
158
- app.debug("Sending delta: " + JSON.stringify(delta));
159
- app.handleMessage(plugin.id, delta);
160
- app.setPluginStatus("Updated tide data");
161
- } catch (e: unknown) {
162
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
163
- app.setPluginError((e as any).message);
164
- // @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
165
- app.error(e);
166
- }
167
- }
168
-
169
- // Perform initial update on startup
170
- performUpdate();
171
- }
172
-
173
- return plugin;
174
- }
@@ -1,111 +0,0 @@
1
- import path from 'path';
2
- import fs from 'fs/promises';
3
- import { getDistance } from 'geolib';
4
- import moment from 'moment';
5
- import type { SignalKApp, TideForecastParams, TideForecastResult, TideSource } from '../types.js';
6
- import type { NoaaPredictionApiResponse, NoaaStation, NoaaStationsApiResponse, NoaaTidePrediction } from '../types/noaa.js';
7
-
8
- const stationsUrl = `https://api.tidesandcurrents.noaa.gov/mdapi/prod/webapi/stations.json?type=tidepredictions`;
9
- const dataGetterUrl = 'https://api.tidesandcurrents.noaa.gov/api/prod/datagetter';
10
-
11
- const datum = 'MLLW';
12
-
13
- export default function (app: SignalKApp): TideSource {
14
- return {
15
- id: 'noaa',
16
- title: 'NOAA (US only)',
17
- async start() {
18
- const stations = await StationList.load(app);
19
-
20
- return async ({ date }: TideForecastParams = {}): Promise<TideForecastResult> => {
21
- const position = app.getSelfPath("navigation.position.value");
22
- if (!position) throw new Error("no position");
23
-
24
- const station = stations.closestTo(position);
25
-
26
- const endpoint = new URL(dataGetterUrl);
27
- endpoint.search = new URLSearchParams({
28
- product: "predictions",
29
- application: "signalk.org/node-server",
30
- begin_date: moment(date).format("YYYYMMDD"),
31
- end_date: moment(date).add(7, "days").format("YYYYMMDD"),
32
- datum,
33
- station: station.id,
34
- time_zone: "gmt",
35
- units: "metric",
36
- interval: "hilo",
37
- format: "json",
38
- }).toString();
39
-
40
- app.debug(`Fetching tides from NOAA: ${endpoint}`);
41
-
42
- try {
43
- const res = await fetch(endpoint.toString());
44
- if (!res.ok) throw new Error("Failed to fetch NOAA tides: " + res.statusText);
45
- const body = await res.json() as NoaaPredictionApiResponse;
46
- app.debug("NOAA response: \n" + JSON.stringify(body, null, 2));
47
-
48
- if (body.error) throw new Error(body.error.message);
49
-
50
- return {
51
- station: {
52
- name: station.name,
53
- position: {
54
- latitude: station.lat,
55
- longitude: station.lng,
56
- },
57
- },
58
- extremes: body.predictions.map(({ t, v, type }: NoaaTidePrediction) => ({
59
- type: type === "H" ? "High" : "Low",
60
- value: Number(v),
61
- time: new Date(`${t}Z`).toISOString(),
62
- })),
63
- };
64
- } catch (err) {
65
- app.setPluginError(`Failed to fetch NOAA tides: ${err}`);
66
- // @ts-expect-error: app.error should accept more than just a string
67
- app.error(err);
68
- throw err;
69
- }
70
- }
71
- }
72
- };
73
- };
74
-
75
- class StationList extends Map<string, NoaaStation> {
76
- static async load(app: SignalKApp): Promise<StationList> {
77
- const filename = path.join(app.config.configPath, "noaastations.json");
78
- let data: NoaaStationsApiResponse;
79
-
80
- try {
81
- data = JSON.parse(await fs.readFile(filename, 'utf-8'));
82
- app.debug("NOAA: Loaded cached tide stations from " + filename);
83
- } catch (e) {
84
- app.debug(`NOAA: failed to load cached tide stations: ${e}`)
85
- app.debug('NOAA: Downloading tide stations');
86
- const res = await fetch(stationsUrl);
87
- if (!res.ok) throw new Error(`Failed to download stations: ${res.statusText}`);
88
- data = await res.json() as NoaaStationsApiResponse;
89
- await fs.writeFile(filename, JSON.stringify(data));
90
- }
91
-
92
- return new this(data.stations);
93
- }
94
-
95
- constructor(data: NoaaStation[]) {
96
- super(data.map((station) => [station.id, station]));
97
- }
98
-
99
- closestTo(position: { latitude: number; longitude: number }): NoaaStation {
100
- return this.near(position, 1)[0];
101
- }
102
-
103
- near(position: { latitude: number; longitude: number }, limit = 10): NoaaStation[] {
104
- const stationsWithDistances = Array.from(this.values()).map((station) => ({
105
- ...station,
106
- distance: getDistance(position, { latitude: station.lat, longitude: station.lng })
107
- }));
108
-
109
- return stationsWithDistances.sort((a, b) => a.distance - b.distance).slice(0, limit);
110
- }
111
- }
@@ -1,64 +0,0 @@
1
- import type { SignalKApp, TideForecastParams, TideForecastResult, TideSource } from "../types.js";
2
- import type { StormGlassApiResponse } from "../types/stormglass.js";
3
- import moment from 'moment';
4
-
5
- export default function (app: SignalKApp): TideSource {
6
- return {
7
- id: 'stormglass',
8
- title: 'StormGlass.io',
9
- properties: {
10
- stormglassApiKey: {
11
- type: 'string',
12
- title: 'StormGlass.io API key'
13
- }
14
- },
15
-
16
- start({ stormglassApiKey } = {}) {
17
- app.debug("Using StormGlass.io API");
18
-
19
- return async (params: TideForecastParams = {}): Promise<TideForecastResult> => {
20
- const { date = moment().subtract(1, "days").toISOString() } = params;
21
- const endPoint = new URL("https://api.stormglass.io/v2/tide/extremes/point");
22
-
23
- const position = app.getSelfPath("navigation.position.value");
24
- if (!position) throw new Error("no position");
25
-
26
- endPoint.search = new URLSearchParams({
27
- start: moment(date).format("YYYY-MM-DD"),
28
- end: moment(date).add(7, "days").format("YYYY-MM-DD"),
29
- // datum: "CD",
30
- lat: position.latitude,
31
- lng: position.longitude,
32
- }).toString();
33
-
34
- app.debug("Fetching StormGlass.io: " + endPoint.toString());
35
-
36
- const res = await fetch(endPoint, {
37
- headers: { Authorization: stormglassApiKey ?? '' },
38
- });
39
-
40
- if (!res.ok) throw new Error('Failed to fetch StormGlass.io: ' + res.statusText);
41
-
42
- const data = await res.json() as StormGlassApiResponse;
43
- app.debug(JSON.stringify(data, null, 2));
44
-
45
- return {
46
- station: {
47
- name: data.meta.station.name,
48
- position: {
49
- latitude: data.meta.station.lat,
50
- longitude: data.meta.station.lng,
51
- },
52
- },
53
- extremes: data.data.map(({ type, time, height }) => {
54
- return {
55
- type: type === "high" ? "High" : "Low",
56
- value: height,
57
- time: new Date(time).toISOString(),
58
- };
59
- }),
60
- };
61
- };
62
- }
63
- }
64
- }
@@ -1,66 +0,0 @@
1
- import type { SignalKApp, TideForecastParams, TideForecastResult, TideSource } from "../types.js";
2
- import type { WorldTidesPredictionApiResponse } from "../types/worldtides.js";
3
- import moment from 'moment';
4
-
5
- export default function (app: SignalKApp): TideSource {
6
- return {
7
- id: 'WorldTides.info',
8
- title: 'worldtides.info',
9
- properties: {
10
- worldtidesApiKey: {
11
- type: 'string',
12
- title: 'worldtides.info API key'
13
- }
14
- },
15
-
16
- start({ worldtidesApiKey = '' } = {}) {
17
- app.debug("Using WorldTides API");
18
-
19
- return async (params: TideForecastParams = {}): Promise<TideForecastResult> => {
20
- const { date = moment().subtract(1, "days") } = params;
21
- const endPoint = new URL("https://www.worldtides.info/api/v3");
22
-
23
- const position = app.getSelfPath("navigation.position.value");
24
- if (!position) throw new Error("no position");
25
-
26
- endPoint.search = new URLSearchParams({
27
- date: moment(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
-
36
- app.debug("Fetching worldtides: " + endPoint.toString());
37
-
38
- const res = await fetch(endPoint);
39
- if (!res.ok) throw new Error('Failed to fetch worldtides: ' + res.statusText);
40
-
41
- const data = await res.json() as WorldTidesPredictionApiResponse;
42
- app.debug(JSON.stringify(data, null, 2));
43
-
44
- if (data.status != 200) throw new Error("worldtides data: " + data.error ? data.error : "none");
45
-
46
- return {
47
- station: {
48
- name: "WorldTides",
49
- position: {
50
- latitude: data.responseLat,
51
- longitude: data.responseLon,
52
- },
53
- },
54
- extremes: data.extremes.map(({ type, dt, height }) => {
55
- return {
56
- type,
57
- value: height,
58
- time: new Date(dt * 1000).toISOString(),
59
- };
60
- }),
61
- };
62
- };
63
-
64
- }
65
- }
66
- }
@@ -1,40 +0,0 @@
1
- export interface NoaaStationsApiResponse {
2
- count: number;
3
- stations: NoaaStation[];
4
- }
5
-
6
- export interface NoaaStation {
7
- state: string;
8
- tidepredoffsets: {
9
- self: string;
10
- };
11
- type: "R" | "S";
12
- timemeridian: number | null;
13
- reference_id: string;
14
- timezonecorr: number;
15
- id: string;
16
- name: string;
17
- lat: number;
18
- lng: number;
19
- affiliations: string;
20
- portscode: string;
21
- products: null;
22
- disclaimers: null;
23
- notices: null;
24
- self: null;
25
- expand: null;
26
- tideType: string;
27
- }
28
-
29
- interface NoaaPredictionApiResponse {
30
- predictions: NoaaTidePrediction[];
31
- error?: {
32
- message: string;
33
- }
34
- }
35
-
36
- interface NoaaTidePrediction {
37
- t: string;
38
- v: string;
39
- type: string;
40
- }
@@ -1,29 +0,0 @@
1
- export interface StormGlassApiResponse {
2
- data: StormGlassExtreme[];
3
- meta: StormGlassMeta;
4
- }
5
-
6
- export interface StormGlassExtreme {
7
- height: number;
8
- time: Date;
9
- type: "high" | "low";
10
- }
11
-
12
- export interface StormGlassMeta {
13
- cost: number;
14
- dailyQuota: number;
15
- end: string;
16
- lat: number;
17
- lng: number;
18
- requestCount: number;
19
- start: string;
20
- station: StormGlassStation;
21
- }
22
-
23
- export interface StormGlassStation {
24
- distance: number;
25
- lat: number;
26
- lng: number;
27
- name: string;
28
- source: string;
29
- }
@@ -1,19 +0,0 @@
1
- export interface WorldTidesPredictionApiResponse {
2
- status: number;
3
- error?: string;
4
- callCount: number;
5
- copyright: string;
6
- requestLat: number;
7
- requestLon: number;
8
- responseLat: number;
9
- responseLon: number;
10
- atlas: string;
11
- extremes: Extreme[];
12
- }
13
-
14
- export interface WorldTidesExtreme {
15
- dt: number;
16
- date: string;
17
- height: number;
18
- type: string;
19
- }
package/src/types.ts DELETED
@@ -1,48 +0,0 @@
1
- import { ServerAPI } from '@signalk/server-api';
2
- // TODO[TS]: remove these once @signalk/server-api has all the types needed.
3
- import { WithConfig } from 'signalk-server/lib/app.js';
4
- import { SignalKServer } from 'signalk-server/lib/types.js';
5
-
6
- // TODO[TS]: Fix this in the upstream types
7
- export type SignalKApp = ServerAPI & SignalKServer & WithConfig;
8
-
9
- export type OptionalPromise<T> = T | Promise<T>;
10
-
11
- export type TideExtremeType = "High" | "Low";
12
-
13
- export interface TideForecastParams {
14
- date?: string;
15
- }
16
-
17
- export interface TideExtreme {
18
- time: string;
19
- value: number;
20
- type: TideExtremeType;
21
- }
22
-
23
- export interface TideForecastResult {
24
- station: {
25
- name: string;
26
- position: {
27
- latitude: number;
28
- longitude: number;
29
- };
30
- }
31
- extremes: TideExtreme[];
32
- }
33
-
34
- export type TideForecastFunction = (params?: TideForecastParams) => OptionalPromise<TideForecastResult>;
35
-
36
- export interface TideSource {
37
- id: string;
38
- title: string;
39
- start: (props: Config) => OptionalPromise<TideForecastFunction>;
40
- properties?: unknown; // TODO: use schema?
41
- }
42
-
43
- export type Config = {
44
- source?: string;
45
- period?: number;
46
- worldtidesApiKey?: string;
47
- stormglassApiKey?: string;
48
- };
@@ -1,28 +0,0 @@
1
- {
2
- "status": 200,
3
- "callCount": 1,
4
- "copyright": "Tidal data retrieved from www.worldtide.info. Copyright (c) 2014-2017 Brainware LLC. Licensed for use of individual spatial coordinates on behalf of/by an end-user. Copyright (c) 2010-2016 Oregon State University. Licensed for individual spatial coordinates via ModEM-Geophysics Inc. NO GUARANTEES ARE MADE ABOUT THE CORRECTNESS OF THIS DATA. You may not use it if anyone or anything could come to harm as a result of using it (e.g. for navigational purposes).",
5
- "requestLat": 60.084516666667,
6
- "requestLon": 23.5391,
7
- "responseLat": 60,
8
- "responseLon": 24,
9
- "atlas": "TPXO_8_v1",
10
- "requestDatum": "LAT",
11
- "responseDatum": "LAT",
12
- "extremes": [{
13
- "dt": 1535574130,
14
- "date": "2018-08-29T20:22+0000",
15
- "height": 0.018,
16
- "type": "High"
17
- }, {
18
- "dt": 1535596057,
19
- "date": "2018-08-30T02:27+0000",
20
- "height": 0.014,
21
- "type": "Low"
22
- }, {
23
- "dt": 1535621815,
24
- "date": "2018-08-30T09:36+0000",
25
- "height": 0.021,
26
- "type": "High"
27
- }]
28
- }
package/vite.config.mts DELETED
@@ -1,16 +0,0 @@
1
- import { defineConfig } from 'vite'
2
- import react from '@vitejs/plugin-react'
3
- import tailwindcss from '@tailwindcss/vite'
4
-
5
- // https://vite.dev/config/
6
- export default defineConfig({
7
- base: './',
8
- publicDir: 'app/public',
9
- build: {
10
- outDir: 'public',
11
- },
12
- plugins: [
13
- tailwindcss(),
14
- react()
15
- ],
16
- })
File without changes