signalk-target-fusion 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
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,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,29 @@
1
+ # Signal K Target Fusion
2
+
3
+ AIS, radar and cameras often see the same boat. This plugin works out which radar and camera targets are a boat AIS already reports, or are the same boat seen by two sensors, and says so in the data model. Collision alarms and chart plotters that follow these links show and alarm each boat once.
4
+
5
+ ## How it works
6
+
7
+ Radar and camera plugins publish what they track as `targets.<type>:<id>` contexts (see the server's _Sensor targets_ plugin documentation). Every two seconds (configurable) this plugin compares them with the AIS vessels and sets `sameAs` on each target that is the same object as another context:
8
+
9
+ ```
10
+ targets.radar:nav1034A-17 sameAs "vessels.urn:mrn:imo:mmsi:244060000"
11
+ ```
12
+
13
+ A target is linked to an AIS vessel when:
14
+
15
+ - the sensor identified the vessel by its MMSI, or
16
+ - the AIS position, moved forward to the time of the radar or camera observation, is within 200 m of the target (configurable) (more at long range, where radar bearings are less precise), and the two agree on course and speed.
17
+
18
+ Targets without AIS are linked to each other the same way, so a radar track and a camera detection of one boat without AIS are one object. One sensor never contributes two targets to one boat. A link, once made, holds a little beyond the distance it took to make it, so a boat near the limit doesn't flicker between one symbol and two. A target keeps its AIS vessel while radar still tracks it after the vessel's AIS falls silent.
19
+
20
+ Run one fusion plugin at a time; two would publish conflicting links. Stopping this plugin withdraws the links it made.
21
+
22
+ ## Settings
23
+
24
+ - **Match targets within (m)**, default 200: how far apart a target and an AIS position may be near own ship and still be linked. Raise it for a radar or camera with a larger position error, lower it in crowded harbours.
25
+ - **Link targets every (s)**, default 2.
26
+
27
+ ## License
28
+
29
+ Apache-2.0
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "signalk-target-fusion",
3
+ "version": "0.1.0",
4
+ "description": "Links radar and camera targets to the AIS vessels they see, so Signal K clients show and alarm each boat once",
5
+ "main": "plugin/index.js",
6
+ "type": "module",
7
+ "scripts": {
8
+ "format": "prettier --write . && eslint --fix .",
9
+ "ci-lint": "eslint . && prettier --check .",
10
+ "build": "vite build",
11
+ "typecheck": "tsc --noEmit -p tsconfig.eslint.json",
12
+ "test": "vitest run",
13
+ "build:all": "npm run ci-lint && npm run typecheck && npm run build && npm run test",
14
+ "prepublishOnly": "npm run build"
15
+ },
16
+ "keywords": [
17
+ "signalk-node-server-plugin",
18
+ "signalk-category-ais",
19
+ "radar",
20
+ "arpa",
21
+ "ais",
22
+ "sensor-fusion"
23
+ ],
24
+ "signalk": {
25
+ "displayName": "Target Fusion"
26
+ },
27
+ "files": [
28
+ "plugin/**/*"
29
+ ],
30
+ "engines": {
31
+ "node": ">=22.15.0",
32
+ "signalk": ">=2.31.0"
33
+ },
34
+ "devDependencies": {
35
+ "@eslint/js": "^10.0.1",
36
+ "@signalk/server-api": "^2.33.0",
37
+ "@types/node": "^22.0.0",
38
+ "eslint": "^10.12.0",
39
+ "eslint-config-prettier": "^10.1.8",
40
+ "eslint-plugin-prettier": "^5.5.6",
41
+ "jiti": "^2.7.0",
42
+ "prettier": "^3.0.0",
43
+ "typescript": "^6.0.3",
44
+ "typescript-eslint": "^8.71.0",
45
+ "vite": "^8.3.2",
46
+ "vite-plugin-checker": "^0.14.5",
47
+ "vitest": "^5.0.0"
48
+ },
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "git+https://github.com/dirkwa/signalk-target-fusion.git"
52
+ },
53
+ "license": "Apache-2.0",
54
+ "dependencies": {
55
+ "typebox": "^1.3.35"
56
+ }
57
+ }
@@ -0,0 +1,361 @@
1
+ import { Type } from "typebox";
2
+ var ConfigSchema = Type.Object({
3
+ gateDistance: Type.Number({
4
+ title: "Match targets within (m)",
5
+ description: "How far apart a radar or camera target and an AIS position may be and still be linked near own ship. The distance grows by 5% of the range further out, because radar bearing error grows with range.",
6
+ minimum: 10,
7
+ default: 200
8
+ }),
9
+ interval: Type.Number({
10
+ title: "Link targets every (s)",
11
+ minimum: 1,
12
+ default: 2
13
+ })
14
+ });
15
+ var DEFAULTS = {
16
+ gateDistance: 200,
17
+ interval: 2
18
+ };
19
+ //#endregion
20
+ //#region src/association.ts
21
+ /**
22
+ * Radar bearing error grows with range (1° is 17 m per km), so the gate widens
23
+ * with the target's distance from own ship.
24
+ */
25
+ var GATE_RANGE_FRACTION = .05;
26
+ /** An existing link survives until the gap exceeds this multiple of the gate. */
27
+ var KEEP_GATE_FACTOR = 1.5;
28
+ /** Below this speed a course is noise and is not compared. */
29
+ var COURSE_MIN_SPEED = 1;
30
+ var MAX_COURSE_DIFF = Math.PI / 4;
31
+ var MIN_SPEED_TOLERANCE = 1.5;
32
+ var SPEED_TOLERANCE_FRACTION = .5;
33
+ var EARTH_RADIUS_M = 6371e3;
34
+ /**
35
+ * The context each target belongs to, by target context. A target that names
36
+ * its own group maps to its own context.
37
+ */
38
+ function associate(input) {
39
+ const groups = input.aisVessels.map((ais) => ({
40
+ context: ais.context,
41
+ ais,
42
+ reference: ais.observation,
43
+ members: [],
44
+ sensors: /* @__PURE__ */ new Set()
45
+ }));
46
+ const unassigned = assignGreedily(input.targets, groups, input);
47
+ const taken = new Set(groups.map((g) => g.context));
48
+ const remaining = [...unassigned].sort((a, b) => Number(isSeed(b, input)) - Number(isSeed(a, input)));
49
+ const darkGroups = [];
50
+ for (const target of remaining) if (assignGreedily([target], darkGroups, input).length > 0) {
51
+ const context = seedContext(target, input, taken);
52
+ taken.add(context);
53
+ darkGroups.push({
54
+ context,
55
+ reference: target.observation,
56
+ members: [target],
57
+ sensors: /* @__PURE__ */ new Set([target.sensor])
58
+ });
59
+ }
60
+ const links = /* @__PURE__ */ new Map();
61
+ for (const group of [...groups, ...darkGroups]) for (const member of group.members) links.set(member.context, group.context);
62
+ return links;
63
+ }
64
+ /** Whether a target named its group last time, itself or as the vessel it kept. */
65
+ function isSeed(target, input) {
66
+ const previous = input.previous.get(target.context);
67
+ return previous === target.context || previous !== void 0 && input.vessels.has(previous);
68
+ }
69
+ /**
70
+ * The context a group seeded by this target is named by: the vessel it was
71
+ * linked to while that vessel is still in the data model, otherwise its own.
72
+ */
73
+ function seedContext(target, input, taken) {
74
+ const previous = input.previous.get(target.context);
75
+ return previous !== void 0 && input.vessels.has(previous) && !taken.has(previous) ? previous : target.context;
76
+ }
77
+ /**
78
+ * Assigns targets to groups cheapest pair first, at most one target per sensor
79
+ * in each group: one sensor does not see the same boat twice. Returns the
80
+ * targets left over.
81
+ */
82
+ function assignGreedily(targets, groups, input) {
83
+ const candidates = [];
84
+ for (const target of targets) for (const group of groups) {
85
+ const cost = matchCost(target, group, input);
86
+ if (cost !== void 0) candidates.push({
87
+ target,
88
+ group,
89
+ cost
90
+ });
91
+ }
92
+ candidates.sort((a, b) => a.cost - b.cost);
93
+ const assigned = /* @__PURE__ */ new Set();
94
+ for (const { target, group } of candidates) {
95
+ if (assigned.has(target) || group.sensors.has(target.sensor)) continue;
96
+ group.members.push(target);
97
+ group.sensors.add(target.sensor);
98
+ assigned.add(target);
99
+ }
100
+ return targets.filter((t) => !assigned.has(t));
101
+ }
102
+ /**
103
+ * How well a target fits a group, lower is better, or `undefined` when it
104
+ * cannot belong to it. A matching MMSI beats any geometric match.
105
+ */
106
+ function matchCost(target, group, input) {
107
+ if (target.mmsi !== void 0) {
108
+ if (group.ais) return target.mmsi === group.ais.mmsi ? -1 : void 0;
109
+ const groupMmsi = group.members.find((m) => m.mmsi !== void 0)?.mmsi;
110
+ if (groupMmsi !== void 0) return target.mmsi === groupMmsi ? -1 : void 0;
111
+ }
112
+ const { observation } = target;
113
+ const wasLinked = input.previous.get(target.context) === group.context;
114
+ const gate = gateRadius(observation.position, input.minGateM, input.ownPosition) * (wasLinked ? KEEP_GATE_FACTOR : 1);
115
+ const gap = distance(extrapolate(group.reference, observation.timeMs), observation.position);
116
+ if (gap > gate || !motionAgrees(group.reference, observation, wasLinked)) return;
117
+ return gap / gate - (wasLinked ? 1 : 0);
118
+ }
119
+ function gateRadius(position, minGateM, ownPosition) {
120
+ if (!ownPosition) return minGateM;
121
+ return Math.max(minGateM, distance(position, ownPosition) * GATE_RANGE_FRACTION);
122
+ }
123
+ function motionAgrees(a, b, lenient) {
124
+ const factor = lenient ? KEEP_GATE_FACTOR : 1;
125
+ if (a.speedOverGround !== void 0 && b.speedOverGround !== void 0) {
126
+ const tolerance = Math.max(MIN_SPEED_TOLERANCE, SPEED_TOLERANCE_FRACTION * Math.max(a.speedOverGround, b.speedOverGround));
127
+ if (Math.abs(a.speedOverGround - b.speedOverGround) > tolerance * factor) return false;
128
+ if (a.courseOverGroundTrue !== void 0 && b.courseOverGroundTrue !== void 0 && a.speedOverGround >= COURSE_MIN_SPEED && b.speedOverGround >= COURSE_MIN_SPEED && angleBetween(a.courseOverGroundTrue, b.courseOverGroundTrue) > MAX_COURSE_DIFF * factor) return false;
129
+ }
130
+ return true;
131
+ }
132
+ /** Dead-reckons an observation to `timeMs` along its course and speed. */
133
+ function extrapolate(o, timeMs) {
134
+ if (o.speedOverGround === void 0 || o.courseOverGroundTrue === void 0) return o.position;
135
+ const run = o.speedOverGround * (timeMs - o.timeMs) / 1e3;
136
+ const dLat = run * Math.cos(o.courseOverGroundTrue) / EARTH_RADIUS_M;
137
+ const dLon = run * Math.sin(o.courseOverGroundTrue) / (EARTH_RADIUS_M * Math.cos(toRad(o.position.latitude)));
138
+ return {
139
+ latitude: o.position.latitude + toDeg(dLat),
140
+ longitude: normaliseLongitude(o.position.longitude + toDeg(dLon))
141
+ };
142
+ }
143
+ /** Great-circle distance in metres (haversine). */
144
+ function distance(a, b) {
145
+ const dLat = toRad(b.latitude - a.latitude);
146
+ const dLon = toRad(b.longitude - a.longitude);
147
+ const h = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(a.latitude)) * Math.cos(toRad(b.latitude)) * Math.sin(dLon / 2) ** 2;
148
+ return 2 * EARTH_RADIUS_M * Math.asin(Math.min(1, Math.sqrt(h)));
149
+ }
150
+ function angleBetween(a, b) {
151
+ const d = Math.abs(a - b) % (2 * Math.PI);
152
+ return d > Math.PI ? 2 * Math.PI - d : d;
153
+ }
154
+ function normaliseLongitude(lon) {
155
+ return ((lon + 180) % 360 + 360) % 360 - 180;
156
+ }
157
+ var toRad = (deg) => deg * Math.PI / 180;
158
+ var toDeg = (rad) => rad * 180 / Math.PI;
159
+ //#endregion
160
+ //#region src/model.ts
161
+ /**
162
+ * AIS vessels whose last position is older than this are not linked to. Class A
163
+ * ships at anchor report every three minutes, so this allows a few misses.
164
+ */
165
+ var AIS_MAX_AGE_MS = 6e5;
166
+ /**
167
+ * Observations stamped further ahead of the clock than this are left out: a
168
+ * future time would keep them fresh until it passed.
169
+ */
170
+ var MAX_CLOCK_SKEW_MS = 6e4;
171
+ /** Motion reported further than this from its position is left out. */
172
+ var MOTION_MAX_LAG_MS = 6e4;
173
+ var MMSI_URN = /^urn:mrn:imo:mmsi:(\d+)$/;
174
+ /**
175
+ * Vessels other than self that AIS reports: plugins also publish vessels AIS
176
+ * never saw (buddy boats over the internet, for one), and every AIS station
177
+ * has an MMSI.
178
+ */
179
+ function aisVessels(vessels, selfId, nowMs) {
180
+ const result = [];
181
+ for (const [vesselId, vessel] of Object.entries(vessels)) {
182
+ if (vesselId === selfId || vesselId === "self" || !vessel) continue;
183
+ const mmsi = typeof vessel.mmsi === "string" ? vessel.mmsi : MMSI_URN.exec(vesselId)?.[1];
184
+ const observation = observationOf(vessel, nowMs, AIS_MAX_AGE_MS);
185
+ if (mmsi && observation) result.push({
186
+ context: `vessels.${vesselId}`,
187
+ mmsi,
188
+ observation
189
+ });
190
+ }
191
+ return result;
192
+ }
193
+ /** Targets under `targets.*` with a fresh position. */
194
+ function sensorTargets(targets, nowMs) {
195
+ const result = [];
196
+ for (const [id, target] of Object.entries(targets)) {
197
+ const observation = target && observationOf(target, nowMs, 6e4);
198
+ if (!observation) continue;
199
+ result.push({
200
+ context: `targets.${id}`,
201
+ sensor: target.navigation?.position?.$source ?? id.split(":")[0] ?? id,
202
+ ...typeof target.mmsi === "string" && { mmsi: target.mmsi },
203
+ observation
204
+ });
205
+ }
206
+ return result;
207
+ }
208
+ /** The `sameAs` each target currently has in the data model, by context. */
209
+ function currentLinks(targets) {
210
+ const links = /* @__PURE__ */ new Map();
211
+ for (const [id, target] of Object.entries(targets)) {
212
+ const value = target?.sameAs?.value;
213
+ links.set(`targets.${id}`, typeof value === "string" ? value : null);
214
+ }
215
+ return links;
216
+ }
217
+ /**
218
+ * Whether the target's sensor reported its track lost, with a null position.
219
+ * Such a track never resumes, so its id may later name a different object.
220
+ */
221
+ function isLost(node) {
222
+ return node?.navigation?.position?.value === null;
223
+ }
224
+ function positionOf(node) {
225
+ const value = node?.navigation?.position?.value;
226
+ return isPosition(value) ? value : void 0;
227
+ }
228
+ function observationOf(node, nowMs, maxAgeMs) {
229
+ const nav = node.navigation;
230
+ const position = positionOf(node);
231
+ const timeMs = Date.parse(nav?.position?.timestamp ?? "");
232
+ if (!position || !(nowMs - timeMs <= maxAgeMs) || timeMs - nowMs > MAX_CLOCK_SKEW_MS) return;
233
+ const observation = {
234
+ position: {
235
+ latitude: position.latitude,
236
+ longitude: position.longitude
237
+ },
238
+ timeMs
239
+ };
240
+ const course = motionAt(nav?.courseOverGroundTrue, timeMs);
241
+ const speed = motionAt(nav?.speedOverGround, timeMs);
242
+ if (course !== void 0) observation.courseOverGroundTrue = course;
243
+ if (speed !== void 0) observation.speedOverGround = speed;
244
+ return observation;
245
+ }
246
+ /**
247
+ * A motion value, unless it was reported well apart from the position: the
248
+ * position is dead-reckoned with it, so a course from another time would
249
+ * mislead the gate.
250
+ */
251
+ function motionAt(leaf, positionMs) {
252
+ const timeMs = Date.parse(leaf?.timestamp ?? "");
253
+ const value = leaf?.value;
254
+ return Math.abs(positionMs - timeMs) <= MOTION_MAX_LAG_MS && typeof value === "number" && Number.isFinite(value) ? value : void 0;
255
+ }
256
+ function isPosition(value) {
257
+ const p = value;
258
+ return typeof p?.latitude === "number" && typeof p.longitude === "number" && Math.abs(p.latitude) <= 90 && Math.abs(p.longitude) <= 180;
259
+ }
260
+ //#endregion
261
+ //#region src/fusion.ts
262
+ /**
263
+ * Links `targets.*` contexts to the context that names the same object, and
264
+ * says which `sameAs` values have to change in the data model.
265
+ */
266
+ var Fusion = class {
267
+ minGateM;
268
+ /** The context each target belonged to last time, for link hysteresis. */
269
+ previous = /* @__PURE__ */ new Map();
270
+ /** The link this plugin published per target, so stop() withdraws only those. */
271
+ linked = /* @__PURE__ */ new Map();
272
+ /** @param minGateM gate radius near own ship (m) */
273
+ constructor(minGateM) {
274
+ this.minGateM = minGateM;
275
+ }
276
+ update({ vessels, targets, selfId, nowMs }) {
277
+ const groups = associate({
278
+ ownPosition: positionOf(vessels[selfId]),
279
+ aisVessels: aisVessels(vessels, selfId, nowMs),
280
+ targets: sensorTargets(targets, nowMs),
281
+ previous: this.previous,
282
+ vessels: new Set(Object.keys(vessels).map((id) => `vessels.${id}`)),
283
+ minGateM: this.minGateM
284
+ });
285
+ this.previous = groups;
286
+ const changes = /* @__PURE__ */ new Map();
287
+ for (const [context, current] of currentLinks(targets)) {
288
+ const group = groups.get(context);
289
+ if (group === void 0 && !isLost(targets[context.slice(8)])) continue;
290
+ const wanted = group === void 0 || group === context ? null : group;
291
+ if (wanted !== current) {
292
+ changes.set(context, wanted);
293
+ if (wanted !== null) this.linked.set(context, wanted);
294
+ }
295
+ if (wanted === null) this.linked.delete(context);
296
+ }
297
+ return changes;
298
+ }
299
+ /** Withdraws the links this plugin made that nobody has replaced since. */
300
+ stop(targets) {
301
+ const current = currentLinks(targets);
302
+ const changes = /* @__PURE__ */ new Map();
303
+ for (const [context, published] of this.linked) if (current.get(context) === published) changes.set(context, null);
304
+ this.linked.clear();
305
+ this.previous = /* @__PURE__ */ new Map();
306
+ return changes;
307
+ }
308
+ };
309
+ //#endregion
310
+ //#region src/index.ts
311
+ var PLUGIN_ID = "signalk-target-fusion";
312
+ function src_default(app) {
313
+ let timer;
314
+ let fusion;
315
+ function publish(changes) {
316
+ for (const [context, value] of changes) app.handleMessage(PLUGIN_ID, {
317
+ context,
318
+ updates: [{ values: [{
319
+ path: "sameAs",
320
+ value
321
+ }] }]
322
+ });
323
+ }
324
+ return {
325
+ id: PLUGIN_ID,
326
+ name: "Target Fusion",
327
+ description: "Links radar and camera targets to the AIS vessels they see",
328
+ schema: () => ConfigSchema,
329
+ start(partial) {
330
+ const config = {
331
+ ...DEFAULTS,
332
+ ...partial
333
+ };
334
+ const active = new Fusion(config.gateDistance);
335
+ fusion = active;
336
+ timer = setInterval(() => {
337
+ try {
338
+ publish(active.update({
339
+ vessels: app.getPath("vessels") ?? {},
340
+ targets: app.getPath("targets") ?? {},
341
+ selfId: app.selfId,
342
+ nowMs: Date.now()
343
+ }));
344
+ } catch (err) {
345
+ app.error(`Target fusion failed: ${String(err)}`);
346
+ }
347
+ }, Math.max(config.interval, 1) * 1e3);
348
+ app.setPluginStatus("Linking targets to AIS vessels");
349
+ },
350
+ stop() {
351
+ clearInterval(timer);
352
+ timer = void 0;
353
+ if (fusion) publish(fusion.stop(app.getPath("targets") ?? {}));
354
+ fusion = void 0;
355
+ }
356
+ };
357
+ }
358
+ //#endregion
359
+ export { src_default as default };
360
+
361
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/config.ts","../src/association.ts","../src/model.ts","../src/fusion.ts","../src/index.ts"],"sourcesContent":["import { Type, type Static } from 'typebox'\n\n/** Linking faster than this would load the server for no gain. */\nexport const MIN_INTERVAL_S = 1\n\nexport const ConfigSchema = Type.Object({\n gateDistance: Type.Number({\n title: 'Match targets within (m)',\n description:\n 'How far apart a radar or camera target and an AIS position may be and still be linked near own ship. The distance grows by 5% of the range further out, because radar bearing error grows with range.',\n minimum: 10,\n default: 200\n }),\n interval: Type.Number({ title: 'Link targets every (s)', minimum: MIN_INTERVAL_S, default: 2 })\n})\n\nexport type Config = Static<typeof ConfigSchema>\n\n// The server only uses schema defaults to seed the admin form; start()\n// receives `{}` for a plugin that has never been configured.\nexport const DEFAULTS: Config = {\n gateDistance: 200,\n interval: 2\n}\n","/**\n * Decides which targets are the same object.\n *\n * AIS vessels anchor the picture because they carry identity. A radar or\n * camera target joins an AIS vessel when it says so through its MMSI, or when\n * the AIS position, extrapolated to the target's time, lies within a distance\n * gate and the two agree on course and speed. Targets no AIS vessel claims are\n * grouped with each other the same way, so a radar track and a camera\n * detection of one dark boat are still one object.\n *\n * A link, once made, is kept with a wider gate than it took to make it, so a\n * target near the threshold does not split and merge on every evaluation.\n */\n\nexport interface Position {\n latitude: number\n longitude: number\n}\n\nexport interface Observation {\n position: Position\n courseOverGroundTrue?: number\n speedOverGround?: number\n timeMs: number\n}\n\nexport interface AisVessel {\n /** Vessel context, e.g. `vessels.urn:mrn:imo:mmsi:244060000`. */\n context: string\n mmsi: string\n observation: Observation\n}\n\nexport interface SensorTarget {\n /** Target context, e.g. `targets.radar:nav1034A-17`. */\n context: string\n /** What reported it, so one sensor never contributes two targets to one object. */\n sensor: string\n /** MMSI when the sensor itself identified the vessel. */\n mmsi?: string\n observation: Observation\n}\n\nexport interface AssociationInput {\n ownPosition?: Position\n aisVessels: AisVessel[]\n targets: SensorTarget[]\n /** The context each target belonged to last time, by target context. */\n previous: ReadonlyMap<string, string>\n /**\n * Vessel contexts still in the data model, so a target keeps the vessel it\n * was linked to after that vessel's AIS falls silent.\n */\n vessels: ReadonlySet<string>\n /** Gate radius near own ship (m), covering GPS, antenna offset and timing errors. */\n minGateM: number\n}\n\n/**\n * Radar bearing error grows with range (1° is 17 m per km), so the gate widens\n * with the target's distance from own ship.\n */\nconst GATE_RANGE_FRACTION = 0.05\n/** An existing link survives until the gap exceeds this multiple of the gate. */\nconst KEEP_GATE_FACTOR = 1.5\n/** Below this speed a course is noise and is not compared. */\nconst COURSE_MIN_SPEED = 1\nconst MAX_COURSE_DIFF = Math.PI / 4\nconst MIN_SPEED_TOLERANCE = 1.5\nconst SPEED_TOLERANCE_FRACTION = 0.5\n\nconst EARTH_RADIUS_M = 6371000\n\ninterface Group {\n /** The context that names the object: the AIS vessel, or one of its targets. */\n context: string\n ais?: AisVessel\n /** The observation new members are gated against. */\n reference: Observation\n members: SensorTarget[]\n sensors: Set<string>\n}\n\ninterface Candidate {\n target: SensorTarget\n group: Group\n cost: number\n}\n\n/**\n * The context each target belongs to, by target context. A target that names\n * its own group maps to its own context.\n */\nexport function associate(input: AssociationInput): Map<string, string> {\n const groups: Group[] = input.aisVessels.map((ais) => ({\n context: ais.context,\n ais,\n reference: ais.observation,\n members: [],\n sensors: new Set()\n }))\n\n const unassigned = assignGreedily(input.targets, groups, input)\n\n // Targets that named their group last time seed first, so an object keeps\n // its context while the target that named it is still tracked.\n const taken = new Set(groups.map((g) => g.context))\n const remaining = [...unassigned].sort(\n (a, b) => Number(isSeed(b, input)) - Number(isSeed(a, input))\n )\n const darkGroups: Group[] = []\n for (const target of remaining) {\n if (assignGreedily([target], darkGroups, input).length > 0) {\n const context = seedContext(target, input, taken)\n taken.add(context)\n darkGroups.push({\n context,\n reference: target.observation,\n members: [target],\n sensors: new Set([target.sensor])\n })\n }\n }\n\n const links = new Map<string, string>()\n for (const group of [...groups, ...darkGroups]) {\n for (const member of group.members) {\n links.set(member.context, group.context)\n }\n }\n return links\n}\n\n/** Whether a target named its group last time, itself or as the vessel it kept. */\nfunction isSeed(target: SensorTarget, input: AssociationInput): boolean {\n const previous = input.previous.get(target.context)\n return previous === target.context || (previous !== undefined && input.vessels.has(previous))\n}\n\n/**\n * The context a group seeded by this target is named by: the vessel it was\n * linked to while that vessel is still in the data model, otherwise its own.\n */\nfunction seedContext(target: SensorTarget, input: AssociationInput, taken: Set<string>): string {\n const previous = input.previous.get(target.context)\n return previous !== undefined && input.vessels.has(previous) && !taken.has(previous)\n ? previous\n : target.context\n}\n\n/**\n * Assigns targets to groups cheapest pair first, at most one target per sensor\n * in each group: one sensor does not see the same boat twice. Returns the\n * targets left over.\n */\nfunction assignGreedily(\n targets: SensorTarget[],\n groups: Group[],\n input: AssociationInput\n): SensorTarget[] {\n const candidates: Candidate[] = []\n for (const target of targets) {\n for (const group of groups) {\n const cost = matchCost(target, group, input)\n if (cost !== undefined) {\n candidates.push({ target, group, cost })\n }\n }\n }\n candidates.sort((a, b) => a.cost - b.cost)\n\n const assigned = new Set<SensorTarget>()\n for (const { target, group } of candidates) {\n if (assigned.has(target) || group.sensors.has(target.sensor)) {\n continue\n }\n group.members.push(target)\n group.sensors.add(target.sensor)\n assigned.add(target)\n }\n return targets.filter((t) => !assigned.has(t))\n}\n\n/**\n * How well a target fits a group, lower is better, or `undefined` when it\n * cannot belong to it. A matching MMSI beats any geometric match.\n */\nfunction matchCost(\n target: SensorTarget,\n group: Group,\n input: AssociationInput\n): number | undefined {\n // A target the sensor has identified only joins the AIS vessel with that\n // MMSI, never one that merely happens to be nearby, and never a group\n // another sensor identified as a different vessel.\n if (target.mmsi !== undefined) {\n if (group.ais) {\n return target.mmsi === group.ais.mmsi ? -1 : undefined\n }\n const groupMmsi = group.members.find((m) => m.mmsi !== undefined)?.mmsi\n if (groupMmsi !== undefined) {\n return target.mmsi === groupMmsi ? -1 : undefined\n }\n }\n const { observation } = target\n const wasLinked = input.previous.get(target.context) === group.context\n const gate =\n gateRadius(observation.position, input.minGateM, input.ownPosition) *\n (wasLinked ? KEEP_GATE_FACTOR : 1)\n const expected = extrapolate(group.reference, observation.timeMs)\n const gap = distance(expected, observation.position)\n if (gap > gate || !motionAgrees(group.reference, observation, wasLinked)) {\n return undefined\n }\n return gap / gate - (wasLinked ? 1 : 0)\n}\n\nfunction gateRadius(position: Position, minGateM: number, ownPosition?: Position): number {\n if (!ownPosition) {\n return minGateM\n }\n return Math.max(minGateM, distance(position, ownPosition) * GATE_RANGE_FRACTION)\n}\n\nfunction motionAgrees(a: Observation, b: Observation, lenient: boolean): boolean {\n const factor = lenient ? KEEP_GATE_FACTOR : 1\n if (a.speedOverGround !== undefined && b.speedOverGround !== undefined) {\n const tolerance = Math.max(\n MIN_SPEED_TOLERANCE,\n SPEED_TOLERANCE_FRACTION * Math.max(a.speedOverGround, b.speedOverGround)\n )\n if (Math.abs(a.speedOverGround - b.speedOverGround) > tolerance * factor) {\n return false\n }\n if (\n a.courseOverGroundTrue !== undefined &&\n b.courseOverGroundTrue !== undefined &&\n a.speedOverGround >= COURSE_MIN_SPEED &&\n b.speedOverGround >= COURSE_MIN_SPEED &&\n angleBetween(a.courseOverGroundTrue, b.courseOverGroundTrue) > MAX_COURSE_DIFF * factor\n ) {\n return false\n }\n }\n return true\n}\n\n/** Dead-reckons an observation to `timeMs` along its course and speed. */\nexport function extrapolate(o: Observation, timeMs: number): Position {\n if (o.speedOverGround === undefined || o.courseOverGroundTrue === undefined) {\n return o.position\n }\n const run = (o.speedOverGround * (timeMs - o.timeMs)) / 1000\n const dLat = (run * Math.cos(o.courseOverGroundTrue)) / EARTH_RADIUS_M\n const dLon =\n (run * Math.sin(o.courseOverGroundTrue)) /\n (EARTH_RADIUS_M * Math.cos(toRad(o.position.latitude)))\n return {\n latitude: o.position.latitude + toDeg(dLat),\n longitude: normaliseLongitude(o.position.longitude + toDeg(dLon))\n }\n}\n\n/** Great-circle distance in metres (haversine). */\nexport function distance(a: Position, b: Position): number {\n const dLat = toRad(b.latitude - a.latitude)\n const dLon = toRad(b.longitude - a.longitude)\n const h =\n Math.sin(dLat / 2) ** 2 +\n Math.cos(toRad(a.latitude)) * Math.cos(toRad(b.latitude)) * Math.sin(dLon / 2) ** 2\n return 2 * EARTH_RADIUS_M * Math.asin(Math.min(1, Math.sqrt(h)))\n}\n\nfunction angleBetween(a: number, b: number): number {\n const d = Math.abs(a - b) % (2 * Math.PI)\n return d > Math.PI ? 2 * Math.PI - d : d\n}\n\nfunction normaliseLongitude(lon: number): number {\n return ((((lon + 180) % 360) + 360) % 360) - 180\n}\n\nconst toRad = (deg: number) => (deg * Math.PI) / 180\nconst toDeg = (rad: number) => (rad * 180) / Math.PI\n","import type { AisVessel, Observation, Position, SensorTarget } from './association.js'\n\n/**\n * AIS vessels whose last position is older than this are not linked to. Class A\n * ships at anchor report every three minutes, so this allows a few misses.\n */\nconst AIS_MAX_AGE_MS = 10 * 60_000\n/** A target its sensor stops updating is left out after this long. */\nexport const TARGET_MAX_AGE_MS = 60_000\n/**\n * Observations stamped further ahead of the clock than this are left out: a\n * future time would keep them fresh until it passed.\n */\nconst MAX_CLOCK_SKEW_MS = 60_000\n/** Motion reported further than this from its position is left out. */\nconst MOTION_MAX_LAG_MS = 60_000\n\nconst MMSI_URN = /^urn:mrn:imo:mmsi:(\\d+)$/\n\ninterface Leaf {\n value?: unknown\n timestamp?: string\n $source?: string\n}\n\n/** The slice of a vessel or target context in the full data model read here. */\nexport interface ContextNode {\n mmsi?: unknown\n sameAs?: Leaf\n navigation?: {\n position?: Leaf\n courseOverGroundTrue?: Leaf\n speedOverGround?: Leaf\n }\n}\n\nexport type Contexts = Record<string, ContextNode | undefined>\n\n/**\n * Vessels other than self that AIS reports: plugins also publish vessels AIS\n * never saw (buddy boats over the internet, for one), and every AIS station\n * has an MMSI.\n */\nexport function aisVessels(vessels: Contexts, selfId: string, nowMs: number): AisVessel[] {\n const result: AisVessel[] = []\n for (const [vesselId, vessel] of Object.entries(vessels)) {\n if (vesselId === selfId || vesselId === 'self' || !vessel) {\n continue\n }\n const mmsi = typeof vessel.mmsi === 'string' ? vessel.mmsi : MMSI_URN.exec(vesselId)?.[1]\n const observation = observationOf(vessel, nowMs, AIS_MAX_AGE_MS)\n if (mmsi && observation) {\n result.push({ context: `vessels.${vesselId}`, mmsi, observation })\n }\n }\n return result\n}\n\n/** Targets under `targets.*` with a fresh position. */\nexport function sensorTargets(targets: Contexts, nowMs: number): SensorTarget[] {\n const result: SensorTarget[] = []\n for (const [id, target] of Object.entries(targets)) {\n const observation = target && observationOf(target, nowMs, TARGET_MAX_AGE_MS)\n if (!observation) {\n continue\n }\n result.push({\n context: `targets.${id}`,\n sensor: target.navigation?.position?.$source ?? id.split(':')[0] ?? id,\n ...(typeof target.mmsi === 'string' && { mmsi: target.mmsi }),\n observation\n })\n }\n return result\n}\n\n/** The `sameAs` each target currently has in the data model, by context. */\nexport function currentLinks(targets: Contexts): Map<string, string | null> {\n const links = new Map<string, string | null>()\n for (const [id, target] of Object.entries(targets)) {\n const value = target?.sameAs?.value\n links.set(`targets.${id}`, typeof value === 'string' ? value : null)\n }\n return links\n}\n\n/**\n * Whether the target's sensor reported its track lost, with a null position.\n * Such a track never resumes, so its id may later name a different object.\n */\nexport function isLost(node: ContextNode | undefined): boolean {\n return node?.navigation?.position?.value === null\n}\n\nexport function positionOf(node: ContextNode | undefined): Position | undefined {\n const value = node?.navigation?.position?.value\n return isPosition(value) ? value : undefined\n}\n\nfunction observationOf(node: ContextNode, nowMs: number, maxAgeMs: number) {\n const nav = node.navigation\n const position = positionOf(node)\n const timeMs = Date.parse(nav?.position?.timestamp ?? '')\n if (!position || !(nowMs - timeMs <= maxAgeMs) || timeMs - nowMs > MAX_CLOCK_SKEW_MS) {\n return undefined\n }\n const observation: Observation = {\n position: { latitude: position.latitude, longitude: position.longitude },\n timeMs\n }\n const course = motionAt(nav?.courseOverGroundTrue, timeMs)\n const speed = motionAt(nav?.speedOverGround, timeMs)\n if (course !== undefined) {\n observation.courseOverGroundTrue = course\n }\n if (speed !== undefined) {\n observation.speedOverGround = speed\n }\n return observation\n}\n\n/**\n * A motion value, unless it was reported well apart from the position: the\n * position is dead-reckoned with it, so a course from another time would\n * mislead the gate.\n */\nfunction motionAt(leaf: Leaf | undefined, positionMs: number): number | undefined {\n const timeMs = Date.parse(leaf?.timestamp ?? '')\n const value = leaf?.value\n return Math.abs(positionMs - timeMs) <= MOTION_MAX_LAG_MS &&\n typeof value === 'number' &&\n Number.isFinite(value)\n ? value\n : undefined\n}\n\nfunction isPosition(value: unknown): value is Position {\n const p = value as Partial<Position> | null | undefined\n return (\n typeof p?.latitude === 'number' &&\n typeof p.longitude === 'number' &&\n Math.abs(p.latitude) <= 90 &&\n Math.abs(p.longitude) <= 180\n )\n}\n","import { associate } from './association.js'\nimport {\n aisVessels,\n currentLinks,\n isLost,\n positionOf,\n sensorTargets,\n type Contexts\n} from './model.js'\n\nexport interface FusionInput {\n vessels: Contexts\n targets: Contexts\n selfId: string\n nowMs: number\n}\n\n/** `sameAs` changes to publish, by target context; `null` withdraws a link. */\nexport type LinkChanges = Map<string, string | null>\n\n/**\n * Links `targets.*` contexts to the context that names the same object, and\n * says which `sameAs` values have to change in the data model.\n */\nexport class Fusion {\n /** The context each target belonged to last time, for link hysteresis. */\n private previous = new Map<string, string>()\n /** The link this plugin published per target, so stop() withdraws only those. */\n private readonly linked = new Map<string, string>()\n\n /** @param minGateM gate radius near own ship (m) */\n constructor(private readonly minGateM: number) {}\n\n update({ vessels, targets, selfId, nowMs }: FusionInput): LinkChanges {\n const groups = associate({\n ownPosition: positionOf(vessels[selfId]),\n aisVessels: aisVessels(vessels, selfId, nowMs),\n targets: sensorTargets(targets, nowMs),\n previous: this.previous,\n vessels: new Set(Object.keys(vessels).map((id) => `vessels.${id}`)),\n minGateM: this.minGateM\n })\n this.previous = groups\n\n const changes: LinkChanges = new Map()\n for (const [context, current] of currentLinks(targets)) {\n const group = groups.get(context)\n // A target without a fresh position keeps its link: consumers already\n // ignore it, and the link is right again if the track resumes. A lost\n // track does not resume, so its link goes.\n if (group === undefined && !isLost(targets[context.slice('targets.'.length)])) {\n continue\n }\n const wanted = group === undefined || group === context ? null : group\n if (wanted !== current) {\n changes.set(context, wanted)\n if (wanted !== null) {\n this.linked.set(context, wanted)\n }\n }\n if (wanted === null) {\n this.linked.delete(context)\n }\n }\n return changes\n }\n\n /** Withdraws the links this plugin made that nobody has replaced since. */\n stop(targets: Contexts): LinkChanges {\n const current = currentLinks(targets)\n const changes: LinkChanges = new Map()\n for (const [context, published] of this.linked) {\n if (current.get(context) === published) {\n changes.set(context, null)\n }\n }\n this.linked.clear()\n this.previous = new Map()\n return changes\n }\n}\n","import type { Context, Path, Plugin, ServerAPI } from '@signalk/server-api'\nimport { ConfigSchema, DEFAULTS, MIN_INTERVAL_S, type Config } from './config.js'\nimport { Fusion, type LinkChanges } from './fusion.js'\nimport type { Contexts } from './model.js'\n\nconst PLUGIN_ID = 'signalk-target-fusion'\n\nexport default function (app: ServerAPI): Plugin {\n let timer: ReturnType<typeof setInterval> | undefined\n let fusion: Fusion | undefined\n\n function publish(changes: LinkChanges): void {\n for (const [context, value] of changes) {\n app.handleMessage(PLUGIN_ID, {\n context: context as Context,\n updates: [{ values: [{ path: 'sameAs' as Path, value }] }]\n })\n }\n }\n\n return {\n id: PLUGIN_ID,\n name: 'Target Fusion',\n description: 'Links radar and camera targets to the AIS vessels they see',\n schema: () => ConfigSchema,\n\n start(partial: object) {\n // The server does not apply schema defaults at runtime.\n const config: Config = { ...DEFAULTS, ...(partial as Partial<Config>) }\n const active = new Fusion(config.gateDistance)\n fusion = active\n timer = setInterval(\n () => {\n // One data-model surprise must not stop linking for good.\n try {\n publish(\n active.update({\n vessels: (app.getPath('vessels') ?? {}) as Contexts,\n targets: (app.getPath('targets') ?? {}) as Contexts,\n selfId: app.selfId,\n nowMs: Date.now()\n })\n )\n } catch (err) {\n app.error(`Target fusion failed: ${String(err)}`)\n }\n },\n Math.max(config.interval, MIN_INTERVAL_S) * 1000\n )\n app.setPluginStatus('Linking targets to AIS vessels')\n },\n\n stop() {\n clearInterval(timer)\n timer = undefined\n if (fusion) {\n publish(fusion.stop((app.getPath('targets') ?? {}) as Contexts))\n }\n fusion = undefined\n }\n }\n}\n"],"mappings":";AAKA,IAAa,eAAe,KAAK,OAAO;CACtC,cAAc,KAAK,OAAO;EACxB,OAAO;EACP,aACE;EACF,SAAS;EACT,SAAS;CACX,CAAC;CACD,UAAU,KAAK,OAAO;EAAE,OAAO;EAA0B,SAAA;EAAyB,SAAS;CAAE,CAAC;AAChG,CAAC;AAMD,IAAa,WAAmB;CAC9B,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