new-home-application 0.1.3

New Home iot application framework. Meant to build application for the New Home Core
Documentation
use std::io::Error;

use crate::communication::client_handler::{ClientHandler, ClientHandlerImpl};
use crate::method::method_manager::MethodManager;
use crate::net::tcp_server::TcpServer;

/// The implementation for the `CommunicationManager` trait
/// Interfaces with the clients via the `TcpServer` trait
/// Handles client with the `ClientHandlerImpl` with will receive the `MethodManager` of this struct
/// Handles clients as long as they are connected.
/// Only responds to clients when a request was made
/// All requests will be handled after each other
pub struct CommunicationManagerImpl {
    /// The `TcpServer` which listens for clients to connect
    tcp_server: Box<dyn TcpServer>,

    /// The applications `MethodManager` which contains all registered `Method`s
    /// Will be given as reference to the created `ClientHandler`
    method_manager: Box<dyn MethodManager>,
}

/// Manages the communication of external clients and the application itself
/// Starts a server for clients to connect to and handles clients with a `ClientHandler` method
/// A client can send multiple requests without establishing a new connection
pub trait CommunicationManager {
    /// Initializes an IPC connection
    fn run(&mut self);

    /// Accepts a client, create and runs a new `ClientHandler` instance for the connected client
    fn handle_client(&self) -> Result<(), Error>;
}

impl CommunicationManagerImpl {
    pub fn new(tcp_server: Box<dyn TcpServer>, method_manager: Box<dyn MethodManager>) -> Self {
        Self {
            tcp_server,
            method_manager,
        }
    }
}

impl CommunicationManager for CommunicationManagerImpl {
    fn run(&mut self) {
        self.tcp_server.bind();
    }

    fn handle_client(&self) -> Result<(), Error> {
        let reader_writer = self.tcp_server.get_tcp_stream()?;

        let mut handler = ClientHandlerImpl::new(
            reader_writer.0,
            reader_writer.1,
            &self.method_manager,
        );

        loop {
            if handler.handle().is_err() {
                println!("Client Connection end.");

                break;
            }
        }

        Ok(())
    }
}

unsafe impl Send for CommunicationManagerImpl {}

unsafe impl Sync for CommunicationManagerImpl {}