#![no_std]
extern crate alloc;
mod packets;
mod read;
mod topic;
use bytes::Buf;
use core::fmt;
use core::fmt::{Display, Formatter};
pub use packets::*;
pub use read::*;
pub use topic::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
InvalidConnectReturnCode(u8),
InvalidProtocol,
InvalidProtocolLevel(u8),
IncorrectPacketFormat,
InvalidPacketType(u8),
InvalidQoS(u8),
PacketIdZero,
PayloadSizeIncorrect,
PayloadTooLong,
PayloadSizeLimitExceeded,
PayloadRequired,
TopicNotUtf8,
BoundaryCrossed,
MalformedRemainingLength,
InsufficientBytes(usize),
}
#[derive(Debug, Clone, PartialEq)]
pub enum Packet {
Connect(Connect),
ConnAck(ConnAck),
Publish(Publish),
PubAck(PubAck),
PubRec(PubRec),
PubRel(PubRel),
PubComp(PubComp),
Subscribe(Subscribe),
SubAck(SubAck),
Unsubscribe(Unsubscribe),
UnsubAck(UnsubAck),
PingReq,
PingResp,
Disconnect,
}
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PacketType {
Connect = 1,
ConnAck,
Publish,
PubAck,
PubRec,
PubRel,
PubComp,
Subscribe,
SubAck,
Unsubscribe,
UnsubAck,
PingReq,
PingResp,
Disconnect,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Protocol {
MQTT(u8),
}
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
pub enum QoS {
AtMostOnce = 0,
AtLeastOnce = 1,
ExactlyOnce = 2,
}
pub struct FixedHeader {
byte1: u8,
fixed_len: usize,
remaining_len: usize,
}
impl FixedHeader {
pub fn new(byte1: u8, remaining_len_len: usize, remaining_len: usize) -> FixedHeader {
FixedHeader {
byte1,
fixed_len: remaining_len_len + 1,
remaining_len,
}
}
pub fn packet_type(&self) -> Result<PacketType, Error> {
let num = self.byte1 >> 4;
match num {
1 => Ok(PacketType::Connect),
2 => Ok(PacketType::ConnAck),
3 => Ok(PacketType::Publish),
4 => Ok(PacketType::PubAck),
5 => Ok(PacketType::PubRec),
6 => Ok(PacketType::PubRel),
7 => Ok(PacketType::PubComp),
8 => Ok(PacketType::Subscribe),
9 => Ok(PacketType::SubAck),
10 => Ok(PacketType::Unsubscribe),
11 => Ok(PacketType::UnsubAck),
12 => Ok(PacketType::PingReq),
13 => Ok(PacketType::PingResp),
14 => Ok(PacketType::Disconnect),
_ => Err(Error::InvalidPacketType(num)),
}
}
pub fn frame_length(&self) -> usize {
self.fixed_len + self.remaining_len
}
}
pub fn qos(num: u8) -> Result<QoS, Error> {
match num {
0 => Ok(QoS::AtMostOnce),
1 => Ok(QoS::AtLeastOnce),
2 => Ok(QoS::ExactlyOnce),
qos => Err(Error::InvalidQoS(qos)),
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "Error = {:?}", self)
}
}