Skip to main content

fidl_fuchsia_bluetooth_test/
fidl_fuchsia_bluetooth_test.rs

1// WARNING: This file is machine generated by fidlgen.
2
3#![warn(clippy::all)]
4#![allow(unused_parens, unused_mut, unused_imports, nonstandard_style)]
5
6use bitflags::bitflags;
7use fidl::client::QueryResponseFut;
8use fidl::encoding::{MessageBufFor, ProxyChannelBox, ResourceDialect};
9use fidl::endpoints::{ControlHandle as _, Responder as _};
10pub use fidl_fuchsia_bluetooth_test_common::*;
11use futures::future::{self, MaybeDone, TryFutureExt};
12use zx_status;
13
14#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
15pub struct GattMarker;
16
17impl fidl::endpoints::ProtocolMarker for GattMarker {
18    type Proxy = GattProxy;
19    type RequestStream = GattRequestStream;
20    #[cfg(target_os = "fuchsia")]
21    type SynchronousProxy = GattSynchronousProxy;
22
23    const DEBUG_NAME: &'static str = "fuchsia.bluetooth.test.Gatt";
24}
25impl fidl::endpoints::DiscoverableProtocolMarker for GattMarker {}
26pub type GattResolvePeerAttHandleResult = Result<GattResolvePeerAttHandleResponse, GattError>;
27
28pub trait GattProxyInterface: Send + Sync {
29    type ResolvePeerAttHandleResponseFut: std::future::Future<Output = Result<GattResolvePeerAttHandleResult, fidl::Error>>
30        + Send;
31    fn r#resolve_peer_att_handle(
32        &self,
33        payload: &GattResolvePeerAttHandleRequest,
34    ) -> Self::ResolvePeerAttHandleResponseFut;
35}
36#[derive(Debug)]
37#[cfg(target_os = "fuchsia")]
38pub struct GattSynchronousProxy {
39    client: fidl::client::sync::Client,
40}
41
42#[cfg(target_os = "fuchsia")]
43impl fidl::endpoints::SynchronousProxy for GattSynchronousProxy {
44    type Proxy = GattProxy;
45    type Protocol = GattMarker;
46
47    fn from_channel(inner: fidl::Channel) -> Self {
48        Self::new(inner)
49    }
50
51    fn into_channel(self) -> fidl::Channel {
52        self.client.into_channel()
53    }
54
55    fn as_channel(&self) -> &fidl::Channel {
56        self.client.as_channel()
57    }
58}
59
60#[cfg(target_os = "fuchsia")]
61impl GattSynchronousProxy {
62    pub fn new(channel: fidl::Channel) -> Self {
63        Self { client: fidl::client::sync::Client::new(channel) }
64    }
65
66    pub fn into_channel(self) -> fidl::Channel {
67        self.client.into_channel()
68    }
69
70    /// Waits until an event arrives and returns it. It is safe for other
71    /// threads to make concurrent requests while waiting for an event.
72    pub fn wait_for_event(&self, deadline: zx::MonotonicInstant) -> Result<GattEvent, fidl::Error> {
73        GattEvent::decode(self.client.wait_for_event::<GattMarker>(deadline)?)
74    }
75
76    /// Resolves a peer's attribute handle into a service and characteristic handle.
77    ///
78    /// * error Returns `MISSING_PARAMETERS` if `id` or `attribute_handle` is missing.
79    /// * error Returns `HANDLE_NOT_FOUND` if `attribute_handle` is not found.
80    /// * error Returns `INTERNAL` if an underlying GATT procedure fails.
81    pub fn r#resolve_peer_att_handle(
82        &self,
83        mut payload: &GattResolvePeerAttHandleRequest,
84        ___deadline: zx::MonotonicInstant,
85    ) -> Result<GattResolvePeerAttHandleResult, fidl::Error> {
86        let _response = self.client.send_query::<
87            GattResolvePeerAttHandleRequest,
88            fidl::encoding::FlexibleResultType<GattResolvePeerAttHandleResponse, GattError>,
89            GattMarker,
90        >(
91            payload,
92            0x462b9cc1b4b58d4f,
93            fidl::encoding::DynamicFlags::FLEXIBLE,
94            ___deadline,
95        )?
96        .into_result::<GattMarker>("resolve_peer_att_handle")?;
97        Ok(_response.map(|x| x))
98    }
99}
100
101#[cfg(target_os = "fuchsia")]
102impl From<GattSynchronousProxy> for zx::NullableHandle {
103    fn from(value: GattSynchronousProxy) -> Self {
104        value.into_channel().into()
105    }
106}
107
108#[cfg(target_os = "fuchsia")]
109impl From<fidl::Channel> for GattSynchronousProxy {
110    fn from(value: fidl::Channel) -> Self {
111        Self::new(value)
112    }
113}
114
115#[cfg(target_os = "fuchsia")]
116impl fidl::endpoints::FromClient for GattSynchronousProxy {
117    type Protocol = GattMarker;
118
119    fn from_client(value: fidl::endpoints::ClientEnd<GattMarker>) -> Self {
120        Self::new(value.into_channel())
121    }
122}
123
124#[derive(Debug, Clone)]
125pub struct GattProxy {
126    client: fidl::client::Client<fidl::encoding::DefaultFuchsiaResourceDialect>,
127}
128
129impl fidl::endpoints::Proxy for GattProxy {
130    type Protocol = GattMarker;
131
132    fn from_channel(inner: ::fidl::AsyncChannel) -> Self {
133        Self::new(inner)
134    }
135
136    fn into_channel(self) -> Result<::fidl::AsyncChannel, Self> {
137        self.client.into_channel().map_err(|client| Self { client })
138    }
139
140    fn as_channel(&self) -> &::fidl::AsyncChannel {
141        self.client.as_channel()
142    }
143}
144
145impl GattProxy {
146    /// Create a new Proxy for fuchsia.bluetooth.test/Gatt.
147    pub fn new(channel: ::fidl::AsyncChannel) -> Self {
148        let protocol_name = <GattMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
149        Self { client: fidl::client::Client::new(channel, protocol_name) }
150    }
151
152    /// Get a Stream of events from the remote end of the protocol.
153    ///
154    /// # Panics
155    ///
156    /// Panics if the event stream was already taken.
157    pub fn take_event_stream(&self) -> GattEventStream {
158        GattEventStream { event_receiver: self.client.take_event_receiver() }
159    }
160
161    /// Resolves a peer's attribute handle into a service and characteristic handle.
162    ///
163    /// * error Returns `MISSING_PARAMETERS` if `id` or `attribute_handle` is missing.
164    /// * error Returns `HANDLE_NOT_FOUND` if `attribute_handle` is not found.
165    /// * error Returns `INTERNAL` if an underlying GATT procedure fails.
166    pub fn r#resolve_peer_att_handle(
167        &self,
168        mut payload: &GattResolvePeerAttHandleRequest,
169    ) -> fidl::client::QueryResponseFut<
170        GattResolvePeerAttHandleResult,
171        fidl::encoding::DefaultFuchsiaResourceDialect,
172    > {
173        GattProxyInterface::r#resolve_peer_att_handle(self, payload)
174    }
175}
176
177impl GattProxyInterface for GattProxy {
178    type ResolvePeerAttHandleResponseFut = fidl::client::QueryResponseFut<
179        GattResolvePeerAttHandleResult,
180        fidl::encoding::DefaultFuchsiaResourceDialect,
181    >;
182    fn r#resolve_peer_att_handle(
183        &self,
184        mut payload: &GattResolvePeerAttHandleRequest,
185    ) -> Self::ResolvePeerAttHandleResponseFut {
186        fn _decode(
187            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
188        ) -> Result<GattResolvePeerAttHandleResult, fidl::Error> {
189            let _response = fidl::client::decode_transaction_body::<
190                fidl::encoding::FlexibleResultType<GattResolvePeerAttHandleResponse, GattError>,
191                fidl::encoding::DefaultFuchsiaResourceDialect,
192                0x462b9cc1b4b58d4f,
193            >(_buf?)?
194            .into_result::<GattMarker>("resolve_peer_att_handle")?;
195            Ok(_response.map(|x| x))
196        }
197        self.client.send_query_and_decode::<
198            GattResolvePeerAttHandleRequest,
199            GattResolvePeerAttHandleResult,
200        >(
201            payload,
202            0x462b9cc1b4b58d4f,
203            fidl::encoding::DynamicFlags::FLEXIBLE,
204            _decode,
205        )
206    }
207}
208
209pub struct GattEventStream {
210    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
211}
212
213impl std::marker::Unpin for GattEventStream {}
214
215impl futures::stream::FusedStream for GattEventStream {
216    fn is_terminated(&self) -> bool {
217        self.event_receiver.is_terminated()
218    }
219}
220
221impl futures::Stream for GattEventStream {
222    type Item = Result<GattEvent, fidl::Error>;
223
224    fn poll_next(
225        mut self: std::pin::Pin<&mut Self>,
226        cx: &mut std::task::Context<'_>,
227    ) -> std::task::Poll<Option<Self::Item>> {
228        match futures::ready!(futures::stream::StreamExt::poll_next_unpin(
229            &mut self.event_receiver,
230            cx
231        )?) {
232            Some(buf) => std::task::Poll::Ready(Some(GattEvent::decode(buf))),
233            None => std::task::Poll::Ready(None),
234        }
235    }
236}
237
238#[derive(Debug)]
239pub enum GattEvent {
240    #[non_exhaustive]
241    _UnknownEvent {
242        /// Ordinal of the event that was sent.
243        ordinal: u64,
244    },
245}
246
247impl GattEvent {
248    /// Decodes a message buffer as a [`GattEvent`].
249    fn decode(
250        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
251    ) -> Result<GattEvent, fidl::Error> {
252        let (bytes, _handles) = buf.split_mut();
253        let (tx_header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
254        debug_assert_eq!(tx_header.tx_id, 0);
255        match tx_header.ordinal {
256            _ if tx_header.dynamic_flags().contains(fidl::encoding::DynamicFlags::FLEXIBLE) => {
257                Ok(GattEvent::_UnknownEvent { ordinal: tx_header.ordinal })
258            }
259            _ => Err(fidl::Error::UnknownOrdinal {
260                ordinal: tx_header.ordinal,
261                protocol_name: <GattMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
262            }),
263        }
264    }
265}
266
267/// A Stream of incoming requests for fuchsia.bluetooth.test/Gatt.
268pub struct GattRequestStream {
269    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
270    is_terminated: bool,
271}
272
273impl std::marker::Unpin for GattRequestStream {}
274
275impl futures::stream::FusedStream for GattRequestStream {
276    fn is_terminated(&self) -> bool {
277        self.is_terminated
278    }
279}
280
281impl fidl::endpoints::RequestStream for GattRequestStream {
282    type Protocol = GattMarker;
283    type ControlHandle = GattControlHandle;
284
285    fn from_channel(channel: ::fidl::AsyncChannel) -> Self {
286        Self { inner: std::sync::Arc::new(fidl::ServeInner::new(channel)), is_terminated: false }
287    }
288
289    fn control_handle(&self) -> Self::ControlHandle {
290        GattControlHandle { inner: self.inner.clone() }
291    }
292
293    fn into_inner(
294        self,
295    ) -> (::std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>, bool)
296    {
297        (self.inner, self.is_terminated)
298    }
299
300    fn from_inner(
301        inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
302        is_terminated: bool,
303    ) -> Self {
304        Self { inner, is_terminated }
305    }
306}
307
308impl futures::Stream for GattRequestStream {
309    type Item = Result<GattRequest, fidl::Error>;
310
311    fn poll_next(
312        mut self: std::pin::Pin<&mut Self>,
313        cx: &mut std::task::Context<'_>,
314    ) -> std::task::Poll<Option<Self::Item>> {
315        let this = &mut *self;
316        if this.inner.check_shutdown(cx) {
317            this.is_terminated = true;
318            return std::task::Poll::Ready(None);
319        }
320        if this.is_terminated {
321            panic!("polled GattRequestStream after completion");
322        }
323        fidl::encoding::with_tls_decode_buf::<_, fidl::encoding::DefaultFuchsiaResourceDialect>(
324            |bytes, handles| {
325                match this.inner.channel().read_etc(cx, bytes, handles) {
326                    std::task::Poll::Ready(Ok(())) => {}
327                    std::task::Poll::Pending => return std::task::Poll::Pending,
328                    std::task::Poll::Ready(Err(zx_status::Status::PEER_CLOSED)) => {
329                        this.is_terminated = true;
330                        return std::task::Poll::Ready(None);
331                    }
332                    std::task::Poll::Ready(Err(e)) => {
333                        return std::task::Poll::Ready(Some(Err(fidl::Error::ServerRequestRead(
334                            e.into(),
335                        ))));
336                    }
337                }
338
339                // A message has been received from the channel
340                let (header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
341
342                std::task::Poll::Ready(Some(match header.ordinal {
343                    0x462b9cc1b4b58d4f => {
344                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
345                        let mut req = fidl::new_empty!(
346                            GattResolvePeerAttHandleRequest,
347                            fidl::encoding::DefaultFuchsiaResourceDialect
348                        );
349                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<GattResolvePeerAttHandleRequest>(&header, _body_bytes, handles, &mut req)?;
350                        let control_handle = GattControlHandle { inner: this.inner.clone() };
351                        Ok(GattRequest::ResolvePeerAttHandle {
352                            payload: req,
353                            responder: GattResolvePeerAttHandleResponder {
354                                control_handle: std::mem::ManuallyDrop::new(control_handle),
355                                tx_id: header.tx_id,
356                            },
357                        })
358                    }
359                    _ if header.tx_id == 0
360                        && header
361                            .dynamic_flags()
362                            .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
363                    {
364                        Ok(GattRequest::_UnknownMethod {
365                            ordinal: header.ordinal,
366                            control_handle: GattControlHandle { inner: this.inner.clone() },
367                            method_type: fidl::MethodType::OneWay,
368                        })
369                    }
370                    _ if header
371                        .dynamic_flags()
372                        .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
373                    {
374                        this.inner.send_framework_err(
375                            fidl::encoding::FrameworkErr::UnknownMethod,
376                            header.tx_id,
377                            header.ordinal,
378                            header.dynamic_flags(),
379                            (bytes, handles),
380                        )?;
381                        Ok(GattRequest::_UnknownMethod {
382                            ordinal: header.ordinal,
383                            control_handle: GattControlHandle { inner: this.inner.clone() },
384                            method_type: fidl::MethodType::TwoWay,
385                        })
386                    }
387                    _ => Err(fidl::Error::UnknownOrdinal {
388                        ordinal: header.ordinal,
389                        protocol_name: <GattMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
390                    }),
391                }))
392            },
393        )
394    }
395}
396
397#[derive(Debug)]
398pub enum GattRequest {
399    /// Resolves a peer's attribute handle into a service and characteristic handle.
400    ///
401    /// * error Returns `MISSING_PARAMETERS` if `id` or `attribute_handle` is missing.
402    /// * error Returns `HANDLE_NOT_FOUND` if `attribute_handle` is not found.
403    /// * error Returns `INTERNAL` if an underlying GATT procedure fails.
404    ResolvePeerAttHandle {
405        payload: GattResolvePeerAttHandleRequest,
406        responder: GattResolvePeerAttHandleResponder,
407    },
408    /// An interaction was received which does not match any known method.
409    #[non_exhaustive]
410    _UnknownMethod {
411        /// Ordinal of the method that was called.
412        ordinal: u64,
413        control_handle: GattControlHandle,
414        method_type: fidl::MethodType,
415    },
416}
417
418impl GattRequest {
419    #[allow(irrefutable_let_patterns)]
420    pub fn into_resolve_peer_att_handle(
421        self,
422    ) -> Option<(GattResolvePeerAttHandleRequest, GattResolvePeerAttHandleResponder)> {
423        if let GattRequest::ResolvePeerAttHandle { payload, responder } = self {
424            Some((payload, responder))
425        } else {
426            None
427        }
428    }
429
430    /// Name of the method defined in FIDL
431    pub fn method_name(&self) -> &'static str {
432        match *self {
433            GattRequest::ResolvePeerAttHandle { .. } => "resolve_peer_att_handle",
434            GattRequest::_UnknownMethod { method_type: fidl::MethodType::OneWay, .. } => {
435                "unknown one-way method"
436            }
437            GattRequest::_UnknownMethod { method_type: fidl::MethodType::TwoWay, .. } => {
438                "unknown two-way method"
439            }
440        }
441    }
442}
443
444#[derive(Debug, Clone)]
445pub struct GattControlHandle {
446    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
447}
448
449impl fidl::endpoints::ControlHandle for GattControlHandle {
450    fn shutdown(&self) {
451        self.inner.shutdown()
452    }
453
454    fn shutdown_with_epitaph(&self, status: zx_status::Status) {
455        self.inner.shutdown_with_epitaph(status)
456    }
457
458    fn is_closed(&self) -> bool {
459        self.inner.channel().is_closed()
460    }
461    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
462        self.inner.channel().on_closed()
463    }
464
465    #[cfg(target_os = "fuchsia")]
466    fn signal_peer(
467        &self,
468        clear_mask: zx::Signals,
469        set_mask: zx::Signals,
470    ) -> Result<(), zx_status::Status> {
471        use fidl::Peered;
472        self.inner.channel().signal_peer(clear_mask, set_mask)
473    }
474}
475
476impl GattControlHandle {}
477
478#[must_use = "FIDL methods require a response to be sent"]
479#[derive(Debug)]
480pub struct GattResolvePeerAttHandleResponder {
481    control_handle: std::mem::ManuallyDrop<GattControlHandle>,
482    tx_id: u32,
483}
484
485/// Set the the channel to be shutdown (see [`GattControlHandle::shutdown`])
486/// if the responder is dropped without sending a response, so that the client
487/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
488impl std::ops::Drop for GattResolvePeerAttHandleResponder {
489    fn drop(&mut self) {
490        self.control_handle.shutdown();
491        // Safety: drops once, never accessed again
492        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
493    }
494}
495
496impl fidl::endpoints::Responder for GattResolvePeerAttHandleResponder {
497    type ControlHandle = GattControlHandle;
498
499    fn control_handle(&self) -> &GattControlHandle {
500        &self.control_handle
501    }
502
503    fn drop_without_shutdown(mut self) {
504        // Safety: drops once, never accessed again due to mem::forget
505        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
506        // Prevent Drop from running (which would shut down the channel)
507        std::mem::forget(self);
508    }
509}
510
511impl GattResolvePeerAttHandleResponder {
512    /// Sends a response to the FIDL transaction.
513    ///
514    /// Sets the channel to shutdown if an error occurs.
515    pub fn send(
516        self,
517        mut result: Result<&GattResolvePeerAttHandleResponse, GattError>,
518    ) -> Result<(), fidl::Error> {
519        let _result = self.send_raw(result);
520        if _result.is_err() {
521            self.control_handle.shutdown();
522        }
523        self.drop_without_shutdown();
524        _result
525    }
526
527    /// Similar to "send" but does not shutdown the channel if an error occurs.
528    pub fn send_no_shutdown_on_err(
529        self,
530        mut result: Result<&GattResolvePeerAttHandleResponse, GattError>,
531    ) -> Result<(), fidl::Error> {
532        let _result = self.send_raw(result);
533        self.drop_without_shutdown();
534        _result
535    }
536
537    fn send_raw(
538        &self,
539        mut result: Result<&GattResolvePeerAttHandleResponse, GattError>,
540    ) -> Result<(), fidl::Error> {
541        self.control_handle.inner.send::<fidl::encoding::FlexibleResultType<
542            GattResolvePeerAttHandleResponse,
543            GattError,
544        >>(
545            fidl::encoding::FlexibleResult::new(result),
546            self.tx_id,
547            0x462b9cc1b4b58d4f,
548            fidl::encoding::DynamicFlags::FLEXIBLE,
549        )
550    }
551}
552
553mod internal {
554    use super::*;
555}