{"id":16218669,"url":"https://github.com/loginov-rocks/bluetooth-terminal","last_synced_at":"2025-08-06T11:14:28.443Z","repository":{"id":43174714,"uuid":"105142077","full_name":"loginov-rocks/bluetooth-terminal","owner":"loginov-rocks","description":"ES6 class for serial communication with your own Bluetooth Low Energy (Smart) devices","archived":false,"fork":false,"pushed_at":"2025-04-05T04:09:23.000Z","size":574,"stargazers_count":44,"open_issues_count":2,"forks_count":13,"subscribers_count":6,"default_branch":"main","last_synced_at":"2025-04-05T05:22:40.689Z","etag":null,"topics":["ble","bluetooth","bluetooth-low-energy","bluetooth-smart","communication","iot","physical-web","serial","terminal"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/bluetooth-terminal","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/loginov-rocks.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-09-28T11:50:33.000Z","updated_at":"2025-03-27T04:06:11.000Z","dependencies_parsed_at":"2025-04-05T05:20:33.853Z","dependency_job_id":"1ca6fcc0-788f-44a0-95b4-7babe60c3f2f","html_url":"https://github.com/loginov-rocks/bluetooth-terminal","commit_stats":null,"previous_names":[],"tags_count":18,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loginov-rocks%2Fbluetooth-terminal","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loginov-rocks%2Fbluetooth-terminal/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loginov-rocks%2Fbluetooth-terminal/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loginov-rocks%2Fbluetooth-terminal/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/loginov-rocks","download_url":"https://codeload.github.com/loginov-rocks/bluetooth-terminal/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248154999,"owners_count":21056542,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ble","bluetooth","bluetooth-low-energy","bluetooth-smart","communication","iot","physical-web","serial","terminal"],"created_at":"2024-10-10T11:50:15.578Z","updated_at":"2025-08-06T11:14:28.421Z","avatar_url":"https://github.com/loginov-rocks.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# bluetooth-terminal\n\n[![npm](https://img.shields.io/npm/v/bluetooth-terminal)](https://www.npmjs.com/package/bluetooth-terminal)\n[![CI](https://github.com/loginov-rocks/bluetooth-terminal/actions/workflows/ci.yml/badge.svg)](https://github.com/loginov-rocks/bluetooth-terminal/actions/workflows/ci.yml)\n[![CD](https://github.com/loginov-rocks/bluetooth-terminal/actions/workflows/cd.yml/badge.svg)](https://github.com/loginov-rocks/bluetooth-terminal/actions/workflows/cd.yml)\n[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=loginov-rocks_bluetooth-terminal\u0026metric=coverage)](https://sonarcloud.io/summary/new_code?id=loginov-rocks_bluetooth-terminal)\n\n**BluetoothTerminal** is a specialized JavaScript class that bridges a critical gap in web-based Bluetooth\ncommunication. It enables real **bidirectional serial communication** with *Bluetooth Low Energy (BLE)* devices\ndirectly from web browsers using the [Web Bluetooth API](https://webbluetoothcg.github.io/web-bluetooth/).\n\nCheck out the [Web Bluetooth Terminal](https://github.com/loginov-rocks/Web-Bluetooth-Terminal) repository for a\ncomplete implementation example, or read the full tutorial on\n[building web apps for your own BLE devices](https://loginov-rocks.medium.com/how-to-make-a-web-app-for-your-own-bluetooth-low-energy-device-arduino-2af8d16fdbe8).\n\n### Problem\n\nWeb browsers can only communicate with *Bluetooth Low Energy (4.0+)* devices through the **Web Bluetooth API**, which\nuses the *Generic Attribute Profile (GATT)* with services and characteristics. However, most affordable BLE modules\navailable to hobbyists and makers (such as *HM-10*, *JDY-08*, *AT-09*, *CC41-A*) only expose a single service\n(typically `0xFFE0`) and characteristic (typically `0xFFE1`) that emulates basic serial communication.\n\nThese limitations present several challenges:\n\n* No native *Serial Port Profile* support in **Web Bluetooth API**.\n* 20-byte size limit for individual BLE characteristic values.\n* Need for a consistent communication protocol between web apps and DIY hardware.\n\n### Solution\n\nThis class provides a complete solution by:\n\n* Creating a robust **serial communication layer** on top of the **Web Bluetooth API**.\n* Automatically handling device discovery, connection, and reconnection.\n* Bypassing the 20-byte characteristic limitation by automatically chunking longer messages.\n* Managing message buffering until complete messages are received (using configurable delimiters).\n* Providing a simple, Promise-based API for sending and receiving data.\n\nWith **BluetoothTerminal**, you can build web applications that seamlessly communicate with your custom *BLE* hardware\nby sending and receiving:\n\n* text messages,\n* JSON data from sensors,\n* commands and control signals,\n* any other data you need to exchange with your device.\n\nThis enables entirely new possibilities for creating web-controlled IoT devices, remote sensors, and other\nBluetooth-enabled projects without needing native mobile applications.\n\n## Quick Start\n\n### Install\n\n**BluetoothTerminal** can be added to your project in two ways:\n\n1. *Direct script usage:* download and include the\n[prebuilt JavaScript file](https://www.npmjs.com/package/bluetooth-terminal?activeTab=code)\n(`dist/BluetoothTerminal.js`) directly in your HTML:\n\n```html\n\u003cscript src=\"path/to/BluetoothTerminal.js\"\u003e\u003c/script\u003e\n```\n\n2. *NPM package:* for projects using module bundlers (Webpack, Rollup, Parcel, etc.), install via npm:\n\n```sh\nnpm install bluetooth-terminal\n```\n\nThen import in your code:\n\n```js\nconst BluetoothTerminal = require('bluetooth-terminal');\n```\n\n### Use\n\n```js\n// Create a BluetoothTerminal instance with the default configuration.\nconst bluetoothTerminal = new BluetoothTerminal();\n\n// Set a callback that will be called when an incoming message from the\n// connected device is received.\nbluetoothTerminal.onReceive((message) =\u003e {\n  console.info(`Message received: \"${message}\"`);\n});\n\n// Open the browser Bluetooth device picker to select a device if none was\n// previously selected, establish a connection with the selected device, and\n// initiate communication.\nbluetoothTerminal.connect()\n  .then(() =\u003e {\n    // Retrieve the name of the currently connected device.\n    console.info(`Device \"${this.getDeviceName()}\" successfully connected`);\n    \n    // Send a message to the connected device.\n    return bluetoothTerminal.send('Simon says: Hello, world!');\n  });\n\n// Later, disconnect from the currently connected device and clean up\n// associated resources.\n// bluetoothTerminal.disconnect();\n```\n\n## Contents\n\n\u003c!-- no toc --\u003e\n- [API](#api)\n  - [BluetoothTerminal](#bluetoothterminal)\n    - [new BluetoothTerminal([optionsOrServiceUuid], [characteristicUuid], [receiveSeparator], [sendSeparator], [onConnectCallback], [onDisconnectCallback])](#new-bluetoothterminaloptionsorserviceuuid-characteristicuuid-receiveseparator-sendseparator-onconnectcallback-ondisconnectcallback)\n      - [BluetoothTerminalOptions](#bluetoothterminaloptions)\n    - [setServiceUuid(uuid)](#setserviceuuiduuid)\n    - [setCharacteristicUuid(uuid)](#setcharacteristicuuiduuid)\n    - [setCharacteristicValueSize(size)](#setcharacteristicvaluesizesize)\n    - [setReceiveSeparator(separator)](#setreceiveseparatorseparator)\n    - [setSendSeparator(separator)](#setsendseparatorseparator)\n    - [onConnect([callback])](#onconnectcallback)\n    - [onDisconnect([callback])](#ondisconnectcallback)\n    - [onReceive([callback])](#onreceivecallback)\n    - [onLog([callback])](#onlogcallback)\n    - [setLogLevel(logLevel)](#setloglevelloglevel)\n    - [connect() ⇒ Promise](#connect--promise)\n    - [disconnect()](#disconnect)\n    - [send(message) ⇒ Promise](#sendmessage--promise)\n    - [getDeviceName() ⇒ string](#getdevicename--string)\n    - [Deprecated API](#deprecated-api)\n      - [setOnConnected([callback])](#setonconnectedcallback)\n      - [setOnDisconnected([callback])](#setondisconnectedcallback)\n      - [receive(message)](#receivemessage)\n- [Development](#development)\n  - [Runtime Dependencies](#runtime-dependencies)\n  - [Scripts and Development Dependencies](#scripts-and-development-dependencies)\n  - [Logging](#logging)\n    - [Log Levels](#log-levels)\n    - [Log Levels Implementation](#log-levels-implementation)\n\n## API\n\n### `BluetoothTerminal`\n\nBluetoothTerminal class.\n\n---\n\n#### `new BluetoothTerminal([optionsOrServiceUuid], [characteristicUuid], [receiveSeparator], [sendSeparator], [onConnectCallback], [onDisconnectCallback])`\n\nCreates a BluetoothTerminal instance with the provided configuration.\n\nSupports both options object (preferred) and individual parameters (deprecated and will be removed in v2.0.0).\n\n| Parameter                | Type                                               | Default  | Description                                                                                         |\n| ------------------------ | -------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------- |\n| `[optionsOrServiceUuid]` | `BluetoothTerminalOptions` \\| `number` \\| `string` | `0xFFE0` | Optional options object or service UUID as an integer (16-bit or 32-bit) or a string (128-bit UUID) |\n| `[characteristicUuid]`   | `number` \\| `string`                               | `0xFFE1` | Optional characteristic UUID as an integer (16-bit or 32-bit) or a string (128-bit UUID)            |\n| `[receiveSeparator]`     | `string`                                           | `'\\n'`   | Optional receive separator with length equal to one character                                       |\n| `[sendSeparator]`        | `string`                                           | `'\\n'`   | Optional send separator with length equal to one character                                          |\n| `[onConnectCallback]`    | `() =\u003e void`                                       | `null`   | Optional callback for successful connection                                                         |\n| `[onDisconnectCallback]` | `() =\u003e void`                                       | `null`   | Optional callback for disconnection                                                                 |\n\n##### `BluetoothTerminalOptions`\n\n| Property                    | Type                                                                           | Default  | Description                                                                              |\n| --------------------------- | ------------------------------------------------------------------------------ | -------- | ---------------------------------------------------------------------------------------- |\n| `[serviceUuid]`             | `number` \\| `string`                                                           | `0xFFE0` | Optional service UUID as an integer (16-bit or 32-bit) or a string (128-bit UUID)        |\n| `[characteristicUuid]`      | `number` \\| `string`                                                           | `0xFFE1` | Optional characteristic UUID as an integer (16-bit or 32-bit) or a string (128-bit UUID) |\n| `[characteristicValueSize]` | `number`                                                                       | `20`     | Optional maximum characteristic value size in bytes (positive integer)                   |\n| `[receiveSeparator]`        | `string`                                                                       | `'\\n'`   | Optional receive separator with length equal to one character                            |\n| `[sendSeparator]`           | `string`                                                                       | `'\\n'`   | Optional send separator with length equal to one character                               |\n| `[onConnectCallback]`       | `() =\u003e void`                                                                   | `null`   | Optional callback for successful connection                                              |\n| `[onDisconnectCallback]`    | `() =\u003e void`                                                                   | `null`   | Optional callback for disconnection                                                      |\n| `[onReceiveCallback]`       | `(message: string) =\u003e void`                                                    | `null`   | Optional callback for incoming message                                                   |\n| `[onLogCallback]`           | `(logLevel: string, method: string, message: string, error?: unknown) =\u003e void` | `null`   | Optional callback for log messages                                                       |\n| `[logLevel]`                | `string`                                                                       | `'log'`  | Optional log level as a string (\"none\", \"error\", \"warn\", \"info\", \"log\", or \"debug\")      |\n\n---\n\n#### `setServiceUuid(uuid)`\n\nSets integer or string representing service UUID used.\n\n| Parameter | Type                 | Description                                                              |\n| --------- | -------------------- | ------------------------------------------------------------------------ |\n| `uuid`    | `number` \\| `string` | Service UUID as an integer (16-bit or 32-bit) or a string (128-bit UUID) |\n\n---\n\n#### `setCharacteristicUuid(uuid)`\n\nSets integer or string representing characteristic UUID used.\n\n| Parameter | Type                 | Description                                                                     |\n| --------- | -------------------- | ------------------------------------------------------------------------------- |\n| `uuid`    | `number` \\| `string` | Characteristic UUID as an integer (16-bit or 32-bit) or a string (128-bit UUID) |\n\n---\n\n#### `setCharacteristicValueSize(size)`\n\nSets the maximum size (in bytes) for each characteristic write operation. Larger messages will be automatically split\ninto chunks of this size.\n\n| Parameter | Type     | Description                                                   |\n| --------- | -------- | ------------------------------------------------------------- |\n| size      | `number` | Maximum characteristic value size in bytes (positive integer) |\n\n---\n\n#### `setReceiveSeparator(separator)`\n\nSets character representing separator for messages received from the connected device, end of line for example.\n\n| Parameter   | Type     | Description                                          |\n| ----------- | -------- | ---------------------------------------------------- |\n| `separator` | `string` | Receive separator with length equal to one character |\n\n---\n\n#### `setSendSeparator(separator)`\n\nSets character representing separator for messages sent to the connected device, end of line for example.\n\n| Parameter   | Type     | Description                                       |\n| ----------- | -------- | ------------------------------------------------- |\n| `separator` | `string` | Send separator with length equal to one character |\n\n---\n\n#### `onConnect([callback])`\n\nSets a callback that will be called after the device is fully connected and communication has started.\n\n| Parameter    | Type                                  | Description                                                               |\n| ------------ | ------------------------------------- | ------------------------------------------------------------------------- |\n| `[callback]` | `() =\u003e void` \\| `null` \\| `undefined` | Callback for successful connection; omit or pass null/undefined to remove |\n\n---\n\n#### `onDisconnect([callback])`\n\nSets a callback that will be called after the device is disconnected.\n\n| Parameter    | Type                                  | Description                                                       |\n| ------------ | ------------------------------------- | ----------------------------------------------------------------- |\n| `[callback]` | `() =\u003e void` \\| `null` \\| `undefined` | Callback for disconnection; omit or pass null/undefined to remove |\n\n---\n\n#### `onReceive([callback])`\n\nSets a callback that will be called when an incoming message from the connected device is received.\n\n| Parameter    | Type                                                 | Description                                                          |\n| ------------ | ---------------------------------------------------- | -------------------------------------------------------------------- |\n| `[callback]` | `(message: string) =\u003e void` \\| `null` \\| `undefined` | Callback for incoming message; omit or pass null/undefined to remove |\n\n---\n\n#### `onLog([callback])`\n\nSets a callback that will be called every time any log message is produced by the class, regardless of the log level\nset.\n\n| Parameter    | Type                                                                                                    | Description                                                      |\n| ------------ | ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |\n| `[callback]` | `(logLevel: string, method: string, message: string, error?: unknown) =\u003e void` \\| `null` \\| `undefined` | Callback for log messages; omit or pass null/undefined to remove |\n\n---\n\n#### `setLogLevel(logLevel)`\n\nSets the log level that controls which messages are displayed in the console. The level hierarchy (from least to most\nverbose) is: \"none\", \"error\", \"warn\", \"info\", \"log\", \"debug\". Each level includes all less verbose levels.\n\n| Parameter  | Type     | Description                                                                |\n| ---------- | -------- | -------------------------------------------------------------------------- |\n| `logLevel` | `string` | Log level as a string (\"none\", \"error\", \"warn\", \"info\", \"log\", or \"debug\") |\n\n---\n\n#### `connect()` ⇒ `Promise`\n\nOpens the browser Bluetooth device picker to select a device if none was previously selected, establishes a connection\nwith the selected device, and initiates communication.\n\nIf configured, the `onConnect()` callback function will be executed after the connection is established.\n\n**Returns**: `Promise` - Promise that resolves when the device is fully connected and communication has started, or\nrejects if an error occurs.\n\n---\n\n#### `disconnect()`\n\nDisconnects from the currently connected device and cleans up associated resources.\n\nIf configured, the `onDisconnect()` callback function will be executed after the complete disconnection.\n\n---\n\n#### `send(message)` ⇒ `Promise`\n\nSends a message to the connected device, automatically adding the configured send separator and splitting the message\ninto appropriate chunks if it exceeds the maximum characteristic value size.\n\n| Parameter | Type     | Description                                    |\n| --------- | -------- | ---------------------------------------------- |\n| `message` | `string` | String message to send to the connected device |\n\n**Returns**: `Promise` - Promise that resolves when message successfully sent, or rejects if the device is disconnected\nor an error occurs.\n\n---\n\n#### `getDeviceName()` ⇒ `string`\n\nRetrieves the name of the currently connected device.\n\n**Returns**: `string` - Device name or an empty string if no device is connected or has no name.\n\n---\n\n#### Deprecated API\n\n##### `setOnConnected([callback])`\n\nSets a callback that will be called after the device is fully connected and communication has started.\n\n| Parameter    | Type                                  | Description                                                               |\n| ------------ | ------------------------------------- | ------------------------------------------------------------------------- |\n| `[callback]` | `() =\u003e void` \\| `null` \\| `undefined` | Callback for successful connection; omit or pass null/undefined to remove |\n\n---\n\n##### `setOnDisconnected([callback])`\n\nSets a callback that will be called after the device is disconnected.\n\n| Parameter    | Type                                  | Description                                                       |\n| ------------ | ------------------------------------- | ----------------------------------------------------------------- |\n| `[callback]` | `() =\u003e void` \\| `null` \\| `undefined` | Callback for disconnection; omit or pass null/undefined to remove |\n\n---\n\n##### `receive(message)`\n\nHandler for incoming messages received from the connected device. Override this method to process messages received\nfrom the connected device. Each time a complete message (ending with the receive separator) is processed, this method\nwill be called with the message string.\n\n| Parameter | Type     | Description                                                                |\n| --------- | -------- | -------------------------------------------------------------------------- |\n| `message` | `string` | String message received from the connected device, with separators removed |\n\n## Development\n\nRequires Node.js v22 (for development only).\n\n### Runtime Dependencies\n\nThe class is designed to have zero runtime dependencies as it should be easily used in browser applications.\n\n### Scripts and Development Dependencies\n\nLinting uses ESLint: `@eslint/js`, `eslint`, `eslint-config-google`, `eslint-plugin-jsdoc`, `typescript-eslint`\n\n- `npm run lint`\n\nTypeScript checking uses TypeScript: `typescript`.\n\n- `npm run typecheck`\n\nTesting uses Jest and Web Bluetooth Mock: `@types/jest`, `babel-jest`, `jest`, `jest-environment-jsdom`, \n`web-bluetooth-mock`\n\n- `npm test` - run tests,\n- `npm run test:coverage` - run tests with coverage,\n- `npm run coverage:clean` - clean coverage directory,\n- `npm run coverage` - clean coverage directory and run tests with coverage.\n\nBuilding uses Babel: `@babel/cli`, `@babel/core`, `@babel/preset-env`, `@babel/preset-typescript`\n\n- `npm run build:clean` - clean dist directory,\n- `npm run build:code` - build code,\n- `npm run build:types` - build TypeScript declaration,\n- `npm run build` - clean dist directory, build code and TypeScript declaration.\n\n### Logging\n\nThe logging system is implemented using simple private functions to avoid the complexity of additional classes or\ndecorators. This lightweight approach reduces bundle size and maintains code readability while still providing\ncomprehensive logging capabilities.\n\n#### Log Levels\n\nThe class supports six hierarchical log levels (from least to most verbose):\n\n* `none` - disables all logging output,\n* `error` - only critical error messages,\n* `warn` - error messages plus warnings about unexpected but non-breaking behavior,\n* `info` - connection and disconnection status information, plus all warnings and errors,\n* `log` - detailed connection process information, plus all info-level messages,\n* `debug` - complete, verbose output of all operations, including internal method calls.\n\n#### Log Levels Implementation\n\nThe following components log at specific levels throughout the class:\n\n* All errors - always logged at `error` level regardless of source,\n* Constructor, setter methods and callback function invocations - logged at `debug` level,\n* `connect()` - primary operation logged at `info` level,\n  * `_requestDevice()` - device selection logged at `debug` level,\n  * `_connectDevice()` - connection details logged at `log` level,\n    * `_startNotifications()` - GATT operations logged at `log` level,\n* `disconnect()` - primary operation logged at `info` level (unexpected conditions at `warn`),\n* `send()` - message sending logged at `debug` level,\n* `characteristicvaluechanged` event listener - message reception logged at `debug` level,\n* `gattserverdisconnected` event listener - reconnection logged at `log` level.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Floginov-rocks%2Fbluetooth-terminal","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Floginov-rocks%2Fbluetooth-terminal","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Floginov-rocks%2Fbluetooth-terminal/lists"}