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

feature(CI): Add test for AWS IoT Device Advisor #54

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
13 changes: 6 additions & 7 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,8 @@ jobs:
AWS_DEFAULT_REGION: ${{ secrets.MGMT_AWS_DEFAULT_REGION }}
AWS_ACCESS_KEY_ID: ${{ secrets.MGMT_AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.MGMT_AWS_SECRET_ACCESS_KEY }}
SUITE_ID: greb3uy2wtq3
THING_ARN: arn:aws:iot:eu-west-1:274906834921:thing/mqttrust
CERTIFICATE_ARN: arn:aws:iot:eu-west-1:274906834921:cert/e7280d8d316b58da3058037a2c1730d9eb15de50e96f4d47e54ea655266b76db
SUITE_ID: 1gaev57dq6i5
THING_ARN: arn:aws:iot:eu-west-1:411974994697:thing/mqttrust
steps:
- name: Checkout
uses: actions/checkout@v1
Expand All @@ -89,7 +88,7 @@ jobs:
- name: Get AWS_HOSTNAME
id: hostname
run: |
hostname=$(aws iotdeviceadvisor get-endpoint --output text --query endpoint)
hostname=$(aws iotdeviceadvisor get-endpoint --thing-arn ${{ env.THING_ARN }} --output text --query endpoint)
ret=$?
echo "::set-output name=AWS_HOSTNAME::$hostname"
exit $ret
Expand All @@ -105,7 +104,7 @@ jobs:
- name: Start test suite
id: test_suite
run: |
suite_id=$(aws iotdeviceadvisor start-suite-run --suite-definition-id ${{ env.SUITE_ID }} --suite-run-configuration "primaryDevice={thingArn=${{ env.THING_ARN }},certificateArn=${{ env.CERTIFICATE_ARN }}}" --output text --query suiteRunId)
suite_id=$(aws iotdeviceadvisor start-suite-run --suite-definition-id ${{ env.SUITE_ID }} --suite-run-configuration "primaryDevice={thingArn=${{ env.THING_ARN }}},parallelRun=true" --output text --query suiteRunId)
ret=$?
echo "::set-output name=SUITE_RUN_ID::$suite_id"
exit $ret
Expand All @@ -121,9 +120,9 @@ jobs:

- name: Monitor test run
run: |
chmod +x ./.github/scripts/da_monitor.sh
chmod +x ./scripts/da_monitor.sh
echo ${{ env.SUITE_ID }} ${{ steps.test_suite.outputs.SUITE_RUN_ID }} ${{ steps.binary.outputs.PID }}
./.github/scripts/da_monitor.sh ${{ env.SUITE_ID }} ${{ steps.test_suite.outputs.SUITE_RUN_ID }} ${{ steps.binary.outputs.PID }}
./scripts/da_monitor.sh ${{ env.SUITE_ID }} ${{ steps.test_suite.outputs.SUITE_RUN_ID }} ${{ steps.binary.outputs.PID }}

- name: Kill test binary process
if: ${{ always() }}
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
.gdb_history
Cargo.lock
target/
device_advisor_integration.log
7 changes: 5 additions & 2 deletions mqttrust_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,14 @@ defmt = { version = "^0.3", optional = true }
[dev-dependencies]
native-tls = { version = "^0.2" }
dns-lookup = "1.0.3"
env_logger = "0.9.0"
env_logger = "0.11"
static_cell = "2.1"

[features]
default = []

std = []

defmt-impl = ["defmt", "mqttrust/defmt-impl", "heapless/defmt-impl", "fugit/defmt"]
log = ["dep:log", "mqttrust/log"]

defmt-impl = ["dep:defmt", "mqttrust/defmt-impl", "heapless/defmt-impl", "fugit/defmt"]
67 changes: 45 additions & 22 deletions mqttrust_core/examples/aws_device_advisor.rs
Original file line number Diff line number Diff line change
@@ -1,56 +1,77 @@
mod common;

use mqttrust::encoding::v4::{Connack, ConnectReturnCode};
use mqttrust::{Mqtt, QoS, SubscribeTopic};
use mqttrust_core::bbqueue::BBBuffer;
use mqttrust_core::{EventLoop, MqttOptions, Notification};

use common::clock::SysClock;
use common::network::Network;
use native_tls::TlsConnector;
use static_cell::StaticCell;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::thread;

use crate::common::credentials;

static mut Q: BBBuffer<{ 1024 * 6 }> = BBBuffer::new();
static mut Q: BBBuffer<{ 1024 * 60 }> = BBBuffer::new();

fn main() {
env_logger::init();

let (p, c) = unsafe { Q.try_split_framed().unwrap() };

let hostname = credentials::HOSTNAME.unwrap();
static HOSTNAME: StaticCell<String> = StaticCell::new();
let hostname = HOSTNAME.init(credentials::hostname());

log::info!(
"Starting device advisor test on endpoint {}",
hostname.as_str()
);

let connector = TlsConnector::builder()
.identity(credentials::identity())
.add_root_certificate(credentials::root_ca())
.build()
.unwrap();

let mut network = Network::new_tls(connector, String::from(hostname));
let mut network = Network::new_tls(connector, hostname.clone());

let thing_name = "mqttrust";

let mut mqtt_eventloop = EventLoop::new(
c,
SysClock::new(),
MqttOptions::new(thing_name, hostname.into(), 8883),
MqttOptions::new(thing_name, hostname.as_str().into(), 8883),
);

let mqtt_client = mqttrust_core::Client::new(p, thing_name);

let connected = Arc::new(AtomicBool::new(false));
let con = connected.clone();

thread::Builder::new()
.name("eventloop".to_string())
.spawn(move || loop {
match nb::block!(mqtt_eventloop.connect(&mut network)) {
Err(_) => continue,
Ok(true) => {
log::info!("Successfully connected to broker");
Ok(Some(Notification::ConnAck(Connack {
session_present,
code: ConnectReturnCode::Accepted,
}))) => {
log::info!(
"Successfully connected to broker. session_present: {}",
session_present
);
con.store(true, std::sync::atomic::Ordering::Release);
}
Ok(n) => {
log::info!("Received {:?} during connect", n);
}
Ok(false) => {}
}

match mqtt_eventloop.yield_event(&mut network) {
match nb::block!(mqtt_eventloop.yield_event(&mut network)) {
Ok(Notification::Publish(_)) => {}
Ok(n) => {
log::trace!("{:?}", n);
Expand All @@ -62,19 +83,21 @@ fn main() {

loop {
thread::sleep(std::time::Duration::from_millis(5000));
mqtt_client
.subscribe(&[SubscribeTopic {
topic_path: format!("{}/device/advisor", thing_name).as_str(),
qos: QoS::AtLeastOnce,
}])
.unwrap();

mqtt_client
.publish(
format!("{}/device/advisor/hello", thing_name).as_str(),
format!("Hello from {}", thing_name).as_bytes(),
QoS::AtLeastOnce,
)
.unwrap();
if connected.load(std::sync::atomic::Ordering::Acquire) {
mqtt_client
.subscribe(&[SubscribeTopic {
topic_path: format!("plc/output/{}", thing_name).as_str(),
qos: QoS::AtLeastOnce,
}])
.unwrap();

mqtt_client
.publish(
format!("plc/input/{}", thing_name).as_str(),
format!("Hello from {}", thing_name).as_bytes(),
QoS::AtLeastOnce,
)
.unwrap();
}
}
}
2 changes: 0 additions & 2 deletions mqttrust_core/examples/common/clock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,12 @@ use std::{
};
pub struct SysClock {
start_time: u32,
countdown_end: Option<u32>,
}

impl SysClock {
pub fn new() -> Self {
Self {
start_time: Self::epoch(),
countdown_end: None,
}
}

Expand Down
4 changes: 3 additions & 1 deletion mqttrust_core/examples/common/credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

use native_tls::{Certificate, Identity};

pub fn identity() -> Identity {

Check warning on line 5 in mqttrust_core/examples/common/credentials.rs

View workflow job for this annotation

GitHub Actions / Integration Test

function `identity` is never used
let pw = env::var("DEVICE_ADVISOR_PASSWORD").unwrap();
Identity::from_pkcs12(include_bytes!("../secrets/identity.pfx"), pw.as_str()).unwrap()
}

pub fn root_ca() -> Certificate {

Check warning on line 10 in mqttrust_core/examples/common/credentials.rs

View workflow job for this annotation

GitHub Actions / Integration Test

function `root_ca` is never used
Certificate::from_pem(include_bytes!("../secrets/root-ca.pem")).unwrap()
}

pub const HOSTNAME: Option<&'static str> = option_env!("AWS_HOSTNAME");
pub fn hostname() -> String {

Check warning on line 14 in mqttrust_core/examples/common/credentials.rs

View workflow job for this annotation

GitHub Actions / Integration Test

function `hostname` is never used
env::var("AWS_HOSTNAME").unwrap()
}
Binary file modified mqttrust_core/examples/secrets/identity.pfx
Binary file not shown.
54 changes: 41 additions & 13 deletions mqttrust_core/src/eventloop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use core::ops::DerefMut;
use core::ops::RangeTo;
use embedded_nal::{AddrType, Dns, SocketAddr, TcpClientStack};
use fugit::ExtU32;
use fugit::{ExtU32, TimerDurationU32};
use heapless::{String, Vec};
use mqttrust::encoding::v4::{decode_slice, encode_slice, Connect, Packet, Protocol};

Expand All @@ -24,6 +24,7 @@
/// Request stream
pub(crate) requests: Option<FrameConsumer<'a, L>>,
network_handle: NetworkHandle<S>,
connect_counter: u8,
}

impl<'a, 'b, S, O, const TIMER_HZ: u32, const L: usize> EventLoop<'a, 'b, S, O, TIMER_HZ, L>
Expand All @@ -41,6 +42,7 @@
options,
requests: Some(requests),
network_handle: NetworkHandle::new(),
connect_counter: 0,
}
}

Expand All @@ -51,10 +53,10 @@
self.requests.take()
}

pub fn connect<N: Dns + TcpClientStack<TcpSocket = S> + ?Sized>(
&mut self,
network: &mut N,
) -> nb::Result<bool, EventError> {
) -> nb::Result<Option<Notification>, EventError> {

Check warning on line 59 in mqttrust_core/src/eventloop.rs

View workflow job for this annotation

GitHub Actions / clippy

docs for function returning `Result` missing `# Errors` section

warning: docs for function returning `Result` missing `# Errors` section --> mqttrust_core/src/eventloop.rs:56:5 | 56 | / pub fn connect<N: Dns + TcpClientStack<TcpSocket = S> + ?Sized>( 57 | | &mut self, 58 | | network: &mut N, 59 | | ) -> nb::Result<Option<Notification>, EventError> { | |_____________________________________________________^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#missing_errors_doc = note: `-W clippy::missing-errors-doc` implied by `-W clippy::pedantic` = help: to override `-W clippy::pedantic` add `#[allow(clippy::missing_errors_doc)]`
// connect to the broker
match self.network_handle.is_connected(network) {
Ok(false) => {
Expand Down Expand Up @@ -112,7 +114,7 @@
// };

// qos_0 || (self.requests.ready() && qos_space)
qos_space

Check warning on line 117 in mqttrust_core/src/eventloop.rs

View workflow job for this annotation

GitHub Actions / clippy

returning the result of a `let` binding from a block

warning: returning the result of a `let` binding from a block --> mqttrust_core/src/eventloop.rs:117:9 | 107 | let qos_space = self.state.outgoing_pub.len() < self.state.outgoing_pub.capacity(); | ----------------------------------------------------------------------------------- unnecessary `let` binding ... 117 | qos_space | ^^^^^^^^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#let_and_return = note: `-W clippy::let-and-return` implied by `-W clippy::all` = help: to override `-W clippy::all` add `#[allow(clippy::let_and_return)]` help: return the expression directly | 107 ~ 108 | ... 116 | // qos_0 || (self.requests.ready() && qos_space) 117 ~ self.state.outgoing_pub.len() < self.state.outgoing_pub.capacity() |
}

/// Selects an event from the client's requests, incoming packets from the
Expand All @@ -128,7 +130,7 @@
match &mut self.requests {
Some(requests) => {
if let Some(mut grant) = requests.read() {
let mut packet = SerializedPacket(grant.deref_mut());

Check warning on line 133 in mqttrust_core/src/eventloop.rs

View workflow job for this annotation

GitHub Actions / clippy

explicit `deref_mut` method call

warning: explicit `deref_mut` method call --> mqttrust_core/src/eventloop.rs:133:59 | 133 | let mut packet = SerializedPacket(grant.deref_mut()); | ^^^^^^^^^^^^^^^^^ help: try: `&mut *grant` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#explicit_deref_methods
match self.state.handle_outgoing_request(&mut packet, &now) {
Ok(()) => {
self.network_handle.send(network, packet.to_inner())?;
Expand Down Expand Up @@ -180,7 +182,7 @@
// Update inflight's timestamp for later retrials
inflight.last_touch_entry().insert(now);
let packet = inflight.packet(*pid).map_err(EventError::from)?;
self.network_handle.send(network, &packet)?;

Check warning on line 185 in mqttrust_core/src/eventloop.rs

View workflow job for this annotation

GitHub Actions / clippy

this expression creates a reference which is immediately dereferenced by the compiler

warning: this expression creates a reference which is immediately dereferenced by the compiler --> mqttrust_core/src/eventloop.rs:185:47 | 185 | self.network_handle.send(network, &packet)?; | ^^^^^^^ help: change this to: `packet` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow
}

notification.ok_or(nb::Error::WouldBlock)
Expand All @@ -189,10 +191,10 @@
/// Yields notification from events. All the error raised while processing
/// event is reported as an `Ok` value of `Notification::Abort`.
#[must_use = "Eventloop should be iterated over a loop to make progress"]
pub fn yield_event<N: TcpClientStack<TcpSocket = S> + ?Sized>(
&mut self,
network: &mut N,
) -> nb::Result<Notification, Infallible> {

Check warning on line 197 in mqttrust_core/src/eventloop.rs

View workflow job for this annotation

GitHub Actions / clippy

docs for function returning `Result` missing `# Errors` section

warning: docs for function returning `Result` missing `# Errors` section --> mqttrust_core/src/eventloop.rs:194:5 | 194 | / pub fn yield_event<N: TcpClientStack<TcpSocket = S> + ?Sized>( 195 | | &mut self, 196 | | network: &mut N, 197 | | ) -> nb::Result<Notification, Infallible> { | |_____________________________________________^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#missing_errors_doc
if self.network_handle.socket.is_none() {
return Ok(Notification::Abort(EventError::Network(
NetworkError::NoSocket,
Expand All @@ -216,16 +218,23 @@
}
}

fn backoff(&self) -> TimerDurationU32<TIMER_HZ> {
let base_time_ms: u32 = 200;
let backoff = base_time_ms.saturating_mul(u32::pow(2, self.connect_counter as u32));

Check warning on line 223 in mqttrust_core/src/eventloop.rs

View workflow job for this annotation

GitHub Actions / clippy

casting `u8` to `u32` may become silently lossy if you later change the type

warning: casting `u8` to `u32` may become silently lossy if you later change the type --> mqttrust_core/src/eventloop.rs:223:63 | 223 | let backoff = base_time_ms.saturating_mul(u32::pow(2, self.connect_counter as u32)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `u32::from(self.connect_counter)` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#cast_lossless = note: `-W clippy::cast-lossless` implied by `-W clippy::pedantic` = help: to override `-W clippy::pedantic` add `#[allow(clippy::cast_lossless)]`

core::cmp::min(50.secs(), backoff.millis())
}

fn mqtt_connect<N: TcpClientStack<TcpSocket = S> + ?Sized>(
&mut self,
network: &mut N,
) -> nb::Result<bool, EventError> {
) -> nb::Result<Option<Notification>, EventError> {
match self.state.connection_status {
MqttConnectionStatus::Connected => Ok(false),
MqttConnectionStatus::Connected => Ok(None),
MqttConnectionStatus::Disconnected => {
info!("MQTT connecting..");
let now = self.last_outgoing_timer.now();
self.state.last_ping_entry().insert(now);
self.connect_counter += 1;

self.state.await_pingresp = false;
self.network_handle.rx_buf.init();
Expand All @@ -234,7 +243,7 @@

let connect = Packet::Connect(Connect {
protocol: Protocol::MQTT311,
keep_alive: (self.options.keep_alive_ms() / 1000) as u16,

Check warning on line 246 in mqttrust_core/src/eventloop.rs

View workflow job for this annotation

GitHub Actions / clippy

casting `u32` to `u16` may truncate the value

warning: casting `u32` to `u16` may truncate the value --> mqttrust_core/src/eventloop.rs:246:33 | 246 | keep_alive: (self.options.keep_alive_ms() / 1000) as u16, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: if this is intentional allow the lint with `#[allow(clippy::cast_possible_truncation)]` ... = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#cast_possible_truncation = note: `-W clippy::cast-possible-truncation` implied by `-W clippy::pedantic` = help: to override `-W clippy::pedantic` add `#[allow(clippy::cast_possible_truncation)]` help: ... or use `try_from` and handle the error accordingly | 246 | keep_alive: u16::try_from(self.options.keep_alive_ms() / 1000), | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
client_id: self.options.client_id(),
clean_session: self.options.clean_session(),
last_will: self.options.last_will(),
Expand All @@ -242,6 +251,12 @@
password,
});

info!(
"MQTT connecting.. Attempt: {}. Backoff time: {}",
self.connect_counter,
self.backoff().to_millis()
);

// mqtt connection with timeout
self.network_handle.send_packet(network, &connect)?;
self.state.handle_outgoing_connect();
Expand All @@ -250,25 +265,37 @@
MqttConnectionStatus::Handshake => {
let now = self.last_outgoing_timer.now();

let backoff_time = self.backoff();

if self
.state
.last_ping_entry()
.or_insert(now)
.has_elapsed(&now, 50.secs())
.has_elapsed(&now, backoff_time)
{
warn!("Timed out waiting for connect packet!");
return Err(nb::Error::Other(EventError::Timeout));
}

self.network_handle
let res = self
.network_handle
.receive(network)
.map_err(|e| e.map(EventError::Network))?
.decode(&mut self.state)
.and_then(|(n, p)| {
if n.is_none() && p.is_none() {
return Err(nb::Error::WouldBlock);
}
Ok(n.map(|n| n == Notification::ConnAck).unwrap_or(false))
})
Ok(n)
});

match res {
Ok(r) => {
self.connect_counter = 0;
Ok(r)
}
Err(e) => Err(e),
}
}
}
}
Expand All @@ -284,7 +311,7 @@
impl<S> NetworkHandle<S> {
fn lookup_host<N: Dns + TcpClientStack<TcpSocket = S> + ?Sized>(
network: &mut N,
broker: Broker,

Check warning on line 314 in mqttrust_core/src/eventloop.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 --> mqttrust_core/src/eventloop.rs:314:17 | 314 | broker: Broker, | ^^^^^^ help: consider taking a reference instead: `&Broker` | help: consider marking this type as `Copy` --> mqttrust_core/src/options.rs:5:1 | 5 | pub enum Broker<'a> { | ^^^^^^^^^^^^^^^^^^^ = 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` = help: to override `-W clippy::pedantic` add `#[allow(clippy::needless_pass_by_value)]`
port: u16,
) -> Result<(String<256>, SocketAddr), NetworkError> {
match broker {
Expand Down Expand Up @@ -324,12 +351,12 @@
&self,
network: &mut N,
) -> Result<bool, NetworkError> {
match self.socket {
Some(ref socket) => network
.is_connected(socket)
.map_err(|_e| NetworkError::SocketClosed),
None => Err(NetworkError::SocketClosed),
}

Check warning on line 359 in mqttrust_core/src/eventloop.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 --> mqttrust_core/src/eventloop.rs:354:9 | 354 | / match self.socket { 355 | | Some(ref socket) => network 356 | | .is_connected(socket) 357 | | .map_err(|_e| NetworkError::SocketClosed), 358 | | None => Err(NetworkError::SocketClosed), 359 | | } | |_________^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#option_if_let_else help: try | 354 ~ self.socket.as_ref().map_or(Err(NetworkError::SocketClosed), |socket| network 355 + .is_connected(socket) 356 + .map_err(|_e| NetworkError::SocketClosed)) |
}

fn connect<N: Dns + TcpClientStack<TcpSocket = S> + ?Sized>(
Expand All @@ -346,7 +373,7 @@
};

let (broker, port) = broker;
let (_hostname, socket_addr) = NetworkHandle::<S>::lookup_host(network, broker, port)?;

Check warning on line 376 in mqttrust_core/src/eventloop.rs

View workflow job for this annotation

GitHub Actions / clippy

unnecessary structure name repetition

warning: unnecessary structure name repetition --> mqttrust_core/src/eventloop.rs:376:40 | 376 | let (_hostname, socket_addr) = NetworkHandle::<S>::lookup_host(network, broker, port)?; | ^^^^^^^^^^^^^^^^^^ help: use the applicable keyword: `Self` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#use_self = note: `-W clippy::use-self` implied by `-W clippy::nursery` = help: to override `-W clippy::nursery` add `#[allow(clippy::use_self)]`

nb::block!(network.connect(socket, socket_addr)).map_err(|_| {
if let Some(socket) = self.socket.take() {
Expand All @@ -356,7 +383,7 @@
})
}

pub fn send_packet<'d, N: TcpClientStack<TcpSocket = S> + ?Sized>(

Check warning on line 386 in mqttrust_core/src/eventloop.rs

View workflow job for this annotation

GitHub Actions / clippy

this lifetime isn't used in the function definition

warning: this lifetime isn't used in the function definition --> mqttrust_core/src/eventloop.rs:386:24 | 386 | pub fn send_packet<'d, N: TcpClientStack<TcpSocket = S> + ?Sized>( | ^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#extra_unused_lifetimes = note: `-W clippy::extra-unused-lifetimes` implied by `-W clippy::all` = help: to override `-W clippy::all` add `#[allow(clippy::extra_unused_lifetimes)]`
&mut self,
network: &mut N,
pkt: &Packet,
Expand All @@ -366,7 +393,7 @@
.resize_default(self.tx_buf.capacity())
.unwrap_or_else(|()| unreachable!("Input length equals to the current capacity."));

let size = encode_slice(&pkt, self.tx_buf.as_mut()).map_err(EventError::Encoding)?;

Check warning on line 396 in mqttrust_core/src/eventloop.rs

View workflow job for this annotation

GitHub Actions / clippy

this expression creates a reference which is immediately dereferenced by the compiler

warning: this expression creates a reference which is immediately dereferenced by the compiler --> mqttrust_core/src/eventloop.rs:396:33 | 396 | let size = encode_slice(&pkt, self.tx_buf.as_mut()).map_err(EventError::Encoding)?; | ^^^^ help: change this to: `pkt` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow

let socket = self
.socket
Expand All @@ -381,7 +408,7 @@
Ok(length)
}

pub fn send<'d, N: TcpClientStack<TcpSocket = S> + ?Sized>(

Check warning on line 411 in mqttrust_core/src/eventloop.rs

View workflow job for this annotation

GitHub Actions / clippy

this lifetime isn't used in the function definition

warning: this lifetime isn't used in the function definition --> mqttrust_core/src/eventloop.rs:411:17 | 411 | pub fn send<'d, N: TcpClientStack<TcpSocket = S> + ?Sized>( | ^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#extra_unused_lifetimes
&mut self,
network: &mut N,
pkt: &[u8],
Expand All @@ -391,7 +418,7 @@
.as_mut()
.ok_or(EventError::Network(NetworkError::NoSocket))?;

let length = nb::block!(network.send(socket, &pkt)).map_err(|_| {

Check warning on line 421 in mqttrust_core/src/eventloop.rs

View workflow job for this annotation

GitHub Actions / clippy

this expression creates a reference which is immediately dereferenced by the compiler

warning: this expression creates a reference which is immediately dereferenced by the compiler --> mqttrust_core/src/eventloop.rs:421:54 | 421 | let length = nb::block!(network.send(socket, &pkt)).map_err(|_| { | ^^^^ help: change this to: `pkt` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow
error!("[send] NetworkError::Write");
EventError::Network(NetworkError::Write)
})?;
Expand All @@ -417,7 +444,7 @@
#[derive(Debug)]
struct PacketBuffer {
range: RangeTo<usize>,
buffer: Vec<u8, 4096>,
buffer: Vec<u8, { 1024 * 16 }>,
}

impl PacketBuffer {
Expand Down Expand Up @@ -518,7 +545,7 @@
})
.enumerate()
.fold(1, |acc, (i, length)| {
acc + 1 + length * 0x80_usize.pow(i as u32)

Check warning on line 548 in mqttrust_core/src/eventloop.rs

View workflow job for this annotation

GitHub Actions / clippy

casting `usize` to `u32` may truncate the value on targets with 64-bit wide pointers

warning: casting `usize` to `u32` may truncate the value on targets with 64-bit wide pointers --> mqttrust_core/src/eventloop.rs:548:51 | 548 | acc + 1 + length * 0x80_usize.pow(i as u32) | ^^^^^^^^ | = help: if this is intentional allow the lint with `#[allow(clippy::cast_possible_truncation)]` ... = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#cast_possible_truncation help: ... or use `try_from` and handle the error accordingly | 548 | acc + 1 + length * 0x80_usize.pow(u32::try_from(i)) | ~~~~~~~~~~~~~~~~
})
.into()
}
Expand All @@ -536,6 +563,7 @@
Err(EventError::Encoding(e).into())
}
Ok(Some(packet)) => {
warn!("Got packet! {:?}", packet);
self.is_err.replace(false);
state
.handle_incoming_packet(packet)
Expand Down Expand Up @@ -679,7 +707,7 @@
let mut state = MqttState::<1000>::new();
const LEN: usize = 1024 * 10;
static mut PUBLISH_MEM: [u8; LEN] = [0u8; LEN];
BoxedPublish::grow(unsafe { &mut PUBLISH_MEM });

Check warning on line 710 in mqttrust_core/src/eventloop.rs

View workflow job for this annotation

GitHub Actions / Coverage

creating a mutable reference to mutable static is discouraged

Check warning on line 710 in mqttrust_core/src/eventloop.rs

View workflow job for this annotation

GitHub Actions / Test

creating a mutable reference to mutable static is discouraged

let mut rx_buf = PacketBuffer::new();
let connack = Connack {
Expand All @@ -699,12 +727,12 @@
rx_buf.range.end += connack_len;
let publish_len = encode_slice(&Packet::from(publish.clone()), rx_buf.buffer()).unwrap();
rx_buf.range.end += publish_len;
assert_eq!(rx_buf.range.end, rx_buf.buffer.capacity());
assert_eq!(rx_buf.range.end, 4096);

// Decode the first Connack packet on the Handshake state.
state.connection_status = MqttConnectionStatus::Handshake;
let (n, p) = PacketDecoder::new(&mut rx_buf).decode(&mut state).unwrap();
assert_eq!(n, Some(Notification::ConnAck));
assert!(matches!(n, Some(Notification::ConnAck(_))));
assert_eq!(p, None);

let mut pkg = SerializedPacket(&mut rx_buf.buffer[rx_buf.range]);
Expand All @@ -728,7 +756,7 @@
let mut state = MqttState::<1000>::new();
const LEN: usize = 1024 * 10;
static mut PUBLISH_MEM: [u8; LEN] = [0u8; LEN];
BoxedPublish::grow(unsafe { &mut PUBLISH_MEM });

Check warning on line 759 in mqttrust_core/src/eventloop.rs

View workflow job for this annotation

GitHub Actions / Coverage

creating a mutable reference to mutable static is discouraged

Check warning on line 759 in mqttrust_core/src/eventloop.rs

View workflow job for this annotation

GitHub Actions / Test

creating a mutable reference to mutable static is discouraged

let mut rx_buf = PacketBuffer::new();
let connack_malformed = Connack {
Expand All @@ -750,7 +778,7 @@
rx_buf.range.end += connack_malformed_len;
let publish_len = encode_slice(&Packet::from(publish.clone()), rx_buf.buffer()).unwrap();
rx_buf.range.end += publish_len;
assert_eq!(rx_buf.range.end, rx_buf.buffer.capacity());
assert_eq!(rx_buf.range.end, 4096);

// When a packet is malformed, we cannot tell its length. The decoder
// discards the entire buffer.
Expand Down
3 changes: 2 additions & 1 deletion mqttrust_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@
use core::convert::TryFrom;
pub use eventloop::EventLoop;
use heapless::{String, Vec};
use mqttrust::encoding::v4::Connack;
pub use mqttrust::encoding::v4::{Pid, Publish, QoS, QosPid, Suback};
pub use mqttrust::*;
pub use options::{Broker, MqttOptions};
use state::StateError;

#[derive(Debug, PartialEq)]

Check warning on line 27 in mqttrust_core/src/lib.rs

View workflow job for this annotation

GitHub Actions / clippy

you are deriving `PartialEq` and can implement `Eq`

warning: you are deriving `PartialEq` and can implement `Eq` --> mqttrust_core/src/lib.rs:27:17 | 27 | #[derive(Debug, PartialEq)] | ^^^^^^^^^ help: consider deriving `Eq` as well: `PartialEq, Eq` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#derive_partial_eq_without_eq
#[cfg_attr(feature = "defmt-impl", derive(defmt::Format))]
pub struct PublishNotification {
pub dup: bool,
Expand All @@ -39,7 +40,7 @@
// #[cfg_attr(feature = "defmt-impl", derive(defmt::Format))]
pub enum Notification {
/// Incoming connection acknowledge
ConnAck,
ConnAck(Connack),
/// Incoming publish from the broker
#[cfg(not(feature = "std"))]
Publish(heapless::pool::singleton::Box<state::BoxedPublish, heapless::pool::Init>),
Expand All @@ -65,12 +66,12 @@
type Error = StateError;

fn try_from(p: Publish<'a>) -> Result<Self, Self::Error> {
Ok(PublishNotification {

Check warning on line 69 in mqttrust_core/src/lib.rs

View workflow job for this annotation

GitHub Actions / clippy

unnecessary structure name repetition

warning: unnecessary structure name repetition --> mqttrust_core/src/lib.rs:69:12 | 69 | Ok(PublishNotification { | ^^^^^^^^^^^^^^^^^^^ help: use the applicable keyword: `Self` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#use_self
dup: p.dup,
qospid: p.qos,
retain: p.retain,
topic_name: String::from(p.topic_name),
payload: Vec::from_slice(p.payload).map_err(|_| {

Check warning on line 74 in mqttrust_core/src/lib.rs

View workflow job for this annotation

GitHub Actions / clippy

matching over `()` is more explicit

warning: matching over `()` is more explicit --> mqttrust_core/src/lib.rs:74:58 | 74 | payload: Vec::from_slice(p.payload).map_err(|_| { | ^ help: use `()` instead of `_`: `()` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#ignored_unit_patterns = note: `-W clippy::ignored-unit-patterns` implied by `-W clippy::pedantic` = help: to override `-W clippy::pedantic` add `#[allow(clippy::ignored_unit_patterns)]`
error!("Failed to convert payload to notification!");
StateError::PayloadEncoding
})?,
Expand All @@ -91,7 +92,7 @@
RequestsNotAvailable,
}

#[derive(Debug, PartialEq)]

Check warning on line 95 in mqttrust_core/src/lib.rs

View workflow job for this annotation

GitHub Actions / clippy

you are deriving `PartialEq` and can implement `Eq`

warning: you are deriving `PartialEq` and can implement `Eq` --> mqttrust_core/src/lib.rs:95:17 | 95 | #[derive(Debug, PartialEq)] | ^^^^^^^^^ help: consider deriving `Eq` as well: `PartialEq, Eq` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#derive_partial_eq_without_eq
#[cfg_attr(feature = "defmt-impl", derive(defmt::Format))]
pub enum NetworkError {
Read,
Expand All @@ -105,12 +106,12 @@

impl From<mqttrust::encoding::v4::Error> for EventError {
fn from(e: mqttrust::encoding::v4::Error) -> Self {
EventError::Encoding(e)

Check warning on line 109 in mqttrust_core/src/lib.rs

View workflow job for this annotation

GitHub Actions / clippy

unnecessary structure name repetition

warning: unnecessary structure name repetition --> mqttrust_core/src/lib.rs:109:9 | 109 | EventError::Encoding(e) | ^^^^^^^^^^ help: use the applicable keyword: `Self` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#use_self
}
}

impl From<StateError> for EventError {
fn from(e: StateError) -> Self {
EventError::MqttState(e)

Check warning on line 115 in mqttrust_core/src/lib.rs

View workflow job for this annotation

GitHub Actions / clippy

unnecessary structure name repetition

warning: unnecessary structure name repetition --> mqttrust_core/src/lib.rs:115:9 | 115 | EventError::MqttState(e) | ^^^^^^^^^^ help: use the applicable keyword: `Self` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#use_self
}
}
Loading
Loading