Compare commits

..

2 Commits

Author SHA1 Message Date
occheung 9a42674bf9 nal: use minimq example 2020-09-01 17:41:40 +08:00
occheung 843556d5e9 readme: rm issue 2020-09-01 15:06:09 +08:00
2 changed files with 170 additions and 94 deletions

View File

@ -44,8 +44,3 @@ Select a different gdb config file from ```gdb_config``` directory.
set-gdb-config-file <filename> set-gdb-config-file <filename>
``` ```
Leave <filename> as blank for default openocd.gdb configuration. Leave <filename> as blank for default openocd.gdb configuration.
# Known problems
This version does not compile on its own.
The SCPI crate referenced in ```cargo.toml``` refers a modified SCPI pasrsng crate stored locally.

View File

@ -1,109 +1,190 @@
use embedded_nal::{TcpStack, Mode, SocketAddr}; use core::cell::RefCell;
use embedded_nal::SocketAddr::{V4, V6}; use nb;
use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr}; use heapless::{consts, Vec};
use smoltcp::iface::{NeighborCache, EthernetInterfaceBuilder};
use smoltcp::socket::SocketSet;
use smoltcp::socket::{SocketHandle, TcpSocket, TcpSocketBuffer};
use smoltcp::time::{Duration, Instant};
use smoltcp::Error;
use nb::Error as nbError; use stm32h7_ethernet as ethernet;
use core::cell; use smoltcp as net;
const BUFFER_SIZE: usize = 2048; use cortex_m_semihosting::hprintln;
pub static mut TX_STORAGE: &'static mut [u8] = &mut [0; BUFFER_SIZE];
pub static mut RX_STORAGE: &'static mut [u8] = &mut [0; BUFFER_SIZE];
/* use minimq::embedded_nal;
* Struct for a TCP socket
* TODO: Consider handling all sockets in this struct
*/
pub struct NalTcpClient {}
// impl NalTcpClient { #[derive(Debug)]
// pub fn new(socket: &'a mut TcpSocket<'a>) -> Self { pub enum NetworkError {
NoSocket,
ConnectionFailure,
ReadFailure,
WriteFailure,
}
// NalTcpClient { pub struct NetStorage {
// socket, pub ip_addrs: [net::wire::IpCidr; 1],
// } pub neighbor_cache: [Option<(net::wire::IpAddress, net::iface::Neighbor)>; 8],
// } }
// }
impl<'a> TcpStack for &'a NalTcpClient{ pub type NetworkInterface =
// The type returned when we create a new TCP socket net::iface::EthernetInterface<'static, 'static, 'static, ethernet::EthernetDMA<'static>>;
type TcpSocket = smoltcp::socket::TcpSocket<'a>;
// The type returned when we have an error
type Error = Error;
// Open a new TCP socket. The socket starts in the unconnected state. // TODO: The network stack likely needs a time-tracking mechanic here to support
fn open(&self, mode: Mode) -> Result<Self::TcpSocket, Self::Error> { // blocking/nonblocking/timeout based operations.
let tx_buffer = unsafe { TcpSocketBuffer::new(&mut TX_STORAGE[..]) }; pub struct NetworkStack<'a, 'b, 'c, 'n> {
let rx_buffer = unsafe { TcpSocketBuffer::new(&mut RX_STORAGE[..]) }; network_interface: &'n mut NetworkInterface,
let mut socket = TcpSocket::new(rx_buffer, tx_buffer); sockets: RefCell<net::socket::SocketSet<'a, 'b, 'c>>,
if let Mode::Timeout(dur) = mode { next_port: RefCell<u16>,
socket.set_timeout(Some(Duration::from_millis(dur.into()))); unused_handles: RefCell<Vec<net::socket::SocketHandle, consts::U16>>,
}
impl<'a, 'b, 'c, 'n> NetworkStack<'a, 'b, 'c, 'n> {
pub fn new(
interface: &'n mut NetworkInterface,
sockets: net::socket::SocketSet<'a, 'b, 'c>,
) -> Self {
let mut unused_handles: Vec<net::socket::SocketHandle, consts::U16> = Vec::new();
for socket in sockets.iter() {
unused_handles.push(socket.handle()).unwrap();
}
NetworkStack {
network_interface: interface,
sockets: RefCell::new(sockets),
next_port: RefCell::new(49152),
unused_handles: RefCell::new(unused_handles),
} }
Ok(socket)
} }
// Connect to the given remote host and port. pub fn update(&mut self, time: u32) -> bool {
fn connect( match self.network_interface.poll(
&self, &mut self.sockets.borrow_mut(),
mut socket: Self::TcpSocket, net::time::Instant::from_millis(time as i64),
remote: SocketAddr, ) {
) -> Result<Self::TcpSocket, Self::Error> { Ok(changed) => changed == false,
let result = match remote { Err(e) => {
V4(v4_addr) => { hprintln!("{:?}", e);
let ip_addr = v4_addr.ip().octets(); true
socket.connect((IpAddress::v4(ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3]), v4_addr.port()), 49500)
},
V6(v6_addr) => {
let ip_addr = v6_addr.ip().segments();
socket.connect((IpAddress::v6(ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3],
ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3]), v6_addr.port()), 49500)
} }
};
match result {
Ok(_) => Ok(socket),
Err(_e) => Err(_e),
} }
} }
/// Check if this socket is connected fn get_ephemeral_port(&self) -> u16 {
fn is_connected(&self, socket: &Self::TcpSocket) -> Result<bool, Self::Error> { // Get the next ephemeral port
Ok(socket.is_active()) let current_port = self.next_port.borrow().clone();
}
/// Write to the stream. Returns the number of bytes written is returned let (next, wrap) = self.next_port.borrow().overflowing_add(1);
/// (which may be less than `buffer.len()`), or an error. *self.next_port.borrow_mut() = if wrap { 49152 } else { next };
fn write(&self, socket: &mut Self::TcpSocket, buffer: &[u8]) -> nb::Result<usize, Self::Error> {
if socket.can_send() {
socket.send_slice(buffer).map_err(nbError::Other)
} else {
Err(nbError::Other(Error::Illegal))
}
}
/// Read from the stream. Returns `Ok(n)`, which means `n` bytes of return current_port;
/// data have been received and they have been placed in
/// `&buffer[0..n]`, or an error.
fn read(
&self,
socket: &mut Self::TcpSocket,
buffer: &mut [u8],
) -> nb::Result<usize, Self::Error> {
if socket.can_recv() {
socket.recv_slice(buffer).map_err(nbError::Other)
} else {
Err(nbError::Other(Error::Illegal))
}
}
/// Close an existing TCP socket.
fn close(&self, mut socket: Self::TcpSocket) -> Result<(), Self::Error> {
socket.close();
Ok(())
} }
} }
impl<'a, 'b, 'c, 'n> embedded_nal::TcpStack for NetworkStack<'a, 'b, 'c, 'n> {
type TcpSocket = net::socket::SocketHandle;
type Error = NetworkError;
fn open(&self, _mode: embedded_nal::Mode) -> Result<Self::TcpSocket, Self::Error> {
// TODO: Handle mode?
match self.unused_handles.borrow_mut().pop() {
Some(handle) => {
// Abort any active connections on the handle.
let mut sockets = self.sockets.borrow_mut();
let internal_socket: &mut net::socket::TcpSocket = &mut *sockets.get(handle);
internal_socket.abort();
Ok(handle)
}
None => Err(NetworkError::NoSocket),
}
}
fn connect(
&self,
socket: Self::TcpSocket,
remote: embedded_nal::SocketAddr,
) -> Result<Self::TcpSocket, Self::Error> {
// TODO: Handle socket mode?
let mut sockets = self.sockets.borrow_mut();
let internal_socket: &mut net::socket::TcpSocket = &mut *sockets.get(socket);
// If we're already in the process of connecting, ignore the request silently.
if internal_socket.is_open() {
return Ok(socket);
}
match remote.ip() {
embedded_nal::IpAddr::V4(addr) => {
let address = {
let octets = addr.octets();
net::wire::Ipv4Address::new(octets[0], octets[1], octets[2], octets[3])
};
internal_socket
.connect((address, remote.port()), self.get_ephemeral_port())
.map_err(|_| NetworkError::ConnectionFailure)?;
}
embedded_nal::IpAddr::V6(addr) => {
let address = {
let octets = addr.segments();
net::wire::Ipv6Address::new(
octets[0], octets[1], octets[2], octets[3], octets[4], octets[5],
octets[6], octets[7],
)
};
internal_socket
.connect((address, remote.port()), self.get_ephemeral_port())
.map_err(|_| NetworkError::ConnectionFailure)?;
}
};
Ok(socket)
}
fn is_connected(&self, socket: &Self::TcpSocket) -> Result<bool, Self::Error> {
let mut sockets = self.sockets.borrow_mut();
let socket: &mut net::socket::TcpSocket = &mut *sockets.get(*socket);
Ok(socket.may_send() && socket.may_recv())
}
fn write(&self, socket: &mut Self::TcpSocket, buffer: &[u8]) -> nb::Result<usize, Self::Error> {
// TODO: Handle the socket mode.
let mut sockets = self.sockets.borrow_mut();
let socket: &mut net::socket::TcpSocket = &mut *sockets.get(*socket);
let result = socket.send_slice(buffer);
match result {
Ok(num_bytes) => Ok(num_bytes),
Err(_) => Err(nb::Error::Other(NetworkError::WriteFailure)),
}
}
fn read(
&self,
socket: &mut Self::TcpSocket,
buffer: &mut [u8],
) -> nb::Result<usize, Self::Error> {
// TODO: Handle the socket mode.
let mut sockets = self.sockets.borrow_mut();
let socket: &mut net::socket::TcpSocket = &mut *sockets.get(*socket);
let result = socket.recv_slice(buffer);
match result {
Ok(num_bytes) => Ok(num_bytes),
Err(_) => Err(nb::Error::Other(NetworkError::ReadFailure)),
}
}
fn close(&self, socket: Self::TcpSocket) -> Result<(), Self::Error> {
// TODO: Free the ephemeral port in use by the socket.
let mut sockets = self.sockets.borrow_mut();
let internal_socket: &mut net::socket::TcpSocket = &mut *sockets.get(socket);
internal_socket.close();
self.unused_handles.borrow_mut().push(socket).unwrap();
Ok(())
}
}