1 /* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef BATTERY_THREAD_H 17 #define BATTERY_THREAD_H 18 19 #include <map> 20 #include <memory> 21 #include <refbase.h> 22 #include <thread> 23 #include <vector> 24 #include "power_supply_provider.h" 25 #include "v2_0/ibattery_callback.h" 26 27 namespace OHOS { 28 namespace HDI { 29 namespace Battery { 30 namespace V2_0 { 31 using UeventMap = std::map<std::string, std::vector<std::pair<std::string, std::string>>>; 32 enum EventType { 33 EVENT_UEVENT_FD, 34 EVENT_TIMER_FD, 35 }; 36 37 class BatteryThread { 38 public: 39 virtual ~BatteryThread(); 40 41 void StartThread(void* service); 42 void InitCallback(const sptr<OHOS::HDI::Battery::V2_0::IBatteryCallback>& callback); 43 protected: 44 void LoopingThreadEntry(void* arg); 45 virtual void Run(void* service); 46 virtual void UpdateBatteryInfo(void* service, const std::string& powerUevent); HandleStates()47 virtual void HandleStates() {} 48 virtual int32_t UpdateWaitInterval(); 49 void UpdateEpollInterval(int32_t chargeState); CycleMatters()50 virtual void CycleMatters() {} 51 private: 52 int32_t OpenUeventSocket(); 53 bool MatchPowerUevent(const char* msg, std::string& powerUevent); 54 bool CheckPowerUevent(const char* msg, std::string& powerUevent); 55 int32_t Init([[maybe_unused]]void* service); 56 int32_t InitUevent(); 57 void UeventCallback(void* service); 58 void SetTimerInterval(int32_t interval); 59 int32_t RegisterCallback(int32_t fd, EventType et); 60 static constexpr int32_t INVALID_FD = -1; 61 int32_t ueventFd_ = INVALID_FD; 62 int32_t epFd_ = INVALID_FD; 63 int32_t epollInterval_ = -1; 64 using Callback = std::function<void(BatteryThread*, void*)>; 65 std::map<int32_t, Callback> callbacks_; 66 std::unique_ptr<PowerSupplyProvider> provider_ = nullptr; 67 UeventMap powerUeventMap_; 68 std::unique_ptr<std::thread> batteryThread_ {nullptr}; 69 std::atomic_bool isRunning_ {true}; 70 }; 71 } // namespace V2_0 72 } // namespace Battery 73 } // namespace HDI 74 } // namespace OHOS 75 76 #endif // BATTERY_THREAD_H 77