Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

bluetooth-terminal

Package Overview
Dependencies
Maintainers
1
Versions
18
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

bluetooth-terminal - npm Package Compare versions

Comparing version 1.3.6 to 1.4.0

34

.eslintrc.json

@@ -10,3 +10,35 @@ {

"google"
]
],
"plugins": [
"jsdoc"
],
"rules": {
"jsdoc/check-alignment": "error",
"jsdoc/check-examples": "error",
"jsdoc/check-indentation": "error",
"jsdoc/check-param-names": "error",
"jsdoc/check-syntax": "error",
"jsdoc/check-tag-names": "error",
"jsdoc/check-types": "error",
"jsdoc/newline-after-description": "error",
"jsdoc/no-undefined-types": "error",
"jsdoc/require-description-complete-sentence": "error",
"jsdoc/require-hyphen-before-param-description": "error",
"jsdoc/require-param": "error",
"jsdoc/require-param-description": "error",
"jsdoc/require-param-name": "error",
"jsdoc/require-param-type": "error",
"jsdoc/require-returns": "error",
"jsdoc/require-returns-check": "error",
"jsdoc/require-returns-description": "error",
"jsdoc/require-returns-type": "error",
"jsdoc/valid-types": "error",
"max-len": [
"error",
{
"code": 120
}
],
"valid-jsdoc": "off"
}
}

17

package.json
{
"name": "bluetooth-terminal",
"version": "1.3.6",
"version": "1.4.0",
"description": "ES6 class for serial communication with Bluetooth Low Energy (Smart) devices",
"main": "./src/BluetoothTerminal.js",
"main": "src/BluetoothTerminal.js",
"scripts": {
"coverage": "istanbul cover ./node_modules/mocha/bin/_mocha",
"coveralls": "npm run coverage -- --report lcovonly -- -R spec && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage",
"ci": "npm run lint && npm run test:coverage",
"clean:coverage": "rm -rf coverage",
"coveralls": "npm run test:coverage -- --report lcovonly -- -R spec && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && npm run clean:coverage",
"lint": "eslint src test",
"test": "mocha"
"test": "mocha",
"test:coverage": "istanbul cover ./node_modules/mocha/bin/_mocha"
},

@@ -39,8 +41,9 @@ "repository": {

"eslint-config-google": "^0.12.0",
"eslint-plugin-jsdoc": "^4.8.3",
"istanbul": "^0.4.5",
"jsdom": "^14.0.0",
"mocha": "^6.0.2",
"sinon": "^7.3.1",
"mocha": "^6.1.4",
"sinon": "^7.3.2",
"web-bluetooth-mock": "^1.0.2"
}
}

@@ -61,3 +61,3 @@ # bluetooth-terminal

* [BluetoothTerminal](#bluetoothterminal)
* [new BluetoothTerminal([serviceUuid], [characteristicUuid], [receiveSeparator], [sendSeparator])](#new-bluetoothterminalserviceuuid-characteristicuuid-receiveseparator-sendseparator)
* [new BluetoothTerminal([serviceUuid], [characteristicUuid], [receiveSeparator], [sendSeparator], [onConnected], [onDisconnected])](#new-bluetoothterminalserviceuuid-characteristicuuid-receiveseparator-sendseparator-onconnected-ondisconnected)
* [setServiceUuid(uuid)](#setserviceuuiduuid)

@@ -67,2 +67,4 @@ * [setCharacteristicUuid(uuid)](#setcharacteristicuuiduuid)

* [setSendSeparator(separator)](#setsendseparatorseparator)
* [setOnConnected(listener)](#setonconnectedlistener)
* [setOnDisconnected(listener)](#setondisconnectedlistener)
* [connect() ⇒ Promise](#connect--promise)

@@ -76,12 +78,14 @@ * [disconnect()](#disconnect)

#### `new BluetoothTerminal([serviceUuid], [characteristicUuid], [receiveSeparator], [sendSeparator])`
#### `new BluetoothTerminal([serviceUuid], [characteristicUuid], [receiveSeparator], [sendSeparator], [onConnected], [onDisconnected])`
Create preconfigured Bluetooth Terminal instance.
| Parameter | Type | Default | Description |
| -------------------- | ------------------------ | -------- | ------------------- |
| [serviceUuid] | `number` | `string` | `0xFFE0` | Service UUID |
| [characteristicUuid] | `number` | `string` | `0xFFE1` | Characteristic UUID |
| [receiveSeparator] | `string` | `'\n'` | Receive separator |
| [sendSeparator] | `string` | `'\n'` | Send separator |
| Parameter | Type | Default | Description |
| -------------------- | ----------------------------- | ----------- | ------------------------------- |
| [serviceUuid] | `number` | `string` | `0xFFE0` | Service UUID |
| [characteristicUuid] | `number` | `string` | `0xFFE1` | Characteristic UUID |
| [receiveSeparator] | `string` | `'\n'` | Receive separator |
| [sendSeparator] | `string` | `'\n'` | Send separator |
| [onConnected] | `Function` | `undefined` | `undefined` | Listener for connected event |
| [onDisconnected] | `Function` | `undefined` | `undefined` | Listener for disconnected event |

@@ -138,2 +142,26 @@ ---

#### `setOnConnected(listener)`
Set a listener to be called after a device is connected.
**Kind**: instance method of `BluetoothTerminal`
| Parameter | Type | Description |
| --------- | ----------------------------- | ---------------------------- |
| listener | `Function` | `undefined` | Listener for connected event |
---
#### `setOnDisconnected(listener)`
Set a listener to be called after a device is disconnected.
**Kind**: instance method of `BluetoothTerminal`
| Parameter | Type | Description |
| --------- | ----------------------------- | ------------------------------- |
| listener | `Function` | `undefined` | Listener for disconnected event |
---
#### `connect()` ⇒ `Promise`

@@ -140,0 +168,0 @@

@@ -7,9 +7,12 @@ /**

* Create preconfigured Bluetooth Terminal instance.
* @param {!(number|string)} [serviceUuid=0xFFE0] - Service UUID
* @param {!(number|string)} [characteristicUuid=0xFFE1] - Characteristic UUID
* @param {string} [receiveSeparator='\n'] - Receive separator
* @param {string} [sendSeparator='\n'] - Send separator
*
* @param {!(number|string)} [serviceUuid=0xFFE0] - Service UUID.
* @param {!(number|string)} [characteristicUuid=0xFFE1] - Characteristic UUID.
* @param {string} [receiveSeparator='\n'] - Receive separator.
* @param {string} [sendSeparator='\n'] - Send separator.
* @param {Function|undefined} [onConnected=undefined] - Listener for connected event.
* @param {Function|undefined} [onDisconnected=undefined] - Listener for disconnected event.
*/
constructor(serviceUuid = 0xFFE0, characteristicUuid = 0xFFE1,
receiveSeparator = '\n', sendSeparator = '\n') {
constructor(serviceUuid = 0xFFE0, characteristicUuid = 0xFFE1, receiveSeparator = '\n', sendSeparator = '\n',
onConnected = undefined, onDisconnected = undefined) {
// Used private variables.

@@ -23,4 +26,3 @@ this._receiveBuffer = ''; // Buffer containing not separated data.

this._boundHandleDisconnection = this._handleDisconnection.bind(this);
this._boundHandleCharacteristicValueChanged =
this._handleCharacteristicValueChanged.bind(this);
this._boundHandleCharacteristicValueChanged = this._handleCharacteristicValueChanged.bind(this);

@@ -32,2 +34,4 @@ // Configure with specified parameters.

this.setSendSeparator(sendSeparator);
this.setOnConnected(onConnected);
this.setOnDisconnected(onDisconnected);
}

@@ -37,7 +41,7 @@

* Set number or string representing service UUID used.
* @param {!(number|string)} uuid - Service UUID
*
* @param {!(number|string)} uuid - Service UUID.
*/
setServiceUuid(uuid) {
if (!Number.isInteger(uuid) &&
!(typeof uuid === 'string' || uuid instanceof String)) {
if (!Number.isInteger(uuid) && !(typeof uuid === 'string' || uuid instanceof String)) {
throw new Error('UUID type is neither a number nor a string');

@@ -55,7 +59,7 @@ }

* Set number or string representing characteristic UUID used.
* @param {!(number|string)} uuid - Characteristic UUID
*
* @param {!(number|string)} uuid - Characteristic UUID.
*/
setCharacteristicUuid(uuid) {
if (!Number.isInteger(uuid) &&
!(typeof uuid === 'string' || uuid instanceof String)) {
if (!Number.isInteger(uuid) && !(typeof uuid === 'string' || uuid instanceof String)) {
throw new Error('UUID type is neither a number nor a string');

@@ -72,6 +76,5 @@ }

/**
* Set character representing separator for data coming from the connected
* device, end of line for example.
* @param {string} separator - Receive separator with length equal to one
* character
* Set character representing separator for data coming from the connected device, end of line for example.
*
* @param {string} separator - Receive separator with length equal to one character.
*/

@@ -91,5 +94,5 @@ setReceiveSeparator(separator) {

/**
* Set string representing separator for data coming to the connected
* device, end of line for example.
* @param {string} separator - Send separator
* Set string representing separator for data coming to the connected device, end of line for example.
*
* @param {string} separator - Send separator.
*/

@@ -109,8 +112,32 @@ setSendSeparator(separator) {

/**
* Set a listener to be called after a device is connected.
*
* @param {Function|undefined} listener - Listener for connected event.
*/
setOnConnected(listener) {
this._onConnected = listener;
}
/**
* Set a listener to be called after a device is disconnected.
*
* @param {Function|undefined} listener - Listener for disconnected event.
*/
setOnDisconnected(listener) {
this._onDisconnected = listener;
}
/**
* Launch Bluetooth device chooser and connect to the selected device.
* @return {Promise} Promise which will be fulfilled when notifications will
* be started or rejected if something went wrong
*
* @returns {Promise} Promise which will be fulfilled when notifications will be started or rejected if something went
* wrong.
*/
connect() {
return this._connectToDevice(this._device);
return this._connectToDevice(this._device).
then(() => {
if (this._onConnected) {
this._onConnected();
}
});
}

@@ -131,8 +158,13 @@

this._device = null;
if (this._onDisconnected) {
this._onDisconnected();
}
}
/**
* Data receiving handler which called whenever the new data comes from
* the connected device, override it to handle incoming data.
* @param {string} data - Data
* Data receiving handler which called whenever the new data comes from the connected device, override it to handle
* incoming data.
*
* @param {string} data - Data.
*/

@@ -145,5 +177,5 @@ receive(data) {

* Send data to the connected device.
* @param {string} data - Data
* @return {Promise} Promise which will be fulfilled when data will be sent or
* rejected if something went wrong
*
* @param {string} data - Data.
* @returns {Promise} Promise which will be fulfilled when data will be sent or rejected if something went wrong.
*/

@@ -162,4 +194,3 @@ send(data) {

// Split data to chunks by max characteristic value length.
const chunks = this.constructor._splitByLength(data,
this._maxCharacteristicValueLength);
const chunks = this.constructor._splitByLength(data, this._maxCharacteristicValueLength);

@@ -195,3 +226,4 @@ // Return rejected promise immediately if there is no connected device.

* Get the connected device name.
* @return {string} Device name or empty string if not connected
*
* @returns {string} Device name or empty string if not connected.
*/

@@ -208,4 +240,5 @@ getDeviceName() {

* Connect to device.
* @param {Object} device
* @return {Promise}
*
* @param {Object} device - Device.
* @returns {Promise} Promise.
* @private

@@ -225,3 +258,5 @@ */

* Disconnect from device.
* @param {Object} device
*
* @param {Object} device - Device.
* @returns {undefined} Undefined.
* @private

@@ -236,8 +271,6 @@ */

device.removeEventListener('gattserverdisconnected',
this._boundHandleDisconnection);
device.removeEventListener('gattserverdisconnected', this._boundHandleDisconnection);
if (!device.gatt.connected) {
this._log('"' + device.name +
'" bluetooth device is already disconnected');
this._log('"' + device.name + '" bluetooth device is already disconnected');
return;

@@ -253,3 +286,4 @@ }

* Request bluetooth device.
* @return {Promise}
*
* @returns {Promise} Promise.
* @private

@@ -267,4 +301,3 @@ */

this._device = device; // Remember device.
this._device.addEventListener('gattserverdisconnected',
this._boundHandleDisconnection);
this._device.addEventListener('gattserverdisconnected', this._boundHandleDisconnection);

@@ -277,4 +310,5 @@ return this._device;

* Connect device and cache characteristic.
* @param {Object} device
* @return {Promise}
*
* @param {Object} device - Device.
* @returns {Promise} Promise.
* @private

@@ -312,4 +346,5 @@ */

* Start notifications.
* @param {Object} characteristic
* @return {Promise}
*
* @param {Object} characteristic - Characteristic.
* @returns {Promise} Promise.
* @private

@@ -324,4 +359,3 @@ */

characteristic.addEventListener('characteristicvaluechanged',
this._boundHandleCharacteristicValueChanged);
characteristic.addEventListener('characteristicvaluechanged', this._boundHandleCharacteristicValueChanged);
});

@@ -332,4 +366,5 @@ }

* Stop notifications.
* @param {Object} characteristic
* @return {Promise}
*
* @param {Object} characteristic - Characteristic.
* @returns {Promise} Promise.
* @private

@@ -344,4 +379,3 @@ */

characteristic.removeEventListener('characteristicvaluechanged',
this._boundHandleCharacteristicValueChanged);
characteristic.removeEventListener('characteristicvaluechanged', this._boundHandleCharacteristicValueChanged);
});

@@ -352,3 +386,5 @@ }

* Handle disconnection.
* @param {Object} event
*
* @param {Object} event - Event.
* @returns {undefined} Undefined.
* @private

@@ -359,7 +395,15 @@ */

this._log('"' + device.name +
'" bluetooth device disconnected, trying to reconnect...');
this._log('"' + device.name + '" bluetooth device disconnected, trying to reconnect...');
if (this._onDisconnected) {
this._onDisconnected();
}
this._connectDeviceAndCacheCharacteristic(device).
then((characteristic) => this._startNotifications(characteristic)).
then(() => {
if (this._onConnected) {
this._onConnected();
}
}).
catch((error) => this._log(error));

@@ -370,3 +414,4 @@ }

* Handle characteristic value changed.
* @param {Object} event
*
* @param {Object} event - Event.
* @private

@@ -393,5 +438,6 @@ */

* Write to characteristic.
* @param {Object} characteristic
* @param {string} data
* @return {Promise}
*
* @param {Object} characteristic - Characteristic.
* @param {string} data - Data.
* @returns {Promise} Promise.
* @private

@@ -405,3 +451,4 @@ */

* Log.
* @param {Array} messages
*
* @param {Array} messages - Messages.
* @private

@@ -415,5 +462,6 @@ */

* Split by length.
* @param {string} string
* @param {number} length
* @return {Array}
*
* @param {string} string - String.
* @param {number} length - Length.
* @returns {Array} Array.
* @private

@@ -420,0 +468,0 @@ */

@@ -46,8 +46,7 @@ 'use strict';

it('should throw an error if value is neither a number nor a string',
() => {
assert.throws(() => {
bt.setServiceUuid(NaN);
});
});
it('should throw an error if value is neither a number nor a string', () => {
assert.throws(() => {
bt.setServiceUuid(NaN);
});
});

@@ -74,8 +73,7 @@ it('should throw an error if value is 0', () => {

it('should throw an error if value is neither a number nor a string',
() => {
assert.throws(() => {
bt.setCharacteristicUuid(NaN);
});
});
it('should throw an error if value is neither a number nor a string', () => {
assert.throws(() => {
bt.setCharacteristicUuid(NaN);
});
});

@@ -102,8 +100,7 @@ it('should throw an error if value is 0', () => {

it('should throw an error if value length is more than one character',
() => {
assert.throws(() => {
bt.setReceiveSeparator('\r\n');
});
});
it('should throw an error if value length is more than one character', () => {
assert.throws(() => {
bt.setReceiveSeparator('\r\n');
});
});
});

@@ -124,10 +121,25 @@

it('should throw an error if value length is more than one character',
() => {
assert.throws(() => {
bt.setSendSeparator('\r\n');
});
});
it('should throw an error if value length is more than one character', () => {
assert.throws(() => {
bt.setSendSeparator('\r\n');
});
});
});
describe('setOnConnected', () => {
it('should set function', () => {
const value = () => undefined;
bt.setOnConnected(value);
assert.strictEqual(bt._onConnected, value);
});
});
describe('setOnDisconnected', () => {
it('should set function', () => {
const value = () => undefined;
bt.setOnDisconnected(value);
assert.strictEqual(bt._onDisconnected, value);
});
});
describe('connect', () => {

@@ -158,2 +170,13 @@ it('should connect', () => {

});
it('should call onConnected listener after establishing connection', () => {
const device = new DeviceMock('Simon', [bt._serviceUuid]);
navigator.bluetooth = new WebBluetoothMock([device]);
const onConnectedSpy = sinon.spy();
bt.setOnConnected(onConnectedSpy);
return bt.connect().
then(() => assert(onConnectedSpy.calledOnce));
});
});

@@ -183,17 +206,25 @@

it('should not call `device.gatt.disconnect` if is already disconnected',
() => {
return connectPromise.
then(() => {
// Hard mock used here to cover the case.
bt._device.gatt.connected = false;
bt.disconnect();
return assert(disconnectSpy.notCalled);
});
});
it('should not call `device.gatt.disconnect` if is already disconnected', () => {
return connectPromise.
then(() => {
// Hard mock used here to cover the case.
bt._device.gatt.connected = false;
bt.disconnect();
return assert(disconnectSpy.notCalled);
});
});
it('should call onDisconnected listener if device was disconnected', () => {
return connectPromise.
then(() => {
const onDisconnectedSpy = sinon.spy();
bt.setOnDisconnected(onDisconnectedSpy);
bt.disconnect();
return assert(onDisconnectedSpy.calledOnce);
});
});
});
describe('receive', () => {
const characteristicValueChangedEvent = new window.
CustomEvent('characteristicvaluechanged');
const characteristicValueChangedEvent = new window.CustomEvent('characteristicvaluechanged');
let connectPromise;

@@ -210,16 +241,15 @@ let receiveSpy;

it('should not be called when a value provided does not have a separator',
() => {
const value = 'Hello, world!';
it('should not be called when a value provided does not have a separator', () => {
const value = 'Hello, world!';
return connectPromise.
then(() => {
const characteristic = bt._characteristic;
return connectPromise.
then(() => {
const characteristic = bt._characteristic;
characteristic.value = new TextEncoder().encode(value);
characteristic.dispatchEvent(characteristicValueChangedEvent);
characteristic.value = new TextEncoder().encode(value);
characteristic.dispatchEvent(characteristicValueChangedEvent);
return assert(receiveSpy.notCalled);
});
});
return assert(receiveSpy.notCalled);
});
});

@@ -240,6 +270,6 @@ it('should be called when a value provided have a separator', () => {

it('should be called twice when a value provided have three separators, ' +
'but there is no data data between the first and second', () => {
const value = 'Hello, world!' + bt._receiveSeparator +
bt._receiveSeparator + 'Ciao, mondo!' + bt._receiveSeparator;
it('should be called twice when a value provided have three separators, but there is no data data between the first'
+ ' and second', () => {
const value = 'Hello, world!' + bt._receiveSeparator + bt._receiveSeparator + 'Ciao, mondo!'
+ bt._receiveSeparator;

@@ -339,4 +369,3 @@ return connectPromise.

describe('_stopNotifications', () => {
const characteristicValueChangedEvent = new window.
CustomEvent('characteristicvaluechanged');
const characteristicValueChangedEvent = new window.CustomEvent('characteristicvaluechanged');
let connectPromise;

@@ -384,4 +413,3 @@ let receiveSpy;

let device;
const gattServerDisconnectedEvent = new window.
CustomEvent('gattserverdisconnected');
const gattServerDisconnectedEvent = new window.CustomEvent('gattserverdisconnected');

@@ -392,4 +420,3 @@ // Set up Web Bluetooth mock before each test.

navigator.bluetooth = new WebBluetoothMock([device]);
connectDeviceAndCacheCharacteristicSpy = sinon.spy(bt,
'_connectDeviceAndCacheCharacteristic');
connectDeviceAndCacheCharacteristicSpy = sinon.spy(bt, '_connectDeviceAndCacheCharacteristic');
connectPromise = bt.connect();

@@ -435,2 +462,30 @@ });

});
it('should call onDisconnected listener on disconnect', () => {
const onDisconnectedSpy = sinon.spy();
connectPromise.
then(() => {
bt.setOnDisconnected(onDisconnectedSpy);
device.dispatchEvent(gattServerDisconnectedEvent);
return assert(onDisconnectedSpy.calledOnce);
});
});
it('should call onConnected listener on reconnect', (done) => {
const onConnectedSpy = sinon.spy();
connectPromise.
then(() => {
bt.setOnConnected(onConnectedSpy);
device.dispatchEvent(gattServerDisconnectedEvent);
}).
then(() => {
// Make sure the assert will be executed after the promise.
setTimeout(() => {
assert(onConnectedSpy.calledOnce);
done();
}, 0);
});
});
});

@@ -437,0 +492,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc