3 * Copyright (c) 2020 Project CHIP Authors
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
19 #include "LightingManager.h"
21 #include "AppConfig.h"
23 #include <drivers/pwm.h>
24 #include <logging/log.h>
27 LOG_MODULE_DECLARE(app);
29 LightingManager LightingManager::sLight;
31 int LightingManager::Init(const device * pwmDevice, uint32_t pwmChannel)
33 // We use a gpioPin instead of a LEDWidget here because we want to use PWM
34 // and other features instead of just on/off.
38 mPwmDevice = pwmDevice;
39 mPwmChannel = pwmChannel;
41 if (!device_is_ready(mPwmDevice))
43 LOG_ERR("PWM device %s is not ready", mPwmDevice->name);
51 void LightingManager::SetCallbacks(LightingCallback_fn aActionInitiated_CB, LightingCallback_fn aActionCompleted_CB)
53 mActionInitiated_CB = aActionInitiated_CB;
54 mActionCompleted_CB = aActionCompleted_CB;
57 bool LightingManager::InitiateAction(Action_t aAction, int32_t aActor, uint8_t size, uint8_t * value)
59 // TODO: this function is called InitiateAction because we want to implement some features such as ramping up here.
60 bool action_initiated = false;
63 // Initiate On/Off Action only when the previous one is complete.
64 if (mState == kState_Off && aAction == ON_ACTION)
66 action_initiated = true;
67 new_state = kState_On;
69 else if (mState == kState_On && aAction == OFF_ACTION)
71 action_initiated = true;
72 new_state = kState_Off;
74 else if (aAction == LEVEL_ACTION && *value != mLevel)
76 action_initiated = true;
79 new_state = kState_Off;
83 new_state = kState_On;
89 if (mActionInitiated_CB)
91 mActionInitiated_CB(aAction, aActor);
94 if (aAction == ON_ACTION || aAction == OFF_ACTION)
96 Set(new_state == kState_On);
98 else if (aAction == LEVEL_ACTION)
103 if (mActionCompleted_CB)
105 mActionCompleted_CB(aAction, aActor);
109 return action_initiated;
112 void LightingManager::SetLevel(uint8_t aLevel)
114 LOG_INF("Setting brightness level to %u", aLevel);
119 void LightingManager::Set(bool aOn)
121 mState = aOn ? kState_On : kState_Off;
125 void LightingManager::UpdateLight()
127 constexpr uint32_t kPwmWidthUs = 20000u;
128 const uint8_t level = mState == kState_On ? mLevel : 0;
129 pwm_pin_set_usec(mPwmDevice, mPwmChannel, kPwmWidthUs, kPwmWidthUs * level / kMaxLevel, 0);