kpal 0.2.2

An extensible and RESTful control system for physical computing
Documentation
//! Routines for initializing the daemon.
mod errors;
mod libraries;
mod transmitters;

use std::{net::SocketAddr, path::PathBuf, sync::RwLock};

use dirs::home_dir;
use lazy_static::lazy_static;
use structopt::StructOpt;

use crate::constants::{KPAL_DIR, LIBRARY_DIR};

pub use errors::InitError;
pub use libraries::TSLibrary;
pub use transmitters::Transmitters;

lazy_static! {
    static ref DEFAULT_LIBRARY_DIR: String = {
        let mut default_dir = PathBuf::new();
        default_dir.push(home_dir().expect("Could not determine user's home directory"));
        default_dir.push(KPAL_DIR);
        default_dir.push(LIBRARY_DIR);
        default_dir.to_string_lossy().to_string()
    };
}

/// The set of command line arguments for the daemon.
#[derive(StructOpt)]
#[structopt(
    name = "kpald",
    about = "An extensible and RESTful control system for physical computing"
)]
pub struct Cli {
    #[structopt(short = "s", long = "server-address", default_value = "0.0.0.0:8000")]
    pub server_addr: SocketAddr,

    #[structopt(
        short = "l",
        long = "library-dir",
        default_value = &DEFAULT_LIBRARY_DIR,
        parse(from_os_str)
    )]
    pub library_dir: PathBuf,
}

/// The datatypes generated by the initialization steps.
pub struct Init {
    pub libraries: Vec<TSLibrary>,
    pub transmitters: RwLock<transmitters::Transmitters>,
}

/// Initializes the daemon.
///
/// This method returns the data structures that are required by the daemon to operate, including
/// and a vector of thread-safe libraries that have been loaded into memory and a collection of
/// transmitters for communicating with peripherals.
///
/// # Arguments
///
/// * `args` - The command line arguments that were passed to the daemon at startup.
pub fn init(args: &Cli) -> Result<Init> {
    let libraries = libraries::init(&args.library_dir)?;
    let transmitters = RwLock::new(transmitters::init());

    Ok(Init {
        libraries,
        transmitters,
    })
}

/// A Result that is returned by this module.
pub type Result<T> = std::result::Result<T, InitError>;