1use 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 futures::channel::oneshot;
28use futures::lock::Mutex;
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
37const MIN_TIME_STEP_US: u32 = 2780;
40const MAX_GAIN: u32 = 64;
42const MAX_COUNT_PER_CYCLE: u32 = 1024;
44const MAX_SATURATION: u32 = u16::MAX as u32;
46const MAX_ATIME: u32 = 256;
47const ADC_SCALING_FACTOR: f32 = 64.0 * 256.0;
49const GAIN_UP_MARGIN_DIVISOR: u32 = 10;
51const 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 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 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 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 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 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 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 inspect_status: InputHandlerStatus,
248 feature_updates: Arc<Mutex<CircularBuffer<FeatureEvent>>>,
249
250 events_saturated_count: fuchsia_inspect::UintProperty,
257 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 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 Ok(feature_updates.lock().await.record_all_lazy_inspect(inspector))
338 }
339 .boxed()
340 }
341 });
342 Rc::new(Self {
343 hanging_get,
344 calibrator,
345 active_setting,
346 rgbc_to_lux_coefs: configuration.rgbc_to_lux_coefficients,
347 si_scaling_factors: configuration.si_scaling_factors,
348 vendor_id: configuration.vendor_id,
349 product_id: configuration.product_id,
350 inspect_status,
351 events_saturated_count,
352 clients_connected_count,
353 feature_updates,
354 })
355 }
356
357 pub async fn handle_light_sensor_request_stream(
358 self: &Rc<Self>,
359 mut stream: SensorRequestStream,
360 ) -> Result<(), Error> {
361 let subscriber = self.hanging_get.borrow_mut().new_subscriber();
362 self.clients_connected_count.add(1);
363 while let Some(request) =
364 stream.try_next().await.context("Error handling light sensor request stream")?
365 {
366 match request {
367 SensorRequest::Watch { responder } => {
368 subscriber
369 .register(responder)
370 .context("registering responder for Watch call")?;
371 }
372 }
373 }
374 self.clients_connected_count.subtract(1);
375 Ok(())
376 }
377
378 fn calculate_lux(&self, reading: Rgbc<f32>) -> f32 {
380 Rgbc::multi_map(reading, self.rgbc_to_lux_coefs, |reading, coef| reading * coef)
381 .fold(0.0, |lux, c| lux + c)
382 }
383}
384
385fn process_reading(reading: Rgbc<u16>, initial_setting: AdjustmentSetting) -> Rgbc<f32> {
391 let gain_bias = MAX_GAIN / initial_setting.gain as u32;
392
393 reading.map(|v| {
394 div_round_closest(v as u32 * gain_bias * MAX_ATIME, num_cycles(initial_setting.atime))
395 as f32
396 })
397}
398
399#[derive(Debug)]
400enum SaturatedError {
401 Saturated,
402 Anyhow(Error),
403}
404
405impl From<Error> for SaturatedError {
406 fn from(value: Error) -> Self {
407 Self::Anyhow(value)
408 }
409}
410
411impl<T> LightSensorHandler<T>
412where
413 T: Calibrate,
414{
415 async fn get_calibrated_data(
416 &self,
417 reading: Rgbc<u16>,
418 device_proxy: &fidl_next::Client<fidl_next_fuchsia_input_report::InputDevice, Transport>,
419 ) -> Result<LightReading, SaturatedError> {
420 let (initial_setting, pulled_up) = {
423 let mut active_setting_state = self.active_setting.borrow_mut();
424 let track_feature_update = |feature_event| async move {
425 self.feature_updates.lock().await.push(feature_event);
426 };
427 match &mut *active_setting_state {
428 ActiveSettingState::Uninitialized(adjustment_settings) => {
429 let active_setting = ActiveSetting::new(std::mem::take(adjustment_settings), 0);
430 if let Err(e) =
431 active_setting.update_device(device_proxy, track_feature_update).await
432 {
433 log::error!(
434 "Unable to set initial settings for sensor. Falling back \
435 to static setting: {e:?}"
436 );
437 let setting = active_setting.settings[0];
439 *active_setting_state = ActiveSettingState::Static(setting);
440 (setting, false)
441 } else {
442 *active_setting_state = ActiveSettingState::Initialized(active_setting);
446 return Err(SaturatedError::Saturated);
447 }
448 }
449 ActiveSettingState::Initialized(active_setting) => {
450 let initial_setting = active_setting.active_setting();
451 let pulled_up = active_setting
452 .adjust(reading, device_proxy, track_feature_update)
453 .await
454 .map_err(|e| match e {
455 SaturatedError::Saturated => SaturatedError::Saturated,
456 SaturatedError::Anyhow(e) => {
457 SaturatedError::Anyhow(e.context("adjusting active setting"))
458 }
459 })?;
460 (initial_setting, pulled_up)
461 }
462 ActiveSettingState::Static(setting) => (*setting, false),
463 }
464 };
465 let uncalibrated_rgbc = process_reading(reading, initial_setting);
466 let rgbc = self
467 .calibrator
468 .as_ref()
469 .map(|calibrator| calibrator.calibrate(uncalibrated_rgbc))
470 .unwrap_or(uncalibrated_rgbc);
471
472 let si_rgbc = (self.si_scaling_factors * rgbc).map(|c| c / ADC_SCALING_FACTOR);
473 let lux = self.calculate_lux(si_rgbc);
474 let cct = correlated_color_temperature(si_rgbc);
475 if cct.is_none() && pulled_up {
479 return Err(SaturatedError::Saturated);
480 }
481
482 let rgbc = uncalibrated_rgbc.map(|c| c as f32 / TRANSITION_SCALING_FACTOR);
483 Ok(LightReading { rgbc, si_rgbc, is_calibrated: self.calibrator.is_some(), lux, cct })
484 }
485}
486
487fn to_us(atime: u32) -> u32 {
489 num_cycles(atime) * MIN_TIME_STEP_US
490}
491
492fn div_round_up(n: u32, d: u32) -> u32 {
494 (n + d - 1) / d
495}
496
497fn div_round_closest(n: u32, d: u32) -> u32 {
499 (n + (d / 2)) / d
500}
501
502const MAX_SATURATION_RED: u16 = 21_067;
504const MAX_SATURATION_GREEN: u16 = 20_395;
505const MAX_SATURATION_BLUE: u16 = 20_939;
506const MAX_SATURATION_CLEAR: u16 = 65_085;
507
508fn saturated(reading: Rgbc<u16>) -> bool {
511 reading.red == MAX_SATURATION_RED
512 && reading.green == MAX_SATURATION_GREEN
513 && reading.blue == MAX_SATURATION_BLUE
514 && reading.clear == MAX_SATURATION_CLEAR
515}
516
517fn correlated_color_temperature(reading: Rgbc<f32>) -> Option<f32> {
521 let big_x = -0.7687 * reading.red + 9.7764 * reading.green + -7.4164 * reading.blue;
523 let big_y = -1.7475 * reading.red + 9.9603 * reading.green + -5.6755 * reading.blue;
524 let big_z = -3.6709 * reading.red + 4.8637 * reading.green + 4.3682 * reading.blue;
525
526 let div = big_x + big_y + big_z;
527 if div.abs() < f32::EPSILON {
528 return None;
529 }
530
531 let x = big_x / div;
532 let y = big_y / div;
533 let n = (x - 0.3320) / (0.1858 - y);
534 Some(449.0 * n.powi(3) + 3525.0 * n.powi(2) + 6823.3 * n + 5520.33)
535}
536
537impl<T> Handler for LightSensorHandler<T>
538where
539 T: Calibrate + 'static,
540{
541 fn set_handler_healthy(self: std::rc::Rc<Self>) {
542 self.inspect_status.health_node.borrow_mut().set_ok();
543 }
544
545 fn set_handler_unhealthy(self: std::rc::Rc<Self>, msg: &str) {
546 self.inspect_status.health_node.borrow_mut().set_unhealthy(msg);
547 }
548
549 fn get_name(&self) -> &'static str {
550 "LightSensorHandler"
551 }
552
553 fn interest(&self) -> Vec<InputEventType> {
554 vec![InputEventType::LightSensor]
555 }
556}
557
558#[async_trait(?Send)]
559impl<T> InputHandler for LightSensorHandler<T>
560where
561 T: Calibrate + 'static,
562{
563 async fn handle_input_event(self: Rc<Self>, mut input_event: InputEvent) -> Vec<InputEvent> {
564 fuchsia_trace::duration!("input", "light_sensor_handler");
565 if let InputEvent {
566 device_event: InputDeviceEvent::LightSensor(ref light_sensor_event),
567 device_descriptor: InputDeviceDescriptor::LightSensor(ref light_sensor_descriptor),
568 event_time,
569 handled: Handled::No,
570 trace_id: _,
571 } = input_event
572 {
573 fuchsia_trace::duration!("input", "light_sensor_handler[processing]");
574 self.inspect_status.count_received_event(&event_time);
575 if !(light_sensor_descriptor.vendor_id == self.vendor_id
577 && light_sensor_descriptor.product_id == self.product_id)
578 {
579 log::warn!(
581 "Unexpected device in light sensor handler: {:?}",
582 light_sensor_descriptor,
583 );
584 return vec![input_event];
585 }
586 let LightReading { rgbc, si_rgbc, is_calibrated, lux, cct } = match self
587 .get_calibrated_data(light_sensor_event.rgbc, &light_sensor_event.device_proxy)
588 .await
589 {
590 Ok(data) => data,
591 Err(SaturatedError::Saturated) => {
592 self.events_saturated_count.add(1);
594 return vec![input_event];
595 }
596 Err(SaturatedError::Anyhow(e)) => {
597 log::warn!("Failed to get light sensor readings: {e:?}");
598 return vec![input_event];
600 }
601 };
602 let publisher = self.hanging_get.borrow_mut().new_publisher();
603 publisher.set(LightSensorData {
604 rgbc,
605 si_rgbc,
606 is_calibrated,
607 calculated_lux: lux,
608 correlated_color_temperature: cct,
609 });
610 input_event.handled = Handled::Yes;
611 self.inspect_status.count_handled_event();
612 }
613 vec![input_event]
614 }
615}
616
617#[derive(Copy, Clone, PartialEq)]
618struct LightSensorData {
619 rgbc: Rgbc<f32>,
620 si_rgbc: Rgbc<f32>,
621 is_calibrated: bool,
622 calculated_lux: f32,
623 correlated_color_temperature: Option<f32>,
624}
625
626impl From<LightSensorData> for FidlLightSensorData {
627 fn from(data: LightSensorData) -> Self {
628 Self {
629 rgbc: Some(FidlRgbc::from(data.rgbc)),
630 si_rgbc: Some(FidlRgbc::from(data.si_rgbc)),
631 is_calibrated: Some(data.is_calibrated),
632 calculated_lux: Some(data.calculated_lux),
633 correlated_color_temperature: data.correlated_color_temperature,
634 ..Default::default()
635 }
636 }
637}
638
639impl From<Rgbc<f32>> for FidlRgbc {
640 fn from(rgbc: Rgbc<f32>) -> Self {
641 Self {
642 red_intensity: rgbc.red,
643 green_intensity: rgbc.green,
644 blue_intensity: rgbc.blue,
645 clear_intensity: rgbc.clear,
646 }
647 }
648}
649
650#[cfg(test)]
651mod light_sensor_handler_tests;