Skip to content

Commit

Permalink
o# This is a combination of 14 commits.
Browse files Browse the repository at this point in the history
Start modularizing packet

move header into its own chunk, include tests

Move auto_respond as a class method

Move packet into its own file

rename "packet" to "message"

Rename Response and Request to *Type to free up the names

Added request and response, pretty clunky feeling though. How can I refactor this?

Better consistency using "message" for the packet inside a Request/Response

cleanup `use`s a bit

more cleaning

Cleanup before pull request

Add tests

Add response test

Cargo fmt
  • Loading branch information
jamesmunns committed Jul 3, 2016
1 parent e1b04ce commit 57ce239
Show file tree
Hide file tree
Showing 14 changed files with 697 additions and 475 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
target
Cargo.lock
*.rs.bk
12 changes: 5 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,9 @@ extern crate coap;
extern crate coap;

use std::io;
use coap::packet::*;
use coap::{CoAPServer, CoAPClient};
use coap::{CoAPResponse, CoAPRequest};

fn request_handler(req: Packet, response: Option<Packet>) -> Option<Packet> {
fn request_handler(req: CoAPRequest) -> Option<CoAPResponse> {
println!("Receive request: {:?}", req);
response
}
Expand All @@ -59,15 +58,14 @@ fn main() {
```rust
extern crate coap;

use coap::packet::*;
use coap::CoAPClient;
use coap::{CoAPClient, CoAPResponse};

fn main() {
let url = "coap://127.0.0.1:5683/Rust";
println!("Client request: {}", url);

let response: Packet = CoAPClient::request(url).unwrap();
println!("Server reply: {}", String::from_utf8(response.payload).unwrap());
let response: CoAPResponse = CoAPClient::request(url).unwrap();
println!("Server reply: {}", String::from_utf8(response.message.payload).unwrap());
}
```

Expand Down
4 changes: 2 additions & 2 deletions benches/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ fn bench_client_request(b: &mut Bencher) {
let request = "test";
let mut packet = Packet::new();
packet.header.set_version(1);
packet.header.set_type(PacketType::Confirmable);
packet.header.set_type(MessageType::Confirmable);
packet.header.set_code("0.01");
packet.header.set_message_id(1);
packet.set_token(vec!(0x51, 0x55, 0x77, 0xE8));
packet.add_option(OptionType::UriPath, request.to_string().into_bytes());
packet.add_option(CoAPOption::UriPath, request.to_string().into_bytes());

b.iter(|| {
let client = CoAPClient::new(addr).unwrap();
Expand Down
52 changes: 26 additions & 26 deletions examples/client.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,34 @@
extern crate coap;

use std::io::ErrorKind;
use coap::packet::*;
use coap::CoAPClient;
use coap::{CoAPClient, CoAPRequest, IsMessage, MessageType, CoAPOption};

fn main() {
let addr = "127.0.0.1:5683";
let request = "test";
let addr = "127.0.0.1:5683";
let endpoint = "test";

let client = CoAPClient::new(addr).unwrap();
let mut packet = Packet::new();
packet.header.set_version(1);
packet.header.set_type(PacketType::Confirmable);
packet.header.set_code("0.01");
packet.header.set_message_id(1);
packet.set_token(vec!(0x51, 0x55, 0x77, 0xE8));
packet.add_option(OptionType::UriPath, request.to_string().into_bytes());
client.send(&packet).unwrap();
println!("Client request: coap://{}/{}", addr, request);
let client = CoAPClient::new(addr).unwrap();
let mut request = CoAPRequest::new();
request.set_version(1);
request.set_type(MessageType::Confirmable);
request.set_code("0.01");
request.set_message_id(1);
request.set_token(vec![0x51, 0x55, 0x77, 0xE8]);
request.add_option(CoAPOption::UriPath, endpoint.to_string().into_bytes());
client.send(&request).unwrap();
println!("Client request: coap://{}/{}", addr, endpoint);

match client.receive() {
Ok(response) => {
println!("Server reply: {}", String::from_utf8(response.payload).unwrap());
},
Err(e) => {
match e.kind() {
ErrorKind::WouldBlock => println!("Request timeout"), // Unix
ErrorKind::TimedOut => println!("Request timeout"), // Windows
_ => println!("Request error: {:?}", e),
}
}
}
match client.receive() {
Ok(response) => {
println!("Server reply: {}",
String::from_utf8(response.message.payload).unwrap());
}
Err(e) => {
match e.kind() {
ErrorKind::WouldBlock => println!("Request timeout"), // Unix
ErrorKind::TimedOut => println!("Request timeout"), // Windows
_ => println!("Request error: {:?}", e),
}
}
}
}
33 changes: 17 additions & 16 deletions examples/client_and_server.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
extern crate coap;

use coap::packet::*;
use coap::{CoAPServer, CoAPClient};
use coap::{CoAPServer, CoAPClient, CoAPRequest, CoAPResponse, CoAPOption};
use coap::IsMessage;

fn request_handler(req: Packet, response: Option<Packet>) -> Option<Packet> {
let uri_path = req.get_option(OptionType::UriPath).unwrap();
fn request_handler(request: CoAPRequest) -> Option<CoAPResponse> {
let uri_path = request.get_option(CoAPOption::UriPath).unwrap();

return match response {
Some(mut packet) => {
packet.set_payload(uri_path.front().unwrap().clone());
Some(packet)
},
_ => None
return match request.response {
Some(mut response) => {
response.set_payload(uri_path.front().unwrap().clone());
Some(response)
}
_ => None,
};
}

fn main() {
let mut server = CoAPServer::new("127.0.0.1:5683").unwrap();
server.handle(request_handler).unwrap();
let mut server = CoAPServer::new("127.0.0.1:5683").unwrap();
server.handle(request_handler).unwrap();

let url = "coap://127.0.0.1:5683/Rust";
println!("Client request: {}", url);
let url = "coap://127.0.0.1:5683/Rust";
println!("Client request: {}", url);

let response: Packet = CoAPClient::request(url).unwrap();
println!("Server reply: {}", String::from_utf8(response.payload).unwrap());
let response: CoAPResponse = CoAPClient::request(url).unwrap();
println!("Server reply: {}",
String::from_utf8(response.message.payload).unwrap());
}
27 changes: 13 additions & 14 deletions examples/server.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,28 @@
extern crate coap;

use std::io;
use coap::packet::*;
use coap::CoAPServer;
use coap::{CoAPServer, CoAPResponse, CoAPRequest, IsMessage};

fn request_handler(_: Packet, response: Option<Packet>) -> Option<Packet> {
return match response {
Some(mut packet) => {
packet.set_payload(b"OK".to_vec());
Some(packet)
fn request_handler(request: CoAPRequest) -> Option<CoAPResponse> {
return match request.response {
Some(mut message) => {
message.set_payload(b"OK".to_vec());
Some(message)
},
_ => None
};
}

fn main() {
let addr = "127.0.0.1:5683";
let addr = "127.0.0.1:5683";

let mut server = CoAPServer::new(addr).unwrap();
server.handle(request_handler).unwrap();
let mut server = CoAPServer::new(addr).unwrap();
server.handle(request_handler).unwrap();

println!("Server up on {}", addr);
println!("Press any key to stop...");
println!("Server up on {}", addr);
println!("Press any key to stop...");

io::stdin().read_line(&mut String::new()).unwrap();
io::stdin().read_line(&mut String::new()).unwrap();

println!("Server shutdown");
println!("Server shutdown");
}
37 changes: 21 additions & 16 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ use std::time::Duration;
use url::{UrlParser, SchemeType};
use num;
use rand::{thread_rng, random, Rng};
use packet::{Packet, PacketType, OptionType};
use message::packet::{Packet, CoAPOption};
use message::header::MessageType;
use message::response::CoAPResponse;
use message::request::CoAPRequest;
use message::IsMessage;

const DEFAULT_RECEIVE_TIMEOUT: u64 = 5; // 5s

Expand Down Expand Up @@ -46,19 +50,19 @@ impl CoAPClient {
}

/// Execute a request with the coap url and a specific timeout. Default timeout is 5s.
pub fn request_with_timeout(url: &str, timeout: Option<Duration>) -> Result<Packet> {
pub fn request_with_timeout(url: &str, timeout: Option<Duration>) -> Result<CoAPResponse> {
let mut url_parser = UrlParser::new();
url_parser.scheme_type_mapper(Self::coap_scheme_type_mapper);

match url_parser.parse(url) {
Ok(url_params) => {
let mut packet = Packet::new();
packet.header.set_version(1);
packet.header.set_type(PacketType::Confirmable);
packet.header.set_code("0.01");
let mut packet = CoAPRequest::new();
packet.set_version(1);
packet.set_type(MessageType::Confirmable);
packet.set_code("0.01");

let message_id = thread_rng().gen_range(0, num::pow(2u32, 16)) as u16;
packet.header.set_message_id(message_id);
packet.set_message_id(message_id);

let mut token: Vec<u8> = vec![1, 1, 1, 1];
for x in token.iter_mut() {
Expand All @@ -74,7 +78,7 @@ impl CoAPClient {

if let Some(path) = url_params.path() {
for p in path.iter() {
packet.add_option(OptionType::UriPath, p.clone().into_bytes().to_vec());
packet.add_option(CoAPOption::UriPath, p.clone().into_bytes().to_vec());
}
};

Expand All @@ -84,7 +88,7 @@ impl CoAPClient {
try!(client.set_receive_timeout(timeout));
match client.receive() {
Ok(receive_packet) => {
if receive_packet.header.get_message_id() == message_id &&
if receive_packet.get_message_id() == message_id &&
*receive_packet.get_token() == token {
return Ok(receive_packet);
} else {
Expand All @@ -99,13 +103,13 @@ impl CoAPClient {
}

/// Execute a request with the coap url.
pub fn request(url: &str) -> Result<Packet> {
pub fn request(url: &str) -> Result<CoAPResponse> {
Self::request_with_timeout(url, Some(Duration::new(DEFAULT_RECEIVE_TIMEOUT, 0)))
}

/// Execute a request.
pub fn send(&self, packet: &Packet) -> Result<()> {
match packet.to_bytes() {
pub fn send(&self, request: &CoAPRequest) -> Result<()> {
match request.message.to_bytes() {
Ok(bytes) => {
let size = try!(self.socket.send_to(&bytes[..], self.peer_addr));
if size == bytes.len() {
Expand All @@ -119,12 +123,12 @@ impl CoAPClient {
}

/// Receive a response.
pub fn receive(&self) -> Result<Packet> {
pub fn receive(&self) -> Result<CoAPResponse> {
let mut buf = [0; 1500];

let (nread, _src) = try!(self.socket.recv_from(&mut buf));
match Packet::from_bytes(&buf[..nread]) {
Ok(packet) => Ok(packet),
Ok(packet) => Ok(CoAPResponse { message: packet }),
Err(_) => Err(Error::new(ErrorKind::InvalidInput, "packet error")),
}
}
Expand All @@ -148,7 +152,8 @@ mod test {
use super::*;
use std::time::Duration;
use std::io::ErrorKind;
use packet::Packet;
use message::request::CoAPRequest;
use message::response::CoAPResponse;
use server::CoAPServer;

#[test]
Expand All @@ -158,7 +163,7 @@ mod test {
assert!(CoAPClient::request("127.0.0.1").is_err());
}

fn request_handler(_: Packet, _: Option<Packet>) -> Option<Packet> {
fn request_handler(_: CoAPRequest) -> Option<CoAPResponse> {
None
}

Expand Down
22 changes: 13 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,10 @@
//! extern crate coap;
//! use std::io;
//! use coap::packet::*;
//! use coap::{CoAPServer, CoAPClient};
//! use coap::{CoAPServer, CoAPClient, CoAPRequest, CoAPResponse};
//! fn request_handler(req: Packet, resp: Option<Packet>) -> Option<Packet> {
//! println!("Receive request: {:?}", req);
//! fn request_handler(request: CoAPRequest) -> Option<CoAPResponse> {
//! println!("Receive request: {:?}", request);
//! None
//! }
Expand All @@ -54,15 +53,15 @@
//! ```no_run
//! extern crate coap;
//!
//! use coap::packet::*;
//! use coap::message::response::CoAPResponse;
//! use coap::CoAPClient;
//!
//! fn main() {
//! let url = "coap://127.0.0.1:5683/Rust";
//! println!("Client request: {}", url);
//!
//! let response: Packet = CoAPClient::request(url).unwrap();
//! println!("Server reply: {}", String::from_utf8(response.payload).unwrap());
//! let response: CoAPResponse = CoAPClient::request(url).unwrap();
//! println!("Server reply: {}", String::from_utf8(response.message.payload).unwrap());
//! }
//! ```
Expand All @@ -79,9 +78,14 @@ extern crate quickcheck;
#[macro_use]
extern crate log;

pub use server::CoAPServer;
pub use client::CoAPClient;
pub use message::header::MessageType;
pub use message::IsMessage;
pub use message::packet::CoAPOption;
pub use message::request::CoAPRequest;
pub use message::response::CoAPResponse;
pub use server::CoAPServer;

pub mod packet;
pub mod message;
pub mod client;
pub mod server;
Loading

0 comments on commit 57ce239

Please sign in to comment.