1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 //! This module implements the ILights AIDL interface.
17 
18 use std::collections::HashMap;
19 use std::sync::Mutex;
20 
21 use log::info;
22 
23 use android_hardware_light::aidl::android::hardware::light::{
24     HwLight::HwLight, HwLightState::HwLightState, ILights::ILights, LightType::LightType,
25 };
26 
27 use binder::{ExceptionCode, Interface, Status};
28 
29 struct Light {
30     hw_light: HwLight,
31     state: HwLightState,
32 }
33 
34 const NUM_DEFAULT_LIGHTS: i32 = 3;
35 
36 /// Defined so we can implement the ILights AIDL interface.
37 pub struct LightsService {
38     lights: Mutex<HashMap<i32, Light>>,
39 }
40 
41 impl Interface for LightsService {}
42 
43 impl LightsService {
new(hw_lights: impl IntoIterator<Item = HwLight>) -> Self44     fn new(hw_lights: impl IntoIterator<Item = HwLight>) -> Self {
45         let mut lights_map = HashMap::new();
46 
47         for hw_light in hw_lights {
48             lights_map.insert(hw_light.id, Light { hw_light, state: Default::default() });
49         }
50 
51         Self { lights: Mutex::new(lights_map) }
52     }
53 }
54 
55 impl Default for LightsService {
default() -> Self56     fn default() -> Self {
57         let id_mapping_closure =
58             |light_id| HwLight { id: light_id, ordinal: light_id, r#type: LightType::BACKLIGHT };
59 
60         Self::new((1..=NUM_DEFAULT_LIGHTS).map(id_mapping_closure))
61     }
62 }
63 
64 impl ILights for LightsService {
setLightState(&self, id: i32, state: &HwLightState) -> binder::Result<()>65     fn setLightState(&self, id: i32, state: &HwLightState) -> binder::Result<()> {
66         info!("Lights setting state for id={} to color {:x}", id, state.color);
67 
68         if let Some(light) = self.lights.lock().unwrap().get_mut(&id) {
69             light.state = *state;
70             Ok(())
71         } else {
72             Err(Status::new_exception(ExceptionCode::UNSUPPORTED_OPERATION, None))
73         }
74     }
75 
getLights(&self) -> binder::Result<Vec<HwLight>>76     fn getLights(&self) -> binder::Result<Vec<HwLight>> {
77         info!("Lights reporting supported lights");
78         Ok(self.lights.lock().unwrap().values().map(|light| light.hw_light).collect())
79     }
80 }
81