Struct Client

Source
pub struct Client<'a> { /* private fields */ }
Expand description

W5500 MQTT client.

§Topic Arguments

In the interest of minimal code size topic arguments are not validated, you must adhere to the topic rules yourself, see Topic Names and Topic Filters. The MQTT server will disconnect if an invalid topic is used.

Implementations§

Source§

impl<'a> Client<'a>

Source

pub fn new(sn: Sn, src_port: u16, server: SocketAddrV4) -> Self

Create a new MQTT client.

§Arguments
  • sn - The socket number to use for MQTT.
  • src_port - The MQTT source port, this is typically SRC_PORT.
  • server - The IP address and port for the MQTT server.
§Example
use w5500_mqtt::{
    ll::{
        net::{Ipv4Addr, SocketAddrV4},
        Sn,
    },
    Client, DST_PORT, SRC_PORT,
};

let client: Client = Client::new(
    Sn::Sn2,
    SRC_PORT,
    SocketAddrV4::new(Ipv4Addr::new(192, 168, 5, 6), DST_PORT),
);
Source

pub fn set_client_id(&mut self, client_id: ClientId<'a>)

Set the MQTT client ID.

This will only apply for new connections. Call this after new, before calling process.

§Example
use w5500_mqtt::{
    ll::{
        net::{Ipv4Addr, SocketAddrV4},
        Sn,
    },
    Client, ClientId, DST_PORT, SRC_PORT,
};

let mut client: Client = Client::new(
    Sn::Sn2,
    SRC_PORT,
    SocketAddrV4::new(Ipv4Addr::new(192, 168, 5, 6), DST_PORT),
);

const CLIENT_ID: ClientId = ClientId::new_unwrapped("MYDEVICE");
client.set_client_id(CLIENT_ID);
Source

pub fn process<'w, W5500: Registers>( &mut self, w5500: &'w mut W5500, monotonic_secs: u32, ) -> Result<Event<W5500::Error, TcpReader<'w, W5500>>, Error<W5500::Error>>

Process the MQTT client.

This should be called repeatedly until it returns:

  • Err(_) What to do upon errors is up to you. Calling process again will re-initialize the client.
  • Ok(Event::CallAfter(seconds)) Call this method again after the number of seconds indicated.
  • Ok(Event::None) The client is idle; you can call subscribe and publish.

This should also be called when there is a pending socket interrupt.

§Example
use w5500_mqtt::{Client, Error, Event};

fn my_rtos_task(client: &mut Client, w5500: &mut MyW5500) -> Result<(), Error<W5500Error>> {
    loop {
        match client.process(w5500, monotonic_secs()) {
            Ok(Event::ConnAck) => {
                client.subscribe(w5500, "/demo/topic/#")?;
            }
            Ok(Event::CallAfter(secs)) => {
                spawn_at_this_many_seconds_in_the_future(secs);
                break;
            }
            Ok(Event::Publish(mut reader)) => {
                let mut topic_buf: [u8; 32] = [0; 32];
                let mut payload_buf: [u8; 32] = [0; 32];
                let topic_len: u16 = reader.read_topic(&mut topic_buf)?;
                let payload_len: u16 = reader.read_payload(&mut payload_buf)?;
                reader.done()?;

                // do something with the topic and payload
            }
            Ok(Event::SubAck(ack)) => {
                // this does not handle failed subscriptions
                log::info!("SubAck {:?}", ack)
            }
            Ok(Event::UnSubAck(ack)) => {
                log::info!("UnsubAck {:?}", ack)
            }
            Ok(Event::None) => break,
            Err(e) => {
                log::error!("oh no, an error! {e:?}");
                // try again in a minute
                spawn_at_this_many_seconds_in_the_future(60);
                break;
            }
        }
    }

    Ok(())
}
Source

pub fn is_connected(&self) -> bool

Returns true if the MQTT client is connected.

Source

pub fn publish<W5500: Registers>( &mut self, w5500: &mut W5500, topic: &str, payload: &[u8], ) -> Result<(), Error<W5500::Error>>

Publish data to the MQTT broker.

§Examples
use w5500_mqtt::{
    ll::{
        net::{Ipv4Addr, SocketAddrV4},
        Sn,
    },
    Client, ClientId, Event, DST_PORT, SRC_PORT,
};

let mut client: Client = Client::new(
    Sn::Sn2,
    SRC_PORT,
    SocketAddrV4::new(Ipv4Addr::new(192, 168, 5, 6), DST_PORT),
);

// wait for a connection or die trying
while !matches!(client.process(&mut w5500, monotonic_secs())?, Event::None) {}

client.publish(&mut w5500, "topic", b"data")?;
Source

pub fn subscribe<W5500: Registers>( &mut self, w5500: &mut W5500, filter: &str, ) -> Result<u16, Error<W5500::Error>>

Subscribe to a topic.

§Return Value

The return value is a u16 packet identifier. This can be compared to Event::SubAck to determine when the subscription is active.

The packet identifier is zero (invalid) when filter is empty.

§Examples
use w5500_mqtt::{
    ll::{
        net::{Ipv4Addr, SocketAddrV4},
        Sn,
    },
    Client, ClientId, Event, DST_PORT, SRC_PORT,
};

let mut client: Client = Client::new(
    Sn::Sn2,
    SRC_PORT,
    SocketAddrV4::new(Ipv4Addr::new(192, 168, 5, 6), DST_PORT),
);

// wait for a connection or die trying
while !matches!(client.process(&mut w5500, monotonic_secs())?, Event::None) {}

client.subscribe(&mut w5500, "topic")?;
Source

pub fn unsubscribe<W5500: Registers>( &mut self, w5500: &mut W5500, filter: &str, ) -> Result<u16, Error<W5500::Error>>

Unsubscribe from a topic.

§Return Value

The return value is a u16 packet identifier. This can be compared to Event::UnsubAck to determine when the subscription has been deleted.

The packet identifier is zero (invalid) when filter is empty.

Trait Implementations§

Source§

impl<'a> Debug for Client<'a>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'a> Format for Client<'a>
where Sn: Format, SocketAddrV4: Format, Option<ClientId<'a>>: Format, StateTimeout: Format,

Source§

fn format(&self, f: Formatter<'_>)

Writes the defmt representation of self to fmt.

Auto Trait Implementations§

§

impl<'a> Freeze for Client<'a>

§

impl<'a> RefUnwindSafe for Client<'a>

§

impl<'a> Send for Client<'a>

§

impl<'a> Sync for Client<'a>

§

impl<'a> Unpin for Client<'a>

§

impl<'a> UnwindSafe for Client<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.