@openfitnessprotocol/ofp 0.0.0-stage → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Binary file
package/index.d.ts ADDED
@@ -0,0 +1,148 @@
1
+ export interface OfpField {
2
+ key: string
3
+ id: number
4
+ name: string
5
+ unit: string
6
+ type: 'int' | 'decimal'
7
+ decimals: number
8
+ min: number
9
+ max: number
10
+ kind: 'instantaneous' | 'event' | 'cumulative' | 'state'
11
+ tier: 'experimental' | 'stable'
12
+ }
13
+
14
+ /** A device OFP recognised. `id` is `<table>:<instance>`, e.g. `keiser-m3i:197`. */
15
+ export interface OfpDevice {
16
+ id: string
17
+ name: string
18
+ table: string
19
+ tableVersion: number
20
+ instance?: number
21
+ instanceLabel?: string
22
+ fields: OfpField[]
23
+ /** Read over a connection: when it comes into use, `on.connect` asks the app to connect and subscribe. */
24
+ connectable: boolean
25
+ }
26
+
27
+ /** What the app's Bluetooth has to do for a connectable device. */
28
+ /** Fixed bytes to write to the device (from its table: never computed, never to a control point). */
29
+ export interface OfpWrite {
30
+ service: string
31
+ characteristic: string
32
+ bytes: Uint8Array
33
+ withResponse: boolean
34
+ }
35
+
36
+ export interface OfpConnectRequest {
37
+ id: string
38
+ /** The app's own id for the device (what it passed as `deviceId` in the advertisement). */
39
+ deviceId: string
40
+ subscribe: Array<{ service: string; characteristic: string }>
41
+ /** Write these once, in order, right after subscribing. Empty for most devices. */
42
+ start: OfpWrite[]
43
+ }
44
+
45
+ export interface OfpBasic {
46
+ power: number
47
+ cadence: number
48
+ speed: number
49
+ heartRate: number
50
+ }
51
+
52
+ export interface OfpValues {
53
+ id: string
54
+ t: number
55
+ /** Field key → value: every field the device sends, described in `OfpDevice.fields`. A field of type
56
+ * `list` (RR intervals) is an array, sent once with its packet and never repeated. */
57
+ fields: Record<string, number | number[]>
58
+ /** The four values every training app has a place for (0 when the device has none). */
59
+ basic: OfpBasic
60
+ /** True for the zeros sent when the device went silent. */
61
+ silent: boolean
62
+ /** True when these are the standing values sent again, not a new packet from the device. */
63
+ repeat: boolean
64
+ rssi?: number
65
+ outOfRange: string[]
66
+ }
67
+
68
+ export interface OfpEngine {
69
+ create(bundleJson: string): { call(request: Record<string, unknown>): any[]; destroy(): void }
70
+ }
71
+
72
+ export interface OfpOptions {
73
+ engine: OfpEngine
74
+ /** The registry bundle (JSON text). */
75
+ bundle: string
76
+ /** Bluetooth services the app reads by itself (short UUIDs: '180d', '1818', '1826', …). */
77
+ iRead?: string[]
78
+ /** Sources the rider used before: used again as soon as they are heard. */
79
+ remembered?: string[]
80
+ on?: {
81
+ device?: (device: OfpDevice) => void
82
+ values?: (values: OfpValues) => void
83
+ /** `auto`: OFP started using a remembered device by itself. */
84
+ inUse?: (id: string, auto: boolean, device?: OfpDevice) => void
85
+ /** A device in use stayed silent for `lostAfterMs`. It is used again by itself if remembered. */
86
+ lost?: (id: string) => void
87
+ silent?: (id: string) => void
88
+ /** Connect to the device and subscribe to these characteristics; then call `connected` and pass their notifications to `notification`. */
89
+ connect?: (request: OfpConnectRequest) => void
90
+ /** A device that answers only when asked: write these fixed bytes now. Needs tick() every 200 ms or so. */
91
+ write?: (request: OfpWrite & { id: string; deviceId: string }) => void
92
+ /** The device is no longer in use: the connection is not needed for it. */
93
+ disconnect?: (request: { id: string; deviceId: string }) => void
94
+ /** Once a minute for a device in use: how well the radio hears it. */
95
+ radio?: (stats: { id: string; packets: number; longestGapMs: number; rssi?: number }) => void
96
+ error?: (error: unknown) => void
97
+ }
98
+ minStaleMs?: number
99
+ repeatMs?: number
100
+ lostAfterMs?: number
101
+ /** Announce a device that keeps being heard but is not in use again this often (0 = never). */
102
+ reofferMs?: number
103
+ tickMs?: number
104
+ now?: () => number
105
+ }
106
+
107
+ export interface OfpAdvertisement {
108
+ deviceId: string
109
+ name?: string | null
110
+ rssi?: number | null
111
+ /** Raw manufacturer data, company id first: bytes, or hex text. */
112
+ manufacturerData?: Uint8Array | number[] | string | null
113
+ /** Service UUIDs the device advertises (how devices that are connected to are recognised). */
114
+ services?: string[]
115
+ }
116
+
117
+ export class Ofp {
118
+ constructor(options: OfpOptions)
119
+ readonly failed: boolean
120
+ /** Bluetooth company ids the registry's tables match on. */
121
+ readonly companyIds: number[]
122
+ advertisement(a: OfpAdvertisement): void
123
+ connected(deviceId: string): void
124
+ disconnected(deviceId: string): void
125
+ notification(deviceId: string, characteristic: string, bytes: Uint8Array | number[] | string): void
126
+ use(id: string): boolean
127
+ release(id: string): void
128
+ isInUse(id: string): boolean
129
+ /** Ids of the devices in use. */
130
+ used(): string[]
131
+ devices(heardWithinMs?: number): OfpDevice[]
132
+ describe(id: string): OfpDevice | undefined
133
+ /** 'in_use': scan continuously and do not stop; 'waiting': a slow scan is enough; null: nothing. */
134
+ scanNeed(): 'in_use' | 'waiting' | null
135
+ hasHeartRate(id: string): boolean
136
+ rssi(id: string): number | undefined
137
+ tick(): void
138
+ destroy(): void
139
+ }
140
+
141
+ export function wasmEngine(wasmBytes: Uint8Array): OfpEngine
142
+ /** `exports`: a WebAssembly instance's exports, or the module `wasm2js` makes from the same file. */
143
+ export function moduleEngine(exports: any): OfpEngine
144
+ export function companyIdsOf(bundleJson: string): number[]
145
+ export function selfTest(engine: OfpEngine, bundle: string, rounds?: number): { ok: boolean; power?: number; cadence?: number; msPerPacket?: number; error?: string }
146
+ export function basic(fields: Record<string, number>): OfpBasic
147
+ export function toHex(bytes: Uint8Array | number[]): string
148
+ export function base64ToHex(base64: string): string
package/index.js ADDED
@@ -0,0 +1,410 @@
1
+ // Open Fitness Protocol for JavaScript apps.
2
+ //
3
+ // OFP has no Bluetooth of its own. An app wires up four things:
4
+ // 1. new Ofp({ engine, bundle, iRead: [...services the app reads itself] })
5
+ // 2. ofp.advertisement(...) for every advertisement its scanner hears, unfiltered
6
+ // 3. on.device / on.values devices OFP recognises, and their readings
7
+ // 4. ofp.use(id) / ofp.release(id) when the rider picks one or lets it go
8
+ //
9
+ // The engine is the OFP core: WebAssembly where the runtime has it (`wasmEngine`), or the same core
10
+ // translated to plain JavaScript where it does not, such as React Native's Hermes (`moduleEngine`).
11
+ // No dependencies, no Node or browser globals beyond typed arrays.
12
+
13
+ function utf8Encode(text) {
14
+ const out = [];
15
+ for (let i = 0; i < text.length; i++) {
16
+ let c = text.charCodeAt(i);
17
+ if (c >= 0xd800 && c <= 0xdbff && i + 1 < text.length) {
18
+ const d = text.charCodeAt(i + 1);
19
+ if (d >= 0xdc00 && d <= 0xdfff) { c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00); i++; }
20
+ }
21
+ if (c < 0x80) out.push(c);
22
+ else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 63));
23
+ else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
24
+ else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
25
+ }
26
+ return out;
27
+ }
28
+
29
+ function utf8Decode(bytes) {
30
+ let s = '';
31
+ for (let i = 0; i < bytes.length; ) {
32
+ const b = bytes[i++];
33
+ let c;
34
+ if (b < 0x80) c = b;
35
+ else if (b < 0xe0) c = ((b & 31) << 6) | (bytes[i++] & 63);
36
+ else if (b < 0xf0) { c = ((b & 15) << 12) | ((bytes[i] & 63) << 6) | (bytes[i + 1] & 63); i += 2; }
37
+ else { c = ((b & 7) << 18) | ((bytes[i] & 63) << 12) | ((bytes[i + 1] & 63) << 6) | (bytes[i + 2] & 63); i += 3; }
38
+ if (c >= 0x10000) { c -= 0x10000; s += String.fromCharCode(0xd800 + (c >> 10), 0xdc00 + (c & 1023)); } else s += String.fromCharCode(c);
39
+ }
40
+ return s;
41
+ }
42
+
43
+ const HEX = [];
44
+ for (let i = 0; i < 256; i++) HEX.push((i < 16 ? '0' : '') + i.toString(16));
45
+
46
+ /** Bytes (Uint8Array, Node Buffer, or number[]) as lower-case hex. */
47
+ export function toHex(bytes) {
48
+ let s = '';
49
+ for (let i = 0; i < bytes.length; i++) s += HEX[bytes[i] & 0xff];
50
+ return s;
51
+ }
52
+
53
+ /** Base64 (what React Native BLE libraries hand over) as hex. */
54
+ export function base64ToHex(b64) {
55
+ const A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
56
+ let s = '', buf = 0, bits = 0;
57
+ for (let i = 0; i < b64.length; i++) {
58
+ const v = A.indexOf(b64[i]);
59
+ if (v < 0) continue;
60
+ buf = (buf << 6) | v;
61
+ bits += 6;
62
+ if (bits >= 8) { bits -= 8; s += HEX[(buf >> bits) & 0xff]; }
63
+ }
64
+ return s;
65
+ }
66
+
67
+ /**
68
+ * The core behind its five C functions. `exports` is what a WebAssembly instance exports, or the
69
+ * module `wasm2js` makes from the same file: both look the same from here.
70
+ */
71
+ export function moduleEngine(exports) {
72
+ const x = exports;
73
+ // The memory can grow (and its buffer be replaced) on any call: take the view each time.
74
+ const mem = () => new Uint8Array(x.memory.buffer);
75
+ const put = (text) => {
76
+ const bytes = utf8Encode(text);
77
+ const ptr = x.ofp_alloc(bytes.length);
78
+ mem().set(bytes, ptr);
79
+ return [ptr, bytes.length];
80
+ };
81
+ const take = (ptr) => {
82
+ const m = mem();
83
+ const len = (m[ptr] | (m[ptr + 1] << 8) | (m[ptr + 2] << 16) | (m[ptr + 3] << 24)) >>> 0;
84
+ const text = utf8Decode(m.subarray(ptr + 4, ptr + 4 + len));
85
+ x.ofp_free(ptr, 4 + len);
86
+ return text;
87
+ };
88
+ return {
89
+ /** A core loaded with a registry bundle (JSON text). Throws when the bundle is refused. */
90
+ create(bundleJson) {
91
+ const [bp, bl] = put(bundleJson);
92
+ let core = x.ofp_core_new(bp, bl);
93
+ x.ofp_free(bp, bl);
94
+ if (!core) throw new Error('OFP bundle refused: ' + take(x.ofp_last_error()));
95
+ return {
96
+ call(request) {
97
+ if (!core) return [];
98
+ const [p, l] = put(JSON.stringify(request));
99
+ const reply = JSON.parse(take(x.ofp_call(core, p, l)));
100
+ x.ofp_free(p, l);
101
+ if (reply.error) throw new Error('OFP: ' + reply.error);
102
+ return reply.messages || [];
103
+ },
104
+ destroy() {
105
+ if (core) x.ofp_core_free(core);
106
+ core = 0;
107
+ },
108
+ };
109
+ },
110
+ };
111
+ }
112
+
113
+ /** The core from its WebAssembly bytes (Node, Electron, browsers). */
114
+ export function wasmEngine(wasmBytes) {
115
+ return moduleEngine(new WebAssembly.Instance(new WebAssembly.Module(wasmBytes), {}).exports);
116
+ }
117
+
118
+ /** The four values every training app has a place for, from a values message's fields. */
119
+ export function basic(fields) {
120
+ return {
121
+ power: fields.power ?? 0,
122
+ cadence: fields.cadence ?? 0,
123
+ speed: fields.speed ?? 0,
124
+ heartRate: fields.heart_rate ?? 0,
125
+ };
126
+ }
127
+
128
+ /** Bluetooth company ids the registry's tables match on: what a filtered scan has to let through. */
129
+ export function companyIdsOf(bundleJson) {
130
+ try {
131
+ const ids = [];
132
+ for (const table of JSON.parse(bundleJson).tables || []) {
133
+ for (const rule of table.match || []) {
134
+ if (typeof rule.manufacturer_id === 'number' && !ids.includes(rule.manufacturer_id)) ids.push(rule.manufacturer_id);
135
+ }
136
+ }
137
+ return ids;
138
+ } catch {
139
+ return [];
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Does the core run here? Decodes a known Keiser M3i packet (187 W, 84 rpm) and times a few hundred
145
+ * more. Worth one log line at start: on a phone the core is a large generated file, and a device in
146
+ * range is the only other thing that would start it.
147
+ */
148
+ export function selfTest(engine, bundle, rounds = 300) {
149
+ try {
150
+ let last;
151
+ const ofp = new Ofp({ engine, bundle, tickMs: 0, on: { values: (v) => { last = v; } } });
152
+ const packet = [0x02, 0x01, 0x06, 0x30, 0x00, 0x07, 0x48, 0x03, 0x8c, 0x05, 0xbb, 0x00, 0x2a, 0x00, 0x0c, 0x22, 0x33, 0x80, 0x0e];
153
+ const started = Date.now();
154
+ for (let i = 0; i < rounds; i++) ofp.advertisement({ deviceId: 'self-test', name: 'M3', manufacturerData: packet });
155
+ const msPerPacket = (Date.now() - started) / rounds;
156
+ ofp.destroy();
157
+ const ok = !!last && last.basic.power === 187 && last.basic.cadence === 84;
158
+ return { ok, power: last && last.basic.power, cadence: last && last.basic.cadence, msPerPacket };
159
+ } catch (error) {
160
+ return { ok: false, error: String(error) };
161
+ }
162
+ }
163
+
164
+ /** One write the core asks for, as the app's Bluetooth wants it. */
165
+ function toWrite(w) {
166
+ const bytes = new Uint8Array((w.data.length / 2) | 0);
167
+ for (let i = 0; i < bytes.length; i++) bytes[i] = parseInt(w.data.substr(i * 2, 2), 16);
168
+ return { service: w.service, characteristic: w.characteristic, bytes, withResponse: !!w.with_response };
169
+ }
170
+
171
+ export class Ofp {
172
+ /**
173
+ * @param {object} o
174
+ * @param o.engine from wasmEngine() or moduleEngine()
175
+ * @param {string} o.bundle the registry bundle (JSON text)
176
+ * @param {string[]} [o.iRead] Bluetooth services the app reads by itself (short UUIDs, e.g. '180d')
177
+ * @param {string[]} [o.remembered] sources the rider used before: used again as soon as heard
178
+ * @param {object} [o.on] { device, values, inUse, lost, silent, error }
179
+ * @param {number} [o.minStaleMs] wait this long before a source counts as silent (default 10 s:
180
+ * a phone's or computer's radio misses adverts for seconds at a time)
181
+ * @param {number} [o.repeatMs] repeat a source's standing values this often while it is in use
182
+ * (default 1 s, for apps that treat "no event" as "no data"); 0 = never
183
+ * @param {number} [o.lostAfterMs] give up a silent source after this long (default 60 s)
184
+ * @param {number} [o.reofferMs] while a device that is not in use keeps being heard, announce it
185
+ * again (on.device) this often, for device lists that drop what they have not seen lately; 0 = never
186
+ * @param {number} [o.tickMs] the timer's period (default 1 s); 0 = the app calls tick() itself
187
+ * @param {() => number} [o.now]
188
+ */
189
+ constructor(o) {
190
+ this.on = o.on || {};
191
+ this.now = o.now || Date.now;
192
+ this.failed = false;
193
+ this.described = new Map(); // source id → its description
194
+ this.inUse = new Set();
195
+ this.remembered = new Set(o.remembered || []);
196
+ this.heard = new Map(); // source id → how well the radio hears it
197
+ this.reofferMs = o.reofferMs || 0;
198
+ this.companyIds = companyIdsOf(o.bundle);
199
+ this.core = o.engine.create(o.bundle);
200
+ this.core.call({
201
+ op: 'configure',
202
+ min_stale_ms: o.minStaleMs ?? 10000,
203
+ repeat_ms: o.repeatMs ?? 1000,
204
+ lost_after_ms: o.lostAfterMs ?? 60000,
205
+ remembered: o.remembered || [],
206
+ ...(o.iRead ? { handled_services: o.iRead } : {}),
207
+ });
208
+ const period = o.tickMs ?? 1000;
209
+ this.timer = period > 0 ? setInterval(() => this.tick(), period) : null;
210
+ if (this.timer && typeof this.timer.unref === 'function') this.timer.unref();
211
+ }
212
+
213
+ /** One failure turns OFP off: it must never take the app's Bluetooth down with it. */
214
+ _guard(fn) {
215
+ if (this.failed || !this.core) return;
216
+ try {
217
+ this._deliver(fn());
218
+ } catch (e) {
219
+ this.failed = true;
220
+ if (this.timer) clearInterval(this.timer);
221
+ for (const id of [...this.inUse]) { this.inUse.delete(id); this.on.lost && this.on.lost(id); }
222
+ this.on.error && this.on.error(e);
223
+ }
224
+ }
225
+
226
+ /** Polls are due as often as every 200 ms: a device that is polled needs tick() that often. */
227
+ get tickNeedMs() {
228
+ return 200;
229
+ }
230
+
231
+ _deliver(messages) {
232
+ for (const m of messages) {
233
+ switch (m.type) {
234
+ // A device that is connected to: the app's Bluetooth makes the connection and passes the
235
+ // notifications in (see `connected`, `notification`, `disconnected`).
236
+ case 'connect':
237
+ // `start`: fixed bytes to write once, in order, right after subscribing (most devices: none)
238
+ this.on.connect && this.on.connect({ id: m.source_id, deviceId: m.device_id, subscribe: m.subscribe, start: (m.start || []).map(toWrite) });
239
+ break;
240
+ // A device that answers only when asked: write these fixed bytes now (a table's `poll`).
241
+ case 'write':
242
+ this.on.write && this.on.write({ id: m.source_id, deviceId: m.device_id, ...toWrite(m.write) });
243
+ break;
244
+ case 'disconnect':
245
+ this.on.disconnect && this.on.disconnect({ id: m.source_id, deviceId: m.device_id });
246
+ break;
247
+ case 'source_appeared': {
248
+ const d = { id: m.source_id, name: m.name, table: m.table, tableVersion: m.table_version, instance: m.instance, instanceLabel: m.instance_label, fields: m.fields, connectable: !!m.connectable };
249
+ this.described.set(d.id, d);
250
+ this.on.device && this.on.device(d);
251
+ break;
252
+ }
253
+ case 'values': {
254
+ const now = this.now();
255
+ let h = this.heard.get(m.source_id);
256
+ if (!h) { h = { packets: 0, minutePackets: 0, lastAt: now, longestGapMs: 0, minuteStart: now, offeredAt: now, rssi: undefined, heartRateSeen: false }; this.heard.set(m.source_id, h); }
257
+ if (!m.stale && !m.repeat) {
258
+ if (h.packets > 0) h.longestGapMs = Math.max(h.longestGapMs, now - h.lastAt);
259
+ h.packets++; h.minutePackets++; h.lastAt = now;
260
+ if (typeof m.rssi === 'number') h.rssi = m.rssi;
261
+ if ((m.fields.heart_rate || 0) > 0) h.heartRateSeen = true;
262
+ // still being heard and nobody is using it: keep it in the app's device list
263
+ if (this.reofferMs > 0 && !this.inUse.has(m.source_id) && now - h.offeredAt >= this.reofferMs) {
264
+ h.offeredAt = now;
265
+ const d = this.described.get(m.source_id);
266
+ if (d && this.on.device) this.on.device(d);
267
+ }
268
+ }
269
+ // once a minute for a device in use: how well the radio hears it
270
+ if (this.inUse.has(m.source_id) && now - h.minuteStart >= 60000) {
271
+ if (this.on.radio) this.on.radio({ id: m.source_id, packets: h.minutePackets, longestGapMs: h.longestGapMs, rssi: h.rssi });
272
+ h.minuteStart = now; h.minutePackets = 0; h.longestGapMs = 0;
273
+ }
274
+ this.on.values && this.on.values({ id: m.source_id, t: m.t, fields: m.fields, basic: basic(m.fields), silent: !!m.stale, repeat: !!m.repeat, rssi: m.rssi, outOfRange: m.out_of_range || [] });
275
+ break;
276
+ }
277
+ case 'source_stale':
278
+ this.on.silent && this.on.silent(m.source_id);
279
+ break;
280
+ case 'source_in_use': {
281
+ this.inUse.add(m.source_id);
282
+ this.remembered.add(m.source_id);
283
+ const h = this.heard.get(m.source_id);
284
+ if (h) { h.minuteStart = this.now(); h.minutePackets = 0; h.longestGapMs = 0; }
285
+ this.on.inUse && this.on.inUse(m.source_id, !!m.auto, this.described.get(m.source_id));
286
+ break;
287
+ }
288
+ case 'source_lost':
289
+ this.inUse.delete(m.source_id);
290
+ this.on.lost && this.on.lost(m.source_id);
291
+ break;
292
+ }
293
+ }
294
+ }
295
+
296
+ /**
297
+ * Hook 2: every advertisement the app's scanner hears, before the app's own filtering.
298
+ * `manufacturerData` is the raw manufacturer data with the 2-byte company id first, as bytes
299
+ * (Uint8Array / Buffer) or already as hex.
300
+ */
301
+ advertisement(a) {
302
+ const data = a.manufacturerData;
303
+ const services = a.services || [];
304
+ // nothing a table could match on
305
+ if ((!data || data.length < 2) && !services.length && !a.name) return;
306
+ this._guard(() => this.core.call({
307
+ op: 'advertisement',
308
+ device_id: a.deviceId || '',
309
+ name: a.name || null,
310
+ rssi: typeof a.rssi === 'number' ? Math.round(a.rssi) : null,
311
+ manufacturer_data: !data ? '' : typeof data === 'string' ? data : toHex(data),
312
+ services,
313
+ now_ms: Math.round(this.now()),
314
+ }));
315
+ }
316
+
317
+ /** The app connected the device and subscribed, as `on.connect` asked. */
318
+ connected(deviceId) {
319
+ this._guard(() => this.core.call({ op: 'connected', device_id: deviceId, now_ms: Math.round(this.now()) }));
320
+ }
321
+
322
+ /** The connection ended, or could not be made. The device's values read zero at once. */
323
+ disconnected(deviceId) {
324
+ this._guard(() => this.core.call({ op: 'disconnected', device_id: deviceId, now_ms: Math.round(this.now()) }));
325
+ }
326
+
327
+ /** One notification from a characteristic `on.connect` asked for. `bytes`: Uint8Array, number[] or hex. */
328
+ notification(deviceId, characteristic, bytes) {
329
+ this._guard(() => this.core.call({ op: 'notification', device_id: deviceId, characteristic, data: typeof bytes === 'string' ? bytes : toHex(bytes), now_ms: Math.round(this.now()) }));
330
+ }
331
+
332
+ /** Hook 4: the rider picked this device. False when it has not been heard. */
333
+ use(id) {
334
+ if (this.failed || !this.core) return false;
335
+ try {
336
+ this._deliver(this.core.call({ op: 'use_source', source_id: id, now_ms: Math.round(this.now()) }));
337
+ return this.inUse.has(id);
338
+ } catch {
339
+ return false;
340
+ }
341
+ }
342
+
343
+ /** Hook 4: the rider let it go. The app also drops it from what it passes as `remembered`. */
344
+ release(id) {
345
+ this.inUse.delete(id);
346
+ this.remembered.delete(id);
347
+ this._guard(() => this.core.call({ op: 'release_source', source_id: id }));
348
+ }
349
+
350
+ isInUse(id) {
351
+ return this.inUse.has(id);
352
+ }
353
+
354
+ /** Ids of the devices in use. */
355
+ used() {
356
+ return [...this.inUse];
357
+ }
358
+
359
+ /** The devices in range (and in use): for a device list that just opened. */
360
+ devices(heardWithinMs = 30000) {
361
+ if (this.failed || !this.core) return [];
362
+ try {
363
+ return this.core.call({ op: 'sources', now_ms: Math.round(this.now()), heard_within_ms: heardWithinMs })
364
+ .map((m) => ({ id: m.source_id, name: m.name, table: m.table, tableVersion: m.table_version, instance: m.instance, instanceLabel: m.instance_label, fields: m.fields, connectable: !!m.connectable }));
365
+ } catch {
366
+ return [];
367
+ }
368
+ }
369
+
370
+ /**
371
+ * What the app's scan has to do for OFP right now. A broadcast-only device's data IS the scan:
372
+ * - 'in_use' one is giving the app its numbers: scan continuously, and do not stop
373
+ * - 'waiting' a remembered one has not been heard yet: a slow scan is enough to notice it
374
+ * - null nothing
375
+ */
376
+ scanNeed() {
377
+ if (this.failed || !this.core) return null;
378
+ if (this.inUse.size > 0) return 'in_use';
379
+ return this.remembered.size > 0 ? 'waiting' : null;
380
+ }
381
+
382
+ /** True once the device sent a heart rate above zero. A bike with no strap paired to it sends 0:
383
+ * offer it as a heart-rate source only when this is true, or it takes the place of a real strap. */
384
+ hasHeartRate(id) {
385
+ const h = this.heard.get(id);
386
+ return !!h && h.heartRateSeen;
387
+ }
388
+
389
+ /** Last signal strength heard for a device, if any. */
390
+ rssi(id) {
391
+ const h = this.heard.get(id);
392
+ return h ? h.rssi : undefined;
393
+ }
394
+
395
+ /** What `source_appeared` said about a device, if it was heard. */
396
+ describe(id) {
397
+ return this.described.get(id);
398
+ }
399
+
400
+ tick() {
401
+ this._guard(() => this.core.call({ op: 'tick', now_ms: Math.round(this.now()) }));
402
+ }
403
+
404
+ destroy() {
405
+ if (this.timer) clearInterval(this.timer);
406
+ this.timer = null;
407
+ try { this.core && this.core.destroy(); } catch { /* already gone */ }
408
+ this.core = null;
409
+ }
410
+ }
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
2
  "name": "@openfitnessprotocol/ofp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.2",
4
+ "description": "Open Fitness Protocol: read fitness devices (heart rate, power, FTMS bikes, rowers, treadmills and more) from any JavaScript app. The core (WebAssembly, or plain JavaScript for React Native), the device tables, and the four hooks an app wires up.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "index.js",
8
+ "types": "index.d.ts",
9
+ "files": [
10
+ "LICENSE",
11
+ "NOTICE",
12
+ "adapters",
13
+ "core",
14
+ "index.d.ts",
15
+ "index.js",
16
+ "registry.bundle.json",
17
+ "registry.d.ts",
18
+ "registry.js"
19
+ ],
20
+ "exports": {
21
+ ".": {
22
+ "types": "./index.d.ts",
23
+ "default": "./index.js"
24
+ },
25
+ "./adapters/noble": "./adapters/noble.js",
26
+ "./adapters/react-native-ble-manager": "./adapters/react-native-ble-manager.js",
27
+ "./core/ofp_core.wasm": "./core/ofp_core.wasm",
28
+ "./core/js": {
29
+ "types": "./core/ofp_core.asm.d.ts",
30
+ "default": "./core/ofp_core.asm.js"
31
+ },
32
+ "./registry": {
33
+ "types": "./registry.d.ts",
34
+ "default": "./registry.js"
35
+ },
36
+ "./registry.bundle.json": "./registry.bundle.json",
37
+ "./package.json": "./package.json"
38
+ },
39
+ "scripts": {
40
+ "test": "node --test test/ofp.test.js"
41
+ },
42
+ "homepage": "https://openfitnessprotocol.org",
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "git+https://github.com/trainerday/openfitnessprotocol.git",
46
+ "directory": "packages/ofp-js"
47
+ },
48
+ "bugs": {
49
+ "url": "https://github.com/trainerday/openfitnessprotocol/issues"
50
+ },
51
+ "keywords": [
52
+ "bluetooth",
53
+ "ble",
54
+ "fitness",
55
+ "ftms",
56
+ "heart-rate",
57
+ "cycling",
58
+ "power-meter",
59
+ "indoor-bike",
60
+ "rower",
61
+ "react-native",
62
+ "electron"
63
+ ],
64
+ "publishConfig": {
65
+ "access": "public"
66
+ }
67
+ }
@@ -0,0 +1 @@
1
+ {"version":1,"fields":[{"id":1,"key":"power","name":"Power","unit":"W","type":"int","decimals":0,"min":0.0,"max":3000.0,"kind":"instantaneous","tier":"experimental"},{"id":2,"key":"cadence","name":"Cadence","unit":"rpm","type":"decimal","decimals":1,"min":0.0,"max":300.0,"kind":"instantaneous","tier":"experimental"},{"id":3,"key":"heart_rate","name":"Heart rate","unit":"bpm","type":"decimal","decimals":1,"min":0.0,"max":255.0,"kind":"instantaneous","tier":"experimental"},{"id":4,"key":"speed","name":"Speed","unit":"km/h","type":"decimal","decimals":1,"min":0.0,"max":150.0,"kind":"instantaneous","tier":"experimental"},{"id":5,"key":"gear","name":"Gear","unit":"","type":"int","decimals":0,"min":0.0,"max":100.0,"kind":"state","tier":"experimental"},{"id":6,"key":"elapsed_time","name":"Elapsed time","unit":"s","type":"int","decimals":0,"min":0.0,"max":360000.0,"kind":"cumulative","tier":"experimental"},{"id":7,"key":"distance","name":"Distance","unit":"m","type":"int","decimals":0,"min":0.0,"max":2000000.0,"kind":"cumulative","tier":"experimental"},{"id":8,"key":"energy","name":"Energy","unit":"kcal","type":"int","decimals":0,"min":0.0,"max":20000.0,"kind":"cumulative","tier":"experimental"},{"id":9,"key":"firmware_build","name":"Firmware build","unit":"","type":"int","decimals":0,"min":0.0,"max":65535.0,"kind":"state","tier":"experimental"},{"id":10,"key":"core_temperature","name":"Core body temperature","unit":"°C","type":"decimal","decimals":2,"min":25.0,"max":45.0,"kind":"instantaneous","tier":"experimental"},{"id":11,"key":"skin_temperature","name":"Skin temperature","unit":"°C","type":"decimal","decimals":2,"min":5.0,"max":45.0,"kind":"instantaneous","tier":"experimental"},{"id":12,"key":"heat_strain_index","name":"Heat strain index","unit":"","type":"decimal","decimals":1,"min":0.0,"max":25.5,"kind":"instantaneous","tier":"experimental"},{"id":13,"key":"breathing_rate","name":"Breathing rate","unit":"br/min","type":"decimal","decimals":1,"min":0.0,"max":120.0,"kind":"instantaneous","tier":"experimental"},{"id":14,"key":"tidal_volume","name":"Tidal volume","unit":"L","type":"decimal","decimals":2,"min":0.0,"max":10.0,"kind":"instantaneous","tier":"experimental"},{"id":15,"key":"minute_ventilation","name":"Minute ventilation","unit":"L/min","type":"decimal","decimals":1,"min":0.0,"max":400.0,"kind":"instantaneous","tier":"experimental"},{"id":16,"key":"resistance","name":"Resistance","unit":"","type":"decimal","decimals":1,"min":-100.0,"max":300.0,"kind":"instantaneous","tier":"experimental"},{"id":17,"key":"stroke_rate","name":"Stroke rate","unit":"spm","type":"decimal","decimals":1,"min":0.0,"max":80.0,"kind":"instantaneous","tier":"experimental"},{"id":18,"key":"stroke_count","name":"Strokes","unit":"","type":"int","decimals":0,"min":0.0,"max":1000000.0,"kind":"cumulative","tier":"experimental"},{"id":19,"key":"running_cadence","name":"Running cadence","unit":"spm","type":"int","decimals":0,"min":0.0,"max":300.0,"kind":"instantaneous","tier":"experimental"},{"id":20,"key":"incline","name":"Incline","unit":"%","type":"decimal","decimals":1,"min":-30.0,"max":50.0,"kind":"instantaneous","tier":"experimental"},{"id":21,"key":"rr_interval","name":"RR interval","unit":"ms","type":"list","decimals":1,"min":200.0,"max":3000.0,"kind":"instantaneous","tier":"experimental"}],"tables":[{"id":"keiser-m3i","name":"Keiser M3i","reader":"broadcast","version":2,"match":[{"manufacturer_id":258,"min_length":17},{"manufacturer_id":1605,"min_length":17},{"name_prefix":"M3","min_length":17,"when":{"bin":["eq",{"u8":0},{"num":6.0}]}}],"only_when":{"bin":["both",{"bin":["eq",{"u8":2},{"num":0.0}]},{"bin":["ne",{"u8":3},{"num":0.0}]}]},"instance":{"label":"bike","value":{"u8":3}},"stale_after_ms":3000,"fields":[{"field":"power","value":{"u16le":8}},{"field":"cadence","value":{"bin":["div",{"u16le":4},{"num":10.0}]}},{"field":"heart_rate","value":{"bin":["div",{"u16le":6},{"num":10.0}]}},{"field":"energy","value":{"u16le":10}},{"field":"elapsed_time","value":{"bin":["add",{"bin":["mul",{"u8":12},{"num":60.0}]},{"u8":13}]}},{"field":"distance","value":{"bin":["mul",{"bin":["div",{"bin":["and",{"u16le":14},{"num":32767.0}]},{"num":10.0}]},{"if":[{"bin":["and",{"u16le":14},{"num":32768.0}]},{"num":1000.0},{"num":1609.344}]}]}},{"field":"gear","value":{"u8":16},"only_when":{"bin":["ge",{"u8":1},{"num":33.0}]}},{"field":"firmware_build","value":{"bin":["add",{"bin":["mul",{"u8":0},{"num":256.0}]},{"u8":1}]}}]}]}
package/registry.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ /** The compiled OFP device tables (registry.bundle.json) as text: pass it as Ofp({ bundle }). */
2
+ declare const bundle: string
3
+ export default bundle