1 /*
2  * Copyright (C) 2018 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 #include "defines.h"
17 #include "eventprovider.h"
18 #include <algorithm>
19 #include <utils/Log.h>
20 
21 using namespace com::android::car::keventreader;
22 
EventProviderImpl(EventGatherer && g)23 EventProviderImpl::EventProviderImpl(EventGatherer&& g) : mGatherer(std::move(g)) {}
24 
startLoop()25 std::thread EventProviderImpl::startLoop() {
26     auto t = std::thread( [this] () -> void {
27         while(true) {
28             auto events = mGatherer.read();
29             {
30                 std::scoped_lock lock(mMutex);
31                 for (auto&& cb : mCallbacks) {
32                     for (const auto& event : events) {
33                         cb->onEvent(event);
34                     }
35                 }
36             }
37         }
38     });
39     return t;
40 }
41 
registerCallback(const sp<IEventCallback> & cb)42 Status EventProviderImpl::registerCallback(const sp<IEventCallback>& cb) {
43     std::scoped_lock lock(mMutex);
44     mCallbacks.push_back(cb);
45     return Status::ok();
46 }
47 
unregisterCallback(const sp<IEventCallback> & cb)48 Status EventProviderImpl::unregisterCallback(const sp<IEventCallback>& cb) {
49     std::scoped_lock lock(mMutex);
50     std::remove(mCallbacks.begin(), mCallbacks.end(), cb);
51     return Status::ok();
52 }
53