### Quick Start: Connect to Boks Device using TypeScript
Source: https://github.com/thib3113/boks-sdk-js/blob/main/wiki/guide/index.md
A quick start example demonstrating how to import and use the BoksController to connect to a Boks device. Requires a 'device' object to be defined elsewhere.
```typescript
import { BoksController } from '@thib3113/boks-sdk';
const controller = new BoksController({ device });
await controller.connect();
```
--------------------------------
### Install Boks SDK JS using npm
Source: https://github.com/thib3113/boks-sdk-js/blob/main/wiki/guide/index.md
Installs the Boks SDK JS package from npm. This is the first step to using the library in your project.
```bash
npm install @thib3113/boks-sdk
```
--------------------------------
### Hardware Simulator Setup
Source: https://github.com/thib3113/boks-sdk-js/blob/main/README.md
Shows how to import and set up the `BoksHardwareSimulator` and `SimulatorTransport` for integration testing without a physical device. It includes configuring the simulator's state.
```typescript
import { BoksHardwareSimulator, SimulatorTransport } from '@thib3113/boks-sdk/simulator';
import { BoksController, BoksCodeType, BoksOpenSource } from '@thib3113/boks-sdk';
// 1. Create the simulator
const simulator = new BoksHardwareSimulator();
// 2. Configure the simulator state
simulator.addPinCode('123456', BoksCodeType.Single); // Add a valid PIN
simulator.setBatteryLevel(85);
// 3. Create a transport linked to the simulator
const transport = new SimulatorTransport(simulator);
// 4. Use the controller as usual
const controller = new BoksController({ transport });
await controller.connect(); // Connects to the simulator immediately
await controller.openDoor('123456'); // Validates against simulator state
```
--------------------------------
### Install Boks SDK using pnpm or npm
Source: https://context7.com/thib3113/boks-sdk-js/llms.txt
Installs the Boks SDK package using either pnpm or npm package managers. This is the first step to integrating the SDK into your project.
```bash
pnpm add @thib3113/boks-sdk
# or
npm install @thib3113/boks-sdk
```
--------------------------------
### Connect to Boks Device via Bluetooth and Log Status (JavaScript)
Source: https://github.com/thib3113/boks-sdk-js/blob/main/examples/initialization-demo.html
This snippet demonstrates connecting to a Boks Bluetooth device using the Boks SDK. It requests a device, establishes a connection, and logs the connection status. It also retrieves and displays hardware and firmware versions if available. Dependencies include the Boks SDK and the Web Bluetooth API.
```javascript
const { BoksController, BoksClient, bytesToHex } = BoksSDK;
const connectBtn = document.getElementById('connectBtn');
const connectionStatus = document.getElementById('connectionStatus');
const deviceInfo = document.getElementById('deviceInfo');
const fwVersion = document.getElementById('fwVersion');
const hwVersion = document.getElementById('hwVersion');
let controller = null;
connectBtn.addEventListener('click', async () => {
try {
log('Requesting Bluetooth device...');
const device = await navigator.bluetooth.requestDevice({
filters: [{ namePrefix: 'Boks' }],
optionalServices: [
'a7630001-f491-4f21-95ea-846ba586e361', // Boks Service
'0000180a-0000-1000-8000-00805f9b34fb' // Device Info
]
});
log(`Device selected: ${device.name}`);
controller = new BoksController({ device });
log('Connecting...');
await controller.connect();
log('Connected successfully!', 'success');
connectionStatus.textContent = `Connected to ${device.name}`;
connectBtn.disabled = true;
if (controller.hardwareInfo) {
fwVersion.textContent = controller.hardwareInfo.firmwareRevision;
hwVersion.textContent = controller.hardwareInfo.hardwareVersion;
deviceInfo.classList.remove('hidden');
}
initCard.classList.remove('hidden');
} catch (err) {
log(`Connection failed: ${err.message}`, 'error');
console.error(err);
}
});
```
--------------------------------
### Secure DFU Firmware Update with Boks SDK (JavaScript)
Source: https://github.com/thib3113/boks-sdk-js/blob/main/examples/dfu_update.html
This snippet shows how to update device firmware using the SecureDfu class from the Boks SDK. It loads firmware from a file, initializes the DFU process, listens for progress and log events, and handles completion or errors. Ensure the SecureDfu library is correctly loaded and a device is selected before execution.
```javascript
if (typeof SecureDfu === 'undefined') { log('SecureDfu library not loaded properly.', 'error'); return; }
const content = await file.arrayBuffer();
const dfu = new SecureDfu(content, selectedDevice);
dfu.addEventListener('progress', (event) => {
const { current, total } = event;
const percent = Math.round((current / total) * 100);
progressBar.value = percent;
progressText.textContent = `${percent}%`;
log(`Progress: ${percent}%`);
});
dfu.addEventListener('log', (event) => {
// log(`DFU: ${event.message}`);
});
await dfu.update();
log('Firmware Update Complete!', 'success');
```
--------------------------------
### Initialize and Log Device Information with Boks SDK (JavaScript)
Source: https://github.com/thib3113/boks-sdk-js/blob/main/examples/dfu_update.html
This snippet initializes the Boks SDK client, connects to a selected Bluetooth device, and attempts to read the battery level. It includes error handling and logging for connection and battery reading operations. Dependencies include the Boks SDK and the Web Bluetooth API.
```javascript
const { BOKS_SERVICE_UUID, DFU_SERVICE_UUID, BOKS_UUIDS } = BoksSDK;
let selectedDevice = null;
let boksClient = null;
async function handleConnection() {
if (!selectedDevice) return;
const isDfu = selectedDevice.name && selectedDevice.name.includes('DfuTarg');
if (isDfu) {
log('Device is in DFU Bootloader mode.');
deviceStatusEl.textContent = "DFU Mode";
normalModeControls.classList.add('hidden');
dfuModeControls.classList.remove('hidden');
} else {
log('Device is in Normal mode. Connecting Boks Client...');
deviceStatusEl.textContent = "Normal Mode";
normalModeControls.classList.remove('hidden');
dfuModeControls.classList.add('hidden');
try {
boksClient = new BoksSDK.BoksClient({
device: selectedDevice,
logger: (level, event, context) => {
if (level === 'error') log(`${event}: ${JSON.stringify(context)}`, 'error');
}
});
await boksClient.connect();
log('Boks Client Connected!', 'success');
// Read Battery
try {
const battery = await boksClient.getBatteryLevel();
batteryLevelEl.textContent = battery !== undefined ? battery : '?';
} catch (e) {
log('Could not read battery: ' + e.message, 'warn');
}
} catch (err) {
log('Connection failed: ' + err.message, 'error');
}
}
}
```
--------------------------------
### Flash Firmware to Boks Device using SecureDfu (JavaScript)
Source: https://github.com/thib3113/boks-sdk-js/blob/main/examples/dfu_update.html
This snippet outlines the process of flashing firmware to a Boks device using the SecureDfu library, likely integrated with the Web Bluetooth API. It assumes a firmware file has been selected and initiates the update process. The actual implementation would involve calling methods from the SecureDfu object, which is expected to be globally available or imported.
```javascript
flashBtn.addEventListener('click', async () => {
if (!selectedDevice || !firmwareFile.files.length) {
log('Select device and firmware first.', 'error');
return;
}
const file = firmwareFile.files[0];
log(`Starting update with ${file.name}...`);
try {
// Using SecureDfu from web-bluetooth-dfu
// Note: The library exposes 'SecureDfu' usually.
// Depending on the bundle, it might be window.SecureDfu or similar.
// Let's assume standard usage from the provided unpkg.
if (typeof SecureDfu ==
```
--------------------------------
### Configure Device Settings and Reboot with Boks SDK
Source: https://context7.com/thib3113/boks-sdk-js/llms.txt
This example demonstrates how to set device credentials and configure specific settings, such as enabling La Poste mode. It also includes the functionality to reboot the device. Note that the connection will be lost after the device reboots.
```typescript
import { BoksController } from '@thib3113/boks-sdk';
const controller = new BoksController();
await controller.connect();
controller.setCredentials('YOUR_CONFIG_KEY_HEX');
// Set a configuration parameter (e.g., enable La Poste mode)
await controller.setConfiguration({ type: 0x01, value: true });
// Reboot the device
await controller.reboot();
// Note: Connection will be lost after reboot
```
--------------------------------
### Generate New Seed and Initialize Boks Device (JavaScript)
Source: https://github.com/thib3113/boks-sdk-js/blob/main/examples/initialization-demo.html
This snippet demonstrates generating a secure 32-byte random seed using the Web Crypto API and then initializing the Boks device with this seed. It includes a critical warning to the user before proceeding with initialization, as it can potentially brick the device or break app compatibility. The initialization progress is displayed to the user. Dependencies include the Boks SDK and the Web Crypto API.
```javascript
const generateKeyBtn = document.getElementById('generateKeyBtn');
const newSeedInput = document.getElementById('newSeed');
const initBtn = document.getElementById('initBtn');
const progressContainer = document.getElementById('progressContainer');
const progressBar = document.getElementById('progressBar');
const progressText = document.getElementById('progressText');
generateKeyBtn.addEventListener('click', () => {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
const hex = Array.from(array)
.map(b => b.toString(16).padStart(2, '0'))
.join('')
.toUpperCase();
newSeedInput.value = hex;
initBtn.disabled = false;
log('New random 32-byte seed generated.', 'success');
});
initBtn.addEventListener('click', async () => {
const seed = newSeedInput.value;
if (!seed) return;
if (!confirm('CRITICAL WARNING: This may brick your device or break app compatibility. Continue?')) return;
progressContainer.classList.remove('hidden');
progressBar.value = 0;
progressText.textContent = '0%';
log('Starting initialization...');
try {
if (!controller.initialize) {
throw new Error('Your BoksSDK build does not support initialize() yet. Please rebuild the SDK.');
}
const success = await controller.initialize(seed, (progress) => {
progressBar.value = progress;
progressText.textContent = `${progress}%`;
log(`Initialization: ${progress}%`);
});
if (success) {
log('Initialization complete! The device has been set up with the new Master Key.', 'success');
alert('Initialization Success! Please save your Master Key.');
} else {
log('Initialization failed (device reported error).', 'error');
}
} catch (err) {
log(`Initialization error: ${err.message}`, 'error');
}
});
```
--------------------------------
### Initialize and Connect Boks Controller (TypeScript)
Source: https://github.com/thib3113/boks-sdk-js/blob/main/README.md
Initializes the BoksController and establishes a connection to a nearby Boks device using WebBluetooth. This is the recommended starting point for interacting with the SDK.
```typescript
import { BoksController } from '@thib3113/boks-sdk';
// Initialize the controller (uses WebBluetooth by default in browsers)
const controller = new BoksController();
// Connect to a nearby Boks device
await controller.connect();
console.log('Connected to Boks!');
```
--------------------------------
### Open Boks Device with PIN using TypeScript
Source: https://github.com/thib3113/boks-sdk-js/blob/main/wiki/examples/open-door.md
This TypeScript code demonstrates how to open a Boks device using its PIN. It utilizes the BoksController from the '@thib3113/boks-sdk' library. The process involves creating a controller instance, connecting to the device, sending the PIN to open the door, and finally disconnecting. Error handling is included for connection and opening failures.
```typescript
import { BoksController } from '@thib3113/boks-sdk';
async function openDoorExample() {
// 1. Create the controller (defaults to WebBluetooth)
const controller = new BoksController();
try {
// 2. Connect to the device
console.log('Connecting...');
await controller.connect();
console.log('Connected!');
// 3. Open the door with a PIN
const pin = '123456';
console.log(`Opening door with PIN: ${pin}`);
const success = await controller.openDoor(pin);
if (success) {
console.log('Door opened successfully!');
} else {
console.error('Failed to open door. Invalid PIN?');
}
} catch (error) {
console.error('An error occurred:', error);
} finally {
// 4. Disconnect
await controller.disconnect();
}
}
```
--------------------------------
### Browser IIFE Usage with CDN (HTML/JavaScript)
Source: https://context7.com/thib3113/boks-sdk-js/llms.txt
Shows how to use the Boks SDK directly in web browsers without a bundler by including it via a CDN. Includes examples for connecting to hardware and opening doors, as well as core functionality for PIN generation.
```html
```
--------------------------------
### Install Boks SDK JS
Source: https://github.com/thib3113/boks-sdk-js/blob/main/README.md
Installs the Boks SDK using the pnpm package manager. This is the first step to integrating the SDK into your project.
```bash
pnpm add @thib3113/boks-sdk
```
--------------------------------
### Logging Function for Boks SDK Example
Source: https://github.com/thib3113/boks-sdk-js/blob/main/examples/provisioning-demo.html
A utility function to log messages to a dedicated HTML element (`#log`). It supports different log levels (info, error, success) by applying distinct text colors. The logs are timestamped and automatically scroll to the bottom. This function is essential for providing feedback to the user during device operations.
```javascript
const logEl = document.getElementById('log');
function log(msg, type = 'info') {
const div = document.createElement('div');
div.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`;
div.style.color = type === 'error' ? 'red' : type === 'success' ? 'green' : '#333';
logEl.appendChild(div);
logEl.scrollTop = logEl.scrollHeight;
}
```
--------------------------------
### Log Messages to the UI (JavaScript)
Source: https://github.com/thib3113/boks-sdk-js/blob/main/examples/initialization-demo.html
This utility function logs messages to a specified HTML element, providing timestamps and styling based on the message type (info, success, error). It ensures the log element is always visible by scrolling to the bottom. This function is crucial for providing user feedback during asynchronous operations like Bluetooth connections and device initialization.
```javascript
const logEl = document.getElementById('log');
function log(msg, type = 'info') {
const div = document.createElement('div');
div.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`;
div.style.color = type === 'error' ? 'red' : type === 'success' ? 'green' : '#333';
logEl.appendChild(div);
logEl.scrollTop = logEl.scrollHeight;
}
```
--------------------------------
### Scan for Boks Devices using Web Bluetooth API (JavaScript)
Source: https://github.com/thib3113/boks-sdk-js/blob/main/examples/dfu_update.html
This JavaScript snippet uses the Web Bluetooth API to request a Bluetooth device. It filters for devices advertising the BOKS_SERVICE_UUID or DFU_SERVICE_UUID and includes optional services like Battery and Device Information. It handles user interaction for device selection and logs the outcome.
```javascript
scanBtn.addEventListener('click', async () => {
try {
log('Scanning...');
selectedDevice = await navigator.bluetooth.requestDevice({
filters: [
{ services: [BOKS_SERVICE_UUID] },
{ services: [DFU_SERVICE_UUID] }
],
optionalServices: [
BOKS_SERVICE_UUID,
DFU_SERVICE_UUID,
0x180F, // Battery
0x180A // Device Info
]
});
log(`Device selected: ${selectedDevice.name}`);
deviceNameEl.textContent = selectedDevice.name;
deviceInfo.classList.remove('hidden');
handleConnection();
} catch (err) {
log('Scan failed: ' + err.message, 'error');
}
});
```
--------------------------------
### Get Hardware Information using BoksController (TypeScript)
Source: https://github.com/thib3113/boks-sdk-js/blob/main/wiki/examples/battery.md
Retrieves firmware revision, hardware version, and chipset information automatically upon device connection. Requires the BoksController from 'boks-sdk'. Outputs are logged to the console.
```typescript
import { BoksController } from 'boks-sdk';
const controller = new BoksController();
await controller.connect();
// Access cached hardware info
const info = controller.hardwareInfo;
if (info) {
console.log('HW Version:', info.hardwareVersion); // e.g., "4.0"
console.log('FW Revision:', info.firmwareRevision); // e.g., "10/125"
console.log('Chipset:', info.chipset); // e.g., "nRF52833"
}
```
--------------------------------
### Log Messages with Timestamp and Type (JavaScript)
Source: https://github.com/thib3113/boks-sdk-js/blob/main/examples/dfu_update.html
A utility function to log messages to both the console and a designated HTML element. It prepends each message with a timestamp and allows for different text colors based on the message type (info, success, error). This is useful for providing user feedback during asynchronous Bluetooth operations.
```javascript
function log(msg, type = 'info') {
const div = document.createElement('div');
div.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`;
div.style.color = type === 'error' ? 'red' : type === 'success' ? 'green' : 'black';
logEl.appendChild(div);
logEl.scrollTop = logEl.scrollHeight;
console.log(msg);
}
```
--------------------------------
### Switch Boks Device to DFU Mode (JavaScript)
Source: https://github.com/thib3113/boks-sdk-js/blob/main/examples/dfu_update.html
This code demonstrates how to switch a connected Boks device to DFU (Device Firmware Update) mode using the Web Bluetooth API. It connects directly to the device's GATT server, accesses the DFU Control Point characteristic, and writes a specific command (0x01) to initiate the mode switch. It includes logging and handles disconnection of the Boks client.
```javascript
switchToDfuBtn.addEventListener('click', async () => {
if (!boksClient) return;
log('Switching to DFU mode...');
try {
const server = await selectedDevice.gatt.connect();
const service = await server.getPrimaryService(DFU_SERVICE_UUID);
const char = await service.getCharacteristic(BOKS_UUIDS.DFU_CONTROL_POINT);
log('Writing 0x01 to DFU Control Point...');
await char.writeValue(new Uint8Array([0x01]));
log('Command sent. Device should reboot into DFU mode.', 'success');
await boksClient.disconnect();
log('Please wait for device to reboot, then Scan again if it doesn\'t auto-reconnect (usually address + 1).');
deviceStatusEl.textContent = "Switching...";
} catch (err) {
log('Failed to switch to DFU: ' + err.message, 'error');
}
});
```
--------------------------------
### Open Boks Door with PIN in TypeScript
Source: https://context7.com/thib3113/boks-sdk-js/llms.txt
Provides a TypeScript example for opening a Boks door using a PIN code. It includes error handling for invalid PINs and rate limiting, which enforces a 1-second delay between attempts to prevent brute-force attacks. The function returns a boolean indicating success or failure.
```typescript
import { BoksController } from '@thib3113/boks-sdk';
const controller = new BoksController();
await controller.connect();
try {
// Open door with a 6-character PIN code
const success = await controller.openDoor('123456');
if (success) {
console.log('Door opened successfully!');
} else {
console.log('Invalid PIN code.');
}
} catch (error) {
if (error.id === 'RATE_LIMIT_REACHED') {
console.log('Please wait 1 second between attempts.');
} else {
console.error('Error:', error.message);
}
}
await controller.disconnect();
```
--------------------------------
### Generate Boks PIN Codes with Core Algorithm
Source: https://context7.com/thib3113/boks-sdk-js/llms.txt
This example shows how to generate Boks PIN codes locally using the proprietary algorithm (modified BLAKE2s with SHA-256 IV). It utilizes `generateBoksPin` from the core SDK entry point and requires the Master Key. The PINs are 6 characters long and use characters from the Boks character set (0-9, A, B).
```typescript
import { generateBoksPin, hexToBytes, bytesToHex } from '@thib3113/boks-sdk/core';
// Master Key (32 bytes)
const masterKeyHex = '0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF';
const masterKey = hexToBytes(masterKeyHex);
// Generate different PIN types with sequence numbers
const singleUsePin = generateBoksPin(masterKey, 'single-use', 0); // First single-use PIN
const multiUsePin = generateBoksPin(masterKey, 'multi-use', 0); // First multi-use PIN
const masterPin = generateBoksPin(masterKey, 'master', 0); // First master PIN
console.log('Single-use PIN #0:', singleUsePin); // e.g., "3A8B21"
console.log('Multi-use PIN #0:', multiUsePin); // e.g., "7B4A09"
console.log('Master PIN #0:', masterPin); // e.g., "1B5920"
// Generate a sequence of single-use codes
for (let i = 0; i < 5; i++) {
const pin = generateBoksPin(masterKey, 'single-use', i);
console.log(`Single-use PIN #${i}: ${pin}`);
}
// PIN characters are from the Boks character set: 0-9, A, B
// Each PIN is 6 characters long
```
--------------------------------
### Fetch and Parse Boks Device History (TypeScript)
Source: https://github.com/thib3113/boks-sdk-js/blob/main/wiki/examples/history.md
Fetches the event history from a Boks device using the fetchHistory() method and iterates through the events to display their dates and descriptions. This example requires the BoksController and BoksOpcode from the '@thib3113/boks-sdk' package. It handles different event opcodes to provide meaningful descriptions.
```typescript
import { BoksController, BoksOpcode } from '@thib3113/boks-sdk';
// ... connect to device ...
try {
console.log('Fetching history...');
const history = await controller.fetchHistory();
console.log(`Retrieved ${history.length} events:`);
history.forEach(event => {
// Determine event type
let description = 'Unknown Event';
switch (event.opcode) {
case BoksOpcode.LOG_DOOR_OPEN:
description = 'Door Opened';
break;
case BoksOpcode.LOG_CODE_BLE_VALID:
description = 'Valid Code (App)';
break;
// ... handle other opcodes
}
console.log(`[${event.date.toLocaleString()}] ${description}`);
});
} catch (error) {
console.error('Failed to sync history:', error);
}
```
--------------------------------
### Integration Testing with Boks SDK JS Simulator
Source: https://github.com/thib3113/boks-sdk-js/blob/main/README.md
Run full integration tests for your application logic without needing physical hardware. The simulator reproduces protocol behavior, including asynchronous notifications and state changes. Requires setup of the simulator, transport, and controller.
```typescript
import { BoksController } from '@thib3113/boks-sdk';
import { BoksHardwareSimulator, SimulatorTransport } from '@thib3113/boks-sdk/simulator';
// 1. Setup Simulator
const simulator = new BoksHardwareSimulator();
const transport = new SimulatorTransport(simulator);
// 2. Setup Controller with Simulator Transport
const controller = new BoksController({ transport });
await controller.connect();
// 3. Run Test Scenario
// Initialize device (Provisioning)
const seed = new Uint8Array(32).fill(0xAA); // 32-byte seed
await controller.initialize(seed);
// Authenticate using the seed (Controller derives keys)
controller.setCredentials(seed);
// Create a code and use it
await controller.createSingleUseCode('123456');
const success = await controller.openDoor('123456');
console.log('Door opened:', success); // true
```
--------------------------------
### Experimental: Boks Scale Integration
Source: https://github.com/thib3113/boks-sdk-js/blob/main/README.md
Provides code examples for interacting with the Boks Scale accessory. It covers bonding with the scale and retrieving weight measurements.
```typescript
// Bond with the scale
await controller.bondScale();
// Get weight
const weight = await controller.getScaleWeight();
console.log(`Weight: ${weight}g`);
```
--------------------------------
### Connect to Boks Device using JavaScript
Source: https://github.com/thib3113/boks-sdk-js/blob/main/examples/provisioning-demo.html
Establishes a Bluetooth connection to a Boks device. It uses the Web Bluetooth API to request a device and then initializes the BoksController. The connection status and device information (firmware and hardware versions) are updated in the UI. Dependencies include the BoksSDK and browser's Web Bluetooth API.
```javascript
const { BoksController, BoksClient, bytesToHex } = BoksSDK;
const connectBtn = document.getElementById('connectBtn');
const connectionStatus = document.getElementById('connectionStatus');
const deviceInfo = document.getElementById('deviceInfo');
const fwVersion = document.getElementById('fwVersion');
const hwVersion = document.getElementById('hwVersion');
let controller = null;
connectBtn.addEventListener('click', async () => {
try {
const device = await navigator.bluetooth.requestDevice({
filters: [{ namePrefix: 'Boks' }],
optionalServices: [
'a7630001-f491-4f21-95ea-846ba586e361', // Boks Service
'0000180a-0000-1000-8000-00805f9b34fb' // Device Info
]
});
controller = new BoksController({ device });
await controller.connect();
connectionStatus.textContent = `Connected to ${device.name}`;
if (controller.hardwareInfo) {
fwVersion.textContent = controller.hardwareInfo.firmwareRevision;
hwVersion.textContent = controller.hardwareInfo.hardwareVersion;
deviceInfo.classList.remove('hidden');
}
} catch (err) {
console.error(err);
}
});
```
--------------------------------
### Provision New Master Key for Boks Device using JavaScript
Source: https://github.com/thib3113/boks-sdk-js/blob/main/examples/provisioning-demo.html
Initiates the process of provisioning a new master key to the Boks device. It prompts the user for confirmation before proceeding. The operation includes progress updates displayed via a progress bar and text. This function requires the `BoksController` to be connected and credentials to be set.
```javascript
const provisionBtn = document.getElementById('provisionBtn');
const newMasterKeyInput = document.getElementById('newMasterKey');
const progressContainer = document.getElementById('progressContainer');
const progressBar = document.getElementById('progressBar');
const progressText = document.getElementById('progressText');
provisionBtn.addEventListener('click', async () => {
const newKey = newMasterKeyInput.value;
if (!newKey) return;
if (!confirm('Are you sure you want to change the Master Key? This cannot be undone.')) return;
progressContainer.classList.remove('hidden');
progressBar.value = 0;
progressText.textContent = '0%';
try {
const success = await controller.regenerateMasterKey(newKey, (progress) => {
progressBar.value = progress;
progressText.textContent = `${progress}%`;
});
if (success) {
// Log success
alert('Provisioning Success! Please update your credentials.');
currentMasterKeyInput.value = newKey;
controller.setCredentials(newKey);
} else {
// Log failure
}
} catch (err) {
// Log error
} finally {
// Optionally hide progress container
}
});
```
--------------------------------
### Get Battery Levels using BoksController (TypeScript)
Source: https://github.com/thib3113/boks-sdk-js/blob/main/wiki/examples/battery.md
Fetches both the standard Bluetooth battery level (0-100%) and detailed custom Boks battery statistics, including temperature and historical measurements. Requires an active BoksController instance. Outputs are logged to the console.
```typescript
// Standard Bluetooth Battery Level
const level = await controller.getBatteryLevel();
console.log(`Battery: ${level}%`);
// Detailed Boks Battery Statistics
const stats = await controller.getBatteryStats();
if (stats) {
console.log(`Main Level: ${stats.level}%`);
console.log(`Temperature: ${stats.temperature}°C`);
// Advanced details (min, max, mean, etc.)
console.log('Details:', stats.details);
}
```
--------------------------------
### Initialize and Connect BoksController in TypeScript
Source: https://context7.com/thib3113/boks-sdk-js/llms.txt
Demonstrates initializing the BoksController and establishing a connection to a Boks device. It also shows how to retrieve hardware information and set administrative credentials. The controller provides reactive state properties for door status, code counts, and logs, and allows subscription to incoming packets.
```typescript
import { BoksController } from '@thib3113/boks-sdk';
// Initialize and connect to a Boks device
const controller = new BoksController();
await controller.connect();
// Get hardware info after connecting
console.log(controller.hardwareInfo);
// Output: { firmwareRevision: "10/125", softwareRevision: "4.6.0", hardwareVersion: "4.0", chipset: "nRF52833" }
// Set credentials for administrative operations
// Option A: Full Master Key (32 bytes hex) - derives Config Key automatically
controller.setCredentials('0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF');
// Option B: Config Key only (4 bytes hex) - for restricted admin tasks
controller.setCredentials('CDEF0123');
// Access reactive state properties
console.log(controller.doorOpen); // boolean: current door state
console.log(controller.codeCount); // { master: number, single: number }
console.log(controller.logCount); // number: total log entries
// Subscribe to all incoming packets
const unsubscribe = controller.onPacket((packet) => {
console.log(`Received packet opcode: 0x${packet.opcode.toString(16)}`);
});
// Clean up
await controller.disconnect();
unsubscribe();
```
--------------------------------
### Initialize or Regenerate Master Key with Boks SDK
Source: https://context7.com/thib3113/boks-sdk-js/llms.txt
This snippet covers advanced device provisioning operations: initializing a factory-fresh device or regenerating the Master Key on an existing device. It requires generating a seed, initializing the device (without authentication), and then setting new credentials. Regeneration requires current credentials and updates the master key.
```typescript
import { BoksController } from '@thib3113/boks-sdk';
const controller = new BoksController();
await controller.connect();
// Generate a 32-byte seed for the Master Key
const seed = new Uint8Array(32);
crypto.getRandomValues(seed);
const seedHex = Array.from(seed).map(b => b.toString(16).padStart(2, '0')).join('').toUpperCase();
// Initialize a factory-fresh device (no auth required)
const initSuccess = await controller.initialize(seedHex, (progress) => {
console.log(`Initialization progress: ${progress}%`);
});
console.log('Device initialized:', initSuccess);
// After initialization, set the new credentials
controller.setCredentials(seedHex);
// Regenerate Master Key on existing device (requires current credentials)
const newKey = '0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF';
const regenSuccess = await controller.regenerateMasterKey(newKey, (progress) => {
console.log(`Regeneration progress: ${progress}%`);
});
console.log('Master key regenerated:', regenSuccess);
// Update credentials with the new key
controller.setCredentials(newKey);
await controller.disconnect();
```
--------------------------------
### Custom Boks Transport Implementation for Node.js/Mobile
Source: https://context7.com/thib3113/boks-sdk-js/llms.txt
Provides an example of implementing a custom BoksTransport for environments lacking WebBluetooth. This involves creating a class that adheres to the BoksTransport interface, handling connection, disconnection, reading, writing, and subscription logic using a specific library like 'noble'. Requires '@thib3113/boks-sdk'.
```typescript
import { BoksController, BoksTransport } from '@thib3113/boks-sdk';
// Example: Custom transport interface implementation
class NobleTransport implements BoksTransport {
private peripheral: any;
private writeChar: any;
private notifyChar: any;
async connect(): Promise {
// Use noble to scan and connect
// this.peripheral = await scanForBoks();
// await this.peripheral.connectAsync();
// Discover services and characteristics...
}
async disconnect(): Promise {
await this.peripheral?.disconnectAsync();
}
async write(data: Uint8Array): Promise {
await this.writeChar.writeAsync(Buffer.from(data), false);
}
async read(uuid: string): Promise {
const buffer = await this.findCharacteristic(uuid).readAsync();
return new Uint8Array(buffer);
}
async subscribe(callback: (data: Uint8Array) => void): Promise {
this.notifyChar.on('data', (buffer: Buffer) => {
callback(new Uint8Array(buffer));
});
await this.notifyChar.subscribeAsync();
}
async subscribeTo(uuid: string, callback: (data: Uint8Array) => void): Promise {
const char = this.findCharacteristic(uuid);
char.on('data', (buffer: Buffer) => callback(new Uint8Array(buffer)));
await char.subscribeAsync();
}
private findCharacteristic(uuid: string): any {
// Implementation to find characteristic by UUID
}
}
// Use custom transport
const transport = new NobleTransport();
const controller = new BoksController({ transport });
await controller.connect();
```
--------------------------------
### Simulator with Persistence using Storage Adapters (TypeScript)
Source: https://context7.com/thib3113/boks-sdk-js/llms.txt
Demonstrates how to persist simulator state across sessions using custom storage adapters for browser localStorage and Node.js file systems. This allows for stateful testing and simulation.
```typescript
import { BoksHardwareSimulator, SimulatorStorage } from '@thib3113/boks-sdk/simulator';
// Browser localStorage adapter
const browserStorage: SimulatorStorage = {
get: (key) => localStorage.getItem(`boks-sim-${key}`),
set: (key, val) => localStorage.setItem(`boks-sim-${key}`, val)
};
// Node.js file-based adapter
import * as fs from 'fs';
class FileStorage implements SimulatorStorage {
private data: Record = {};
private path: string;
constructor(filePath: string) {
this.path = filePath;
if (fs.existsSync(filePath)) {
this.data = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
}
}
get(key: string): string | null {
return this.data[key] || null;
}
set(key: string, val: string): void {
this.data[key] = val;
fs.writeFileSync(this.path, JSON.stringify(this.data, null, 2));
}
}
// Create simulator with persistence
const simulator = new BoksHardwareSimulator({ storage: browserStorage });
// Or with logging
const simulatorWithLogging = new BoksHardwareSimulator({
storage: browserStorage,
logger: (level, event, context) => {
console.log(`[SIM][${level}] ${event}:`, context);
}
});
```
--------------------------------
### Set Credentials for Boks Device using JavaScript
Source: https://github.com/thib3113/boks-sdk-js/blob/main/examples/provisioning-demo.html
Sets the master credentials for the connected Boks device. It takes a 64-character hexadecimal master key as input from a UI element. This function is crucial for authenticating subsequent operations. It requires an active connection to a Boks device via BoksController.
```javascript
const setCredentialsBtn = document.getElementById('setCredentialsBtn');
const currentMasterKeyInput = document.getElementById('currentMasterKey');
setCredentialsBtn.addEventListener('click', () => {
const key = currentMasterKeyInput.value.trim();
if (key.length !== 64) {
// Log error
return;
}
try {
controller.setCredentials(key);
// Log success
// Show next UI section
} catch (err) {
// Log error
}
});
```
--------------------------------
### Control Boks Scale Accessory with Boks SDK
Source: https://context7.com/thib3113/boks-sdk-js/llms.txt
This experimental snippet demonstrates how to control the optional Boks scale accessory for package weight measurement. It includes bonding with the scale, taring it (empty or with a reference weight), measuring the weight, retrieving raw sensor data, and forgetting the scale bonding.
```typescript
import { BoksController } from '@thib3113/boks-sdk';
const controller = new BoksController();
await controller.connect();
// Bond with the scale
const bonded = await controller.bondScale();
console.log('Scale bonded:', bonded);
// Tare the scale (empty)
await controller.tareScale(true);
// Tare the scale (with reference weight loaded)
await controller.tareScale(false);
// Measure weight
const weight = await controller.getScaleWeight();
console.log(`Package weight: ${weight}g`);
// Get raw sensor data (for diagnostics)
const rawData = await controller.getScaleRawSensors();
console.log('Raw sensor data:', rawData);
// Forget scale bonding
await controller.forgetScale();
await controller.disconnect();
```
--------------------------------
### Manage NFC Tags: Scan, Register, and Unregister with Boks SDK (TypeScript)
Source: https://context7.com/thib3113/boks-sdk-js/llms.txt
Provides examples for managing NFC tags with the Boks SDK. This includes scanning for new tags, registering them, and unregistering existing tags. Requires hardware version 4.0+ and software version 4.3.3+. Handles potential errors like timeouts or already registered tags.
```typescript
import { BoksController } from '@thib3113/boks-sdk';
const controller = new BoksController();
await controller.connect();
controller.setCredentials('YOUR_MASTER_KEY_HEX_STRING_HERE');
try {
// Start NFC tag scan (place tag on reader within timeout)
console.log('Scanning for NFC tag...');
const scanResult = await controller.scanNFCTags(10000); // 10 second timeout
console.log(`Found tag: ${scanResult.tagId}`);
// Register the scanned tag
const registered = await scanResult.register();
console.log('Tag registered:', registered);
// Alternative: Register a known tag ID directly
await controller.registerNfcTag('04:A3:2B:1C:00:00:00');
// Unregister a tag
await controller.unregisterNfcTag('04:A3:2B:1C:00:00:00');
} catch (error) {
if (error.id === 'TIMEOUT') {
console.log('No NFC tag detected within timeout.');
} else if (error.id === 'ALREADY_EXISTS') {
console.log('NFC tag is already registered.');
} else if (error.id === 'UNSUPPORTED_FEATURE') {
console.log('NFC features require HW 4.0+ and SW 4.3.3+');
}
}
await controller.disconnect();
```
--------------------------------
### Perform Boks Firmware Update via DFU (JavaScript)
Source: https://github.com/thib3113/boks-sdk-js/blob/main/examples/firmware-update.html
Handles the firmware update process for Boks devices in DFU mode. It reads a firmware package (.zip) from a file input, initializes the SecureDfu module, and uploads the firmware, providing progress and log feedback.
```javascript
updateBtn.addEventListener('click', async () => {
if (!firmwareFile.files[0]) {
alert('Please select a firmware .zip file.');
return;
}
try {
const file = firmwareFile.files[0];
const content = await file.arrayBuffer();
log(`Starting DFU update with ${file.name} (${content.byteLength} bytes)...`);
const dfu = new SecureDfu(content, selectedDevice);
dfu.addEventListener('progress', (event) => {
const { current, total, percent } = event.detail;
progressDiv.textContent = `Progress: ${percent}% (${current}/${total})`;
});
dfu.addEventListener('log', (event) => {
log(`[DFU] ${event.detail.message}`);
});
await dfu.update();
log('Update Complete!');
statusDiv.textContent = 'Update Complete';
progressDiv.textContent = '100%';
} catch (err) {
log(`DFU Error: ${err.message}`);
statusDiv.textContent = 'Update Failed';
}
});
```
--------------------------------
### Handle Door Opening Rate Limit in TypeScript
Source: https://github.com/thib3113/boks-sdk-js/blob/main/wiki/guide/safety.md
Demonstrates how to handle the `RATE_LIMIT_REACHED` error when attempting to open a door too quickly using the Boks SDK. It shows a try-catch block to gracefully manage the error and inform the user to wait.
```typescript
try {
await controller.openDoor('123456');
// ... immediately try again
await controller.openDoor('123456');
} catch (error) {
if (error.id === 'RATE_LIMIT_REACHED') {
console.error('Please wait a moment before trying again.');
}
}
```
--------------------------------
### Experimental: Provisioning (Master Key Regeneration)
Source: https://github.com/thib3113/boks-sdk-js/blob/main/README.md
Demonstrates the experimental features for managing the Master Key on the Boks device. This includes regenerating the key with current credentials and initializing the device with a seed.
```typescript
// Regenerate the Master Key (requires current credentials)
await controller.regenerateMasterKey(newMasterKeyBytes);
// Factory Initialization (requires seed, no auth)
await controller.initialize(seedBytes);
```
--------------------------------
### Hardware Simulator Persistence
Source: https://github.com/thib3113/boks-sdk-js/blob/main/README.md
Illustrates how to persist the state of the `BoksHardwareSimulator`, including PINs, logs, and configuration, by injecting a storage implementation like `localStorage`.
```typescript
const storage = {
get: (key) => localStorage.getItem('boks-sim-' + key),
set: (key, val) => localStorage.setItem('boks-sim-' + key, val)
};
const simulator = new BoksHardwareSimulator(storage);
```
--------------------------------
### Manage PIN Codes: Create, Delete, Convert, and Reactivate with Boks SDK (TypeScript)
Source: https://context7.com/thib3113/boks-sdk-js/llms.txt
Demonstrates how to manage PIN codes using the Boks SDK. This includes creating single-use, multi-use, and master codes, converting between types, editing master codes, deleting codes, and reactivating disabled codes. Requires setting credentials before performing operations.
```typescript
import { BoksController, BoksCodeType } from '@thib3113/boks-sdk';
const controller = new BoksController();
await controller.connect();
controller.setCredentials('YOUR_MASTER_KEY_HEX_STRING_HERE');
// Create a new single-use code (consumed after one use)
const created = await controller.createSingleUseCode('654321');
console.log('Single-use code created:', created);
// Create a new multi-use code (can be used multiple times)
await controller.createMultiUseCode('111222');
// Create a master code at index 0-9 (permanent admin code)
await controller.createMasterCode(0, 'AABBCC');
// Get current code counts
const counts = await controller.countCodes();
console.log(`Master codes: ${counts.masterCount}, Other codes: ${counts.singleCount}`);
// Convert a single-use code to multi-use
await controller.convertCodeType('654321', BoksCodeType.Multi);
// Convert back to single-use
await controller.convertCodeType('654321', BoksCodeType.Single);
// Edit an existing master code
await controller.editMasterCode(0, 'NEWPIN');
// Delete codes by type
await controller.deleteSingleUseCode('654321');
await controller.deleteMultiUseCode('111222');
await controller.deleteMasterCode(0);
// Reactivate a disabled code
await controller.reactivateCode('123456');
await controller.disconnect();
```
--------------------------------
### BoksClient Low-Level BLE API with TypeScript
Source: https://context7.com/thib3113/boks-sdk-js/llms.txt
Demonstrates using the BoksClient for direct control over BLE protocol interactions. It covers connecting, executing transactions with explicit success/error handling, reading device characteristics, and subscribing to packets. Requires the '@thib3113/boks-sdk' package.
```typescript
import {
BoksClient,
OpenDoorPacket,
AskDoorStatusPacket,
BoksOpcode
} from '@thib3113/boks-sdk';
// Create client with optional logging
const client = new BoksClient({
logger: (level, event, context) => {
console.log(`[${level}] ${event}:`, context);
}
});
await client.connect();
// Execute a transaction with explicit success/error handling
const doorStatusTx = await client.execute(new AskDoorStatusPacket(), {
successOpcodes: [BoksOpcode.ANSWER_DOOR_STATUS, BoksOpcode.NOTIFY_DOOR_STATUS],
timeout: 5000
});
if (doorStatusTx.isSuccess) {
console.log('Door status:', doorStatusTx.response);
}
// Read device characteristics directly
const softwareRevBytes = await client.readCharacteristic('00002a28-0000-1000-8000-00805f9b34fb');
const softwareRev = new TextDecoder().decode(softwareRevBytes);
console.log('Software revision:', softwareRev);
// Subscribe to all packets
const unsubscribe = client.onPacket((packet) => {
console.log('Packet received:', packet.opcode);
});
await client.disconnect();
unsubscribe();
```
--------------------------------
### Core SDK Functionality (Low-Level)
Source: https://github.com/thib3113/boks-sdk-js/blob/main/README.md
Illustrates using the 'core' entry point of the Boks SDK for environments with critical bundle size constraints or when only specific algorithms are needed. It shows local PIN generation and manual BLE packet creation.
```typescript
import { BoksPacketFactory, generateBoksPin } from '@thib3113/boks-sdk/core';
// 1. Generate a PIN locally (BLAKE2s based)
// Useful for server-side generation or offline apps
const pin = generateBoksPin(masterKeyBytes, 'single-use', sequenceNumber);
// 2. Create raw BLE packets manually
const packet = BoksPacketFactory.createOpenDoorPacket('123456');
const bytes = packet.encode();
```
--------------------------------
### Generate New Master Key using JavaScript
Source: https://github.com/thib3113/boks-sdk-js/blob/main/examples/provisioning-demo.html
Generates a new random 32-byte (64 hexadecimal characters) master key. This is typically used before provisioning a new key to the device. The generated key is displayed in a UI input field, enabling the user to copy or use it for the next step. It utilizes the browser's `crypto.getRandomValues` API.
```javascript
const generateKeyBtn = document.getElementById('generateKeyBtn');
const newMasterKeyInput = document.getElementById('newMasterKey');
generateKeyBtn.addEventListener('click', () => {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
const hex = Array.from(array)
.map(b => b.toString(16).padStart(2, '0'))
.join('')
.toUpperCase();
newMasterKeyInput.value = hex;
// Enable provision button
});
```