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 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
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 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 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
386fn 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 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 let setting = active_setting.settings[0];
440 *active_setting_state = ActiveSettingState::Static(setting);
441 (setting, false)
442 } else {
443 *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 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
488fn to_us(atime: u32) -> u32 {
490 num_cycles(atime) * MIN_TIME_STEP_US
491}
492
493fn div_round_up(n: u32, d: u32) -> u32 {
495 (n + d - 1) / d
496}
497
498fn div_round_closest(n: u32, d: u32) -> u32 {
500 (n + (d / 2)) / d
501}
502
503const 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
509fn 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
518fn correlated_color_temperature(reading: Rgbc<f32>) -> Option<f32> {
522 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 if !(light_sensor_descriptor.vendor_id == self.vendor_id
578 && light_sensor_descriptor.product_id == self.product_id)
579 {
580 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 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 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;