1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
use std::sync::mpsc::{channel, Sender, Receiver}; use std::collections::HashMap; use std::time::Duration; use ra_common::models::Envelope; use std::io::{Error, ErrorKind}; #[derive(Debug, Copy, Clone)] pub enum BusType { Internal, DBus, IPCD } impl BusType { pub fn as_string(&self) -> &'static str { match *self { BusType::Internal => "Internal", BusType::DBus => "DBus", BusType::IPCD => "IPCD" } } pub fn from_str(sig_type: &str) -> Result<Self, Error> { match sig_type { "Internal" => Ok(BusType::Internal), "DBus" => Ok(BusType::DBus), "IPCD" => Ok(BusType::IPCD), _ => Result::Err(Error::new(ErrorKind::InvalidData, format!("BusType provided not supported: {}", sig_type))) } } } pub struct MessageChannel { pub addr: u8, pub tx: Sender<Envelope>, pub rx: Receiver<Envelope> } impl MessageChannel { pub fn new(addr: u8) -> MessageChannel { let (tx, rx) = channel(); MessageChannel { addr, tx, rx } } } pub struct MessageBus { b_type: BusType, name: String, channels: HashMap<u8,MessageChannel> } impl MessageBus { pub fn new(name: String, b_type: BusType) -> Result<MessageBus,Error> { match b_type { BusType::Internal => { Ok(MessageBus { name, b_type, channels: HashMap::new() }) }, BusType::DBus => { Err(Error::new(ErrorKind::NotFound, "DBus not yet implemented.")) }, BusType::IPCD => { Err(Error::new(ErrorKind::NotFound, "IPCD not yet implemented.")) } } } pub fn register(&mut self) -> u8 { let id :u8 = self.channels.len() as u8; self.channels.insert(id, MessageChannel::new(id)); id } pub fn unregister(&mut self, id: u8) -> bool { self.channels.remove(&id).is_some() } pub fn send(&mut self, env: Envelope) -> bool { match self.channels.get(&env.to) { Some(ch) => { match ch.tx.send(env) { Ok(()) => true, Err(_) => false } }, None => false } } pub fn poll(&mut self, addr: u8) -> Option<Envelope> { match self.channels.get(&addr) { Some(ch) => { match ch.rx.try_recv() { Ok(env) => Option::Some(env), Err(_) => Option::None } }, None => Option::None } } pub fn poll_wait(&mut self, addr: u8, wait: u64) -> Option<Envelope> { match self.channels.get(&addr) { Some(ch) => { match ch.rx.recv_timeout(Duration::from_millis(wait)) { Ok(env) => Option::Some(env), Err(_) => Option::None } }, None => Option::None } } }