Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/examples #29

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,17 @@ jobs:
target: thumbv7m-none-eabi
override: true

- name: Build
- name: Build examples
uses: actions-rs/cargo@v1
with:
command: build
args: --all --all-features --target thumbv7m-none-eabi
args: --all --all-features --target x86_64-unknown-linux-gnu

- name: Build library for ARM
uses: actions-rs/cargo@v1
with:
command: build
args: -p ublox-cellular-rs --all-features --target thumbv7m-none-eabi

- name: Test
uses: actions-rs/cargo@v1
Expand Down
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
[workspace]
members = [
"ublox-cellular",
# "examples/common_lib",
# "examples/linux",
"examples/common_lib",
"examples/linux",
# "examples/linux_mqtt",
# "examples/linux_jobs",
]
5 changes: 2 additions & 3 deletions examples/common_lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,5 @@ doctest = false

[dependencies]
serialport = "3.3.0"
embedded-hal = "0.2.3"
nb = "0.1.2"
void = { version = "1.0.2", default-features = false }
embedded-hal = "1.0.0-alpha.4"
nb = "1.0"
18 changes: 9 additions & 9 deletions examples/common_lib/src/serial.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use embedded_hal as hal;
use serialport;
use std::io::{ErrorKind as IoErrorKind, Read, Write};
use embedded_hal::serial::{Read, Write};
pub use serialport;
use std::io::ErrorKind as IoErrorKind;

pub struct Serial(pub Box<dyn serialport::SerialPort>);

/// Helper to convert std::io::Error to the nb::Error
/// Helper to convert `std::io::Error` to the `nb::Error`
fn translate_io_errors(err: std::io::Error) -> nb::Error<IoErrorKind> {
match err.kind() {
IoErrorKind::WouldBlock | IoErrorKind::TimedOut | IoErrorKind::Interrupted => {
Expand All @@ -14,10 +14,10 @@ fn translate_io_errors(err: std::io::Error) -> nb::Error<IoErrorKind> {
}
}

impl hal::serial::Read<u8> for Serial {
impl Read<u8> for Serial {
type Error = IoErrorKind;

fn read(&mut self) -> nb::Result<u8, Self::Error> {
fn try_read(&mut self) -> nb::Result<u8, Self::Error> {
let mut buffer = [0; 1];
let bytes_read = self.0.read(&mut buffer).map_err(translate_io_errors)?;
if bytes_read == 1 {
Expand All @@ -28,15 +28,15 @@ impl hal::serial::Read<u8> for Serial {
}
}

impl hal::serial::Write<u8> for Serial {
impl Write<u8> for Serial {
type Error = IoErrorKind;

fn write(&mut self, word: u8) -> nb::Result<(), Self::Error> {
fn try_write(&mut self, word: u8) -> nb::Result<(), Self::Error> {
self.0.write(&[word]).map_err(translate_io_errors)?;
Ok(())
}

fn flush(&mut self) -> nb::Result<(), Self::Error> {
fn try_flush(&mut self) -> nb::Result<(), Self::Error> {
self.0.flush().map_err(translate_io_errors)
}
}
40 changes: 30 additions & 10 deletions examples/common_lib/src/timer.rs
Original file line number Diff line number Diff line change
@@ -1,41 +1,61 @@
use embedded_hal::timer::CountDown;
use core::convert::Infallible;
use embedded_hal::{
blocking::delay::DelayMs,
timer::{CountDown, Periodic},
};
use std::time::{Duration, Instant};

#[allow(clippy::module_name_repetitions)]
pub struct SysTimer {
start: Instant,
count: u32,
}

impl SysTimer {
pub fn new() -> SysTimer {
SysTimer {
#[must_use]
pub fn new() -> Self {
Self {
start: Instant::now(),
count: 0,
}
}
}

impl Default for SysTimer {
fn default() -> Self {
Self::new()
}
}

impl DelayMs<u32> for SysTimer {
type Error = Infallible;

fn try_delay_ms(&mut self, ms: u32) -> Result<(), Self::Error> {
self.try_start(ms)?;
nb::block!(self.try_wait())
}
}

impl CountDown for SysTimer {
type Error = Infallible;
type Time = u32;

fn start<T>(&mut self, count: T)
fn try_start<T>(&mut self, count: T) -> Result<(), Self::Error>
where
T: Into<Self::Time>,
{
self.start = Instant::now();
self.count = count.into();
Ok(())
}

fn wait(&mut self) -> nb::Result<(), void::Void> {
if Instant::now() - self.start > Duration::from_millis(self.count as u64) {
fn try_wait(&mut self) -> nb::Result<(), Self::Error> {
if Instant::now() - self.start > Duration::from_millis(u64::from(self.count)) {
Ok(())
} else {
Err(nb::Error::WouldBlock)
}
}
}

// #[cfg(test)]
// mod tests {
// extern crate nb;
// }
impl Periodic for SysTimer {}
10 changes: 4 additions & 6 deletions examples/linux/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,10 @@ repository = "https://github.com/BlackbirdHQ/ublox-cellular-rs"
edition = "2018"

[dependencies]
embedded-hal = "0.2.3"
atat = { version = "^0.4.1", features = ["derive", "logging"] }
log = { version = "0.4", default-features = false }
env_logger = "0.7.1"
linux-embedded-hal = "0.3.0"
serialport = "3.3.0"
embedded-hal = "1.0.0-alpha.4"
embedded-nal = "0.2.0"

atat = { version = "^0.6.0", features = ["derive"] }
heapless = "0.5.5"

common_lib = { path = "../common_lib" }
Expand Down
137 changes: 63 additions & 74 deletions examples/linux/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,44 +1,25 @@
use atat::{ClientBuilder, ComQueue, Queues, ResQueue, UrcQueue};
use serialport;
use std::io;
use std::thread;

use ublox_cellular::gprs::APNInfo;
use ublox_cellular::prelude::*;
use ublox_cellular::sockets::{Ipv4Addr, Mode, SocketAddrV4, SocketSet};
use ublox_cellular::{error::Error as GSMError, Config, GsmClient};

use atat::AtatClient;
use embedded_hal::digital::v2::OutputPin;

use linux_embedded_hal::Pin;

use heapless::{self, consts, spsc::Queue, ArrayLength};

use common::{serial::Serial, timer::SysTimer};
use std::{io, thread};
use ublox_cellular::{
sockets::{
udp::{Ipv4Addr, SocketAddrV4},
SocketSet,
},
APNInfo, Apn, Config, ContextId, GsmClient, ProfileId,
};

use common::{
serial::{serialport, Serial},
timer::SysTimer,
};
use embedded_nal::nb;
use embedded_nal::TcpClient;
use heapless::{self, consts, spsc::Queue};
use std::time::Duration;

fn attach_gprs<C, RST, DTR, N, L>(gsm: &GsmClient<C, RST, DTR, N, L>) -> Result<(), GSMError>
where
C: AtatClient,
RST: OutputPin,
DTR: OutputPin,
N: ArrayLength<Option<ublox_cellular::sockets::SocketSetItem<L>>>,
L: ArrayLength<u8>,
{
gsm.init(true)?;
gsm.begin().unwrap();
gsm.attach_gprs().unwrap();
Ok(())
}

static mut SOCKET_SET: Option<SocketSet<consts::U6, consts::U2048>> = None;

fn main() {
env_logger::builder()
.filter_level(log::LevelFilter::Trace)
.init();

// Serial port settings
let settings = serialport::SerialPortSettings {
baud_rate: 115_200,
Expand Down Expand Up @@ -75,12 +56,20 @@ fn main() {
SOCKET_SET = Some(SocketSet::new());
}

let gsm = GsmClient::<_, Pin, Pin, _, _>::new(
let mut gsm = GsmClient::<_, _, consts::U6, consts::U2048>::new(
cell_client,
unsafe { SOCKET_SET.as_mut().unwrap() },
Config::new(APNInfo::new("em"), ""),
SysTimer::new(),
Config::new(""),
);

let socket_set: &'static mut _ = unsafe {
SOCKET_SET.as_mut().unwrap_or_else(|| {
panic!("Failed to get the static socket_set");
})
};

gsm.set_socket_storage(socket_set);

// Launch reading thread
thread::Builder::new()
.spawn(move || loop {
Expand All @@ -95,49 +84,49 @@ fn main() {
Err(e) => match e.kind() {
io::ErrorKind::Interrupted => {}
_ => {
log::error!("Serial reading thread error while reading: {}", e);
// log::error!("Serial reading thread error while reading: {}", e);
}
},
}
})
.unwrap();

if attach_gprs(&gsm).is_ok() {
let mut socket = {
let soc = <GsmClient<_, _, _, _, _> as TcpStack>::open(&gsm, Mode::Blocking)
.expect("Cannot open socket!");

gsm.connect(
soc,
// Connect to echo.u-blox.com:7
SocketAddrV4::new(Ipv4Addr::new(195, 34, 89, 241), 7).into(),
)
.expect("Failed to connect to remote!")
};

let mut cnt = 1;
loop {
thread::sleep(Duration::from_millis(5000));
let mut buf = [0u8; 256];
let read = <GsmClient<_, _, _, _, _> as TcpStack>::read(&gsm, &mut socket, &mut buf)
.expect("Failed to read from socket!");
if read > 0 {
log::info!("Read {:?} bytes from socket layer! - {:?}", read, unsafe {
core::str::from_utf8_unchecked(&buf[..read])
});
let apn_info = APNInfo {
apn: Apn::Given(heapless::String::from("em")),
..APNInfo::default()
};

let mut cnt = 1;
loop {
match gsm.data_service(ProfileId(0), ContextId(2), &apn_info) {
Err(nb::Error::WouldBlock) => {}
Err(nb::Error::Other(_e)) => {
// defmt::error!("Data Service error! {:?}", e);
}
Ok(data) => {
let mut socket = data.socket().expect("Cannot open socket!");

data.connect(
&mut socket,
// Connect to echo.u-blox.com:7
SocketAddrV4::new(Ipv4Addr::new(195, 34, 89, 241), 7).into(),
)
.expect("Failed to connect to remote!");

thread::sleep(Duration::from_millis(5000));
let mut buf = [0u8; 256];
let read = nb::block!(data.receive(&mut socket, &mut buf))
.expect("Failed to read from socket!");

if read > 0 {
// YAY
}

let _wrote =
nb::block!(data.send(&mut socket, format!("Whatup {}", cnt).as_bytes(),))
.expect("Failed to write to socket!");
cnt += 1;
}
let _wrote = <GsmClient<_, _, _, _, _> as TcpStack>::write(
&gsm,
&mut socket,
format!("Whatup {}", cnt).as_bytes(),
)
.expect("Failed to write to socket!");
log::info!(
"Writing {:?} bytes to socket layer! - {:?}",
_wrote,
format!("Whatup {}", cnt)
);
cnt += 1;
}
}
}
20 changes: 9 additions & 11 deletions examples/linux_jobs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,15 @@ repository = "https://github.com/BlackbirdHQ/ublox-cellular-rs"
edition = "2018"

[dependencies]
embedded-hal = "0.2.3"
atat = { version = "^0.4.1", features = ["derive"] }
log = { version = "0.4", default-features = false }
env_logger = "0.7.1"
linux-embedded-hal = "0.3.0"
serialport = "3.3.0"
nb = "0.1.2"
heapless = { version = "^0.5", features = ["serde"] }
rust-crypto = "^0.2"
mqttrust = { git = "https://github.com/BlackbirdHQ/mqttrust", rev = "2cdffdb" }
rustot = { git = "https://github.com/BlackbirdHQ/rustot", rev = "46d573a" }
mqttrust = { git = "https://github.com/BlackbirdHQ/mqttrust", rev = "4c6c35e" }
rustot = { git = "https://github.com/BlackbirdHQ/rustot", rev = "33c2ec9" }

embedded-hal = "1.0.0-alpha.4"
embedded-nal = "0.2.0"

atat = { version = "^0.6.0", features = ["derive"] }
heapless = { version = "^0.5.5", features = ["serde"] }

common_lib = { path = "../common_lib" }
ublox-cellular-rs = { path = "../../ublox-cellular", features = ["logging"] }
ublox-cellular-rs = { path = "../../ublox-cellular" }
2 changes: 1 addition & 1 deletion examples/linux_jobs/src/file_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ impl OtaPal for FileHandler {
if let Some(ref mut buf) = &mut self.filebuf {
let mut hasher = Sha1::new();
hasher.input(buf.get_ref());
log::info!("Sha1 is {:}!", hasher.result_str());
// log::info!("Sha1 is {:}!", hasher.result_str());
Ok(())
} else {
Err(OtaPalError::BadFileHandle)
Expand Down
Loading