### DeviceSDK Init with Empty Template Source: https://devicesdk.com/docs/cli/init Initialize a project using the empty template, providing a minimal setup with no example code. ```bash devicesdk init my-project --template empty ``` -------------------------------- ### Initialize a new project Source: https://devicesdk.com/docs/quickstart Creates a new directory with the necessary configuration and example files. ```bash npx @devicesdk/cli init hello-world ``` -------------------------------- ### Complete Example: LED Controller Source: https://devicesdk.com/docs/first-device A full example demonstrating how to control an LED. It configures a GPIO pin for input monitoring and toggles an LED based on button presses. ```typescript import { DeviceEntrypoint, type DeviceResponse } from '@devicesdk/core'; export default class LEDController extends DeviceEntrypoint { async onDeviceConnect() { // Configure button input on GPIO 20 await this.env.DEVICE.configureGpioInputMonitoring(20, true, "up"); console.info(`Device initialized`); } async onMessage(message: DeviceResponse) { if (message.type === 'gpio_state_changed' && message.payload.pin === 20) { // Button pressed (pulled low) if (message.payload.state === 'low') { // Toggle LED await this.env.DEVICE.setGpioState(25, "high"); console.info('LED ON'); } else { await this.env.DEVICE.setGpioState(25, "low"); console.info('LED OFF'); } } } async onDeviceDisconnect() { console.info(`Device disconnected`); } } ``` -------------------------------- ### Start DeviceSDK Development Server Source: https://devicesdk.com/docs/resources/faq Use this command to start the DeviceSDK development server. This allows you to test your IoT applications without physical hardware. ```bash devicesdk dev ``` -------------------------------- ### Install esptool Source: https://devicesdk.com/docs/cli/flash Install the esptool utility for ESP32 flashing. This is a prerequisite for flashing ESP32 devices. ```bash pip install esptool ``` -------------------------------- ### Install DeviceSDK CLI Source: https://devicesdk.com/docs/cli Install the CLI globally using npm. This command makes the `devicesdk` command available system-wide. ```bash npm install -g @devicesdk/cli ``` -------------------------------- ### DeviceSDK Init with Basic Template Source: https://devicesdk.com/docs/cli/init Initialize a project using the basic template, which includes a single device with an LED blink example. ```bash devicesdk init my-project --template basic ``` -------------------------------- ### Example status output Source: https://devicesdk.com/docs/cli/status Sample output format showing device connection details. ```text Project: my-project DEVICE STATUS VERSION LAST SEEN ───────────────────────────────────────────────────── temperature-sensor ● online a1b2c3d4 connected 2m ago humidity-sensor ○ offline a1b2c3d4 5h ago door-sensor ○ offline — never ``` -------------------------------- ### Interactive SPI CLI Examples Source: https://devicesdk.com/docs/guides/using-spi Example usage of the CLI to configure, transfer, write, and read data over SPI. ```bash > spi configure 0 18 19 16 17 1000000 0 OK > spi transfer 0 0x8F 0x00 SPI transfer on bus 0: [0x00, 0x33] > spi write 0 0x20 0x47 OK > spi read 0 4 SPI read from bus 0: [0x12, 0x34, 0x56, 0x78] ``` -------------------------------- ### Verify esptool installation Source: https://devicesdk.com/docs/cli/flash Verify that the esptool has been installed correctly by checking its version. ```bash esptool.py version ``` -------------------------------- ### Interactive REPL Session Example Source: https://devicesdk.com/docs/cli/inspect Demonstrates an interactive session with the devicesdk inspect command, showing command execution and responses for GPIO and I2C operations. ```bash Connecting to device "temperature-sensor" in project "my-project"... Type "help" for available commands, "exit" to quit. devicesdk:temperature-sensor> gpio read 5 Pin 5: HIGH devicesdk:temperature-sensor> i2c scan Found 1 device(s) on bus 0: 0x48 devicesdk:temperature-sensor> i2c read 0 0x48 2 Read from 0x48: [0x1A, 0xC0] devicesdk:temperature-sensor> exit Goodbye. ``` -------------------------------- ### Cron Field Syntax Examples Source: https://devicesdk.com/docs/concepts/cron-scheduling Examples of cron field syntax including any value, specific value, every N units, range, list of values, and range with step. ```text Syntax | Example | Meaning ---|---|-- `*` | `*` | Any value `N` | `5` | Specific value `*/N` | `*/15` | Every N units `N-M` | `1-5` | Range (inclusive) `N,M` | `0,30` | List of values `N-M/S` | `0-30/10` | Range with step ``` -------------------------------- ### Example CLI Usage for WS2812 LEDs Source: https://devicesdk.com/docs/guides/addressable-leds Demonstrates the usage of `ws2812 configure` and `ws2812 fill` commands. The `fill` command sets all LEDs to the specified color and requires the number of LEDs to match the configured count. ```bash > ws2812 configure 2 16 OK ``` ```bash > ws2812 fill 255 0 0 16 OK ``` ```bash > ws2812 fill 0 0 0 16 OK ``` -------------------------------- ### Execute CLI Commands Source: https://devicesdk.com/docs/resources/troubleshooting Run CLI commands using npx or via global installation. ```bash npx @devicesdk/cli [command] ``` ```bash npm install -g @devicesdk/cli ``` -------------------------------- ### Verify CLI Version Source: https://devicesdk.com/docs/resources/troubleshooting Check the installed version of the DeviceSDK CLI. ```bash npx @devicesdk/cli@latest --version ``` -------------------------------- ### Get Help for DeviceSDK Command Source: https://devicesdk.com/docs/cli Display detailed usage information for any DeviceSDK CLI command by appending the `--help` flag. This is useful for understanding command-specific options. ```bash npx @devicesdk/cli deploy --help ``` -------------------------------- ### Run DeviceSDK CLI with npx Source: https://devicesdk.com/docs/cli Execute the DeviceSDK CLI commands directly without global installation using npx. Replace `[command]` with the desired CLI command. ```bash npx @devicesdk/cli [command] ``` -------------------------------- ### Enable Verbose Logging Source: https://devicesdk.com/docs/resources/troubleshooting To get more detailed output during deployment, use the --verbose flag with the deploy command. This is useful for debugging. ```bash devicesdk deploy --verbose ``` -------------------------------- ### Inter-Device Communication Example Source: https://devicesdk.com/docs/resources/faq Example of how devices within the same project can call methods on each other. This utilizes types generated in `devicesdk-env.d.ts` for type safety. The `onMessage` method is called when a message is received from a device. ```typescript import type { Env } from '../../devicesdk-env'; export class Sensor extends DeviceEntrypoint { async onMessage(message: DeviceResponse) { // Call a method on another device — fully typed with autocomplete const result = await this.env.DEVICES['light-controller'].turnOn(); console.info('Light status:', result.status); } } ``` -------------------------------- ### JSON Message Protocol Example Source: https://devicesdk.com/docs/concepts/architecture Standard JSON structure used for device-to-cloud communication. ```json { "type": "gpio_write", "pin": 25, "value": 1 } ``` -------------------------------- ### Hardcoded Secret Example Source: https://devicesdk.com/docs/concepts/env-vars Demonstrates the insecure practice of hardcoding secrets directly in source code. ```javascript // ❌ Secret in source code — visible in version history const DISCORD_WEBHOOK_URL = "https://discord.com/api/webhooks/YOUR_WEBHOOK_URL"; ``` -------------------------------- ### Rainbow Animation Example Source: https://devicesdk.com/docs/guides/addressable-leds Creates a smooth rainbow cycle across a strip of LEDs. Includes a helper function for HSV to RGB conversion. Ensure the hsvToRgb function is available in your scope. ```typescript import { DeviceEntrypoint } from '@devicesdk/core'; const LED_PIN = 2; const NUM_LEDS = 16; export default class RainbowDevice extends DeviceEntrypoint { async onDeviceConnect() { await this.env.DEVICE.pioWs2812Configure(LED_PIN, NUM_LEDS); // Run 100 frames of rainbow animation for (let frame = 0; frame < 100; frame++) { const pixels: [number, number, number][] = []; for (let i = 0; i < NUM_LEDS; i++) { // Each LED is offset in hue, and the whole pattern shifts each frame const hue = ((i * 360) / NUM_LEDS + frame * 5) % 360; pixels.push(hsvToRgb(hue, 1.0, 0.3)); // 30% brightness to save power } await this.env.DEVICE.pioWs2812Update(pixels); await new Promise(r => setTimeout(r, 50)); } // Turn off all LEDs when done const off: [number, number, number][] = Array.from({ length: NUM_LEDS }, () => [0, 0, 0]); await this.env.DEVICE.pioWs2812Update(off); } } /** Convert HSV (hue 0-360, saturation 0-1, value 0-1) to RGB [0-255, 0-255, 0-255]. */ function hsvToRgb(h: number, s: number, v: number): [number, number, number] { const c = v * s; const x = c * (1 - Math.abs(((h / 60) % 2) - 1)); const m = v - c; let r = 0, g = 0, b = 0; if (h < 60) { r = c; g = x; } else if (h < 120) { r = x; g = c; } else if (h < 180) { g = c; b = x; } else if (h < 240) { g = x; b = c; } else if (h < 300) { r = x; b = c; } else { r = c; b = x; } return [ Math.round((r + m) * 255), Math.round((g + m) * 255), Math.round((b + m) * 255), ]; } ``` -------------------------------- ### devicesdk flash Source: https://devicesdk.com/docs/cli/flash Flashes the DeviceSDK firmware to your microcontroller. This command is typically used once per device for initial setup, with subsequent updates handled over-the-air (OTA). ```APIDOC ## POST /devicesdk/flash ### Description Flashes the DeviceSDK firmware to Raspberry Pi Pico and ESP32 devices. This process embeds device credentials for authentication and association with your project, enabling secure communication. ### Method POST ### Endpoint /devicesdk/flash ### Parameters #### Path Parameters - **device-id** (string) - Required - The unique identifier for the device to be flashed. #### Query Parameters - **config** (string) - Optional - Path to the `devicesdk.ts` config file. Defaults to auto-detection. - **timeout** (integer) - Optional - Time in milliseconds to wait for the device. Defaults to 30000 for Pico and 60000 for ESP32. - **port** (string) - Optional - Serial port for ESP32 flashing (e.g., `/dev/ttyUSB0`). Defaults to auto-detection. - **baud** (integer) - Optional - Baud rate for ESP32 flashing. Defaults to 460800. - **before** (string) - Optional - Reset method before flashing. Options are `default_reset` or `no_reset`. Defaults to `default_reset`. - **host** (string) - Optional - Custom URL to download firmware from. Defaults to the Production API. ### Request Example ```json { "device-id": "my-esp32-device", "config": "./devicesdk.ts", "timeout": 60000, "port": "/dev/ttyUSB0", "baud": 460800, "before": "default_reset", "host": "https://api.example.com" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the flashing operation. - **message** (string) - A confirmation message. #### Response Example ```json { "status": "success", "message": "Firmware flashed successfully to device my-esp32-device." } ``` ### Error Handling - **400 Bad Request**: Invalid parameters or configuration. - **500 Internal Server Error**: An error occurred during the flashing process. ``` -------------------------------- ### Inter-Device Communication Setup Source: https://devicesdk.com/docs/concepts/entrypoints Enable type-safe inter-device communication by extending `DeviceEntrypoint` with an `Env` type and using `this.env.DEVICES` to call public methods on other devices within the same project. ```typescript import { DeviceEntrypoint, type DeviceResponse } from '@devicesdk/core'; import type { Env } from '../../devicesdk-env'; export class Sensor extends DeviceEntrypoint { async onMessage(message: DeviceResponse) { if (message.type === 'gpio_state_changed' && message.payload.pin === 20) { // Type-safe call to another device's public method const result = await this.env.DEVICES['led-controller'].turnOn(); console.info('Light turned on:', result); } } } ``` -------------------------------- ### Change DeviceSDK Port Source: https://devicesdk.com/docs/resources/troubleshooting If the DeviceSDK simulator fails to start due to a port conflict, use this command to specify an alternative port. ```bash devicesdk dev --port 3001 ``` -------------------------------- ### Receiving and Processing Device Messages Source: https://devicesdk.com/docs/first-device Use the `onMessage` method to handle different message types from devices. This example shows how to process pin state updates and respond to GPIO state changes. ```typescript async onMessage(message: DeviceResponse) { switch (message.type) { case 'pin_state_update': // Store sensor data console.info(`Pin ${message.payload.pin}: ${message.payload.value}`); break; case 'gpio_state_changed': // Respond to button press await this.env.DEVICE.setGpioState(99, "high"); break; } } ``` -------------------------------- ### Flash Multiple Devices Sequentially Source: https://devicesdk.com/docs/cli/flash To flash multiple devices, run the devicesdk flash command for each device sequentially. Ensure you wait for the completion of one flash operation before starting the next. ```bash devicesdk flash sensor-1 # Wait for completion, switch device devicesdk flash sensor-2 # Repeat... ``` -------------------------------- ### DeviceSDK Init with Defaults Source: https://devicesdk.com/docs/cli/init Create a new project using the 'init' command with the --yes flag to skip interactive prompts and use default settings. ```bash devicesdk init my-iot-app --yes ``` -------------------------------- ### DeviceSDK Init in Current Directory Source: https://devicesdk.com/docs/cli/init Create a new project in the current directory by specifying '.' as the project name and using the --yes flag for default settings. ```bash mkdir my-project && cd my-project devicesdk init . --yes ``` -------------------------------- ### DeviceSDK Init with Multi-Device Template Source: https://devicesdk.com/docs/cli/init Initialize a project using the multi-device template, which sets up multiple device entrypoints. ```bash devicesdk init my-project --template multi-device ``` -------------------------------- ### Navigate to Project Directory Source: https://devicesdk.com/docs/cli/init After creating a project, use the 'cd' command to navigate into the newly created project directory. ```bash cd my-project ``` -------------------------------- ### DeviceSDK Init with Specific Template Source: https://devicesdk.com/docs/cli/init Initialize a project with a specific template, such as 'multi-device', using the --template flag. ```bash devicesdk init sensor-network --template multi-device ``` -------------------------------- ### Read GPS Data Over UART Source: https://devicesdk.com/docs/guides/using-uart Example implementation for reading NMEA sentences from a GPS module. ```typescript import { DeviceEntrypoint, type DeviceResponse } from '@devicesdk/core'; const GPS_TX_PIN = 4; // Microcontroller TX -> GPS RX (if needed) const GPS_RX_PIN = 5; // GPS TX -> Microcontroller RX const GPS_PORT = 1; export default class GpsDevice extends DeviceEntrypoint { async onDeviceConnect() { // GPS modules typically communicate at 9600 baud await this.env.DEVICE.uartConfigure(GPS_PORT, GPS_TX_PIN, GPS_RX_PIN, 9600); // Read GPS data in a loop for (let i = 0; i < 60; i++) { const result = await this.env.DEVICE.uartRead(GPS_PORT, 256, 1000); if (result.type === 'uart_read_result' && result.payload.bytes_read > 0) { const text = hexToAscii(result.payload.data); const lines = text.split('\r\n'); for (const line of lines) { // $GPGGA contains position fix data if (line.startsWith('$GPGGA')) { console.log('GPS fix:', line); await this.env.DEVICE.persistLog('info', `GPS: ${line}`); } } } await new Promise(r => setTimeout(r, 1000)); } } } function hexToAscii(hexBytes: string[]): string { return hexBytes .map(h => String.fromCharCode(parseInt(h, 16))) .join(''); } ``` -------------------------------- ### Deploying to All Devices Source: https://devicesdk.com/docs/concepts/versioning Activates the new version across all devices immediately. ```bash devicesdk deploy ``` -------------------------------- ### Handle Remote Call Errors Source: https://devicesdk.com/docs/guides/inter-device-communication Example of wrapping remote RPC calls in a try/catch block to handle potential runtime errors. ```typescript async onMessage(message: DeviceResponse) { if (message.type === 'gpio_state_changed') { try { await this.env.DEVICES['light-controller'].turnOn(); } catch (error) { console.error('Failed to call light controller:', error); } } } ``` -------------------------------- ### DeviceSDK Init Command Usage Source: https://devicesdk.com/docs/cli/init Use this command to create a new DeviceSDK project. You can specify the project name and use flags to customize the initialization process. ```bash devicesdk init [project-name] [flags] ``` -------------------------------- ### Deploying Device Code Source: https://devicesdk.com/docs/first-device Deploy your tested device code to the platform using the CLI. ```bash npx @devicesdk/cli deploy ``` -------------------------------- ### Build Project Source: https://devicesdk.com/docs/guides/inter-device-communication Command to build the project and generate environment types. ```bash devicesdk build # Output: # ✓ Generated devicesdk-env.d.ts # ✓ Built light-controller.js (2.1 KB) # ✓ Built sensor.js (1.8 KB) ``` -------------------------------- ### DeviceSDK Init Interactive Mode Source: https://devicesdk.com/docs/cli/init Run the init command without flags to enter interactive mode, where you will be prompted for project name, template selection, and initial device name. ```bash devicesdk init my-project ``` -------------------------------- ### Deploying with a Message via CLI Source: https://devicesdk.com/docs/concepts/versioning Creates a new version with an optional deployment message. ```bash devicesdk deploy --message "Add temperature sensor support" ``` -------------------------------- ### CLI Inspect Commands for WS2812 LEDs Source: https://devicesdk.com/docs/guides/addressable-leds Use these CLI commands to interactively test WS2812 LEDs. The `configure` command initializes the LEDs, and the `fill` command sets their color. Ensure the number of LEDs matches the configured count. ```bash ws2812 configure ``` ```bash ws2812 fill ``` -------------------------------- ### Flashing Firmware to Hardware Source: https://devicesdk.com/docs/first-device After deploying, flash the firmware to your physical device. ```bash npx @devicesdk/cli flash ``` -------------------------------- ### Deploy DeviceSDK Project with Token Source: https://devicesdk.com/docs/resources/faq Deploy your DeviceSDK project using the CLI. You need to set the DEVICESDK_TOKEN environment variable with your deployment token. ```bash DEVICESDK_TOKEN=xxx devicesdk deploy ``` -------------------------------- ### Deploy with Message Source: https://devicesdk.com/docs/cli/deploy Deploys device scripts and adds a descriptive message to the version history. Use the --message flag followed by the message text. ```bash devicesdk deploy --message "Fix temperature reading bug" ``` ```bash devicesdk deploy --message "Add humidity sensor support" ``` -------------------------------- ### Navigate to project directory Source: https://devicesdk.com/docs/quickstart Changes the current working directory to the newly created project folder. ```bash cd hello-world ``` -------------------------------- ### Open Inspect Session Source: https://devicesdk.com/docs/cli/inspect Initiates an interactive REPL session for a specified device. The device must be online and connected to the DeviceSDK platform. ```bash devicesdk inspect temperature-sensor ``` -------------------------------- ### Testing Device Code with the Simulator Source: https://devicesdk.com/docs/first-device Run the local simulator to test your device code before deploying. This provides a virtual environment for GPIO pins, buttons, and sensor readings. ```bash npx @devicesdk/cli dev ``` -------------------------------- ### Common Cron Expression Examples Source: https://devicesdk.com/docs/concepts/cron-scheduling Common cron expressions and their corresponding schedule descriptions, such as every minute, every 5 minutes, every hour, daily at 08:00 UTC, weekdays at 08:00 UTC, and the first day of every month. ```text Expression | Schedule ---|--- `* * * * *` | Every minute `*/5 * * * *` | Every 5 minutes `0 * * * *` | Every hour (on the hour) `0 8 * * *` | Daily at 08:00 UTC `0 8 * * 1-5` | Weekdays at 08:00 UTC `0 0 1 * *` | First day of every month ``` -------------------------------- ### Configure Project Devices Source: https://devicesdk.com/docs/guides/inter-device-communication Defines the project configuration including device entrypoints and hardware types. ```typescript // devicesdk.ts import { defineConfig } from '@devicesdk/cli'; export default defineConfig({ projectId: 'smart-home', devices: { 'light-controller': { main: './src/devices/light.ts', entrypoint: 'LightController', deviceType: 'pico-w', wifi: { ssid: '...', password: '...' }, }, 'sensor': { main: './src/devices/sensor.ts', entrypoint: 'Sensor', deviceType: 'pico-w', wifi: { ssid: '...', password: '...' }, }, }, }); ``` -------------------------------- ### Listing Environment Variables via CLI Source: https://devicesdk.com/docs/concepts/env-vars Displays a list of configured environment variable keys. ```bash devicesdk env list # Output: # KEY UPDATED AT # ───────────────────────────────────────────────── # DISCORD_WEBHOOK_URL 2024-01-15 10:23:00 # API_KEY 2024-01-10 09:00:00 ``` -------------------------------- ### devicesdk inspect Source: https://devicesdk.com/docs/cli/inspect Opens an interactive REPL for sending hardware commands to a connected device. The device must be online. ```APIDOC ## POST /devicesdk/inspect ### Description Opens an interactive REPL (Read-Eval-Print Loop) to send hardware commands directly to a connected device and see the results in real time. Useful for debugging hardware, testing pin states, and exploring I2C peripherals. ### Method POST ### Endpoint `/devicesdk/inspect` ### Parameters #### Path Parameters - **device** (string) - Required - Device slug to connect to. #### Query Parameters - **project** (string) - Optional - Project ID (overrides config file). - **config** (string) - Optional - Path to config file (default: `devicesdk.ts`). ### Request Example ```json { "command": "gpio read 5" } ``` ### Response #### Success Response (200) - **output** (string) - The result of the executed command. #### Response Example ```json { "output": "Pin 5: HIGH" } ``` ### Available Commands in REPL - `gpio read `: Read digital pin state (HIGH or LOW). - `gpio write high|low`: Set a GPIO output pin. - `adc read `: Read analog pin value. - `pwm `: Set PWM output. - `i2c scan [bus]`: Scan for I2C devices on a bus (default: bus 0). - `i2c configure [freq]`: Configure I2C bus pins and frequency. - `i2c read [register]`: Read bytes from an I2C device. - `i2c write `: Write bytes to an I2C device. - `monitor [up|down|none]`: Enable GPIO input change monitoring. - `reboot`: Reboot the device (prompts for confirmation). - `help`: Show available commands. - `exit` / `quit` / Ctrl-C: Exit inspect mode. ``` -------------------------------- ### Flash Pico W Source: https://devicesdk.com/docs/cli/flash Basic command to flash a Raspberry Pi Pico W. Ensure the Pico is in BOOTSEL mode before running. ```bash devicesdk flash my-sensor-001 ``` -------------------------------- ### Environment Bindings (this.env.DEVICE) Source: https://devicesdk.com/docs/concepts/entrypoints Methods available via the environment binding to interact with hardware and persistent storage. ```APIDOC ## Environment Bindings ### setGpioState Sets the state of a specific GPIO pin. - **pin** (number) - The pin number. - **state** (string) - The state to set (e.g., "high"). ### reboot Reboots the connected device. ### kv.put Stores a value in the device's KV storage. - **key** (string) - The key to store. - **value** (string) - The value to store. ### kv.get Retrieves a value from the device's KV storage. - **key** (string) - The key to retrieve. ``` -------------------------------- ### Flash using custom host Source: https://devicesdk.com/docs/cli/flash Flash a device using firmware downloaded from a custom host URL instead of the production API. ```bash devicesdk flash my-device --host http://192.168.1.238:8787 ``` -------------------------------- ### View logs command usage Source: https://devicesdk.com/docs/cli/logs Basic syntax for the devicesdk logs command. ```bash devicesdk logs [options] ``` -------------------------------- ### Basic Device Entrypoint Structure Source: https://devicesdk.com/docs/first-device Extend the DeviceEntrypoint class to handle device connections, messages, and disconnections. Ensure necessary imports from '@devicesdk/core'. ```typescript import { DeviceEntrypoint, type DeviceResponse } from '@devicesdk/core'; export default class MyDevice extends DeviceEntrypoint { async onDeviceConnect() { // Called when a device connects console.log(`Device connected`); } async onMessage(message: DeviceResponse) { // Called when a device sends a message console.log(`Received from`, message); } async onDeviceDisconnect() { // Called when a device disconnects console.log(`Device disconnected`); } } ``` -------------------------------- ### Log Information from Device Entrypoint Source: https://devicesdk.com/docs/concepts/entrypoints Utilize standard `console` methods (`info`, `error`, `warn`) within your device entrypoint. All output is automatically captured and accessible in the dashboard. ```typescript console.info('Device connected'); console.error('Sensor reading failed', error); console.warn('Temperature threshold exceeded', { temp: 85 }); ``` -------------------------------- ### Configure Addressable LEDs Source: https://devicesdk.com/docs/guides/addressable-leds Initialize the PIO state machine for WS2812 protocol timing on the specified pin. Call this once during onDeviceConnect(). ```typescript // Configure 16 WS2812 LEDs on pin GP2 await this.env.DEVICE.pioWs2812Configure(2, 16); ``` -------------------------------- ### Deploy Specific Device Source: https://devicesdk.com/docs/cli/deploy Deploys device scripts to a single, specified device. Use the --device flag followed by the device name. ```bash devicesdk deploy --device temperature-sensor ``` -------------------------------- ### Integrating Deployment with GitHub Actions Source: https://devicesdk.com/docs/concepts/versioning Automates deployment in a CI/CD pipeline using a token and the current git tag as the version message. ```yaml - name: Deploy env: DEVICESDK_TOKEN: ${{ secrets.DEVICESDK_TOKEN }} run: | VERSION=$(git describe --tags) npx @devicesdk/cli deploy --message "Release $VERSION" ``` -------------------------------- ### Implement Chained Device Calls Source: https://devicesdk.com/docs/guides/inter-device-communication Demonstrates a device calling another device, which in turn calls a third device. Ensure all arguments and return values are JSON-compatible. ```javascript // Device A calls B await this.env.DEVICES['device-b'].doSomething(); // Device B's doSomething() calls C async doSomething() { await this.env.DEVICES['device-c'].finalize(); return { done: true }; } ``` -------------------------------- ### Tail logs with custom initial batch Source: https://devicesdk.com/docs/cli/logs Stream logs while specifying the number of initial lines to display. ```bash devicesdk logs my-project my-device --tail --lines 100 ``` -------------------------------- ### GitHub Actions CI/CD Deployment Source: https://devicesdk.com/docs/cli/deploy Automates the deployment of device scripts using GitHub Actions. Requires checking out the code, setting up Node.js, and providing the DEVICESDK_TOKEN as a secret. ```yaml name: Deploy on: push: branches: [main] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Node.js uses: actions/setup-node@v3 with: node-version: '22' - name: Deploy env: DEVICESDK_TOKEN: ${{ secrets.DEVICESDK_TOKEN }} run: npx @devicesdk/cli deploy --message "Deploy from CI" ``` -------------------------------- ### Verify Deployment Status Source: https://devicesdk.com/docs/resources/troubleshooting Check current authentication status and build state before deploying. ```bash devicesdk whoami ``` ```bash devicesdk build ``` -------------------------------- ### Interact with Device Hardware and Storage Source: https://devicesdk.com/docs/concepts/entrypoints Access environment bindings via `this.env.DEVICE` to send commands like setting GPIO states or rebooting, and to interact with Key-Value (KV) storage for data persistence. ```typescript // Send commands to the device await this.env.DEVICE.setGpioState(25, "high"); await this.env.DEVICE.reboot(); // Access KV storage await this.env.DEVICE.kv.put('key', 'value'); const value = await this.env.DEVICE.kv.get('key'); ``` -------------------------------- ### Dry Run Deployment Source: https://devicesdk.com/docs/cli/deploy Previews a deployment without actually making any changes. Use the --dry-run flag to simulate the deployment process. ```bash devicesdk deploy --dry-run ``` -------------------------------- ### DeviceSDK Configuration Source: https://devicesdk.com/docs/cli Configure DeviceSDK by defining device mappings in `devicesdk.ts`. This file should be located at the root of your project. ```typescript export default { devices: { 'my-device': './src/devices/my-device.ts' } } ``` -------------------------------- ### Build Project Locally Source: https://devicesdk.com/docs/cli/deploy Builds the project locally, typically to fix TypeScript errors before deployment. This command should be run before executing the devicesdk deploy command. ```bash npm run build ``` -------------------------------- ### GitLab CI Deployment Source: https://devicesdk.com/docs/cli/deploy Sets up a GitLab CI pipeline to deploy device scripts. The deployment is triggered on pushes to the main branch and requires the DEVICESDK_TOKEN to be configured in GitLab's CI/CD variables. ```yaml deploy: script: - npx @devicesdk/cli deploy --message "Deploy from CI" only: - main ``` -------------------------------- ### Configure Multiple Device Types in a Project Source: https://devicesdk.com/docs/concepts/entrypoints Define multiple device types within a single project by exporting an object with a `devices` property. Each key represents a device type, and its value is the path to its entrypoint file. ```typescript // devicesdk.ts export default { devices: { 'temperature-sensor': './src/devices/temp-sensor.ts', 'motion-detector': './src/devices/motion.ts', 'led-controller': './src/devices/led.ts' } } ``` -------------------------------- ### Stream logs in real time Source: https://devicesdk.com/docs/cli/logs Continuously output new log entries as they arrive on the device. ```bash devicesdk logs my-project my-device --tail ``` -------------------------------- ### Handling Device Connections Source: https://devicesdk.com/docs/first-device Implement the `onDeviceConnect` method to initialize device state, such as updating a status in key-value storage. ```typescript async onDeviceConnect() { // Initialize device state await this.env.DEVICE.kv.put('status', 'online'); } ``` -------------------------------- ### Specify Project for Inspect Session Source: https://devicesdk.com/docs/cli/inspect Opens an inspect session for a device while explicitly setting the project ID. This overrides the project ID configured in the config file. ```bash devicesdk inspect temperature-sensor --project my-project-id ``` -------------------------------- ### Configure Addressable LEDs Source: https://devicesdk.com/docs/resources/hardware Configure PIO for WS2812/NeoPixel LED strips, specifying the data pin and the number of LEDs. ```typescript // Configure 8 LEDs on pin 2 await this.env.DEVICE.pioWs2812Configure(2, 8); ``` -------------------------------- ### Flash ESP32 with manual boot mode Source: https://devicesdk.com/docs/cli/flash Flash an ESP32 device when it does not auto-reset into download mode. Use the --before no_reset flag and manually trigger boot mode. ```bash devicesdk flash my-device --before no_reset ``` -------------------------------- ### Check Node.js Version Source: https://devicesdk.com/docs/resources/troubleshooting Verify the current Node.js version; version 22+ is required. ```bash node --version ``` -------------------------------- ### Setting Environment Variables via CLI Source: https://devicesdk.com/docs/concepts/env-vars Configures environment variables for a project using the CLI. ```bash # Set a single variable devicesdk env set DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/... # Set multiple variables at once devicesdk env set API_KEY=abc123 REGION=us-east-1 # Target a specific project devicesdk env set API_KEY=abc123 --project my-project ``` -------------------------------- ### Manage environment variables Source: https://devicesdk.com/docs/quickstart Sets and retrieves project-scoped environment variables to store sensitive information. ```bash npx @devicesdk/cli env set DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/... ``` ```typescript const webhookUrl = await this.env.VARS.get("DISCORD_WEBHOOK_URL"); ``` -------------------------------- ### Sending Commands to Devices Source: https://devicesdk.com/docs/first-device Utilize typed methods within the environment bindings to send commands to devices, such as controlling GPIO states or reading pin states. ```typescript // Turn on an LED await this.env.DEVICE.setGpioState(25, "high"); // Read a pin state const reading = await this.env.DEVICE.getPinState(26, "analog"); ``` -------------------------------- ### Configure the SPI Bus in TypeScript Source: https://devicesdk.com/docs/guides/using-spi Initializes the SPI bus with specific pin assignments, clock frequency, and operating mode. Must be called before any communication occurs. ```typescript await this.env.DEVICE.spiConfigure( 0, // bus number 18, // CLK pin 19, // MOSI pin 16, // MISO pin 17, // CS pin 1000000, // frequency in Hz (1 MHz) 0 // SPI mode (0-3) ); ``` -------------------------------- ### DeviceSDK Architecture Diagram Source: https://devicesdk.com/docs/concepts/architecture Visual representation of the connection flow between devices, the WebSocket gateway, and the runtime. ```text ┌──────────┐ ┌──────────────┐ ┌─────────────────┐ │ Device │ ◄─────► │ WebSocket │ ◄─────► │ Device Script │ │ (Pico W) │ HTTPS │ Connection │ │ (Runtime) │ └──────────┘ └──────────────┘ └─────────────────┘ │ ▼ ┌──────────────┐ │ Dashboard │ │ & Logs │ └──────────────┘ ``` -------------------------------- ### pioWs2812Configure Source: https://devicesdk.com/docs/guides/addressable-leds Initializes the PIO state machine for WS2812 protocol timing on a specific GPIO pin. ```APIDOC ## pioWs2812Configure ### Description Initializes the PIO state machine for WS2812 protocol timing on the specified pin. Call this once during onDeviceConnect(). ### Parameters - **pin** (number) - Required - The GPIO pin connected to the LED strip data line. - **numLeds** (number) - Required - The total number of LEDs in the strip. ### Request Example await this.env.DEVICE.pioWs2812Configure(2, 16); ``` -------------------------------- ### Implement GPIO Blink Pattern Source: https://devicesdk.com/docs/resources/hardware Demonstrates toggling a GPIO pin to create a blink effect using the DeviceEntrypoint class. ```typescript import { DeviceEntrypoint } from '@devicesdk/core'; export default class BlinkDevice extends DeviceEntrypoint { async onDeviceConnect() { const LED_PIN = 25; // Pico W — use 2 for ESP32 for (let i = 0; i < 5; i++) { await this.env.DEVICE.setGpioState(LED_PIN, 'high'); await new Promise(r => setTimeout(r, 500)); await this.env.DEVICE.setGpioState(LED_PIN, 'low'); await new Promise(r => setTimeout(r, 500)); } } } ``` -------------------------------- ### Device-to-Device Communication Diagram Source: https://devicesdk.com/docs/concepts/architecture Flow diagram illustrating how devices communicate via the serverless runtime. ```text ┌──────────────┐ ┌────────────────────┐ ┌──────────────┐ │ Device A │ │ Serverless Runtime │ │ Device B │ │ (Sensor) │ ──WS──► │ │ ──WS──► │ (Light) │ │ │ │ Sensor script: │ │ │ │ │ │ this.env.DEVICES │ │ │ │ │ │ ["light"].turnOn() │ │ │ │ │ │ │ │ │ │ │ │ │ ▼ │ │ │ │ │ │ Light script: │ │ │ │ │ │ turnOn() executes │ │ │ │ │ │ result flows back │ │ │ └──────────────┘ └────────────────────┘ └──────────────┘ ``` -------------------------------- ### Status command usage Source: https://devicesdk.com/docs/cli/status Basic syntax for executing the status command. ```bash devicesdk status [flags] ``` -------------------------------- ### SPI CLI Command Syntax Source: https://devicesdk.com/docs/guides/using-spi Reference for available SPI commands in the interactive CLI. ```bash spi configure [mode] spi transfer spi write spi read ``` -------------------------------- ### Define LightController Device Source: https://devicesdk.com/docs/guides/inter-device-communication Implements the LightController entrypoint with public methods for hardware control and state management. ```typescript // src/devices/light.ts import { DeviceEntrypoint, type DeviceResponse } from '@devicesdk/core'; import type { Env } from '../../devicesdk-env'; export class LightController extends DeviceEntrypoint { async turnOn() { await this.env.DEVICE.setGpioState(5, 'high'); return { status: 'on' as const }; } async turnOff() { await this.env.DEVICE.setGpioState(5, 'low'); return { status: 'off' as const }; } async updateDesiredState(state: { brightness: number }) { // KV writes always work, even when hardware is offline await this.env.DEVICE.kv.put('desired', state); } async onDeviceConnect() { // Apply saved state when hardware reconnects const desired = await this.env.DEVICE.kv.get<{ brightness: number }>('desired'); if (desired) { console.info('Applying saved brightness:', desired.brightness); } } async onMessage(message: DeviceResponse) { // Handle hardware messages } } ``` -------------------------------- ### Exporting DEVICESDK_TOKEN Environment Variable Source: https://devicesdk.com/docs/cli/deploy Sets the DEVICESDK_TOKEN environment variable for authentication with the DeviceSDK CLI. This is typically done before running the deploy command in a CI/CD environment or local terminal. ```bash export DEVICESDK_TOKEN="your-token-here" devicesdk deploy ``` -------------------------------- ### Custom flash timeout Source: https://devicesdk.com/docs/cli/flash Set a custom timeout for the flashing process in milliseconds. The default is 30000ms for Pico and 60000ms for ESP32. ```bash devicesdk flash my-device --timeout 120000 ``` -------------------------------- ### Define a Custom Device Entrypoint Source: https://devicesdk.com/docs/concepts/entrypoints Extend the DeviceEntrypoint class to create a custom device handler. Implement lifecycle methods to manage device connections and messages. ```typescript import { DeviceEntrypoint } from '@devicesdk/core'; export default class MyDevice extends DeviceEntrypoint { // Lifecycle methods async onDeviceConnect() { } async onMessage(message: DeviceResponse) { } async onDeviceDisconnect() { } } ``` -------------------------------- ### Deploy Specific Devices Independently Source: https://devicesdk.com/docs/cli/deploy Deploys device scripts to individual devices, allowing for independent updates. This is useful for per-device deployment strategies. ```bash devicesdk deploy --device sensor-1 ``` ```bash devicesdk deploy --device sensor-2 ``` -------------------------------- ### Deferred State Pattern Source: https://devicesdk.com/docs/guides/inter-device-communication Demonstrates writing state to KV storage for later application when hardware reconnects. ```typescript // From any device — works even when light hardware is disconnected await this.env.DEVICES['light-controller'].updateDesiredState({ brightness: 80 }); // In LightController.onDeviceConnect() — applied when hardware comes back const desired = await this.env.DEVICE.kv.get('desired'); if (desired) { /* apply to hardware */ } ```