/* * Copyright (c) 2023 Fancy Code. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "LedManager.h" #include "ILog.h" std::shared_ptr &LedManager::GetInstance(std::shared_ptr *impl) { static auto instance = std::make_shared(); if (impl) { if (instance.use_count() == 1) { LogInfo("Instance changed succeed.\n"); instance = *impl; } else { LogError("Can't changing the instance becase of using by some one.\n"); } } return instance; } void LedManager::Init(void) { std::map> allLeds; IHalCpp::GetInstance()->GetAllLeds(allLeds); LedConversion(allLeds); } void LedManager::UnInit(void) { StopTimer(); mMutex.lock(); for (auto &iter : mAllLedHal) { iter.second->DeleteAllState(); } mMutex.unlock(); mAllLedHal.clear(); } void LedManager::Timer(void) { mTimerRuning = true; std::map>::iterator iter; while (mTimerRuning) { mMutex.lock(); for (iter = mAllLedHal.begin(); iter != mAllLedHal.end(); ++iter) { std::shared_ptr ledHal = iter->second; ledHal->CheckState(LED_STATE_CHECK_PERIOD_MS); } mMutex.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(LED_STATE_CHECK_PERIOD_MS)); } } void LedManager::ControlLed(const std::string &ledName, std::shared_ptr &control) { std::lock_guard locker(mMutex); std::shared_ptr singleControl = std::dynamic_pointer_cast(control); if (!singleControl) { LogError("led can't be controled.\n"); return; } auto iter = mAllLedHal.find(ledName); if (iter == mAllLedHal.end()) { LogError("Can't find led [%s].\n", ledName.c_str()); return; } mAllLedHal[ledName]->AddLedState(singleControl); } void LedManager::StartTimer(void) { auto timerThread = [](std::shared_ptr timer) { LogInfo("Led timer started.\n"); timer->Timer(); }; mTimer = std::thread(timerThread, shared_from_this()); } void LedManager::StopTimer(void) { mTimerRuning = false; if (mTimer.joinable()) { mTimer.join(); } } void LedManager::LedConversion(std::map> &ledHal) { std::map>::iterator iter; for (iter = ledHal.begin(); iter != ledHal.end(); ++iter) { std::shared_ptr led = std::dynamic_pointer_cast(iter->second); if (led) { LogInfo("Get led [%s].\n", iter->first.c_str()); mAllLedHal[iter->first] = led; } else { LogWarning("Missing something.\n"); } } }