Skip to main content

input_pipeline/light_sensor/
light_sensor_handler.rs

1// Copyright 2022 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::Transport;
6use crate::input_device::{
7    Handled, InputDeviceDescriptor, InputDeviceEvent, InputEvent, InputEventType,
8};
9use crate::input_handler::{Handler, InputHandler, InputHandlerStatus};
10use crate::inspect_handler::{BufferNode, CircularBuffer};
11use crate::light_sensor::calibrator::{Calibrate, Calibrator};
12use crate::light_sensor::led_watcher::{CancelableTask, LedWatcher, LedWatcherHandle};
13use crate::light_sensor::types::{AdjustmentSetting, Calibration, Rgbc, SensorConfiguration};
14use anyhow::{Context, Error, format_err};
15use async_trait::async_trait;
16use async_utils::hanging_get::server::HangingGet;
17use fidl_fuchsia_lightsensor::{
18    LightSensorData as FidlLightSensorData, Rgbc as FidlRgbc, SensorRequest, SensorRequestStream,
19    SensorWatchResponder,
20};
21use fidl_fuchsia_settings::LightProxy;
22use fidl_fuchsia_ui_brightness::ControlProxy as BrightnessControlProxy;
23use fidl_next_fuchsia_input_report::{FeatureReport, SensorFeatureReport};
24use fuchsia_inspect::NumericProperty;
25use fuchsia_inspect::health::Reporter;
26
27use fuchsia_sync::Mutex;
28use futures::channel::oneshot;
29use futures::{Future, FutureExt, TryStreamExt};
30use std::cell::RefCell;
31use std::rc::Rc;
32use std::sync::Arc;
33
34type NotifyFn = Box<dyn Fn(&LightSensorData, SensorWatchResponder) -> bool>;
35type SensorHangingGet = HangingGet<LightSensorData, SensorWatchResponder, NotifyFn>;
36
37// Precise value is 2.78125ms, but data sheet lists 2.78ms.
38/// Number of us for each cycle of the sensor.
39const MIN_TIME_STEP_US: u32 = 2780;
40/// Maximum multiplier.
41const MAX_GAIN: u32 = 64;
42/// Maximum sensor reading per cycle for any 1 color channel.
43const MAX_COUNT_PER_CYCLE: u32 = 1024;
44/// Absolute maximum reading the sensor can return for any 1 color channel.
45const MAX_SATURATION: u32 = u16::MAX as u32;
46const MAX_ATIME: u32 = 256;
47/// Driver scales the values by max gain & atime in ms.
48const ADC_SCALING_FACTOR: f32 = 64.0 * 256.0;
49/// The gain up margin should be 10% of the saturation point.
50const GAIN_UP_MARGIN_DIVISOR: u32 = 10;
51/// The divisor for scaling uncalibrated values to transition old clients to auto gain.
52const TRANSITION_SCALING_FACTOR: f32 = 4.0;
53
54#[derive(Copy, Clone, Debug)]
55struct LightReading {
56    rgbc: Rgbc<f32>,
57    si_rgbc: Rgbc<f32>,
58    is_calibrated: bool,
59    lux: f32,
60    cct: Option<f32>,
61}
62
63fn num_cycles(atime: u32) -> u32 {
64    MAX_ATIME - atime
65}
66
67#[cfg_attr(test, derive(Debug))]
68struct ActiveSetting {
69    settings: Vec<AdjustmentSetting>,
70    idx: usize,
71}
72
73impl ActiveSetting {
74    fn new(settings: Vec<AdjustmentSetting>, idx: usize) -> Self {
75        Self { settings, idx }
76    }
77
78    /// Update sensor if it's near or past a saturation point. Returns a saturation error if the
79    /// sensor is saturated, `true` if the sensor is not saturated but still pulled up, and `false`
80    /// otherwise.
81    async fn adjust<Fut>(
82        &mut self,
83        reading: Rgbc<u16>,
84        device_proxy: &fidl_next::Client<fidl_next_fuchsia_input_report::InputDevice, Transport>,
85        track_feature_update: impl Fn(FeatureEvent) -> Fut,
86    ) -> Result<bool, SaturatedError>
87    where
88        Fut: Future<Output = ()>,
89    {
90        let saturation_point =
91            (num_cycles(self.active_setting().atime) * MAX_COUNT_PER_CYCLE).min(MAX_SATURATION);
92        let gain_up_margin = saturation_point / GAIN_UP_MARGIN_DIVISOR;
93
94        let step_change = self.step_change();
95        let mut pull_up = true;
96
97        if saturated(reading) {
98            if self.adjust_down() {
99                log::info!("adjusting down due to saturation sentinel");
100                self.update_device(&device_proxy, track_feature_update)
101                    .await
102                    .context("updating light sensor device")?;
103            }
104            return Err(SaturatedError::Saturated);
105        }
106
107        for value in [reading.red, reading.green, reading.blue, reading.clear] {
108            let value = value as u32;
109            if value >= saturation_point {
110                if self.adjust_down() {
111                    log::info!("adjusting down due to saturation point");
112                    self.update_device(&device_proxy, track_feature_update)
113                        .await
114                        .context("updating light sensor device")?;
115                }
116                return Err(SaturatedError::Saturated);
117            } else if (value * step_change + gain_up_margin) >= saturation_point {
118                pull_up = false;
119            }
120        }
121
122        if pull_up {
123            if self.adjust_up() {
124                log::info!("adjusting up");
125                self.update_device(&device_proxy, track_feature_update)
126                    .await
127                    .context("updating light sensor device")?;
128                return Ok(true);
129            }
130        }
131
132        Ok(false)
133    }
134
135    async fn update_device<Fut>(
136        &self,
137        device_proxy: &fidl_next::Client<fidl_next_fuchsia_input_report::InputDevice, Transport>,
138        track_feature_update: impl Fn(FeatureEvent) -> Fut,
139    ) -> Result<(), Error>
140    where
141        Fut: Future<Output = ()>,
142    {
143        let active_setting = self.active_setting();
144        let feature_report = device_proxy
145            .get_feature_report()
146            .await
147            .context("calling get_feature_report")?
148            .map_err(|e| format_err!("getting feature report on light sensor device: {e:?}"))?
149            .report;
150        let feature_report = FeatureReport {
151            sensor: Some(SensorFeatureReport {
152                sensitivity: Some(vec![active_setting.gain as i64]),
153                // Feature report expects sampling rate in microseconds.
154                sampling_rate: Some(to_us(active_setting.atime) as i64),
155                ..(feature_report
156                    .sensor
157                    .ok_or_else(|| format_err!("missing sensor in feature_report"))?)
158            }),
159            ..feature_report
160        };
161        device_proxy
162            .set_feature_report(&feature_report)
163            .await
164            .context("calling set_feature_report")?
165            .map_err(|e| format_err!("updating feature report on light sensor device: {e:?}"))?;
166        if let Some(feature_event) = FeatureEvent::maybe_new(feature_report) {
167            (track_feature_update)(feature_event).await;
168        }
169        Ok(())
170    }
171
172    fn active_setting(&self) -> AdjustmentSetting {
173        self.settings[self.idx]
174    }
175
176    /// Adjusts to a lower setting. Returns whether or not the setting changed.
177    fn adjust_down(&mut self) -> bool {
178        if self.idx == 0 {
179            false
180        } else {
181            self.idx -= 1;
182            true
183        }
184    }
185
186    /// Calculate the effect to saturation that occurs by moving the setting up a step.
187    fn step_change(&self) -> u32 {
188        let current = self.active_setting();
189        let new = match self.settings.get(self.idx + 1) {
190            Some(setting) => *setting,
191            // If we're at the limit, just return a coefficient of 1 since there will be no step
192            // change.
193            None => return 1,
194        };
195        div_round_up(new.gain, current.gain) * div_round_up(to_us(new.atime), to_us(current.atime))
196    }
197
198    /// Adjusts to a higher setting. Returns whether or not the setting changed.
199    fn adjust_up(&mut self) -> bool {
200        if self.idx == self.settings.len() - 1 {
201            false
202        } else {
203            self.idx += 1;
204            true
205        }
206    }
207}
208
209struct FeatureEvent {
210    event_time: zx::MonotonicInstant,
211    sampling_rate: i64,
212    sensitivity: i64,
213}
214
215impl FeatureEvent {
216    fn maybe_new(report: FeatureReport) -> Option<Self> {
217        let sensor = report.sensor?;
218        Some(FeatureEvent {
219            sampling_rate: sensor.sampling_rate?,
220            sensitivity: *sensor.sensitivity?.get(0)?,
221            event_time: zx::MonotonicInstant::get(),
222        })
223    }
224}
225
226impl BufferNode for FeatureEvent {
227    fn get_name(&self) -> &'static str {
228        "feature_report_update_event"
229    }
230
231    fn record_inspect(&self, node: &fuchsia_inspect::Node) {
232        node.record_int("sampling_rate", self.sampling_rate);
233        node.record_int("sensitivity", self.sensitivity);
234        node.record_int("event_time", self.event_time.into_nanos());
235    }
236}
237
238pub struct LightSensorHandler<T> {
239    hanging_get: RefCell<SensorHangingGet>,
240    calibrator: Option<T>,
241    active_setting: RefCell<ActiveSettingState>,
242    rgbc_to_lux_coefs: Rgbc<f32>,
243    si_scaling_factors: Rgbc<f32>,
244    vendor_id: u32,
245    product_id: u32,
246    /// The inventory of this handler's Inspect status.
247    inspect_status: InputHandlerStatus,
248    feature_updates: Arc<Mutex<CircularBuffer<FeatureEvent>>>,
249
250    // Additional inspect properties specific to LightSensorHandler
251
252    // Number of received events that were discarded because handler could not process
253    // its saturation values. These events are marked as handled in Input Pipeline so
254    // they are ignored by downstream handlers, but are not counted to events_handled_count.
255    // events_received_count >= events_handled_count + events_saturated_count
256    events_saturated_count: fuchsia_inspect::UintProperty,
257    // Number of connected clients subscribed to receive updated sensor readings from
258    // the HangingGet.
259    clients_connected_count: fuchsia_inspect::UintProperty,
260}
261
262#[cfg_attr(test, derive(Debug))]
263enum ActiveSettingState {
264    Uninitialized(Vec<AdjustmentSetting>),
265    Initialized(ActiveSetting),
266    Static(AdjustmentSetting),
267}
268
269pub type CalibratedLightSensorHandler = LightSensorHandler<Calibrator<LedWatcherHandle>>;
270pub async fn make_light_sensor_handler_and_spawn_led_watcher(
271    light_proxy: LightProxy,
272    brightness_proxy: BrightnessControlProxy,
273    calibration: Option<Calibration>,
274    configuration: SensorConfiguration,
275    input_handlers_node: &fuchsia_inspect::Node,
276) -> Result<(Rc<CalibratedLightSensorHandler>, Option<CancelableTask>), Error> {
277    let inspect_status = InputHandlerStatus::new(
278        input_handlers_node,
279        "light_sensor_handler",
280        /* generates_events */ false,
281    );
282    let (calibrator, watcher_task) = if let Some(calibration) = calibration {
283        let light_groups =
284            light_proxy.watch_light_groups().await.context("request initial light groups")?;
285        let led_watcher = LedWatcher::new(light_groups);
286        let (cancelation_tx, cancelation_rx) = oneshot::channel();
287        let light_proxy_receives_initial_response =
288            inspect_status.inspect_node.create_bool("light_proxy_receives_initial_response", false);
289        let brightness_proxy_receives_initial_response = inspect_status
290            .inspect_node
291            .create_bool("brightness_proxy_receives_initial_response", false);
292        let (led_watcher_handle, watcher_task) = led_watcher
293            .handle_light_groups_and_brightness_watch(
294                light_proxy,
295                brightness_proxy,
296                cancelation_rx,
297                light_proxy_receives_initial_response,
298                brightness_proxy_receives_initial_response,
299            );
300        let watcher_task = CancelableTask::new(cancelation_tx, watcher_task);
301        let calibrator = Calibrator::new(calibration, led_watcher_handle);
302        (Some(calibrator), Some(watcher_task))
303    } else {
304        (None, None)
305    };
306    Ok((LightSensorHandler::new(calibrator, configuration, inspect_status), watcher_task))
307}
308
309impl<T> LightSensorHandler<T> {
310    pub fn new(
311        calibrator: impl Into<Option<T>>,
312        configuration: SensorConfiguration,
313        inspect_status: InputHandlerStatus,
314    ) -> Rc<Self> {
315        let calibrator = calibrator.into();
316        let hanging_get = RefCell::new(HangingGet::new_unknown_state(Box::new(
317            |sensor_data: &LightSensorData, responder: SensorWatchResponder| -> bool {
318                if let Err(e) = responder.send(&FidlLightSensorData::from(*sensor_data)) {
319                    log::warn!("Failed to send updated data to client: {e:?}",);
320                }
321                true
322            },
323        ) as NotifyFn));
324        let feature_updates = Arc::new(Mutex::new(CircularBuffer::new(5)));
325        let active_setting =
326            RefCell::new(ActiveSettingState::Uninitialized(configuration.settings));
327        let events_saturated_count =
328            inspect_status.inspect_node.create_uint("events_saturated_count", 0);
329        let clients_connected_count =
330            inspect_status.inspect_node.create_uint("clients_connected_count", 0);
331        inspect_status.inspect_node.record_lazy_child("recent_feature_events_log", {
332            let feature_updates = Arc::clone(&feature_updates);
333            move || {
334                let feature_updates = Arc::clone(&feature_updates);
335                async move {
336                    let inspector = fuchsia_inspect::Inspector::default();
337                    let feature_updates = feature_updates.lock();
338                    Ok(feature_updates.record_all_lazy_inspect(inspector))
339                }
340                .boxed()
341            }
342        });
343        Rc::new(Self {
344            hanging_get,
345            calibrator,
346            active_setting,
347            rgbc_to_lux_coefs: configuration.rgbc_to_lux_coefficients,
348            si_scaling_factors: configuration.si_scaling_factors,
349            vendor_id: configuration.vendor_id,
350            product_id: configuration.product_id,
351            inspect_status,
352            events_saturated_count,
353            clients_connected_count,
354            feature_updates,
355        })
356    }
357
358    pub async fn handle_light_sensor_request_stream(
359        self: &Rc<Self>,
360        mut stream: SensorRequestStream,
361    ) -> Result<(), Error> {
362        let subscriber = self.hanging_get.borrow_mut().new_subscriber();
363        self.clients_connected_count.add(1);
364        while let Some(request) =
365            stream.try_next().await.context("Error handling light sensor request stream")?
366        {
367            match request {
368                SensorRequest::Watch { responder } => {
369                    subscriber
370                        .register(responder)
371                        .context("registering responder for Watch call")?;
372                }
373            }
374        }
375        self.clients_connected_count.subtract(1);
376        Ok(())
377    }
378
379    /// Calculates the lux of a reading.
380    fn calculate_lux(&self, reading: Rgbc<f32>) -> f32 {
381        Rgbc::multi_map(reading, self.rgbc_to_lux_coefs, |reading, coef| reading * coef)
382            .fold(0.0, |lux, c| lux + c)
383    }
384}
385
386/// Normalize raw sensor counts.
387///
388/// I.e. values being read in dark lighting will be returned as their original value,
389/// but values in the brighter lighting will be returned larger, as a reading within the true
390/// output range of the light sensor.
391fn process_reading(reading: Rgbc<u16>, initial_setting: AdjustmentSetting) -> Rgbc<f32> {
392    let gain_bias = MAX_GAIN / initial_setting.gain as u32;
393
394    reading.map(|v| {
395        div_round_closest(v as u32 * gain_bias * MAX_ATIME, num_cycles(initial_setting.atime))
396            as f32
397    })
398}
399
400#[derive(Debug)]
401enum SaturatedError {
402    Saturated,
403    Anyhow(Error),
404}
405
406impl From<Error> for SaturatedError {
407    fn from(value: Error) -> Self {
408        Self::Anyhow(value)
409    }
410}
411
412impl<T> LightSensorHandler<T>
413where
414    T: Calibrate,
415{
416    async fn get_calibrated_data(
417        &self,
418        reading: Rgbc<u16>,
419        device_proxy: &fidl_next::Client<fidl_next_fuchsia_input_report::InputDevice, Transport>,
420    ) -> Result<LightReading, SaturatedError> {
421        // Update the sensor after the active setting has been used for calculations, since it may
422        // change after this call.
423        let (initial_setting, pulled_up) = {
424            let mut active_setting_state = self.active_setting.borrow_mut();
425            let track_feature_update = |feature_event| async move {
426                self.feature_updates.lock().push(feature_event);
427            };
428            match &mut *active_setting_state {
429                ActiveSettingState::Uninitialized(adjustment_settings) => {
430                    let active_setting = ActiveSetting::new(std::mem::take(adjustment_settings), 0);
431                    if let Err(e) =
432                        active_setting.update_device(device_proxy, track_feature_update).await
433                    {
434                        log::error!(
435                            "Unable to set initial settings for sensor. Falling back \
436                                        to static setting: {e:?}"
437                        );
438                        // Switch to a static state because this sensor cannot change its settings.
439                        let setting = active_setting.settings[0];
440                        *active_setting_state = ActiveSettingState::Static(setting);
441                        (setting, false)
442                    } else {
443                        // Initial setting is unset. Reading cannot be properly adjusted, so
444                        // override the current settings on the device and report a saturated error
445                        // so this reading is not sent to any clients.
446                        *active_setting_state = ActiveSettingState::Initialized(active_setting);
447                        return Err(SaturatedError::Saturated);
448                    }
449                }
450                ActiveSettingState::Initialized(active_setting) => {
451                    let initial_setting = active_setting.active_setting();
452                    let pulled_up = active_setting
453                        .adjust(reading, device_proxy, track_feature_update)
454                        .await
455                        .map_err(|e| match e {
456                            SaturatedError::Saturated => SaturatedError::Saturated,
457                            SaturatedError::Anyhow(e) => {
458                                SaturatedError::Anyhow(e.context("adjusting active setting"))
459                            }
460                        })?;
461                    (initial_setting, pulled_up)
462                }
463                ActiveSettingState::Static(setting) => (*setting, false),
464            }
465        };
466        let uncalibrated_rgbc = process_reading(reading, initial_setting);
467        let rgbc = self
468            .calibrator
469            .as_ref()
470            .map(|calibrator| calibrator.calibrate(uncalibrated_rgbc))
471            .unwrap_or(uncalibrated_rgbc);
472
473        let si_rgbc = (self.si_scaling_factors * rgbc).map(|c| c / ADC_SCALING_FACTOR);
474        let lux = self.calculate_lux(si_rgbc);
475        let cct = correlated_color_temperature(si_rgbc);
476        // Only return saturation error if the cct is invalid and the sensor was also adjusted. If
477        // only the cct is invalid, it means the sensor is not undersaturated but reading
478        // pitch-black at the highest sensitivity.
479        if cct.is_none() && pulled_up {
480            return Err(SaturatedError::Saturated);
481        }
482
483        let rgbc = uncalibrated_rgbc.map(|c| c as f32 / TRANSITION_SCALING_FACTOR);
484        Ok(LightReading { rgbc, si_rgbc, is_calibrated: self.calibrator.is_some(), lux, cct })
485    }
486}
487
488/// Converts atime values to microseconds.
489fn to_us(atime: u32) -> u32 {
490    num_cycles(atime) * MIN_TIME_STEP_US
491}
492
493/// Divides n by d, rounding up.
494fn div_round_up(n: u32, d: u32) -> u32 {
495    (n + d - 1) / d
496}
497
498/// Divides n by d, rounding to the closest value.
499fn div_round_closest(n: u32, d: u32) -> u32 {
500    (n + (d / 2)) / d
501}
502
503// These values are defined in //src/devices/light-sensor/ams-light/tcs3400.cc
504const MAX_SATURATION_RED: u16 = 21_067;
505const MAX_SATURATION_GREEN: u16 = 20_395;
506const MAX_SATURATION_BLUE: u16 = 20_939;
507const MAX_SATURATION_CLEAR: u16 = 65_085;
508
509// TODO(https://fxbug.dev/42143847) Update when sensor reports include saturation
510// information.
511fn saturated(reading: Rgbc<u16>) -> bool {
512    reading.red == MAX_SATURATION_RED
513        && reading.green == MAX_SATURATION_GREEN
514        && reading.blue == MAX_SATURATION_BLUE
515        && reading.clear == MAX_SATURATION_CLEAR
516}
517
518// See http://ams.com/eng/content/view/download/145158 for the detail of the
519// following calculation.
520/// Returns `None` when the reading is under or over saturated.
521fn correlated_color_temperature(reading: Rgbc<f32>) -> Option<f32> {
522    // TODO(https://fxbug.dev/42072871): Move color_temp calculation out of common code
523    let big_x = -0.7687 * reading.red + 9.7764 * reading.green + -7.4164 * reading.blue;
524    let big_y = -1.7475 * reading.red + 9.9603 * reading.green + -5.6755 * reading.blue;
525    let big_z = -3.6709 * reading.red + 4.8637 * reading.green + 4.3682 * reading.blue;
526
527    let div = big_x + big_y + big_z;
528    if div.abs() < f32::EPSILON {
529        return None;
530    }
531
532    let x = big_x / div;
533    let y = big_y / div;
534    let n = (x - 0.3320) / (0.1858 - y);
535    Some(449.0 * n.powi(3) + 3525.0 * n.powi(2) + 6823.3 * n + 5520.33)
536}
537
538impl<T> Handler for LightSensorHandler<T>
539where
540    T: Calibrate + 'static,
541{
542    fn set_handler_healthy(self: std::rc::Rc<Self>) {
543        self.inspect_status.health_node.borrow_mut().set_ok();
544    }
545
546    fn set_handler_unhealthy(self: std::rc::Rc<Self>, msg: &str) {
547        self.inspect_status.health_node.borrow_mut().set_unhealthy(msg);
548    }
549
550    fn get_name(&self) -> &'static str {
551        "LightSensorHandler"
552    }
553
554    fn interest(&self) -> Vec<InputEventType> {
555        vec![InputEventType::LightSensor]
556    }
557}
558
559#[async_trait(?Send)]
560impl<T> InputHandler for LightSensorHandler<T>
561where
562    T: Calibrate + 'static,
563{
564    async fn handle_input_event(self: Rc<Self>, mut input_event: InputEvent) -> Vec<InputEvent> {
565        fuchsia_trace::duration!("input", "light_sensor_handler");
566        if let InputEvent {
567            device_event: InputDeviceEvent::LightSensor(ref light_sensor_event),
568            device_descriptor: InputDeviceDescriptor::LightSensor(ref light_sensor_descriptor),
569            event_time,
570            handled: Handled::No,
571            trace_id: _,
572        } = input_event
573        {
574            fuchsia_trace::duration!("input", "light_sensor_handler[processing]");
575            self.inspect_status.count_received_event(&event_time);
576            // Validate descriptor matches.
577            if !(light_sensor_descriptor.vendor_id == self.vendor_id
578                && light_sensor_descriptor.product_id == self.product_id)
579            {
580                // Don't handle the event.
581                log::warn!(
582                    "Unexpected device in light sensor handler: {:?}",
583                    light_sensor_descriptor,
584                );
585                return vec![input_event];
586            }
587            let LightReading { rgbc, si_rgbc, is_calibrated, lux, cct } = match self
588                .get_calibrated_data(light_sensor_event.rgbc, &light_sensor_event.device_proxy)
589                .await
590            {
591                Ok(data) => data,
592                Err(SaturatedError::Saturated) => {
593                    // Saturated data is not useful for clients so we do not publish data.
594                    self.events_saturated_count.add(1);
595                    return vec![input_event];
596                }
597                Err(SaturatedError::Anyhow(e)) => {
598                    log::warn!("Failed to get light sensor readings: {e:?}");
599                    // Don't handle the event.
600                    return vec![input_event];
601                }
602            };
603            let publisher = self.hanging_get.borrow_mut().new_publisher();
604            publisher.set(LightSensorData {
605                rgbc,
606                si_rgbc,
607                is_calibrated,
608                calculated_lux: lux,
609                correlated_color_temperature: cct,
610            });
611            input_event.handled = Handled::Yes;
612            self.inspect_status.count_handled_event();
613        }
614        vec![input_event]
615    }
616}
617
618#[derive(Copy, Clone, PartialEq)]
619struct LightSensorData {
620    rgbc: Rgbc<f32>,
621    si_rgbc: Rgbc<f32>,
622    is_calibrated: bool,
623    calculated_lux: f32,
624    correlated_color_temperature: Option<f32>,
625}
626
627impl From<LightSensorData> for FidlLightSensorData {
628    fn from(data: LightSensorData) -> Self {
629        Self {
630            rgbc: Some(FidlRgbc::from(data.rgbc)),
631            si_rgbc: Some(FidlRgbc::from(data.si_rgbc)),
632            is_calibrated: Some(data.is_calibrated),
633            calculated_lux: Some(data.calculated_lux),
634            correlated_color_temperature: data.correlated_color_temperature,
635            ..Default::default()
636        }
637    }
638}
639
640impl From<Rgbc<f32>> for FidlRgbc {
641    fn from(rgbc: Rgbc<f32>) -> Self {
642        Self {
643            red_intensity: rgbc.red,
644            green_intensity: rgbc.green,
645            blue_intensity: rgbc.blue,
646            clear_intensity: rgbc.clear,
647        }
648    }
649}
650
651#[cfg(test)]
652mod light_sensor_handler_tests;