@superrouteca/sindoor-react-native 0.0.0-stage → 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/src/site.ts ADDED
@@ -0,0 +1,291 @@
1
+ // A site on the phone: downloaded once (or from a cache), compiled by the native engine, routed and positioned
2
+ // offline; a locator fed by the phone's sensors and BLE beacons. The same names as @superrouteca/sindoor, except that
3
+ // making a site is asynchronous (the native engine compiles it off the JavaScript thread).
4
+ import NativeSindoor, { type Spec, type SindoorErrorEvent, type SindoorEstimateEvent } from './NativeSindoor';
5
+ import { SindoorClient } from './client';
6
+ import { parse, SindoorError } from './errors';
7
+ import { levelToLngLat, lngLatToLevel } from './geo';
8
+ import type { Anchor, BeaconStatus, Download, Estimate, IndoorLayer, Observation, Place, Route } from './types';
9
+
10
+ /** The native module, or a SindoorError when the app was built without it. */
11
+ export function nativeModule(): Spec {
12
+ if (!NativeSindoor) {
13
+ throw new SindoorError('unavailable', 'the sIndoor native module is not linked: rebuild the app after installing @superrouteca/sindoor-react-native (New Architecture)');
14
+ }
15
+ return NativeSindoor;
16
+ }
17
+
18
+ /** `{engine, sdk}`: the engine library's version and the native SDK's. */
19
+ export function engineVersion(): { engine: string; sdk: string } {
20
+ return parse(nativeModule().version());
21
+ }
22
+
23
+ export interface LoadOptions {
24
+ site: string;
25
+ /** An sMap map key (smk_…): the customer form. */
26
+ key?: string;
27
+ /** An sIndoor token (si1.…) from your server: the full form. */
28
+ token?: string;
29
+ form?: 'customer' | 'full';
30
+ baseUrl?: string;
31
+ /** Download through this client (in TypeScript) instead of the native SDK's. */
32
+ client?: SindoorClient;
33
+ }
34
+
35
+ export interface RouteOptions {
36
+ role?: 'customer' | 'staff' | 'delivery' | 'all' | string;
37
+ profile?: string;
38
+ at?: number;
39
+ }
40
+
41
+ export class SindoorSite {
42
+ private _h: number | null;
43
+ private _download: Download | null;
44
+ private _layer: IndoorLayer | null = null;
45
+
46
+ /** Made by `load`, `fromDownload` or `fromPackage`. */
47
+ constructor(handle: number, download: Download | null = null) {
48
+ this._h = handle;
49
+ this._download = download;
50
+ }
51
+
52
+ /**
53
+ * Download a site's package and compile it on the phone: with `key` / `token` the native SDK downloads it; with
54
+ * `client` a SindoorClient does.
55
+ */
56
+ static async load(o: LoadOptions): Promise<SindoorSite> {
57
+ if (!o || !o.site) throw new SindoorError('no_site', 'pass the site id');
58
+ if (o.client) return SindoorSite.fromDownload(await o.client.package(o.site, o.form || 'customer'));
59
+ if (!o.key && !o.token) throw new SindoorError('no_credentials', 'pass a map key, a token or a client');
60
+ const m = nativeModule();
61
+ const a = parse<{ handle: number }>(await m.loadSite(JSON.stringify({ site: o.site, key: o.key, token: o.token, form: o.form || 'customer', baseUrl: o.baseUrl })));
62
+ return new SindoorSite(a.handle, null);
63
+ }
64
+
65
+ /** A site from a download kept earlier (offline): the object or its JSON text. */
66
+ static async fromDownload(d: Download | string): Promise<SindoorSite> {
67
+ let obj: Download | null = null;
68
+ let text: string;
69
+ if (typeof d === 'string') {
70
+ text = d;
71
+ } else {
72
+ if (!d || !d.package) throw new SindoorError('bad_download', 'expected {package, overlay, live}');
73
+ obj = d;
74
+ text = JSON.stringify(d);
75
+ }
76
+ const a = parse<{ handle: number }>(await nativeModule().siteFromDownload(text));
77
+ return new SindoorSite(a.handle, obj);
78
+ }
79
+
80
+ /** A site package with no overlay (e.g. a file the developer ships with the app). */
81
+ static fromPackage(pkg: object, overlay: object = {}, live: object[] = [], revision = 0): Promise<SindoorSite> {
82
+ return SindoorSite.fromDownload({ package: pkg, overlay: { revision, overlay }, live });
83
+ }
84
+
85
+ /** The native handle (for the module's own calls). */
86
+ get handle(): number {
87
+ if (this._h === null) throw new SindoorError('disposed', 'the site was disposed');
88
+ return this._h;
89
+ }
90
+
91
+ /** What was downloaded (`{site, package, overlay, live}`), for a cache: `SindoorSite.fromDownload(site.download)`. */
92
+ get download(): Download {
93
+ if (!this._download) this._download = parse<Download>(nativeModule().siteDownload(this.handle));
94
+ return this._download;
95
+ }
96
+
97
+ get id(): string | undefined {
98
+ const d = this.download as Download & { package?: { site?: { id?: string } } };
99
+ return d?.site ?? d?.package?.site?.id;
100
+ }
101
+
102
+ get version(): string {
103
+ return String(this.layer().version ?? '');
104
+ }
105
+
106
+ /** Walk from → to; each end a ref (`door`, `fixture:12`), `{level, x, y}` (mm) or `{lng, lat, level}`. */
107
+ route(from: Place, to: Place, options: RouteOptions = {}): Route {
108
+ return parse(nativeModule().siteRoute(this.handle, JSON.stringify({ from: this.toEngine(from), to: this.toEngine(to), ...options })));
109
+ }
110
+
111
+ /** A list of targets in the shortest order (IV13): `{targets, start?, end?}`. */
112
+ tour(request: object): any {
113
+ return parse(nativeModule().siteTour(this.handle, JSON.stringify(request)));
114
+ }
115
+
116
+ /** From a parking point / delivery point (IV5). */
117
+ approach(request: object = {}): any {
118
+ return parse(nativeModule().siteApproach(this.handle, JSON.stringify(request)));
119
+ }
120
+
121
+ levels(): any[] {
122
+ const v = parse<any>(nativeModule().siteLevels(this.handle));
123
+ return Array.isArray(v) ? v : (v?.levels ?? []);
124
+ }
125
+
126
+ /** The indoor layer's GeoJSON — what sMap's `addIndoor` draws. */
127
+ layer(): IndoorLayer {
128
+ if (!this._layer) this._layer = parse<IndoorLayer>(nativeModule().siteLayer(this.handle));
129
+ return this._layer;
130
+ }
131
+
132
+ anchor(level: string): Anchor {
133
+ const l = (this.layer().levels || []).find((x) => x.id === level);
134
+ if (!l) throw new SindoorError('unknown_level', `no level ${level}`, [level]);
135
+ return l.anchor;
136
+ }
137
+
138
+ /** Level mm → [lng, lat] (in TypeScript, the engine's formulas). */
139
+ toLngLat(level: string, x: number, y: number): [number, number] {
140
+ return levelToLngLat(this.anchor(level), x, y);
141
+ }
142
+
143
+ /** [lng, lat] on a level → {level, x, y} mm. */
144
+ fromLngLat(level: string, lng: number, lat: number): { level: string; x: number; y: number } {
145
+ const [x, y] = lngLatToLevel(this.anchor(level), lng, lat);
146
+ return { level, x: Math.round(x), y: Math.round(y) };
147
+ }
148
+
149
+ toEngine(p: Place): unknown {
150
+ if (p && typeof p === 'object' && 'lng' in p && 'lat' in p) return this.fromLngLat(p.level, p.lng, p.lat);
151
+ if (p && typeof p === 'object' && 'x' in p && 'y' in p) {
152
+ const o: { x: number; y: number; level?: string } = { x: Math.round(p.x), y: Math.round(p.y) };
153
+ if (p.level !== undefined) o.level = p.level;
154
+ return o;
155
+ }
156
+ return p;
157
+ }
158
+
159
+ /** A positioning filter running here (steps, heading, pressure, beacons, scans, GPS → estimates). */
160
+ locator(config: object = {}): SindoorLocator {
161
+ return new SindoorLocator(this, config);
162
+ }
163
+
164
+ dispose(): void {
165
+ if (this._h === null) return;
166
+ const h = this._h;
167
+ this._h = null;
168
+ nativeModule().siteFree(h);
169
+ }
170
+ }
171
+
172
+ type Unsubscribe = () => void;
173
+
174
+ export class SindoorLocator {
175
+ readonly site: SindoorSite;
176
+ /** The last estimate, null before the first fix. */
177
+ last: Estimate | null = null;
178
+ private _h: number | null;
179
+ private _estimateListeners = new Set<(e: Estimate) => void>();
180
+ private _errorListeners = new Set<(e: SindoorError & { source?: string }) => void>();
181
+ private _subs: { remove(): void }[] = [];
182
+
183
+ constructor(site: SindoorSite, config: object = {}) {
184
+ this.site = site;
185
+ const m = nativeModule();
186
+ this._h = parse<{ handle: number }>(m.locatorNew(site.handle, JSON.stringify(config))).handle;
187
+ // The native sensors and beacons tell every locator's estimates on one emitter.
188
+ if (typeof m.sindoorEstimate === 'function') {
189
+ this._subs.push(m.sindoorEstimate((ev: SindoorEstimateEvent) => {
190
+ if (ev.locator !== this._h) return;
191
+ let e: Estimate | null = null;
192
+ try {
193
+ e = this._withLngLat(parse<Estimate | null>(ev.estimate));
194
+ } catch {
195
+ return;
196
+ }
197
+ if (e) this._tell(e);
198
+ }));
199
+ }
200
+ if (typeof m.sindoorError === 'function') {
201
+ this._subs.push(m.sindoorError((ev: SindoorErrorEvent) => {
202
+ if (ev.locator !== this._h) return;
203
+ const err = Object.assign(new SindoorError(ev.code, ev.message), { source: ev.source });
204
+ for (const l of [...this._errorListeners]) l(err);
205
+ }));
206
+ }
207
+ }
208
+
209
+ get handle(): number {
210
+ if (this._h === null) throw new SindoorError('disposed', 'the locator was disposed');
211
+ return this._h;
212
+ }
213
+
214
+ private _withLngLat(e: Estimate | null): Estimate | null {
215
+ if (!e || e.level === undefined) return null;
216
+ if (typeof e.lng !== 'number' || typeof e.lat !== 'number') {
217
+ const [lng, lat] = this.site.toLngLat(e.level, e.x, e.y);
218
+ e.lng = lng;
219
+ e.lat = lat;
220
+ }
221
+ return e;
222
+ }
223
+
224
+ private _tell(e: Estimate): void {
225
+ this.last = e;
226
+ for (const l of [...this._estimateListeners]) l(e);
227
+ }
228
+
229
+ /** One observation or a list (`{t, kind, …}` as the engine takes them) → the estimate `{x, y, level, acc_mm, at}`
230
+ * with `lng` / `lat`, or null before the first fix. `onEstimate` listeners hear it too. */
231
+ observe(obs: Observation | Observation[]): Estimate | null {
232
+ const e = this._withLngLat(parse<Estimate | null>(nativeModule().locatorObserve(this.handle, JSON.stringify(obs))));
233
+ if (e) this._tell(e);
234
+ return e;
235
+ }
236
+
237
+ /** `{step_scale, features}` — keep `step_scale` per person on the device and pass it back in the config. */
238
+ state(): { step_scale: number | null; features: Record<string, boolean> } {
239
+ return parse(nativeModule().locatorState(this.handle));
240
+ }
241
+
242
+ setCalibration(calibration: object | null): unknown {
243
+ return parse(nativeModule().locatorSetCalibration(this.handle, JSON.stringify(calibration ?? null)));
244
+ }
245
+
246
+ /** Every estimate: of `observe`, the phone's sensors and beacons. → a function that stops listening. */
247
+ onEstimate(listener: (e: Estimate) => void): Unsubscribe {
248
+ this._estimateListeners.add(listener);
249
+ return () => this._estimateListeners.delete(listener);
250
+ }
251
+
252
+ /** Problems of the sensors and beacons (`permission_missing`, `permission_denied`, `bluetooth_off`, …; `source`
253
+ * `sensors` | `beacons`). */
254
+ onError(listener: (e: SindoorError & { source?: string }) => void): Unsubscribe {
255
+ this._errorListeners.add(listener);
256
+ return () => this._errorListeners.delete(listener);
257
+ }
258
+
259
+ /** The phone's steps, heading and pressure feed this locator. True when at least one sensor is there. Ask for the
260
+ * motion permission first (iOS `NSMotionUsageDescription`; Android needs none for these sensors). */
261
+ startSensors(): boolean {
262
+ return parse<{ status: string }>(nativeModule().startSensors(this.handle)).status === 'started';
263
+ }
264
+
265
+ stopSensors(): void {
266
+ if (this._h !== null) nativeModule().stopSensors(this._h);
267
+ }
268
+
269
+ /** BLE beacons feed this locator once a second. `uuids` iBeacon UUIDs to listen for (none: the site's beacons on
270
+ * iOS, every beacon heard on Android). Never asks for a permission: a missing one is answered (and told to
271
+ * `onError`). */
272
+ startBeacons(uuids: string[] = []): BeaconStatus {
273
+ return parse<BeaconStatus>(nativeModule().startBeacons(this.handle, JSON.stringify(uuids.map((u) => String(u).toLowerCase()))));
274
+ }
275
+
276
+ stopBeacons(): void {
277
+ if (this._h !== null) nativeModule().stopBeacons(this._h);
278
+ }
279
+
280
+ /** Stops the sensors and beacons and frees the locator. */
281
+ dispose(): void {
282
+ if (this._h === null) return;
283
+ const h = this._h;
284
+ this._h = null;
285
+ for (const s of this._subs) s.remove();
286
+ this._subs = [];
287
+ this._estimateListeners.clear();
288
+ this._errorListeners.clear();
289
+ nativeModule().locatorFree(h);
290
+ }
291
+ }
package/src/types.ts ADDED
@@ -0,0 +1,84 @@
1
+ // The shapes of sIndoor's answers, as @superrouteca/sindoor types them.
2
+
3
+ export interface Download {
4
+ site?: string;
5
+ package: object;
6
+ overlay?: { revision: number; overlay: object };
7
+ live?: object[];
8
+ }
9
+
10
+ export interface Anchor {
11
+ lat: number;
12
+ lon: number;
13
+ rotation_deg?: number;
14
+ scale?: number;
15
+ }
16
+
17
+ export interface LayerLevel {
18
+ id: string;
19
+ ordinal: number;
20
+ kind: 'indoor' | 'outdoor';
21
+ building?: string | null;
22
+ anchor: Anchor;
23
+ }
24
+
25
+ export interface IndoorLayer {
26
+ type: 'FeatureCollection';
27
+ frame: 'wgs84' | 'local';
28
+ site: string;
29
+ version: string;
30
+ levels: LayerLevel[];
31
+ features: object[];
32
+ }
33
+
34
+ export interface PublicSite {
35
+ site: string;
36
+ name: string;
37
+ bbox: [number, number, number, number];
38
+ levels: LayerLevel[];
39
+ }
40
+
41
+ /** A ref (`door`, `fixture:12`), a point in millimetres, or a longitude / latitude on a level. */
42
+ export type Place = string | { level?: string; x: number; y: number } | { level: string; lng: number; lat: number };
43
+
44
+ export interface Step {
45
+ kind: string;
46
+ level: string;
47
+ at: [number, number];
48
+ distance_mm: number;
49
+ angle_deg?: number;
50
+ }
51
+
52
+ export interface Route {
53
+ length_mm: number;
54
+ duration_s: number;
55
+ level: string;
56
+ legs: { level: string; polyline: [number, number][] }[];
57
+ steps: Step[];
58
+ connectors: object[];
59
+ version: string;
60
+ }
61
+
62
+ export interface Estimate {
63
+ x: number;
64
+ y: number;
65
+ level: string;
66
+ acc_mm: number;
67
+ at: number;
68
+ lng: number;
69
+ lat: number;
70
+ [k: string]: unknown;
71
+ }
72
+
73
+ export interface Observation {
74
+ t: number;
75
+ kind: string;
76
+ [k: string]: unknown;
77
+ }
78
+
79
+ /** What `startBeacons` found. */
80
+ export interface BeaconStatus {
81
+ status: 'started' | 'permission_missing' | 'bluetooth_off' | 'not_supported' | string;
82
+ /** Android: the permissions not granted (the app asks for them). */
83
+ permissions?: string[];
84
+ }