signalk-fixedstation 0.5.1 → 0.8.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 ADDED
@@ -0,0 +1,30 @@
1
+ # Change Log
2
+
3
+ Releases up to 0.6.0 are not documented here. 0.7.0 was an interim version on `dev` and is part of 0.8.0.
4
+
5
+ ## [0.8.0]
6
+
7
+ ### Feature
8
+ - Elevation provider *Open-Meteo* (default, free for non-commercial use without API key, customer API with an API key), *Google Maps* or *None*; one API key field for the selected provider. Configurations from before 0.8.0 with a Google API key keep Google - the provider is saved to their configuration.
9
+ - The elevation is also looked up for a configured position without elevation - it was looked up only for the position determined from the public IP address.
10
+ - The determined position and elevation are shown on the plugin status, lookup failures as plugin error (once per outage, cleared once the lookup succeeds again).
11
+ - Determined position and elevation are kept in the plugin data directory and published right away at the next start, also without internet; the elevation is looked up again only once the position or the provider changed.
12
+ - Failed lookups are retried after 1 minute, doubling up to 1 hour - they were tried once per start.
13
+ - With a `timeout` in the meta data of `navigation.position` or `navigation.gnss.antennaAltitude` the values are re-published at half of the timeout, so that they don't expire.
14
+ - Plugin logo, shown in the App Store of the SignalK server (`signalk.appIcon`).
15
+
16
+ ### Fix
17
+ - No public IP address (eg. no internet at boot) no longer causes an unhandled promise rejection, and the elevation is no longer looked up for an empty position.
18
+ - A network error or timeout of the elevation lookup no longer crashes the error handling; the Google API is no longer called without API key.
19
+ - Lookups still pending on stop or restart no longer publish values of the stopped plugin.
20
+ - A position on the equator or the prime meridian (0) is valid.
21
+ - Configuration schema: `required` listed field names that don't exist (`lat`, `lon`), the latitude defaulted to an empty text.
22
+ - Unset position or elevation values are no longer published - an empty delta on startup is avoided.
23
+ - The altitude meta no longer carries a `pgn` (not a meta field).
24
+
25
+ ### Update
26
+ - Elevation lookups via `fetch` - `@googlemaps/google-maps-services-js` and axios removed; `geoip-lite` (GeoLite data in memory) is loaded only when the position is determined from the public IP address.
27
+ - Logging via the `signalk-fixedstation` debug log.
28
+ - Package updates.
29
+ - Release to NPM via npm trusted publishing (OIDC) on a push to `main`; the package contents are whitelisted (`files`), tests and repository files are no longer published.
30
+ - SignalK Plugin CI and automated tests (`npm test`) - no network access required.
package/README.md CHANGED
@@ -1,11 +1,63 @@
1
1
  # signalk-fixedstation-plugin
2
- SignalK Plugin to inject fixed station data in absence of GPS input (eg. for weather-station or marina use)
3
- # Install & Use
4
- Note: This plugin can be used to calculate elevation via '@googlemaps/google-maps-services-js', but requires a google API subscription - hence, the feature is deactivated by design.<br><br>
5
- <p>Install the plugin through the SignalK plugin interface. After installation you can either enter the fixed position / elevation or you may want to 'Activate' automatic updates through the SignalK Plugin Config interface - nearest position will be determined based on public IP assgined to the SignalK server.</p>
6
- <br>
7
- <p>The plugin will output 2 new SignalK-values:<br>
8
- <br>
9
- <code>'navigation.position'</code><br>
10
- <code>'navigation.gnss.antennaAltitude'</code><br>
11
- <br></p>
2
+
3
+ SignalK plugin to inject fixed station data in absence of GPS input (e.g. for weather-station or marina use).
4
+
5
+ ## Install & Use
6
+
7
+ Install the plugin through the SignalK plugin interface and configure it in the *Plugin Config*:
8
+
9
+ - **Position** - enter latitude / longitude, or *Determine the position from the public IP address* at every
10
+ start. The location of the public IP address is looked up locally in the GeoLite data bundled with
11
+ [`geoip-lite`](https://www.npmjs.com/package/geoip-lite) (city level); only the public IP address itself is
12
+ determined online ([`public-ip`](https://www.npmjs.com/package/public-ip): DNS queries to OpenDNS / Google,
13
+ HTTPS fallback icanhazip / ipify). No online geolocation service learns the position.
14
+ - **Elevation** - enter it, or leave it empty to look it up for the position from the elevation provider:
15
+ - *Open-Meteo* (default): [Elevation API](https://open-meteo.com/en/docs/elevation-api), free for non-commercial
16
+ use without API key. With an API key the customer API is used (commercial use, see
17
+ [pricing](https://open-meteo.com/en/pricing)). Returns 0 over sea.
18
+ - *Google Maps*: [Elevation API](https://developers.google.com/maps/documentation/elevation), requires an API key.
19
+ - *None*: no elevation lookup.
20
+
21
+ There is one API key field - change the key together with the provider. Configurations from before 0.8.0
22
+ with a Google API key keep Google as provider.
23
+
24
+ The plugin publishes
25
+
26
+ - `navigation.position` (latitude, longitude and - once known - altitude)
27
+ - `navigation.gnss.antennaAltitude` (m above sea level)
28
+
29
+ The determined position and elevation are shown on the plugin status, eg.
30
+ `Position 52.5200° N, 13.4050° E (public IP) · elevation 38 m (Open-Meteo)`. Determined values are kept in the
31
+ plugin data directory and published right away at the next start - also without internet; failed lookups are
32
+ reported as plugin error and retried after 1 minute, doubling up to 1 hour.
33
+
34
+ The values are published at start and when they change. If a `timeout` is set in the meta data of the paths
35
+ (eg. in the *Data Browser* of the server), they are re-published at half of the timeout, so that they don't expire.
36
+
37
+ ### Data sources
38
+
39
+ - Elevation data from [Open-Meteo.com](https://open-meteo.com/) under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/),
40
+ based on the Copernicus DEM GLO-90 ([doi:10.5270/ESA-c5d3d65](https://doi.org/10.5270/ESA-c5d3d65)) of the
41
+ European Union's Copernicus programme.
42
+ - This product includes GeoLite data created by MaxMind, available from [maxmind.com](https://www.maxmind.com).
43
+
44
+ ## Development
45
+
46
+ The plugin ships with baseline and lifecycle tests based on the built-in
47
+ [`node:test`](https://nodejs.org/api/test.html) runner — no services or network access required:
48
+
49
+ ```sh
50
+ npm install
51
+ npm test
52
+ ```
53
+
54
+ - [`test/baseline.test.js`](./test/baseline.test.js) verifies the plugin interface, the configuration
55
+ schema, the migration of the elevation provider and the deltas published for a configured position and elevation.
56
+ - [`test/lifecycle.test.js`](./test/lifecycle.test.js) runs the dynamic lifecycle — start, IP based position
57
+ lookup, elevation lookup from Open-Meteo / Google, cached values, retries, meta timeout, stop — against a
58
+ stubbed geolocation module and a stubbed `fetch`.
59
+
60
+ ***
61
+
62
+ ## Release Notes
63
+ See [Changelog](CHANGELOG.md).
package/elevation.js ADDED
@@ -0,0 +1,80 @@
1
+ 'use strict'
2
+ /*
3
+ Terrain elevation of a position from an online provider.
4
+ - Open-Meteo Elevation API (Copernicus DEM GLO-90, 90 m): free for non-commercial use without API key,
5
+ with an API key the customer API is used (commercial use). Over sea it returns 0.
6
+ - Google Maps Elevation API: requires an API key.
7
+ Errors never contain the request URL - it may carry the API key.
8
+ */
9
+
10
+ const TIMEOUT = 10000
11
+
12
+ const PROVIDERS = {
13
+ 'open-meteo': {
14
+ name: 'Open-Meteo',
15
+ keyRequired: false,
16
+ url: (lat, lon, apikey) => {
17
+ const params = new URLSearchParams({ latitude: String(lat), longitude: String(lon) })
18
+ if (apikey) params.set('apikey', apikey)
19
+ return `${apikey ? 'https://customer-api.open-meteo.com' : 'https://api.open-meteo.com'}/v1/elevation?${params}`
20
+ },
21
+ parse: (status, json) => {
22
+ if (status !== 200 || !json || json.error)
23
+ throw new Error(`HTTP ${status}${json && json.reason ? ' - ' + json.reason : ''}`)
24
+ const value = Array.isArray(json.elevation) ? json.elevation[0] : undefined
25
+ if (typeof value !== 'number' || Number.isNaN(value))
26
+ throw new Error('no elevation in the response')
27
+ return value
28
+ }
29
+ },
30
+ google: {
31
+ name: 'Google',
32
+ keyRequired: true,
33
+ url: (lat, lon, apikey) => {
34
+ const params = new URLSearchParams({ locations: `${lat},${lon}`, key: apikey })
35
+ return `https://maps.googleapis.com/maps/api/elevation/json?${params}`
36
+ },
37
+ parse: (status, json) => {
38
+ if (status !== 200 || !json || json.status !== 'OK')
39
+ throw new Error(`${json && json.status ? json.status : 'HTTP ' + status}${json && json.error_message ? ' - ' + json.error_message : ''}`)
40
+ const value = Array.isArray(json.results) && json.results[0] ? json.results[0].elevation : undefined
41
+ if (typeof value !== 'number' || Number.isNaN(value))
42
+ throw new Error('no elevation in the response')
43
+ return value
44
+ }
45
+ }
46
+ }
47
+
48
+ function providerName(provider) {
49
+ return PROVIDERS[provider] ? PROVIDERS[provider].name : provider
50
+ }
51
+
52
+ // @returns {Promise<number>} elevation in m above sea level
53
+ async function lookup(provider, lat, lon, apikey) {
54
+ const p = PROVIDERS[provider]
55
+ if (!p)
56
+ throw new Error(`unknown elevation provider '${provider}'`)
57
+ if (p.keyRequired && !apikey)
58
+ throw new Error(`${p.name} requires an API key`)
59
+ let response
60
+ try {
61
+ response = await fetch(p.url(lat, lon, apikey), { signal: AbortSignal.timeout(TIMEOUT) })
62
+ } catch (err) {
63
+ // network errors and timeouts - the cause carries the reason (eg. ENOTFOUND), never the URL
64
+ const reason = err && err.cause && err.cause.code ? err.cause.code : (err && err.name === 'TimeoutError' ? 'timeout' : 'network error')
65
+ throw new Error(`${p.name}: ${reason}`)
66
+ }
67
+ let json = null
68
+ try { json = await response.json() } catch { /* no JSON body */ }
69
+ try {
70
+ return p.parse(response.status, json)
71
+ } catch (err) {
72
+ throw new Error(`${p.name}: ${err.message}`)
73
+ }
74
+ }
75
+
76
+ module.exports = {
77
+ PROVIDERS,
78
+ providerName,
79
+ lookup
80
+ }
package/fixedstation.js CHANGED
@@ -1,146 +1,323 @@
1
- const geoloc = require('./geoloc');
2
-
3
- const navigationPosition = 'navigation.position';
4
- const navigationElevation = 'navigation.gnss.antennaAltitude';
5
- let deltahandler = null;
6
- let log = null;
7
-
8
- const latest = {
9
- position: {
10
- time: null,
11
- lat: null,
12
- lon: null
13
- },
14
- altitude: {
15
- time: null,
16
- elevation: null
17
- }
1
+ 'use strict'
2
+ /*
3
+ Fixed station - publishes a position and elevation in absence of a GPS.
4
+ - position: configured, or determined from the public IP address at every start
5
+ - elevation: configured, or looked up from the elevation provider for the position
6
+ Determined values are cached in the plugin data directory and published right away at the next start
7
+ (no internet at boot), lookups that fail are retried with a growing delay.
8
+ */
9
+ const fs = require('fs')
10
+ const path = require('path')
11
+ const geoloc = require('./geoloc')
12
+ const elevation = require('./elevation')
13
+
14
+ const POSITION = 'navigation.position'
15
+ const ALTITUDE = 'navigation.gnss.antennaAltitude'
16
+ const CACHE_FILE = 'station.json'
17
+ const PROVIDERS = ['open-meteo', 'google', 'none']
18
+
19
+ // seconds - exported for the tests
20
+ const timing = {
21
+ retryFirst: 60, // first retry of a failed lookup, doubling ...
22
+ retryMax: 3600, // ... up to one hour
23
+ republishMin: 1, // shortest re-publish interval for a meta timeout
24
+ republishCheck: 60, // check for a meta timeout without one
18
25
  }
19
26
 
20
- function onPositionUpdated(lat, lon) {
21
- latest.position.time = Date.now();
22
- latest.position.lat = lat;
23
- latest.position.lon = lon;
27
+ function isNumber(value) {
28
+ return typeof value === 'number' && Number.isFinite(value)
29
+ }
24
30
 
25
- if (lat && typeof lat==="number" && lon && typeof lon==="number")
26
- {
27
- let update = []
28
- update.push(buildDelta(navigationPosition, formatPosition()))
29
- deltahandler(update);
30
- }
31
+ function toNumber(value) {
32
+ if (typeof value === 'string' && value.trim() !== '')
33
+ value = Number(value)
34
+ return isNumber(value) ? value : undefined
31
35
  }
32
36
 
33
- function onAltitudeUpdated(elevation) {
34
- latest.altitude.time = Date.now();
35
- latest.altitude.elevation = elevation;
37
+ function isPosition(lat, lon) {
38
+ return isNumber(lat) && isNumber(lon) && Math.abs(lat) <= 90 && Math.abs(lon) <= 180
39
+ }
36
40
 
37
- if (elevation && typeof elevation==="number")
38
- {
39
- let update = []
40
- update.push(buildDelta(navigationElevation, formatAltitude()))
41
- deltahandler(update);
42
- }
41
+ function samePosition(a, b) {
42
+ return !!a && !!b && Math.abs(a.latitude - b.latitude) < 1e-6 && Math.abs(a.longitude - b.longitude) < 1e-6
43
43
  }
44
44
 
45
- function buildDelta(path, value) {
45
+ function formatPosition(p) {
46
+ const lat = `${Math.abs(p.latitude).toFixed(4)}° ${p.latitude < 0 ? 'S' : 'N'}`
47
+ const lon = `${Math.abs(p.longitude).toFixed(4)}° ${p.longitude < 0 ? 'W' : 'E'}`
48
+ return `${lat}, ${lon}`
49
+ }
50
+
51
+ function formatDelay(seconds) {
52
+ return seconds < 120 ? `${Math.round(seconds)}s` : `${Math.round(seconds / 60)} min`
53
+ }
54
+
55
+ // plugin options → configuration; an unknown provider falls back to Google for configurations with
56
+ // an API key (installs before 0.8.0 only knew Google), Open-Meteo otherwise
57
+ function normalize(options) {
58
+ const o = options || {}
59
+ const apikey = typeof o.apikey === 'string' ? o.apikey.trim() : ''
60
+ const provider = PROVIDERS.includes(o.elevationProvider) ? o.elevationProvider : (apikey ? 'google' : 'open-meteo')
46
61
  return {
47
- path: path,
48
- value: value
62
+ latitude: toNumber(o.latitude),
63
+ longitude: toNumber(o.longitude),
64
+ elevation: toNumber(o.elevation),
65
+ dynamic: o.dynamic === true,
66
+ provider,
67
+ apikey,
49
68
  }
50
69
  }
51
70
 
52
- function prepareFixed() {
53
- let update = []
54
- let meta = []
55
- if (latest.position.lat!==null && latest.position.lon!==null)
56
- update.push(buildDelta(navigationPosition, formatPosition()))
57
- if (latest.altitude.elevation!==null) {
58
- update.push(buildDelta(navigationElevation, formatAltitude()))
59
- meta.push(buildDelta(navigationElevation, { "units": "m", "description": "Altitude above sealevel", "pgn":129029 } ))
71
+ function create(app, sourceId, config, log) {
72
+ let running = false
73
+ let generation = 0
74
+ const timers = new Set()
75
+
76
+ let position = null // { latitude, longitude, source }
77
+ let altitude = null // { value, source, latitude?, longitude?, provider? }
78
+ let cache = {}
79
+ let metaSent = false
80
+ const errors = {} // kind → reported reason
81
+ const retries = {} // kind → { delay, next }
82
+
83
+ const stale = (started) => !running || started !== generation
84
+
85
+ function later(started, fn, ms) {
86
+ const id = setTimeout(() => {
87
+ timers.delete(id)
88
+ if (!stale(started)) fn()
89
+ }, ms)
90
+ timers.add(id)
60
91
  }
61
- return { "update": update, "meta": meta }
62
- }
63
92
 
64
- function prepareMeta(alt) {
65
- let update = []
66
- let meta = []
67
- update.push(buildDelta(navigationElevation, alt && typeof alt==="number" ? alt : 0 ))
68
- meta.push(buildDelta(navigationElevation, { "units": "m", "description": "Altitude above sealevel", "pgn":129029 } ))
69
- return { "update": update, "meta": meta }
70
- }
93
+ // cache
71
94
 
72
- async function prepareDynamic (callback) {
73
- await geoloc.getIP('v4')
74
- .then (ip => {
75
- let geo = geoloc.getGeo(ip)
76
- if (ip && geo) {
77
- log(`Fixed Position determined [${geo.ll[0]},${geo.ll[1]}]`)
78
- onPositionUpdated(geo.ll[0], geo.ll[1])
95
+ function cacheFile() {
96
+ const dir = typeof app.getDataDirPath === 'function' ? app.getDataDirPath() : null
97
+ return dir ? path.join(dir, CACHE_FILE) : null
98
+ }
79
99
 
80
- } else {
81
- log(`Failed to determine position via external IP [${ip}].`)
100
+ function readCache() {
101
+ const file = cacheFile()
102
+ if (!file) return {}
103
+ try {
104
+ const data = JSON.parse(fs.readFileSync(file, 'utf8'))
105
+ return data && typeof data === 'object' ? data : {}
106
+ } catch (err) {
107
+ if (err.code !== 'ENOENT') log(`Cache ${file} not readable (${err.message}) - ignored`)
108
+ return {}
82
109
  }
83
- })
84
- .finally(() => {
85
- geoloc.callElevation(latest.position.lat, latest.position.lon, (e) => {
86
- if (e && typeof e==='number')
87
- {
88
- log(`Elevation determined for [${latest.position.lat},${latest.position.lon}] to ${e}m`)
89
- onAltitudeUpdated(Math.round(e*1000)/1000)
90
- } else {
91
- log(`Failed to determin elevation: ${e}`)
92
- }
93
-
94
- })
95
- })
96
- }
110
+ }
97
111
 
98
- function formatPosition()
99
- {
100
- let value = {
101
- "latitude": latest.position.lat,
102
- "longitude": latest.position.lon,
103
- }
104
- if (latest.altitude.elevation!==null)
105
- value.altitude = latest.altitude.elevation
112
+ function writeCache() {
113
+ const file = cacheFile()
114
+ if (!file) return
115
+ if (position && position.source === 'public IP')
116
+ cache.position = { latitude: position.latitude, longitude: position.longitude }
117
+ if (altitude && altitude.provider)
118
+ cache.elevation = { value: altitude.value, provider: altitude.provider, latitude: altitude.latitude, longitude: altitude.longitude }
119
+ cache.updated = new Date().toISOString()
120
+ try {
121
+ fs.writeFileSync(`${file}.tmp`, JSON.stringify(cache, null, 2))
122
+ fs.renameSync(`${file}.tmp`, file)
123
+ } catch (err) {
124
+ log(`Cache ${file} not written (${err.message})`)
125
+ }
126
+ }
106
127
 
107
- return value;
108
- }
128
+ // SignalK
109
129
 
110
- function formatAltitude()
111
- {
112
- return latest.altitude.elevation;
113
- }
130
+ function publish() {
131
+ const values = []
132
+ if (position) {
133
+ const value = { latitude: position.latitude, longitude: position.longitude }
134
+ if (altitude) value.altitude = altitude.value
135
+ values.push({ path: POSITION, value })
136
+ }
137
+ if (altitude)
138
+ values.push({ path: ALTITUDE, value: altitude.value })
139
+ if (values.length === 0) return
140
+ app.handleMessage(sourceId, { updates: [{ values }] })
141
+ if (altitude && !metaSent) {
142
+ app.handleMessage(sourceId, { updates: [{ meta: [{ path: ALTITUDE, value: { units: 'm', description: 'Altitude above sea level' } }] }] })
143
+ metaSent = true
144
+ }
145
+ }
114
146
 
115
- module.exports = {
147
+ // a meta timeout on the published paths (eg. set in the server's data browser) means the value expires -
148
+ // it is re-published at half of the shortest timeout, no timer without timeout
149
+ function metaTimeout() {
150
+ if (typeof app.getSelfPath !== 'function') return undefined
151
+ const timeouts = [POSITION, ALTITUDE]
152
+ .map(p => app.getSelfPath(p))
153
+ .map(node => node && node.meta ? toNumber(node.meta.timeout) : undefined)
154
+ .filter(t => t > 0)
155
+ return timeouts.length > 0 ? Math.min(...timeouts) : undefined
156
+ }
116
157
 
117
- // initialize
118
- init: function(config, loghandler, messagehandler) {
119
- geoloc.init(config)
120
- log = loghandler
121
- deltahandler = messagehandler
122
- },
123
-
124
- // clear all data
125
- clearAll: function () {
126
- latest.position.lat = null;
127
- latest.position.lon = null;
128
- latest.altitude.elevation = null;
129
- },
130
-
131
- // @param {bool} value calculate from external IP.
132
- // @returns {Array<[{path:path, value:value}]>} Delta JSON-array of updates
133
- onLoad: function(lat, lon, elev, calc) {
134
- if (calc) // throw new Error("Cannot add null value");
135
- {
136
- prepareDynamic();
137
- return prepareMeta(elev);
158
+ function scheduleRepublish(started) {
159
+ // without timeout check again in a minute - a timeout may be configured meanwhile
160
+ const next = () => {
161
+ const timeout = metaTimeout()
162
+ return (timeout ? Math.max(timing.republishMin, timeout / 2) : timing.republishCheck) * 1000
163
+ }
164
+ const check = () => {
165
+ if (metaTimeout()) publish()
166
+ later(started, check, next())
138
167
  }
168
+ later(started, check, next())
169
+ }
170
+
171
+ // status and errors
172
+
173
+ function status() {
174
+ const parts = []
175
+ if (position)
176
+ parts.push(`Position ${formatPosition(position)} (${position.source})`)
139
177
  else
140
- {
141
- onPositionUpdated(lat, lon);
142
- onAltitudeUpdated(elev);
143
- return prepareFixed();
178
+ parts.push(config.dynamic ? 'Position from the public IP address pending' : 'No position configured')
179
+ if (altitude)
180
+ parts.push(`elevation ${Math.round(altitude.value * 10) / 10} m (${altitude.source})`)
181
+ else if (position && config.provider !== 'none')
182
+ parts.push(`elevation from ${elevation.providerName(config.provider)} pending`)
183
+ Object.keys(errors).forEach(kind => {
184
+ if (retries[kind] && retries[kind].next)
185
+ parts.push(`${kind} lookup again in ${formatDelay((retries[kind].next - Date.now()) / 1000)}`)
186
+ })
187
+ app.setPluginStatus(parts.join(' · '))
188
+ }
189
+
190
+ function fail(started, kind, reason, retry) {
191
+ if (errors[kind] !== reason) {
192
+ log(reason)
193
+ app.setPluginError(reason)
194
+ errors[kind] = reason
144
195
  }
196
+ if (retry) {
197
+ const r = retries[kind] || (retries[kind] = { delay: timing.retryFirst })
198
+ r.next = Date.now() + r.delay * 1000
199
+ later(started, retry, r.delay * 1000)
200
+ r.delay = Math.min(r.delay * 2, timing.retryMax)
201
+ }
202
+ status()
203
+ }
204
+
205
+ function recovered(kind) {
206
+ delete retries[kind]
207
+ if (!errors[kind]) return
208
+ log(`${kind} lookup succeeded again`)
209
+ delete errors[kind]
210
+ // an empty status removes the reported error from the plugin state
211
+ if (Object.keys(errors).length === 0)
212
+ app.setPluginStatus('')
145
213
  }
146
- }
214
+
215
+ // lookups
216
+
217
+ function needsElevation() {
218
+ if (!position || isNumber(config.elevation) || config.provider === 'none') return false
219
+ return !(altitude && altitude.provider === config.provider && samePosition(altitude, position))
220
+ }
221
+
222
+ async function determinePosition(started) {
223
+ let geo
224
+ try {
225
+ const ip = await geoloc.getIP('v4')
226
+ geo = ip ? geoloc.getGeo(ip) : null
227
+ if (!geo || !Array.isArray(geo.ll) || !isPosition(geo.ll[0], geo.ll[1]))
228
+ throw new Error('no location known for the public IP address')
229
+ } catch (err) {
230
+ if (stale(started)) return
231
+ fail(started, 'position', `Position not determined from the public IP address (${err && err.message ? err.message : err})`,
232
+ () => determinePosition(started))
233
+ return
234
+ }
235
+ if (stale(started)) return
236
+ recovered('position')
237
+ const determined = { latitude: geo.ll[0], longitude: geo.ll[1], source: 'public IP' }
238
+ log(`Position determined from the public IP address: ${formatPosition(determined)}`)
239
+ if (!samePosition(determined, position) && altitude && altitude.source !== 'configured')
240
+ altitude = null
241
+ position = determined
242
+ writeCache()
243
+ publish()
244
+ status()
245
+ if (needsElevation())
246
+ lookupElevation(started)
247
+ }
248
+
249
+ async function lookupElevation(started) {
250
+ const at = position
251
+ let value
252
+ try {
253
+ value = await elevation.lookup(config.provider, at.latitude, at.longitude, config.apikey)
254
+ } catch (err) {
255
+ if (stale(started)) return
256
+ // a missing API key does not resolve by itself - no retry
257
+ const permanent = config.provider === 'google' && !config.apikey
258
+ fail(started, 'elevation', `Elevation not determined (${err && err.message ? err.message : err})`,
259
+ permanent ? null : () => { if (needsElevation()) lookupElevation(started) })
260
+ return
261
+ }
262
+ if (stale(started) || !samePosition(at, position)) return
263
+ recovered('elevation')
264
+ altitude = {
265
+ value: Math.round(value * 1000) / 1000,
266
+ source: elevation.providerName(config.provider),
267
+ provider: config.provider,
268
+ latitude: at.latitude,
269
+ longitude: at.longitude,
270
+ }
271
+ log(`Elevation determined for ${formatPosition(at)}: ${altitude.value} m (${altitude.source})`)
272
+ writeCache()
273
+ publish()
274
+ status()
275
+ }
276
+
277
+ return {
278
+ start() {
279
+ running = true
280
+ const started = ++generation
281
+ cache = readCache()
282
+
283
+ if (!config.dynamic && isPosition(config.latitude, config.longitude))
284
+ position = { latitude: config.latitude, longitude: config.longitude, source: 'configured' }
285
+ else if (config.dynamic && cache.position && isPosition(cache.position.latitude, cache.position.longitude))
286
+ position = { latitude: cache.position.latitude, longitude: cache.position.longitude, source: 'public IP, cached' }
287
+
288
+ if (isNumber(config.elevation))
289
+ altitude = { value: config.elevation, source: 'configured' }
290
+ else if (position && config.provider !== 'none' && cache.elevation && cache.elevation.provider === config.provider
291
+ && isNumber(cache.elevation.value) && samePosition(cache.elevation, position))
292
+ altitude = { ...cache.elevation, source: `${elevation.providerName(config.provider)}, cached` }
293
+
294
+ log(`Started - position ${position ? formatPosition(position) + ' (' + position.source + ')' : 'none'}, ` +
295
+ `elevation ${altitude ? altitude.value + ' m (' + altitude.source + ')' : 'none'}, ` +
296
+ `${config.dynamic ? 'position from the public IP address, ' : ''}elevation provider ${config.provider}`)
297
+ publish()
298
+ status()
299
+ scheduleRepublish(started)
300
+
301
+ if (config.dynamic)
302
+ determinePosition(started)
303
+ else if (needsElevation())
304
+ lookupElevation(started)
305
+ },
306
+
307
+ stop() {
308
+ running = false
309
+ generation++
310
+ timers.forEach(clearTimeout)
311
+ timers.clear()
312
+ },
313
+ }
314
+ }
315
+
316
+ module.exports = {
317
+ POSITION,
318
+ ALTITUDE,
319
+ PROVIDERS,
320
+ timing,
321
+ normalize,
322
+ create,
323
+ }
package/geoloc.js CHANGED
@@ -1,90 +1,29 @@
1
- const geoip = require('geoip-lite')
2
-
3
- let maps_api_key
4
-
5
- function init(config)
6
- {
7
- maps_api_key = config.apikey
8
- }
9
-
10
- async function getIP(version)
11
- {
12
- let result
13
- if (!version || version==='v4')
14
- {
15
- const { publicIpv4 } = await import('public-ip')
16
- await publicIpv4()
17
- .then((res) => {
18
- result = res
19
- })
20
- }
21
- else if (version==='v6')
22
- {
23
- const { publicIpv6 } = await import('public-ip')
24
- await publicIpv6({
25
- fallbackUrls: [
26
- 'https://ifconfig.co/ip'
27
- ]
28
- }).then((res) => {
29
- result = res
30
- })
31
- }
32
- else
33
- return undefined
34
- return result
1
+ 'use strict'
2
+ /*
3
+ Position from the public IP address.
4
+ - public IP: `public-ip` (DNS OpenDNS / Google, HTTPS fallback icanhazip / ipify)
5
+ - location: MaxMind GeoLite data bundled with `geoip-lite`, looked up locally - no online geolocation service.
6
+ geoip-lite reads its data files into memory when required, hence it is loaded only when a position is determined.
7
+ */
8
+
9
+ let geoip = null
10
+
11
+ // @returns {Promise<string>} public IP address, rejects if it cannot be determined (eg. no internet)
12
+ async function getIP(version = 'v4') {
13
+ const { publicIpv4, publicIpv6 } = await import('public-ip')
14
+ if (version === 'v6')
15
+ return publicIpv6({ fallbackUrls: ['https://ifconfig.co/ip'] })
16
+ return publicIpv4()
35
17
  }
36
18
 
37
- function getGeo(ip)
38
- {
19
+ // @returns {{ ll: [number, number] } | null} geoip-lite record of the IP address
20
+ function getGeo(ip) {
21
+ if (!geoip)
22
+ geoip = require('geoip-lite')
39
23
  return geoip.lookup(ip)
40
24
  }
41
25
 
42
- function getElevation (lat, lon) {
43
-
44
- const { Client } = require("@googlemaps/google-maps-services-js");
45
- const client = new Client({});
46
-
47
- client
48
- .elevation({
49
- params: {
50
- locations: [{ lat: lat, lng: lon }],
51
- key: config.google.maps.key,
52
- },
53
- timeout: 1000, // milliseconds
54
- })
55
- .then((r) => {
56
- return r.data.results[0].elevation;
57
- })
58
- .catch((e) => {
59
- return e.response.data.error_message;
60
- });
61
- }
62
-
63
- async function callElevation (lat, lon, callback) {
64
-
65
- const { Client } = require("@googlemaps/google-maps-services-js");
66
- const client = new Client({});
67
-
68
- client
69
- .elevation({
70
- params: {
71
- locations: [{ lat: lat, lng: lon }],
72
- key: maps_api_key,
73
- },
74
- timeout: 1000, // milliseconds
75
- })
76
- .then((r) => {
77
- callback(r.data.results[0].elevation);
78
- })
79
- .catch((e) => {
80
- callback(e.response.data.error_message);
81
- });
82
- }
83
-
84
- module.exports = {
85
- init,
26
+ module.exports = {
86
27
  getIP,
87
- getGeo,
88
- getElevation,
89
- callElevation
90
- };
28
+ getGeo
29
+ }
package/img/logo.png ADDED
Binary file
package/index.js CHANGED
@@ -1,92 +1,78 @@
1
1
  'use strict'
2
- const fs = require('./fixedstation')
2
+ const log = require('debug')('signalk-fixedstation')
3
+ const station = require('./fixedstation')
3
4
 
4
5
  module.exports = function (app) {
5
- var plugin = {};
6
+ let current = null
6
7
 
7
- plugin.id = 'signalk-fixedstation';
8
- plugin.name = 'Fixed Station';
9
- plugin.description = 'Provide fixed navigation data (position, altitude)';
10
-
11
- var unsubscribes = [ fs.clearAll ];
8
+ const plugin = {
9
+ id: 'signalk-fixedstation',
10
+ name: 'Fixed Station',
11
+ description: 'Provide fixed navigation data (position, altitude)',
12
+ }
12
13
 
13
- plugin.start = function (options, restartPlugin) {
14
- app.debug('Plugin starting ...');
15
- fs.init(options, log, sendDelta);
16
- let delta = fs.onLoad(options["latitude"], options["longitude"], options["elevation"], options["dynamic"]);
17
- app.debug('Plugin started.');
18
-
19
- if (delta && delta.update && delta.update.length>0) {
20
- sendDelta(delta.update);
21
- if (delta.meta && delta.meta.length>0)
22
- sendMeta(delta.meta);
14
+ plugin.start = function (options) {
15
+ if (current) current.stop()
16
+ const config = station.normalize(options)
17
+ // configurations before 0.8.0 have no provider - keep Google for those with an API key and save
18
+ // the provider, so that the configuration form shows it instead of the default
19
+ if (!options || options.elevationProvider === undefined) {
20
+ app.savePluginOptions({ ...(options || {}), elevationProvider: config.provider }, (err) => {
21
+ if (err) log(`Elevation provider not saved to the configuration (${err.message || err})`)
22
+ else log(`Elevation provider '${config.provider}' saved to the configuration`)
23
+ })
23
24
  }
24
- };
25
+ current = station.create(app, plugin.id, config, log)
26
+ current.start()
27
+ }
25
28
 
26
29
  plugin.stop = function () {
27
- unsubscribes.forEach(f => f());
28
- unsubscribes = [];
29
- app.debug('Plugin stopped');
30
- };
30
+ if (current) current.stop()
31
+ current = null
32
+ log('Stopped')
33
+ }
31
34
 
32
35
  plugin.schema = {
33
- // The plugin schema
34
- type: "object",
35
- title: "FixedStation Configuration",
36
- description: "Configure fixed navigation data (position, altitude)",
37
- required: ['lat', 'lon', 'elevation'],
36
+ type: 'object',
37
+ title: 'Fixed Station',
38
+ description: 'Publishes navigation.position and navigation.gnss.antennaAltitude of a fixed station (weather station, marina) in absence of a GPS - the determined position and elevation are shown on the plugin status.',
38
39
  properties: {
39
- latitude: {
40
- type: 'number',
41
- title: 'Latitude. Used to export navigation.position',
42
- default: ''
43
- },
44
- longitude: {
45
- type: 'number',
46
- title: 'Longitude. Used to export navigation.position',
47
- },
48
- dynamic: {
49
- type: "boolean",
50
- title: "Overwrite with position from external IP address",
51
- description: "When enabled the position is dynamically determined at plugin start.",
52
- default: false
53
- },
54
- elevation: {
55
- type: 'number',
56
- title: 'Elevation above sea level. Used to export navigation.gnss.antennaAltitude'
57
- },
58
- apikey: {
59
- type: 'string',
60
- title: 'Google Maps API Key. Elevation data for any point in the world.'
61
- }
62
- }
63
- };
64
-
65
- /**
66
- *
67
- * @param {Array<[{path:path, value:value}]>} messages
68
- */
69
- function sendDelta(messages) {
70
- app.handleMessage('signalk-fixedstation', {
71
- updates: [
72
- {
73
- values: messages
74
- }
75
- ]
76
- })
77
- }
78
-
79
- function sendMeta(units) {
80
- app.handleMessage('signalk-fixedstation', {
81
- updates: [
82
- {
83
- meta: units
84
- }
85
- ]
86
- })
40
+ latitude: {
41
+ type: 'number',
42
+ title: 'Latitude',
43
+ description: 'Decimal degrees (WGS84), negative south - published on navigation.position',
44
+ },
45
+ longitude: {
46
+ type: 'number',
47
+ title: 'Longitude',
48
+ description: 'Decimal degrees (WGS84), negative west - published on navigation.position',
49
+ },
50
+ dynamic: {
51
+ type: 'boolean',
52
+ title: 'Determine the position from the public IP address',
53
+ description: 'At every start, instead of latitude / longitude - looked up locally (GeoLite data, city level), the last determined position is published while the lookup is pending or without internet',
54
+ default: false,
55
+ },
56
+ elevation: {
57
+ type: 'number',
58
+ title: 'Elevation (m)',
59
+ description: 'Above sea level - published on navigation.gnss.antennaAltitude and as altitude of navigation.position; leave empty to look it up from the elevation provider',
60
+ },
61
+ elevationProvider: {
62
+ type: 'string',
63
+ title: 'Elevation provider',
64
+ description: 'Looks up the elevation of the position if none is entered',
65
+ enum: ['open-meteo', 'google', 'none'],
66
+ enumNames: ['Open-Meteo (free for non-commercial use)', 'Google Maps (API key required)', 'None'],
67
+ default: 'open-meteo',
68
+ },
69
+ apikey: {
70
+ type: 'string',
71
+ title: 'API key of the elevation provider',
72
+ description: 'Google Maps: required. Open-Meteo: optional, only for commercial use (customer API, https://open-meteo.com/en/pricing). Change the key together with the provider.',
73
+ },
74
+ },
87
75
  }
88
76
 
89
- function log(msg) { app.debug(msg); }
90
-
91
- return plugin;
92
- };
77
+ return plugin
78
+ }
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "signalk-fixedstation",
3
- "version": "0.5.1",
3
+ "version": "0.8.0",
4
4
  "description": "SignalK plugin to provide fixed navigation data",
5
5
  "main": "index.js",
6
6
  "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1",
8
- "debug": "node --inspect-brk=192.168.0.97:9229 /usr/local/lib/node_modules/signalk-server/bin/signalk-server"
7
+ "test": "node --test test/*.test.js",
8
+ "debug": "node --inspect-brk=192.168.0.97:9229 /usr/lib/node_modules/signalk-server/bin/signalk-server -c /home/pi/signalk"
9
9
  },
10
10
  "repository": {
11
11
  "type": "git",
@@ -22,10 +22,24 @@
22
22
  "url": "https://github.com/inspired-technologies/signalk-fixedstation-plugin/issues"
23
23
  },
24
24
  "homepage": "https://github.com/inspired-technologies/signalk-fixedstation-plugin#readme",
25
+ "files": [
26
+ "index.js",
27
+ "fixedstation.js",
28
+ "geoloc.js",
29
+ "elevation.js",
30
+ "img/logo.png",
31
+ "CHANGELOG.md"
32
+ ],
33
+ "engines": {
34
+ "node": ">=20"
35
+ },
36
+ "signalk": {
37
+ "displayName": "Fixed Station",
38
+ "appIcon": "./img/logo.png"
39
+ },
25
40
  "dependencies": {
26
- "@googlemaps/google-maps-services-js": "^3.3.42",
27
- "debug": "^4.3.4",
28
- "geoip-lite": "^1.4.10",
29
- "public-ip": "^6.0.2"
41
+ "debug": "^4.4.3",
42
+ "geoip-lite": "^2.0.3",
43
+ "public-ip": "^8.0.0"
30
44
  }
31
45
  }
package/SignalKPath.json DELETED
@@ -1,58 +0,0 @@
1
- { "navigation":
2
- {
3
- "position":
4
- {
5
- "meta":
6
- {
7
- "description":"Fixed position in 2 or 3 dimensions (WGS84 datum)",
8
- "properties":
9
- {
10
- "longitude":
11
- {
12
- "type":"number",
13
- "description":"Longitude",
14
- "units":"deg",
15
- "example":4.98765245
16
- },
17
- "latitude":
18
- {
19
- "type":"number",
20
- "description":"Latitude",
21
- "units":"deg",
22
- "example":52.0987654
23
- },
24
- "altitude":
25
- {
26
- "type":"number",
27
- "description":"Altitude",
28
- "units":"m"
29
- }
30
- }
31
- },
32
- "value":
33
- {
34
- "longitude":24.7313641,
35
- "latitude":59.7158565,
36
- "altitude":-0.11
37
- },
38
- "$source":"n2k-sample-data.160",
39
- "timestamp":"2014-08-15T19:05:06.675Z",
40
- "pgn":129029
41
- },
42
- "gnss":
43
- {
44
- "antennaAltitude":
45
- {
46
- "meta":
47
- {
48
- "units":"m",
49
- "description":"Altitude of antenna"
50
- },
51
- "value":-0.11,
52
- "$source":"n2k-sample-data.160",
53
- "timestamp":"2014-08-15T19:01:49.651Z",
54
- "pgn":129029
55
- }
56
- }
57
- }
58
- }