### Create and Build Bruce JavaScript Application Source: https://context7.com/brucedevices/bruce-js-tooling/llms.txt Commands to create a new Bruce application using the setup wizard, navigate to the project directory, start development, and build the project for deployment. The build process compiles JavaScript files into the `bundle/` folder. ```bash # Create a new Bruce application using the setup wizard npx create-bruce-app@latest # Navigate to your project and start development cd my-bruce-app npm run start # Build your project - compiled JS will be in bundle/ folder npm run build ``` -------------------------------- ### Initialize and Control GPIO LED Example (JavaScript) Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/gpio.md This example demonstrates how to initialize a GPIO pin as an output, write HIGH and LOW states to control an LED, and use delays. It requires the 'gpio' module and assumes predefined constants like OUTPUT, HIGH, LOW, and delay function. ```javascript const gpio = require("gpio"); const led = 26; gpio.init(led, OUTPUT); gpio.write(led, HIGH); delay(1000); gpio.write(led, LOW); delay(1000); ``` -------------------------------- ### Start a Bruce Application (CLI) Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/README.md After setting up a new Bruce application, navigate to the project directory and use npm (or pnpm/yarn) to start the application. This command is used to run the development server or build the project. ```sh cd my-bruce-app npm run start ``` -------------------------------- ### Sub-GHz Communication Example (JavaScript) Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/subghz.md Demonstrates how to use the subghz module to set frequency, read incoming signals for a specified duration, and transmit a signal from a file. Requires the 'subghz' module to be installed. ```javascript const subghz = require("subghz"); // Set frequency to 433 MHz subghz.setFrequency(433); // Read incoming signal for 5 seconds const receivedData = subghz.read(5); console.log("Received Data:", receivedData); // Transmit a stored signal file const success = subghz.transmitFile("/plug1_on.sub"); if (success) { console.log("Transmission successful!"); } ``` -------------------------------- ### Create a New Bruce Application (CLI) Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/README.md Use the npx command to create a new Bruce application with TypeScript and modern JavaScript (ES6+) support. This command initiates an interactive setup wizard. Ensure Node.js is installed before running. ```sh npx create-bruce-app@latest ``` -------------------------------- ### Require External Module (ES5) Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/README.md Example of requiring an external module using the ES5 compatible syntax. This is necessary when uploading scripts directly without the setup wizard, as modern import syntax is not supported. ```javascript const ir = require('ir'); ``` -------------------------------- ### Connect to Wi-Fi and Fetch Data (JavaScript) Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/wifi.md This example demonstrates how to use the wifi module to check the connection status, connect to a specified network if not already connected, scan for available networks, and perform an HTTP GET request to a given URL. It requires the 'wifi' module to be imported. ```javascript const wifi = require("wifi"); if (!wifi.connected()) { wifi.connect("MySSID", 10, "password123"); } const networks = wifi.scan(); console.log("Available Networks:", networks); const response = wifi.httpFetch("https://example.com/api", { method: "GET", headers: { "Content-Type": "application/json" }, }); console.log(response.body); ``` -------------------------------- ### Create Bruce App with TypeScript and ES6+ Source: https://github.com/brucedevices/bruce-js-tooling/wiki/Bruce-JavaScript-tooling Initiates the creation of a new Bruce application with built-in support for TypeScript and modern JavaScript (ES6+) features using an interactive setup wizard. Requires Node.js to be installed. ```sh npx create-bruce-app@latest cd my-bruce-app npm run start ``` -------------------------------- ### GPIO LEDC Setup Source: https://github.com/brucedevices/bruce-js-tooling/wiki/Bruce-JavaScript-tooling Configures a specific LEDC (PWM) channel with a given frequency and resolution. This must be called before attaching a pin to the channel. ```APIDOC ## gpio.ledcSetup() ### Description Configures an LEDC (PWM) channel with a specific frequency and resolution. ### Method POST ### Endpoint /gpio/ledcSetup ### Parameters #### Request Body - **channel** (number) - Required - LEDC channel number (0–15). - **freq** (number) - Required - PWM frequency in Hz. - **resolution_bits** (number) - Required - Resolution (1–16 bits, defining duty cycle range). ### Response #### Success Response (200) - **actual_freq** (number) - The actual frequency set. #### Response Example ```json { "actual_freq": 1000 } ``` ``` -------------------------------- ### Serial Communication Example (JavaScript) Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/serial.md Demonstrates basic usage of the serial module, including sending a line of text and reading a line of input from the serial port. This example requires the 'serial' module to be installed and a serial connection to be available. ```javascript const serial = require("serial"); serial.println("Hello, Serial Port!"); const input = serial.readln(); console.log("Received:", input); ``` -------------------------------- ### BadUSB Setup API Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/badusb.md Initializes the BadUSB module. This function must be called before using any other BadUSB functions. ```APIDOC ## badusb.setup() ### Description Initializes the BadUSB module. ### Method `setup` ### Endpoint N/A (Local module function) ### Parameters None ### Request Example ```javascript const badusb = require("badusb"); badusb.setup(); ``` ### Response #### Success Response `void` #### Response Example N/A ``` -------------------------------- ### Example Usage of createTextViewer (JavaScript) Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/dialog.md Demonstrates how to use dialog.createTextViewer to create a scrollable text viewer. This example shows manual scrolling using keyboard input and continuous drawing of the viewer, highlighting the non-blocking nature of the function. ```javascript const dialog = require("dialog"); const textViewer = dialog.createTextViewer("long text"); while (true) { if (keyboard.getPrevPress()) { textViewer.scrollUp(); } if (keyboard.getNextPress()) { textViewer.scrollDown(); } textViewer.draw(); delay(100); } ``` -------------------------------- ### GPIO LEDC Setup Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/DOCS.md Configures a Low-Energy Controller (LEDC) channel for PWM generation. This function sets the frequency and resolution for the PWM signal. ```APIDOC ## gpio.ledcSetup() ### Description Configures an LEDC (PWM) channel with a specific frequency and resolution. ### Method POST ### Endpoint /gpio/ledcSetup ### Parameters #### Request Body - **channel** (number) - Required - LEDC channel number (0–15). - **freq** (number) - Required - PWM frequency in Hz. - **resolution_bits** (number) - Required - Resolution (1–16 bits, defining duty cycle range). ### Request Example ```json { "channel": 0, "freq": 1000, "resolution_bits": 8 } ``` ### Response #### Success Response (200) - **actual_freq** (number) - The actual frequency set. #### Response Example ```json { "actual_freq": 1000.5 } ``` ``` -------------------------------- ### Initialize and Use badusb Module Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/badusb.md Demonstrates the basic usage of the badusb module, including initialization, simulating key presses, and typing text. This requires the 'badusb' module to be installed. ```javascript const badusb = require("badusb"); badusb.setup(); badusb.press(0x04); // Presses the 'A' key badusb.release(0x04); // Releases the 'A' key badusb.println("Hello, world!"); // Types and presses Enter ``` -------------------------------- ### ES5 JavaScript Syntax for Direct Uploads Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/create-bruce-app/README.md Illustrates the required ES5 syntax for JavaScript files uploaded directly to Bruce, without using the setup wizard. This includes using 'var' instead of 'let', traditional for loops, 'function' keyword for functions, and 'require' for module imports. ```javascript var message = "Hello, Bruce!"; function greet(name) { console.log("Hello, " + name + "!"); } for (var i = 0; i < 5; i++) { console.log(i); } var utils = require('bruce-utils'); ``` -------------------------------- ### ES5 JavaScript Compatibility for Direct Uploads Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/DOCS.md When uploading scripts directly without the setup wizard, they must be written in ES5. This means avoiding TypeScript, IntelliSense, and modern JavaScript features like 'let', arrow functions, and 'import'. Use 'var', 'function', and 'require' instead. ```javascript // Example of ES5 syntax for direct upload var message = "Hello Bruce"; console.log(message); function greet(name) { return "Hello, " + name; } var ir = require('ir'); // Use require for modules console.log(greet("World")); ``` -------------------------------- ### ES5 JavaScript Compatibility for Direct Uploads Source: https://github.com/brucedevices/bruce-js-tooling/wiki/Bruce-JavaScript-tooling Demonstrates the ES5 syntax required for scripts uploaded directly to the Bruce platform without using the setup wizard. This includes using 'var' instead of 'let', traditional 'for' loops, 'function' keyword instead of arrow functions, and 'require' for module imports. ```javascript // Example of ES5 syntax for direct upload var count = 0; for (var i = 0; i < 5; i++) { count++; } function greet(name) { return 'Hello, ' + name; } var utils = require('utils'); console.log(greet('World')); ``` -------------------------------- ### Get Device Information (JavaScript) Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/device.md Demonstrates how to use the 'device' module to fetch and display various device attributes like name, board, model, battery charge, and free heap memory. This requires the 'device' module to be installed and accessible. ```javascript const device = require("device"); console.log("Device Name:", device.getName()); console.log("Board:", device.getBoard()); console.log("Model:", device.getModel()); console.log("Battery Charge:", device.getBatteryCharge(), "%"); const memoryStats = device.getFreeHeapSize(); console.log("RAM Free:", memoryStats.ram_free); console.log("PSRAM Free:", memoryStats.psram_free); ``` -------------------------------- ### Simulate USB Keyboard Input with BadUSB Module (JavaScript) Source: https://context7.com/brucedevices/bruce-js-tooling/llms.txt This code demonstrates the 'badusb' module for simulating USB keyboard input (HID automation). It covers initializing the module, typing text, pressing/releasing individual keys, holding modifier keys, and running DuckyScript files. An example of opening the Run dialog and executing a command is also included. ```javascript const badusb = require("badusb"); // Initialize BadUSB (required before use) badusb.setup(); // Type text badusb.print("Hello World"); badusb.println("This line ends with Enter"); // Press individual keys using HID keycodes badusb.press(0x04); // Press 'A' key badusb.release(0x04); // Release 'A' key // Hold modifier keys badusb.hold(0xE0); // Hold Left Control badusb.press(0x06); // Press 'C' (Ctrl+C = Copy) badusb.releaseAll(); // Release all keys // Press raw HID key value badusb.pressRaw(0x28); // Enter key // Run DuckyScript file badusb.runFile("/payloads/script.txt"); // Example: Open Run dialog on Windows and execute command badusb.setup(); delay(1000); // Win+R to open Run dialog badusb.hold(0xE3); // Left GUI (Windows key) badusb.press(0x15); // 'R' key badusb.releaseAll(); delay(500); // Type command badusb.println("notepad.exe"); // Common HID Keycodes: // 0x04-0x1D: A-Z // 0x1E-0x27: 1-0 // 0x28: Enter // 0x29: Escape // 0x2A: Backspace // 0x2B: Tab // 0x2C: Space // 0xE0: Left Control // 0xE1: Left Shift // 0xE2: Left Alt // 0xE3: Left GUI (Windows/Command) ``` -------------------------------- ### Access Keyboard Input with Bruce JS Tooling Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/keyboard.md Demonstrates how to import and use the keyboard module to detect any key press and exit a loop. It requires the 'keyboard' module to be installed. ```javascript const keyboard = require("keyboard"); while (true) { if (keyboard.getAnyPress()) { break; // Exits the loop when a button is pressed. } } ``` -------------------------------- ### File Storage Operations Example (JavaScript) Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/storage.md Demonstrates the usage of the storage module for various file operations including writing, reading, renaming, deleting, listing directory contents, creating, and removing directories. ```javascript const storage = require("storage"); // Write data to a file const success = storage.write("/data/log.txt", "Hello, world!"); if (success) { console.log("File written successfully!"); } // Read data from a file const content = storage.read("/data/log.txt"); console.log("File content:", content); // Rename a file const renamed = storage.rename("/data/log.txt", "/data/log_old.txt"); console.log("Rename successful:", renamed); // Delete a file const deleted = storage.delete("/data/log_old.txt"); console.log("Delete successful:", deleted); // List directory contents const files = storage.readdir("/data", { withFileTypes: true }); console.log("Files:\n", JSON.stringify(files, null, 2)); // Create a new directory storage.mkdir("/data/newdir"); // Remove a directory storage.rmdir("/data/newdir"); ``` -------------------------------- ### Initialize and Draw on TFT Display (JavaScript) Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/display.md This example demonstrates how to initialize the display, set colors, fill the screen, and draw a filled rectangle. It requires the 'display' module and uses basic color and drawing functions. ```javascript const display = require("display"); const black = display.color(0, 0, 0); const white = display.color(255, 255, 255); display.fill(black); display.drawFillRect(20, 20, 50, 50, white); delay(2000); ``` -------------------------------- ### Setup LEDC PWM Channel (TypeScript) Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/gpio.md Configures an LEDC (PWM) channel with a specified frequency and bit resolution. This function is essential for advanced PWM control and returns the actual frequency set. ```typescript gpio.ledcSetup( channel: number, freq: number, resolution_bits: number, ): number; ``` -------------------------------- ### Display API Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/DOCS.md Functions for interacting with the display, including drawing GIFs and getting display dimensions. ```APIDOC ## GET /display/drawGif ### Description Draws a GIF image on the display. ### Method GET ### Endpoint /display/drawGif ### Parameters #### Query Parameters - **path** (string | Path) - Required - The path to the GIF file. Supports: - A string path (e.g., "/images/anim.gif"). - A `Path` object specifying storage { fs: "sd", path: "/images/anim.gif" }. - **x** (number) - Optional - X-coordinate. - **y** (number) - Optional - Y-coordinate. - **center** (boolean) - Optional - Whether to center the image. - **playDurationMs** (number) - Optional - Duration to play the GIF. ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "success" } ``` ``` ```APIDOC ## GET /display/gifOpen ### Description Opens a GIF for manual frame playback. ### Method GET ### Endpoint /display/gifOpen ### Parameters #### Query Parameters - **path** (string | Path) - Required - The path to the GIF file. Supports: - A string path (e.g., "/images/anim.gif"). - A `Path` object specifying storage { fs: "sd", path: "/images/anim.gif" }. ### Response #### Success Response (200) - **gifObject** (Gif) - A `Gif` object for controlling playback. #### Response Example ```json { "gifObject": "" } ``` ``` ```APIDOC ## GET /display/width ### Description Gets the display width. ### Method GET ### Endpoint /display/width ### Response #### Success Response (200) - **width** (number) - Display width in pixels. #### Response Example ```json { "width": 320 } ``` ``` ```APIDOC ## GET /display/height ### Description Gets the display height. ### Method GET ### Endpoint /display/height ### Response #### Success Response (200) - **height** (number) - Display height in pixels. #### Response Example ```json { "height": 240 } ``` ``` -------------------------------- ### Open File Picker with dialog.pickFile() Source: https://github.com/brucedevices/bruce-js-tooling/wiki/Bruce-JavaScript-tooling The dialog.pickFile() function opens a file picker dialog, allowing the user to select a file. It can optionally take a starting path and an extension filter. The function returns the selected file path as a string. ```typescript dialog.pickFile(path?: string, extension?: string): string; ``` ```javascript const dialog = require("dialog"); const filePath = dialog.pickFile("/documents", "txt"); dialog.viewFile(filePath); ``` -------------------------------- ### Import External Module (Modern JS) Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/README.md Example of importing an external npm module using the modern JavaScript import syntax. This is supported when using the create-bruce-app wizard and TypeScript. ```javascript import isEven from "is-even"; ``` -------------------------------- ### File Path Selection in Bruce JS Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/globals.md Shows how to use the 'dialog' module to prompt the user for file selection. It specifies the file system ('fs') and the starting path for the dialog. Requires the 'dialog' module to be available. ```javascript const dialog = require("dialog"); dialog.pickFile({ fs: "user", path: "/" }); ``` -------------------------------- ### Read and Transmit IR Signals with IR Module (JavaScript) Source: https://context7.com/brucedevices/bruce-js-tooling/llms.txt This code demonstrates the 'ir' module for reading and transmitting infrared signals. It shows how to read signals with a timeout, save them to storage, and transmit signals from files. An example of building a simple IR remote control interface using dialogs is also included. ```javascript const ir = require("ir"); // Read IR signal with timeout var signal = ir.read(10); // Wait up to 10 seconds if (signal) { console.log("Received IR signal:", signal); // Save signal to file storage.write("/ir_signals/captured.ir", signal); } // Read raw IR signal data var rawSignal = ir.readRaw(5); console.log("Raw signal:", rawSignal); // Transmit IR signal from saved file var success = ir.transmitFile("/ir_signals/tv_power.ir"); if (success) { console.log("IR transmission successful!"); } else { console.log("IR transmission failed!"); } // IR remote control example const dialog = require("dialog"); var irCommands = { "Power": "/ir/power.ir", "Volume Up": "/ir/vol_up.ir", "Volume Down": "/ir/vol_down.ir", "Channel Up": "/ir/ch_up.ir", "Channel Down": "/ir/ch_down.ir" }; var selected = dialog.choice(Object.keys(irCommands)); ir.transmitFile(irCommands[selected]); ``` -------------------------------- ### Communicate with SubGHz Module (JavaScript) Source: https://context7.com/brucedevices/bruce-js-tooling/llms.txt This snippet illustrates the usage of the 'subghz' module for Sub-GHz radio communication. It covers setting the operating frequency, reading incoming signals with a timeout, capturing raw data, and transmitting saved signal files. A basic scanner example using dialogs is also provided. ```javascript const subghz = require("subghz"); // Set operating frequency (in MHz) subghz.setFrequency(433); // 433 MHz // subghz.setFrequency(315); // 315 MHz // subghz.setFrequency(868); // 868 MHz // Read incoming signal with timeout var receivedSignal = subghz.read(10); // Wait up to 10 seconds if (receivedSignal) { console.log("Received:", receivedSignal); // Save captured signal storage.write("/subghz/captured.sub", receivedSignal); } // Read raw signal data var rawData = subghz.readRaw(5); console.log("Raw SubGHz data:", rawData); // Transmit saved signal file var transmitted = subghz.transmitFile("/subghz/garage_door.sub"); if (transmitted) { console.log("Signal transmitted successfully!"); } // SubGHz scanner example const dialog = require("dialog"); var frequencies = ["315 MHz", "433 MHz", "868 MHz", "915 MHz"]; var freqValues = [315, 433, 868, 915]; var choice = dialog.choice(frequencies); var freqIndex = frequencies.indexOf(choice); subghz.setFrequency(freqValues[freqIndex]); dialog.info("Scanning on " + choice + "..."); var signal = subghz.read(30); if (signal) { dialog.success("Signal captured!"); } ``` -------------------------------- ### Read and Transmit IR Signals with ir.js Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/ir.md Demonstrates how to use the 'ir' module to read infrared signals with a specified timeout and transmit signals from a file. Requires the 'ir' module to be installed. ```javascript const ir = require("ir"); const signal = ir.read(5); // Waits up to 5 seconds for an IR signal console.log("Received IR signal:", signal); const rawSignal = ir.readRaw(5); console.log("Received raw IR signal:", rawSignal); const success = ir.transmitFile("/signals/power_on.ir"); console.log("Transmission successful:", success); ``` -------------------------------- ### display.setCursor() Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/display.md Sets the starting position (X, Y coordinates) for subsequent text rendering operations on the display. ```APIDOC ## display.setCursor() ### Description Sets the cursor position for text rendering. ### Method `display.setCursor(x: number, y: number): void` ### Parameters #### Path Parameters - **x** (number) - Required - The X-coordinate for the cursor position. - **y** (number) - Required - The Y-coordinate for the cursor position. ### Response #### Success Response (200) - **status** (string) - Indicates the operation was successful. ``` -------------------------------- ### display.drawFillRectGradient() Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/display.md Draws a filled rectangle with a gradient effect, specifying start and end colors and the gradient direction. ```APIDOC ## POST /display/drawFillRectGradient ### Description Draws a filled gradient rectangle. ### Method POST ### Endpoint /display/drawFillRectGradient ### Parameters #### Request Body - **x** (number) - Required - X-coordinate. - **y** (number) - Required - Y-coordinate. - **width** (number) - Required - Rectangle width. - **height** (number) - Required - Rectangle height. - **color1** (number) - Required - The starting color of the gradient. - **color2** (number) - Required - The ending color of the gradient. - **direction** (string) - Required - The direction of the gradient ('horizontal' or 'vertical'). ### Request Example ```json { "x": 30, "y": 30, "width": 70, "height": 50, "color1": 65280, "color2": 255, "direction": "horizontal" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Get Display Dimensions (TypeScript) Source: https://github.com/brucedevices/bruce-js-tooling/wiki/Bruce-JavaScript-tooling Retrieves the width and height of the display in pixels. These functions return a number representing the dimension. ```typescript display.width(): number; ``` ```typescript display.height(): number; ``` -------------------------------- ### wifi.connectDialog() Source: https://github.com/brucedevices/bruce-js-tooling/wiki/Bruce-JavaScript-tooling Opens a dialog to select and connect to a Wi-Fi network. ```APIDOC ## wifi.connectDialog() ### Description Opens a dialog to select and connect to a Wi-Fi network. ### Method GET ### Endpoint /wifi/connectDialog ### Response #### Success Response (200) - **message** (string) - Indicates the dialog was opened. #### Response Example ```json { "message": "Wi-Fi connection dialog opened." } ``` ``` -------------------------------- ### Get Current Time - TypeScript Source: https://github.com/brucedevices/bruce-js-tooling/wiki/Bruce-JavaScript-tooling Defines the 'now()' function in TypeScript, which returns the current time in milliseconds since the epoch. ```typescript now(): number; ``` -------------------------------- ### storage.mkdir() Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/storage.md Creates a new directory. ```APIDOC ## POST /storage/mkdir ### Description Creates a new directory at the specified path. ### Method POST ### Endpoint /storage/mkdir ### Parameters #### Request Body - **path** (string | Path) - Required - The path for the new directory. ### Request Example ```json { "path": "/data/newdir" } ``` ### Response #### Success Response (200) - **created** (boolean) - True if the directory was created successfully, false otherwise. #### Response Example ```json { "created": true } ``` ``` -------------------------------- ### Get Currently Pressed Keys Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/keyboard.md Retrieves a list of all keys that are currently being held down. This function returns an array of strings, where each string is the name of a pressed key. ```typescript keyboard.getKeysPressed(): string[]; ``` -------------------------------- ### dialog.prompt() Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/DOCS.md Opens an on-screen keyboard for user input, optionally with a title, maximum value length, and an initial value. ```APIDOC ## dialog.prompt() ### Description Opens an on-screen keyboard for user input. You can customize the prompt with a title, set a maximum length for the input, and provide an initial value. ### Method `dialog.prompt(title?: string, valueLength?: number, value?: string): string;` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```js const dialog = require("dialog"); const userInput = dialog.prompt("Enter your name:", 50, "Default Name"); console.log("User input:", userInput); ``` ### Response #### Success Response (200) - **string** - User input. #### Response Example ```json "John Doe" ``` ``` -------------------------------- ### Get Device Model (TypeScript) Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/device.md Provides the TypeScript signature for the `device.getModel()` function, which returns the model name of the device as a string. This function has no input parameters. ```typescript device.getModel(): string; ``` -------------------------------- ### Get Device Name (TypeScript) Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/device.md Provides the TypeScript signature for the `device.getName()` function, which returns the unique name of the device as a string. This function has no input parameters. ```typescript device.getName(): string; ``` -------------------------------- ### Display Text Cursor Positioning Source: https://github.com/brucedevices/bruce-js-tooling/wiki/Bruce-JavaScript-tooling Sets the starting position (X, Y coordinates) for rendering text on the TFT display. Subsequent text drawing operations will begin at this location. ```APIDOC ## display.setCursor() ### Description Sets the cursor position for text rendering. ### Method `display.setCursor(x: number, y: number): void` ### Parameters #### Path Parameters - **x** (number) - Required - The X-coordinate for the cursor position. - **y** (number) - Required - The Y-coordinate for the cursor position. ### Returns #### Success Response (200) - **status** (void) - Indicates the operation completed successfully. ### Request Example ```js display.setCursor(10, 50); ``` ### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### BadUSB Module API Source: https://context7.com/brucedevices/bruce-js-tooling/llms.txt API for simulating USB keyboard input and automating HID tasks. ```APIDOC ## BadUSB Module API ### Description Allows simulation of USB keyboard input for HID (Human Interface Device) automation. ### Methods #### `badusb.setup()` Initializes the BadUSB module. Must be called before other BadUSB functions. #### `badusb.print(text)` Types the given text without pressing Enter. - **text** (string) - The text to type. #### `badusb.println(text)` Types the given text and then presses Enter. - **text** (string) - The text to type. #### `badusb.press(keyCode)` Presses a specific key. - **keyCode** (number) - The HID keycode for the key to press. #### `badusb.release(keyCode)` Releases a specific key. - **keyCode** (number) - The HID keycode for the key to release. #### `badusb.hold(keyCode)` Holds down a modifier key. - **keyCode** (number) - The HID keycode for the modifier key to hold. #### `badusb.releaseAll()` Releases all currently held keys. #### `badusb.pressRaw(keyCode)` Presses a raw HID key value. - **keyCode** (number) - The raw HID key value. #### `badusb.runFile(filePath)` Executes a script from a file (e.g., DuckyScript). - **filePath** (string) - The path to the script file. ### Common HID Keycodes - **0x04-0x1D**: A-Z - **0x1E-0x27**: 1-0 - **0x28**: Enter - **0x29**: Escape - **0x2A**: Backspace - **0x2B**: Tab - **0x2C**: Space - **0xE0**: Left Control - **0xE1**: Left Shift - **0xE2**: Left Alt - **0xE3**: Left GUI (Windows/Command) ``` -------------------------------- ### Get Display Height - TypeScript Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/display.md Retrieves the current height of the display in pixels. This function takes no arguments and returns a number representing the display's height. ```typescript display.height(): number; ``` -------------------------------- ### Fetch Utility Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/DOCS.md This section describes the fetch utility, which allows for making HTTP requests with various options and provides detailed response information. ```APIDOC ## GET /fetch ### Description Fetches a resource from a given URL with customizable request options. ### Method GET ### Endpoint /fetch ### Parameters #### Query Parameters - **url** (string) - Required - The URL to fetch. - **options** (object) - Optional - Request options including method, body, and headers. - **options.method** (string) - Optional - The HTTP method to use (e.g., "GET", "POST"). Defaults to "GET". - **options.body** (string) - Optional - The request body. - **options.responseType** (string) - Optional - The expected response type, either "string" or "binary". Defaults to "string". - **options.headers** (string[] | [string, string][] | Record) - Optional - Custom headers for the request. ### Request Example ```json { "url": "https://api.example.com/data", "options": { "method": "POST", "body": "{\"key\": \"value\"}", "headers": { "Content-Type": "application/json" } } } ``` ### Response #### Success Response (200) - **status** (number) - The HTTP response status code. - **ok** (boolean) - True if the response status is 200-299, otherwise false. - **body** (string | Uint8Array) - The response body. #### Response Example ```json { "status": 200, "ok": true, "body": "{\"message\": \"Success\"}" } ``` ``` -------------------------------- ### Get Display Width - TypeScript Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/display.md Retrieves the current width of the display in pixels. This function takes no arguments and returns a number representing the display's width. ```typescript display.width(): number; ``` -------------------------------- ### dialog.pickFile() Source: https://github.com/brucedevices/bruce-js-tooling/wiki/Bruce-JavaScript-tooling Opens a file picker dialog and returns the path of the selected file. ```APIDOC ## POST /dialog/pickFile ### Description Opens a file picker dialog and returns the selected file path. ### Method POST ### Endpoint /dialog/pickFile ### Parameters #### Request Body - **path** (string) - Optional - The initial directory to open the file picker in. - **extension** (string) - Optional - The default file extension to filter by. ### Request Example ```json { "path": "/documents", "extension": "txt" } ``` ### Response #### Success Response (200) - **filePath** (string) - The path of the selected file. #### Response Example ```json { "filePath": "/documents/example.txt" } ``` ``` -------------------------------- ### dialog.prompt() Source: https://github.com/brucedevices/bruce-js-tooling/wiki/Bruce-JavaScript-tooling Opens an on-screen keyboard for user input with an optional title, maximum value length, and initial value. ```APIDOC ## POST /dialog/prompt ### Description Opens an on-screen keyboard for user input. ### Method POST ### Endpoint /dialog/prompt ### Parameters #### Request Body - **title** (string) - Optional - Title of the keyboard prompt. - **valueLength** (number) - Optional - Maximum length of the input value. - **value** (string) - Optional - Initial value to display. ### Returns #### Success Response (200) - **userInput** (string) - User input. #### Response Example { "userInput": "User entered text" } ``` -------------------------------- ### Get Battery Charge (TypeScript) Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/device.md Provides the TypeScript signature for the `device.getBatteryCharge()` function, which returns the current battery charge percentage as a number. The value ranges from 0 to 100. ```typescript device.getBatteryCharge(): number; ``` -------------------------------- ### Get Board Type (TypeScript) Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/device.md Provides the TypeScript signature for the `device.getBoard()` function, which returns the identifier for the device's board type as a string. This function has no input parameters. ```typescript device.getBoard(): string; ``` -------------------------------- ### dialog.pickFile() Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/DOCS.md Opens a file picker dialog, allowing the user to select a file. Returns the path of the selected file. ```APIDOC ## dialog.pickFile() ### Description Opens a file picker dialog and returns the selected file path. Optionally, you can specify an initial directory and a file extension filter. ### Method `dialog.pickFile(path?: string, extension?: string): string;` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```js const dialog = require("dialog"); const filePath = dialog.pickFile("/documents", "txt"); dialog.viewFile(filePath); ``` ### Response #### Success Response (200) - **string** - The selected file path or `null` if no file is chosen. #### Response Example ```json "/documents/my_file.txt" ``` ``` -------------------------------- ### wifi.connect() Source: https://github.com/brucedevices/bruce-js-tooling/wiki/Bruce-JavaScript-tooling Connects to a Wi-Fi network with a specified SSID, timeout, and password. ```APIDOC ## wifi.connect() ### Description Connects to a Wi-Fi network with a specified SSID, timeout, and password. ### Method POST ### Endpoint /wifi/connect ### Parameters #### Request Body - **ssid** (string) - Required - The name of the Wi-Fi network (SSID). - **timeoutInSeconds** (number) - Required - The time (in seconds) to wait for a connection before failing. - **password** (string) - Required - The Wi-Fi password. ### Response #### Success Response (200) - **success** (boolean) - `true` if successfully connected, otherwise `false`. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Fetch Utility Source: https://github.com/brucedevices/bruce-js-tooling/wiki/Bruce-JavaScript-tooling This section describes the primary fetch utility, which allows making HTTP requests with various options. ```APIDOC ## GET /fetch ### Description Fetches a resource from a given URL with customizable request options. ### Method GET ### Endpoint /fetch ### Parameters #### Query Parameters - **url** (string) - Required - The URL to fetch. - **options** (object) - Optional - Request options including method, body, and headers. - **method** (string) - Optional - HTTP method (e.g., "GET", "POST"). Defaults to "GET". - **body** (string) - Optional - The request body. - **binaryResponse** (boolean) - Optional - If true, the response body will be a Uint8Array. - **headers** (string[] | [string, string][] | Record) - Optional - Request headers. ### Request Example ```json { "url": "https://api.example.com/data", "options": { "method": "POST", "body": "{\"key\": \"value\"}", "headers": { "Content-Type": "application/json" } } } ``` ### Response #### Success Response (200) - **status** (number) - The HTTP response status code. - **ok** (boolean) - True if the response status is 200-299, otherwise false. - **body** (string | Uint8Array) - The response body. #### Response Example ```json { "status": 200, "ok": true, "body": "{\"message\": \"Success!\"}" } ``` ``` -------------------------------- ### dialog.pickFile() Source: https://github.com/brucedevices/bruce-js-tooling/wiki/Bruce-JavaScript-tooling Presents a file picker dialog to the user, allowing them to select a file. Returns the selected file path or null if no file is chosen. ```APIDOC ## GET /dialog/pickFile ### Description Presents a file picker dialog to the user, allowing them to select a file. ### Method GET ### Endpoint /dialog/pickFile ### Parameters #### Query Parameters - **path** (string) - Optional - The initial directory path. - **extension** (string) - Optional - The file extension filter. ### Returns #### Success Response (200) - **filePath** (string) - The selected file path or null if no file is chosen. #### Response Example { "filePath": "/path/to/selected/file.txt" } ``` -------------------------------- ### Device Information Retrieval with Bruce JS Source: https://context7.com/brucedevices/bruce-js-tooling/llms.txt This snippet demonstrates how to retrieve device information and system status using the 'device' module. It includes fetching device identifiers, checking battery status, and obtaining detailed memory statistics. ```javascript const device = require("device"); // Get device identifiers console.log("Device Name:", device.getName()); console.log("Board Type:", device.getBoard()); console.log("Model:", device.getModel()); // Get battery status var batteryLevel = device.getBatteryCharge(); console.log("Battery:", batteryLevel + "%"); if (batteryLevel < 20) { dialog.warning("Low battery: " + batteryLevel + "%"); } // Get memory statistics var memory = device.getFreeHeapSize(); console.log("RAM Free:", memory.ram_free, "bytes"); console.log("RAM Total:", memory.ram_size, "bytes"); console.log("RAM Min Free:", memory.ram_min_free, "bytes"); console.log("RAM Largest Block:", memory.ram_largest_free_block, "bytes"); console.log("PSRAM Free:", memory.psram_free, "bytes"); console.log("PSRAM Total:", memory.psram_size, "bytes"); // Memory usage percentage var ramUsage = ((memory.ram_size - memory.ram_free) / memory.ram_size * 100).toFixed(1); console.log("RAM Usage:", ramUsage + "%"); // System info display const display = require("display"); display.fill(display.color(0, 0, 0)); display.setTextColor(display.color(255, 255, 255)); display.setTextSize(1); display.setCursor(10, 10); display.println("Device: " + device.getName()); display.println("Board: " + device.getBoard()); display.println("Battery: " + device.getBatteryCharge() + "%"); display.println("Free RAM: " + memory.ram_free + " bytes"); ``` -------------------------------- ### Play Audio Tones and Files with Audio Module (JavaScript) Source: https://context7.com/brucedevices/bruce-js-tooling/llms.txt This snippet demonstrates how to use the 'audio' module to play specific audio tones by frequency and duration, as well as play audio files from storage. It covers both blocking and non-blocking tone playback, and sequences of musical notes. ```javascript const audio = require("audio"); // Play a tone at specific frequency audio.tone(440, 1000); // 440Hz (A4 note) for 1 second audio.tone(988, 500); // B5 note for 500ms // Non-blocking tone (won't block execution) audio.tone(262, 200, true); // C4 note, 200ms, non-blocking // Play musical notes sequence var melody = [ { freq: 262, duration: 200 }, // C4 { freq: 294, duration: 200 }, // D4 { freq: 330, duration: 200 }, // E4 { freq: 349, duration: 200 }, // F4 { freq: 392, duration: 400 } // G4 ]; for (var i = 0; i < melody.length; i++) { audio.tone(melody[i].freq, melody[i].duration); delay(50); // Small pause between notes } // Play audio file from storage audio.playFile("/sounds/alert.wav"); audio.playFile("/music/background.wav"); ``` -------------------------------- ### wifi.httpFetch() Source: https://github.com/brucedevices/bruce-js-tooling/wiki/Bruce-JavaScript-tooling Performs an HTTP request to a specified URL with optional configuration. ```APIDOC ## wifi.httpFetch() ### Description Performs an HTTP request to a specified URL with optional configuration. ### Method POST ### Endpoint /wifi/httpFetch ### Parameters #### Request Body - **url** (string) - Required - The URL to fetch. - **options** (object) - Optional - Configuration for the request. - **method** (string) - The HTTP method (GET, POST, etc.). Defaults to GET. - **body** (string) - The request body. - **binaryResponse** (boolean) - Whether to expect a binary response. Defaults to false. - **headers** (object or array) - Request headers. ### Response #### Success Response (200) - **status** (number) - The HTTP status code of the response. - **ok** (boolean) - `true` if the status code is in the 2xx range, otherwise `false`. - **body** (string) - The response body. #### Response Example ```json { "status": 200, "ok": true, "body": "Response body content" } ``` ``` -------------------------------- ### Play Audio File using JavaScript Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/audio.md Demonstrates how to play an audio file from storage using the audio module. It requires the 'audio' module to be required and takes a filename as a string argument. ```javascript const audio = require("audio"); audio.playFile("/sound.wav"); ``` -------------------------------- ### Get User Choice with dialog.choice() Source: https://github.com/brucedevices/bruce-js-tooling/wiki/Bruce-JavaScript-tooling The dialog.choice() function presents a dialog with options and returns the user's selection as a string. It accepts an array of strings, an array of string pairs, or an object as input for the choices. The return type is string. ```typescript dialog.choice(values: string[] | [string, string][] | {}): string; ``` ```javascript const dialog = require("dialog"); const options = ["Yes", "No", "Cancel"]; const selected = dialog.choice(options); console.log("Selected:", selected); ``` -------------------------------- ### Serial Communication with Bruce JS Source: https://context7.com/brucedevices/bruce-js-tooling/llms.txt This snippet demonstrates how to use the 'serial' module to print messages, read lines from the serial monitor with a timeout, and execute Bruce serial commands. It includes examples for basic debugging and interactive communication. ```javascript const serial = require("serial"); // Print to serial monitor serial.print("Status: "); serial.println("OK"); serial.println("Value:", 42, "units"); // Read line from serial with timeout var input = serial.readln(5000); // 5 second timeout if (input) { console.log("Received:", input); } // Execute Bruce serial commands // See: https://github.com/pr3y/Bruce/wiki/Serial serial.cmd("wifi scan"); serial.cmd("ir tx /signals/power.ir"); // Serial communication example serial.println("Enter your name:"); var name = serial.readln(30000); serial.println("Hello, " + name + "!"); // Debug logging function debug(message) { serial.println("[DEBUG] " + now() + ": " + message); } debug("Application started"); debug("Initializing sensors..."); ``` -------------------------------- ### Get Free Heap Size (TypeScript) Source: https://github.com/brucedevices/bruce-js-tooling/blob/main/packages/bruce-sdk/docs/device.md Provides the TypeScript signature for the `device.getFreeHeapSize()` function, which returns an object containing detailed memory usage statistics for both RAM and PSRAM. This includes free, minimum free, largest free block, and total size for each memory type. ```typescript device.getFreeHeapSize(): { ram_free: number; ram_min_free: number; ram_largest_free_block: number; ram_size: number; psram_free: number; psram_size: number; }; ```