blob: 18d03f8bab9fadfd32a00084ca745cec863a6368 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2005 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
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070017#include <assert.h>
18#include <dirent.h>
19#include <errno.h>
20#include <fcntl.h>
21#include <inttypes.h>
Colin Cross5b799302022-10-18 21:52:41 -070022#include <linux/ioctl.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070023#include <memory.h>
24#include <stdint.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +010028#include <sys/capability.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070029#include <sys/epoll.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070030#include <sys/inotify.h>
31#include <sys/ioctl.h>
Kim Low03ea0352020-11-06 12:45:07 -080032#include <sys/stat.h>
33#include <sys/sysmacros.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070034#include <unistd.h>
35
Michael Wrightd02c5b62014-02-10 15:10:22 -080036#define LOG_TAG "EventHub"
37
38// #define LOG_NDEBUG 0
Kim Low03ea0352020-11-06 12:45:07 -080039#include <android-base/file.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080040#include <android-base/stringprintf.h>
Chris Yed3fef462021-03-07 17:10:08 -080041#include <android-base/strings.h>
Philip Quinn39b81682019-01-09 22:20:39 -080042#include <cutils/properties.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080043#include <ftl/enum.h>
Chris Ye8594e192020-07-14 10:34:06 -070044#include <input/KeyCharacterMap.h>
45#include <input/KeyLayoutMap.h>
Prabir Pradhan07525ef2022-10-03 21:51:26 +000046#include <input/PrintTools.h>
Chris Ye8594e192020-07-14 10:34:06 -070047#include <input/VirtualKeyMap.h>
Dan Albert677d87e2014-06-16 17:31:28 -070048#include <openssl/sha.h>
Chris Yed3fef462021-03-07 17:10:08 -080049#include <statslog.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070050#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#include <utils/Log.h>
52#include <utils/Timers.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080053
Chris Ye8594e192020-07-14 10:34:06 -070054#include <filesystem>
Chris Ye3fdbfef2021-01-06 18:45:18 -080055#include <regex>
Prabir Pradhancb42b472022-08-23 16:01:19 +000056#include <utility>
Chris Ye8594e192020-07-14 10:34:06 -070057
58#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080059
Michael Wrightd02c5b62014-02-10 15:10:22 -080060#define INDENT " "
61#define INDENT2 " "
62#define INDENT3 " "
63
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080064using android::base::StringPrintf;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +000065using android::hardware::input::InputDeviceCountryCode;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080066
Michael Wrightd02c5b62014-02-10 15:10:22 -080067namespace android {
68
Dominik Laskowski2f01d772022-03-23 16:01:29 -070069using namespace ftl::flag_operators;
70
Usama Arifb27c8e62021-06-03 16:44:09 +010071static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080072// v4l2 devices go directly into /dev
Usama Arifb27c8e62021-06-03 16:44:09 +010073static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080074
Chris Ye657c2f02021-05-25 16:24:37 -070075static constexpr size_t OBFUSCATED_LENGTH = 8;
76
Chris Ye87143712020-11-10 05:05:58 +000077static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
78static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070079
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -070080static constexpr size_t EVENT_BUFFER_SIZE = 256;
81
Chris Yee2b1e5c2021-03-10 22:45:12 -080082// Mapping for input battery class node IDs lookup.
83// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
84static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
85 {{"capacity", InputBatteryClass::CAPACITY},
86 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
87 {"status", InputBatteryClass::STATUS}};
88
89// Mapping for input battery class node names lookup.
90// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
91static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
92 {{InputBatteryClass::CAPACITY, "capacity"},
93 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
94 {InputBatteryClass::STATUS, "status"}};
95
Kim Low03ea0352020-11-06 12:45:07 -080096// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
97static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
98 {{"Unknown", BATTERY_STATUS_UNKNOWN},
99 {"Charging", BATTERY_STATUS_CHARGING},
100 {"Discharging", BATTERY_STATUS_DISCHARGING},
101 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
102 {"Full", BATTERY_STATUS_FULL}};
103
104// Mapping taken from
105// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
106static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
107 {"Low", 10},
108 {"Normal", 55},
109 {"High", 70},
110 {"Full", 100},
111 {"Unknown", 50}};
112
Chris Ye3fdbfef2021-01-06 18:45:18 -0800113// Mapping for input led class node names lookup.
114// https://www.kernel.org/doc/html/latest/leds/leds-class.html
115static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
116 {{"red", InputLightClass::RED},
117 {"green", InputLightClass::GREEN},
118 {"blue", InputLightClass::BLUE},
119 {"global", InputLightClass::GLOBAL},
120 {"brightness", InputLightClass::BRIGHTNESS},
121 {"multi_index", InputLightClass::MULTI_INDEX},
122 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000123 {"max_brightness", InputLightClass::MAX_BRIGHTNESS},
124 {"kbd_backlight", InputLightClass::KEYBOARD_BACKLIGHT}};
Chris Ye3fdbfef2021-01-06 18:45:18 -0800125
126// Mapping for input multicolor led class node names.
127// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
128static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
129 {{InputLightClass::BRIGHTNESS, "brightness"},
130 {InputLightClass::MULTI_INDEX, "multi_index"},
131 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
132
133// Mapping for light color name and the light color
134const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
135 {"green", LightColor::GREEN},
136 {"blue", LightColor::BLUE}};
137
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100138static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700139 SHA_CTX ctx;
140 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100141 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700142 u_char digest[SHA_DIGEST_LENGTH];
143 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100145 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700146 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100147 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148 }
149 return out;
150}
151
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800152/**
153 * Return true if name matches "v4l-touch*"
154 */
Chris Ye8594e192020-07-14 10:34:06 -0700155static bool isV4lTouchNode(std::string name) {
156 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800157}
158
Philip Quinn39b81682019-01-09 22:20:39 -0800159/**
160 * Returns true if V4L devices should be scanned.
161 *
162 * The system property ro.input.video_enabled can be used to control whether
163 * EventHub scans and opens V4L devices. As V4L does not support multiple
164 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700165 * them.
166 *
167 * Setting this to "false" would prevent any video devices from being discovered and
168 * associated with input devices.
169 *
170 * This property can be used as follows:
171 * 1. To turn off features that are dependent on video device presence.
172 * 2. During testing and development, to allow other clients to read video devices
173 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800174 */
175static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700176 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800177}
178
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800179static nsecs_t processEventTimestamp(const struct input_event& event) {
180 // Use the time specified in the event instead of the current time
181 // so that downstream code can get more accurate estimates of
182 // event dispatch latency from the time the event is enqueued onto
183 // the evdev client buffer.
184 //
185 // The event's timestamp fortuitously uses the same monotonic clock
186 // time base as the rest of Android. The kernel event device driver
187 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
188 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
189 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
190 // system call that also queries ktime_get_ts().
191
Colin Cross5b799302022-10-18 21:52:41 -0700192 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.input_event_sec) +
193 microseconds_to_nanoseconds(event.input_event_usec);
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800194 return inputEventTime;
195}
196
Kim Low03ea0352020-11-06 12:45:07 -0800197/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000198 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800199 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800200static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800201 std::error_code errorCode;
202
203 // Stat the device path to get the major and minor number of the character file
204 struct stat statbuf;
205 if (stat(devicePath, &statbuf) == -1) {
206 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800207 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800208 }
209
210 unsigned int major_num = major(statbuf.st_rdev);
211 unsigned int minor_num = minor(statbuf.st_rdev);
212
213 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
214 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
215 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
216 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
217
218 // Make sure nothing went wrong in call to canonical()
219 if (errorCode) {
220 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
221 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800222 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800223 }
224
225 // Continue to go up a directory until we reach a directory named "input"
226 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
227 sysfsPath = sysfsPath.parent_path();
228 }
229
230 // Then go up one more and you will be at the sysfs root of the device
231 sysfsPath = sysfsPath.parent_path();
232
233 // Make sure we didn't reach root path and that directory actually exists
234 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
235 if (errorCode) {
236 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
237 errorCode.message().c_str());
238 }
239
240 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800241 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800242 }
243
244 return sysfsPath;
245}
246
247/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800248 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800249 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800250static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
251 std::vector<std::filesystem::path> nodes;
252 std::error_code errorCode;
253 auto iter = std::filesystem::directory_iterator(path, errorCode);
254 while (!errorCode && iter != std::filesystem::directory_iterator()) {
255 nodes.push_back(iter->path());
256 iter++;
257 }
258 return nodes;
259}
260
261/**
262 * Returns the list of files under a specified directory in a sysfs path.
263 * Example:
264 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
265 * in the sysfs path.
266 */
267static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
268 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800269 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800270 std::for_each(nodeStr.begin(), nodeStr.end(),
271 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
272 std::vector<std::filesystem::path> nodes;
273 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
274 nodes = allFilesInPath(path / nodeStr);
275 }
276 return nodes;
277}
278
279static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
280 std::filesystem::path path) {
281 std::string indexStr;
282 if (!base::ReadFileToString(path, &indexStr)) {
283 return std::nullopt;
284 }
285
286 // Parse the multi color LED index file, refer to kernel docs
287 // leds/leds-class-multicolor.html
288 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
289 std::smatch results;
290 std::array<LightColor, COLOR_NUM> colors;
291 if (!std::regex_match(indexStr, results, indexPattern)) {
292 return std::nullopt;
293 }
294
295 for (size_t i = 1; i < results.size(); i++) {
296 const auto it = LIGHT_COLORS.find(results[i].str());
297 if (it != LIGHT_COLORS.end()) {
298 // intensities.emplace(it->second, 0);
299 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800300 }
301 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800302 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800303}
304
Prabir Pradhancb42b472022-08-23 16:01:19 +0000305/**
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000306 * Read country code information exposed through the sysfs path.
307 */
308static InputDeviceCountryCode readCountryCodeLocked(const std::filesystem::path& sysfsRootPath) {
309 // Check the sysfs root path
310 int hidCountryCode = static_cast<int>(InputDeviceCountryCode::INVALID);
311 std::string str;
312 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
313 hidCountryCode = std::stoi(str, nullptr, 16);
314 LOG_ALWAYS_FATAL_IF(hidCountryCode > 35 || hidCountryCode < 0,
315 "HID country code should be in range [0, 35]. Found country code "
316 "to be %d",
317 hidCountryCode);
318 }
319
320 return static_cast<InputDeviceCountryCode>(hidCountryCode);
321}
322
323/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000324 * Read information about batteries exposed through the sysfs path.
325 */
326static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
327 const std::filesystem::path& sysfsRootPath) {
328 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
329 int32_t nextBatteryId = 0;
330 // Check if device has any battery.
331 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
332 for (const auto& nodePath : paths) {
333 RawBatteryInfo info;
334 info.id = ++nextBatteryId;
335 info.path = nodePath;
336 info.name = nodePath.filename();
337
338 // Scan the path for all the files
339 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
340 const auto& files = allFilesInPath(nodePath);
341 for (const auto& file : files) {
342 const auto it = BATTERY_CLASSES.find(file.filename().string());
343 if (it != BATTERY_CLASSES.end()) {
344 info.flags |= it->second;
345 }
346 }
347 batteryInfos.insert_or_assign(info.id, info);
348 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
349 }
350 return batteryInfos;
351}
352
353/**
354 * Read information about lights exposed through the sysfs path.
355 */
356static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
357 const std::filesystem::path& sysfsRootPath) {
358 std::unordered_map<int32_t, RawLightInfo> lightInfos;
359 int32_t nextLightId = 0;
360 // Check if device has any lights.
361 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
362 for (const auto& nodePath : paths) {
363 RawLightInfo info;
364 info.id = ++nextLightId;
365 info.path = nodePath;
366 info.name = nodePath.filename();
367 info.maxBrightness = std::nullopt;
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000368
369 // Light name should follow the naming pattern <name>:<color>:<function>
370 // Refer kernel docs /leds/leds-class.html for valid supported LED names.
371 std::regex indexPattern("([a-zA-Z0-9_.:]*:)?([a-zA-Z0-9_.]*):([a-zA-Z0-9_.]*)");
372 std::smatch results;
373
374 if (std::regex_match(info.name, results, indexPattern)) {
375 // regex_match will return full match at index 0 and <name> at index 1. For RawLightInfo
376 // we only care about sections <color> and <function> which will be at index 2 and 3.
377 for (int i = 2; i <= 3; i++) {
378 const auto it = LIGHT_CLASSES.find(results.str(i));
379 if (it != LIGHT_CLASSES.end()) {
380 info.flags |= it->second;
381 }
Prabir Pradhancb42b472022-08-23 16:01:19 +0000382 }
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000383
384 // Set name of the raw light to <function> which represents playerIDs for LEDs that
385 // turn on/off based on the current player ID (Refer to PeripheralController.cpp for
386 // player ID logic)
387 info.name = results.str(3);
Prabir Pradhancb42b472022-08-23 16:01:19 +0000388 }
389 // Scan the path for all the files
390 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
391 const auto& files = allFilesInPath(nodePath);
392 for (const auto& file : files) {
393 const auto it = LIGHT_CLASSES.find(file.filename().string());
394 if (it != LIGHT_CLASSES.end()) {
395 info.flags |= it->second;
396 // If the node has maximum brightness, read it
397 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
398 std::string str;
399 if (base::ReadFileToString(file, &str)) {
400 info.maxBrightness = std::stoi(str);
401 }
402 }
403 }
404 }
405 lightInfos.insert_or_assign(info.id, info);
406 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
407 }
408 return lightInfos;
409}
410
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411// --- Global Functions ---
412
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700413ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
414 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800415 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700416 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800417 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700418 case ABS_X:
419 case ABS_Y:
420 case ABS_PRESSURE:
421 case ABS_TOOL_WIDTH:
422 case ABS_DISTANCE:
423 case ABS_TILT_X:
424 case ABS_TILT_Y:
425 case ABS_MT_SLOT:
426 case ABS_MT_TOUCH_MAJOR:
427 case ABS_MT_TOUCH_MINOR:
428 case ABS_MT_WIDTH_MAJOR:
429 case ABS_MT_WIDTH_MINOR:
430 case ABS_MT_ORIENTATION:
431 case ABS_MT_POSITION_X:
432 case ABS_MT_POSITION_Y:
433 case ABS_MT_TOOL_TYPE:
434 case ABS_MT_BLOB_ID:
435 case ABS_MT_TRACKING_ID:
436 case ABS_MT_PRESSURE:
437 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700438 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800439 }
440 }
441
Chris Yef59a2f42020-10-16 12:55:26 -0700442 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
443 switch (axis) {
444 case ABS_X:
445 case ABS_Y:
446 case ABS_Z:
447 case ABS_RX:
448 case ABS_RY:
449 case ABS_RZ:
450 return InputDeviceClass::SENSOR;
451 }
452 }
453
Michael Wright842500e2015-03-13 17:32:02 -0700454 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700455 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700456 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700457 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700458 }
459 }
460
Michael Wrightd02c5b62014-02-10 15:10:22 -0800461 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700462 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800463}
464
465// --- EventHub::Device ---
466
Prabir Pradhancb42b472022-08-23 16:01:19 +0000467EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
468 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700469 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700470 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000471 path(std::move(path)),
472 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700473 classes(0),
474 configuration(nullptr),
475 virtualKeyMap(nullptr),
476 ffEffectPlaying(false),
477 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000478 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700479 controllerNumber(0),
480 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700481 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800482
483EventHub::Device::~Device() {
484 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800485}
486
487void EventHub::Device::close() {
488 if (fd >= 0) {
489 ::close(fd);
490 fd = -1;
491 }
492}
493
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700494status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100495 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700496 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100497 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700498 return -errno;
499 }
500 enabled = true;
501 return OK;
502}
503
504status_t EventHub::Device::disable() {
505 close();
506 enabled = false;
507 return OK;
508}
509
Chris Ye989bb932020-07-04 16:18:59 -0700510bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700511 return !isVirtual && enabled;
512}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800513
Chris Ye3a1e4462020-08-12 10:13:15 -0700514const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700515 return keyMap.keyCharacterMap;
516}
517
518template <std::size_t N>
519status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
520 if (!hasValidFd()) {
521 return BAD_VALUE;
522 }
523 if ((_IOC_SIZE(ioctlCode) == 0)) {
524 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
525 }
526
527 typename BitArray<N>::Buffer buffer;
528 status_t ret = ioctl(fd, ioctlCode, buffer.data());
529 bitArray.loadFromBuffer(buffer);
530 return ret;
531}
532
533void EventHub::Device::configureFd() {
534 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
535 if (classes.test(InputDeviceClass::KEYBOARD)) {
536 // Disable kernel key repeat since we handle it ourselves
537 unsigned int repeatRate[] = {0, 0};
538 if (ioctl(fd, EVIOCSREP, repeatRate)) {
539 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
540 }
541 }
542
543 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
544 // associated with input events. This is important because the input system
545 // uses the timestamps extensively and assumes they were recorded using the monotonic
546 // clock.
547 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700548 if (classes.test(InputDeviceClass::SENSOR)) {
549 // Each new sensor event should use the same time base as
550 // SystemClock.elapsedRealtimeNanos().
551 clockId = CLOCK_BOOTTIME;
552 }
Chris Ye989bb932020-07-04 16:18:59 -0700553 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
554 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
555}
556
557bool EventHub::Device::hasKeycodeLocked(int keycode) const {
558 if (!keyMap.haveKeyLayout()) {
559 return false;
560 }
561
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700562 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700563 const size_t N = scanCodes.size();
564 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
565 int32_t sc = scanCodes[i];
566 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
567 return true;
568 }
569 }
570
571 return false;
572}
573
574void EventHub::Device::loadConfigurationLocked() {
575 configurationFile =
576 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
577 InputDeviceConfigurationFileType::
578 CONFIGURATION);
579 if (configurationFile.empty()) {
580 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
581 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500582 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
583 PropertyMap::load(configurationFile.c_str());
584 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700585 ALOGE("Error loading input device configuration file for device '%s'. "
586 "Using default configuration.",
587 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500588 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500589 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700590 }
591 }
592}
593
594bool EventHub::Device::loadVirtualKeyMapLocked() {
595 // The virtual key map is supplied by the kernel as a system board property file.
596 std::string propPath = "/sys/board_properties/virtualkeys.";
597 propPath += identifier.getCanonicalName();
598 if (access(propPath.c_str(), R_OK)) {
599 return false;
600 }
601 virtualKeyMap = VirtualKeyMap::load(propPath);
602 return virtualKeyMap != nullptr;
603}
604
605status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500606 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700607}
608
609bool EventHub::Device::isExternalDeviceLocked() {
610 if (configuration) {
611 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700612 if (configuration->tryGetProperty("device.internal", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700613 return !value;
614 }
615 }
616 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
617}
618
619bool EventHub::Device::deviceHasMicLocked() {
620 if (configuration) {
621 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700622 if (configuration->tryGetProperty("audio.mic", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700623 return value;
624 }
625 }
626 return false;
627}
628
629void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
630 int32_t sc;
631 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
632 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -0700633 ev.input_event_sec = 0;
634 ev.input_event_usec = 0;
Chris Ye989bb932020-07-04 16:18:59 -0700635 ev.type = EV_LED;
636 ev.code = sc;
637 ev.value = on ? 1 : 0;
638
639 ssize_t nWrite;
640 do {
641 nWrite = write(fd, &ev, sizeof(struct input_event));
642 } while (nWrite == -1 && errno == EINTR);
643 }
644}
645
646void EventHub::Device::setLedForControllerLocked() {
647 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
648 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
649 }
650}
651
652status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
653 if (!keyMap.haveKeyLayout()) {
654 return NAME_NOT_FOUND;
655 }
656
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700657 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
658 if (scanCode.has_value()) {
659 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
660 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700661 return NO_ERROR;
662 }
663 }
664 return NAME_NOT_FOUND;
665}
666
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100667/**
668 * Get the capabilities for the current process.
669 * Crashes the system if unable to create / check / destroy the capabilities object.
670 */
671class Capabilities final {
672public:
673 explicit Capabilities() {
674 mCaps = cap_get_proc();
675 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
676 }
677
678 /**
679 * Check whether the current process has a specific capability
680 * in the set of effective capabilities.
681 * Return CAP_SET if the process has the requested capability
682 * Return CAP_CLEAR otherwise.
683 */
684 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
685 cap_flag_value_t value;
686 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
687 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
688 return value;
689 }
690
691 ~Capabilities() {
692 const int result = cap_free(mCaps);
693 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
694 }
695
696private:
697 cap_t mCaps;
698};
699
700static void ensureProcessCanBlockSuspend() {
701 Capabilities capabilities;
702 const bool canBlockSuspend =
703 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
704 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
705 "Input must be able to block suspend to properly process events");
706}
707
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708// --- EventHub ---
709
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710const int EventHub::EPOLL_MAX_EVENTS;
711
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700712EventHub::EventHub(void)
713 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
714 mNextDeviceId(1),
715 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700717 mNeedToReopenDevices(false),
718 mNeedToScanDevices(true),
719 mPendingEventCount(0),
720 mPendingEventIndex(0),
721 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100722 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800723
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800724 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800725 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800726
Michael Wright8e9a8562022-02-09 13:44:29 +0000727 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000728 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100729
730 std::error_code errorCode;
731 bool isDeviceInotifyAdded = false;
732 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
733 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800734 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100735 addDeviceInotify();
736 isDeviceInotifyAdded = true;
737 if (errorCode) {
738 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
739 errorCode.message().c_str());
740 }
741 }
742
743 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
744 addDeviceInotify();
745 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800746 ALOGI("Video device scanning disabled");
747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100749 struct epoll_event eventItem = {};
750 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700751 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800752 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
754
755 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000756 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800757 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
758
759 mWakeReadPipeFd = wakeFds[0];
760 mWakeWritePipeFd = wakeFds[1];
761
762 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
763 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700764 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800765
766 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
767 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700768 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800769
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700770 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
772 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700773 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774}
775
776EventHub::~EventHub(void) {
777 closeAllDevicesLocked();
778
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 ::close(mEpollFd);
780 ::close(mINotifyFd);
781 ::close(mWakeReadPipeFd);
782 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800783}
784
Usama Arifb27c8e62021-06-03 16:44:09 +0100785/**
786 * On devices that don't have any input devices (like some development boards), the /dev/input
787 * directory will be absent. However, the user may still plug in an input device at a later time.
788 * Add watch for contents of /dev/input only when /dev/input appears.
789 */
790void EventHub::addDeviceInputInotify() {
791 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
792 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
793 DEVICE_INPUT_PATH, strerror(errno));
794}
795
796void EventHub::addDeviceInotify() {
797 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
798 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
799 strerror(errno));
800}
801
Michael Wrightd02c5b62014-02-10 15:10:22 -0800802InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000803 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700805 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806}
807
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700808ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000809 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700811 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812}
813
814int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000815 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800816 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700817 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818}
819
820void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Chris Ye87143712020-11-10 05:05:58 +0000821 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700823 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 *outConfiguration = *device->configuration;
825 } else {
826 outConfiguration->clear();
827 }
828}
829
830status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700831 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800832 outAxisInfo->clear();
833
834 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000835 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836
837 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700838 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700840 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
841 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
842 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800843 return -errno;
844 }
845
846 if (info.minimum != info.maximum) {
847 outAxisInfo->valid = true;
848 outAxisInfo->minValue = info.minimum;
849 outAxisInfo->maxValue = info.maximum;
850 outAxisInfo->flat = info.flat;
851 outAxisInfo->fuzz = info.fuzz;
852 outAxisInfo->resolution = info.resolution;
853 }
854 return OK;
855 }
856 }
857 return -1;
858}
859
860bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
861 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000862 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700864 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 }
866 return false;
867}
868
869bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000870 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871
Chris Ye989bb932020-07-04 16:18:59 -0700872 Device* device = getDeviceLocked(deviceId);
873 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
874 ? device->propBitmask.test(property)
875 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876}
877
Chris Yef59a2f42020-10-16 12:55:26 -0700878bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
879 std::scoped_lock _l(mLock);
880
881 Device* device = getDeviceLocked(deviceId);
882 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
883 ? device->mscBitmask.test(mscEvent)
884 : false;
885}
886
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
888 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000889 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890
891 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700892 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
893 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
894 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895 }
896 }
897 }
898 return AKEY_STATE_UNKNOWN;
899}
900
901int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000902 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800903
904 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700905 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700906 std::vector<int32_t> scanCodes = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700908 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800910 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700911 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 return AKEY_STATE_DOWN;
913 }
914 }
915 return AKEY_STATE_UP;
916 }
917 }
918 }
919 return AKEY_STATE_UNKNOWN;
920}
921
Philip Junker4af3b3d2021-12-14 10:36:55 +0100922int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
923 std::scoped_lock _l(mLock);
924
925 Device* device = getDeviceLocked(deviceId);
926 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
927 device->keyMap.keyLayoutMap == nullptr) {
928 return AKEYCODE_UNKNOWN;
929 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700930 std::vector<int32_t> scanCodes =
931 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +0100932 if (scanCodes.empty()) {
933 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
934 "device %d",
935 locationKeyCode, deviceId);
936 return AKEYCODE_UNKNOWN;
937 }
938 if (scanCodes.size() > 1) {
939 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
940 locationKeyCode);
941 }
942 int32_t outKeyCode;
943 status_t mapKeyRes =
944 device->getKeyCharacterMap()->mapKey(scanCodes[0], 0 /*usageCode*/, &outKeyCode);
945 switch (mapKeyRes) {
946 case OK:
947 return outKeyCode;
948 case NAME_NOT_FOUND:
949 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
950 return locationKeyCode;
951 default:
952 ALOGW("Failed to get key code for key location: Key character map returned error %s",
953 statusToString(mapKeyRes).c_str());
954 return AKEYCODE_UNKNOWN;
955 }
956}
957
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
959 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000960 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961
962 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700963 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
964 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
965 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 }
967 }
968 }
969 return AKEY_STATE_UNKNOWN;
970}
971
972status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
973 *outValue = 0;
974
975 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000976 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977
978 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700979 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700981 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
982 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
983 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 return -errno;
985 }
986
987 *outValue = info.value;
988 return OK;
989 }
990 }
991 return -1;
992}
993
Siarhei Vishniakou74007942022-06-13 13:57:47 -0700994bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700995 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000996 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997
998 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700999 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001000 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001001 std::vector<int32_t> scanCodes =
1002 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001004 // check the possible scan codes identified by the layout map against the
1005 // map of codes actually emitted by the driver
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001006 for (const int32_t scanCode : scanCodes) {
1007 if (device->keyBitmask.test(scanCode)) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001008 outFlags[codeIndex] = 1;
1009 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 }
1011 }
1012 }
1013 return true;
1014 }
1015 return false;
1016}
1017
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001018status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1019 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001020 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001022 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023
Chris Ye66fbac32020-07-06 20:36:43 -07001024 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001026 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1027 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1029 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001030 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031 }
1032 }
1033
1034 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001035 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001036 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001037 status = NO_ERROR;
1038 }
1039 }
1040
1041 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001042 if (kcm) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001043 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
1044 } else {
1045 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046 }
1047 }
1048 }
1049
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001050 if (status != NO_ERROR) {
1051 *outKeycode = 0;
1052 *outFlags = 0;
1053 *outMetaState = metaState;
1054 }
1055
1056 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057}
1058
1059status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001060 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001061 Device* device = getDeviceLocked(deviceId);
1062
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001063 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1064 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001066 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1067 if (!info.has_value()) {
1068 return NAME_NOT_FOUND;
1069 }
1070 *outAxisInfo = *info;
1071 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072}
1073
Chris Yef59a2f42020-10-16 12:55:26 -07001074base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001075 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001076 std::scoped_lock _l(mLock);
1077 Device* device = getDeviceLocked(deviceId);
1078
1079 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1080 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1081 }
1082 return Errorf("Device not found or device has no key layout.");
1083}
1084
Chris Yee2b1e5c2021-03-10 22:45:12 -08001085// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1086// associated with the device ID. Returns an empty map if no miscellaneous device found.
1087const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1088 int32_t deviceId) const {
1089 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1090 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001091 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001092 return EMPTY_BATTERY_INFO;
1093 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001094 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001095}
1096
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001097std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001098 std::scoped_lock _l(mLock);
1099 std::vector<int32_t> batteryIds;
1100
Prabir Pradhan51894782022-08-23 16:29:10 +00001101 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001102 batteryIds.push_back(id);
1103 }
1104
1105 return batteryIds;
1106}
1107
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001108std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1109 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001110 std::scoped_lock _l(mLock);
1111
1112 const auto infos = getBatteryInfoLocked(deviceId);
1113
1114 auto it = infos.find(batteryId);
1115 if (it != infos.end()) {
1116 return it->second;
1117 }
1118
1119 return std::nullopt;
1120}
1121
1122// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001123// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001124const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1125 int32_t deviceId) const {
1126 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1127 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001128 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001129 return EMPTY_LIGHT_INFO;
1130 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001131 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001132}
1133
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001134std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001135 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001136 std::vector<int32_t> lightIds;
1137
Prabir Pradhan51894782022-08-23 16:29:10 +00001138 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001139 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001140 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001141
Chris Ye3fdbfef2021-01-06 18:45:18 -08001142 return lightIds;
1143}
1144
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001145std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001146 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001147
Chris Yee2b1e5c2021-03-10 22:45:12 -08001148 const auto infos = getLightInfoLocked(deviceId);
1149
1150 auto it = infos.find(lightId);
1151 if (it != infos.end()) {
1152 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001153 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001154
Chris Ye3fdbfef2021-01-06 18:45:18 -08001155 return std::nullopt;
1156}
1157
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001158std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001159 std::scoped_lock _l(mLock);
1160
Chris Yee2b1e5c2021-03-10 22:45:12 -08001161 const auto infos = getLightInfoLocked(deviceId);
1162 auto it = infos.find(lightId);
1163 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001164 return std::nullopt;
1165 }
1166 std::string buffer;
1167 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1168 &buffer)) {
1169 return std::nullopt;
1170 }
1171 return std::stoi(buffer);
1172}
1173
1174std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001175 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001176 std::scoped_lock _l(mLock);
1177
Chris Yee2b1e5c2021-03-10 22:45:12 -08001178 const auto infos = getLightInfoLocked(deviceId);
1179 auto lightIt = infos.find(lightId);
1180 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001181 return std::nullopt;
1182 }
1183
1184 auto ret =
1185 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1186
1187 if (!ret.has_value()) {
1188 return std::nullopt;
1189 }
1190 std::array<LightColor, COLOR_NUM> colors = ret.value();
1191
1192 std::string intensityStr;
1193 if (!base::ReadFileToString(lightIt->second.path /
1194 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1195 &intensityStr)) {
1196 return std::nullopt;
1197 }
1198
1199 // Intensity node outputs 3 color values
1200 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1201 std::smatch results;
1202
1203 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1204 return std::nullopt;
1205 }
1206 std::unordered_map<LightColor, int32_t> intensities;
1207 for (size_t i = 1; i < results.size(); i++) {
1208 int value = std::stoi(results[i].str());
1209 intensities.emplace(colors[i - 1], value);
1210 }
1211 return intensities;
1212}
1213
1214void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1215 std::scoped_lock _l(mLock);
1216
Chris Yee2b1e5c2021-03-10 22:45:12 -08001217 const auto infos = getLightInfoLocked(deviceId);
1218 auto lightIt = infos.find(lightId);
1219 if (lightIt == infos.end()) {
1220 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001221 return;
1222 }
1223
1224 if (!base::WriteStringToFile(std::to_string(brightness),
1225 lightIt->second.path /
1226 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1227 ALOGE("Can not write to file, error: %s", strerror(errno));
1228 }
1229}
1230
1231void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1232 std::unordered_map<LightColor, int32_t> intensities) {
1233 std::scoped_lock _l(mLock);
1234
Chris Yee2b1e5c2021-03-10 22:45:12 -08001235 const auto infos = getLightInfoLocked(deviceId);
1236 auto lightIt = infos.find(lightId);
1237 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001238 ALOGE("Light Id %d does not exist.", lightId);
1239 return;
1240 }
1241
1242 auto ret =
1243 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1244
1245 if (!ret.has_value()) {
1246 return;
1247 }
1248 std::array<LightColor, COLOR_NUM> colors = ret.value();
1249
1250 std::string rgbStr;
1251 for (size_t i = 0; i < COLOR_NUM; i++) {
1252 auto it = intensities.find(colors[i]);
1253 if (it != intensities.end()) {
1254 rgbStr += std::to_string(it->second);
1255 // Insert space between colors
1256 if (i < COLOR_NUM - 1) {
1257 rgbStr += " ";
1258 }
1259 }
1260 }
1261 // Append new line
1262 rgbStr += "\n";
1263
1264 if (!base::WriteStringToFile(rgbStr,
1265 lightIt->second.path /
1266 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1267 ALOGE("Can not write to file, error: %s", strerror(errno));
1268 }
1269}
1270
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001271InputDeviceCountryCode EventHub::getCountryCode(int32_t deviceId) const {
1272 std::scoped_lock _l(mLock);
1273 Device* device = getDeviceLocked(deviceId);
1274 if (device == nullptr || !device->associatedDevice) {
1275 return InputDeviceCountryCode::INVALID;
1276 }
1277 return device->associatedDevice->countryCode;
1278}
1279
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001280void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001281 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282
1283 mExcludedDevices = devices;
1284}
1285
1286bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001287 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001289 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1290 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291 }
1292 return false;
1293}
1294
Arthur Hungcb40a002021-08-03 14:31:01 +00001295bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1296 std::scoped_lock _l(mLock);
1297 Device* device = getDeviceLocked(deviceId);
1298 if (device != nullptr) {
1299 return device->hasKeycodeLocked(keyCode);
1300 }
1301 return false;
1302}
1303
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001305 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 Device* device = getDeviceLocked(deviceId);
1307 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001308 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001309 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 }
1311 return false;
1312}
1313
1314void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001315 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001317 if (device != nullptr && device->hasValidFd()) {
1318 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319 }
1320}
1321
1322void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001323 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 outVirtualKeys.clear();
1325
Chris Ye87143712020-11-10 05:05:58 +00001326 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001328 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001329 const std::vector<VirtualKeyDefinition> virtualKeys =
1330 device->virtualKeyMap->getVirtualKeys();
1331 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332 }
1333}
1334
Chris Ye3a1e4462020-08-12 10:13:15 -07001335const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001336 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001338 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 return device->getKeyCharacterMap();
1340 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001341 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342}
1343
Chris Ye3a1e4462020-08-12 10:13:15 -07001344bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001345 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346 Device* device = getDeviceLocked(deviceId);
Philip Junker90bc9492021-12-10 18:39:42 +01001347 if (device == nullptr || map == nullptr || device->keyMap.keyCharacterMap == nullptr) {
1348 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 }
Philip Junker90bc9492021-12-10 18:39:42 +01001350 device->keyMap.keyCharacterMap->combine(*map);
1351 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352}
1353
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001354static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1355 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001356 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001357 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001358 if (!identifier.uniqueId.empty()) {
1359 rawDescriptor += "uniqueId:";
1360 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001361 }
1362 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001363 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 }
1365
1366 if (identifier.vendor == 0 && identifier.product == 0) {
1367 // If we don't know the vendor and product id, then the device is probably
1368 // built-in so we need to rely on other information to uniquely identify
1369 // the input device. Usually we try to avoid relying on the device name or
1370 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001371 if (!identifier.name.empty()) {
1372 rawDescriptor += "name:";
1373 rawDescriptor += identifier.name;
1374 } else if (!identifier.location.empty()) {
1375 rawDescriptor += "location:";
1376 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 }
1378 }
1379 identifier.descriptor = sha1(rawDescriptor);
1380 return rawDescriptor;
1381}
1382
1383void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1384 // Compute a device descriptor that uniquely identifies the device.
1385 // The descriptor is assumed to be a stable identifier. Its value should not
1386 // change between reboots, reconnections, firmware updates or new releases
1387 // of Android. In practice we sometimes get devices that cannot be uniquely
1388 // identified. In this case we enforce uniqueness between connected devices.
1389 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001390 // Note that we explicitly do not use the path or location for external devices
1391 // as their path or location will change as they are plugged/unplugged or moved
1392 // to different ports. We do fallback to using name and location in the case of
1393 // internal devices which are detected by the vendor and product being 0 in
1394 // generateDescriptor. If two identical descriptors are detected we will fallback
1395 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1396 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397
1398 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001399 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001400 // Enforce that the generated descriptor is unique.
1401 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1402 identifier.nonce++;
1403 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001405 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001406 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407}
1408
Prabir Pradhancb42b472022-08-23 16:01:19 +00001409std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1410 const std::filesystem::path& devicePath) const {
1411 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1412 getSysfsRootPath(devicePath.c_str());
1413 if (!sysfsRootPathOpt) {
1414 return nullptr;
1415 }
1416
1417 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001418
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001419 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001420 AssociatedDevice{.sysfsRootPath = path,
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001421 .countryCode = readCountryCodeLocked(path),
Prabir Pradhancb42b472022-08-23 16:01:19 +00001422 .batteryInfos = readBatteryConfiguration(path),
1423 .lightInfos = readLightsConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001424
1425 bool associatedDeviceChanged = false;
1426 for (const auto& [id, dev] : mDevices) {
1427 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1428 if (*associatedDevice != *dev->associatedDevice) {
1429 associatedDeviceChanged = true;
1430 dev->associatedDevice = associatedDevice;
1431 }
1432 associatedDevice = dev->associatedDevice;
1433 }
1434 }
1435 ALOGI_IF(associatedDeviceChanged,
1436 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1437 path.c_str(), associatedDevice->dump().c_str());
1438
1439 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001440}
1441
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001442void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001443 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001445 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 ff_effect effect;
1447 memset(&effect, 0, sizeof(effect));
1448 effect.type = FF_RUMBLE;
1449 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001450 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001451 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1452 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001453 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 effect.replay.delay = 0;
1455 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1456 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001457 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458 return;
1459 }
1460 device->ffEffectId = effect.id;
1461
1462 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001463 ev.input_event_sec = 0;
1464 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465 ev.type = EV_FF;
1466 ev.code = device->ffEffectId;
1467 ev.value = 1;
1468 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1469 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001470 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471 return;
1472 }
1473 device->ffEffectPlaying = true;
1474 }
1475}
1476
1477void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001478 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001480 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481 if (device->ffEffectPlaying) {
1482 device->ffEffectPlaying = false;
1483
1484 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001485 ev.input_event_sec = 0;
1486 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 ev.type = EV_FF;
1488 ev.code = device->ffEffectId;
1489 ev.value = 0;
1490 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1491 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001492 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493 return;
1494 }
1495 }
1496 }
1497}
1498
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001499std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001500 std::scoped_lock _l(mLock);
1501 std::vector<int32_t> vibrators;
1502 Device* device = getDeviceLocked(deviceId);
1503 if (device != nullptr && device->hasValidFd() &&
1504 device->classes.test(InputDeviceClass::VIBRATOR)) {
1505 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1506 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1507 }
1508 return vibrators;
1509}
1510
Josh Bartel938632f2022-07-19 15:34:22 -05001511/**
1512 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1513 */
1514bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1515 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001516 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001517 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 }
1519 }
Josh Bartel938632f2022-07-19 15:34:22 -05001520
1521 for (const auto& [id, device] : mDevices) {
1522 if (descriptor == device->identifier.descriptor) {
1523 return true;
1524 }
1525 }
1526 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527}
1528
1529EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001530 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 deviceId = mBuiltInKeyboardId;
1532 }
Chris Ye989bb932020-07-04 16:18:59 -07001533 const auto& it = mDevices.find(deviceId);
1534 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535}
1536
Chris Ye8594e192020-07-14 10:34:06 -07001537EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001538 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001540 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541 }
1542 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001543 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544}
1545
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001546/**
1547 * The file descriptor could be either input device, or a video device (associated with a
1548 * specific input device). Check both cases here, and return the device that this event
1549 * belongs to. Caller can compare the fd's once more to determine event type.
1550 * Looks through all input devices, and only attached video devices. Unattached video
1551 * devices are ignored.
1552 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001553EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001554 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001555 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001556 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001557 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001558 }
1559 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1560 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001561 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001562 }
1563 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001564 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1565 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001566 return nullptr;
1567}
1568
Chris Yee2b1e5c2021-03-10 22:45:12 -08001569std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001570 std::filesystem::path batteryPath;
1571 {
1572 // Do not read the sysfs node to get the battery state while holding
1573 // the EventHub lock. For some peripheral devices, reading battery state
1574 // can be broken and take 5+ seconds. Holding the lock in this case would
1575 // block all other event processing during this time. For now, we assume this
1576 // call never happens on the InputReader thread and read the sysfs node outside
1577 // the lock to prevent event processing from being blocked by this call.
1578 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001579
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001580 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001581 auto it = infos.find(batteryId);
1582 if (it == infos.end()) {
1583 return std::nullopt;
1584 }
1585 batteryPath = it->second.path;
1586 } // release lock
1587
Chris Yee2b1e5c2021-03-10 22:45:12 -08001588 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001589
1590 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001591 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001592 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001593 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001594 }
1595
1596 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1597 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001598 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001599 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001600 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001601 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1602 if (levelIt != BATTERY_LEVEL.end()) {
1603 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001604 }
1605 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001606
Kim Low03ea0352020-11-06 12:45:07 -08001607 return std::nullopt;
1608}
1609
Chris Yee2b1e5c2021-03-10 22:45:12 -08001610std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001611 std::filesystem::path batteryPath;
1612 {
1613 // Do not read the sysfs node to get the battery state while holding
1614 // the EventHub lock. For some peripheral devices, reading battery state
1615 // can be broken and take 5+ seconds. Holding the lock in this case would
1616 // block all other event processing during this time. For now, we assume this
1617 // call never happens on the InputReader thread and read the sysfs node outside
1618 // the lock to prevent event processing from being blocked by this call.
1619 std::scoped_lock _l(mLock);
1620
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001621 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001622 auto it = infos.find(batteryId);
1623 if (it == infos.end()) {
1624 return std::nullopt;
1625 }
1626 batteryPath = it->second.path;
1627 } // release lock
1628
Chris Yee2b1e5c2021-03-10 22:45:12 -08001629 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001630
Andy Chenf9f1a022022-08-29 20:07:10 -04001631 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001632 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001633 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1634 return std::nullopt;
1635 }
1636
Chris Yed1936772021-02-22 10:30:40 -08001637 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001638 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1639 if (statusIt != BATTERY_STATUS.end()) {
1640 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001641 }
1642
1643 return std::nullopt;
1644}
1645
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001646std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001647 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001649 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001651 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 bool awoken = false;
1653 for (;;) {
1654 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1655
1656 // Reopen input devices if needed.
1657 if (mNeedToReopenDevices) {
1658 mNeedToReopenDevices = false;
1659
1660 ALOGI("Reopening all input devices due to a configuration change.");
1661
1662 closeAllDevicesLocked();
1663 mNeedToScanDevices = true;
1664 break; // return to the caller before we actually rescan
1665 }
1666
1667 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001668 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1669 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001670 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001671 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001672 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1673 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001674 events.push_back({
1675 .when = now,
1676 .deviceId = deviceId,
1677 .type = DEVICE_REMOVED,
1678 });
Chris Ye989bb932020-07-04 16:18:59 -07001679 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001681 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 break;
1683 }
1684 }
1685
1686 if (mNeedToScanDevices) {
1687 mNeedToScanDevices = false;
1688 scanDevicesLocked();
1689 mNeedToSendFinishedDeviceScan = true;
1690 }
1691
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001692 while (!mOpeningDevices.empty()) {
1693 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1694 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001695 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001696 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1697 events.push_back({
1698 .when = now,
1699 .deviceId = deviceId,
1700 .type = DEVICE_ADDED,
1701 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001702
1703 // Try to find a matching video device by comparing device names
1704 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1705 it++) {
1706 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001707 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001708 // videoDevice was transferred to 'device'
1709 it = mUnattachedVideoDevices.erase(it);
1710 break;
1711 }
1712 }
1713
1714 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1715 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001716 ALOGW("Device id %d exists, replaced.", device->id);
1717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001719 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 break;
1721 }
1722 }
1723
1724 if (mNeedToSendFinishedDeviceScan) {
1725 mNeedToSendFinishedDeviceScan = false;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001726 events.push_back({
1727 .when = now,
1728 .type = FINISHED_DEVICE_SCAN,
1729 });
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001730 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731 break;
1732 }
1733 }
1734
1735 // Grab the next input event.
1736 bool deviceChanged = false;
1737 while (mPendingEventIndex < mPendingEventCount) {
1738 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001739 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 if (eventItem.events & EPOLLIN) {
1741 mPendingINotify = true;
1742 } else {
1743 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1744 }
1745 continue;
1746 }
1747
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001748 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 if (eventItem.events & EPOLLIN) {
1750 ALOGV("awoken after wake()");
1751 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001752 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753 ssize_t nRead;
1754 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001755 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1756 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757 } else {
1758 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001759 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760 }
1761 continue;
1762 }
1763
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001764 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001765 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001766 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1767 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001768 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769 continue;
1770 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001771 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1772 if (eventItem.events & EPOLLIN) {
1773 size_t numFrames = device->videoDevice->readAndQueueFrames();
1774 if (numFrames == 0) {
1775 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001776 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001777 }
1778 } else if (eventItem.events & EPOLLHUP) {
1779 // TODO(b/121395353) - consider adding EPOLLRDHUP
1780 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001781 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001782 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1783 device->videoDevice = nullptr;
1784 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001785 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1786 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001787 ALOG_ASSERT(!DEBUG);
1788 }
1789 continue;
1790 }
1791 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001793 int32_t readSize =
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001794 read(device->fd, readBuffer.data(),
1795 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1797 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001798 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001799 " capacity: %zu errno: %d)\n",
1800 device->fd, readSize, readBuffer.size(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001802 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803 } else if (readSize < 0) {
1804 if (errno != EAGAIN && errno != EINTR) {
1805 ALOGW("could not get event (errno=%d)", errno);
1806 }
1807 } else if ((readSize % sizeof(struct input_event)) != 0) {
1808 ALOGE("could not get event (wrong size: %d)", readSize);
1809 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001810 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001812 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813 for (size_t i = 0; i < count; i++) {
1814 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001815 events.push_back({
1816 .when = processEventTimestamp(iev),
1817 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
1818 .deviceId = deviceId,
1819 .type = iev.type,
1820 .code = iev.code,
1821 .value = iev.value,
1822 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001824 if (events.size() >= EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825 // The result buffer is full. Reset the pending event index
1826 // so we will try to read the device again on the next iteration.
1827 mPendingEventIndex -= 1;
1828 break;
1829 }
1830 }
1831 } else if (eventItem.events & EPOLLHUP) {
1832 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001833 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001835 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001837 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1838 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 }
1840 }
1841
1842 // readNotify() will modify the list of devices so this must be done after
1843 // processing all other events to ensure that we read all remaining events
1844 // before closing the devices.
1845 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1846 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00001847 const auto res = readNotifyLocked();
1848 if (!res.ok()) {
1849 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
1850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 deviceChanged = true;
1852 }
1853
1854 // Report added or removed devices immediately.
1855 if (deviceChanged) {
1856 continue;
1857 }
1858
1859 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001860 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 break;
1862 }
1863
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001864 // Poll for events.
1865 // When a device driver has pending (unread) events, it acquires
1866 // a kernel wake lock. Once the last pending event has been read, the device
1867 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1868 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1869 // is called again for the same fd that produced the event.
1870 // Thus the system can only sleep if there are no events pending or
1871 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001872 //
1873 // The timeout is advisory only. If the device is asleep, it will not wake just to
1874 // service the timeout.
1875 mPendingEventIndex = 0;
1876
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001877 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001878
1879 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1880
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001881 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882
1883 if (pollResult == 0) {
1884 // Timed out.
1885 mPendingEventCount = 0;
1886 break;
1887 }
1888
1889 if (pollResult < 0) {
1890 // An error occurred.
1891 mPendingEventCount = 0;
1892
1893 // Sleep after errors to avoid locking up the system.
1894 // Hopefully the error is transient.
1895 if (errno != EINTR) {
1896 ALOGW("poll failed (errno=%d)\n", errno);
1897 usleep(100000);
1898 }
1899 } else {
1900 // Some events occurred.
1901 mPendingEventCount = size_t(pollResult);
1902 }
1903 }
1904
1905 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001906 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907}
1908
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001909std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001910 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001911
1912 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001913 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001914 return {};
1915 }
1916 return device->videoDevice->consumeFrames();
1917}
1918
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919void EventHub::wake() {
1920 ALOGV("wake() called");
1921
1922 ssize_t nWrite;
1923 do {
1924 nWrite = write(mWakeWritePipeFd, "W", 1);
1925 } while (nWrite == -1 && errno == EINTR);
1926
1927 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001928 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 }
1930}
1931
1932void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01001933 status_t result;
1934 std::error_code errorCode;
1935
1936 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
1937 result = scanDirLocked(DEVICE_INPUT_PATH);
1938 if (result < 0) {
1939 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
1940 }
1941 } else {
1942 if (errorCode) {
1943 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
1944 errorCode.message().c_str());
1945 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001946 }
Philip Quinn39b81682019-01-09 22:20:39 -08001947 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001948 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001949 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001950 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952 }
Chris Ye989bb932020-07-04 16:18:59 -07001953 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 createVirtualKeyboardLocked();
1955 }
1956}
1957
1958// ----------------------------------------------------------------------------
1959
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001961 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1962 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1963 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1964 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1965 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1966 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967};
1968
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001969status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001970 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001971 struct epoll_event eventItem = {};
1972 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1973 eventItem.data.fd = fd;
1974 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1975 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001976 return -errno;
1977 }
1978 return OK;
1979}
1980
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001981status_t EventHub::unregisterFdFromEpoll(int fd) {
1982 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1983 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1984 return -errno;
1985 }
1986 return OK;
1987}
1988
Chris Ye989bb932020-07-04 16:18:59 -07001989status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1990 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001991 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001992 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001993 return result;
1994 }
Chris Ye989bb932020-07-04 16:18:59 -07001995 if (device.videoDevice) {
1996 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001997 }
1998 return result;
1999}
2000
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002001void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2002 status_t result = registerFdForEpoll(videoDevice.getFd());
2003 if (result != OK) {
2004 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2005 }
2006}
2007
Chris Ye989bb932020-07-04 16:18:59 -07002008status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2009 if (device.hasValidFd()) {
2010 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002011 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002012 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002013 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002014 }
2015 }
Chris Ye989bb932020-07-04 16:18:59 -07002016 if (device.videoDevice) {
2017 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002018 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002019 return OK;
2020}
2021
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002022void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2023 if (videoDevice.hasValidFd()) {
2024 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2025 if (result != OK) {
2026 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002027 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002028 }
2029 }
2030}
2031
Chris Yed3fef462021-03-07 17:10:08 -08002032void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002033 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002034 SHA256_CTX ctx;
2035 SHA256_Init(&ctx);
2036 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2037 identifier.uniqueId.size());
2038 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2039 SHA256_Final(digest.data(), &ctx);
2040
2041 std::string obfuscatedId;
2042 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2043 obfuscatedId += StringPrintf("%02x", digest[i]);
2044 }
2045
Chris Yed3fef462021-03-07 17:10:08 -08002046 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2047 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002048 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002049}
2050
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002051void EventHub::openDeviceLocked(const std::string& devicePath) {
2052 // If an input device happens to register around the time when EventHub's constructor runs, it
2053 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2054 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2055 // from getting registered, ensure that this path is not already covered by an existing device.
2056 for (const auto& [deviceId, device] : mDevices) {
2057 if (device->path == devicePath) {
2058 return; // device was already registered
2059 }
2060 }
2061
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062 char buffer[80];
2063
Chris Ye8594e192020-07-14 10:34:06 -07002064 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002065
Chris Ye8594e192020-07-14 10:34:06 -07002066 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002067 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002068 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002069 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 }
2071
2072 InputDeviceIdentifier identifier;
2073
2074 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002075 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002076 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 } else {
2078 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002079 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 }
2081
2082 // Check to see if the device is on our excluded list
2083 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002084 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002086 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002088 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 }
2090 }
2091
2092 // Get device driver version.
2093 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002094 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002095 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002097 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 }
2099
2100 // Get device identifier.
2101 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002102 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002103 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002105 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 }
2107 identifier.bus = inputId.bustype;
2108 identifier.product = inputId.product;
2109 identifier.vendor = inputId.vendor;
2110 identifier.version = inputId.version;
2111
2112 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002113 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2114 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 } else {
2116 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002117 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118 }
2119
2120 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002121 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2122 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123 } else {
2124 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002125 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 }
2127
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002128 // Attempt to get the bluetooth address of an input device from the uniqueId.
2129 if (identifier.bus == BUS_BLUETOOTH &&
2130 std::regex_match(identifier.uniqueId,
2131 std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2132 identifier.bluetoothAddress = identifier.uniqueId;
2133 // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2134 for (auto& c : *identifier.bluetoothAddress) {
2135 c = ::toupper(c);
2136 }
2137 }
2138
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139 // Fill in the descriptor.
2140 assignDescriptorLocked(identifier);
2141
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142 // Allocate device. (The device object takes ownership of the fd at this point.)
2143 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002144 std::unique_ptr<Device> device =
2145 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2146 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147
Chris Ye8594e192020-07-14 10:34:06 -07002148 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002150 " vendor %04x\n"
2151 " product %04x\n"
2152 " version %04x\n",
2153 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002154 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2155 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2156 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2157 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002158 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2159 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160
2161 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002162 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163
2164 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002165 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2166 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2167 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2168 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2169 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2170 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002171 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002172 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173
2174 // See if this is a keyboard. Ignore everything in the button range except for
2175 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002176 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002177 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2178 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2179 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002181 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182 }
2183
2184 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002185 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2186 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002187 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188 }
2189
Prashant Malani1941ff52015-08-11 18:29:28 -07002190 // See if this is a rotary encoder type device.
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002191 std::string deviceType;
2192 if (device->configuration && device->configuration->tryGetProperty("device.type", deviceType)) {
2193 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002194 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002195 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002196 }
2197
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198 // See if this is a touch pad.
2199 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002200 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 // Some joysticks such as the PS3 controller report axes that conflict
2202 // with the ABS_MT range. Try to confirm that the device really is
2203 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002204 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002205 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002207 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002208 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2209 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002210 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002211 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07002212 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2213 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002214 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07002215 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
2216 // can fuse it with the touch screen data, so just take them back. Note this means an
2217 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07002218 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219 }
2220
2221 // See if this device is a joystick.
2222 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2223 // from other devices such as accelerometers that also have absolute axes.
2224 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002225 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002227 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002228 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 device->classes = assumedClasses;
2230 break;
2231 }
2232 }
2233 }
2234
Chris Yef59a2f42020-10-16 12:55:26 -07002235 // Check whether this device is an accelerometer.
2236 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2237 device->classes |= InputDeviceClass::SENSOR;
2238 }
2239
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240 // Check whether this device has switches.
2241 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002242 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002243 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244 break;
2245 }
2246 }
2247
2248 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002249 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002250 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251 }
2252
2253 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002254 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 // Load the virtual keys for the touch screen, if any.
2256 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002257 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002258 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002259 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260 }
2261 }
2262
2263 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002264 // We need to do this for joysticks too because the key layout may specify axes, and for
2265 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002267 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2268 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002270 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271 }
2272
2273 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002274 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002276 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002277 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2278 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 mBuiltInKeyboardId = device->id;
2280 }
2281
2282 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002283 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002284 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 }
2286
2287 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002288 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2289 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2290 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2291 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2292 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002293 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 }
2295
2296 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002297 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002298 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002299 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 break;
2301 }
2302 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 }
2304
2305 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002306 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002307 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002308 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002309 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 }
2311
Chris Ye3fdbfef2021-01-06 18:45:18 -08002312 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002313 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002314 device->classes |= InputDeviceClass::BATTERY;
2315 }
Kim Low03ea0352020-11-06 12:45:07 -08002316
Chris Ye3fdbfef2021-01-06 18:45:18 -08002317 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002318 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002319 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002320 }
2321
Tim Kilbourn063ff532015-04-08 10:26:18 -07002322 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002323 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002324 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002325 }
2326
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002328 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002329 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 }
2331
Chris Ye1b0c7342020-07-28 21:57:03 -07002332 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2333 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002334 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2335 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 }
2337
Chris Ye989bb932020-07-04 16:18:59 -07002338 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002339 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340 }
2341
Chris Ye989bb932020-07-04 16:18:59 -07002342 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002343
Chris Ye1b0c7342020-07-28 21:57:03 -07002344 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002345 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002346 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2347 device->classes.string().c_str(), device->configurationFile.c_str(),
2348 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2349 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002350
Chris Ye989bb932020-07-04 16:18:59 -07002351 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002352}
2353
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002354void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2355 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2356 if (!videoDevice) {
2357 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2358 return;
2359 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002360 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002361 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002362 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002363 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002364 }
2365 }
2366
2367 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2368 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002369 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002370 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002371 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2372}
2373
Chris Yed3fef462021-03-07 17:10:08 -08002374bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2375 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002376 if (videoDevice->getName() != device.identifier.name) {
2377 return false;
2378 }
2379 device.videoDevice = std::move(videoDevice);
2380 if (device.enabled) {
2381 registerVideoDeviceForEpollLocked(*device.videoDevice);
2382 }
2383 return true;
2384}
2385
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002386bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002387 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002388 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002389 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002390 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2391 return false;
2392 }
2393 return device->enabled;
2394}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002396status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002397 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002398 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002399 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002400 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2401 return BAD_VALUE;
2402 }
2403 if (device->enabled) {
2404 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2405 return OK;
2406 }
2407 status_t result = device->enable();
2408 if (result != OK) {
2409 ALOGE("Failed to enable device %" PRId32, deviceId);
2410 return result;
2411 }
2412
Chris Ye989bb932020-07-04 16:18:59 -07002413 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002414
Chris Ye989bb932020-07-04 16:18:59 -07002415 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002416}
2417
2418status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002419 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002420 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002421 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002422 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2423 return BAD_VALUE;
2424 }
2425 if (!device->enabled) {
2426 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2427 return OK;
2428 }
Chris Ye989bb932020-07-04 16:18:59 -07002429 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002430 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431}
2432
2433void EventHub::createVirtualKeyboardLocked() {
2434 InputDeviceIdentifier identifier;
2435 identifier.name = "Virtual";
2436 identifier.uniqueId = "<virtual>";
2437 assignDescriptorLocked(identifier);
2438
Chris Ye989bb932020-07-04 16:18:59 -07002439 std::unique_ptr<Device> device =
2440 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Prabir Pradhancb42b472022-08-23 16:01:19 +00002441 identifier, nullptr /*associatedDevice*/);
Chris Ye1b0c7342020-07-28 21:57:03 -07002442 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2443 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002444 device->loadKeyMapLocked();
2445 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002446}
2447
Chris Ye989bb932020-07-04 16:18:59 -07002448void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002449 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002450 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451}
2452
Chris Ye989bb932020-07-04 16:18:59 -07002453int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454 if (mControllerNumbers.isFull()) {
2455 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002456 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 return 0;
2458 }
2459 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2460 // one
2461 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2462}
2463
Chris Ye989bb932020-07-04 16:18:59 -07002464void EventHub::releaseControllerNumberLocked(int32_t num) {
2465 if (num > 0) {
2466 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468}
2469
Chris Ye8594e192020-07-14 10:34:06 -07002470void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002472 if (device != nullptr) {
2473 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002474 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475 }
Chris Ye8594e192020-07-14 10:34:06 -07002476 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002477}
2478
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002479/**
2480 * Find the video device by filename, and close it.
2481 * The video device is closed by path during an inotify event, where we don't have the
2482 * additional context about the video device fd, or the associated input device.
2483 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002484void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002485 // A video device may be owned by an existing input device, or it may be stored in
2486 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002487 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002488 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002489 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002490 device->videoDevice = nullptr;
2491 return;
2492 }
2493 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002494 std::erase_if(mUnattachedVideoDevices,
2495 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2496 return videoDevice->getPath() == devicePath;
2497 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498}
2499
2500void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002501 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002502 while (!mDevices.empty()) {
2503 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 }
2505}
2506
Chris Ye989bb932020-07-04 16:18:59 -07002507void EventHub::closeDeviceLocked(Device& device) {
2508 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2509 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510
Chris Ye989bb932020-07-04 16:18:59 -07002511 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002513 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002514 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2515 }
2516
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002517 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002518 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002519 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002520 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002521 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522
Chris Ye989bb932020-07-04 16:18:59 -07002523 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002524 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002525 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002526 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002527
Chris Ye989bb932020-07-04 16:18:59 -07002528 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529}
2530
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002531base::Result<void> EventHub::readNotifyLocked() {
2532 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2533 uint8_t eventBuffer[512];
2534 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535
2536 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002537 do {
2538 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2539 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002541 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2542
2543 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2544 const inotify_event* event;
2545 event = (const inotify_event*)(eventBuffer + eventPos);
2546 if (event->len == 0) continue;
2547
2548 handleNotifyEventLocked(*event);
2549
2550 const ssize_t eventSize = EVENT_SIZE + event->len;
2551 sizeRead -= eventSize;
2552 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002554 return {};
2555}
2556
2557void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2558 if (event.wd == mDeviceInputWd) {
2559 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2560 if (event.mask & IN_CREATE) {
2561 openDeviceLocked(filename);
2562 } else {
2563 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2564 closeDeviceByPathLocked(filename);
2565 }
2566 } else if (event.wd == mDeviceWd) {
2567 if (isV4lTouchNode(event.name)) {
2568 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2569 if (event.mask & IN_CREATE) {
2570 openVideoDeviceLocked(filename);
2571 } else {
2572 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2573 closeVideoDeviceByPathLocked(filename);
2574 }
2575 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2576 addDeviceInputInotify();
2577 }
2578 } else {
2579 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581}
2582
Chris Ye8594e192020-07-14 10:34:06 -07002583status_t EventHub::scanDirLocked(const std::string& dirname) {
2584 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2585 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 return 0;
2588}
2589
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002590/**
2591 * Look for all dirname/v4l-touch* devices, and open them.
2592 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002593status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002594 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2595 if (isV4lTouchNode(entry.path())) {
2596 ALOGI("Found touch video device %s", entry.path().c_str());
2597 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002598 }
2599 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002600 return OK;
2601}
2602
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603void EventHub::requestReopenDevices() {
2604 ALOGV("requestReopenDevices() called");
2605
Chris Ye87143712020-11-10 05:05:58 +00002606 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607 mNeedToReopenDevices = true;
2608}
2609
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002610void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002611 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612
2613 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002614 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002615
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002616 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002618 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619
Chris Ye989bb932020-07-04 16:18:59 -07002620 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002622 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002623 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002625 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002626 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002627 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002628 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002629 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002630 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002631 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2632 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002633 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002634 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002635 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002636 "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002637 device->identifier.bus, device->identifier.vendor,
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002638 device->identifier.product, device->identifier.version,
2639 toString(device->identifier.bluetoothAddress).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002640 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002641 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002642 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002643 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00002644 dump += StringPrintf(INDENT3 "CountryCode: %d\n",
2645 device->associatedDevice ? device->associatedDevice->countryCode
2646 : InputDeviceCountryCode::INVALID);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002647 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002648 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002649 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2650 device->videoDevice ? device->videoDevice->dump().c_str()
2651 : "<none>");
2652 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2653 device->associatedDevice
2654 ? device->associatedDevice->sysfsRootPath.c_str()
2655 : "<none>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002657
2658 dump += INDENT "Unattached video devices:\n";
2659 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2660 dump += INDENT2 + videoDevice->dump() + "\n";
2661 }
2662 if (mUnattachedVideoDevices.empty()) {
2663 dump += INDENT2 "<none>\n";
2664 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002665 } // release lock
2666}
2667
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002668void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002670 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671}
2672
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002673std::string EventHub::AssociatedDevice::dump() const {
2674 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2675 batteryInfos.size(), lightInfos.size());
2676}
2677
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002678} // namespace android