1use core::fmt::Display;
3use core::mem;
4
5use crate::codec;
6use crate::cursor::{ReadCursor, WriteCursor};
7use crate::types::uuid::*;
8
9pub(crate) const ATT_READ_BY_GROUP_TYPE_REQ: u8 = 0x10;
10pub(crate) const ATT_READ_BY_GROUP_TYPE_RSP: u8 = 0x11;
11pub(crate) const ATT_ERROR_RSP: u8 = 0x01;
12pub(crate) const ATT_READ_BY_TYPE_REQ: u8 = 0x08;
13pub(crate) const ATT_READ_BY_TYPE_RSP: u8 = 0x09;
14pub(crate) const ATT_READ_REQ: u8 = 0x0a;
15pub(crate) const ATT_READ_RSP: u8 = 0x0b;
16pub(crate) const ATT_WRITE_REQ: u8 = 0x12;
17pub(crate) const ATT_WRITE_CMD: u8 = 0x52;
18pub(crate) const ATT_WRITE_RSP: u8 = 0x13;
19pub(crate) const ATT_EXCHANGE_MTU_REQ: u8 = 0x02;
20pub(crate) const ATT_EXCHANGE_MTU_RSP: u8 = 0x03;
21pub(crate) const ATT_FIND_BY_TYPE_VALUE_REQ: u8 = 0x06;
22pub(crate) const ATT_FIND_BY_TYPE_VALUE_RSP: u8 = 0x07;
23pub(crate) const ATT_FIND_INFORMATION_REQ: u8 = 0x04;
24pub(crate) const ATT_FIND_INFORMATION_RSP: u8 = 0x05;
25pub(crate) const ATT_PREPARE_WRITE_REQ: u8 = 0x16;
26pub(crate) const ATT_PREPARE_WRITE_RSP: u8 = 0x17;
27pub(crate) const ATT_EXECUTE_WRITE_REQ: u8 = 0x18;
28pub(crate) const ATT_EXECUTE_WRITE_RSP: u8 = 0x19;
29pub(crate) const ATT_READ_MULTIPLE_REQ: u8 = 0x20;
30pub(crate) const ATT_READ_MULTIPLE_RSP: u8 = 0x21;
31pub(crate) const ATT_READ_BLOB_REQ: u8 = 0x0c;
32pub(crate) const ATT_READ_BLOB_RSP: u8 = 0x0d;
33pub(crate) const ATT_HANDLE_VALUE_NTF: u8 = 0x1b;
34pub(crate) const ATT_HANDLE_VALUE_IND: u8 = 0x1d;
35pub(crate) const ATT_HANDLE_VALUE_CMF: u8 = 0x1e;
36
37#[cfg_attr(feature = "defmt", derive(defmt::Format))]
43#[derive(Debug, PartialEq, Eq, Clone, Copy)]
44pub struct AttErrorCode {
45 value: u8,
46}
47
48impl AttErrorCode {
49 pub const INVALID_HANDLE: Self = Self { value: 0x01 };
51 pub const READ_NOT_PERMITTED: Self = Self { value: 0x02 };
53 pub const WRITE_NOT_PERMITTED: Self = Self { value: 0x03 };
55 pub const INVALID_PDU: Self = Self { value: 0x04 };
57 pub const INSUFFICIENT_AUTHENTICATION: Self = Self { value: 0x05 };
59 pub const REQUEST_NOT_SUPPORTED: Self = Self { value: 0x06 };
61 pub const INVALID_OFFSET: Self = Self { value: 0x07 };
63 pub const INSUFFICIENT_AUTHORISATION: Self = Self { value: 0x08 };
65 pub const PREPARE_QUEUE_FULL: Self = Self { value: 0x09 };
67 pub const ATTRIBUTE_NOT_FOUND: Self = Self { value: 0x0a };
69 pub const ATTRIBUTE_NOT_LONG: Self = Self { value: 0x0b };
71 pub const INSUFFICIENT_ENCRYPTION_KEY_SIZE: Self = Self { value: 0x0c };
73 pub const INVALID_ATTRIBUTE_VALUE_LENGTH: Self = Self { value: 0x0d };
75 pub const UNLIKELY_ERROR: Self = Self { value: 0x0e };
77 pub const INSUFFICIENT_ENCRYPTION: Self = Self { value: 0x0f };
79 pub const UNSUPPORTED_GROUP_TYPE: Self = Self { value: 0x10 };
81 pub const INSUFFICIENT_RESOURCES: Self = Self { value: 0x11 };
83 pub const DATABASE_OUT_OF_SYNC: Self = Self { value: 0x12 };
85 pub const VALUE_NOT_ALLOWED: Self = Self { value: 0x13 };
87
88 pub const WRITE_REQUEST_REJECTED: Self = Self { value: 0xFC };
91 pub const CCCD_IMPROPERLY_CONFIGURED: Self = Self { value: 0xFD };
93 pub const PROCEDURE_ALREADY_IN_PROGRESS: Self = Self { value: 0xFE };
95 pub const OUT_OF_RANGE: Self = Self { value: 0xFF };
97}
98
99impl Display for AttErrorCode {
100 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
101 match self {
102 &Self::INVALID_HANDLE => {
103 f.write_str("invalid handle: Attempted to use a handle that isn't valid on this server")
104 }
105 &Self::READ_NOT_PERMITTED => f.write_str("read not permitted: the attribute cannot be read"),
106 &Self::WRITE_NOT_PERMITTED => f.write_str("write not permitted: the attribute cannot be written due to permissions"),
107 &Self::INVALID_PDU => f.write_str("invalid pdu: the attribute PDU was invalid"),
108 &Self::INSUFFICIENT_AUTHENTICATION => f.write_str(
109 "insufficient authentication: the attribute requires authentication before it can be written",
110 ),
111 &Self::REQUEST_NOT_SUPPORTED => {
112 f.write_str("request not supported: ATT server does not support the request received from the client")
113 }
114 &Self::INVALID_OFFSET => f.write_str("Offset specified was past the end of the attribute"),
115 &Self::INSUFFICIENT_AUTHORISATION => f.write_str(
116 "insufficient authorisation: the attribute requires authorisation before it can be read or written",
117 ),
118 &Self::PREPARE_QUEUE_FULL => f.write_str("prepare queue full: too many prepare writes have been queued"),
119 &Self::ATTRIBUTE_NOT_FOUND => f.write_str("attribute not found: no attribute found within the given attribute handle range"),
120 &Self::ATTRIBUTE_NOT_LONG => f.write_str("The attribute cannot be read using the ATT_READ_BLOB_REQ PDU"),
121 &Self::INSUFFICIENT_ENCRYPTION_KEY_SIZE => f.write_str("insufficient encryption key size: the encryption key size used for encrypting this link is too short"),
122 &Self::INVALID_ATTRIBUTE_VALUE_LENGTH => f.write_str("invalid attribute value length: the attribute value length is invalid for the operation"),
123 &Self::UNLIKELY_ERROR => f.write_str("unlikely error: the attribute request encountered an error that was unlikely, and therefore could not be completed"),
124 &Self::INSUFFICIENT_ENCRYPTION => f.write_str("insufficient encryption: the attribute requires encryption before it can be read or written"),
125 &Self::UNSUPPORTED_GROUP_TYPE => f.write_str("unsupported group type: the attribute type is not a supported grouping attribute as defined by a higher layer specification"),
126 &Self::INSUFFICIENT_RESOURCES => f.write_str("insufficient resources: insufficient resources to complete the request"),
127 &Self::DATABASE_OUT_OF_SYNC => f.write_str("the server requests the client to rediscover the database"),
128 &Self::VALUE_NOT_ALLOWED => f.write_str("value not allowed: the attribute parameter value was not allowed"),
129
130 &Self{value: 0x80..=0x9F} => write!(f, "application error code {}: check the application documentation of the device which produced this error code", self.value),
131
132 &Self::WRITE_REQUEST_REJECTED => f.write_str("write request rejected: the write request could not be fulfilled for reasons other than permissions"),
133 &Self::CCCD_IMPROPERLY_CONFIGURED => f.write_str("CCCD improperly configured: the client characteristic configuration descriptor (CCCD) is not configured according to the requirements of the profile or service"),
134 &Self::PROCEDURE_ALREADY_IN_PROGRESS => f.write_str("procedure already in progress: the profile or service request could not be serviced because an operation that has been previousl triggered is still in progress"),
135 &Self::OUT_OF_RANGE => f.write_str("out of range: the attribute value is out of range as defined by a profile or service specification"),
136
137 other => write!(f, "unknown error code {other}: check the most recent bluetooth spec"),
138 }
139 }
140}
141
142impl codec::Encode for AttErrorCode {
143 fn encode(&self, dest: &mut [u8]) -> Result<(), codec::Error> {
144 dest[0] = self.value;
145 Ok(())
146 }
147}
148
149impl codec::Decode<'_> for AttErrorCode {
150 fn decode(src: &[u8]) -> Result<Self, codec::Error> {
151 Ok(Self { value: src[0] })
152 }
153}
154
155impl codec::Type for AttErrorCode {
156 fn size(&self) -> usize {
157 mem::size_of::<u8>()
158 }
159}
160
161#[cfg_attr(feature = "defmt", derive(defmt::Format))]
165#[derive(Debug)]
166pub enum AttClient<'d> {
167 Request(AttReq<'d>),
169 Command(AttCmd<'d>),
171 Confirmation(AttCfm),
173}
174
175#[cfg_attr(feature = "defmt", derive(defmt::Format))]
177#[derive(Debug)]
178pub enum AttReq<'d> {
179 ReadByGroupType {
181 start: u16,
183 end: u16,
185 group_type: Uuid,
187 },
188 ReadByType {
190 start: u16,
192 end: u16,
194 attribute_type: Uuid,
196 },
197 Read {
199 handle: u16,
201 },
202 Write {
204 handle: u16,
206 data: &'d [u8],
208 },
209 ExchangeMtu {
211 mtu: u16,
213 },
214 FindByTypeValue {
216 start_handle: u16,
218 end_handle: u16,
220 att_type: u16,
222 att_value: &'d [u8],
224 },
225 FindInformation {
227 start_handle: u16,
229 end_handle: u16,
231 },
232 PrepareWrite {
234 handle: u16,
236 offset: u16,
238 value: &'d [u8],
240 },
241 ExecuteWrite {
243 flags: u8,
245 },
246 ReadMultiple {
248 handles: &'d [u8],
250 },
251 ReadBlob {
253 handle: u16,
255 offset: u16,
257 },
258}
259
260#[cfg_attr(feature = "defmt", derive(defmt::Format))]
262#[derive(Debug)]
263pub enum AttCmd<'d> {
264 Write {
266 handle: u16,
268 data: &'d [u8],
270 },
271}
272
273#[cfg_attr(feature = "defmt", derive(defmt::Format))]
275#[derive(Debug)]
276pub enum AttCfm {
277 ConfirmIndication,
279}
280
281#[cfg_attr(feature = "defmt", derive(defmt::Format))]
283#[derive(Debug)]
284pub enum AttServer<'d> {
285 Response(AttRsp<'d>),
287 Unsolicited(AttUns<'d>),
289}
290
291#[cfg_attr(feature = "defmt", derive(defmt::Format))]
293#[derive(Debug)]
294pub enum AttRsp<'d> {
295 ExchangeMtu {
297 mtu: u16,
299 },
300 FindByTypeValue {
302 it: FindByTypeValueIter<'d>,
304 },
305 FindInformation {
307 it: FindInformationIter<'d>,
309 },
310 Error {
312 request: u8,
314 handle: u16,
316 code: AttErrorCode,
318 },
319 ReadByType {
321 it: ReadByTypeIter<'d>,
323 },
324 Read {
326 data: &'d [u8],
328 },
329 Write,
331}
332
333#[cfg_attr(feature = "defmt", derive(defmt::Format))]
335#[derive(Debug)]
336pub enum AttUns<'d> {
337 Notify {
339 handle: u16,
341 data: &'d [u8],
343 },
344 Indicate {
346 handle: u16,
348 data: &'d [u8],
350 },
351}
352
353#[cfg_attr(feature = "defmt", derive(defmt::Format))]
355#[derive(Debug)]
356pub enum Att<'d> {
357 Client(AttClient<'d>),
361 Server(AttServer<'d>),
365}
366
367#[cfg_attr(feature = "defmt", derive(defmt::Format))]
369#[derive(Clone, Debug)]
370pub struct FindByTypeValueIter<'d> {
371 cursor: ReadCursor<'d>,
372}
373
374impl FindByTypeValueIter<'_> {
375 #[allow(clippy::should_implement_trait)]
377 pub fn next(&mut self) -> Option<Result<(u16, u16), crate::Error>> {
378 if self.cursor.available() >= 4 {
379 let res = (|| {
380 let handle: u16 = self.cursor.read()?;
381 let end: u16 = self.cursor.read()?;
382 Ok((handle, end))
383 })();
384 Some(res)
385 } else {
386 None
387 }
388 }
389}
390
391#[cfg_attr(feature = "defmt", derive(defmt::Format))]
393#[derive(Clone, Debug)]
394pub struct ReadByTypeIter<'d> {
395 item_len: usize,
396 cursor: ReadCursor<'d>,
397}
398
399impl<'d> ReadByTypeIter<'d> {
400 #[allow(clippy::should_implement_trait)]
402 pub fn next(&mut self) -> Option<Result<(u16, &'d [u8]), crate::Error>> {
403 if self.cursor.available() >= self.item_len {
404 let res = (|| {
405 let handle: u16 = self.cursor.read()?;
406 let item = self.cursor.slice(self.item_len - 2)?;
407 Ok((handle, item))
408 })();
409 Some(res)
410 } else {
411 None
412 }
413 }
414}
415
416#[cfg_attr(feature = "defmt", derive(defmt::Format))]
417#[derive(Debug, Copy, Clone)]
418enum FindInformationUuidFormat {
419 Uuid16 = 1,
420 Uuid128 = 2,
421}
422
423impl FindInformationUuidFormat {
424 fn num_bytes(self) -> usize {
425 match self {
426 Self::Uuid16 => 2,
427 Self::Uuid128 => 16,
428 }
429 }
430
431 fn from(format: u8) -> Result<Self, codec::Error> {
432 match format {
433 1 => Ok(Self::Uuid16),
434 2 => Ok(Self::Uuid128),
435 _ => Err(codec::Error::InvalidValue),
436 }
437 }
438}
439
440#[cfg_attr(feature = "defmt", derive(defmt::Format))]
442#[derive(Clone, Debug)]
443pub struct FindInformationIter<'d> {
444 format: FindInformationUuidFormat,
446 cursor: ReadCursor<'d>,
447}
448
449impl<'d> FindInformationIter<'d> {
450 #[allow(clippy::should_implement_trait)]
452 pub fn next(&mut self) -> Option<Result<(u16, Uuid), crate::Error>> {
453 let uuid_len = self.format.num_bytes();
454
455 if self.cursor.available() >= 2 + uuid_len {
456 let res = (|| {
457 let handle: u16 = self.cursor.read()?;
458 let uuid = Uuid::try_from(self.cursor.slice(uuid_len)?)?;
459 Ok((handle, uuid))
460 })();
461 Some(res)
462 } else {
463 None
464 }
465 }
466}
467
468impl<'d> AttServer<'d> {
469 fn size(&self) -> usize {
470 match self {
471 Self::Response(rsp) => rsp.size(),
472 Self::Unsolicited(uns) => uns.size(),
473 }
474 }
475
476 fn encode(&self, dest: &mut [u8]) -> Result<(), codec::Error> {
477 match self {
478 Self::Response(rsp) => rsp.encode(dest),
479 Self::Unsolicited(uns) => uns.encode(dest),
480 }
481 }
482
483 fn decode_with_opcode(opcode: u8, r: ReadCursor<'d>) -> Result<Self, codec::Error> {
484 let decoded = match opcode {
485 ATT_HANDLE_VALUE_NTF | ATT_HANDLE_VALUE_IND => Self::Unsolicited(AttUns::decode_with_opcode(opcode, r)?),
486 _ => Self::Response(AttRsp::decode_with_opcode(opcode, r)?),
487 };
488 Ok(decoded)
489 }
490}
491
492impl<'d> AttRsp<'d> {
493 fn size(&self) -> usize {
494 1 + match self {
495 Self::ExchangeMtu { mtu: u16 } => 2,
496 Self::FindByTypeValue { it } => it.cursor.len(),
497 Self::FindInformation { it } => 1 + it.cursor.len(), Self::Error { .. } => 4,
499 Self::Read { data } => data.len(),
500 Self::ReadByType { it } => it.cursor.len(),
501 Self::Write => 0,
502 }
503 }
504
505 fn encode(&self, dest: &mut [u8]) -> Result<(), codec::Error> {
506 let mut w = WriteCursor::new(dest);
507 match self {
508 Self::ExchangeMtu { mtu } => {
509 w.write(ATT_EXCHANGE_MTU_RSP)?;
510 w.write(*mtu)?;
511 }
512 Self::FindByTypeValue { it } => {
513 w.write(ATT_FIND_BY_TYPE_VALUE_RSP)?;
514 let mut it = it.clone();
515 while let Some(Ok((start, end))) = it.next() {
516 w.write(start)?;
517 w.write(end)?;
518 }
519 }
520 Self::FindInformation { it } => {
521 w.write(ATT_FIND_INFORMATION_RSP)?;
522 w.write(it.format as u8)?;
523 let mut it = it.clone();
524 while let Some(Ok((handle, uuid))) = it.next() {
525 w.write(handle)?;
526 w.append(uuid.as_raw())?;
527 }
528 }
529 Self::Error { request, handle, code } => {
530 w.write(ATT_ERROR_RSP)?;
531 w.write(*request)?;
532 w.write(*handle)?;
533 w.write(*code)?;
534 }
535 Self::ReadByType { it } => {
536 w.write(ATT_READ_BY_TYPE_RSP)?;
537 w.write(it.item_len as u8)?;
538 let mut it = it.clone();
539 while let Some(Ok((handle, item))) = it.next() {
540 w.write(handle)?;
541 w.append(item)?;
542 }
543 }
544 Self::Read { data } => {
545 w.write(ATT_READ_RSP)?;
546 w.append(data)?;
547 }
548 Self::Write => {
549 w.write(ATT_WRITE_RSP)?;
550 }
551 }
552 Ok(())
553 }
554
555 fn decode_with_opcode(opcode: u8, mut r: ReadCursor<'d>) -> Result<Self, codec::Error> {
556 match opcode {
557 ATT_FIND_BY_TYPE_VALUE_RSP => Ok(Self::FindByTypeValue {
558 it: FindByTypeValueIter { cursor: r },
559 }),
560 ATT_FIND_INFORMATION_RSP => Ok(Self::FindInformation {
561 it: FindInformationIter {
562 format: FindInformationUuidFormat::from(r.read()?)?,
563 cursor: r,
564 },
565 }),
566 ATT_EXCHANGE_MTU_RSP => {
567 let mtu: u16 = r.read()?;
568 Ok(Self::ExchangeMtu { mtu })
569 }
570 ATT_ERROR_RSP => {
571 let request = r.read()?;
572 let handle = r.read()?;
573 let code = r.read()?;
574 Ok(Self::Error { request, handle, code })
575 }
576 ATT_READ_RSP => Ok(Self::Read { data: r.remaining() }),
577 ATT_READ_BY_TYPE_RSP => {
578 let item_len: u8 = r.read()?;
579 Ok(Self::ReadByType {
580 it: ReadByTypeIter {
581 item_len: item_len as usize,
582 cursor: r,
583 },
584 })
585 }
586 ATT_WRITE_RSP => Ok(Self::Write),
587 _ => Err(codec::Error::InvalidValue),
588 }
589 }
590}
591
592impl<'d> AttUns<'d> {
593 fn size(&self) -> usize {
594 1 + match self {
595 Self::Notify { data, .. } => 2 + data.len(),
596 Self::Indicate { data, .. } => 2 + data.len(),
597 }
598 }
599
600 fn encode(&self, dest: &mut [u8]) -> Result<(), codec::Error> {
601 let mut w = WriteCursor::new(dest);
602 match self {
603 Self::Notify { handle, data } => {
604 w.write(ATT_HANDLE_VALUE_NTF)?;
605 w.write(*handle)?;
606 w.append(data)?;
607 }
608 Self::Indicate { handle, data } => {
609 w.write(ATT_HANDLE_VALUE_IND)?;
610 w.write(*handle)?;
611 w.append(data)?;
612 }
613 }
614 Ok(())
615 }
616
617 fn decode_with_opcode(opcode: u8, mut r: ReadCursor<'d>) -> Result<Self, codec::Error> {
618 match opcode {
619 ATT_HANDLE_VALUE_NTF => {
620 let handle = r.read()?;
621 Ok(Self::Notify {
622 handle,
623 data: r.remaining(),
624 })
625 }
626 ATT_HANDLE_VALUE_IND => {
627 let handle = r.read()?;
628 Ok(Self::Indicate {
629 handle,
630 data: r.remaining(),
631 })
632 }
633 _ => Err(codec::Error::InvalidValue),
634 }
635 }
636}
637
638impl<'d> AttClient<'d> {
639 fn size(&self) -> usize {
640 match self {
641 Self::Request(req) => req.size(),
642 Self::Command(cmd) => cmd.size(),
643 Self::Confirmation(cfm) => cfm.size(),
644 }
645 }
646
647 fn encode(&self, dest: &mut [u8]) -> Result<(), codec::Error> {
648 match self {
649 Self::Request(req) => req.encode(dest),
650 Self::Command(cmd) => cmd.encode(dest),
651 Self::Confirmation(cfm) => cfm.encode(dest),
652 }
653 }
654
655 fn decode_with_opcode(opcode: u8, r: ReadCursor<'d>) -> Result<Self, codec::Error> {
656 let decoded = match opcode {
657 ATT_WRITE_CMD => Self::Command(AttCmd::decode_with_opcode(opcode, r)?),
658 ATT_HANDLE_VALUE_CMF => Self::Confirmation(AttCfm::decode_with_opcode(opcode, r)?),
659 _ => Self::Request(AttReq::decode_with_opcode(opcode, r)?),
660 };
661 Ok(decoded)
662 }
663}
664
665impl<'d> AttReq<'d> {
666 fn size(&self) -> usize {
667 1 + match self {
668 Self::ExchangeMtu { .. } => 2,
669 Self::FindByTypeValue {
670 start_handle,
671 end_handle,
672 att_type,
673 att_value,
674 } => 6 + att_value.len(),
675 Self::FindInformation {
676 start_handle,
677 end_handle,
678 } => 4,
679 Self::ReadByType {
680 start,
681 end,
682 attribute_type,
683 } => 4 + attribute_type.as_raw().len(),
684 Self::Read { .. } => 2,
685 Self::Write { handle, data } => 2 + data.len(),
686 _ => unimplemented!(),
687 }
688 }
689 fn encode(&self, dest: &mut [u8]) -> Result<(), codec::Error> {
690 let mut w = WriteCursor::new(dest);
691 match self {
692 Self::ExchangeMtu { mtu } => {
693 w.write(ATT_EXCHANGE_MTU_REQ)?;
694 w.write(*mtu)?;
695 }
696 Self::FindByTypeValue {
697 start_handle,
698 end_handle,
699 att_type,
700 att_value,
701 } => {
702 w.write(ATT_FIND_BY_TYPE_VALUE_REQ)?;
703 w.write(*start_handle)?;
704 w.write(*end_handle)?;
705 w.write(*att_type)?;
706 w.append(att_value)?;
707 }
708 Self::FindInformation {
709 start_handle,
710 end_handle,
711 } => {
712 w.write(ATT_FIND_INFORMATION_REQ)?;
713 w.write(*start_handle)?;
714 w.write(*end_handle)?;
715 }
716 Self::ReadByType {
717 start,
718 end,
719 attribute_type,
720 } => {
721 w.write(ATT_READ_BY_TYPE_REQ)?;
722 w.write(*start)?;
723 w.write(*end)?;
724 w.write_ref(attribute_type)?;
725 }
726 Self::Read { handle } => {
727 w.write(ATT_READ_REQ)?;
728 w.write(*handle)?;
729 }
730 Self::Write { handle, data } => {
731 w.write(ATT_WRITE_REQ)?;
732 w.write(*handle)?;
733 w.append(data)?;
734 }
735 _ => unimplemented!(),
736 }
737 Ok(())
738 }
739
740 fn decode_with_opcode(opcode: u8, r: ReadCursor<'d>) -> Result<Self, codec::Error> {
741 let payload = r.remaining();
742 match opcode {
743 ATT_READ_BY_GROUP_TYPE_REQ => {
744 let start_handle = (payload[0] as u16) + ((payload[1] as u16) << 8);
745 let end_handle = (payload[2] as u16) + ((payload[3] as u16) << 8);
746
747 let group_type = if payload.len() == 6 {
748 Uuid::Uuid16([payload[4], payload[5]])
749 } else if payload.len() == 20 {
750 let uuid = payload[4..21].try_into().map_err(|_| codec::Error::InvalidValue)?;
751 Uuid::Uuid128(uuid)
752 } else {
753 return Err(codec::Error::InvalidValue);
754 };
755
756 Ok(Self::ReadByGroupType {
757 start: start_handle,
758 end: end_handle,
759 group_type,
760 })
761 }
762 ATT_READ_BY_TYPE_REQ => {
763 let start_handle = (payload[0] as u16) + ((payload[1] as u16) << 8);
764 let end_handle = (payload[2] as u16) + ((payload[3] as u16) << 8);
765
766 let attribute_type = if payload.len() == 6 {
767 Uuid::Uuid16([payload[4], payload[5]])
768 } else if payload.len() == 20 {
769 let uuid = payload[4..20].try_into().map_err(|_| codec::Error::InvalidValue)?;
770 Uuid::Uuid128(uuid)
771 } else {
772 return Err(codec::Error::InvalidValue);
773 };
774
775 Ok(Self::ReadByType {
776 start: start_handle,
777 end: end_handle,
778 attribute_type,
779 })
780 }
781 ATT_READ_REQ => {
782 let handle = (payload[0] as u16) + ((payload[1] as u16) << 8);
783
784 Ok(Self::Read { handle })
785 }
786 ATT_WRITE_REQ => {
787 let handle = (payload[0] as u16) + ((payload[1] as u16) << 8);
788 let data = &payload[2..];
789
790 Ok(Self::Write { handle, data })
791 }
792 ATT_EXCHANGE_MTU_REQ => {
793 let mtu = (payload[0] as u16) + ((payload[1] as u16) << 8);
794 Ok(Self::ExchangeMtu { mtu })
795 }
796 ATT_FIND_BY_TYPE_VALUE_REQ => {
797 let start_handle = (payload[0] as u16) + ((payload[1] as u16) << 8);
798 let end_handle = (payload[2] as u16) + ((payload[3] as u16) << 8);
799 let att_type = (payload[4] as u16) + ((payload[5] as u16) << 8);
800 let att_value = &payload[6..];
801
802 Ok(Self::FindByTypeValue {
803 start_handle,
804 end_handle,
805 att_type,
806 att_value,
807 })
808 }
809 ATT_FIND_INFORMATION_REQ => {
810 let start_handle = (payload[0] as u16) + ((payload[1] as u16) << 8);
811 let end_handle = (payload[2] as u16) + ((payload[3] as u16) << 8);
812
813 Ok(Self::FindInformation {
814 start_handle,
815 end_handle,
816 })
817 }
818 ATT_PREPARE_WRITE_REQ => {
819 let handle = (payload[0] as u16) + ((payload[1] as u16) << 8);
820 let offset = (payload[2] as u16) + ((payload[3] as u16) << 8);
821 Ok(Self::PrepareWrite {
822 handle,
823 offset,
824 value: &payload[4..],
825 })
826 }
827 ATT_EXECUTE_WRITE_REQ => {
828 let flags = payload[0];
829 Ok(Self::ExecuteWrite { flags })
830 }
831 ATT_READ_MULTIPLE_REQ => Ok(Self::ReadMultiple { handles: payload }),
832 ATT_READ_BLOB_REQ => {
833 let handle = (payload[0] as u16) + ((payload[1] as u16) << 8);
834 let offset = (payload[2] as u16) + ((payload[3] as u16) << 8);
835 Ok(Self::ReadBlob { handle, offset })
836 }
837 code => {
838 warn!("[att] unknown opcode {:x}", code);
839 Err(codec::Error::InvalidValue)
840 }
841 }
842 }
843}
844
845impl<'d> AttCmd<'d> {
846 fn size(&self) -> usize {
847 1 + match self {
848 Self::Write { handle, data } => 2 + data.len(),
849 }
850 }
851
852 fn encode(&self, dest: &mut [u8]) -> Result<(), codec::Error> {
853 let mut w = WriteCursor::new(dest);
854 match self {
855 Self::Write { handle, data } => {
856 w.write(ATT_WRITE_CMD)?;
857 w.write(*handle)?;
858 w.append(data)?;
859 }
860 }
861 Ok(())
862 }
863
864 fn decode_with_opcode(opcode: u8, r: ReadCursor<'d>) -> Result<Self, codec::Error> {
865 let payload = r.remaining();
866 match opcode {
867 ATT_WRITE_CMD => {
868 let handle = (payload[0] as u16) + ((payload[1] as u16) << 8);
869 let data = &payload[2..];
870
871 Ok(Self::Write { handle, data })
872 }
873 code => {
874 warn!("[att] unknown opcode {:x}", code);
875 Err(codec::Error::InvalidValue)
876 }
877 }
878 }
879}
880
881impl AttCfm {
882 fn size(&self) -> usize {
883 1
884 }
885
886 fn encode(&self, dest: &mut [u8]) -> Result<(), codec::Error> {
887 let mut w = WriteCursor::new(dest);
888 match self {
889 Self::ConfirmIndication => {
890 w.write(ATT_HANDLE_VALUE_CMF)?;
891 }
892 }
893 Ok(())
894 }
895
896 fn decode_with_opcode(opcode: u8, r: ReadCursor<'_>) -> Result<Self, codec::Error> {
897 let payload = r.remaining();
898 match opcode {
899 ATT_HANDLE_VALUE_CMF => Ok(Self::ConfirmIndication),
900 code => {
901 warn!("[att] unknown opcode {:x}", code);
902 Err(codec::Error::InvalidValue)
903 }
904 }
905 }
906}
907
908impl<'d> Att<'d> {
909 pub fn size(&self) -> usize {
911 match self {
912 Self::Client(client) => client.size(),
913 Self::Server(server) => server.size(),
914 }
915 }
916
917 pub fn encode(&self, dest: &mut [u8]) -> Result<(), codec::Error> {
919 match self {
920 Self::Client(client) => client.encode(dest),
921 Self::Server(server) => server.encode(dest),
922 }
923 }
924
925 pub fn decode(data: &'d [u8]) -> Result<Att<'d>, codec::Error> {
927 let mut r = ReadCursor::new(data);
928 let opcode: u8 = r.read()?;
929 if opcode % 2 == 0 {
930 let client = AttClient::decode_with_opcode(opcode, r)?;
931 Ok(Att::Client(client))
932 } else {
933 let server = AttServer::decode_with_opcode(opcode, r)?;
934 Ok(Att::Server(server))
935 }
936 }
937}
938
939impl From<codec::Error> for AttErrorCode {
940 fn from(e: codec::Error) -> Self {
941 AttErrorCode::INVALID_PDU
942 }
943}
944
945impl codec::Type for Att<'_> {
946 fn size(&self) -> usize {
947 Self::size(self)
948 }
949}
950
951impl codec::Encode for Att<'_> {
952 fn encode(&self, dest: &mut [u8]) -> Result<(), codec::Error> {
953 Self::encode(self, dest)
954 }
955}
956
957impl<'d> codec::Decode<'d> for Att<'d> {
958 fn decode(data: &'d [u8]) -> Result<Self, codec::Error> {
959 Self::decode(data)
960 }
961}