### Getting Started with micro-Jest Source: https://github.com/kaluma-project/kaluma/blob/master/src/modules/__ujest/README.md Instructions on how to add micro-Jest as a dependency and a basic example of its usage. ```APIDOC ## Getting Started with micro-Jest Add `@niklauslee/micro-jest` dependency to your `package.json`. ### Request Body ```json { "dependencies": { "@niklauslee/micro-jest": "" } } ``` ### Request Example ```js const { test, expect, start } = require("@niklauslee/micro-jest"); function sum(a, b) { return a + b; } test("adds 1 + 2 to equal 3", (done) => { expect(sum(1, 2)).toBe(3); done(); // should be called }); start(); // start to test ``` It is recommended to add a `test.js` file including test cases to your project. To run the `test.js` open and activate `test.js` file in IDE and select **Upload Current** menu. ``` -------------------------------- ### Initialize Repository Source: https://github.com/kaluma-project/kaluma/wiki/Build Clones the repository, initializes submodules, and installs required npm dependencies. ```sh # clone repo $ git clone https://github.com/kaluma-project/kaluma.git $ cd kaluma # init & update git submodules $ git submodule update --init --recursive # install npm modules $ npm install ``` -------------------------------- ### File System Operations with fs Module Source: https://context7.com/kaluma-project/kaluma/llms.txt Provides examples of various file system operations including opening, writing, reading, checking existence, getting stats, creating directories, changing directories, and deleting files/directories. ```javascript const fs = require('fs'); // Mount filesystem (typically done at startup) // fs.mount('/', blockDevice, 'lfs', true); // Mount LittleFS with auto-format // File operations const fd = fs.open('/data.txt', 'w'); // Open for writing const data = new Uint8Array([72, 101, 108, 108, 111]); // "Hello" fs.write(fd, data, 0, data.length, 0); fs.close(fd); // Read file const content = fs.readFile('/data.txt'); console.log(String.fromCharCode.apply(null, content)); // Write file (high-level) const text = new TextEncoder().encode('Hello, Kaluma!'); fs.writeFile('/message.txt', text); // Check if file exists if (fs.exists('/data.txt')) { console.log('File exists'); } // Get file stats const stats = fs.stat('/data.txt'); console.log(`Size: ${stats.size}`); console.log(`Is file: ${stats.isFile()}`); console.log(`Is directory: ${stats.isDirectory()}`); // Directory operations fs.mkdir('/mydir'); fs.chdir('/mydir'); console.log('Current directory:', fs.cwd()); const files = fs.readdir('/'); files.forEach((f) => console.log(f)); // Rename and delete fs.rename('/old.txt', '/new.txt'); fs.unlink('/new.txt'); // Delete file fs.rmdir('/mydir'); // Delete directory fs.rm('/path'); // Delete file or directory ``` -------------------------------- ### CMake Build Configuration for KB2040 Source: https://github.com/kaluma-project/kaluma/blob/master/targets/rp2/boards/kb2040/README.md Example CMake command to build Kaluma for the RP2040 target with the kb2040 board configuration. ```bash -DTARGET=rp2 -DBOARD=kb2040 ``` -------------------------------- ### Running Tests with micro-Jest Source: https://github.com/kaluma-project/kaluma/blob/master/src/modules/__ujest/README.md How to run all test cases or specific test cases using the `start` function. ```APIDOC ## Running Tests with micro-Jest To run all test cases you have to call `jest.start()`. However sometimes you want to run a particular test case rather than all test cases. You can do it by calling `start()` with a number of test case. ### Request Example ```javascript start(0); // Run the first test case. start(3); // Run the 4-th test case. start(); // Run all the test cases. ``` It is convenient to add `global.start = start` in the end of the your test code (e.g., `test.js`). Then you can run all test or run a particular test in Terminal like `start()` or `start(3);`. ``` -------------------------------- ### Porting Kaluma to New Hardware Source: https://github.com/kaluma-project/kaluma/wiki/Internal Step-by-step guide for porting Kaluma to a new hardware platform, focusing on implementing hardware-neutral interfaces and setting up target-specific configurations. ```text 1. Create a folder in `targets/` (e.g. `targets/esp32`). 2. Implement all header files in `include/port/*.h` into `targets//src/*.c`. 3. Create a board folder in `targets//boards/`. 4. Add `board.h` and `board.js` into the board folder. 5. Create a CMAKE file `target.cmake` for the target. 6. Put required libraries in `lib` if any. ``` -------------------------------- ### Verify Build Dependencies Source: https://github.com/kaluma-project/kaluma/wiki/Build Checks that the required toolchain components are installed and accessible in the environment. ```sh $ arm-none-eabi-gcc --version # check gcc arm $ python --version # check python $ cmake --version # check cmake $ node --version # check node.js ``` -------------------------------- ### Install dfu-util on macOS Source: https://github.com/kaluma-project/kaluma/blob/master/targets/stm32/README.md This command installs the `dfu-util` tool using Homebrew, which is required for DFU mode operations on macOS. ```sh $ brew install dfu-util ``` -------------------------------- ### Set Version Name in CMakeLists.txt Source: https://github.com/kaluma-project/kaluma/wiki/Release Use Semver for version names. Examples include '1.0.0-beta.1', '1.0.0', and '1.1.0'. ```cmake set(VER "") ``` -------------------------------- ### CMake Build Command for RP2040-PiZero Source: https://github.com/kaluma-project/kaluma/blob/master/targets/rp2/boards/rp2040-pizero/README.md Use this CMake command to build Kaluma firmware for the RP2040-PiZero board. Ensure you have CMake installed and configured for your build environment. ```bash cmake -DTARGET=rp2 -DBOARD=rp2040-pizero ``` -------------------------------- ### Build RP2040-PiZero Docker Image Source: https://github.com/kaluma-project/kaluma/blob/master/targets/rp2/boards/rp2040-pizero/README.md This shell script is used to build the Docker image for the RP2040-PiZero board. It's part of the optional Docker setup for Kaluma development. ```bash tools/docker/build_rp2040_pizero.sh ``` -------------------------------- ### Define and run a test case Source: https://github.com/kaluma-project/kaluma/blob/master/src/modules/__ujest/README.md Basic structure for defining tests using the test function and executing them with start. Always call the done callback to signal test completion. ```js const { test, expect, start } = require("@niklauslee/micro-jest"); function sum(a, b) { return a + b; } test("adds 1 + 2 to equal 3", (done) => { expect(sum(1, 2)).toBe(3); done(); // should be called }); start(); // start to test ``` -------------------------------- ### Execute specific test cases Source: https://github.com/kaluma-project/kaluma/blob/master/src/modules/__ujest/README.md Control test execution by passing an index to the start function, or run all tests by calling it without arguments. ```javascript start(0); // Run the first test case. start(3); // Run the 4-th test case. start(); // Run all the test cases. ``` -------------------------------- ### Flash Kameleon Core Firmware with ST-Link Source: https://github.com/kaluma-project/kaluma/blob/master/targets/stm32/README.md Use this command to flash the built `kameleon-core.bin` file to the device's memory address `0x8000000`. Ensure you have the `stlink` tool installed. ```sh $ st-flash write build/kameleon-core.bin 0x8000000 ``` -------------------------------- ### TCP Client and Server with Net Module Source: https://context7.com/kaluma-project/kaluma/llms.txt Demonstrates creating a TCP client to connect to a server and a TCP server to handle client connections. Includes basic data exchange and event handling. ```javascript const net = require('net'); // Create TCP client const client = new net.Socket(); client.connect({ host: '192.168.1.100', port: 3000 }, () => { console.log('Connected to server'); client.write('Hello Server!'); }); client.on('data', (data) => { console.log('Received:', String.fromCharCode.apply(null, data)); }); client.on('end', () => { console.log('Connection ended'); }); client.on('close', () => { console.log('Connection closed'); }); client.on('error', (err) => { console.error('Error:', err); }); // Shortcut for creating connection const socket = net.createConnection({ host: '192.168.1.100', port: 3000 }, () => { socket.write('Connected!'); }); // Create TCP server const server = net.createServer((socket) => { console.log('Client connected:', socket.remoteAddress); socket.on('data', (data) => { console.log('Received:', String.fromCharCode.apply(null, data)); socket.write('Echo: ' + String.fromCharCode.apply(null, data)); }); socket.on('close', () => { console.log('Client disconnected'); }); }); server.on('listening', () => { console.log('Server listening'); }); server.listen(3000); // Close server server.close(() => { console.log('Server closed'); }); ``` -------------------------------- ### Build Kameleon Core Firmware Source: https://github.com/kaluma-project/kaluma/blob/master/targets/stm32/README.md Execute this command to build the Kameleon Core firmware. The output binary `kameleon-core.bin` will be placed in the `/build` directory. ```sh $ node build --target=kameleon-core ``` -------------------------------- ### Build Kaluma for Raspberry Pi Pico Source: https://github.com/kaluma-project/kaluma/blob/master/targets/rp2/README.md Execute this command to build the firmware. The output file will be `rpi-pico.uf2` in the `/build` directory. ```sh $ node build # or, node build --target=rpi-pico ``` -------------------------------- ### Node.js Build Command for RP2040-PiZero Source: https://github.com/kaluma-project/kaluma/blob/master/targets/rp2/boards/rp2040-pizero/README.md Execute this Node.js command to build Kaluma firmware for the RP2040-PiZero board. This script requires Node.js and the build.js script to be available in your project. ```bash node build.js --target rp2 --board rp2040-pizero ``` -------------------------------- ### Build with CMake Source: https://github.com/kaluma-project/kaluma/wiki/Build Performs a manual build using CMake and make. ```sh $ mkdir build # if not exist $ cd build $ cmake .. # or, you can specify parameters # $ cmake .. -DTARGET=rp2 -DBOARD=pico -DMODULES=events;gpio;...;startup $ make ``` -------------------------------- ### Flash RP2040-PiZero UF2 File Source: https://github.com/kaluma-project/kaluma/blob/master/targets/rp2/boards/rp2040-pizero/README.md Instructions for flashing the generated UF2 firmware file to the RP2040-PiZero board. This involves holding the BOOTSEL button, connecting the board, and copying the UF2 file to the RPI-RP2 drive. ```bash Hold BOOTSEL, plug board in, copy UF2 to RPI-RP2 ``` -------------------------------- ### Initialize Submodules for RP2 Source: https://github.com/kaluma-project/kaluma/wiki/Build Updates submodules specifically for the rp2 target and pico board. ```sh # init & update git submodules for pico-sdk and others $ git submodule update --init --recursive ``` -------------------------------- ### Mount LittleFS with Dynamic Partitioning Source: https://github.com/kaluma-project/kaluma/blob/master/AGENTS.md Configures the filesystem using available flash space after firmware and user program partitions. Use the appropriate sector offsets based on the specific board's partition layout. ```javascript // in board.js (Pico 2) const fs = require('fs'); const { VFSLittleFS } = require('vfs_lfs'); const { Flash } = require('flash'); fs.register('lfs', VFSLittleFS); const total = new Flash().count; // sectors after A const bd = new Flash(400, total - 400); // B=16, C=384 → start=400 fs.mount('/', bd, 'lfs', true); ``` ```javascript // in board.js const fs = require('fs'); const { VFSLittleFS } = require('vfs_lfs'); const { Flash } = require('flash'); fs.register('lfs', VFSLittleFS); const total = new Flash().count; // sectors after A const bd = new Flash(132, total - 132); // B=4, C=128 → start=132 fs.mount('/', bd, 'lfs', true); ``` -------------------------------- ### Initialize hardware with the board object Source: https://context7.com/kaluma-project/kaluma/llms.txt The global board object provides factory methods to instantiate hardware peripherals like GPIO, PWM, ADC, I2C, SPI, and UART. ```javascript // The board object is globally available // Create instances using factory methods // GPIO const led = board.gpio(25, OUTPUT); led.toggle(); // LED (shortcut for GPIO output) const statusLed = board.led(25); statusLed.on(); // Button const btn = board.button(15); btn.on('click', () => console.log('Clicked!')); // PWM const pwm = board.pwm(16); // ADC const adc = board.adc(26); console.log(adc.read()); // I2C const i2c = board.i2c(0); // SPI const spi = board.spi(0); // UART const uart = board.uart(0, { baudrate: 9600 }); ``` -------------------------------- ### Key-Value Storage with storage Module Source: https://context7.com/kaluma-project/kaluma/llms.txt Demonstrates using the storage module for persistent key-value storage, including storing, retrieving, checking length, iterating, removing items, and clearing all storage. Also shows the global storage object. ```javascript const storage = require('storage'); // Store values storage.setItem('username', 'kaluma'); storage.setItem('count', '42'); storage.setItem('config', JSON.stringify({ debug: true, interval: 1000 })); // Retrieve values const username = storage.getItem('username'); console.log(`Username: ${username}`); const config = JSON.parse(storage.getItem('config') || '{}'); console.log(`Debug mode: ${config.debug}`); // Check number of stored items console.log(`Items stored: ${storage.length}`); // Iterate through all keys for (let i = 0; i < storage.length; i++) { const key = storage.key(i); console.log(`${key}: ${storage.getItem(key)}`); } // Remove specific item storage.removeItem('count'); // Clear all storage storage.clear(); // Use global storage object (available without require) storage.setItem('WIFI_SSID', 'MyNetwork'); storage.setItem('WIFI_PASSWORD', 'secret'); ``` -------------------------------- ### Build Project via Node.js Source: https://github.com/kaluma-project/kaluma/blob/master/targets/rp2/boards/rp2040-touch-lcd-1-28/README.md Compile the project for the specific board target using the Node.js build script. ```bash node build.js --target rp2 --board rp2040-touch-lcd-1-28 ``` -------------------------------- ### Run Kaluma Tests Source: https://github.com/kaluma-project/kaluma/blob/master/tests/onboard/README.md Execute the Kaluma test suite using the npm test command. ```bash $ npm test ``` -------------------------------- ### Manage LEDs with the LED Module Source: https://context7.com/kaluma-project/kaluma/llms.txt Use the LED abstraction for simple state control and periodic blinking. ```javascript const { LED } = require('led'); // Create LED instance on pin 25 const led = new LED(25); // Control LED state led.on(); // Turn LED on led.off(); // Turn LED off led.toggle(); // Toggle LED state // Read current state const isOn = led.read(); // Returns 0 or 1 // Blink LED using setInterval setInterval(() => { led.toggle(); }, 500); // Blink every 500ms ``` -------------------------------- ### Kaluma Entry Point Source: https://github.com/kaluma-project/kaluma/wiki/Internal Identifies the main entry point file for the Kaluma C runtime. ```text `src/main.c` is the entry point. ``` -------------------------------- ### Build with build.js Script Source: https://github.com/kaluma-project/kaluma/wiki/Build Executes the build process using the project's JavaScript build utility. ```sh $ node build --target= --board= --modules= # ex) node build (rp2-pico is default) # ex) node build --target=rp2 --board=pico --modules="events;gpio;i2c;...;startup" ``` -------------------------------- ### Build Kaluma for Linux Source: https://github.com/kaluma-project/kaluma/blob/master/targets/linux/README.md Commands to configure and compile the project for the Linux target. ```sh # assume at /kaluma $ mkdir build # if not exist $ cd build $ cmake .. -DTARGET=linux $ make ``` -------------------------------- ### Path Manipulation with path Module Source: https://context7.com/kaluma-project/kaluma/llms.txt Illustrates various utilities for working with file and directory paths, including joining, resolving, normalizing, checking for absolute paths, parsing path components, formatting paths, and accessing the path separator. ```javascript const path = require('path'); // Join path segments const fullPath = path.join('/home', 'user', 'file.txt'); console.log(fullPath); // '/home/user/file.txt' // Resolve path (with current working directory) const resolved = path.resolve('data', 'config.json'); console.log(resolved); // '/current/dir/data/config.json' // Normalize path const normalized = path.normalize('/home/user/../docs/./file.txt'); console.log(normalized); // '/home/docs/file.txt' // Check if path is absolute console.log(path.isAbsolute('/home')); // true console.log(path.isAbsolute('relative')); // false // Parse path into components const parsed = path.parse('/home/user/file.txt'); console.log(parsed); // { root: '/', dir: '/home/user', base: 'file.txt', name: 'file', ext: '.txt' } // Format path from object const formatted = path.format({ dir: '/home/user', name: 'document', ext: '.pdf' }); console.log(formatted); // '/home/user/document.pdf' // Path separator console.log(path.sep); // '/' ``` -------------------------------- ### Build Project via CMake Source: https://github.com/kaluma-project/kaluma/blob/master/targets/rp2/boards/rp2040-touch-lcd-1-28/README.md Compile the project for the specific board target using CMake. ```bash -DTARGET=rp2 -DBOARD=rp2040-touch-lcd-1-28 ``` -------------------------------- ### Perform HTTP Requests and Server Operations Source: https://context7.com/kaluma-project/kaluma/llms.txt Execute HTTP GET/POST requests or initialize a local HTTP server to handle incoming web traffic. ```javascript const http = require('http'); // HTTP GET request http.get({ host: 'api.example.com', port: 80, path: '/data' }, (res) => { console.log(`Status: ${res.statusCode}`); let body = ''; res.on('data', (chunk) => { body += String.fromCharCode.apply(null, chunk); }); res.on('end', () => { console.log('Response:', body); }); }); // HTTP POST request const req = http.request({ host: 'api.example.com', port: 80, method: 'POST', path: '/submit', headers: { 'Content-Type': 'application/json' } }, (res) => { console.log(`Status: ${res.statusCode}`); res.on('data', (chunk) => { console.log('Response:', String.fromCharCode.apply(null, chunk)); }); }); req.write(JSON.stringify({ key: 'value' })); req.end(); // Create HTTP server const server = http.createServer((req, res) => { console.log(`${req.method} ${req.url}`); if (req.url === '/api/data') { res.writeHead(200, 'OK', { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: 'ok', value: 42 })); } else { res.writeHead(200, 'OK', { 'Content-Type': 'text/html' }); res.end('

Hello from Kaluma!

'); } }); server.listen(80, () => { console.log('Server running on port 80'); }); ``` -------------------------------- ### Makefile Integration for Modules Source: https://github.com/kaluma-project/kaluma/blob/master/src/modules/README.md Adds a module's source files and include paths to the Kaluma build system via the Makefile. Ensure KALUMA_MODULE_ is defined to include the module. ```makefile ifdef KALUMA_MODULE_ KALUMA_SRC += src/modules//module_.c KALUMA_INC += -Isrc/modules/ endif ``` -------------------------------- ### Create PIO Assembly Programs with RP2 Module Source: https://context7.com/kaluma-project/kaluma/llms.txt Use the RP2 module to create and control PIO state machines for custom hardware protocols. Define programs using ASM and configure state machines with frequency, pin bases, and shift directions. ```javascript const { ASM, StateMachine, PIO } = require('rp2'); // Create PIO assembly program for blinking LED const asm = new ASM({ sideset: 1 }); asm.wrap_target() .set('pins', 1).delay(31) // Set pin high, delay .nop().delay(31) .nop().delay(31) .nop().delay(31) .set('pins', 0).delay(31) // Set pin low, delay .nop().delay(31) .nop().delay(31) .nop().delay(31) .wrap(); // Get available state machine ID const smId = StateMachine.getAvailableId(); // Create state machine with configuration const sm = new StateMachine(smId, asm, { freq: 2000, // 2kHz frequency setBase: 25, // Base pin for set instruction setCount: 1, // Number of set pins sidesetBase: 25 // Base pin for sideset }); // Start state machine sm.active(true); // WS2812 LED strip example const ws2812Asm = new ASM({ sideset: 1 }); ws2812Asm.label('bitloop') .out('x', 1).side(0).delay(2) .jmp('!x', 'do_zero').side(1).delay(1) .jmp('bitloop').side(1).delay(4) .label('do_zero') .nop().side(0).delay(4) .jmp('bitloop'); const ws2812Sm = new StateMachine(StateMachine.getAvailableId(), ws2812Asm, { freq: 800000 * 10, // WS2812 timing outBase: 16, // Data pin outCount: 1, sidesetBase: 16, outShiftDir: PIO.SHIFT_LEFT, autopull: true, pullThreshold: 24, fifoJoin: PIO.FIFO_JOIN_TX }); ws2812Sm.active(true); // Send RGB data (GRB format for WS2812) function setPixel(r, g, b) { const grb = (g << 16) | (r << 8) | b; ws2812Sm.put(grb << 8); } setPixel(255, 0, 0); // Red ``` -------------------------------- ### Flash Firmware to Raspberry Pi Pico Source: https://github.com/kaluma-project/kaluma/blob/master/targets/rp2/README.md Follow these steps to flash the compiled `.uf2` file to your Raspberry Pi Pico. Ensure the device is recognized as a USB Mass Storage device. ```text 1. Push and hold BOOTSEL button and plug into USB (recognized as a USB Mass Storage named `RPI-RP2`) 2. Drag and drop the `rpi-pico.uf2` on the `RPI-RP2` volume. 3. Automatically reboot. ``` -------------------------------- ### Communicate with AT-based devices Source: https://context7.com/kaluma-project/kaluma/llms.txt Use the ATCommand module to interface with modems or WiFi modules via UART. Requires the 'at' and 'uart' modules. ```javascript const { ATCommand } = require('at'); const { UART } = require('uart'); // Create UART for AT device const serial = new UART(1, { baudrate: 115200 }); // Create AT command handler const at = new ATCommand(serial, { debug: true, // Enable debug logging interval: 100 // Processing interval in ms }); // Send AT command and wait for response at.send('AT', (result) => { console.log('Result:', result); // 'OK' or 'ERROR' }); // Send with custom expected responses at.send('AT+CWJAP="SSID","PASSWORD"', (result) => { if (result === 'OK') { console.log('Connected to WiFi'); } else if (result === 'FAIL') { console.log('Connection failed'); } else if (result === 'TIMEOUT') { console.log('Command timed out'); } }, ['OK', 'FAIL', 'ERROR'], { timeout: 15000 }); // Add handler for unsolicited responses at.addHandler('+IPD', (line, buffer) => { // Parse incoming data const match = line.match(/\+IPD,(\d+):/); if (match) { const length = parseInt(match[1]); if (buffer.length >= length) { const data = buffer.substr(0, length); console.log('Received data:', data); return buffer.substr(length); // Return remaining buffer } return false; // Need more data } }); // Send raw data without appending \r\n at.send(new Uint8Array([0x01, 0x02, 0x03]), null, 100, { sendAsData: true }); // Remove handler at.removeHandler('+IPD'); // Close AT handler at.close(); ``` -------------------------------- ### Manage Wireless Connectivity with WiFi Module Source: https://context7.com/kaluma-project/kaluma/llms.txt Connect to networks, scan for access points, or host an access point using the WiFi module. ```javascript const { WiFi } = require('wifi'); const wifi = new WiFi(); // Event handlers wifi.on('associated', () => { console.log('Associated with access point'); }); wifi.on('connected', () => { console.log('Connected and got IP address'); }); wifi.on('disconnected', () => { console.log('Disconnected from network'); }); // Connect to WiFi network wifi.connect({ ssid: 'MyNetwork', password: 'MyPassword' }, (err, info) => { if (err) { console.error('Connection failed:', err); } else { console.log('Connected:', info); } }); // Scan for available networks wifi.scan((err, results) => { if (err) { console.error('Scan failed:', err); } else { results.forEach((ap) => { console.log(`SSID: ${ap.ssid}, RSSI: ${ap.rssi}`); }); } }); // Get current connection info wifi.getConnection((err, info) => { if (info) { console.log(`Connected to: ${info.ssid}`); } }); // Start access point mode wifi.wifiApMode({ ssid: 'Kaluma_AP', password: 'password123', gateway: '192.168.4.1', subnet_mask: '255.255.255.0' }, (err, info) => { if (!err) console.log('AP mode started'); }); // Disconnect wifi.disconnect((err) => { if (!err) console.log('Disconnected'); }); ``` -------------------------------- ### Module Configuration (module.json) Source: https://github.com/kaluma-project/kaluma/blob/master/src/modules/README.md Defines the properties of a Kaluma module, indicating if it's required, has a JavaScript implementation, or a native C implementation. ```json { "require": true, // if you want to import this module by `require()` "js": true, // has javascript impl. "native": true // has native C impl. } ``` -------------------------------- ### Mount LittleFS with Dynamic Filesystem Size Source: https://github.com/kaluma-project/kaluma/blob/master/targets/rp2/boards/kb2040/README.md This JavaScript code dynamically sizes the LittleFS filesystem based on the available flash memory. It calculates the number of sectors for the filesystem after accounting for firmware and storage partitions. ```javascript const total = new Flash().count; const bd = new Flash(132, total - 132); fs.mount("/", bd, "lfs", true); ``` -------------------------------- ### Using micro-Jest Matchers Source: https://github.com/kaluma-project/kaluma/blob/master/src/modules/__ujest/README.md An overview of the available matchers for assertions in micro-Jest. ```APIDOC ## Using micro-Jest Matchers Micro-Jest provides various matchers to test values. `toBe()` is used to test a value with exact equality. ### Request Example ```js test("1 + 1 = 2", (done) => { expect(1 + 1).toBe(2); done(); }); ``` Here is the list of matchers provided: - `expect(value).toBe(value)` - `expect(value).notToBe(value)` - `expect(value).toBeTruthy()` - `expect(value).toBeFalsy()` - `expect(number).toBeGreaterThan(number)` - `expect(number).toBeGreaterThanOrEqual(number)` - `expect(number).toBeLessThan(number)` - `expect(number).toBeLessThanOrEqual(number)` - `expect(array).toContain(value)` - `expect(array).notToContain(value)` - `expect(string).toMatch(regex)` - `expect(string).notToMatch(regex)` - `expect(function).toThrow([message])` - `expect(function).notToThrow([message])` ``` -------------------------------- ### Upload DFU File on macOS Source: https://github.com/kaluma-project/kaluma/blob/master/targets/stm32/README.md After connecting the board in DFU mode, use this command to upload the `.dfu` file. This is typically used for firmware updates via DFU. ```sh % dfu-util -a 0 -D kameleon-1.0.0.dfu ``` -------------------------------- ### Use toBe matcher Source: https://github.com/kaluma-project/kaluma/blob/master/src/modules/__ujest/README.md Verify exact equality of values using the toBe matcher. ```js test("1 + 1 = 2", (done) => { expect(1 + 1).toBe(2); done(); }); ``` -------------------------------- ### Implement Readable, Writable, and Duplex Streams Source: https://context7.com/kaluma-project/kaluma/llms.txt The stream module allows for the creation of abstract stream classes. Implement _read for Readable streams to provide data, _write for Writable streams to consume data, and both for Duplex streams. ```javascript const stream = require('stream'); const { EventEmitter } = require('events'); // Readable stream class SensorStream extends stream.Readable { constructor() { super(); } // Override to provide data _read() { // Called when consumer wants data } } const sensor = new SensorStream(); sensor.on('data', (chunk) => { console.log('Data:', chunk); }); sensor.on('end', () => { console.log('No more data'); }); // Writable stream class LogStream extends stream.Writable { _write(chunk, cb) { console.log('Writing:', String.fromCharCode.apply(null, chunk)); cb(); // Signal completion } _final(cb) { console.log('Stream finished'); cb(); } } const log = new LogStream(); log.write('Hello'); log.end('Goodbye'); log.on('finish', () => { console.log('All data written'); }); // Duplex stream (readable and writable) class TransformStream extends stream.Duplex { _write(chunk, cb) { // Process and push transformed data this.push(chunk); cb(); } _final(cb) { cb(); } } ``` -------------------------------- ### Handle Button Input with Debouncing Source: https://context7.com/kaluma-project/kaluma/llms.txt Implement event-driven button inputs with configurable debounce times and pin modes. ```javascript const { Button } = require('button'); // Create button with default options (INPUT_PULLUP, FALLING edge, 50ms debounce) const btn = new Button(15); // Listen for click events btn.on('click', () => { console.log('Button clicked!'); }); // Create button with custom options const btn2 = new Button(16, { mode: INPUT_PULLDOWN, // Pin mode event: RISING, // Trigger on rising edge debounce: 100 // Debounce time in ms }); btn2.on('click', () => { console.log('Button 2 clicked!'); }); // Read current button state const pressed = btn.read(); // Returns 0 or 1 // Clean up when done btn.close(); ``` -------------------------------- ### Kaluma Architecture Diagram Source: https://github.com/kaluma-project/kaluma/wiki/Internal Visual representation of Kaluma's layered architecture, showing the relationship between built-in JS modules, core runtime, hardware-neutral interfaces, and hardware-specific implementations. ```text +----------------------------------+ | Builtin JS Modules | # event, i2c, pwm, spi, uart, ... (src/modules/*) +----------------------------------+ | Core Runtime | # Event I/O, JavaScript Engine, REPL, ... (src/*.c) +----------------------------------+ | Hardware Neutral Interface | # system.h, gpio.h, uart.h, ... (include/port/*.h) +----------------------------------+ | Hardware Specific Implementation | # system.c, gpio.c, uart.c, ... (targets/*) +----------------------------------+ ``` -------------------------------- ### Control GPIO Pins with Kaluma Source: https://context7.com/kaluma-project/kaluma/llms.txt Manage digital input and output pins, including pull-up/down configurations and interrupt handling. ```javascript const { GPIO } = require('gpio'); // Create GPIO instance for pin 25 (built-in LED on Pico) const led = new GPIO(25, OUTPUT); // Write digital values led.write(1); // Set pin HIGH led.write(0); // Set pin LOW led.high(); // Shortcut for HIGH led.low(); // Shortcut for LOW led.toggle(); // Toggle current state // Read pin state const state = led.read(); // Returns 0 or 1 // Change pin mode dynamically led.setMode(INPUT_PULLUP); // Setup interrupt handler const button = new GPIO(15, INPUT_PULLUP); button.irq(() => { console.log('Button pressed!'); }, FALLING); // Trigger on falling edge (RISING, FALLING, CHANGE) ``` -------------------------------- ### Configure Serial Communication with UART Module Source: https://context7.com/kaluma-project/kaluma/llms.txt Manage serial data transmission and reception with configurable baud rates and flow control settings. ```javascript const { UART } = require('uart'); // Create UART instance const serial = new UART(0, { baudrate: 115200, bits: 8, parity: UART.PARITY_NONE, // PARITY_NONE, PARITY_ODD, PARITY_EVEN stop: 1, flow: UART.FLOW_NONE, // FLOW_NONE, FLOW_RTS, FLOW_CTS, FLOW_RTS_CTS bufferSize: 1024 }); // Send data serial.write('Hello, World!\r\n'); serial.write(new Uint8Array([0x48, 0x65, 0x6C, 0x6C, 0x6F])); // Receive data with event handler serial.on('data', (data) => { const str = String.fromCharCode.apply(null, data); console.log(`Received: ${str}`); }); // Echo example serial.on('data', (data) => { serial.write(data); // Echo back received data }); // Close when done serial.close(); ``` -------------------------------- ### Kaluma Repository Structure Source: https://github.com/kaluma-project/kaluma/wiki/Internal Overview of the Kaluma project's directory layout, indicating the purpose of each top-level folder and sub-directory. ```text lib/ # External libraries include/ # C headers └─ port # Hardware neutral interfaces src/ # C implementations ├─ gen # Generated source files (DOT NOT EDIT) └─ modules # JavaScript builtin modules └─ targets/ # Target implementations └─ / # A specific target (e.g. rp2, stm32, esp32, ...) ├─ include/ # header files ├─ src/ # Implementations of include/port/*.h ├─ boards/ # Supported boards of the target │ └─ / # A specific board (e.g. pico) └─ target.cmake # CMake for the target tools/ # Build tools ``` -------------------------------- ### Implement Observer Pattern with EventEmitter Source: https://context7.com/kaluma-project/kaluma/llms.txt Use the EventEmitter class to manage custom events, listeners, and event-driven logic. ```javascript const { EventEmitter } = require('events'); // Create custom event emitter class Sensor extends EventEmitter { constructor() { super(); this.value = 0; } update(newValue) { this.value = newValue; this.emit('change', newValue); if (newValue > 100) { this.emit('alarm', newValue); } } } const sensor = new Sensor(); // Add event listeners sensor.on('change', (value) => { console.log(`Value changed: ${value}`); }); sensor.once('alarm', (value) => { console.log(`ALARM! High value: ${value}`); }); // Emit events sensor.update(50); // Logs: "Value changed: 50" sensor.update(150); // Logs: "Value changed: 150" and "ALARM! High value: 150" // Remove listeners const handler = (v) => console.log(v); sensor.on('change', handler); sensor.removeListener('change', handler); sensor.removeAllListeners('change'); // Get listener info console.log(sensor.listenerCount('change')); console.log(sensor.listeners('change')); ``` -------------------------------- ### Reboot Raspberry Pi Source: https://github.com/kaluma-project/kaluma/blob/master/tests/onboard/README.md Reboot the Raspberry Pi after making configuration changes to apply them. ```bash $ sudo reboot ``` -------------------------------- ### Enable Wi-Fi 2.4G Scan on Raspberry Pi Source: https://github.com/kaluma-project/kaluma/blob/master/tests/onboard/README.md Use the raspi-config tool to enable Wi-Fi scanning. This involves navigating to Localization Options and changing the WLAN Country. ```bash $ sudo raspi-config # Localisation Options --> Change WLAN Country --> US --> Yes ``` -------------------------------- ### Enable UART on Raspberry Pi Source: https://github.com/kaluma-project/kaluma/blob/master/tests/onboard/README.md Configure the Raspberry Pi to enable UART for serial communication. This involves using raspi-config to enable the serial interface and modifying the cmdline.txt file to remove the console output. ```bash $ sudo raspi-config # Interfacing Options --> P6 Serial --> Yes $ sudo nano /boot/cmdline.txt # Delete the text "console=serial0,115200", and save ``` -------------------------------- ### Handling Errors in micro-Jest Source: https://github.com/kaluma-project/kaluma/blob/master/src/modules/__ujest/README.md Demonstrates how to handle and pass errors to the `done()` callback in both asynchronous and synchronous tests. ```APIDOC ## Handling Errors in micro-Jest If you catch an error you can pass it to `done()` callback. ### Request Example (Async) ```javascript // async test('adds 1 + 2 to equal 3', (done) => { someAsyncFunction(err => { if (err) { done(err); } else { expect(...).toBe(...); done(); } }) }); ``` ### Request Example (Sync) ```javascript // sync test('adds 1 + 2 to equal 3', (done) => { try { someSyncFunction(); done(); } catch(err) { done(err); } }); ``` ``` -------------------------------- ### Clean Build Artifacts Source: https://github.com/kaluma-project/kaluma/wiki/Build Removes existing build artifacts from the project. ```sh $ node build --clean ``` -------------------------------- ### Parse and Manipulate URLs with the URL Module Source: https://context7.com/kaluma-project/kaluma/llms.txt Use the URL module to parse URL strings and access their components. It also provides functionality for working with URL search parameters. ```javascript const { URL, URLSearchParams } = require('url'); // Parse URL const url = new URL('https://user:pass@example.com:8080/path/page?foo=bar&baz=qux#section'); console.log(url.protocol); // 'https:' console.log(url.username); // 'user' console.log(url.password); // 'pass' console.log(url.hostname); // 'example.com' console.log(url.port); // '8080' console.log(url.host); // 'example.com:8080' console.log(url.pathname); // '/path/page' console.log(url.search); // '?foo=bar&baz=qux' console.log(url.hash); // 'section' console.log(url.origin); // 'https://user:pass@example.com:8080' console.log(url.href); // Full URL string // Work with search parameters console.log(url.searchParams.get('foo')); // 'bar' console.log(url.searchParams.has('baz')); // true console.log(url.searchParams.getAll('foo')); // ['bar'] // URLSearchParams standalone const params = new URLSearchParams('name=John&age=30'); params.append('city', 'NYC'); params.set('age', '31'); params.delete('city'); console.log(params.toString()); // 'name=John&age=31' console.log(params.keys()); // ['name', 'age'] console.log(params.values()); // ['John', '31'] console.log(params.entries()); // [['name', 'John'], ['age', '31']] ``` -------------------------------- ### Add micro-Jest dependency Source: https://github.com/kaluma-project/kaluma/blob/master/src/modules/__ujest/README.md Include the micro-Jest package in your project's package.json file. ```json { dependencies: { "@niklauslee/micro-jest": } } ``` -------------------------------- ### Read Analog Sensors with ADC Module Source: https://context7.com/kaluma-project/kaluma/llms.txt Utilize the ADC module to read analog pins or internal sensors like the RP2040 temperature sensor. ```javascript const { ADC } = require('adc'); // Create ADC instance for analog pin const adc = new ADC(26); // ADC0 on Pico // Read analog value (returns 0-4095 for 12-bit ADC) const value = adc.read(); console.log(`ADC value: ${value}`); // Convert to voltage (assuming 3.3V reference) const voltage = (value / 4095) * 3.3; console.log(`Voltage: ${voltage.toFixed(2)}V`); // Read temperature sensor (RP2040 internal) const { TEMPERATURE_ADC } = require('rp2'); const tempAdc = new ADC(TEMPERATURE_ADC); // Continuous reading with interval setInterval(() => { const raw = tempAdc.read(); // Convert to temperature (RP2040 specific formula) const temp = 27 - (raw * 3.3 / 4096 - 0.706) / 0.001721; console.log(`Temperature: ${temp.toFixed(1)}C`); }, 1000); ``` -------------------------------- ### Handle errors in tests Source: https://github.com/kaluma-project/kaluma/blob/master/src/modules/__ujest/README.md Pass errors to the done callback to report failures in both asynchronous and synchronous test scenarios. ```javascript // async test('adds 1 + 2 to equal 3', (done) => { someAsyncFunction(err => { if (err) { done(err); } else { expect(...).toBe(...); done(); } }) }); // sync test('adds 1 + 2 to equal 3', (done) => { try { someSyncFunction(); done(); } catch(err) { done(err); } }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.