fidl_fuchsia_power_clientlevel/
fidl_fuchsia_power_clientlevel.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 _};
10use futures::future::{self, MaybeDone, TryFutureExt};
11use zx_status;
12
13/// A value that represents the type of client using the protocol.
14///
15/// `ClientType` is used as a parameter for:
16///   1) [`Connector.Connect`] to connect a [`Watcher`] to the power level of
17///   the specified client type
18///   2) [`fuchsia.power.systemmode/ClientConfigurator.Get`] and
19///   [`fuchsia.power.systemmode/ClientConfigurator.Set`] to update the power
20///   configuration of the specified client type
21#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
22pub enum ClientType {
23    Wlan,
24    #[doc(hidden)]
25    __SourceBreaking {
26        unknown_ordinal: u32,
27    },
28}
29
30/// Pattern that matches an unknown `ClientType` member.
31#[macro_export]
32macro_rules! ClientTypeUnknown {
33    () => {
34        _
35    };
36}
37
38impl ClientType {
39    #[inline]
40    pub fn from_primitive(prim: u32) -> Option<Self> {
41        match prim {
42            1 => Some(Self::Wlan),
43            _ => None,
44        }
45    }
46
47    #[inline]
48    pub fn from_primitive_allow_unknown(prim: u32) -> Self {
49        match prim {
50            1 => Self::Wlan,
51            unknown_ordinal => Self::__SourceBreaking { unknown_ordinal },
52        }
53    }
54
55    #[inline]
56    pub fn unknown() -> Self {
57        Self::__SourceBreaking { unknown_ordinal: 0xffffffff }
58    }
59
60    #[inline]
61    pub const fn into_primitive(self) -> u32 {
62        match self {
63            Self::Wlan => 1,
64            Self::__SourceBreaking { unknown_ordinal } => unknown_ordinal,
65        }
66    }
67
68    #[inline]
69    pub fn is_unknown(&self) -> bool {
70        match self {
71            Self::__SourceBreaking { unknown_ordinal: _ } => true,
72            _ => false,
73        }
74    }
75}
76
77#[derive(Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
78pub struct ConnectorConnectRequest {
79    pub client_type: ClientType,
80    pub watcher: fidl::endpoints::ServerEnd<WatcherMarker>,
81}
82
83impl fidl::Standalone<fidl::encoding::DefaultFuchsiaResourceDialect> for ConnectorConnectRequest {}
84
85#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
86#[repr(C)]
87pub struct WatcherWatchResponse {
88    pub level: u64,
89}
90
91impl fidl::Persistable for WatcherWatchResponse {}
92
93#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
94pub struct ConnectorMarker;
95
96impl fidl::endpoints::ProtocolMarker for ConnectorMarker {
97    type Proxy = ConnectorProxy;
98    type RequestStream = ConnectorRequestStream;
99    #[cfg(target_os = "fuchsia")]
100    type SynchronousProxy = ConnectorSynchronousProxy;
101
102    const DEBUG_NAME: &'static str = "fuchsia.power.clientlevel.Connector";
103}
104impl fidl::endpoints::DiscoverableProtocolMarker for ConnectorMarker {}
105
106pub trait ConnectorProxyInterface: Send + Sync {
107    fn r#connect(
108        &self,
109        client_type: ClientType,
110        watcher: fidl::endpoints::ServerEnd<WatcherMarker>,
111    ) -> Result<(), fidl::Error>;
112}
113#[derive(Debug)]
114#[cfg(target_os = "fuchsia")]
115pub struct ConnectorSynchronousProxy {
116    client: fidl::client::sync::Client,
117}
118
119#[cfg(target_os = "fuchsia")]
120impl fidl::endpoints::SynchronousProxy for ConnectorSynchronousProxy {
121    type Proxy = ConnectorProxy;
122    type Protocol = ConnectorMarker;
123
124    fn from_channel(inner: fidl::Channel) -> Self {
125        Self::new(inner)
126    }
127
128    fn into_channel(self) -> fidl::Channel {
129        self.client.into_channel()
130    }
131
132    fn as_channel(&self) -> &fidl::Channel {
133        self.client.as_channel()
134    }
135}
136
137#[cfg(target_os = "fuchsia")]
138impl ConnectorSynchronousProxy {
139    pub fn new(channel: fidl::Channel) -> Self {
140        let protocol_name = <ConnectorMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
141        Self { client: fidl::client::sync::Client::new(channel, protocol_name) }
142    }
143
144    pub fn into_channel(self) -> fidl::Channel {
145        self.client.into_channel()
146    }
147
148    /// Waits until an event arrives and returns it. It is safe for other
149    /// threads to make concurrent requests while waiting for an event.
150    pub fn wait_for_event(
151        &self,
152        deadline: zx::MonotonicInstant,
153    ) -> Result<ConnectorEvent, fidl::Error> {
154        ConnectorEvent::decode(self.client.wait_for_event(deadline)?)
155    }
156
157    /// Connects a [`Watcher`] to the power level of the specified
158    /// [`ClientType`].
159    ///
160    /// A client may call this method and begin using the [`Watcher`] client
161    /// endpoint immediately.
162    ///
163    /// If a power configuration does not exist for the provided `client_type`,
164    /// then the request will fail. On failure, both the `watcher` server
165    /// endpoint as well as the current `Connector` connection will be
166    /// terminated.
167    ///
168    /// + `client_type` specifies to which [`ClientType`] power level that
169    /// `watcher` should be connected. The value is valid iff a power
170    /// configuration exists for the provided `client_type`.
171    ///
172    /// + `watcher` is the server endpoint of a [`Watcher`] channel that will be
173    /// connected to the [`ClientType`] power level.
174    pub fn r#connect(
175        &self,
176        mut client_type: ClientType,
177        mut watcher: fidl::endpoints::ServerEnd<WatcherMarker>,
178    ) -> Result<(), fidl::Error> {
179        self.client.send::<ConnectorConnectRequest>(
180            (client_type, watcher),
181            0x29e603fe743fd08a,
182            fidl::encoding::DynamicFlags::empty(),
183        )
184    }
185}
186
187#[derive(Debug, Clone)]
188pub struct ConnectorProxy {
189    client: fidl::client::Client<fidl::encoding::DefaultFuchsiaResourceDialect>,
190}
191
192impl fidl::endpoints::Proxy for ConnectorProxy {
193    type Protocol = ConnectorMarker;
194
195    fn from_channel(inner: ::fidl::AsyncChannel) -> Self {
196        Self::new(inner)
197    }
198
199    fn into_channel(self) -> Result<::fidl::AsyncChannel, Self> {
200        self.client.into_channel().map_err(|client| Self { client })
201    }
202
203    fn as_channel(&self) -> &::fidl::AsyncChannel {
204        self.client.as_channel()
205    }
206}
207
208impl ConnectorProxy {
209    /// Create a new Proxy for fuchsia.power.clientlevel/Connector.
210    pub fn new(channel: ::fidl::AsyncChannel) -> Self {
211        let protocol_name = <ConnectorMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
212        Self { client: fidl::client::Client::new(channel, protocol_name) }
213    }
214
215    /// Get a Stream of events from the remote end of the protocol.
216    ///
217    /// # Panics
218    ///
219    /// Panics if the event stream was already taken.
220    pub fn take_event_stream(&self) -> ConnectorEventStream {
221        ConnectorEventStream { event_receiver: self.client.take_event_receiver() }
222    }
223
224    /// Connects a [`Watcher`] to the power level of the specified
225    /// [`ClientType`].
226    ///
227    /// A client may call this method and begin using the [`Watcher`] client
228    /// endpoint immediately.
229    ///
230    /// If a power configuration does not exist for the provided `client_type`,
231    /// then the request will fail. On failure, both the `watcher` server
232    /// endpoint as well as the current `Connector` connection will be
233    /// terminated.
234    ///
235    /// + `client_type` specifies to which [`ClientType`] power level that
236    /// `watcher` should be connected. The value is valid iff a power
237    /// configuration exists for the provided `client_type`.
238    ///
239    /// + `watcher` is the server endpoint of a [`Watcher`] channel that will be
240    /// connected to the [`ClientType`] power level.
241    pub fn r#connect(
242        &self,
243        mut client_type: ClientType,
244        mut watcher: fidl::endpoints::ServerEnd<WatcherMarker>,
245    ) -> Result<(), fidl::Error> {
246        ConnectorProxyInterface::r#connect(self, client_type, watcher)
247    }
248}
249
250impl ConnectorProxyInterface for ConnectorProxy {
251    fn r#connect(
252        &self,
253        mut client_type: ClientType,
254        mut watcher: fidl::endpoints::ServerEnd<WatcherMarker>,
255    ) -> Result<(), fidl::Error> {
256        self.client.send::<ConnectorConnectRequest>(
257            (client_type, watcher),
258            0x29e603fe743fd08a,
259            fidl::encoding::DynamicFlags::empty(),
260        )
261    }
262}
263
264pub struct ConnectorEventStream {
265    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
266}
267
268impl std::marker::Unpin for ConnectorEventStream {}
269
270impl futures::stream::FusedStream for ConnectorEventStream {
271    fn is_terminated(&self) -> bool {
272        self.event_receiver.is_terminated()
273    }
274}
275
276impl futures::Stream for ConnectorEventStream {
277    type Item = Result<ConnectorEvent, fidl::Error>;
278
279    fn poll_next(
280        mut self: std::pin::Pin<&mut Self>,
281        cx: &mut std::task::Context<'_>,
282    ) -> std::task::Poll<Option<Self::Item>> {
283        match futures::ready!(futures::stream::StreamExt::poll_next_unpin(
284            &mut self.event_receiver,
285            cx
286        )?) {
287            Some(buf) => std::task::Poll::Ready(Some(ConnectorEvent::decode(buf))),
288            None => std::task::Poll::Ready(None),
289        }
290    }
291}
292
293#[derive(Debug)]
294pub enum ConnectorEvent {}
295
296impl ConnectorEvent {
297    /// Decodes a message buffer as a [`ConnectorEvent`].
298    fn decode(
299        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
300    ) -> Result<ConnectorEvent, fidl::Error> {
301        let (bytes, _handles) = buf.split_mut();
302        let (tx_header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
303        debug_assert_eq!(tx_header.tx_id, 0);
304        match tx_header.ordinal {
305            _ => Err(fidl::Error::UnknownOrdinal {
306                ordinal: tx_header.ordinal,
307                protocol_name: <ConnectorMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
308            }),
309        }
310    }
311}
312
313/// A Stream of incoming requests for fuchsia.power.clientlevel/Connector.
314pub struct ConnectorRequestStream {
315    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
316    is_terminated: bool,
317}
318
319impl std::marker::Unpin for ConnectorRequestStream {}
320
321impl futures::stream::FusedStream for ConnectorRequestStream {
322    fn is_terminated(&self) -> bool {
323        self.is_terminated
324    }
325}
326
327impl fidl::endpoints::RequestStream for ConnectorRequestStream {
328    type Protocol = ConnectorMarker;
329    type ControlHandle = ConnectorControlHandle;
330
331    fn from_channel(channel: ::fidl::AsyncChannel) -> Self {
332        Self { inner: std::sync::Arc::new(fidl::ServeInner::new(channel)), is_terminated: false }
333    }
334
335    fn control_handle(&self) -> Self::ControlHandle {
336        ConnectorControlHandle { inner: self.inner.clone() }
337    }
338
339    fn into_inner(
340        self,
341    ) -> (::std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>, bool)
342    {
343        (self.inner, self.is_terminated)
344    }
345
346    fn from_inner(
347        inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
348        is_terminated: bool,
349    ) -> Self {
350        Self { inner, is_terminated }
351    }
352}
353
354impl futures::Stream for ConnectorRequestStream {
355    type Item = Result<ConnectorRequest, fidl::Error>;
356
357    fn poll_next(
358        mut self: std::pin::Pin<&mut Self>,
359        cx: &mut std::task::Context<'_>,
360    ) -> std::task::Poll<Option<Self::Item>> {
361        let this = &mut *self;
362        if this.inner.check_shutdown(cx) {
363            this.is_terminated = true;
364            return std::task::Poll::Ready(None);
365        }
366        if this.is_terminated {
367            panic!("polled ConnectorRequestStream after completion");
368        }
369        fidl::encoding::with_tls_decode_buf::<_, fidl::encoding::DefaultFuchsiaResourceDialect>(
370            |bytes, handles| {
371                match this.inner.channel().read_etc(cx, bytes, handles) {
372                    std::task::Poll::Ready(Ok(())) => {}
373                    std::task::Poll::Pending => return std::task::Poll::Pending,
374                    std::task::Poll::Ready(Err(zx_status::Status::PEER_CLOSED)) => {
375                        this.is_terminated = true;
376                        return std::task::Poll::Ready(None);
377                    }
378                    std::task::Poll::Ready(Err(e)) => {
379                        return std::task::Poll::Ready(Some(Err(fidl::Error::ServerRequestRead(
380                            e.into(),
381                        ))))
382                    }
383                }
384
385                // A message has been received from the channel
386                let (header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
387
388                std::task::Poll::Ready(Some(match header.ordinal {
389                    0x29e603fe743fd08a => {
390                        header.validate_request_tx_id(fidl::MethodType::OneWay)?;
391                        let mut req = fidl::new_empty!(
392                            ConnectorConnectRequest,
393                            fidl::encoding::DefaultFuchsiaResourceDialect
394                        );
395                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<ConnectorConnectRequest>(&header, _body_bytes, handles, &mut req)?;
396                        let control_handle = ConnectorControlHandle { inner: this.inner.clone() };
397                        Ok(ConnectorRequest::Connect {
398                            client_type: req.client_type,
399                            watcher: req.watcher,
400
401                            control_handle,
402                        })
403                    }
404                    _ => Err(fidl::Error::UnknownOrdinal {
405                        ordinal: header.ordinal,
406                        protocol_name:
407                            <ConnectorMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
408                    }),
409                }))
410            },
411        )
412    }
413}
414
415/// Allows a client to connect a [`Watcher`] to the power level of a given
416/// [`ClientType`].
417#[derive(Debug)]
418pub enum ConnectorRequest {
419    /// Connects a [`Watcher`] to the power level of the specified
420    /// [`ClientType`].
421    ///
422    /// A client may call this method and begin using the [`Watcher`] client
423    /// endpoint immediately.
424    ///
425    /// If a power configuration does not exist for the provided `client_type`,
426    /// then the request will fail. On failure, both the `watcher` server
427    /// endpoint as well as the current `Connector` connection will be
428    /// terminated.
429    ///
430    /// + `client_type` specifies to which [`ClientType`] power level that
431    /// `watcher` should be connected. The value is valid iff a power
432    /// configuration exists for the provided `client_type`.
433    ///
434    /// + `watcher` is the server endpoint of a [`Watcher`] channel that will be
435    /// connected to the [`ClientType`] power level.
436    Connect {
437        client_type: ClientType,
438        watcher: fidl::endpoints::ServerEnd<WatcherMarker>,
439        control_handle: ConnectorControlHandle,
440    },
441}
442
443impl ConnectorRequest {
444    #[allow(irrefutable_let_patterns)]
445    pub fn into_connect(
446        self,
447    ) -> Option<(ClientType, fidl::endpoints::ServerEnd<WatcherMarker>, ConnectorControlHandle)>
448    {
449        if let ConnectorRequest::Connect { client_type, watcher, control_handle } = self {
450            Some((client_type, watcher, control_handle))
451        } else {
452            None
453        }
454    }
455
456    /// Name of the method defined in FIDL
457    pub fn method_name(&self) -> &'static str {
458        match *self {
459            ConnectorRequest::Connect { .. } => "connect",
460        }
461    }
462}
463
464#[derive(Debug, Clone)]
465pub struct ConnectorControlHandle {
466    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
467}
468
469impl fidl::endpoints::ControlHandle for ConnectorControlHandle {
470    fn shutdown(&self) {
471        self.inner.shutdown()
472    }
473    fn shutdown_with_epitaph(&self, status: zx_status::Status) {
474        self.inner.shutdown_with_epitaph(status)
475    }
476
477    fn is_closed(&self) -> bool {
478        self.inner.channel().is_closed()
479    }
480    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
481        self.inner.channel().on_closed()
482    }
483
484    #[cfg(target_os = "fuchsia")]
485    fn signal_peer(
486        &self,
487        clear_mask: zx::Signals,
488        set_mask: zx::Signals,
489    ) -> Result<(), zx_status::Status> {
490        use fidl::Peered;
491        self.inner.channel().signal_peer(clear_mask, set_mask)
492    }
493}
494
495impl ConnectorControlHandle {}
496
497#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
498pub struct WatcherMarker;
499
500impl fidl::endpoints::ProtocolMarker for WatcherMarker {
501    type Proxy = WatcherProxy;
502    type RequestStream = WatcherRequestStream;
503    #[cfg(target_os = "fuchsia")]
504    type SynchronousProxy = WatcherSynchronousProxy;
505
506    const DEBUG_NAME: &'static str = "(anonymous) Watcher";
507}
508
509pub trait WatcherProxyInterface: Send + Sync {
510    type WatchResponseFut: std::future::Future<Output = Result<u64, fidl::Error>> + Send;
511    fn r#watch(&self) -> Self::WatchResponseFut;
512}
513#[derive(Debug)]
514#[cfg(target_os = "fuchsia")]
515pub struct WatcherSynchronousProxy {
516    client: fidl::client::sync::Client,
517}
518
519#[cfg(target_os = "fuchsia")]
520impl fidl::endpoints::SynchronousProxy for WatcherSynchronousProxy {
521    type Proxy = WatcherProxy;
522    type Protocol = WatcherMarker;
523
524    fn from_channel(inner: fidl::Channel) -> Self {
525        Self::new(inner)
526    }
527
528    fn into_channel(self) -> fidl::Channel {
529        self.client.into_channel()
530    }
531
532    fn as_channel(&self) -> &fidl::Channel {
533        self.client.as_channel()
534    }
535}
536
537#[cfg(target_os = "fuchsia")]
538impl WatcherSynchronousProxy {
539    pub fn new(channel: fidl::Channel) -> Self {
540        let protocol_name = <WatcherMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
541        Self { client: fidl::client::sync::Client::new(channel, protocol_name) }
542    }
543
544    pub fn into_channel(self) -> fidl::Channel {
545        self.client.into_channel()
546    }
547
548    /// Waits until an event arrives and returns it. It is safe for other
549    /// threads to make concurrent requests while waiting for an event.
550    pub fn wait_for_event(
551        &self,
552        deadline: zx::MonotonicInstant,
553    ) -> Result<WatcherEvent, fidl::Error> {
554        WatcherEvent::decode(self.client.wait_for_event(deadline)?)
555    }
556
557    /// Watches for changes to the power level of the connected [`ClientType`].
558    ///
559    /// The power level for a given [`ClientType`] is determined according to
560    /// the power configuration for that [`ClientType`]. See the
561    /// [README.md](/src/power/power-manager/system_power_mode_config/README.md)
562    /// for more details.
563    ///
564    /// On a given connection, the first call will return immediately with the
565    /// current power level for the connected [`ClientType`]. Subsequent `Watch`
566    /// requests will only return a new `level` if the power level of the
567    /// connected [`ClientType`] has changed. This follows the [hanging
568    /// get](https://fuchsia.dev/fuchsia-src/concepts/api/fidl#hanging-get)
569    /// pattern.
570    ///
571    /// - `level` is an unsigned integer representing the power level of the
572    /// connected [`ClientType`].
573    pub fn r#watch(&self, ___deadline: zx::MonotonicInstant) -> Result<u64, fidl::Error> {
574        let _response =
575            self.client.send_query::<fidl::encoding::EmptyPayload, WatcherWatchResponse>(
576                (),
577                0x29592d2e62f4101a,
578                fidl::encoding::DynamicFlags::empty(),
579                ___deadline,
580            )?;
581        Ok(_response.level)
582    }
583}
584
585#[derive(Debug, Clone)]
586pub struct WatcherProxy {
587    client: fidl::client::Client<fidl::encoding::DefaultFuchsiaResourceDialect>,
588}
589
590impl fidl::endpoints::Proxy for WatcherProxy {
591    type Protocol = WatcherMarker;
592
593    fn from_channel(inner: ::fidl::AsyncChannel) -> Self {
594        Self::new(inner)
595    }
596
597    fn into_channel(self) -> Result<::fidl::AsyncChannel, Self> {
598        self.client.into_channel().map_err(|client| Self { client })
599    }
600
601    fn as_channel(&self) -> &::fidl::AsyncChannel {
602        self.client.as_channel()
603    }
604}
605
606impl WatcherProxy {
607    /// Create a new Proxy for fuchsia.power.clientlevel/Watcher.
608    pub fn new(channel: ::fidl::AsyncChannel) -> Self {
609        let protocol_name = <WatcherMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
610        Self { client: fidl::client::Client::new(channel, protocol_name) }
611    }
612
613    /// Get a Stream of events from the remote end of the protocol.
614    ///
615    /// # Panics
616    ///
617    /// Panics if the event stream was already taken.
618    pub fn take_event_stream(&self) -> WatcherEventStream {
619        WatcherEventStream { event_receiver: self.client.take_event_receiver() }
620    }
621
622    /// Watches for changes to the power level of the connected [`ClientType`].
623    ///
624    /// The power level for a given [`ClientType`] is determined according to
625    /// the power configuration for that [`ClientType`]. See the
626    /// [README.md](/src/power/power-manager/system_power_mode_config/README.md)
627    /// for more details.
628    ///
629    /// On a given connection, the first call will return immediately with the
630    /// current power level for the connected [`ClientType`]. Subsequent `Watch`
631    /// requests will only return a new `level` if the power level of the
632    /// connected [`ClientType`] has changed. This follows the [hanging
633    /// get](https://fuchsia.dev/fuchsia-src/concepts/api/fidl#hanging-get)
634    /// pattern.
635    ///
636    /// - `level` is an unsigned integer representing the power level of the
637    /// connected [`ClientType`].
638    pub fn r#watch(
639        &self,
640    ) -> fidl::client::QueryResponseFut<u64, fidl::encoding::DefaultFuchsiaResourceDialect> {
641        WatcherProxyInterface::r#watch(self)
642    }
643}
644
645impl WatcherProxyInterface for WatcherProxy {
646    type WatchResponseFut =
647        fidl::client::QueryResponseFut<u64, fidl::encoding::DefaultFuchsiaResourceDialect>;
648    fn r#watch(&self) -> Self::WatchResponseFut {
649        fn _decode(
650            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
651        ) -> Result<u64, fidl::Error> {
652            let _response = fidl::client::decode_transaction_body::<
653                WatcherWatchResponse,
654                fidl::encoding::DefaultFuchsiaResourceDialect,
655                0x29592d2e62f4101a,
656            >(_buf?)?;
657            Ok(_response.level)
658        }
659        self.client.send_query_and_decode::<fidl::encoding::EmptyPayload, u64>(
660            (),
661            0x29592d2e62f4101a,
662            fidl::encoding::DynamicFlags::empty(),
663            _decode,
664        )
665    }
666}
667
668pub struct WatcherEventStream {
669    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
670}
671
672impl std::marker::Unpin for WatcherEventStream {}
673
674impl futures::stream::FusedStream for WatcherEventStream {
675    fn is_terminated(&self) -> bool {
676        self.event_receiver.is_terminated()
677    }
678}
679
680impl futures::Stream for WatcherEventStream {
681    type Item = Result<WatcherEvent, fidl::Error>;
682
683    fn poll_next(
684        mut self: std::pin::Pin<&mut Self>,
685        cx: &mut std::task::Context<'_>,
686    ) -> std::task::Poll<Option<Self::Item>> {
687        match futures::ready!(futures::stream::StreamExt::poll_next_unpin(
688            &mut self.event_receiver,
689            cx
690        )?) {
691            Some(buf) => std::task::Poll::Ready(Some(WatcherEvent::decode(buf))),
692            None => std::task::Poll::Ready(None),
693        }
694    }
695}
696
697#[derive(Debug)]
698pub enum WatcherEvent {}
699
700impl WatcherEvent {
701    /// Decodes a message buffer as a [`WatcherEvent`].
702    fn decode(
703        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
704    ) -> Result<WatcherEvent, fidl::Error> {
705        let (bytes, _handles) = buf.split_mut();
706        let (tx_header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
707        debug_assert_eq!(tx_header.tx_id, 0);
708        match tx_header.ordinal {
709            _ => Err(fidl::Error::UnknownOrdinal {
710                ordinal: tx_header.ordinal,
711                protocol_name: <WatcherMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
712            }),
713        }
714    }
715}
716
717/// A Stream of incoming requests for fuchsia.power.clientlevel/Watcher.
718pub struct WatcherRequestStream {
719    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
720    is_terminated: bool,
721}
722
723impl std::marker::Unpin for WatcherRequestStream {}
724
725impl futures::stream::FusedStream for WatcherRequestStream {
726    fn is_terminated(&self) -> bool {
727        self.is_terminated
728    }
729}
730
731impl fidl::endpoints::RequestStream for WatcherRequestStream {
732    type Protocol = WatcherMarker;
733    type ControlHandle = WatcherControlHandle;
734
735    fn from_channel(channel: ::fidl::AsyncChannel) -> Self {
736        Self { inner: std::sync::Arc::new(fidl::ServeInner::new(channel)), is_terminated: false }
737    }
738
739    fn control_handle(&self) -> Self::ControlHandle {
740        WatcherControlHandle { inner: self.inner.clone() }
741    }
742
743    fn into_inner(
744        self,
745    ) -> (::std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>, bool)
746    {
747        (self.inner, self.is_terminated)
748    }
749
750    fn from_inner(
751        inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
752        is_terminated: bool,
753    ) -> Self {
754        Self { inner, is_terminated }
755    }
756}
757
758impl futures::Stream for WatcherRequestStream {
759    type Item = Result<WatcherRequest, fidl::Error>;
760
761    fn poll_next(
762        mut self: std::pin::Pin<&mut Self>,
763        cx: &mut std::task::Context<'_>,
764    ) -> std::task::Poll<Option<Self::Item>> {
765        let this = &mut *self;
766        if this.inner.check_shutdown(cx) {
767            this.is_terminated = true;
768            return std::task::Poll::Ready(None);
769        }
770        if this.is_terminated {
771            panic!("polled WatcherRequestStream after completion");
772        }
773        fidl::encoding::with_tls_decode_buf::<_, fidl::encoding::DefaultFuchsiaResourceDialect>(
774            |bytes, handles| {
775                match this.inner.channel().read_etc(cx, bytes, handles) {
776                    std::task::Poll::Ready(Ok(())) => {}
777                    std::task::Poll::Pending => return std::task::Poll::Pending,
778                    std::task::Poll::Ready(Err(zx_status::Status::PEER_CLOSED)) => {
779                        this.is_terminated = true;
780                        return std::task::Poll::Ready(None);
781                    }
782                    std::task::Poll::Ready(Err(e)) => {
783                        return std::task::Poll::Ready(Some(Err(fidl::Error::ServerRequestRead(
784                            e.into(),
785                        ))))
786                    }
787                }
788
789                // A message has been received from the channel
790                let (header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
791
792                std::task::Poll::Ready(Some(match header.ordinal {
793                    0x29592d2e62f4101a => {
794                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
795                        let mut req = fidl::new_empty!(
796                            fidl::encoding::EmptyPayload,
797                            fidl::encoding::DefaultFuchsiaResourceDialect
798                        );
799                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<fidl::encoding::EmptyPayload>(&header, _body_bytes, handles, &mut req)?;
800                        let control_handle = WatcherControlHandle { inner: this.inner.clone() };
801                        Ok(WatcherRequest::Watch {
802                            responder: WatcherWatchResponder {
803                                control_handle: std::mem::ManuallyDrop::new(control_handle),
804                                tx_id: header.tx_id,
805                            },
806                        })
807                    }
808                    _ => Err(fidl::Error::UnknownOrdinal {
809                        ordinal: header.ordinal,
810                        protocol_name:
811                            <WatcherMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
812                    }),
813                }))
814            },
815        )
816    }
817}
818
819/// Allows a client to watch for changes to the power level of a given
820/// [`ClientType`].
821///
822/// This protocol cannot be connected to the service directly. Instead, the
823/// server endpoint of a `Watcher` channel must first be connected to the power
824/// level of the desired [`ClientType`] using the [`Connector.Connect`] method.
825/// The client endpoint of a `Watcher` channel is only useful after it has been
826/// connected in this way.
827#[derive(Debug)]
828pub enum WatcherRequest {
829    /// Watches for changes to the power level of the connected [`ClientType`].
830    ///
831    /// The power level for a given [`ClientType`] is determined according to
832    /// the power configuration for that [`ClientType`]. See the
833    /// [README.md](/src/power/power-manager/system_power_mode_config/README.md)
834    /// for more details.
835    ///
836    /// On a given connection, the first call will return immediately with the
837    /// current power level for the connected [`ClientType`]. Subsequent `Watch`
838    /// requests will only return a new `level` if the power level of the
839    /// connected [`ClientType`] has changed. This follows the [hanging
840    /// get](https://fuchsia.dev/fuchsia-src/concepts/api/fidl#hanging-get)
841    /// pattern.
842    ///
843    /// - `level` is an unsigned integer representing the power level of the
844    /// connected [`ClientType`].
845    Watch { responder: WatcherWatchResponder },
846}
847
848impl WatcherRequest {
849    #[allow(irrefutable_let_patterns)]
850    pub fn into_watch(self) -> Option<(WatcherWatchResponder)> {
851        if let WatcherRequest::Watch { responder } = self {
852            Some((responder))
853        } else {
854            None
855        }
856    }
857
858    /// Name of the method defined in FIDL
859    pub fn method_name(&self) -> &'static str {
860        match *self {
861            WatcherRequest::Watch { .. } => "watch",
862        }
863    }
864}
865
866#[derive(Debug, Clone)]
867pub struct WatcherControlHandle {
868    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
869}
870
871impl fidl::endpoints::ControlHandle for WatcherControlHandle {
872    fn shutdown(&self) {
873        self.inner.shutdown()
874    }
875    fn shutdown_with_epitaph(&self, status: zx_status::Status) {
876        self.inner.shutdown_with_epitaph(status)
877    }
878
879    fn is_closed(&self) -> bool {
880        self.inner.channel().is_closed()
881    }
882    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
883        self.inner.channel().on_closed()
884    }
885
886    #[cfg(target_os = "fuchsia")]
887    fn signal_peer(
888        &self,
889        clear_mask: zx::Signals,
890        set_mask: zx::Signals,
891    ) -> Result<(), zx_status::Status> {
892        use fidl::Peered;
893        self.inner.channel().signal_peer(clear_mask, set_mask)
894    }
895}
896
897impl WatcherControlHandle {}
898
899#[must_use = "FIDL methods require a response to be sent"]
900#[derive(Debug)]
901pub struct WatcherWatchResponder {
902    control_handle: std::mem::ManuallyDrop<WatcherControlHandle>,
903    tx_id: u32,
904}
905
906/// Set the the channel to be shutdown (see [`WatcherControlHandle::shutdown`])
907/// if the responder is dropped without sending a response, so that the client
908/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
909impl std::ops::Drop for WatcherWatchResponder {
910    fn drop(&mut self) {
911        self.control_handle.shutdown();
912        // Safety: drops once, never accessed again
913        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
914    }
915}
916
917impl fidl::endpoints::Responder for WatcherWatchResponder {
918    type ControlHandle = WatcherControlHandle;
919
920    fn control_handle(&self) -> &WatcherControlHandle {
921        &self.control_handle
922    }
923
924    fn drop_without_shutdown(mut self) {
925        // Safety: drops once, never accessed again due to mem::forget
926        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
927        // Prevent Drop from running (which would shut down the channel)
928        std::mem::forget(self);
929    }
930}
931
932impl WatcherWatchResponder {
933    /// Sends a response to the FIDL transaction.
934    ///
935    /// Sets the channel to shutdown if an error occurs.
936    pub fn send(self, mut level: u64) -> Result<(), fidl::Error> {
937        let _result = self.send_raw(level);
938        if _result.is_err() {
939            self.control_handle.shutdown();
940        }
941        self.drop_without_shutdown();
942        _result
943    }
944
945    /// Similar to "send" but does not shutdown the channel if an error occurs.
946    pub fn send_no_shutdown_on_err(self, mut level: u64) -> Result<(), fidl::Error> {
947        let _result = self.send_raw(level);
948        self.drop_without_shutdown();
949        _result
950    }
951
952    fn send_raw(&self, mut level: u64) -> Result<(), fidl::Error> {
953        self.control_handle.inner.send::<WatcherWatchResponse>(
954            (level,),
955            self.tx_id,
956            0x29592d2e62f4101a,
957            fidl::encoding::DynamicFlags::empty(),
958        )
959    }
960}
961
962mod internal {
963    use super::*;
964    unsafe impl fidl::encoding::TypeMarker for ClientType {
965        type Owned = Self;
966
967        #[inline(always)]
968        fn inline_align(_context: fidl::encoding::Context) -> usize {
969            std::mem::align_of::<u32>()
970        }
971
972        #[inline(always)]
973        fn inline_size(_context: fidl::encoding::Context) -> usize {
974            std::mem::size_of::<u32>()
975        }
976
977        #[inline(always)]
978        fn encode_is_copy() -> bool {
979            false
980        }
981
982        #[inline(always)]
983        fn decode_is_copy() -> bool {
984            false
985        }
986    }
987
988    impl fidl::encoding::ValueTypeMarker for ClientType {
989        type Borrowed<'a> = Self;
990        #[inline(always)]
991        fn borrow(value: &<Self as fidl::encoding::TypeMarker>::Owned) -> Self::Borrowed<'_> {
992            *value
993        }
994    }
995
996    unsafe impl<D: fidl::encoding::ResourceDialect> fidl::encoding::Encode<Self, D> for ClientType {
997        #[inline]
998        unsafe fn encode(
999            self,
1000            encoder: &mut fidl::encoding::Encoder<'_, D>,
1001            offset: usize,
1002            _depth: fidl::encoding::Depth,
1003        ) -> fidl::Result<()> {
1004            encoder.debug_check_bounds::<Self>(offset);
1005            encoder.write_num(self.into_primitive(), offset);
1006            Ok(())
1007        }
1008    }
1009
1010    impl<D: fidl::encoding::ResourceDialect> fidl::encoding::Decode<Self, D> for ClientType {
1011        #[inline(always)]
1012        fn new_empty() -> Self {
1013            Self::unknown()
1014        }
1015
1016        #[inline]
1017        unsafe fn decode(
1018            &mut self,
1019            decoder: &mut fidl::encoding::Decoder<'_, D>,
1020            offset: usize,
1021            _depth: fidl::encoding::Depth,
1022        ) -> fidl::Result<()> {
1023            decoder.debug_check_bounds::<Self>(offset);
1024            let prim = decoder.read_num::<u32>(offset);
1025
1026            *self = Self::from_primitive_allow_unknown(prim);
1027            Ok(())
1028        }
1029    }
1030
1031    impl fidl::encoding::ResourceTypeMarker for ConnectorConnectRequest {
1032        type Borrowed<'a> = &'a mut Self;
1033        fn take_or_borrow<'a>(
1034            value: &'a mut <Self as fidl::encoding::TypeMarker>::Owned,
1035        ) -> Self::Borrowed<'a> {
1036            value
1037        }
1038    }
1039
1040    unsafe impl fidl::encoding::TypeMarker for ConnectorConnectRequest {
1041        type Owned = Self;
1042
1043        #[inline(always)]
1044        fn inline_align(_context: fidl::encoding::Context) -> usize {
1045            4
1046        }
1047
1048        #[inline(always)]
1049        fn inline_size(_context: fidl::encoding::Context) -> usize {
1050            8
1051        }
1052    }
1053
1054    unsafe impl
1055        fidl::encoding::Encode<
1056            ConnectorConnectRequest,
1057            fidl::encoding::DefaultFuchsiaResourceDialect,
1058        > for &mut ConnectorConnectRequest
1059    {
1060        #[inline]
1061        unsafe fn encode(
1062            self,
1063            encoder: &mut fidl::encoding::Encoder<
1064                '_,
1065                fidl::encoding::DefaultFuchsiaResourceDialect,
1066            >,
1067            offset: usize,
1068            _depth: fidl::encoding::Depth,
1069        ) -> fidl::Result<()> {
1070            encoder.debug_check_bounds::<ConnectorConnectRequest>(offset);
1071            // Delegate to tuple encoding.
1072            fidl::encoding::Encode::<ConnectorConnectRequest, fidl::encoding::DefaultFuchsiaResourceDialect>::encode(
1073                (
1074                    <ClientType as fidl::encoding::ValueTypeMarker>::borrow(&self.client_type),
1075                    <fidl::encoding::Endpoint<fidl::endpoints::ServerEnd<WatcherMarker>> as fidl::encoding::ResourceTypeMarker>::take_or_borrow(&mut self.watcher),
1076                ),
1077                encoder, offset, _depth
1078            )
1079        }
1080    }
1081    unsafe impl<
1082            T0: fidl::encoding::Encode<ClientType, fidl::encoding::DefaultFuchsiaResourceDialect>,
1083            T1: fidl::encoding::Encode<
1084                fidl::encoding::Endpoint<fidl::endpoints::ServerEnd<WatcherMarker>>,
1085                fidl::encoding::DefaultFuchsiaResourceDialect,
1086            >,
1087        >
1088        fidl::encoding::Encode<
1089            ConnectorConnectRequest,
1090            fidl::encoding::DefaultFuchsiaResourceDialect,
1091        > for (T0, T1)
1092    {
1093        #[inline]
1094        unsafe fn encode(
1095            self,
1096            encoder: &mut fidl::encoding::Encoder<
1097                '_,
1098                fidl::encoding::DefaultFuchsiaResourceDialect,
1099            >,
1100            offset: usize,
1101            depth: fidl::encoding::Depth,
1102        ) -> fidl::Result<()> {
1103            encoder.debug_check_bounds::<ConnectorConnectRequest>(offset);
1104            // Zero out padding regions. There's no need to apply masks
1105            // because the unmasked parts will be overwritten by fields.
1106            // Write the fields.
1107            self.0.encode(encoder, offset + 0, depth)?;
1108            self.1.encode(encoder, offset + 4, depth)?;
1109            Ok(())
1110        }
1111    }
1112
1113    impl fidl::encoding::Decode<Self, fidl::encoding::DefaultFuchsiaResourceDialect>
1114        for ConnectorConnectRequest
1115    {
1116        #[inline(always)]
1117        fn new_empty() -> Self {
1118            Self {
1119                client_type: fidl::new_empty!(
1120                    ClientType,
1121                    fidl::encoding::DefaultFuchsiaResourceDialect
1122                ),
1123                watcher: fidl::new_empty!(
1124                    fidl::encoding::Endpoint<fidl::endpoints::ServerEnd<WatcherMarker>>,
1125                    fidl::encoding::DefaultFuchsiaResourceDialect
1126                ),
1127            }
1128        }
1129
1130        #[inline]
1131        unsafe fn decode(
1132            &mut self,
1133            decoder: &mut fidl::encoding::Decoder<
1134                '_,
1135                fidl::encoding::DefaultFuchsiaResourceDialect,
1136            >,
1137            offset: usize,
1138            _depth: fidl::encoding::Depth,
1139        ) -> fidl::Result<()> {
1140            decoder.debug_check_bounds::<Self>(offset);
1141            // Verify that padding bytes are zero.
1142            fidl::decode!(
1143                ClientType,
1144                fidl::encoding::DefaultFuchsiaResourceDialect,
1145                &mut self.client_type,
1146                decoder,
1147                offset + 0,
1148                _depth
1149            )?;
1150            fidl::decode!(
1151                fidl::encoding::Endpoint<fidl::endpoints::ServerEnd<WatcherMarker>>,
1152                fidl::encoding::DefaultFuchsiaResourceDialect,
1153                &mut self.watcher,
1154                decoder,
1155                offset + 4,
1156                _depth
1157            )?;
1158            Ok(())
1159        }
1160    }
1161
1162    impl fidl::encoding::ValueTypeMarker for WatcherWatchResponse {
1163        type Borrowed<'a> = &'a Self;
1164        fn borrow(value: &<Self as fidl::encoding::TypeMarker>::Owned) -> Self::Borrowed<'_> {
1165            value
1166        }
1167    }
1168
1169    unsafe impl fidl::encoding::TypeMarker for WatcherWatchResponse {
1170        type Owned = Self;
1171
1172        #[inline(always)]
1173        fn inline_align(_context: fidl::encoding::Context) -> usize {
1174            8
1175        }
1176
1177        #[inline(always)]
1178        fn inline_size(_context: fidl::encoding::Context) -> usize {
1179            8
1180        }
1181        #[inline(always)]
1182        fn encode_is_copy() -> bool {
1183            true
1184        }
1185
1186        #[inline(always)]
1187        fn decode_is_copy() -> bool {
1188            true
1189        }
1190    }
1191
1192    unsafe impl<D: fidl::encoding::ResourceDialect> fidl::encoding::Encode<WatcherWatchResponse, D>
1193        for &WatcherWatchResponse
1194    {
1195        #[inline]
1196        unsafe fn encode(
1197            self,
1198            encoder: &mut fidl::encoding::Encoder<'_, D>,
1199            offset: usize,
1200            _depth: fidl::encoding::Depth,
1201        ) -> fidl::Result<()> {
1202            encoder.debug_check_bounds::<WatcherWatchResponse>(offset);
1203            unsafe {
1204                // Copy the object into the buffer.
1205                let buf_ptr = encoder.buf.as_mut_ptr().add(offset);
1206                (buf_ptr as *mut WatcherWatchResponse)
1207                    .write_unaligned((self as *const WatcherWatchResponse).read());
1208                // Zero out padding regions. Unlike `fidl_struct_impl_noncopy!`, this must be
1209                // done second because the memcpy will write garbage to these bytes.
1210            }
1211            Ok(())
1212        }
1213    }
1214    unsafe impl<D: fidl::encoding::ResourceDialect, T0: fidl::encoding::Encode<u64, D>>
1215        fidl::encoding::Encode<WatcherWatchResponse, D> for (T0,)
1216    {
1217        #[inline]
1218        unsafe fn encode(
1219            self,
1220            encoder: &mut fidl::encoding::Encoder<'_, D>,
1221            offset: usize,
1222            depth: fidl::encoding::Depth,
1223        ) -> fidl::Result<()> {
1224            encoder.debug_check_bounds::<WatcherWatchResponse>(offset);
1225            // Zero out padding regions. There's no need to apply masks
1226            // because the unmasked parts will be overwritten by fields.
1227            // Write the fields.
1228            self.0.encode(encoder, offset + 0, depth)?;
1229            Ok(())
1230        }
1231    }
1232
1233    impl<D: fidl::encoding::ResourceDialect> fidl::encoding::Decode<Self, D> for WatcherWatchResponse {
1234        #[inline(always)]
1235        fn new_empty() -> Self {
1236            Self { level: fidl::new_empty!(u64, D) }
1237        }
1238
1239        #[inline]
1240        unsafe fn decode(
1241            &mut self,
1242            decoder: &mut fidl::encoding::Decoder<'_, D>,
1243            offset: usize,
1244            _depth: fidl::encoding::Depth,
1245        ) -> fidl::Result<()> {
1246            decoder.debug_check_bounds::<Self>(offset);
1247            let buf_ptr = unsafe { decoder.buf.as_ptr().add(offset) };
1248            // Verify that padding bytes are zero.
1249            // Copy from the buffer into the object.
1250            unsafe {
1251                std::ptr::copy_nonoverlapping(buf_ptr, self as *mut Self as *mut u8, 8);
1252            }
1253            Ok(())
1254        }
1255    }
1256}