Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Uploading and running programs

A small command-line tool that uploads compiled programs (.rxe), sounds (.rso) or any other file, and optionally runs it.

use std::path::Path;

use nxt_rs::prelude::*;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut args = std::env::args().skip(1);
    let path = args.next().ok_or("usage: upload <file> [--run]")?;
    let run = args.any(|a| a == "--run");

    let data = std::fs::read(&path)?;
    let base = Path::new(&path).file_name().and_then(|n| n.to_str()).ok_or("bad file name")?;
    let name = FileName::new(base)?;    // checks the 15.3 limit

    let brick = Brick::usb_first().block()?;
    let free = brick.info().block()?.free_flash;
    if data.len() as u64 > u64::from(free) {
        return Err(format!("{name} needs {} bytes, only {free} free", data.len()).into());
    }

    brick.stop_program().block()?;               // a running program may hold the file
    brick.files().upload(&name, &data).block()?; // replaces an existing file
    println!("uploaded {name} ({} bytes)", data.len());

    if run {
        match name.extension() {
            Some("rxe") => brick.start_program(&name).block()?,
            Some("rso") => brick.play_sound(&name, false).block()?,
            _ => println!("don't know how to run {name}"),
        }
    }
    Ok(())
}

Notes

  • Executables are written as linear files automatically, as the brick requires.
  • Uploading over Bluetooth is slow: each request carries at most 61 bytes. Prefer USB for large files.
  • brick.files().list(&"*.*".parse()?) shows what’s already on the brick.