Skip to content

Commit

Permalink
Changed linarmap to deque. Dnsstate inside DNStable
Browse files Browse the repository at this point in the history
  • Loading branch information
KennethKnudsen97 committed Aug 16, 2023
1 parent f481251 commit b402a4c
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 43 deletions.
74 changes: 53 additions & 21 deletions ublox-short-range/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use ublox_sockets::{
UdpSocket, UdpState,
};

#[derive(PartialEq, Copy, Clone)]
#[derive(PartialEq, Eq, Copy, Clone)]
pub enum SerialMode {
Cmd,
ExtendedData,
Expand All @@ -53,26 +53,68 @@ pub enum DNSState {
Error(PingError),
}

/// From u-connectXpress AT commands manual:
/// <domain> depends on the <scheme>. For internet domain names, the maximum
/// length is 64 characters.
/// Domain name length is 128 for NINA-W13 and NINA-W15 software version 4.0
/// .0 or later.

#[cfg(not(feature = "nina_w1xx"))]
pub const MAX_DOMAIN_NAME_LENGTH: usize = 64;

Check warning on line 63 in ublox-short-range/src/client.rs

View workflow job for this annotation

GitHub Actions / clippy

found an empty line after a doc comment. Perhaps you need to use `//!` to make a comment on a module, remove the empty line, or make a regular comment with `//`?

warning: found an empty line after a doc comment. Perhaps you need to use `//!` to make a comment on a module, remove the empty line, or make a regular comment with `//`? --> ublox-short-range/src/client.rs:60:1 | 60 | / /// .0 or later. 61 | | 62 | | #[cfg(not(feature = "nina_w1xx"))] 63 | | pub const MAX_DOMAIN_NAME_LENGTH: usize = 64; | |_ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#empty_line_after_doc_comments = note: `-W clippy::empty-line-after-doc-comments` implied by `-W clippy::nursery`

#[cfg(feature = "nina_w1xx")]
pub const MAX_DOMAIN_NAME_LENGTH: usize = 128;

pub struct DNSTableEntry{
domain_name: heapless::String<MAX_DOMAIN_NAME_LENGTH>,
state: DNSState
}

impl DNSTableEntry {
pub fn new(state: DNSState, domain_name: heapless::String<MAX_DOMAIN_NAME_LENGTH>) -> Self{
Self {domain_name, state }
}

Check warning on line 76 in ublox-short-range/src/client.rs

View workflow job for this annotation

GitHub Actions / clippy

this could be a `const fn`

warning: this could be a `const fn` --> ublox-short-range/src/client.rs:74:5 | 74 | / pub fn new(state: DNSState, domain_name: heapless::String<MAX_DOMAIN_NAME_LENGTH>) -> Self{ 75 | | Self {domain_name, state } 76 | | } | |_____^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#missing_const_for_fn = note: `-W clippy::missing-const-for-fn` implied by `-W clippy::nursery`
}

pub struct DNSTable {
pub table: heapless::LinearMap<IpAddr, heapless::String<256>, 16>,
pub table: heapless::Deque<DNSTableEntry, 3>,
}

impl DNSTable {
fn new() -> Self {
const fn new() -> Self {
Self {
table: heapless::LinearMap::new(),
table: heapless::Deque::new(),
}
}
pub fn insert(&mut self, ip: IpAddr, hostname: heapless::String<256>) -> Result<(), ()> {
self.table.insert(ip, hostname).ok();
Ok(())
pub fn upsert(&mut self, new_entry: DNSTableEntry){
if let Some(entry) = self.table.iter_mut().find(|e| e.domain_name == new_entry.domain_name){
entry.state = new_entry.state;
return;
}

if self.table.is_full(){
self.table.pop_front();
}
unsafe{
self.table.push_back_unchecked(new_entry);
}
}
pub fn get_hostname_by_ip(&self, ip: &IpAddr) -> Option<&heapless::String<256>> {
self.table.get(ip)

pub fn get_state(&self, domain_name: heapless::String<MAX_DOMAIN_NAME_LENGTH>) -> Option<DNSState> {

Check warning on line 103 in ublox-short-range/src/client.rs

View workflow job for this annotation

GitHub Actions / clippy

this argument is passed by value, but not consumed in the function body

warning: this argument is passed by value, but not consumed in the function body --> ublox-short-range/src/client.rs:103:42 | 103 | pub fn get_state(&self, domain_name: heapless::String<MAX_DOMAIN_NAME_LENGTH>) -> Option<DNSState> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider taking a reference instead: `&heapless::String<MAX_DOMAIN_NAME_LENGTH>` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_value = note: `-W clippy::needless-pass-by-value` implied by `-W clippy::pedantic`
match self.table.iter().find(|e| e.domain_name == domain_name){
Some(entry) => Some(entry.state),
None => None
}

Check warning on line 107 in ublox-short-range/src/client.rs

View workflow job for this annotation

GitHub Actions / clippy

use Option::map_or instead of an if let/else

warning: use Option::map_or instead of an if let/else --> ublox-short-range/src/client.rs:104:9 | 104 | / match self.table.iter().find(|e| e.domain_name == domain_name){ 105 | | Some(entry) => Some(entry.state), 106 | | None => None 107 | | } | |_________^ help: try: `self.table.iter().find(|e| e.domain_name == domain_name).map_or(None, |entry| Some(entry.state))` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#option_if_let_else = note: `-W clippy::option-if-let-else` implied by `-W clippy::nursery`

Check warning on line 107 in ublox-short-range/src/client.rs

View workflow job for this annotation

GitHub Actions / clippy

manual implementation of `Option::map`

warning: manual implementation of `Option::map` --> ublox-short-range/src/client.rs:104:9 | 104 | / match self.table.iter().find(|e| e.domain_name == domain_name){ 105 | | Some(entry) => Some(entry.state), 106 | | None => None 107 | | } | |_________^ help: try this: `self.table.iter().find(|e| e.domain_name == domain_name).map(|entry| entry.state)` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#manual_map = note: `-W clippy::manual-map` implied by `-W clippy::all`
}
pub fn reverse_lookup(&self, ip: IpAddr) -> Option<&heapless::String<MAX_DOMAIN_NAME_LENGTH>>{
match self.table.iter().find(|e| e.state == DNSState::Resolved(ip)) {
Some(entry) => {Some(&entry.domain_name)},
None => None,
}

Check warning on line 113 in ublox-short-range/src/client.rs

View workflow job for this annotation

GitHub Actions / clippy

use Option::map_or instead of an if let/else

warning: use Option::map_or instead of an if let/else --> ublox-short-range/src/client.rs:110:9 | 110 | / match self.table.iter().find(|e| e.state == DNSState::Resolved(ip)) { 111 | | Some(entry) => {Some(&entry.domain_name)}, 112 | | None => None, 113 | | } | |_________^ help: try: `self.table.iter().find(|e| e.state == DNSState::Resolved(ip)).map_or(None, |entry| Some(&entry.domain_name))` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#option_if_let_else
}
}

#[derive(PartialEq, Clone, Default)]
#[derive(PartialEq, Eq, Clone, Default)]
pub struct SecurityCredentials {
pub ca_cert_name: Option<heapless::String<16>>,
pub c_cert_name: Option<heapless::String<16>>, // TODO: Make &str with lifetime
Expand Down Expand Up @@ -109,7 +151,6 @@ where
pub(crate) client: C,
pub(crate) config: Config<RST>,
pub(crate) sockets: Option<&'static mut SocketSet<TIMER_HZ, N, L>>,
pub(crate) dns_state: DNSState,
pub(crate) urc_attempts: u8,
pub(crate) security_credentials: SecurityCredentials,
pub(crate) timer: CLK,
Expand All @@ -135,7 +176,6 @@ where
client,
config,
sockets: None,
dns_state: DNSState::NotResolving,
urc_attempts: 0,
security_credentials: SecurityCredentials::default(),
timer,
Expand Down Expand Up @@ -290,7 +330,6 @@ where
self.module_started = false;
self.wifi_connection = None;
self.wifi_config_active_on_startup = None;
self.dns_state = DNSState::NotResolving;
self.urc_attempts = 0;
self.security_credentials = SecurityCredentials::default();
self.socket_map = SocketMap::default();
Expand Down Expand Up @@ -329,7 +368,6 @@ where
self.module_started = false;
self.wifi_connection = None;
self.wifi_config_active_on_startup = None;
self.dns_state = DNSState::NotResolving;
self.urc_attempts = 0;
self.security_credentials = SecurityCredentials::default();
self.socket_map = SocketMap::default();
Expand Down Expand Up @@ -410,7 +448,6 @@ where
fn handle_urc(&mut self) -> Result<bool, Error> {
let mut ran = false;
let socket_set = self.sockets.as_deref_mut();
let dns_state = &mut self.dns_state;
let socket_map = &mut self.socket_map;
let udp_listener = &mut self.udp_listener;
let wifi_connection = &mut self.wifi_connection;
Expand Down Expand Up @@ -661,16 +698,11 @@ where
}
Urc::PingResponse(resp) => {
debug!("[URC] PingResponse");
if *dns_state == DNSState::Resolving {
*dns_state = DNSState::Resolved(resp.ip)
}
self.dns_table.upsert(DNSTableEntry { domain_name: resp.hostname, state: DNSState::Resolved(resp.ip) });
true
}
Urc::PingErrorResponse(resp) => {
debug!("[URC] PingErrorResponse: {:?}", resp.error);
if *dns_state == DNSState::Resolving {
*dns_state = DNSState::Error(resp.error)
}
true
}
}
Expand Down
25 changes: 14 additions & 11 deletions ublox-short-range/src/wifi/dns.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::client::DNSState;
use crate::client::{DNSState, DNSTableEntry};
use embedded_hal::digital::OutputPin;
use embedded_nal::{nb, AddrType, Dns, IpAddr};
use fugit::ExtU32;
Expand Down Expand Up @@ -31,27 +31,30 @@ where
retry_num: 1,
})
.map_err(|_| nb::Error::Other(Error::Unaddressable))?;
self.dns_state = DNSState::Resolving;

self.dns_table.upsert(DNSTableEntry::new(DNSState::Resolving, String::from(hostname)));

let expiration = self.timer.now() + 8.secs();

while self.dns_state == DNSState::Resolving {
while let Some(DNSState::Resolving) = self.dns_table.get_state(String::from(hostname)){

Check warning on line 39 in ublox-short-range/src/wifi/dns.rs

View workflow job for this annotation

GitHub Actions / clippy

this pattern matching can be expressed using equality

warning: this pattern matching can be expressed using equality --> ublox-short-range/src/wifi/dns.rs:39:15 | 39 | while let Some(DNSState::Resolving) = self.dns_table.get_state(String::from(hostname)){ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `self.dns_table.get_state(String::from(hostname)) == Some(DNSState::Resolving)` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#equatable_if_let = note: `-W clippy::equatable-if-let` implied by `-W clippy::nursery`
self.spin().map_err(|_| nb::Error::Other(Error::Illegal))?;

if self.timer.now() >= expiration {
return Err(nb::Error::Other(Error::Timeout));
break;
}
}

match self.dns_state {
DNSState::Resolved(ip) => {
//Insert hostname and ip into dns table
self.dns_table
.insert(ip, heapless::String::from(hostname))
.ok();
match self.dns_table.get_state(String::from(hostname)) {
Some(DNSState::Resolved(ip)) => {
Ok(ip)
}
_ => Err(nb::Error::Other(Error::Illegal)),
Some(DNSState::Resolving) => {
self.dns_table.upsert(DNSTableEntry::new(DNSState::Error(types::PingError::Timeout), String::from(hostname)));
Err(nb::Error::Other(Error::Timeout))
}
_ => Err(nb::Error::Other(Error::Illegal))
}
}
}


19 changes: 8 additions & 11 deletions ublox-short-range/src/wifi/tcp_stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,19 +65,16 @@ where
defmt::debug!("[TCP] Connect socket");
self.connected_to_network().map_err(|_| Error::Illegal)?;

let mut url = PeerUrlBuilder::new();

//Connect with hostname if seen before
if let Some(hostname) = self.dns_table.get_hostname_by_ip(&remote.ip()) {
url.hostname(hostname).port(remote.port());
let url = if let Some(hostname) = self.dns_table.reverse_lookup(remote.ip()){
PeerUrlBuilder::new().hostname(hostname.as_str()).port(remote.port()).creds(self.security_credentials.clone())
.tcp()
.map_err(|_| Error::Unaddressable)?
} else {
url.address(&remote);
}

let url = url
.creds(self.security_credentials.clone())
PeerUrlBuilder::new().ip_addr(remote.ip()).port(remote.port()).creds(self.security_credentials.clone())
.tcp()
.map_err(|_| Error::Unaddressable)?;
.map_err(|_| Error::Unaddressable)?
};

defmt::debug!("[TCP] Connecting socket: {:?} to url: {=str}", socket, url);

// If no socket is found we stop here
Expand Down

0 comments on commit b402a4c

Please sign in to comment.