@hangtime/grip-connect 0.5.8 → 0.5.10

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.
@@ -62,18 +62,55 @@ export interface IDevice extends IBase {
62
62
  * @readonly
63
63
  */
64
64
  commands: Commands;
65
+ /**
66
+ * Sets the callback function to be called when the activity status changes,
67
+ * and optionally sets the configuration for threshold and duration.
68
+ *
69
+ * This function allows you to specify a callback that will be invoked whenever
70
+ * the activity status changes, indicating whether the device is currently active.
71
+ * It also allows optionally configuring the threshold and duration used to determine activity.
72
+ *
73
+ * @param {ActiveCallback} callback - The callback function to be set. This function
74
+ * receives a boolean value indicating the new activity status.
75
+ * @param {object} [options] - Optional configuration object containing the threshold and duration.
76
+ * @param {number} [options.threshold=2.5] - The threshold value for determining activity.
77
+ * @param {number} [options.duration=1000] - The duration (in milliseconds) to monitor the input for activity.
78
+ * @returns {void}
79
+ * @public
80
+ *
81
+ * @example
82
+ * device.active((isActive) => {
83
+ * console.log(`Device is ${isActive ? 'active' : 'inactive'}`);
84
+ * }, { threshold: 3.0, duration: 1500 });
85
+ */
86
+ active(callback?: (data: boolean) => void, options?: {
87
+ threshold?: number;
88
+ duration?: number;
89
+ }): void;
65
90
  /**
66
91
  * Connects to a Bluetooth device.
67
92
  * @param {Function} [onSuccess] - Optional callback function to execute on successful connection. Default logs success.
68
93
  * @param {Function} [onError] - Optional callback function to execute on error. Default logs the error.
69
94
  * @public
95
+ *
96
+ * @example
97
+ * device.connect(
98
+ * () => console.log("Connected successfully"),
99
+ * (error) => console.error("Connection failed:", error)
100
+ * );
70
101
  */
71
102
  connect(onSuccess?: () => void, onError?: (error: Error) => void): Promise<void>;
72
103
  /**
73
104
  * Disconnects the device if it is currently connected.
74
- * - Checks if the device is connected via it's GATT server.
75
- * - If the device is connected, it attempts to gracefully disconnect.
105
+ * - Removes all notification listeners from the device's characteristics.
106
+ * - Removes the 'gattserverdisconnected' event listener.
107
+ * - Attempts to gracefully disconnect the device's GATT server.
108
+ * - Resets relevant properties to their initial states.
109
+ * @returns {void}
76
110
  * @public
111
+ *
112
+ * @example
113
+ * device.disconnect();
77
114
  */
78
115
  disconnect(): void;
79
116
  /**
@@ -85,12 +122,22 @@ export interface IDevice extends IBase {
85
122
  *
86
123
  * @returns {void} Initiates a download of the data in the specified format.
87
124
  * @private
125
+ *
126
+ * @example
127
+ * device.download('json');
88
128
  */
89
129
  download(format?: "csv" | "json" | "xml"): void;
90
130
  /**
91
131
  * Checks if a Bluetooth device is connected.
92
132
  * @returns {boolean} A boolean indicating whether the device is connected.
93
133
  * @public
134
+ *
135
+ * @example
136
+ * if (device.isConnected()) {
137
+ * console.log('Device is connected');
138
+ * } else {
139
+ * console.log('Device is not connected');
140
+ * }
94
141
  */
95
142
  isConnected(): boolean;
96
143
  /**
@@ -98,6 +145,11 @@ export interface IDevice extends IBase {
98
145
  * @param {NotifyCallback} callback - The callback function to be set.
99
146
  * @returns {void}
100
147
  * @public
148
+ *
149
+ * @example
150
+ * device.notify((data) => {
151
+ * console.log('Received notification:', data);
152
+ * });
101
153
  */
102
154
  notify(callback: (data: massObject) => void): void;
103
155
  /**
@@ -107,14 +159,27 @@ export interface IDevice extends IBase {
107
159
  * @param {number} [duration=0] - The duration to wait before resolving the promise, in milliseconds.
108
160
  * @returns {Promise<string | undefined>} A promise that resolves when the read operation is completed.
109
161
  * @public
162
+ *
163
+ * @example
164
+ * const value = await device.read('battery', 'level', 1000);
165
+ * console.log('Battery level:', value);
110
166
  */
111
167
  read(serviceId: string, characteristicId: string, duration?: number): Promise<string | undefined>;
112
168
  /**
113
169
  * Initiates the tare calibration process.
114
170
  * @param {number} duration - The duration time for tare calibration.
115
- * @returns {void}
171
+ * @returns {boolean} A boolean indicating whether the tare calibration was successful.
172
+ * @public
173
+ *
174
+ * @example
175
+ * const success = device.tare(5000);
176
+ * if (success) {
177
+ * console.log('Tare calibration started');
178
+ * } else {
179
+ * console.log('Tare calibration failed to start');
180
+ * }
116
181
  */
117
- tare(duration?: number): void;
182
+ tare(duration?: number): boolean;
118
183
  /**
119
184
  * Writes a message to the specified characteristic of a Bluetooth device and optionally provides a callback to handle responses.
120
185
  * @param {string} serviceId - The service UUID of the Bluetooth device containing the target characteristic.
@@ -3,7 +3,7 @@ export class BaseModel {
3
3
  createdAt;
4
4
  updatedAt;
5
5
  constructor(base) {
6
- this.id = base.id ? base.id : self.crypto.randomUUID();
6
+ this.id = base.id ?? globalThis.crypto?.randomUUID();
7
7
  this.createdAt = base.createdAt;
8
8
  this.updatedAt = base.updatedAt;
9
9
  }
@@ -22,9 +22,9 @@ export declare class Entralpi extends Device implements IEntralpi {
22
22
  * and updates mass data including maximum and average values.
23
23
  * It also handles command responses for retrieving device information.
24
24
  *
25
- * @param {Event} event - The notification event.
25
+ * @param {BluetoothRemoteGATTCharacteristic} characteristic - The notification event.
26
26
  */
27
- handleNotifications: (event: Event) => void;
27
+ handleNotifications: (characteristic: BluetoothRemoteGATTCharacteristic) => void;
28
28
  /**
29
29
  * Retrieves hardware version from the device.
30
30
  * @returns {Promise<string>} A Promise that resolves with the hardware version.
@@ -147,12 +147,13 @@ export class Entralpi extends Device {
147
147
  * and updates mass data including maximum and average values.
148
148
  * It also handles command responses for retrieving device information.
149
149
  *
150
- * @param {Event} event - The notification event.
150
+ * @param {BluetoothRemoteGATTCharacteristic} characteristic - The notification event.
151
151
  */
152
- handleNotifications = (event) => {
153
- const characteristic = event.target;
152
+ handleNotifications = (characteristic) => {
154
153
  const value = characteristic.value;
155
154
  if (value) {
155
+ // Update timestamp
156
+ this.updateTimestamp();
156
157
  if (value.buffer) {
157
158
  const receivedTime = Date.now();
158
159
  const receivedData = (value.getUint16(0) / 100).toFixed(1);
@@ -15,9 +15,9 @@ export declare class ForceBoard extends Device implements IForceBoard {
15
15
  * and updates mass data including maximum and average values.
16
16
  * It also handles command responses for retrieving device information.
17
17
  *
18
- * @param {Event} event - The notification event.
18
+ * @param {BluetoothRemoteGATTCharacteristic} characteristic - The notification event.
19
19
  */
20
- handleNotifications: (event: Event) => void;
20
+ handleNotifications: (characteristic: BluetoothRemoteGATTCharacteristic) => void;
21
21
  /**
22
22
  * Retrieves humidity level from the device.
23
23
  * @returns {Promise<string>} A Promise that resolves with the humidity level,
@@ -176,12 +176,13 @@ export class ForceBoard extends Device {
176
176
  * and updates mass data including maximum and average values.
177
177
  * It also handles command responses for retrieving device information.
178
178
  *
179
- * @param {Event} event - The notification event.
179
+ * @param {BluetoothRemoteGATTCharacteristic} characteristic - The notification event.
180
180
  */
181
- handleNotifications = (event) => {
182
- const characteristic = event.target;
181
+ handleNotifications = (characteristic) => {
183
182
  const value = characteristic.value;
184
183
  if (value) {
184
+ // Update timestamp
185
+ this.updateTimestamp();
185
186
  if (value.buffer) {
186
187
  const receivedTime = Date.now();
187
188
  const dataArray = new Uint8Array(value.buffer);
@@ -60,9 +60,9 @@ export declare class Motherboard extends Device implements IMotherboard {
60
60
  * to extract samples, calibrate masses, and update running averages of mass data.
61
61
  * If the received data is not a valid hex packet, it returns the unprocessed data.
62
62
  *
63
- * @param {Event} event - The notification event.
63
+ * @param {BluetoothRemoteGATTCharacteristic} characteristic - The notification event.
64
64
  */
65
- handleNotifications: (event: Event) => void;
65
+ handleNotifications: (characteristic: BluetoothRemoteGATTCharacteristic) => void;
66
66
  /**
67
67
  * Retrieves hardware version from the device.
68
68
  * @returns {Promise<string>} A Promise that resolves with the hardware version,
@@ -186,12 +186,13 @@ export class Motherboard extends Device {
186
186
  * to extract samples, calibrate masses, and update running averages of mass data.
187
187
  * If the received data is not a valid hex packet, it returns the unprocessed data.
188
188
  *
189
- * @param {Event} event - The notification event.
189
+ * @param {BluetoothRemoteGATTCharacteristic} characteristic - The notification event.
190
190
  */
191
- handleNotifications = (event) => {
192
- const characteristic = event.target;
191
+ handleNotifications = (characteristic) => {
193
192
  const value = characteristic.value;
194
193
  if (value) {
194
+ // Update timestamp
195
+ this.updateTimestamp();
195
196
  if (value.buffer) {
196
197
  for (let i = 0; i < value.byteLength; i++) {
197
198
  this.receiveBuffer.push(value.getUint8(i));
@@ -20,9 +20,9 @@ export declare class Progressor extends Device implements IProgressor {
20
20
  * and updates mass data including maximum and average values.
21
21
  * It also handles command responses for retrieving device information.
22
22
  *
23
- * @param {Event} event - The notification event.
23
+ * @param {BluetoothRemoteGATTCharacteristic} characteristic - The notification event.
24
24
  */
25
- handleNotifications: (event: Event) => void;
25
+ handleNotifications: (characteristic: BluetoothRemoteGATTCharacteristic) => void;
26
26
  /**
27
27
  * Stops the data stream on the specified device.
28
28
  * @returns {Promise<void>} A promise that resolves when the stream is stopped.
@@ -111,12 +111,13 @@ export class Progressor extends Device {
111
111
  * and updates mass data including maximum and average values.
112
112
  * It also handles command responses for retrieving device information.
113
113
  *
114
- * @param {Event} event - The notification event.
114
+ * @param {BluetoothRemoteGATTCharacteristic} characteristic - The notification event.
115
115
  */
116
- handleNotifications = (event) => {
117
- const characteristic = event.target;
116
+ handleNotifications = (characteristic) => {
118
117
  const value = characteristic.value;
119
118
  if (value) {
119
+ // Update timestamp
120
+ this.updateTimestamp();
120
121
  if (value.buffer) {
121
122
  const receivedTime = Date.now();
122
123
  // Read the first byte of the buffer to determine the kind of message
@@ -72,6 +72,8 @@ export class WHC06 extends Device {
72
72
  if (!this.bluetooth.gatt) {
73
73
  throw new Error("GATT is not available on this device");
74
74
  }
75
+ // Update timestamp
76
+ this.updateTimestamp();
75
77
  // Device has no services / characteristics, so we directly call onSuccess
76
78
  onSuccess();
77
79
  this.bluetooth.addEventListener("advertisementreceived", (event) => {
@@ -138,6 +138,22 @@ export declare abstract class Device extends BaseModel implements IDevice {
138
138
  * @protected
139
139
  */
140
140
  protected activeCallback: ActiveCallback;
141
+ /**
142
+ * Event listener for handling the 'gattserverdisconnected' event.
143
+ * This listener delegates the event to the `onDisconnected` method.
144
+ *
145
+ * @private
146
+ * @type {(event: Event) => void}
147
+ */
148
+ private onDisconnectedListener;
149
+ /**
150
+ * A map that stores notification event listeners keyed by characteristic UUIDs.
151
+ * This allows for proper addition and removal of event listeners associated with each characteristic.
152
+ *
153
+ * @private
154
+ * @type {Map<string, EventListener>}
155
+ */
156
+ private notificationListeners;
141
157
  constructor(device: Partial<IDevice>);
142
158
  /**
143
159
  * Sets the callback function to be called when the activity status changes,
@@ -154,6 +170,11 @@ export declare abstract class Device extends BaseModel implements IDevice {
154
170
  * @param {number} [options.duration=1000] - The duration (in milliseconds) to monitor the input for activity.
155
171
  * @returns {void}
156
172
  * @public
173
+ *
174
+ * @example
175
+ * device.active((isActive) => {
176
+ * console.log(`Device is ${isActive ? 'active' : 'inactive'}`);
177
+ * }, { threshold: 3.0, duration: 1500 });
157
178
  */
158
179
  active: (callback: ActiveCallback, options?: {
159
180
  threshold?: number;
@@ -168,6 +189,9 @@ export declare abstract class Device extends BaseModel implements IDevice {
168
189
  *
169
190
  * @param {number} input - The dynamic value to check for activity status.
170
191
  * @returns {Promise<void>} A promise that resolves once the activity check is complete.
192
+ *
193
+ * @example
194
+ * await device.activityCheck(5.0);
171
195
  */
172
196
  protected activityCheck: (input: number) => Promise<void>;
173
197
  /**
@@ -175,31 +199,55 @@ export declare abstract class Device extends BaseModel implements IDevice {
175
199
  * @param {Function} [onSuccess] - Optional callback function to execute on successful connection. Default logs success.
176
200
  * @param {Function} [onError] - Optional callback function to execute on error. Default logs the error.
177
201
  * @public
202
+ *
203
+ * @example
204
+ * device.connect(
205
+ * () => console.log("Connected successfully"),
206
+ * (error) => console.error("Connection failed:", error)
207
+ * );
178
208
  */
179
209
  connect: (onSuccess?: () => void, onError?: (error: Error) => void) => Promise<void>;
180
210
  /**
181
211
  * Disconnects the device if it is currently connected.
182
- * - Checks if the device is connected via it's GATT server.
183
- * - If the device is connected, it attempts to gracefully disconnect.
212
+ * - Removes all notification listeners from the device's characteristics.
213
+ * - Removes the 'gattserverdisconnected' event listener.
214
+ * - Attempts to gracefully disconnect the device's GATT server.
215
+ * - Resets relevant properties to their initial states.
216
+ * @returns {void}
184
217
  * @public
218
+ *
219
+ * @example
220
+ * device.disconnect();
185
221
  */
186
222
  disconnect: () => void;
187
223
  /**
188
224
  * Converts the `downloadPackets` array into a CSV formatted string.
189
225
  * @returns {string} A CSV string representation of the `downloadPackets` data, with each packet on a new line.
190
226
  * @private
227
+ *
228
+ * @example
229
+ * const csvData = device.downloadToCSV();
230
+ * console.log(csvData);
191
231
  */
192
232
  private downloadToCSV;
193
233
  /**
194
234
  * Converts an array of DownloadPacket objects to a JSON string.
195
235
  * @returns {string} JSON string representation of the data.
196
236
  * @private
237
+ *
238
+ * @example
239
+ * const jsonData = device.downloadToJSON();
240
+ * console.log(jsonData);
197
241
  */
198
242
  private downloadToJSON;
199
243
  /**
200
244
  * Converts an array of DownloadPacket objects to an XML string.
201
245
  * @returns {string} XML string representation of the data.
202
246
  * @private
247
+ *
248
+ * @example
249
+ * const xmlData = device.downloadToXML();
250
+ * console.log(xmlData);
203
251
  */
204
252
  private downloadToXML;
205
253
  /**
@@ -211,12 +259,19 @@ export declare abstract class Device extends BaseModel implements IDevice {
211
259
  *
212
260
  * @returns {void} Initiates a download of the data in the specified format.
213
261
  * @private
262
+ *
263
+ * @example
264
+ * device.download('json');
214
265
  */
215
266
  download: (format?: "csv" | "json" | "xml") => void;
216
267
  /**
217
268
  * Returns UUIDs of all services associated with the device.
218
269
  * @returns {string[]} Array of service UUIDs.
219
270
  * @protected
271
+ *
272
+ * @example
273
+ * const serviceUUIDs = device.getAllServiceUUIDs();
274
+ * console.log(serviceUUIDs);
220
275
  */
221
276
  protected getAllServiceUUIDs: () => string[];
222
277
  /**
@@ -225,18 +280,33 @@ export declare abstract class Device extends BaseModel implements IDevice {
225
280
  * @param {string} characteristicId - The UUID of the characteristic.
226
281
  * @returns {BluetoothRemoteGATTCharacteristic | undefined} The characteristic, if found.
227
282
  * @protected
283
+ *
284
+ * @example
285
+ * const characteristic = device.getCharacteristic('battery', 'level');
286
+ * if (characteristic) {
287
+ * console.log('Characteristic found');
288
+ * }
228
289
  */
229
290
  protected getCharacteristic: (serviceId: string, characteristicId: string) => BluetoothRemoteGATTCharacteristic | undefined;
230
291
  /**
231
292
  * Handles notifications received from a characteristic.
232
- * @param {Event} event - The notification event.
233
- * @protected
293
+ * @param {BluetoothRemoteGATTCharacteristic} characteristic - The notification event.
294
+ *
295
+ * @example
296
+ * device.handleNotifications(someCharacteristic);
234
297
  */
235
- protected handleNotifications: (event: Event) => void;
298
+ protected handleNotifications: (characteristic: BluetoothRemoteGATTCharacteristic) => void;
236
299
  /**
237
300
  * Checks if a Bluetooth device is connected.
238
301
  * @returns {boolean} A boolean indicating whether the device is connected.
239
302
  * @public
303
+ *
304
+ * @example
305
+ * if (device.isConnected()) {
306
+ * console.log('Device is connected');
307
+ * } else {
308
+ * console.log('Device is not connected');
309
+ * }
240
310
  */
241
311
  isConnected: () => boolean;
242
312
  /**
@@ -244,18 +314,31 @@ export declare abstract class Device extends BaseModel implements IDevice {
244
314
  * @param {NotifyCallback} callback - The callback function to be set.
245
315
  * @returns {void}
246
316
  * @public
317
+ *
318
+ * @example
319
+ * device.notify((data) => {
320
+ * console.log('Received notification:', data);
321
+ * });
247
322
  */
248
323
  notify: (callback: NotifyCallback) => void;
249
324
  /**
250
325
  * Handles the 'connected' event.
251
326
  * @param {Function} onSuccess - Callback function to execute on successful connection.
252
327
  * @public
328
+ *
329
+ * @example
330
+ * device.onConnected(() => {
331
+ * console.log('Device connected successfully');
332
+ * });
253
333
  */
254
334
  protected onConnected: (onSuccess: () => void) => Promise<void>;
255
335
  /**
256
336
  * Handles the 'disconnected' event.
257
337
  * @param {Event} event - The 'disconnected' event.
258
338
  * @public
339
+ *
340
+ * @example
341
+ * device.onDisconnected(event);
259
342
  */
260
343
  protected onDisconnected: (event: Event) => void;
261
344
  /**
@@ -265,22 +348,48 @@ export declare abstract class Device extends BaseModel implements IDevice {
265
348
  * @param {number} [duration=0] - The duration to wait before resolving the promise, in milliseconds.
266
349
  * @returns {Promise<string | undefined>} A promise that resolves when the read operation is completed.
267
350
  * @public
351
+ *
352
+ * @example
353
+ * const value = await device.read('battery', 'level', 1000);
354
+ * console.log('Battery level:', value);
268
355
  */
269
356
  read: (serviceId: string, characteristicId: string, duration?: number) => Promise<string | undefined>;
270
357
  /**
271
358
  * Initiates the tare calibration process.
272
359
  * @param {number} duration - The duration time for tare calibration.
273
- * @returns {void}
360
+ * @returns {boolean} A boolean indicating whether the tare calibration was successful.
274
361
  * @public
362
+ *
363
+ * @example
364
+ * const success = device.tare(5000);
365
+ * if (success) {
366
+ * console.log('Tare calibration started');
367
+ * } else {
368
+ * console.log('Tare calibration failed to start');
369
+ * }
275
370
  */
276
- tare(duration?: number): void;
371
+ tare(duration?: number): boolean;
277
372
  /**
278
373
  * Apply tare calibration to the provided sample.
279
374
  * @param {number} sample - The sample to calibrate.
280
375
  * @returns {number} The calibrated tare value.
281
376
  * @protected
377
+ *
378
+ * @example
379
+ * const calibratedSample = device.applyTare(rawSample);
380
+ * console.log('Calibrated sample:', calibratedSample);
282
381
  */
283
382
  protected applyTare(sample: number): number;
383
+ /**
384
+ * Updates the timestamp of the last device interaction.
385
+ * This method sets the updatedAt property to the current date and time.
386
+ * @protected
387
+ *
388
+ * @example
389
+ * device.updateTimestamp();
390
+ * console.log('Last updated:', device.updatedAt);
391
+ */
392
+ protected updateTimestamp: () => void;
284
393
  /**
285
394
  * Writes a message to the specified characteristic of a Bluetooth device and optionally provides a callback to handle responses.
286
395
  * @param {string} serviceId - The service UUID of the Bluetooth device containing the target characteristic.