Commit efcba9ad authored by MrMan's avatar MrMan

Improve pattern with reddit feedback

- see updated blog post
parent b25f2c40
......@@ -49,10 +49,29 @@ impl Clock {
impl Component for Clock {
fn get_name(&self) -> &'static str { "clock" }
fn start(&mut self) -> ! {
fn start(&mut self) -> Result<(), ComponentError> {
// Control loop
loop {
// TODO: process messages
let msg = self.recv_request()?;
match msg {
// Lifecycle handling
ComponentRequest::Lifecycle(req) => {
match req {
ComponentLifecycleRequest::Shutdown => { break }
}
},
// Simple request-response handling
ComponentRequest::Operation(req) => {
// Maybe we should do something with the result below...
let _ = self.handle_simple_req(req)?;
thread::yield_now();
}
}
}
Ok(())
}
fn stop(&self) -> Result<(), ComponentError> {
......@@ -73,7 +92,9 @@ impl Configurable<ClockCfg> for Clock {
fn get_config(&self) -> &ClockCfg { &self.clock_cfg }
}
impl HandlesSimpleRequests<ClockRequest> for Clock {
impl HandlesSimpleRequests for Clock {
type Request = ClockRequest;
fn recv_request(&self) -> Result<ComponentRequest<ClockRequest>, ComponentError> {
self.cmd_bus_rx.recv().map_err(ComponentError::from)
}
......@@ -125,26 +146,7 @@ where
cloned_tx.send(ComponentRequest::Lifecycle(ComponentLifecycleRequest::Shutdown)).expect("failed to send shutdown");
});
// Control loop
loop {
let msg = c.recv_request()?;
match msg {
// Lifecycle handling
ComponentRequest::Lifecycle(req) => {
match req {
ComponentLifecycleRequest::Shutdown => { break }
}
},
// Simple request-response handling
ComponentRequest::Operation(req) => {
// Maybe we should do something with the result below...
let _ = c.handle_simple_req(req)?;
thread::yield_now();
}
}
}
let _ = c.start()?;
Ok(())
});
......
......@@ -22,9 +22,9 @@ pub enum ComponentRequest<T> {
Operation(RequestResponse<T>)
}
pub trait Component {
pub trait Component: HandlesSimpleRequests {
fn get_name(&self) -> &str;
fn start(&mut self) -> !;
fn start(&mut self) -> Result<(), ComponentError>;
fn stop(&self) -> Result<(), ComponentError>;
}
......@@ -35,10 +35,12 @@ pub trait Configurable<C> where Self: Component {
fn get_config(&self) -> &C;
}
pub trait HandlesSimpleRequests<RQ> {
fn recv_request(&self) -> Result<ComponentRequest<RQ>, ComponentError>;
fn get_request_chan(&self) -> Result<Sender<ComponentRequest<RQ>>, ComponentError>;
fn handle_simple_req(&mut self, envelope: RequestResponse<RQ>) -> Result<(), ComponentError>;
pub trait HandlesSimpleRequests {
type Request;
fn recv_request(&self) -> Result<ComponentRequest<Self::Request>, ComponentError>;
fn get_request_chan(&self) -> Result<Sender<ComponentRequest<Self::Request>>, ComponentError>;
fn handle_simple_req(&mut self, envelope: RequestResponse<Self::Request>) -> Result<(), ComponentError>;
}
#[derive(Debug)]
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment