1pub mod opcode {
28 pub const ERROR_RESPONSE: u8 = 0x01;
29 pub const EXCHANGE_MTU_REQUEST: u8 = 0x02;
30 pub const EXCHANGE_MTU_RESPONSE: u8 = 0x03;
31 pub const FIND_INFORMATION_REQUEST: u8 = 0x04;
32 pub const FIND_INFORMATION_RESPONSE: u8 = 0x05;
33 pub const READ_BY_TYPE_REQUEST: u8 = 0x08;
34 pub const READ_BY_TYPE_RESPONSE: u8 = 0x09;
35 pub const READ_REQUEST: u8 = 0x0A;
36 pub const READ_RESPONSE: u8 = 0x0B;
37 pub const READ_BLOB_REQUEST: u8 = 0x0C;
38 pub const READ_BLOB_RESPONSE: u8 = 0x0D;
39 pub const READ_BY_GROUP_TYPE_REQUEST: u8 = 0x10;
40 pub const READ_BY_GROUP_TYPE_RESPONSE: u8 = 0x11;
41 pub const WRITE_REQUEST: u8 = 0x12;
42 pub const WRITE_RESPONSE: u8 = 0x13;
43 pub const PREPARE_WRITE_REQUEST: u8 = 0x16;
44 pub const PREPARE_WRITE_RESPONSE: u8 = 0x17;
45 pub const EXECUTE_WRITE_REQUEST: u8 = 0x18;
46 pub const EXECUTE_WRITE_RESPONSE: u8 = 0x19;
47 pub const WRITE_COMMAND: u8 = 0x52;
48 pub const HANDLE_VALUE_NOTIFICATION: u8 = 0x1B;
49 pub const HANDLE_VALUE_INDICATION: u8 = 0x1D;
50 pub const HANDLE_VALUE_CONFIRMATION: u8 = 0x1E;
51}
52
53pub mod gatt_type {
55 pub const PRIMARY_SERVICE: u16 = 0x2800;
56 pub const SECONDARY_SERVICE: u16 = 0x2801;
57 pub const INCLUDE: u16 = 0x2802;
58 pub const CHARACTERISTIC: u16 = 0x2803;
59 pub const CLIENT_CHARACTERISTIC_CONFIGURATION: u16 = 0x2902;
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub struct AttError(pub u8);
65
66impl AttError {
67 pub const INVALID_HANDLE: u8 = 0x01;
68 pub const READ_NOT_PERMITTED: u8 = 0x02;
69 pub const WRITE_NOT_PERMITTED: u8 = 0x03;
70 pub const INSUFFICIENT_AUTHENTICATION: u8 = 0x05;
71 pub const REQUEST_NOT_SUPPORTED: u8 = 0x06;
72 pub const INVALID_OFFSET: u8 = 0x07;
73 pub const INSUFFICIENT_AUTHORIZATION: u8 = 0x08;
74 pub const ATTRIBUTE_NOT_FOUND: u8 = 0x0A;
75 pub const ATTRIBUTE_NOT_LONG: u8 = 0x0B;
76 pub const INVALID_ATTRIBUTE_VALUE_LENGTH: u8 = 0x0D;
77 pub const UNLIKELY_ERROR: u8 = 0x0E;
78 pub const INSUFFICIENT_ENCRYPTION: u8 = 0x0F;
79 pub const INSUFFICIENT_RESOURCES: u8 = 0x11;
80
81 pub fn is_end_of_discovery(self) -> bool {
84 self.0 == Self::ATTRIBUTE_NOT_FOUND
85 }
86
87 pub fn describe(self) -> &'static str {
88 match self.0 {
89 Self::INVALID_HANDLE => "invalid handle",
90 Self::READ_NOT_PERMITTED => "read not permitted",
91 Self::WRITE_NOT_PERMITTED => "write not permitted",
92 Self::INSUFFICIENT_AUTHENTICATION => "insufficient authentication",
93 Self::REQUEST_NOT_SUPPORTED => "request not supported",
94 Self::INVALID_OFFSET => "invalid offset",
95 Self::INSUFFICIENT_AUTHORIZATION => "insufficient authorization",
96 Self::ATTRIBUTE_NOT_FOUND => "attribute not found",
97 Self::ATTRIBUTE_NOT_LONG => "attribute not long",
98 Self::INVALID_ATTRIBUTE_VALUE_LENGTH => "invalid attribute value length",
99 Self::UNLIKELY_ERROR => "unlikely error",
100 Self::INSUFFICIENT_ENCRYPTION => "insufficient encryption",
101 Self::INSUFFICIENT_RESOURCES => "insufficient resources",
102 _ => "unknown ATT error",
103 }
104 }
105}
106
107impl std::fmt::Display for AttError {
108 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109 write!(f, "{} (0x{:02x})", self.describe(), self.0)
110 }
111}
112
113#[derive(Debug, Clone, PartialEq, Eq)]
115pub enum Uuid {
116 Short(u16),
117 Long([u8; 16]),
118}
119
120impl Uuid {
121 pub fn parse(bytes: &[u8]) -> Option<Self> {
126 match bytes.len() {
127 2 => Some(Self::Short(u16::from_le_bytes([bytes[0], bytes[1]]))),
128 16 => {
129 let mut be = [0u8; 16];
130 for (i, b) in bytes.iter().enumerate() {
131 be[15 - i] = *b;
132 }
133 Some(Self::Long(be))
134 }
135 _ => None,
136 }
137 }
138
139 pub fn to_wire(&self) -> Vec<u8> {
141 match self {
142 Self::Short(v) => v.to_le_bytes().to_vec(),
143 Self::Long(be) => be.iter().rev().copied().collect(),
144 }
145 }
146
147 pub fn to_canonical(&self) -> String {
150 let bytes = match self {
151 Self::Short(v) => {
152 let mut b = [
153 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F,
154 0x9B, 0x34, 0xFB,
155 ];
156 b[2] = (*v >> 8) as u8;
157 b[3] = *v as u8;
158 b
159 }
160 Self::Long(b) => *b,
161 };
162 let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
163 format!(
164 "{}-{}-{}-{}-{}",
165 &hex[0..8],
166 &hex[8..12],
167 &hex[12..16],
168 &hex[16..20],
169 &hex[20..32]
170 )
171 }
172}
173
174#[derive(Debug, Clone, PartialEq, Eq)]
176pub struct Service {
177 pub start_handle: u16,
178 pub end_handle: u16,
179 pub uuid: Uuid,
180}
181
182#[derive(Debug, Clone, PartialEq, Eq)]
184pub struct Characteristic {
185 pub handle: u16,
187 pub value_handle: u16,
189 pub properties: u8,
190 pub uuid: Uuid,
191}
192
193#[derive(Debug, Clone, PartialEq, Eq)]
195pub struct Descriptor {
196 pub handle: u16,
197 pub uuid: Uuid,
198}
199
200pub fn exchange_mtu_request(mtu: u16) -> Vec<u8> {
203 let mut pdu = vec![opcode::EXCHANGE_MTU_REQUEST];
204 pdu.extend_from_slice(&mtu.to_le_bytes());
205 pdu
206}
207
208pub fn read_by_group_type_request(start: u16, end: u16, group_type: u16) -> Vec<u8> {
209 let mut pdu = vec![opcode::READ_BY_GROUP_TYPE_REQUEST];
210 pdu.extend_from_slice(&start.to_le_bytes());
211 pdu.extend_from_slice(&end.to_le_bytes());
212 pdu.extend_from_slice(&group_type.to_le_bytes());
213 pdu
214}
215
216pub fn read_by_type_request(start: u16, end: u16, attribute_type: u16) -> Vec<u8> {
217 let mut pdu = vec![opcode::READ_BY_TYPE_REQUEST];
218 pdu.extend_from_slice(&start.to_le_bytes());
219 pdu.extend_from_slice(&end.to_le_bytes());
220 pdu.extend_from_slice(&attribute_type.to_le_bytes());
221 pdu
222}
223
224pub fn find_information_request(start: u16, end: u16) -> Vec<u8> {
225 let mut pdu = vec![opcode::FIND_INFORMATION_REQUEST];
226 pdu.extend_from_slice(&start.to_le_bytes());
227 pdu.extend_from_slice(&end.to_le_bytes());
228 pdu
229}
230
231pub fn read_request(handle: u16) -> Vec<u8> {
232 let mut pdu = vec![opcode::READ_REQUEST];
233 pdu.extend_from_slice(&handle.to_le_bytes());
234 pdu
235}
236
237pub fn read_blob_request(handle: u16, offset: u16) -> Vec<u8> {
238 let mut pdu = vec![opcode::READ_BLOB_REQUEST];
239 pdu.extend_from_slice(&handle.to_le_bytes());
240 pdu.extend_from_slice(&offset.to_le_bytes());
241 pdu
242}
243
244pub fn write_request(handle: u16, value: &[u8]) -> Vec<u8> {
245 let mut pdu = vec![opcode::WRITE_REQUEST];
246 pdu.extend_from_slice(&handle.to_le_bytes());
247 pdu.extend_from_slice(value);
248 pdu
249}
250
251pub fn prepare_write_request(handle: u16, offset: u16, value: &[u8]) -> Vec<u8> {
259 let mut pdu = Vec::with_capacity(5 + value.len());
260 pdu.push(opcode::PREPARE_WRITE_REQUEST);
261 pdu.extend_from_slice(&handle.to_le_bytes());
262 pdu.extend_from_slice(&offset.to_le_bytes());
263 pdu.extend_from_slice(value);
264 pdu
265}
266
267pub fn execute_write_request(apply: bool) -> Vec<u8> {
269 vec![opcode::EXECUTE_WRITE_REQUEST, u8::from(apply)]
270}
271
272pub fn exchange_mtu_response(mtu: u16) -> Vec<u8> {
274 let mut pdu = Vec::with_capacity(3);
275 pdu.push(opcode::EXCHANGE_MTU_RESPONSE);
276 pdu.extend_from_slice(&mtu.to_le_bytes());
277 pdu
278}
279
280pub fn error_response(request: u8, handle: u16, error: AttError) -> Vec<u8> {
282 let mut pdu = Vec::with_capacity(5);
283 pdu.push(opcode::ERROR_RESPONSE);
284 pdu.push(request);
285 pdu.extend_from_slice(&handle.to_le_bytes());
286 pdu.push(error.0);
287 pdu
288}
289
290pub fn is_peer_request(opcode: u8) -> bool {
298 matches!(
299 opcode,
300 opcode::EXCHANGE_MTU_REQUEST
301 | opcode::FIND_INFORMATION_REQUEST
302 | opcode::READ_BY_TYPE_REQUEST
303 | opcode::READ_REQUEST
304 | opcode::READ_BLOB_REQUEST
305 | opcode::READ_BY_GROUP_TYPE_REQUEST
306 | opcode::WRITE_REQUEST
307 | opcode::PREPARE_WRITE_REQUEST
308 | opcode::EXECUTE_WRITE_REQUEST
309 )
310}
311
312pub fn write_command(handle: u16, value: &[u8]) -> Vec<u8> {
313 let mut pdu = vec![opcode::WRITE_COMMAND];
314 pdu.extend_from_slice(&handle.to_le_bytes());
315 pdu.extend_from_slice(value);
316 pdu
317}
318
319pub fn handle_value_confirmation() -> Vec<u8> {
320 vec![opcode::HANDLE_VALUE_CONFIRMATION]
321}
322
323#[derive(Debug, Clone, PartialEq)]
331pub struct Include {
332 pub handle: u16,
334 pub start_handle: u16,
336 pub end_handle: u16,
338 pub uuid: Option<Uuid>,
339}
340
341#[derive(Debug, Clone, PartialEq)]
343pub enum Response {
344 Error {
346 opcode: u8,
347 handle: u16,
348 error: AttError,
349 },
350 Mtu(u16),
351 Services(Vec<Service>),
352 Characteristics(Vec<Characteristic>),
353 Includes(Vec<Include>),
354 Descriptors(Vec<Descriptor>),
355 Value(Vec<u8>),
356 WriteComplete,
357 Notification {
359 handle: u16,
360 value: Vec<u8>,
361 },
362 Indication {
364 handle: u16,
365 value: Vec<u8>,
366 },
367 PrepareWriteComplete,
369 PeerRequest {
371 opcode: u8,
372 body: Vec<u8>,
373 },
374 Unknown(u8),
376}
377
378pub fn parse(pdu: &[u8]) -> Option<Response> {
380 let opcode = *pdu.first()?;
381 let body = &pdu[1..];
382 Some(match opcode {
383 opcode::ERROR_RESPONSE => {
384 if body.len() < 4 {
385 return None;
386 }
387 Response::Error {
388 opcode: body[0],
389 handle: u16::from_le_bytes([body[1], body[2]]),
390 error: AttError(body[3]),
391 }
392 }
393
394 opcode::EXCHANGE_MTU_RESPONSE => {
395 if body.len() < 2 {
396 return None;
397 }
398 Response::Mtu(u16::from_le_bytes([body[0], body[1]]))
399 }
400
401 op if is_peer_request(op) => Response::PeerRequest {
404 opcode: op,
405 body: body.to_vec(),
406 },
407
408 opcode::PREPARE_WRITE_RESPONSE => Response::PrepareWriteComplete,
411 opcode::EXECUTE_WRITE_RESPONSE => Response::WriteComplete,
412
413 opcode::READ_BY_GROUP_TYPE_RESPONSE => {
415 let length = *body.first()? as usize;
416 if length < 6 {
417 return None;
418 }
419 let mut services = Vec::new();
420 for entry in body[1..].chunks(length) {
421 if entry.len() < length {
422 break;
423 }
424 let Some(uuid) = Uuid::parse(&entry[4..length]) else {
425 break;
426 };
427 services.push(Service {
428 start_handle: u16::from_le_bytes([entry[0], entry[1]]),
429 end_handle: u16::from_le_bytes([entry[2], entry[3]]),
430 uuid,
431 });
432 }
433 Response::Services(services)
434 }
435
436 opcode::READ_BY_TYPE_RESPONSE if matches!(*body.first()?, 6 | 8) => {
450 let length = *body.first()? as usize;
451 let mut includes = Vec::new();
452 for entry in body[1..].chunks(length) {
453 if entry.len() < length {
454 break;
455 }
456 includes.push(Include {
457 handle: u16::from_le_bytes([entry[0], entry[1]]),
458 start_handle: u16::from_le_bytes([entry[2], entry[3]]),
459 end_handle: u16::from_le_bytes([entry[4], entry[5]]),
460 uuid: if length == 8 {
461 Uuid::parse(&entry[6..8])
462 } else {
463 None
464 },
465 });
466 }
467 Response::Includes(includes)
468 }
469
470 opcode::READ_BY_TYPE_RESPONSE => {
471 let length = *body.first()? as usize;
472 if length < 7 {
473 return None;
474 }
475 let mut characteristics = Vec::new();
476 for entry in body[1..].chunks(length) {
477 if entry.len() < length {
478 break;
479 }
480 let Some(uuid) = Uuid::parse(&entry[5..length]) else {
481 break;
482 };
483 characteristics.push(Characteristic {
484 handle: u16::from_le_bytes([entry[0], entry[1]]),
485 properties: entry[2],
486 value_handle: u16::from_le_bytes([entry[3], entry[4]]),
487 uuid,
488 });
489 }
490 Response::Characteristics(characteristics)
491 }
492
493 opcode::FIND_INFORMATION_RESPONSE => {
495 let format = *body.first()?;
496 let uuid_len = match format {
497 0x01 => 2,
498 0x02 => 16,
499 _ => return None,
500 };
501 let entry_len = 2 + uuid_len;
502 let mut descriptors = Vec::new();
503 for entry in body[1..].chunks(entry_len) {
504 if entry.len() < entry_len {
505 break;
506 }
507 let Some(uuid) = Uuid::parse(&entry[2..entry_len]) else {
508 break;
509 };
510 descriptors.push(Descriptor {
511 handle: u16::from_le_bytes([entry[0], entry[1]]),
512 uuid,
513 });
514 }
515 Response::Descriptors(descriptors)
516 }
517
518 opcode::READ_RESPONSE | opcode::READ_BLOB_RESPONSE => Response::Value(body.to_vec()),
519 opcode::WRITE_RESPONSE => Response::WriteComplete,
520
521 opcode::HANDLE_VALUE_NOTIFICATION => {
522 if body.len() < 2 {
523 return None;
524 }
525 Response::Notification {
526 handle: u16::from_le_bytes([body[0], body[1]]),
527 value: body[2..].to_vec(),
528 }
529 }
530
531 opcode::HANDLE_VALUE_INDICATION => {
532 if body.len() < 2 {
533 return None;
534 }
535 Response::Indication {
536 handle: u16::from_le_bytes([body[0], body[1]]),
537 value: body[2..].to_vec(),
538 }
539 }
540
541 other => Response::Unknown(other),
542 })
543}
544
545pub fn is_unsolicited(opcode: u8) -> bool {
547 matches!(
548 opcode,
549 opcode::HANDLE_VALUE_NOTIFICATION | opcode::HANDLE_VALUE_INDICATION
550 )
551}
552
553#[cfg(test)]
554mod tests {
555 use super::*;
556
557 #[test]
558 fn short_uuids_expand_to_the_bluetooth_base() {
559 assert_eq!(
560 Uuid::Short(0x180D).to_canonical(),
561 "0000180d-0000-1000-8000-00805f9b34fb"
562 );
563 assert_eq!(
564 Uuid::Short(0x2A37).to_canonical(),
565 "00002a37-0000-1000-8000-00805f9b34fb"
566 );
567 }
568
569 #[test]
570 fn uuids_go_on_the_wire_least_significant_first() {
571 assert_eq!(Uuid::Short(0x180D).to_wire(), vec![0x0D, 0x18]);
572 assert_eq!(Uuid::parse(&[0x0D, 0x18]), Some(Uuid::Short(0x180D)));
573
574 let nordic_uart = [
576 0x6E, 0x40, 0x00, 0x01, 0xB5, 0xA3, 0xF3, 0x93, 0xE0, 0xA9, 0xE5, 0x0E, 0x24, 0xDC,
577 0xCA, 0x9E,
578 ];
579 let long = Uuid::Long(nordic_uart);
580 assert_eq!(long.to_canonical(), "6e400001-b5a3-f393-e0a9-e50e24dcca9e");
581 let wire = long.to_wire();
582 assert_eq!(wire[0], 0x9E, "wire order must be reversed");
583 assert_eq!(Uuid::parse(&wire), Some(long));
584 }
585
586 #[test]
587 fn a_bad_uuid_length_is_rejected() {
588 assert_eq!(Uuid::parse(&[]), None);
589 assert_eq!(Uuid::parse(&[1, 2, 3]), None);
590 }
591
592 #[test]
593 fn requests_encode_little_endian() {
594 assert_eq!(read_request(0x0025), vec![0x0A, 0x25, 0x00]);
595 assert_eq!(write_command(0x0012, &[0xAB]), vec![0x52, 0x12, 0x00, 0xAB]);
596 }
597
598 #[test]
603 fn an_include_declaration_is_not_read_as_a_characteristic() {
604 let pdu = [
606 0x09, 0x08, 0x02, 0x00, 0x10, 0x00, 0x1F, 0x00, 0x0F, 0x18, ];
612 assert_eq!(
613 parse(&pdu),
614 Some(Response::Includes(vec![Include {
615 handle: 0x0002,
616 start_handle: 0x0010,
617 end_handle: 0x001F,
618 uuid: Some(Uuid::Short(0x180F)),
619 }]))
620 );
621 }
622
623 #[test]
627 fn a_six_byte_include_has_no_uuid_to_give() {
628 let pdu = [
629 0x09, 0x06, 0x02, 0x00, 0x10, 0x00, 0x1F, 0x00,
631 ];
632 let Some(Response::Includes(includes)) = parse(&pdu) else {
633 panic!("expected includes");
634 };
635 assert_eq!(includes.len(), 1);
636 assert_eq!(includes[0].start_handle, 0x0010);
637 assert!(
638 includes[0].uuid.is_none(),
639 "a 6-byte declaration carries no UUID"
640 );
641 }
642
643 #[test]
644 fn a_characteristic_declaration_still_parses_as_one() {
645 let pdu = [
647 0x09, 0x07, 0x03, 0x00, 0x12, 0x04, 0x00, 0x19, 0x2A, ];
653 let Some(Response::Characteristics(found)) = parse(&pdu) else {
654 panic!("expected characteristics");
655 };
656 assert_eq!(found.len(), 1);
657 assert_eq!(found[0].value_handle, 0x0004);
658 assert_eq!(found[0].uuid, Uuid::Short(0x2A19));
659 }
660
661 #[test]
662 fn several_includes_come_back_in_one_response() {
663 let pdu = [
664 0x09, 0x08, 0x02, 0x00, 0x10, 0x00, 0x1F, 0x00, 0x0F, 0x18, 0x03, 0x00, 0x20, 0x00, 0x2F, 0x00, 0x0D, 0x18,
667 ];
668 let Some(Response::Includes(includes)) = parse(&pdu) else {
669 panic!("expected includes");
670 };
671 assert_eq!(includes.len(), 2);
672 assert_eq!(includes[1].uuid, Some(Uuid::Short(0x180D)));
673 assert_eq!(includes[1].end_handle, 0x002F);
674 }
675
676 #[test]
677 fn a_truncated_include_entry_is_dropped_not_guessed() {
678 let pdu = [0x09, 0x08, 0x02, 0x00, 0x10, 0x00, 0x1F];
680 assert_eq!(parse(&pdu), Some(Response::Includes(vec![])));
681 }
682
683 #[test]
684 fn long_writes_encode_offset_and_commit() {
685 assert_eq!(
686 prepare_write_request(0x0012, 0x0014, &[0xAA, 0xBB]),
687 vec![0x16, 0x12, 0x00, 0x14, 0x00, 0xAA, 0xBB]
688 );
689 assert_eq!(execute_write_request(true), vec![0x18, 0x01]);
690 assert_eq!(execute_write_request(false), vec![0x18, 0x00]);
693 }
694
695 #[test]
696 fn a_prepared_write_echo_is_only_an_acknowledgement() {
697 let echoed = [0x17, 0x12, 0x00, 0x14, 0x00, 0xAA, 0xBB];
699 assert_eq!(parse(&echoed), Some(Response::PrepareWriteComplete));
700 assert_eq!(parse(&[0x19]), Some(Response::WriteComplete));
701 }
702
703 #[test]
704 fn the_peers_own_requests_are_not_replies() {
705 let request = [0x02, 0x17, 0x02];
709 assert_eq!(
710 parse(&request),
711 Some(Response::PeerRequest {
712 opcode: 0x02,
713 body: vec![0x17, 0x02],
714 })
715 );
716 assert_eq!(parse(&[0x03, 0x17, 0x02]), Some(Response::Mtu(0x0217)));
718
719 for op in [0x04u8, 0x08, 0x0A, 0x0C, 0x10, 0x12, 0x16, 0x18] {
720 assert!(is_peer_request(op), "{op:#04x} should be a peer request");
721 }
722 for op in [0x01u8, 0x03, 0x05, 0x0B, 0x11, 0x13, 0x1B, 0x1D, 0x52] {
724 assert!(!is_peer_request(op), "{op:#04x} is not a peer request");
725 }
726 }
727
728 #[test]
729 fn declining_a_request_names_it() {
730 let pdu = error_response(0x0A, 0x0021, AttError(AttError::REQUEST_NOT_SUPPORTED));
731 assert_eq!(pdu, vec![0x01, 0x0A, 0x21, 0x00, 0x06]);
732 assert_eq!(exchange_mtu_response(517), vec![0x03, 0x05, 0x02]);
733 assert_eq!(
734 read_by_group_type_request(0x0001, 0xFFFF, gatt_type::PRIMARY_SERVICE),
735 vec![0x10, 0x01, 0x00, 0xFF, 0xFF, 0x00, 0x28]
736 );
737 assert_eq!(exchange_mtu_request(517), vec![0x02, 0x05, 0x02]);
738 }
739
740 #[test]
741 fn an_error_response_decodes() {
742 let pdu = [0x01, 0x0A, 0x25, 0x00, 0x02];
744 assert_eq!(
745 parse(&pdu),
746 Some(Response::Error {
747 opcode: opcode::READ_REQUEST,
748 handle: 0x0025,
749 error: AttError(AttError::READ_NOT_PERMITTED),
750 })
751 );
752 }
753
754 #[test]
755 fn attribute_not_found_ends_discovery_rather_than_failing_it() {
756 assert!(AttError(AttError::ATTRIBUTE_NOT_FOUND).is_end_of_discovery());
758 assert!(!AttError(AttError::READ_NOT_PERMITTED).is_end_of_discovery());
759 }
760
761 #[test]
762 fn a_service_discovery_response_decodes() {
763 let pdu = [
765 0x11, 0x06, 0x01, 0x00, 0x09, 0x00, 0x00, 0x18, 0x0A, 0x00, 0x0F, 0x00, 0x0D, 0x18, ];
769 let Some(Response::Services(services)) = parse(&pdu) else {
770 panic!("not a service response");
771 };
772 assert_eq!(services.len(), 2);
773 assert_eq!(services[1].start_handle, 0x000A);
774 assert_eq!(services[1].end_handle, 0x000F);
775 assert_eq!(
776 services[1].uuid.to_canonical(),
777 "0000180d-0000-1000-8000-00805f9b34fb"
778 );
779 }
780
781 #[test]
782 fn a_characteristic_discovery_response_decodes() {
783 let pdu = [
785 0x09, 0x07, 0x0B, 0x00, 0x10, 0x0C, 0x00, 0x37, 0x2A, ];
788 let Some(Response::Characteristics(chars)) = parse(&pdu) else {
789 panic!("not a characteristic response");
790 };
791 assert_eq!(chars.len(), 1);
792 assert_eq!(chars[0].handle, 0x000B);
793 assert_eq!(
794 chars[0].value_handle, 0x000C,
795 "reads address the value handle"
796 );
797 assert_eq!(chars[0].properties, 0x10);
798 assert_eq!(
799 chars[0].uuid.to_canonical(),
800 "00002a37-0000-1000-8000-00805f9b34fb"
801 );
802 }
803
804 #[test]
805 fn descriptor_discovery_decodes_both_formats() {
806 let short = [0x05, 0x01, 0x0D, 0x00, 0x02, 0x29];
808 let Some(Response::Descriptors(d)) = parse(&short) else {
809 panic!()
810 };
811 assert_eq!(d.len(), 1);
812 assert_eq!(d[0].handle, 0x000D);
813 assert_eq!(d[0].uuid, Uuid::Short(0x2902));
814
815 let mut long = vec![0x05, 0x02, 0x0E, 0x00];
817 long.extend_from_slice(&Uuid::Short(0x2902).to_wire());
818 long.extend_from_slice(&[0; 14]);
819 let Some(Response::Descriptors(d)) = parse(&long) else {
820 panic!()
821 };
822 assert_eq!(d[0].handle, 0x000E);
823
824 assert_eq!(parse(&[0x05, 0x03, 0x00, 0x00]), None);
826 }
827
828 #[test]
829 fn notifications_are_recognised_as_unsolicited() {
830 let pdu = [0x1B, 0x0C, 0x00, 0x00, 0x48];
831 assert_eq!(
832 parse(&pdu),
833 Some(Response::Notification {
834 handle: 0x000C,
835 value: vec![0x00, 0x48]
836 })
837 );
838 assert!(is_unsolicited(opcode::HANDLE_VALUE_NOTIFICATION));
839 assert!(is_unsolicited(opcode::HANDLE_VALUE_INDICATION));
840 assert!(!is_unsolicited(opcode::READ_RESPONSE));
842 }
843
844 #[test]
845 fn truncated_pdus_are_rejected_rather_than_misread() {
846 assert_eq!(parse(&[]), None);
848 assert_eq!(parse(&[0x01, 0x0A]), None);
849 assert_eq!(parse(&[0x03]), None);
850 assert_eq!(parse(&[0x1B, 0x0C]), None);
851 assert_eq!(parse(&[0x11, 0x02, 0x00, 0x00]), None);
853 assert_eq!(parse(&[0x09, 0x03, 0x00, 0x00]), None);
854 }
855
856 #[test]
857 fn a_trailing_partial_entry_is_dropped_not_decoded() {
858 let pdu = [0x11, 0x06, 0x01, 0x00, 0x09, 0x00, 0x00, 0x18, 0x0A, 0x00];
860 let Some(Response::Services(services)) = parse(&pdu) else {
861 panic!()
862 };
863 assert_eq!(services.len(), 1);
864 }
865}