Skip to main content

fidl_fuchsia_hardware_power_battery/
fidl_fuchsia_hardware_power_battery.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_hardware_power_battery_common::*;
11use futures::future::{self, MaybeDone, TryFutureExt};
12use zx_status;
13
14#[derive(Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
15pub struct BatteryWatchRequest {
16    pub lease: Option<fidl::EventPair>,
17}
18
19impl fidl::Standalone<fidl::encoding::DefaultFuchsiaResourceDialect> for BatteryWatchRequest {}
20
21#[derive(Debug, PartialEq)]
22pub struct BatteryWatchResponse {
23    pub status: Status,
24    pub wake_lease: Option<fidl::EventPair>,
25}
26
27impl fidl::Standalone<fidl::encoding::DefaultFuchsiaResourceDialect> for BatteryWatchResponse {}
28
29#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
30pub struct BatteryMarker;
31
32impl fidl::endpoints::ProtocolMarker for BatteryMarker {
33    type Proxy = BatteryProxy;
34    type RequestStream = BatteryRequestStream;
35    #[cfg(target_os = "fuchsia")]
36    type SynchronousProxy = BatterySynchronousProxy;
37
38    const DEBUG_NAME: &'static str = "fuchsia.hardware.power.battery.Battery";
39}
40impl fidl::endpoints::DiscoverableProtocolMarker for BatteryMarker {}
41pub type BatteryGetSpecResult = Result<Spec, Error>;
42pub type BatteryGetStatusResult = Result<Status, Error>;
43pub type BatteryConfigureWatchResult = Result<WatchOptions, Error>;
44pub type BatteryWatchResult = Result<(Status, Option<fidl::EventPair>), Error>;
45
46pub trait BatteryProxyInterface: Send + Sync {
47    type GetSpecResponseFut: std::future::Future<Output = Result<BatteryGetSpecResult, fidl::Error>>
48        + Send;
49    fn r#get_spec(&self) -> Self::GetSpecResponseFut;
50    type GetStatusResponseFut: std::future::Future<Output = Result<BatteryGetStatusResult, fidl::Error>>
51        + Send;
52    fn r#get_status(&self) -> Self::GetStatusResponseFut;
53    type ConfigureWatchResponseFut: std::future::Future<Output = Result<BatteryConfigureWatchResult, fidl::Error>>
54        + Send;
55    fn r#configure_watch(&self, options: &WatchOptions) -> Self::ConfigureWatchResponseFut;
56    type WatchResponseFut: std::future::Future<Output = Result<BatteryWatchResult, fidl::Error>>
57        + Send;
58    fn r#watch(&self, lease: Option<fidl::EventPair>) -> Self::WatchResponseFut;
59}
60#[derive(Debug)]
61#[cfg(target_os = "fuchsia")]
62pub struct BatterySynchronousProxy {
63    client: fidl::client::sync::Client,
64}
65
66#[cfg(target_os = "fuchsia")]
67impl fidl::endpoints::SynchronousProxy for BatterySynchronousProxy {
68    type Proxy = BatteryProxy;
69    type Protocol = BatteryMarker;
70
71    fn from_channel(inner: fidl::Channel) -> Self {
72        Self::new(inner)
73    }
74
75    fn into_channel(self) -> fidl::Channel {
76        self.client.into_channel()
77    }
78
79    fn as_channel(&self) -> &fidl::Channel {
80        self.client.as_channel()
81    }
82}
83
84#[cfg(target_os = "fuchsia")]
85impl BatterySynchronousProxy {
86    pub fn new(channel: fidl::Channel) -> Self {
87        Self { client: fidl::client::sync::Client::new(channel) }
88    }
89
90    pub fn into_channel(self) -> fidl::Channel {
91        self.client.into_channel()
92    }
93
94    /// Waits until an event arrives and returns it. It is safe for other
95    /// threads to make concurrent requests while waiting for an event.
96    pub fn wait_for_event(
97        &self,
98        deadline: zx::MonotonicInstant,
99    ) -> Result<BatteryEvent, fidl::Error> {
100        BatteryEvent::decode(self.client.wait_for_event::<BatteryMarker>(deadline)?)
101    }
102
103    /// Retrieves the static specification of the battery.
104    ///
105    /// Returns:
106    /// + `spec`: Static hardware characteristics and driver capabilities of the battery.
107    ///
108    /// Errors:
109    /// - `NOT_SUPPORTED`: Hardware does not supply a static specification.
110    /// - `IO`: Communication failure with the fuel gauge hardware (e.g. I2C transfer failure).
111    /// - `INTERNAL`: Internal driver error.
112    pub fn r#get_spec(
113        &self,
114        ___deadline: zx::MonotonicInstant,
115    ) -> Result<BatteryGetSpecResult, fidl::Error> {
116        let _response = self.client.send_query::<
117            fidl::encoding::EmptyPayload,
118            fidl::encoding::FlexibleResultType<BatteryGetSpecResponse, Error>,
119            BatteryMarker,
120        >(
121            (),
122            0x235609229653654f,
123            fidl::encoding::DynamicFlags::FLEXIBLE,
124            ___deadline,
125        )?
126        .into_result::<BatteryMarker>("get_spec")?;
127        Ok(_response.map(|x| x.spec))
128    }
129
130    /// Retrieves an instantaneous snapshot of the battery status.
131    ///
132    /// Returns:
133    /// + `status`: Complete current telemetry snapshot of battery metrics.
134    ///
135    /// Errors:
136    /// - `IO`: Communication failure with the fuel gauge hardware (e.g. I2C transfer failure).
137    /// - `INTERNAL`: Internal driver error.
138    pub fn r#get_status(
139        &self,
140        ___deadline: zx::MonotonicInstant,
141    ) -> Result<BatteryGetStatusResult, fidl::Error> {
142        let _response = self.client.send_query::<
143            fidl::encoding::EmptyPayload,
144            fidl::encoding::FlexibleResultType<BatteryGetStatusResponse, Error>,
145            BatteryMarker,
146        >(
147            (),
148            0x2e0c03524d47095a,
149            fidl::encoding::DynamicFlags::FLEXIBLE,
150            ___deadline,
151        )?
152        .into_result::<BatteryMarker>("get_status")?;
153        Ok(_response.map(|x| x.status))
154    }
155
156    /// Configures the fields of interest and wake triggers for this client connection.
157    ///
158    /// The driver filters the requested masks against hardware capabilities and returns the
159    /// effective configuration in `effective_options`.
160    ///
161    /// - **Partially supported options**: If some requested fields are supported and others are not
162    ///   (e.g., requesting passive fields like `voltage_uv` or `current_ua` that do not support
163    ///   active interrupt notifications), the driver enables the supported fields and returns the
164    ///   active subset in `effective_options`. The call succeeds (`Ok`).
165    /// - **Fully unsupported options**: If non-empty masks were specified but NONE of the requested
166    ///   fields are supported, the driver returns `NOT_SUPPORTED`.
167    ///
168    /// If `ConfigureWatch` is never called, `Watch` defaults to returning on ANY supported field
169    /// change. The driver aggregates constraints across all clients to determine hardware reporting
170    /// rates.
171    ///
172    /// `ConfigureWatch` may be called at any time, including while a `Watch` is pending. The new
173    /// masks take effect immediately and apply to that pending call. Change detection continues to
174    /// compare against the status last delivered on this connection, so a field that changed
175    /// before the reconfiguration can still resolve the pending `Watch`.
176    ///
177    /// Parameters:
178    /// + `options`: Requested watch options. Both `interest` and `wake_on` are optional.
179    ///
180    /// Returns:
181    /// + `effective_options`: The subset of requested options supported and enabled by the driver.
182    ///
183    /// Errors:
184    /// - `NOT_SUPPORTED`: Non-empty options were requested, but none of the requested interest/wake
185    ///   fields or periodic sampling are supported by the driver.
186    ///
187    /// On error the connection's configuration is left unchanged; a failed call never partially
188    /// applies.
189    pub fn r#configure_watch(
190        &self,
191        mut options: &WatchOptions,
192        ___deadline: zx::MonotonicInstant,
193    ) -> Result<BatteryConfigureWatchResult, fidl::Error> {
194        let _response = self.client.send_query::<
195            BatteryConfigureWatchRequest,
196            fidl::encoding::FlexibleResultType<BatteryConfigureWatchResponse, Error>,
197            BatteryMarker,
198        >(
199            (options,),
200            0x71fc28fbfc1f88c7,
201            fidl::encoding::DynamicFlags::FLEXIBLE,
202            ___deadline,
203        )?
204        .into_result::<BatteryMarker>("configure_watch")?;
205        Ok(_response.map(|x| x.effective_options))
206    }
207
208    /// Change notification for battery state using a hanging-get pattern.
209    ///
210    /// The first call returns the full current hardware state immediately. Subsequent calls block
211    /// until a state change matches the masks in [`ConfigureWatch`] or the interval in
212    /// `max_interval` has elapsed. Each return contains a complete telemetry snapshot of all
213    /// current battery fields, not a sparse delta.
214    ///
215    /// At most one `Watch` call may be outstanding per connection; concurrent calls fail with
216    /// `ALREADY_WATCHING`.
217    ///
218    /// Parameters:
219    /// + `lease`: An optional power lease token that keeps the system awake while the server
220    ///   processes the call. If the call is answered immediately, as the first call always is, the
221    ///   server hands it back as `wake_lease` unless it returns a wake lease of its own. If the
222    ///   call is parked, the server drops it.
223    ///
224    /// Returns:
225    /// + `status`: Complete current telemetry snapshot of the battery.
226    /// + `wake_lease`: An optional lease token that the client should hold while it handles
227    ///   `status`: the client's `lease` handed back on an immediate reply, or a wake lease provided
228    ///   if the change triggered a `wake_on` condition or a `max_interval` sample woke the system
229    ///   for a client that set `wake_on_max_interval`. Omitted otherwise.
230    ///
231    /// Errors:
232    /// - `ALREADY_WATCHING`: A `Watch` call is already pending on this connection.
233    /// - `IO`: Communication failure with the fuel gauge hardware (e.g. I2C transfer failure).
234    /// - `INTERNAL`: Internal driver error.
235    pub fn r#watch(
236        &self,
237        mut lease: Option<fidl::EventPair>,
238        ___deadline: zx::MonotonicInstant,
239    ) -> Result<BatteryWatchResult, fidl::Error> {
240        let _response = self.client.send_query::<
241            BatteryWatchRequest,
242            fidl::encoding::FlexibleResultType<BatteryWatchResponse, Error>,
243            BatteryMarker,
244        >(
245            (lease,),
246            0x7386830cdd9e3390,
247            fidl::encoding::DynamicFlags::FLEXIBLE,
248            ___deadline,
249        )?
250        .into_result::<BatteryMarker>("watch")?;
251        Ok(_response.map(|x| (x.status, x.wake_lease)))
252    }
253}
254
255#[cfg(target_os = "fuchsia")]
256impl From<BatterySynchronousProxy> for zx::NullableHandle {
257    fn from(value: BatterySynchronousProxy) -> Self {
258        value.into_channel().into()
259    }
260}
261
262#[cfg(target_os = "fuchsia")]
263impl From<fidl::Channel> for BatterySynchronousProxy {
264    fn from(value: fidl::Channel) -> Self {
265        Self::new(value)
266    }
267}
268
269#[cfg(target_os = "fuchsia")]
270impl fidl::endpoints::FromClient for BatterySynchronousProxy {
271    type Protocol = BatteryMarker;
272
273    fn from_client(value: fidl::endpoints::ClientEnd<BatteryMarker>) -> Self {
274        Self::new(value.into_channel())
275    }
276}
277
278#[derive(Debug, Clone)]
279pub struct BatteryProxy {
280    client: fidl::client::Client<fidl::encoding::DefaultFuchsiaResourceDialect>,
281}
282
283impl fidl::endpoints::Proxy for BatteryProxy {
284    type Protocol = BatteryMarker;
285
286    fn from_channel(inner: ::fidl::AsyncChannel) -> Self {
287        Self::new(inner)
288    }
289
290    fn into_channel(self) -> Result<::fidl::AsyncChannel, Self> {
291        self.client.into_channel().map_err(|client| Self { client })
292    }
293
294    fn as_channel(&self) -> &::fidl::AsyncChannel {
295        self.client.as_channel()
296    }
297}
298
299impl BatteryProxy {
300    /// Create a new Proxy for fuchsia.hardware.power.battery/Battery.
301    pub fn new(channel: ::fidl::AsyncChannel) -> Self {
302        let protocol_name = <BatteryMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME;
303        Self { client: fidl::client::Client::new(channel, protocol_name) }
304    }
305
306    /// Get a Stream of events from the remote end of the protocol.
307    ///
308    /// # Panics
309    ///
310    /// Panics if the event stream was already taken.
311    pub fn take_event_stream(&self) -> BatteryEventStream {
312        BatteryEventStream { event_receiver: self.client.take_event_receiver() }
313    }
314
315    /// Retrieves the static specification of the battery.
316    ///
317    /// Returns:
318    /// + `spec`: Static hardware characteristics and driver capabilities of the battery.
319    ///
320    /// Errors:
321    /// - `NOT_SUPPORTED`: Hardware does not supply a static specification.
322    /// - `IO`: Communication failure with the fuel gauge hardware (e.g. I2C transfer failure).
323    /// - `INTERNAL`: Internal driver error.
324    pub fn r#get_spec(
325        &self,
326    ) -> fidl::client::QueryResponseFut<
327        BatteryGetSpecResult,
328        fidl::encoding::DefaultFuchsiaResourceDialect,
329    > {
330        BatteryProxyInterface::r#get_spec(self)
331    }
332
333    /// Retrieves an instantaneous snapshot of the battery status.
334    ///
335    /// Returns:
336    /// + `status`: Complete current telemetry snapshot of battery metrics.
337    ///
338    /// Errors:
339    /// - `IO`: Communication failure with the fuel gauge hardware (e.g. I2C transfer failure).
340    /// - `INTERNAL`: Internal driver error.
341    pub fn r#get_status(
342        &self,
343    ) -> fidl::client::QueryResponseFut<
344        BatteryGetStatusResult,
345        fidl::encoding::DefaultFuchsiaResourceDialect,
346    > {
347        BatteryProxyInterface::r#get_status(self)
348    }
349
350    /// Configures the fields of interest and wake triggers for this client connection.
351    ///
352    /// The driver filters the requested masks against hardware capabilities and returns the
353    /// effective configuration in `effective_options`.
354    ///
355    /// - **Partially supported options**: If some requested fields are supported and others are not
356    ///   (e.g., requesting passive fields like `voltage_uv` or `current_ua` that do not support
357    ///   active interrupt notifications), the driver enables the supported fields and returns the
358    ///   active subset in `effective_options`. The call succeeds (`Ok`).
359    /// - **Fully unsupported options**: If non-empty masks were specified but NONE of the requested
360    ///   fields are supported, the driver returns `NOT_SUPPORTED`.
361    ///
362    /// If `ConfigureWatch` is never called, `Watch` defaults to returning on ANY supported field
363    /// change. The driver aggregates constraints across all clients to determine hardware reporting
364    /// rates.
365    ///
366    /// `ConfigureWatch` may be called at any time, including while a `Watch` is pending. The new
367    /// masks take effect immediately and apply to that pending call. Change detection continues to
368    /// compare against the status last delivered on this connection, so a field that changed
369    /// before the reconfiguration can still resolve the pending `Watch`.
370    ///
371    /// Parameters:
372    /// + `options`: Requested watch options. Both `interest` and `wake_on` are optional.
373    ///
374    /// Returns:
375    /// + `effective_options`: The subset of requested options supported and enabled by the driver.
376    ///
377    /// Errors:
378    /// - `NOT_SUPPORTED`: Non-empty options were requested, but none of the requested interest/wake
379    ///   fields or periodic sampling are supported by the driver.
380    ///
381    /// On error the connection's configuration is left unchanged; a failed call never partially
382    /// applies.
383    pub fn r#configure_watch(
384        &self,
385        mut options: &WatchOptions,
386    ) -> fidl::client::QueryResponseFut<
387        BatteryConfigureWatchResult,
388        fidl::encoding::DefaultFuchsiaResourceDialect,
389    > {
390        BatteryProxyInterface::r#configure_watch(self, options)
391    }
392
393    /// Change notification for battery state using a hanging-get pattern.
394    ///
395    /// The first call returns the full current hardware state immediately. Subsequent calls block
396    /// until a state change matches the masks in [`ConfigureWatch`] or the interval in
397    /// `max_interval` has elapsed. Each return contains a complete telemetry snapshot of all
398    /// current battery fields, not a sparse delta.
399    ///
400    /// At most one `Watch` call may be outstanding per connection; concurrent calls fail with
401    /// `ALREADY_WATCHING`.
402    ///
403    /// Parameters:
404    /// + `lease`: An optional power lease token that keeps the system awake while the server
405    ///   processes the call. If the call is answered immediately, as the first call always is, the
406    ///   server hands it back as `wake_lease` unless it returns a wake lease of its own. If the
407    ///   call is parked, the server drops it.
408    ///
409    /// Returns:
410    /// + `status`: Complete current telemetry snapshot of the battery.
411    /// + `wake_lease`: An optional lease token that the client should hold while it handles
412    ///   `status`: the client's `lease` handed back on an immediate reply, or a wake lease provided
413    ///   if the change triggered a `wake_on` condition or a `max_interval` sample woke the system
414    ///   for a client that set `wake_on_max_interval`. Omitted otherwise.
415    ///
416    /// Errors:
417    /// - `ALREADY_WATCHING`: A `Watch` call is already pending on this connection.
418    /// - `IO`: Communication failure with the fuel gauge hardware (e.g. I2C transfer failure).
419    /// - `INTERNAL`: Internal driver error.
420    pub fn r#watch(
421        &self,
422        mut lease: Option<fidl::EventPair>,
423    ) -> fidl::client::QueryResponseFut<
424        BatteryWatchResult,
425        fidl::encoding::DefaultFuchsiaResourceDialect,
426    > {
427        BatteryProxyInterface::r#watch(self, lease)
428    }
429}
430
431impl BatteryProxyInterface for BatteryProxy {
432    type GetSpecResponseFut = fidl::client::QueryResponseFut<
433        BatteryGetSpecResult,
434        fidl::encoding::DefaultFuchsiaResourceDialect,
435    >;
436    fn r#get_spec(&self) -> Self::GetSpecResponseFut {
437        fn _decode(
438            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
439        ) -> Result<BatteryGetSpecResult, fidl::Error> {
440            let _response = fidl::client::decode_transaction_body::<
441                fidl::encoding::FlexibleResultType<BatteryGetSpecResponse, Error>,
442                fidl::encoding::DefaultFuchsiaResourceDialect,
443                0x235609229653654f,
444            >(_buf?)?
445            .into_result::<BatteryMarker>("get_spec")?;
446            Ok(_response.map(|x| x.spec))
447        }
448        self.client.send_query_and_decode::<fidl::encoding::EmptyPayload, BatteryGetSpecResult>(
449            (),
450            0x235609229653654f,
451            fidl::encoding::DynamicFlags::FLEXIBLE,
452            _decode,
453        )
454    }
455
456    type GetStatusResponseFut = fidl::client::QueryResponseFut<
457        BatteryGetStatusResult,
458        fidl::encoding::DefaultFuchsiaResourceDialect,
459    >;
460    fn r#get_status(&self) -> Self::GetStatusResponseFut {
461        fn _decode(
462            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
463        ) -> Result<BatteryGetStatusResult, fidl::Error> {
464            let _response = fidl::client::decode_transaction_body::<
465                fidl::encoding::FlexibleResultType<BatteryGetStatusResponse, Error>,
466                fidl::encoding::DefaultFuchsiaResourceDialect,
467                0x2e0c03524d47095a,
468            >(_buf?)?
469            .into_result::<BatteryMarker>("get_status")?;
470            Ok(_response.map(|x| x.status))
471        }
472        self.client.send_query_and_decode::<fidl::encoding::EmptyPayload, BatteryGetStatusResult>(
473            (),
474            0x2e0c03524d47095a,
475            fidl::encoding::DynamicFlags::FLEXIBLE,
476            _decode,
477        )
478    }
479
480    type ConfigureWatchResponseFut = fidl::client::QueryResponseFut<
481        BatteryConfigureWatchResult,
482        fidl::encoding::DefaultFuchsiaResourceDialect,
483    >;
484    fn r#configure_watch(&self, mut options: &WatchOptions) -> Self::ConfigureWatchResponseFut {
485        fn _decode(
486            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
487        ) -> Result<BatteryConfigureWatchResult, fidl::Error> {
488            let _response = fidl::client::decode_transaction_body::<
489                fidl::encoding::FlexibleResultType<BatteryConfigureWatchResponse, Error>,
490                fidl::encoding::DefaultFuchsiaResourceDialect,
491                0x71fc28fbfc1f88c7,
492            >(_buf?)?
493            .into_result::<BatteryMarker>("configure_watch")?;
494            Ok(_response.map(|x| x.effective_options))
495        }
496        self.client
497            .send_query_and_decode::<BatteryConfigureWatchRequest, BatteryConfigureWatchResult>(
498                (options,),
499                0x71fc28fbfc1f88c7,
500                fidl::encoding::DynamicFlags::FLEXIBLE,
501                _decode,
502            )
503    }
504
505    type WatchResponseFut = fidl::client::QueryResponseFut<
506        BatteryWatchResult,
507        fidl::encoding::DefaultFuchsiaResourceDialect,
508    >;
509    fn r#watch(&self, mut lease: Option<fidl::EventPair>) -> Self::WatchResponseFut {
510        fn _decode(
511            mut _buf: Result<<fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc, fidl::Error>,
512        ) -> Result<BatteryWatchResult, fidl::Error> {
513            let _response = fidl::client::decode_transaction_body::<
514                fidl::encoding::FlexibleResultType<BatteryWatchResponse, Error>,
515                fidl::encoding::DefaultFuchsiaResourceDialect,
516                0x7386830cdd9e3390,
517            >(_buf?)?
518            .into_result::<BatteryMarker>("watch")?;
519            Ok(_response.map(|x| (x.status, x.wake_lease)))
520        }
521        self.client.send_query_and_decode::<BatteryWatchRequest, BatteryWatchResult>(
522            (lease,),
523            0x7386830cdd9e3390,
524            fidl::encoding::DynamicFlags::FLEXIBLE,
525            _decode,
526        )
527    }
528}
529
530pub struct BatteryEventStream {
531    event_receiver: fidl::client::EventReceiver<fidl::encoding::DefaultFuchsiaResourceDialect>,
532}
533
534impl std::marker::Unpin for BatteryEventStream {}
535
536impl futures::stream::FusedStream for BatteryEventStream {
537    fn is_terminated(&self) -> bool {
538        self.event_receiver.is_terminated()
539    }
540}
541
542impl futures::Stream for BatteryEventStream {
543    type Item = Result<BatteryEvent, fidl::Error>;
544
545    fn poll_next(
546        mut self: std::pin::Pin<&mut Self>,
547        cx: &mut std::task::Context<'_>,
548    ) -> std::task::Poll<Option<Self::Item>> {
549        match futures::ready!(futures::stream::StreamExt::poll_next_unpin(
550            &mut self.event_receiver,
551            cx
552        )?) {
553            Some(buf) => std::task::Poll::Ready(Some(BatteryEvent::decode(buf))),
554            None => std::task::Poll::Ready(None),
555        }
556    }
557}
558
559#[derive(Debug)]
560pub enum BatteryEvent {
561    #[non_exhaustive]
562    _UnknownEvent {
563        /// Ordinal of the event that was sent.
564        ordinal: u64,
565    },
566}
567
568impl BatteryEvent {
569    /// Decodes a message buffer as a [`BatteryEvent`].
570    fn decode(
571        mut buf: <fidl::encoding::DefaultFuchsiaResourceDialect as fidl::encoding::ResourceDialect>::MessageBufEtc,
572    ) -> Result<BatteryEvent, fidl::Error> {
573        let (bytes, _handles) = buf.split_mut();
574        let (tx_header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
575        debug_assert_eq!(tx_header.tx_id, 0);
576        match tx_header.ordinal {
577            _ if tx_header.dynamic_flags().contains(fidl::encoding::DynamicFlags::FLEXIBLE) => {
578                Ok(BatteryEvent::_UnknownEvent { ordinal: tx_header.ordinal })
579            }
580            _ => Err(fidl::Error::UnknownOrdinal {
581                ordinal: tx_header.ordinal,
582                protocol_name: <BatteryMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
583            }),
584        }
585    }
586}
587
588/// A Stream of incoming requests for fuchsia.hardware.power.battery/Battery.
589pub struct BatteryRequestStream {
590    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
591    is_terminated: bool,
592}
593
594impl std::marker::Unpin for BatteryRequestStream {}
595
596impl futures::stream::FusedStream for BatteryRequestStream {
597    fn is_terminated(&self) -> bool {
598        self.is_terminated
599    }
600}
601
602impl fidl::endpoints::RequestStream for BatteryRequestStream {
603    type Protocol = BatteryMarker;
604    type ControlHandle = BatteryControlHandle;
605
606    fn from_channel(channel: ::fidl::AsyncChannel) -> Self {
607        Self { inner: std::sync::Arc::new(fidl::ServeInner::new(channel)), is_terminated: false }
608    }
609
610    fn control_handle(&self) -> Self::ControlHandle {
611        BatteryControlHandle { inner: self.inner.clone() }
612    }
613
614    fn into_inner(
615        self,
616    ) -> (::std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>, bool)
617    {
618        (self.inner, self.is_terminated)
619    }
620
621    fn from_inner(
622        inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
623        is_terminated: bool,
624    ) -> Self {
625        Self { inner, is_terminated }
626    }
627}
628
629impl futures::Stream for BatteryRequestStream {
630    type Item = Result<BatteryRequest, fidl::Error>;
631
632    fn poll_next(
633        mut self: std::pin::Pin<&mut Self>,
634        cx: &mut std::task::Context<'_>,
635    ) -> std::task::Poll<Option<Self::Item>> {
636        let this = &mut *self;
637        if this.inner.check_shutdown(cx) {
638            this.is_terminated = true;
639            return std::task::Poll::Ready(None);
640        }
641        if this.is_terminated {
642            panic!("polled BatteryRequestStream after completion");
643        }
644        fidl::encoding::with_tls_decode_buf::<_, fidl::encoding::DefaultFuchsiaResourceDialect>(
645            |bytes, handles| {
646                match this.inner.channel().read_etc(cx, bytes, handles) {
647                    std::task::Poll::Ready(Ok(())) => {}
648                    std::task::Poll::Pending => return std::task::Poll::Pending,
649                    std::task::Poll::Ready(Err(zx_status::Status::PEER_CLOSED)) => {
650                        this.is_terminated = true;
651                        return std::task::Poll::Ready(None);
652                    }
653                    std::task::Poll::Ready(Err(e)) => {
654                        return std::task::Poll::Ready(Some(Err(fidl::Error::ServerRequestRead(
655                            e.into(),
656                        ))));
657                    }
658                }
659
660                // A message has been received from the channel
661                let (header, _body_bytes) = fidl::encoding::decode_transaction_header(bytes)?;
662
663                std::task::Poll::Ready(Some(match header.ordinal {
664                    0x235609229653654f => {
665                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
666                        let mut req = fidl::new_empty!(
667                            fidl::encoding::EmptyPayload,
668                            fidl::encoding::DefaultFuchsiaResourceDialect
669                        );
670                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<fidl::encoding::EmptyPayload>(&header, _body_bytes, handles, &mut req)?;
671                        let control_handle = BatteryControlHandle { inner: this.inner.clone() };
672                        Ok(BatteryRequest::GetSpec {
673                            responder: BatteryGetSpecResponder {
674                                control_handle: std::mem::ManuallyDrop::new(control_handle),
675                                tx_id: header.tx_id,
676                            },
677                        })
678                    }
679                    0x2e0c03524d47095a => {
680                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
681                        let mut req = fidl::new_empty!(
682                            fidl::encoding::EmptyPayload,
683                            fidl::encoding::DefaultFuchsiaResourceDialect
684                        );
685                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<fidl::encoding::EmptyPayload>(&header, _body_bytes, handles, &mut req)?;
686                        let control_handle = BatteryControlHandle { inner: this.inner.clone() };
687                        Ok(BatteryRequest::GetStatus {
688                            responder: BatteryGetStatusResponder {
689                                control_handle: std::mem::ManuallyDrop::new(control_handle),
690                                tx_id: header.tx_id,
691                            },
692                        })
693                    }
694                    0x71fc28fbfc1f88c7 => {
695                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
696                        let mut req = fidl::new_empty!(
697                            BatteryConfigureWatchRequest,
698                            fidl::encoding::DefaultFuchsiaResourceDialect
699                        );
700                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<BatteryConfigureWatchRequest>(&header, _body_bytes, handles, &mut req)?;
701                        let control_handle = BatteryControlHandle { inner: this.inner.clone() };
702                        Ok(BatteryRequest::ConfigureWatch {
703                            options: req.options,
704
705                            responder: BatteryConfigureWatchResponder {
706                                control_handle: std::mem::ManuallyDrop::new(control_handle),
707                                tx_id: header.tx_id,
708                            },
709                        })
710                    }
711                    0x7386830cdd9e3390 => {
712                        header.validate_request_tx_id(fidl::MethodType::TwoWay)?;
713                        let mut req = fidl::new_empty!(
714                            BatteryWatchRequest,
715                            fidl::encoding::DefaultFuchsiaResourceDialect
716                        );
717                        fidl::encoding::Decoder::<fidl::encoding::DefaultFuchsiaResourceDialect>::decode_into::<BatteryWatchRequest>(&header, _body_bytes, handles, &mut req)?;
718                        let control_handle = BatteryControlHandle { inner: this.inner.clone() };
719                        Ok(BatteryRequest::Watch {
720                            lease: req.lease,
721
722                            responder: BatteryWatchResponder {
723                                control_handle: std::mem::ManuallyDrop::new(control_handle),
724                                tx_id: header.tx_id,
725                            },
726                        })
727                    }
728                    _ if header.tx_id == 0
729                        && header
730                            .dynamic_flags()
731                            .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
732                    {
733                        Ok(BatteryRequest::_UnknownMethod {
734                            ordinal: header.ordinal,
735                            control_handle: BatteryControlHandle { inner: this.inner.clone() },
736                            method_type: fidl::MethodType::OneWay,
737                        })
738                    }
739                    _ if header
740                        .dynamic_flags()
741                        .contains(fidl::encoding::DynamicFlags::FLEXIBLE) =>
742                    {
743                        this.inner.send_framework_err(
744                            fidl::encoding::FrameworkErr::UnknownMethod,
745                            header.tx_id,
746                            header.ordinal,
747                            header.dynamic_flags(),
748                            (bytes, handles),
749                        )?;
750                        Ok(BatteryRequest::_UnknownMethod {
751                            ordinal: header.ordinal,
752                            control_handle: BatteryControlHandle { inner: this.inner.clone() },
753                            method_type: fidl::MethodType::TwoWay,
754                        })
755                    }
756                    _ => Err(fidl::Error::UnknownOrdinal {
757                        ordinal: header.ordinal,
758                        protocol_name:
759                            <BatteryMarker as fidl::endpoints::ProtocolMarker>::DEBUG_NAME,
760                    }),
761                }))
762            },
763        )
764    }
765}
766
767/// Diagnostic and telemetry interface for battery hardware.
768///
769/// This is a read-only protocol that supports multiple concurrent clients.
770#[derive(Debug)]
771pub enum BatteryRequest {
772    /// Retrieves the static specification of the battery.
773    ///
774    /// Returns:
775    /// + `spec`: Static hardware characteristics and driver capabilities of the battery.
776    ///
777    /// Errors:
778    /// - `NOT_SUPPORTED`: Hardware does not supply a static specification.
779    /// - `IO`: Communication failure with the fuel gauge hardware (e.g. I2C transfer failure).
780    /// - `INTERNAL`: Internal driver error.
781    GetSpec { responder: BatteryGetSpecResponder },
782    /// Retrieves an instantaneous snapshot of the battery status.
783    ///
784    /// Returns:
785    /// + `status`: Complete current telemetry snapshot of battery metrics.
786    ///
787    /// Errors:
788    /// - `IO`: Communication failure with the fuel gauge hardware (e.g. I2C transfer failure).
789    /// - `INTERNAL`: Internal driver error.
790    GetStatus { responder: BatteryGetStatusResponder },
791    /// Configures the fields of interest and wake triggers for this client connection.
792    ///
793    /// The driver filters the requested masks against hardware capabilities and returns the
794    /// effective configuration in `effective_options`.
795    ///
796    /// - **Partially supported options**: If some requested fields are supported and others are not
797    ///   (e.g., requesting passive fields like `voltage_uv` or `current_ua` that do not support
798    ///   active interrupt notifications), the driver enables the supported fields and returns the
799    ///   active subset in `effective_options`. The call succeeds (`Ok`).
800    /// - **Fully unsupported options**: If non-empty masks were specified but NONE of the requested
801    ///   fields are supported, the driver returns `NOT_SUPPORTED`.
802    ///
803    /// If `ConfigureWatch` is never called, `Watch` defaults to returning on ANY supported field
804    /// change. The driver aggregates constraints across all clients to determine hardware reporting
805    /// rates.
806    ///
807    /// `ConfigureWatch` may be called at any time, including while a `Watch` is pending. The new
808    /// masks take effect immediately and apply to that pending call. Change detection continues to
809    /// compare against the status last delivered on this connection, so a field that changed
810    /// before the reconfiguration can still resolve the pending `Watch`.
811    ///
812    /// Parameters:
813    /// + `options`: Requested watch options. Both `interest` and `wake_on` are optional.
814    ///
815    /// Returns:
816    /// + `effective_options`: The subset of requested options supported and enabled by the driver.
817    ///
818    /// Errors:
819    /// - `NOT_SUPPORTED`: Non-empty options were requested, but none of the requested interest/wake
820    ///   fields or periodic sampling are supported by the driver.
821    ///
822    /// On error the connection's configuration is left unchanged; a failed call never partially
823    /// applies.
824    ConfigureWatch { options: WatchOptions, responder: BatteryConfigureWatchResponder },
825    /// Change notification for battery state using a hanging-get pattern.
826    ///
827    /// The first call returns the full current hardware state immediately. Subsequent calls block
828    /// until a state change matches the masks in [`ConfigureWatch`] or the interval in
829    /// `max_interval` has elapsed. Each return contains a complete telemetry snapshot of all
830    /// current battery fields, not a sparse delta.
831    ///
832    /// At most one `Watch` call may be outstanding per connection; concurrent calls fail with
833    /// `ALREADY_WATCHING`.
834    ///
835    /// Parameters:
836    /// + `lease`: An optional power lease token that keeps the system awake while the server
837    ///   processes the call. If the call is answered immediately, as the first call always is, the
838    ///   server hands it back as `wake_lease` unless it returns a wake lease of its own. If the
839    ///   call is parked, the server drops it.
840    ///
841    /// Returns:
842    /// + `status`: Complete current telemetry snapshot of the battery.
843    /// + `wake_lease`: An optional lease token that the client should hold while it handles
844    ///   `status`: the client's `lease` handed back on an immediate reply, or a wake lease provided
845    ///   if the change triggered a `wake_on` condition or a `max_interval` sample woke the system
846    ///   for a client that set `wake_on_max_interval`. Omitted otherwise.
847    ///
848    /// Errors:
849    /// - `ALREADY_WATCHING`: A `Watch` call is already pending on this connection.
850    /// - `IO`: Communication failure with the fuel gauge hardware (e.g. I2C transfer failure).
851    /// - `INTERNAL`: Internal driver error.
852    Watch { lease: Option<fidl::EventPair>, responder: BatteryWatchResponder },
853    /// An interaction was received which does not match any known method.
854    #[non_exhaustive]
855    _UnknownMethod {
856        /// Ordinal of the method that was called.
857        ordinal: u64,
858        control_handle: BatteryControlHandle,
859        method_type: fidl::MethodType,
860    },
861}
862
863impl BatteryRequest {
864    #[allow(irrefutable_let_patterns)]
865    pub fn into_get_spec(self) -> Option<(BatteryGetSpecResponder)> {
866        if let BatteryRequest::GetSpec { responder } = self { Some((responder)) } else { None }
867    }
868
869    #[allow(irrefutable_let_patterns)]
870    pub fn into_get_status(self) -> Option<(BatteryGetStatusResponder)> {
871        if let BatteryRequest::GetStatus { responder } = self { Some((responder)) } else { None }
872    }
873
874    #[allow(irrefutable_let_patterns)]
875    pub fn into_configure_watch(self) -> Option<(WatchOptions, BatteryConfigureWatchResponder)> {
876        if let BatteryRequest::ConfigureWatch { options, responder } = self {
877            Some((options, responder))
878        } else {
879            None
880        }
881    }
882
883    #[allow(irrefutable_let_patterns)]
884    pub fn into_watch(self) -> Option<(Option<fidl::EventPair>, BatteryWatchResponder)> {
885        if let BatteryRequest::Watch { lease, responder } = self {
886            Some((lease, responder))
887        } else {
888            None
889        }
890    }
891
892    /// Name of the method defined in FIDL
893    pub fn method_name(&self) -> &'static str {
894        match *self {
895            BatteryRequest::GetSpec { .. } => "get_spec",
896            BatteryRequest::GetStatus { .. } => "get_status",
897            BatteryRequest::ConfigureWatch { .. } => "configure_watch",
898            BatteryRequest::Watch { .. } => "watch",
899            BatteryRequest::_UnknownMethod { method_type: fidl::MethodType::OneWay, .. } => {
900                "unknown one-way method"
901            }
902            BatteryRequest::_UnknownMethod { method_type: fidl::MethodType::TwoWay, .. } => {
903                "unknown two-way method"
904            }
905        }
906    }
907}
908
909#[derive(Debug, Clone)]
910pub struct BatteryControlHandle {
911    inner: std::sync::Arc<fidl::ServeInner<fidl::encoding::DefaultFuchsiaResourceDialect>>,
912}
913
914impl BatteryControlHandle {
915    pub fn shutdown_with_epitaph(&self, status: impl Into<fidl::Epitaph>) {
916        self.inner.shutdown_with_epitaph(status.into())
917    }
918}
919
920impl fidl::endpoints::ControlHandle for BatteryControlHandle {
921    fn shutdown(&self) {
922        self.inner.shutdown()
923    }
924
925    fn shutdown_with_epitaph(&self, status: fidl::Epitaph) {
926        self.inner.shutdown_with_epitaph(status)
927    }
928
929    fn is_closed(&self) -> bool {
930        self.inner.channel().is_closed()
931    }
932    fn on_closed(&self) -> fidl::OnSignalsRef<'_> {
933        self.inner.channel().on_closed()
934    }
935
936    #[cfg(target_os = "fuchsia")]
937    fn signal_peer(
938        &self,
939        clear_mask: zx::Signals,
940        set_mask: zx::Signals,
941    ) -> Result<(), zx_status::Status> {
942        use fidl::Peered;
943        self.inner.channel().signal_peer(clear_mask, set_mask)
944    }
945}
946
947impl BatteryControlHandle {}
948
949#[must_use = "FIDL methods require a response to be sent"]
950#[derive(Debug)]
951pub struct BatteryGetSpecResponder {
952    control_handle: std::mem::ManuallyDrop<BatteryControlHandle>,
953    tx_id: u32,
954}
955
956/// Set the the channel to be shutdown (see [`BatteryControlHandle::shutdown`])
957/// if the responder is dropped without sending a response, so that the client
958/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
959impl std::ops::Drop for BatteryGetSpecResponder {
960    fn drop(&mut self) {
961        self.control_handle.shutdown();
962        // Safety: drops once, never accessed again
963        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
964    }
965}
966
967impl fidl::endpoints::Responder for BatteryGetSpecResponder {
968    type ControlHandle = BatteryControlHandle;
969
970    fn control_handle(&self) -> &BatteryControlHandle {
971        &self.control_handle
972    }
973
974    fn drop_without_shutdown(mut self) {
975        // Safety: drops once, never accessed again due to mem::forget
976        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
977        // Prevent Drop from running (which would shut down the channel)
978        std::mem::forget(self);
979    }
980}
981
982impl BatteryGetSpecResponder {
983    /// Sends a response to the FIDL transaction.
984    ///
985    /// Sets the channel to shutdown if an error occurs.
986    pub fn send(self, mut result: Result<&Spec, Error>) -> Result<(), fidl::Error> {
987        let _result = self.send_raw(result);
988        if _result.is_err() {
989            self.control_handle.shutdown();
990        }
991        self.drop_without_shutdown();
992        _result
993    }
994
995    /// Similar to "send" but does not shutdown the channel if an error occurs.
996    pub fn send_no_shutdown_on_err(
997        self,
998        mut result: Result<&Spec, Error>,
999    ) -> Result<(), fidl::Error> {
1000        let _result = self.send_raw(result);
1001        self.drop_without_shutdown();
1002        _result
1003    }
1004
1005    fn send_raw(&self, mut result: Result<&Spec, Error>) -> Result<(), fidl::Error> {
1006        self.control_handle
1007            .inner
1008            .send::<fidl::encoding::FlexibleResultType<BatteryGetSpecResponse, Error>>(
1009                fidl::encoding::FlexibleResult::new(result.map(|spec| (spec,))),
1010                self.tx_id,
1011                0x235609229653654f,
1012                fidl::encoding::DynamicFlags::FLEXIBLE,
1013            )
1014    }
1015}
1016
1017#[must_use = "FIDL methods require a response to be sent"]
1018#[derive(Debug)]
1019pub struct BatteryGetStatusResponder {
1020    control_handle: std::mem::ManuallyDrop<BatteryControlHandle>,
1021    tx_id: u32,
1022}
1023
1024/// Set the the channel to be shutdown (see [`BatteryControlHandle::shutdown`])
1025/// if the responder is dropped without sending a response, so that the client
1026/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
1027impl std::ops::Drop for BatteryGetStatusResponder {
1028    fn drop(&mut self) {
1029        self.control_handle.shutdown();
1030        // Safety: drops once, never accessed again
1031        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
1032    }
1033}
1034
1035impl fidl::endpoints::Responder for BatteryGetStatusResponder {
1036    type ControlHandle = BatteryControlHandle;
1037
1038    fn control_handle(&self) -> &BatteryControlHandle {
1039        &self.control_handle
1040    }
1041
1042    fn drop_without_shutdown(mut self) {
1043        // Safety: drops once, never accessed again due to mem::forget
1044        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
1045        // Prevent Drop from running (which would shut down the channel)
1046        std::mem::forget(self);
1047    }
1048}
1049
1050impl BatteryGetStatusResponder {
1051    /// Sends a response to the FIDL transaction.
1052    ///
1053    /// Sets the channel to shutdown if an error occurs.
1054    pub fn send(self, mut result: Result<&Status, Error>) -> Result<(), fidl::Error> {
1055        let _result = self.send_raw(result);
1056        if _result.is_err() {
1057            self.control_handle.shutdown();
1058        }
1059        self.drop_without_shutdown();
1060        _result
1061    }
1062
1063    /// Similar to "send" but does not shutdown the channel if an error occurs.
1064    pub fn send_no_shutdown_on_err(
1065        self,
1066        mut result: Result<&Status, Error>,
1067    ) -> Result<(), fidl::Error> {
1068        let _result = self.send_raw(result);
1069        self.drop_without_shutdown();
1070        _result
1071    }
1072
1073    fn send_raw(&self, mut result: Result<&Status, Error>) -> Result<(), fidl::Error> {
1074        self.control_handle
1075            .inner
1076            .send::<fidl::encoding::FlexibleResultType<BatteryGetStatusResponse, Error>>(
1077                fidl::encoding::FlexibleResult::new(result.map(|status| (status,))),
1078                self.tx_id,
1079                0x2e0c03524d47095a,
1080                fidl::encoding::DynamicFlags::FLEXIBLE,
1081            )
1082    }
1083}
1084
1085#[must_use = "FIDL methods require a response to be sent"]
1086#[derive(Debug)]
1087pub struct BatteryConfigureWatchResponder {
1088    control_handle: std::mem::ManuallyDrop<BatteryControlHandle>,
1089    tx_id: u32,
1090}
1091
1092/// Set the the channel to be shutdown (see [`BatteryControlHandle::shutdown`])
1093/// if the responder is dropped without sending a response, so that the client
1094/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
1095impl std::ops::Drop for BatteryConfigureWatchResponder {
1096    fn drop(&mut self) {
1097        self.control_handle.shutdown();
1098        // Safety: drops once, never accessed again
1099        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
1100    }
1101}
1102
1103impl fidl::endpoints::Responder for BatteryConfigureWatchResponder {
1104    type ControlHandle = BatteryControlHandle;
1105
1106    fn control_handle(&self) -> &BatteryControlHandle {
1107        &self.control_handle
1108    }
1109
1110    fn drop_without_shutdown(mut self) {
1111        // Safety: drops once, never accessed again due to mem::forget
1112        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
1113        // Prevent Drop from running (which would shut down the channel)
1114        std::mem::forget(self);
1115    }
1116}
1117
1118impl BatteryConfigureWatchResponder {
1119    /// Sends a response to the FIDL transaction.
1120    ///
1121    /// Sets the channel to shutdown if an error occurs.
1122    pub fn send(self, mut result: Result<&WatchOptions, Error>) -> Result<(), fidl::Error> {
1123        let _result = self.send_raw(result);
1124        if _result.is_err() {
1125            self.control_handle.shutdown();
1126        }
1127        self.drop_without_shutdown();
1128        _result
1129    }
1130
1131    /// Similar to "send" but does not shutdown the channel if an error occurs.
1132    pub fn send_no_shutdown_on_err(
1133        self,
1134        mut result: Result<&WatchOptions, Error>,
1135    ) -> Result<(), fidl::Error> {
1136        let _result = self.send_raw(result);
1137        self.drop_without_shutdown();
1138        _result
1139    }
1140
1141    fn send_raw(&self, mut result: Result<&WatchOptions, Error>) -> Result<(), fidl::Error> {
1142        self.control_handle.inner.send::<fidl::encoding::FlexibleResultType<
1143            BatteryConfigureWatchResponse,
1144            Error,
1145        >>(
1146            fidl::encoding::FlexibleResult::new(
1147                result.map(|effective_options| (effective_options,)),
1148            ),
1149            self.tx_id,
1150            0x71fc28fbfc1f88c7,
1151            fidl::encoding::DynamicFlags::FLEXIBLE,
1152        )
1153    }
1154}
1155
1156#[must_use = "FIDL methods require a response to be sent"]
1157#[derive(Debug)]
1158pub struct BatteryWatchResponder {
1159    control_handle: std::mem::ManuallyDrop<BatteryControlHandle>,
1160    tx_id: u32,
1161}
1162
1163/// Set the the channel to be shutdown (see [`BatteryControlHandle::shutdown`])
1164/// if the responder is dropped without sending a response, so that the client
1165/// doesn't hang. To prevent this behavior, call `drop_without_shutdown`.
1166impl std::ops::Drop for BatteryWatchResponder {
1167    fn drop(&mut self) {
1168        self.control_handle.shutdown();
1169        // Safety: drops once, never accessed again
1170        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
1171    }
1172}
1173
1174impl fidl::endpoints::Responder for BatteryWatchResponder {
1175    type ControlHandle = BatteryControlHandle;
1176
1177    fn control_handle(&self) -> &BatteryControlHandle {
1178        &self.control_handle
1179    }
1180
1181    fn drop_without_shutdown(mut self) {
1182        // Safety: drops once, never accessed again due to mem::forget
1183        unsafe { std::mem::ManuallyDrop::drop(&mut self.control_handle) };
1184        // Prevent Drop from running (which would shut down the channel)
1185        std::mem::forget(self);
1186    }
1187}
1188
1189impl BatteryWatchResponder {
1190    /// Sends a response to the FIDL transaction.
1191    ///
1192    /// Sets the channel to shutdown if an error occurs.
1193    pub fn send(
1194        self,
1195        mut result: Result<(&Status, Option<fidl::EventPair>), Error>,
1196    ) -> Result<(), fidl::Error> {
1197        let _result = self.send_raw(result);
1198        if _result.is_err() {
1199            self.control_handle.shutdown();
1200        }
1201        self.drop_without_shutdown();
1202        _result
1203    }
1204
1205    /// Similar to "send" but does not shutdown the channel if an error occurs.
1206    pub fn send_no_shutdown_on_err(
1207        self,
1208        mut result: Result<(&Status, Option<fidl::EventPair>), Error>,
1209    ) -> Result<(), fidl::Error> {
1210        let _result = self.send_raw(result);
1211        self.drop_without_shutdown();
1212        _result
1213    }
1214
1215    fn send_raw(
1216        &self,
1217        mut result: Result<(&Status, Option<fidl::EventPair>), Error>,
1218    ) -> Result<(), fidl::Error> {
1219        self.control_handle
1220            .inner
1221            .send::<fidl::encoding::FlexibleResultType<BatteryWatchResponse, Error>>(
1222                fidl::encoding::FlexibleResult::new(result),
1223                self.tx_id,
1224                0x7386830cdd9e3390,
1225                fidl::encoding::DynamicFlags::FLEXIBLE,
1226            )
1227    }
1228}
1229
1230#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
1231pub struct ServiceMarker;
1232
1233#[cfg(target_os = "fuchsia")]
1234impl fidl::endpoints::ServiceMarker for ServiceMarker {
1235    type Proxy = ServiceProxy;
1236    type Request = ServiceRequest;
1237    const SERVICE_NAME: &'static str = "fuchsia.hardware.power.battery.Service";
1238}
1239
1240/// A request for one of the member protocols of Service.
1241///
1242#[cfg(target_os = "fuchsia")]
1243pub enum ServiceRequest {
1244    Battery(BatteryRequestStream),
1245}
1246
1247#[cfg(target_os = "fuchsia")]
1248impl fidl::endpoints::ServiceRequest for ServiceRequest {
1249    type Service = ServiceMarker;
1250
1251    fn dispatch(name: &str, _channel: fidl::AsyncChannel) -> Self {
1252        match name {
1253            "battery" => Self::Battery(
1254                <BatteryRequestStream as fidl::endpoints::RequestStream>::from_channel(_channel),
1255            ),
1256            _ => panic!("no such member protocol name for service Service"),
1257        }
1258    }
1259
1260    fn member_names() -> &'static [&'static str] {
1261        &["battery"]
1262    }
1263}
1264#[cfg(target_os = "fuchsia")]
1265pub struct ServiceProxy(#[allow(dead_code)] Box<dyn fidl::endpoints::MemberOpener>);
1266
1267#[cfg(target_os = "fuchsia")]
1268impl fidl::endpoints::ServiceProxy for ServiceProxy {
1269    type Service = ServiceMarker;
1270
1271    fn from_member_opener(opener: Box<dyn fidl::endpoints::MemberOpener>) -> Self {
1272        Self(opener)
1273    }
1274}
1275
1276#[cfg(target_os = "fuchsia")]
1277impl ServiceProxy {
1278    pub fn connect_to_battery(&self) -> Result<BatteryProxy, fidl::Error> {
1279        let (proxy, server_end) = fidl::endpoints::create_proxy::<BatteryMarker>();
1280        self.connect_channel_to_battery(server_end)?;
1281        Ok(proxy)
1282    }
1283
1284    /// Like `connect_to_battery`, but returns a sync proxy.
1285    /// See [`Self::connect_to_battery`] for more details.
1286    pub fn connect_to_battery_sync(&self) -> Result<BatterySynchronousProxy, fidl::Error> {
1287        let (proxy, server_end) = fidl::endpoints::create_sync_proxy::<BatteryMarker>();
1288        self.connect_channel_to_battery(server_end)?;
1289        Ok(proxy)
1290    }
1291
1292    /// Like `connect_to_battery`, but accepts a server end.
1293    /// See [`Self::connect_to_battery`] for more details.
1294    pub fn connect_channel_to_battery(
1295        &self,
1296        server_end: fidl::endpoints::ServerEnd<BatteryMarker>,
1297    ) -> Result<(), fidl::Error> {
1298        self.0.open_member("battery", server_end.into_channel())
1299    }
1300
1301    pub fn instance_name(&self) -> &str {
1302        self.0.instance_name()
1303    }
1304}
1305
1306mod internal {
1307    use super::*;
1308
1309    impl fidl::encoding::ResourceTypeMarker for BatteryWatchRequest {
1310        type Borrowed<'a> = &'a mut Self;
1311        fn take_or_borrow<'a>(
1312            value: &'a mut <Self as fidl::encoding::TypeMarker>::Owned,
1313        ) -> Self::Borrowed<'a> {
1314            value
1315        }
1316    }
1317
1318    unsafe impl fidl::encoding::TypeMarker for BatteryWatchRequest {
1319        type Owned = Self;
1320
1321        #[inline(always)]
1322        fn inline_align(_context: fidl::encoding::Context) -> usize {
1323            4
1324        }
1325
1326        #[inline(always)]
1327        fn inline_size(_context: fidl::encoding::Context) -> usize {
1328            4
1329        }
1330    }
1331
1332    unsafe impl
1333        fidl::encoding::Encode<BatteryWatchRequest, fidl::encoding::DefaultFuchsiaResourceDialect>
1334        for &mut BatteryWatchRequest
1335    {
1336        #[inline]
1337        unsafe fn encode(
1338            self,
1339            encoder: &mut fidl::encoding::Encoder<
1340                '_,
1341                fidl::encoding::DefaultFuchsiaResourceDialect,
1342            >,
1343            offset: usize,
1344            _depth: fidl::encoding::Depth,
1345        ) -> fidl::Result<()> {
1346            encoder.debug_check_bounds::<BatteryWatchRequest>(offset);
1347            // Delegate to tuple encoding.
1348            fidl::encoding::Encode::<
1349                BatteryWatchRequest,
1350                fidl::encoding::DefaultFuchsiaResourceDialect,
1351            >::encode(
1352                (<fidl::encoding::Optional<
1353                    fidl::encoding::HandleType<
1354                        fidl::EventPair,
1355                        { fidl::ObjectType::EVENTPAIR.into_raw() },
1356                        16387,
1357                    >,
1358                > as fidl::encoding::ResourceTypeMarker>::take_or_borrow(
1359                    &mut self.lease
1360                ),),
1361                encoder,
1362                offset,
1363                _depth,
1364            )
1365        }
1366    }
1367    unsafe impl<
1368        T0: fidl::encoding::Encode<
1369                fidl::encoding::Optional<
1370                    fidl::encoding::HandleType<
1371                        fidl::EventPair,
1372                        { fidl::ObjectType::EVENTPAIR.into_raw() },
1373                        16387,
1374                    >,
1375                >,
1376                fidl::encoding::DefaultFuchsiaResourceDialect,
1377            >,
1378    > fidl::encoding::Encode<BatteryWatchRequest, fidl::encoding::DefaultFuchsiaResourceDialect>
1379        for (T0,)
1380    {
1381        #[inline]
1382        unsafe fn encode(
1383            self,
1384            encoder: &mut fidl::encoding::Encoder<
1385                '_,
1386                fidl::encoding::DefaultFuchsiaResourceDialect,
1387            >,
1388            offset: usize,
1389            depth: fidl::encoding::Depth,
1390        ) -> fidl::Result<()> {
1391            encoder.debug_check_bounds::<BatteryWatchRequest>(offset);
1392            // Zero out padding regions. There's no need to apply masks
1393            // because the unmasked parts will be overwritten by fields.
1394            // Write the fields.
1395            self.0.encode(encoder, offset + 0, depth)?;
1396            Ok(())
1397        }
1398    }
1399
1400    impl fidl::encoding::Decode<Self, fidl::encoding::DefaultFuchsiaResourceDialect>
1401        for BatteryWatchRequest
1402    {
1403        #[inline(always)]
1404        fn new_empty() -> Self {
1405            Self {
1406                lease: fidl::new_empty!(
1407                    fidl::encoding::Optional<
1408                        fidl::encoding::HandleType<
1409                            fidl::EventPair,
1410                            { fidl::ObjectType::EVENTPAIR.into_raw() },
1411                            16387,
1412                        >,
1413                    >,
1414                    fidl::encoding::DefaultFuchsiaResourceDialect
1415                ),
1416            }
1417        }
1418
1419        #[inline]
1420        unsafe fn decode(
1421            &mut self,
1422            decoder: &mut fidl::encoding::Decoder<
1423                '_,
1424                fidl::encoding::DefaultFuchsiaResourceDialect,
1425            >,
1426            offset: usize,
1427            _depth: fidl::encoding::Depth,
1428        ) -> fidl::Result<()> {
1429            decoder.debug_check_bounds::<Self>(offset);
1430            // Verify that padding bytes are zero.
1431            fidl::decode!(
1432                fidl::encoding::Optional<
1433                    fidl::encoding::HandleType<
1434                        fidl::EventPair,
1435                        { fidl::ObjectType::EVENTPAIR.into_raw() },
1436                        16387,
1437                    >,
1438                >,
1439                fidl::encoding::DefaultFuchsiaResourceDialect,
1440                &mut self.lease,
1441                decoder,
1442                offset + 0,
1443                _depth
1444            )?;
1445            Ok(())
1446        }
1447    }
1448
1449    impl fidl::encoding::ResourceTypeMarker for BatteryWatchResponse {
1450        type Borrowed<'a> = &'a mut Self;
1451        fn take_or_borrow<'a>(
1452            value: &'a mut <Self as fidl::encoding::TypeMarker>::Owned,
1453        ) -> Self::Borrowed<'a> {
1454            value
1455        }
1456    }
1457
1458    unsafe impl fidl::encoding::TypeMarker for BatteryWatchResponse {
1459        type Owned = Self;
1460
1461        #[inline(always)]
1462        fn inline_align(_context: fidl::encoding::Context) -> usize {
1463            8
1464        }
1465
1466        #[inline(always)]
1467        fn inline_size(_context: fidl::encoding::Context) -> usize {
1468            24
1469        }
1470    }
1471
1472    unsafe impl
1473        fidl::encoding::Encode<BatteryWatchResponse, fidl::encoding::DefaultFuchsiaResourceDialect>
1474        for &mut BatteryWatchResponse
1475    {
1476        #[inline]
1477        unsafe fn encode(
1478            self,
1479            encoder: &mut fidl::encoding::Encoder<
1480                '_,
1481                fidl::encoding::DefaultFuchsiaResourceDialect,
1482            >,
1483            offset: usize,
1484            _depth: fidl::encoding::Depth,
1485        ) -> fidl::Result<()> {
1486            encoder.debug_check_bounds::<BatteryWatchResponse>(offset);
1487            // Delegate to tuple encoding.
1488            fidl::encoding::Encode::<
1489                BatteryWatchResponse,
1490                fidl::encoding::DefaultFuchsiaResourceDialect,
1491            >::encode(
1492                (
1493                    <Status as fidl::encoding::ValueTypeMarker>::borrow(&self.status),
1494                    <fidl::encoding::Optional<
1495                        fidl::encoding::HandleType<
1496                            fidl::EventPair,
1497                            { fidl::ObjectType::EVENTPAIR.into_raw() },
1498                            16387,
1499                        >,
1500                    > as fidl::encoding::ResourceTypeMarker>::take_or_borrow(
1501                        &mut self.wake_lease
1502                    ),
1503                ),
1504                encoder,
1505                offset,
1506                _depth,
1507            )
1508        }
1509    }
1510    unsafe impl<
1511        T0: fidl::encoding::Encode<Status, fidl::encoding::DefaultFuchsiaResourceDialect>,
1512        T1: fidl::encoding::Encode<
1513                fidl::encoding::Optional<
1514                    fidl::encoding::HandleType<
1515                        fidl::EventPair,
1516                        { fidl::ObjectType::EVENTPAIR.into_raw() },
1517                        16387,
1518                    >,
1519                >,
1520                fidl::encoding::DefaultFuchsiaResourceDialect,
1521            >,
1522    >
1523        fidl::encoding::Encode<BatteryWatchResponse, fidl::encoding::DefaultFuchsiaResourceDialect>
1524        for (T0, T1)
1525    {
1526        #[inline]
1527        unsafe fn encode(
1528            self,
1529            encoder: &mut fidl::encoding::Encoder<
1530                '_,
1531                fidl::encoding::DefaultFuchsiaResourceDialect,
1532            >,
1533            offset: usize,
1534            depth: fidl::encoding::Depth,
1535        ) -> fidl::Result<()> {
1536            encoder.debug_check_bounds::<BatteryWatchResponse>(offset);
1537            // Zero out padding regions. There's no need to apply masks
1538            // because the unmasked parts will be overwritten by fields.
1539            unsafe {
1540                let ptr = encoder.buf.as_mut_ptr().add(offset).offset(16);
1541                (ptr as *mut u64).write_unaligned(0);
1542            }
1543            // Write the fields.
1544            self.0.encode(encoder, offset + 0, depth)?;
1545            self.1.encode(encoder, offset + 16, depth)?;
1546            Ok(())
1547        }
1548    }
1549
1550    impl fidl::encoding::Decode<Self, fidl::encoding::DefaultFuchsiaResourceDialect>
1551        for BatteryWatchResponse
1552    {
1553        #[inline(always)]
1554        fn new_empty() -> Self {
1555            Self {
1556                status: fidl::new_empty!(Status, fidl::encoding::DefaultFuchsiaResourceDialect),
1557                wake_lease: fidl::new_empty!(
1558                    fidl::encoding::Optional<
1559                        fidl::encoding::HandleType<
1560                            fidl::EventPair,
1561                            { fidl::ObjectType::EVENTPAIR.into_raw() },
1562                            16387,
1563                        >,
1564                    >,
1565                    fidl::encoding::DefaultFuchsiaResourceDialect
1566                ),
1567            }
1568        }
1569
1570        #[inline]
1571        unsafe fn decode(
1572            &mut self,
1573            decoder: &mut fidl::encoding::Decoder<
1574                '_,
1575                fidl::encoding::DefaultFuchsiaResourceDialect,
1576            >,
1577            offset: usize,
1578            _depth: fidl::encoding::Depth,
1579        ) -> fidl::Result<()> {
1580            decoder.debug_check_bounds::<Self>(offset);
1581            // Verify that padding bytes are zero.
1582            let ptr = unsafe { decoder.buf.as_ptr().add(offset).offset(16) };
1583            let padval = unsafe { (ptr as *const u64).read_unaligned() };
1584            let mask = 0xffffffff00000000u64;
1585            let maskedval = padval & mask;
1586            if maskedval != 0 {
1587                return Err(fidl::Error::NonZeroPadding {
1588                    padding_start: offset + 16 + ((mask as u64).trailing_zeros() / 8) as usize,
1589                });
1590            }
1591            fidl::decode!(
1592                Status,
1593                fidl::encoding::DefaultFuchsiaResourceDialect,
1594                &mut self.status,
1595                decoder,
1596                offset + 0,
1597                _depth
1598            )?;
1599            fidl::decode!(
1600                fidl::encoding::Optional<
1601                    fidl::encoding::HandleType<
1602                        fidl::EventPair,
1603                        { fidl::ObjectType::EVENTPAIR.into_raw() },
1604                        16387,
1605                    >,
1606                >,
1607                fidl::encoding::DefaultFuchsiaResourceDialect,
1608                &mut self.wake_lease,
1609                decoder,
1610                offset + 16,
1611                _depth
1612            )?;
1613            Ok(())
1614        }
1615    }
1616}