blob: f2ea90c291f964eccf0001c25f692b29adc2fad9 [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
Prabir Pradhana3621852022-10-14 18:57:23 +0000152/* The set of all Android key codes that correspond to buttons (bit-switches) on a stylus. */
153static constexpr std::array<int32_t, 4> STYLUS_BUTTON_KEYCODES = {
154 AKEYCODE_STYLUS_BUTTON_PRIMARY,
155 AKEYCODE_STYLUS_BUTTON_SECONDARY,
156 AKEYCODE_STYLUS_BUTTON_TERTIARY,
157 AKEYCODE_STYLUS_BUTTON_TAIL,
158};
159
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800160/**
161 * Return true if name matches "v4l-touch*"
162 */
Chris Ye8594e192020-07-14 10:34:06 -0700163static bool isV4lTouchNode(std::string name) {
164 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800165}
166
Philip Quinn39b81682019-01-09 22:20:39 -0800167/**
168 * Returns true if V4L devices should be scanned.
169 *
170 * The system property ro.input.video_enabled can be used to control whether
171 * EventHub scans and opens V4L devices. As V4L does not support multiple
172 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700173 * them.
174 *
175 * Setting this to "false" would prevent any video devices from being discovered and
176 * associated with input devices.
177 *
178 * This property can be used as follows:
179 * 1. To turn off features that are dependent on video device presence.
180 * 2. During testing and development, to allow other clients to read video devices
181 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800182 */
183static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700184 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800185}
186
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800187static nsecs_t processEventTimestamp(const struct input_event& event) {
188 // Use the time specified in the event instead of the current time
189 // so that downstream code can get more accurate estimates of
190 // event dispatch latency from the time the event is enqueued onto
191 // the evdev client buffer.
192 //
193 // The event's timestamp fortuitously uses the same monotonic clock
194 // time base as the rest of Android. The kernel event device driver
195 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
196 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
197 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
198 // system call that also queries ktime_get_ts().
199
Colin Cross5b799302022-10-18 21:52:41 -0700200 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.input_event_sec) +
201 microseconds_to_nanoseconds(event.input_event_usec);
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800202 return inputEventTime;
203}
204
Kim Low03ea0352020-11-06 12:45:07 -0800205/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000206 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800207 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800208static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800209 std::error_code errorCode;
210
211 // Stat the device path to get the major and minor number of the character file
212 struct stat statbuf;
213 if (stat(devicePath, &statbuf) == -1) {
214 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800215 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800216 }
217
218 unsigned int major_num = major(statbuf.st_rdev);
219 unsigned int minor_num = minor(statbuf.st_rdev);
220
221 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
222 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
223 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
224 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
225
226 // Make sure nothing went wrong in call to canonical()
227 if (errorCode) {
228 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
229 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800230 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800231 }
232
233 // Continue to go up a directory until we reach a directory named "input"
234 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
235 sysfsPath = sysfsPath.parent_path();
236 }
237
238 // Then go up one more and you will be at the sysfs root of the device
239 sysfsPath = sysfsPath.parent_path();
240
241 // Make sure we didn't reach root path and that directory actually exists
242 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
243 if (errorCode) {
244 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
245 errorCode.message().c_str());
246 }
247
248 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800249 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800250 }
251
252 return sysfsPath;
253}
254
255/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800256 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800257 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800258static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
259 std::vector<std::filesystem::path> nodes;
260 std::error_code errorCode;
261 auto iter = std::filesystem::directory_iterator(path, errorCode);
262 while (!errorCode && iter != std::filesystem::directory_iterator()) {
263 nodes.push_back(iter->path());
264 iter++;
265 }
266 return nodes;
267}
268
269/**
270 * Returns the list of files under a specified directory in a sysfs path.
271 * Example:
272 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
273 * in the sysfs path.
274 */
275static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
276 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800277 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800278 std::for_each(nodeStr.begin(), nodeStr.end(),
279 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
280 std::vector<std::filesystem::path> nodes;
281 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
282 nodes = allFilesInPath(path / nodeStr);
283 }
284 return nodes;
285}
286
287static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
288 std::filesystem::path path) {
289 std::string indexStr;
290 if (!base::ReadFileToString(path, &indexStr)) {
291 return std::nullopt;
292 }
293
294 // Parse the multi color LED index file, refer to kernel docs
295 // leds/leds-class-multicolor.html
296 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
297 std::smatch results;
298 std::array<LightColor, COLOR_NUM> colors;
299 if (!std::regex_match(indexStr, results, indexPattern)) {
300 return std::nullopt;
301 }
302
303 for (size_t i = 1; i < results.size(); i++) {
304 const auto it = LIGHT_COLORS.find(results[i].str());
305 if (it != LIGHT_COLORS.end()) {
306 // intensities.emplace(it->second, 0);
307 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800308 }
309 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800310 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800311}
312
Prabir Pradhancb42b472022-08-23 16:01:19 +0000313/**
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000314 * Read country code information exposed through the sysfs path.
315 */
316static InputDeviceCountryCode readCountryCodeLocked(const std::filesystem::path& sysfsRootPath) {
317 // Check the sysfs root path
318 int hidCountryCode = static_cast<int>(InputDeviceCountryCode::INVALID);
319 std::string str;
320 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
321 hidCountryCode = std::stoi(str, nullptr, 16);
322 LOG_ALWAYS_FATAL_IF(hidCountryCode > 35 || hidCountryCode < 0,
323 "HID country code should be in range [0, 35]. Found country code "
324 "to be %d",
325 hidCountryCode);
326 }
327
328 return static_cast<InputDeviceCountryCode>(hidCountryCode);
329}
330
331/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000332 * Read information about batteries exposed through the sysfs path.
333 */
334static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
335 const std::filesystem::path& sysfsRootPath) {
336 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
337 int32_t nextBatteryId = 0;
338 // Check if device has any battery.
339 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
340 for (const auto& nodePath : paths) {
341 RawBatteryInfo info;
342 info.id = ++nextBatteryId;
343 info.path = nodePath;
344 info.name = nodePath.filename();
345
346 // Scan the path for all the files
347 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
348 const auto& files = allFilesInPath(nodePath);
349 for (const auto& file : files) {
350 const auto it = BATTERY_CLASSES.find(file.filename().string());
351 if (it != BATTERY_CLASSES.end()) {
352 info.flags |= it->second;
353 }
354 }
355 batteryInfos.insert_or_assign(info.id, info);
356 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
357 }
358 return batteryInfos;
359}
360
361/**
362 * Read information about lights exposed through the sysfs path.
363 */
364static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
365 const std::filesystem::path& sysfsRootPath) {
366 std::unordered_map<int32_t, RawLightInfo> lightInfos;
367 int32_t nextLightId = 0;
368 // Check if device has any lights.
369 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
370 for (const auto& nodePath : paths) {
371 RawLightInfo info;
372 info.id = ++nextLightId;
373 info.path = nodePath;
374 info.name = nodePath.filename();
375 info.maxBrightness = std::nullopt;
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000376
377 // Light name should follow the naming pattern <name>:<color>:<function>
378 // Refer kernel docs /leds/leds-class.html for valid supported LED names.
379 std::regex indexPattern("([a-zA-Z0-9_.:]*:)?([a-zA-Z0-9_.]*):([a-zA-Z0-9_.]*)");
380 std::smatch results;
381
382 if (std::regex_match(info.name, results, indexPattern)) {
383 // regex_match will return full match at index 0 and <name> at index 1. For RawLightInfo
384 // we only care about sections <color> and <function> which will be at index 2 and 3.
385 for (int i = 2; i <= 3; i++) {
386 const auto it = LIGHT_CLASSES.find(results.str(i));
387 if (it != LIGHT_CLASSES.end()) {
388 info.flags |= it->second;
389 }
Prabir Pradhancb42b472022-08-23 16:01:19 +0000390 }
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000391
392 // Set name of the raw light to <function> which represents playerIDs for LEDs that
393 // turn on/off based on the current player ID (Refer to PeripheralController.cpp for
394 // player ID logic)
395 info.name = results.str(3);
Prabir Pradhancb42b472022-08-23 16:01:19 +0000396 }
397 // Scan the path for all the files
398 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
399 const auto& files = allFilesInPath(nodePath);
400 for (const auto& file : files) {
401 const auto it = LIGHT_CLASSES.find(file.filename().string());
402 if (it != LIGHT_CLASSES.end()) {
403 info.flags |= it->second;
404 // If the node has maximum brightness, read it
405 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
406 std::string str;
407 if (base::ReadFileToString(file, &str)) {
408 info.maxBrightness = std::stoi(str);
409 }
410 }
411 }
412 }
413 lightInfos.insert_or_assign(info.id, info);
414 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
415 }
416 return lightInfos;
417}
418
Michael Wrightd02c5b62014-02-10 15:10:22 -0800419// --- Global Functions ---
420
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700421ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
422 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800423 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700424 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800425 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700426 case ABS_X:
427 case ABS_Y:
428 case ABS_PRESSURE:
429 case ABS_TOOL_WIDTH:
430 case ABS_DISTANCE:
431 case ABS_TILT_X:
432 case ABS_TILT_Y:
433 case ABS_MT_SLOT:
434 case ABS_MT_TOUCH_MAJOR:
435 case ABS_MT_TOUCH_MINOR:
436 case ABS_MT_WIDTH_MAJOR:
437 case ABS_MT_WIDTH_MINOR:
438 case ABS_MT_ORIENTATION:
439 case ABS_MT_POSITION_X:
440 case ABS_MT_POSITION_Y:
441 case ABS_MT_TOOL_TYPE:
442 case ABS_MT_BLOB_ID:
443 case ABS_MT_TRACKING_ID:
444 case ABS_MT_PRESSURE:
445 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700446 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800447 }
448 }
449
Chris Yef59a2f42020-10-16 12:55:26 -0700450 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
451 switch (axis) {
452 case ABS_X:
453 case ABS_Y:
454 case ABS_Z:
455 case ABS_RX:
456 case ABS_RY:
457 case ABS_RZ:
458 return InputDeviceClass::SENSOR;
459 }
460 }
461
Michael Wright842500e2015-03-13 17:32:02 -0700462 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700463 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700464 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700465 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700466 }
467 }
468
Michael Wrightd02c5b62014-02-10 15:10:22 -0800469 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700470 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800471}
472
473// --- EventHub::Device ---
474
Prabir Pradhancb42b472022-08-23 16:01:19 +0000475EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
476 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700477 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700478 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000479 path(std::move(path)),
480 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700481 classes(0),
482 configuration(nullptr),
483 virtualKeyMap(nullptr),
484 ffEffectPlaying(false),
485 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000486 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700487 controllerNumber(0),
488 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700489 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800490
491EventHub::Device::~Device() {
492 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493}
494
495void EventHub::Device::close() {
496 if (fd >= 0) {
497 ::close(fd);
498 fd = -1;
499 }
500}
501
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700502status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100503 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700504 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100505 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700506 return -errno;
507 }
508 enabled = true;
509 return OK;
510}
511
512status_t EventHub::Device::disable() {
513 close();
514 enabled = false;
515 return OK;
516}
517
Chris Ye989bb932020-07-04 16:18:59 -0700518bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700519 return !isVirtual && enabled;
520}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800521
Chris Ye3a1e4462020-08-12 10:13:15 -0700522const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700523 return keyMap.keyCharacterMap;
524}
525
526template <std::size_t N>
527status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
528 if (!hasValidFd()) {
529 return BAD_VALUE;
530 }
531 if ((_IOC_SIZE(ioctlCode) == 0)) {
532 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
533 }
534
535 typename BitArray<N>::Buffer buffer;
536 status_t ret = ioctl(fd, ioctlCode, buffer.data());
537 bitArray.loadFromBuffer(buffer);
538 return ret;
539}
540
541void EventHub::Device::configureFd() {
542 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
543 if (classes.test(InputDeviceClass::KEYBOARD)) {
544 // Disable kernel key repeat since we handle it ourselves
545 unsigned int repeatRate[] = {0, 0};
546 if (ioctl(fd, EVIOCSREP, repeatRate)) {
547 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
548 }
549 }
550
551 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
552 // associated with input events. This is important because the input system
553 // uses the timestamps extensively and assumes they were recorded using the monotonic
554 // clock.
555 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700556 if (classes.test(InputDeviceClass::SENSOR)) {
557 // Each new sensor event should use the same time base as
558 // SystemClock.elapsedRealtimeNanos().
559 clockId = CLOCK_BOOTTIME;
560 }
Chris Ye989bb932020-07-04 16:18:59 -0700561 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
562 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
563}
564
565bool EventHub::Device::hasKeycodeLocked(int keycode) const {
566 if (!keyMap.haveKeyLayout()) {
567 return false;
568 }
569
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700570 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700571 const size_t N = scanCodes.size();
572 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
573 int32_t sc = scanCodes[i];
574 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
575 return true;
576 }
577 }
578
579 return false;
580}
581
582void EventHub::Device::loadConfigurationLocked() {
583 configurationFile =
584 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
585 InputDeviceConfigurationFileType::
586 CONFIGURATION);
587 if (configurationFile.empty()) {
588 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
589 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500590 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
591 PropertyMap::load(configurationFile.c_str());
592 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700593 ALOGE("Error loading input device configuration file for device '%s'. "
594 "Using default configuration.",
595 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500596 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500597 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700598 }
599 }
600}
601
602bool EventHub::Device::loadVirtualKeyMapLocked() {
603 // The virtual key map is supplied by the kernel as a system board property file.
604 std::string propPath = "/sys/board_properties/virtualkeys.";
605 propPath += identifier.getCanonicalName();
606 if (access(propPath.c_str(), R_OK)) {
607 return false;
608 }
609 virtualKeyMap = VirtualKeyMap::load(propPath);
610 return virtualKeyMap != nullptr;
611}
612
613status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500614 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700615}
616
617bool EventHub::Device::isExternalDeviceLocked() {
618 if (configuration) {
619 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700620 if (configuration->tryGetProperty("device.internal", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700621 return !value;
622 }
623 }
624 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
625}
626
627bool EventHub::Device::deviceHasMicLocked() {
628 if (configuration) {
629 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700630 if (configuration->tryGetProperty("audio.mic", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700631 return value;
632 }
633 }
634 return false;
635}
636
637void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
638 int32_t sc;
639 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
640 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -0700641 ev.input_event_sec = 0;
642 ev.input_event_usec = 0;
Chris Ye989bb932020-07-04 16:18:59 -0700643 ev.type = EV_LED;
644 ev.code = sc;
645 ev.value = on ? 1 : 0;
646
647 ssize_t nWrite;
648 do {
649 nWrite = write(fd, &ev, sizeof(struct input_event));
650 } while (nWrite == -1 && errno == EINTR);
651 }
652}
653
654void EventHub::Device::setLedForControllerLocked() {
655 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
656 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
657 }
658}
659
660status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
661 if (!keyMap.haveKeyLayout()) {
662 return NAME_NOT_FOUND;
663 }
664
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700665 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
666 if (scanCode.has_value()) {
667 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
668 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700669 return NO_ERROR;
670 }
671 }
672 return NAME_NOT_FOUND;
673}
674
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100675/**
676 * Get the capabilities for the current process.
677 * Crashes the system if unable to create / check / destroy the capabilities object.
678 */
679class Capabilities final {
680public:
681 explicit Capabilities() {
682 mCaps = cap_get_proc();
683 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
684 }
685
686 /**
687 * Check whether the current process has a specific capability
688 * in the set of effective capabilities.
689 * Return CAP_SET if the process has the requested capability
690 * Return CAP_CLEAR otherwise.
691 */
692 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
693 cap_flag_value_t value;
694 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
695 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
696 return value;
697 }
698
699 ~Capabilities() {
700 const int result = cap_free(mCaps);
701 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
702 }
703
704private:
705 cap_t mCaps;
706};
707
708static void ensureProcessCanBlockSuspend() {
709 Capabilities capabilities;
710 const bool canBlockSuspend =
711 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
712 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
713 "Input must be able to block suspend to properly process events");
714}
715
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716// --- EventHub ---
717
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718const int EventHub::EPOLL_MAX_EVENTS;
719
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700720EventHub::EventHub(void)
721 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
722 mNextDeviceId(1),
723 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700725 mNeedToReopenDevices(false),
726 mNeedToScanDevices(true),
727 mPendingEventCount(0),
728 mPendingEventIndex(0),
729 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100730 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800731
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800732 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800733 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800734
Michael Wright8e9a8562022-02-09 13:44:29 +0000735 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000736 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100737
738 std::error_code errorCode;
739 bool isDeviceInotifyAdded = false;
740 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
741 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800742 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100743 addDeviceInotify();
744 isDeviceInotifyAdded = true;
745 if (errorCode) {
746 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
747 errorCode.message().c_str());
748 }
749 }
750
751 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
752 addDeviceInotify();
753 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800754 ALOGI("Video device scanning disabled");
755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100757 struct epoll_event eventItem = {};
758 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700759 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800760 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800761 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
762
763 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000764 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800765 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
766
767 mWakeReadPipeFd = wakeFds[0];
768 mWakeWritePipeFd = wakeFds[1];
769
770 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
771 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700772 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773
774 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
775 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700776 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700778 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
780 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700781 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782}
783
784EventHub::~EventHub(void) {
785 closeAllDevicesLocked();
786
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787 ::close(mEpollFd);
788 ::close(mINotifyFd);
789 ::close(mWakeReadPipeFd);
790 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791}
792
Usama Arifb27c8e62021-06-03 16:44:09 +0100793/**
794 * On devices that don't have any input devices (like some development boards), the /dev/input
795 * directory will be absent. However, the user may still plug in an input device at a later time.
796 * Add watch for contents of /dev/input only when /dev/input appears.
797 */
798void EventHub::addDeviceInputInotify() {
799 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
800 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
801 DEVICE_INPUT_PATH, strerror(errno));
802}
803
804void EventHub::addDeviceInotify() {
805 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
806 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
807 strerror(errno));
808}
809
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000811 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700813 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814}
815
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700816ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000817 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700819 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820}
821
822int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000823 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700825 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826}
827
828void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Chris Ye87143712020-11-10 05:05:58 +0000829 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700831 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800832 *outConfiguration = *device->configuration;
833 } else {
834 outConfiguration->clear();
835 }
836}
837
838status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700839 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840 outAxisInfo->clear();
841
842 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000843 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844
845 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700846 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700848 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
849 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
850 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851 return -errno;
852 }
853
854 if (info.minimum != info.maximum) {
855 outAxisInfo->valid = true;
856 outAxisInfo->minValue = info.minimum;
857 outAxisInfo->maxValue = info.maximum;
858 outAxisInfo->flat = info.flat;
859 outAxisInfo->fuzz = info.fuzz;
860 outAxisInfo->resolution = info.resolution;
861 }
862 return OK;
863 }
864 }
865 return -1;
866}
867
868bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
869 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000870 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700872 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 }
874 return false;
875}
876
877bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000878 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879
Chris Ye989bb932020-07-04 16:18:59 -0700880 Device* device = getDeviceLocked(deviceId);
881 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
882 ? device->propBitmask.test(property)
883 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884}
885
Chris Yef59a2f42020-10-16 12:55:26 -0700886bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
887 std::scoped_lock _l(mLock);
888
889 Device* device = getDeviceLocked(deviceId);
890 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
891 ? device->mscBitmask.test(mscEvent)
892 : false;
893}
894
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
896 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000897 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898
899 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700900 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
901 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
902 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800903 }
904 }
905 }
906 return AKEY_STATE_UNKNOWN;
907}
908
909int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000910 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911
912 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700913 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700914 std::vector<int32_t> scanCodes = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800915 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700916 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800917 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800918 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700919 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920 return AKEY_STATE_DOWN;
921 }
922 }
923 return AKEY_STATE_UP;
924 }
925 }
926 }
927 return AKEY_STATE_UNKNOWN;
928}
929
Philip Junker4af3b3d2021-12-14 10:36:55 +0100930int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
931 std::scoped_lock _l(mLock);
932
933 Device* device = getDeviceLocked(deviceId);
934 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
935 device->keyMap.keyLayoutMap == nullptr) {
936 return AKEYCODE_UNKNOWN;
937 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700938 std::vector<int32_t> scanCodes =
939 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +0100940 if (scanCodes.empty()) {
941 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
942 "device %d",
943 locationKeyCode, deviceId);
944 return AKEYCODE_UNKNOWN;
945 }
946 if (scanCodes.size() > 1) {
947 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
948 locationKeyCode);
949 }
950 int32_t outKeyCode;
951 status_t mapKeyRes =
952 device->getKeyCharacterMap()->mapKey(scanCodes[0], 0 /*usageCode*/, &outKeyCode);
953 switch (mapKeyRes) {
954 case OK:
955 return outKeyCode;
956 case NAME_NOT_FOUND:
957 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
958 return locationKeyCode;
959 default:
960 ALOGW("Failed to get key code for key location: Key character map returned error %s",
961 statusToString(mapKeyRes).c_str());
962 return AKEYCODE_UNKNOWN;
963 }
964}
965
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
967 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000968 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969
970 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700971 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
972 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
973 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974 }
975 }
976 }
977 return AKEY_STATE_UNKNOWN;
978}
979
980status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
981 *outValue = 0;
982
983 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000984 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985
986 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700987 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700989 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
990 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
991 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992 return -errno;
993 }
994
995 *outValue = info.value;
996 return OK;
997 }
998 }
999 return -1;
1000}
1001
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001002bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001003 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001004 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005
1006 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001007 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001008 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001009 std::vector<int32_t> scanCodes =
1010 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001012 // check the possible scan codes identified by the layout map against the
1013 // map of codes actually emitted by the driver
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001014 for (const int32_t scanCode : scanCodes) {
1015 if (device->keyBitmask.test(scanCode)) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001016 outFlags[codeIndex] = 1;
1017 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 }
1019 }
1020 }
1021 return true;
1022 }
1023 return false;
1024}
1025
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001026status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1027 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001028 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001030 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031
Chris Ye66fbac32020-07-06 20:36:43 -07001032 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001034 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1035 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1037 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001038 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 }
1040 }
1041
1042 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001043 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001044 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001045 status = NO_ERROR;
1046 }
1047 }
1048
1049 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001050 if (kcm) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001051 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
1052 } else {
1053 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054 }
1055 }
1056 }
1057
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001058 if (status != NO_ERROR) {
1059 *outKeycode = 0;
1060 *outFlags = 0;
1061 *outMetaState = metaState;
1062 }
1063
1064 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065}
1066
1067status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001068 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069 Device* device = getDeviceLocked(deviceId);
1070
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001071 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1072 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001074 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1075 if (!info.has_value()) {
1076 return NAME_NOT_FOUND;
1077 }
1078 *outAxisInfo = *info;
1079 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080}
1081
Chris Yef59a2f42020-10-16 12:55:26 -07001082base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001083 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001084 std::scoped_lock _l(mLock);
1085 Device* device = getDeviceLocked(deviceId);
1086
1087 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1088 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1089 }
1090 return Errorf("Device not found or device has no key layout.");
1091}
1092
Chris Yee2b1e5c2021-03-10 22:45:12 -08001093// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1094// associated with the device ID. Returns an empty map if no miscellaneous device found.
1095const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1096 int32_t deviceId) const {
1097 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1098 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001099 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001100 return EMPTY_BATTERY_INFO;
1101 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001102 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001103}
1104
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001105std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001106 std::scoped_lock _l(mLock);
1107 std::vector<int32_t> batteryIds;
1108
Prabir Pradhan51894782022-08-23 16:29:10 +00001109 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001110 batteryIds.push_back(id);
1111 }
1112
1113 return batteryIds;
1114}
1115
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001116std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1117 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001118 std::scoped_lock _l(mLock);
1119
1120 const auto infos = getBatteryInfoLocked(deviceId);
1121
1122 auto it = infos.find(batteryId);
1123 if (it != infos.end()) {
1124 return it->second;
1125 }
1126
1127 return std::nullopt;
1128}
1129
1130// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001131// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001132const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1133 int32_t deviceId) const {
1134 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1135 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001136 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001137 return EMPTY_LIGHT_INFO;
1138 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001139 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001140}
1141
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001142std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001143 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001144 std::vector<int32_t> lightIds;
1145
Prabir Pradhan51894782022-08-23 16:29:10 +00001146 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001147 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001148 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001149
Chris Ye3fdbfef2021-01-06 18:45:18 -08001150 return lightIds;
1151}
1152
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001153std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001154 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001155
Chris Yee2b1e5c2021-03-10 22:45:12 -08001156 const auto infos = getLightInfoLocked(deviceId);
1157
1158 auto it = infos.find(lightId);
1159 if (it != infos.end()) {
1160 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001161 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001162
Chris Ye3fdbfef2021-01-06 18:45:18 -08001163 return std::nullopt;
1164}
1165
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001166std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001167 std::scoped_lock _l(mLock);
1168
Chris Yee2b1e5c2021-03-10 22:45:12 -08001169 const auto infos = getLightInfoLocked(deviceId);
1170 auto it = infos.find(lightId);
1171 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001172 return std::nullopt;
1173 }
1174 std::string buffer;
1175 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1176 &buffer)) {
1177 return std::nullopt;
1178 }
1179 return std::stoi(buffer);
1180}
1181
1182std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001183 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001184 std::scoped_lock _l(mLock);
1185
Chris Yee2b1e5c2021-03-10 22:45:12 -08001186 const auto infos = getLightInfoLocked(deviceId);
1187 auto lightIt = infos.find(lightId);
1188 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001189 return std::nullopt;
1190 }
1191
1192 auto ret =
1193 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1194
1195 if (!ret.has_value()) {
1196 return std::nullopt;
1197 }
1198 std::array<LightColor, COLOR_NUM> colors = ret.value();
1199
1200 std::string intensityStr;
1201 if (!base::ReadFileToString(lightIt->second.path /
1202 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1203 &intensityStr)) {
1204 return std::nullopt;
1205 }
1206
1207 // Intensity node outputs 3 color values
1208 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1209 std::smatch results;
1210
1211 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1212 return std::nullopt;
1213 }
1214 std::unordered_map<LightColor, int32_t> intensities;
1215 for (size_t i = 1; i < results.size(); i++) {
1216 int value = std::stoi(results[i].str());
1217 intensities.emplace(colors[i - 1], value);
1218 }
1219 return intensities;
1220}
1221
1222void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1223 std::scoped_lock _l(mLock);
1224
Chris Yee2b1e5c2021-03-10 22:45:12 -08001225 const auto infos = getLightInfoLocked(deviceId);
1226 auto lightIt = infos.find(lightId);
1227 if (lightIt == infos.end()) {
1228 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001229 return;
1230 }
1231
1232 if (!base::WriteStringToFile(std::to_string(brightness),
1233 lightIt->second.path /
1234 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1235 ALOGE("Can not write to file, error: %s", strerror(errno));
1236 }
1237}
1238
1239void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1240 std::unordered_map<LightColor, int32_t> intensities) {
1241 std::scoped_lock _l(mLock);
1242
Chris Yee2b1e5c2021-03-10 22:45:12 -08001243 const auto infos = getLightInfoLocked(deviceId);
1244 auto lightIt = infos.find(lightId);
1245 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001246 ALOGE("Light Id %d does not exist.", lightId);
1247 return;
1248 }
1249
1250 auto ret =
1251 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1252
1253 if (!ret.has_value()) {
1254 return;
1255 }
1256 std::array<LightColor, COLOR_NUM> colors = ret.value();
1257
1258 std::string rgbStr;
1259 for (size_t i = 0; i < COLOR_NUM; i++) {
1260 auto it = intensities.find(colors[i]);
1261 if (it != intensities.end()) {
1262 rgbStr += std::to_string(it->second);
1263 // Insert space between colors
1264 if (i < COLOR_NUM - 1) {
1265 rgbStr += " ";
1266 }
1267 }
1268 }
1269 // Append new line
1270 rgbStr += "\n";
1271
1272 if (!base::WriteStringToFile(rgbStr,
1273 lightIt->second.path /
1274 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1275 ALOGE("Can not write to file, error: %s", strerror(errno));
1276 }
1277}
1278
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001279InputDeviceCountryCode EventHub::getCountryCode(int32_t deviceId) const {
1280 std::scoped_lock _l(mLock);
1281 Device* device = getDeviceLocked(deviceId);
1282 if (device == nullptr || !device->associatedDevice) {
1283 return InputDeviceCountryCode::INVALID;
1284 }
1285 return device->associatedDevice->countryCode;
1286}
1287
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001288void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001289 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290
1291 mExcludedDevices = devices;
1292}
1293
1294bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001295 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001297 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1298 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 }
1300 return false;
1301}
1302
Arthur Hungcb40a002021-08-03 14:31:01 +00001303bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1304 std::scoped_lock _l(mLock);
1305 Device* device = getDeviceLocked(deviceId);
1306 if (device != nullptr) {
1307 return device->hasKeycodeLocked(keyCode);
1308 }
1309 return false;
1310}
1311
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001313 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001314 Device* device = getDeviceLocked(deviceId);
1315 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001316 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001317 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 }
1319 return false;
1320}
1321
1322void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001323 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001325 if (device != nullptr && device->hasValidFd()) {
1326 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327 }
1328}
1329
1330void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001331 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332 outVirtualKeys.clear();
1333
Chris Ye87143712020-11-10 05:05:58 +00001334 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001336 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001337 const std::vector<VirtualKeyDefinition> virtualKeys =
1338 device->virtualKeyMap->getVirtualKeys();
1339 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 }
1341}
1342
Chris Ye3a1e4462020-08-12 10:13:15 -07001343const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001344 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001346 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347 return device->getKeyCharacterMap();
1348 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001349 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350}
1351
Chris Ye3a1e4462020-08-12 10:13:15 -07001352bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001353 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354 Device* device = getDeviceLocked(deviceId);
Philip Junker90bc9492021-12-10 18:39:42 +01001355 if (device == nullptr || map == nullptr || device->keyMap.keyCharacterMap == nullptr) {
1356 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001357 }
Philip Junker90bc9492021-12-10 18:39:42 +01001358 device->keyMap.keyCharacterMap->combine(*map);
1359 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360}
1361
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001362static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1363 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001364 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001366 if (!identifier.uniqueId.empty()) {
1367 rawDescriptor += "uniqueId:";
1368 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001369 }
1370 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001371 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372 }
1373
1374 if (identifier.vendor == 0 && identifier.product == 0) {
1375 // If we don't know the vendor and product id, then the device is probably
1376 // built-in so we need to rely on other information to uniquely identify
1377 // the input device. Usually we try to avoid relying on the device name or
1378 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001379 if (!identifier.name.empty()) {
1380 rawDescriptor += "name:";
1381 rawDescriptor += identifier.name;
1382 } else if (!identifier.location.empty()) {
1383 rawDescriptor += "location:";
1384 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001385 }
1386 }
1387 identifier.descriptor = sha1(rawDescriptor);
1388 return rawDescriptor;
1389}
1390
1391void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1392 // Compute a device descriptor that uniquely identifies the device.
1393 // The descriptor is assumed to be a stable identifier. Its value should not
1394 // change between reboots, reconnections, firmware updates or new releases
1395 // of Android. In practice we sometimes get devices that cannot be uniquely
1396 // identified. In this case we enforce uniqueness between connected devices.
1397 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001398 // Note that we explicitly do not use the path or location for external devices
1399 // as their path or location will change as they are plugged/unplugged or moved
1400 // to different ports. We do fallback to using name and location in the case of
1401 // internal devices which are detected by the vendor and product being 0 in
1402 // generateDescriptor. If two identical descriptors are detected we will fallback
1403 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1404 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405
1406 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001407 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001408 // Enforce that the generated descriptor is unique.
1409 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1410 identifier.nonce++;
1411 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001412 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001413 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001414 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415}
1416
Prabir Pradhancb42b472022-08-23 16:01:19 +00001417std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1418 const std::filesystem::path& devicePath) const {
1419 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1420 getSysfsRootPath(devicePath.c_str());
1421 if (!sysfsRootPathOpt) {
1422 return nullptr;
1423 }
1424
1425 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001426
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001427 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001428 AssociatedDevice{.sysfsRootPath = path,
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001429 .countryCode = readCountryCodeLocked(path),
Prabir Pradhancb42b472022-08-23 16:01:19 +00001430 .batteryInfos = readBatteryConfiguration(path),
1431 .lightInfos = readLightsConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001432
1433 bool associatedDeviceChanged = false;
1434 for (const auto& [id, dev] : mDevices) {
1435 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1436 if (*associatedDevice != *dev->associatedDevice) {
1437 associatedDeviceChanged = true;
1438 dev->associatedDevice = associatedDevice;
1439 }
1440 associatedDevice = dev->associatedDevice;
1441 }
1442 }
1443 ALOGI_IF(associatedDeviceChanged,
1444 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1445 path.c_str(), associatedDevice->dump().c_str());
1446
1447 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001448}
1449
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001450void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001451 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001453 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 ff_effect effect;
1455 memset(&effect, 0, sizeof(effect));
1456 effect.type = FF_RUMBLE;
1457 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001458 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001459 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1460 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001461 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 effect.replay.delay = 0;
1463 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1464 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001465 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466 return;
1467 }
1468 device->ffEffectId = effect.id;
1469
1470 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001471 ev.input_event_sec = 0;
1472 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 ev.type = EV_FF;
1474 ev.code = device->ffEffectId;
1475 ev.value = 1;
1476 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1477 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001478 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479 return;
1480 }
1481 device->ffEffectPlaying = true;
1482 }
1483}
1484
1485void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001486 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001488 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489 if (device->ffEffectPlaying) {
1490 device->ffEffectPlaying = false;
1491
1492 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001493 ev.input_event_sec = 0;
1494 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 ev.type = EV_FF;
1496 ev.code = device->ffEffectId;
1497 ev.value = 0;
1498 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1499 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001500 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 return;
1502 }
1503 }
1504 }
1505}
1506
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001507std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001508 std::scoped_lock _l(mLock);
1509 std::vector<int32_t> vibrators;
1510 Device* device = getDeviceLocked(deviceId);
1511 if (device != nullptr && device->hasValidFd() &&
1512 device->classes.test(InputDeviceClass::VIBRATOR)) {
1513 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1514 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1515 }
1516 return vibrators;
1517}
1518
Josh Bartel938632f2022-07-19 15:34:22 -05001519/**
1520 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1521 */
1522bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1523 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001524 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001525 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 }
1527 }
Josh Bartel938632f2022-07-19 15:34:22 -05001528
1529 for (const auto& [id, device] : mDevices) {
1530 if (descriptor == device->identifier.descriptor) {
1531 return true;
1532 }
1533 }
1534 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535}
1536
1537EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001538 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 deviceId = mBuiltInKeyboardId;
1540 }
Chris Ye989bb932020-07-04 16:18:59 -07001541 const auto& it = mDevices.find(deviceId);
1542 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543}
1544
Chris Ye8594e192020-07-14 10:34:06 -07001545EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001546 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001548 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 }
1550 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001551 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552}
1553
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001554/**
1555 * The file descriptor could be either input device, or a video device (associated with a
1556 * specific input device). Check both cases here, and return the device that this event
1557 * belongs to. Caller can compare the fd's once more to determine event type.
1558 * Looks through all input devices, and only attached video devices. Unattached video
1559 * devices are ignored.
1560 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001561EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001562 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001563 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001564 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001565 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001566 }
1567 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1568 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001569 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001570 }
1571 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001572 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1573 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001574 return nullptr;
1575}
1576
Chris Yee2b1e5c2021-03-10 22:45:12 -08001577std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001578 std::filesystem::path batteryPath;
1579 {
1580 // Do not read the sysfs node to get the battery state while holding
1581 // the EventHub lock. For some peripheral devices, reading battery state
1582 // can be broken and take 5+ seconds. Holding the lock in this case would
1583 // block all other event processing during this time. For now, we assume this
1584 // call never happens on the InputReader thread and read the sysfs node outside
1585 // the lock to prevent event processing from being blocked by this call.
1586 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001587
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001588 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001589 auto it = infos.find(batteryId);
1590 if (it == infos.end()) {
1591 return std::nullopt;
1592 }
1593 batteryPath = it->second.path;
1594 } // release lock
1595
Chris Yee2b1e5c2021-03-10 22:45:12 -08001596 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001597
1598 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001599 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001600 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001601 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001602 }
1603
1604 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1605 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001606 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001607 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001608 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001609 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1610 if (levelIt != BATTERY_LEVEL.end()) {
1611 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001612 }
1613 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001614
Kim Low03ea0352020-11-06 12:45:07 -08001615 return std::nullopt;
1616}
1617
Chris Yee2b1e5c2021-03-10 22:45:12 -08001618std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001619 std::filesystem::path batteryPath;
1620 {
1621 // Do not read the sysfs node to get the battery state while holding
1622 // the EventHub lock. For some peripheral devices, reading battery state
1623 // can be broken and take 5+ seconds. Holding the lock in this case would
1624 // block all other event processing during this time. For now, we assume this
1625 // call never happens on the InputReader thread and read the sysfs node outside
1626 // the lock to prevent event processing from being blocked by this call.
1627 std::scoped_lock _l(mLock);
1628
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001629 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001630 auto it = infos.find(batteryId);
1631 if (it == infos.end()) {
1632 return std::nullopt;
1633 }
1634 batteryPath = it->second.path;
1635 } // release lock
1636
Chris Yee2b1e5c2021-03-10 22:45:12 -08001637 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001638
Andy Chenf9f1a022022-08-29 20:07:10 -04001639 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001640 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001641 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1642 return std::nullopt;
1643 }
1644
Chris Yed1936772021-02-22 10:30:40 -08001645 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001646 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1647 if (statusIt != BATTERY_STATUS.end()) {
1648 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001649 }
1650
1651 return std::nullopt;
1652}
1653
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001654std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001655 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001657 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001659 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660 bool awoken = false;
1661 for (;;) {
1662 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1663
1664 // Reopen input devices if needed.
1665 if (mNeedToReopenDevices) {
1666 mNeedToReopenDevices = false;
1667
1668 ALOGI("Reopening all input devices due to a configuration change.");
1669
1670 closeAllDevicesLocked();
1671 mNeedToScanDevices = true;
1672 break; // return to the caller before we actually rescan
1673 }
1674
1675 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001676 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1677 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001678 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001679 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001680 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1681 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001682 events.push_back({
1683 .when = now,
1684 .deviceId = deviceId,
1685 .type = DEVICE_REMOVED,
1686 });
Chris Ye989bb932020-07-04 16:18:59 -07001687 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001689 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690 break;
1691 }
1692 }
1693
1694 if (mNeedToScanDevices) {
1695 mNeedToScanDevices = false;
1696 scanDevicesLocked();
1697 mNeedToSendFinishedDeviceScan = true;
1698 }
1699
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001700 while (!mOpeningDevices.empty()) {
1701 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1702 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001703 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001704 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1705 events.push_back({
1706 .when = now,
1707 .deviceId = deviceId,
1708 .type = DEVICE_ADDED,
1709 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001710
1711 // Try to find a matching video device by comparing device names
1712 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1713 it++) {
1714 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001715 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001716 // videoDevice was transferred to 'device'
1717 it = mUnattachedVideoDevices.erase(it);
1718 break;
1719 }
1720 }
1721
1722 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1723 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001724 ALOGW("Device id %d exists, replaced.", device->id);
1725 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001727 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 break;
1729 }
1730 }
1731
1732 if (mNeedToSendFinishedDeviceScan) {
1733 mNeedToSendFinishedDeviceScan = false;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001734 events.push_back({
1735 .when = now,
1736 .type = FINISHED_DEVICE_SCAN,
1737 });
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001738 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 break;
1740 }
1741 }
1742
1743 // Grab the next input event.
1744 bool deviceChanged = false;
1745 while (mPendingEventIndex < mPendingEventCount) {
1746 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001747 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748 if (eventItem.events & EPOLLIN) {
1749 mPendingINotify = true;
1750 } else {
1751 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1752 }
1753 continue;
1754 }
1755
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001756 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757 if (eventItem.events & EPOLLIN) {
1758 ALOGV("awoken after wake()");
1759 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001760 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 ssize_t nRead;
1762 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001763 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1764 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765 } else {
1766 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001767 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001768 }
1769 continue;
1770 }
1771
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001772 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001773 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001774 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1775 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001776 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 continue;
1778 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001779 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1780 if (eventItem.events & EPOLLIN) {
1781 size_t numFrames = device->videoDevice->readAndQueueFrames();
1782 if (numFrames == 0) {
1783 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001784 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001785 }
1786 } else if (eventItem.events & EPOLLHUP) {
1787 // TODO(b/121395353) - consider adding EPOLLRDHUP
1788 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001789 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001790 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1791 device->videoDevice = nullptr;
1792 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001793 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1794 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001795 ALOG_ASSERT(!DEBUG);
1796 }
1797 continue;
1798 }
1799 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001801 int32_t readSize =
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001802 read(device->fd, readBuffer.data(),
1803 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1805 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001806 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001807 " capacity: %zu errno: %d)\n",
1808 device->fd, readSize, readBuffer.size(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001810 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811 } else if (readSize < 0) {
1812 if (errno != EAGAIN && errno != EINTR) {
1813 ALOGW("could not get event (errno=%d)", errno);
1814 }
1815 } else if ((readSize % sizeof(struct input_event)) != 0) {
1816 ALOGE("could not get event (wrong size: %d)", readSize);
1817 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001818 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001820 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 for (size_t i = 0; i < count; i++) {
1822 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001823 events.push_back({
1824 .when = processEventTimestamp(iev),
1825 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
1826 .deviceId = deviceId,
1827 .type = iev.type,
1828 .code = iev.code,
1829 .value = iev.value,
1830 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001832 if (events.size() >= EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 // The result buffer is full. Reset the pending event index
1834 // so we will try to read the device again on the next iteration.
1835 mPendingEventIndex -= 1;
1836 break;
1837 }
1838 }
1839 } else if (eventItem.events & EPOLLHUP) {
1840 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001841 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001843 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001845 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1846 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 }
1848 }
1849
1850 // readNotify() will modify the list of devices so this must be done after
1851 // processing all other events to ensure that we read all remaining events
1852 // before closing the devices.
1853 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1854 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00001855 const auto res = readNotifyLocked();
1856 if (!res.ok()) {
1857 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
1858 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 deviceChanged = true;
1860 }
1861
1862 // Report added or removed devices immediately.
1863 if (deviceChanged) {
1864 continue;
1865 }
1866
1867 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001868 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 break;
1870 }
1871
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001872 // Poll for events.
1873 // When a device driver has pending (unread) events, it acquires
1874 // a kernel wake lock. Once the last pending event has been read, the device
1875 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1876 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1877 // is called again for the same fd that produced the event.
1878 // Thus the system can only sleep if there are no events pending or
1879 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880 //
1881 // The timeout is advisory only. If the device is asleep, it will not wake just to
1882 // service the timeout.
1883 mPendingEventIndex = 0;
1884
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001885 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886
1887 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1888
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001889 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890
1891 if (pollResult == 0) {
1892 // Timed out.
1893 mPendingEventCount = 0;
1894 break;
1895 }
1896
1897 if (pollResult < 0) {
1898 // An error occurred.
1899 mPendingEventCount = 0;
1900
1901 // Sleep after errors to avoid locking up the system.
1902 // Hopefully the error is transient.
1903 if (errno != EINTR) {
1904 ALOGW("poll failed (errno=%d)\n", errno);
1905 usleep(100000);
1906 }
1907 } else {
1908 // Some events occurred.
1909 mPendingEventCount = size_t(pollResult);
1910 }
1911 }
1912
1913 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001914 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915}
1916
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001917std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001918 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001919
1920 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001921 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001922 return {};
1923 }
1924 return device->videoDevice->consumeFrames();
1925}
1926
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927void EventHub::wake() {
1928 ALOGV("wake() called");
1929
1930 ssize_t nWrite;
1931 do {
1932 nWrite = write(mWakeWritePipeFd, "W", 1);
1933 } while (nWrite == -1 && errno == EINTR);
1934
1935 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001936 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937 }
1938}
1939
1940void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01001941 status_t result;
1942 std::error_code errorCode;
1943
1944 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
1945 result = scanDirLocked(DEVICE_INPUT_PATH);
1946 if (result < 0) {
1947 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
1948 }
1949 } else {
1950 if (errorCode) {
1951 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
1952 errorCode.message().c_str());
1953 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001954 }
Philip Quinn39b81682019-01-09 22:20:39 -08001955 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001956 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001957 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001958 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001959 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 }
Chris Ye989bb932020-07-04 16:18:59 -07001961 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 createVirtualKeyboardLocked();
1963 }
1964}
1965
1966// ----------------------------------------------------------------------------
1967
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001969 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1970 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1971 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1972 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1973 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1974 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975};
1976
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001977status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001978 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001979 struct epoll_event eventItem = {};
1980 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1981 eventItem.data.fd = fd;
1982 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1983 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001984 return -errno;
1985 }
1986 return OK;
1987}
1988
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001989status_t EventHub::unregisterFdFromEpoll(int fd) {
1990 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1991 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1992 return -errno;
1993 }
1994 return OK;
1995}
1996
Chris Ye989bb932020-07-04 16:18:59 -07001997status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1998 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001999 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002000 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002001 return result;
2002 }
Chris Ye989bb932020-07-04 16:18:59 -07002003 if (device.videoDevice) {
2004 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002005 }
2006 return result;
2007}
2008
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002009void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2010 status_t result = registerFdForEpoll(videoDevice.getFd());
2011 if (result != OK) {
2012 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2013 }
2014}
2015
Chris Ye989bb932020-07-04 16:18:59 -07002016status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2017 if (device.hasValidFd()) {
2018 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002019 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002020 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002021 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002022 }
2023 }
Chris Ye989bb932020-07-04 16:18:59 -07002024 if (device.videoDevice) {
2025 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002026 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002027 return OK;
2028}
2029
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002030void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2031 if (videoDevice.hasValidFd()) {
2032 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2033 if (result != OK) {
2034 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002035 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002036 }
2037 }
2038}
2039
Chris Yed3fef462021-03-07 17:10:08 -08002040void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002041 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002042 SHA256_CTX ctx;
2043 SHA256_Init(&ctx);
2044 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2045 identifier.uniqueId.size());
2046 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2047 SHA256_Final(digest.data(), &ctx);
2048
2049 std::string obfuscatedId;
2050 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2051 obfuscatedId += StringPrintf("%02x", digest[i]);
2052 }
2053
Chris Yed3fef462021-03-07 17:10:08 -08002054 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2055 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002056 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002057}
2058
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002059void EventHub::openDeviceLocked(const std::string& devicePath) {
2060 // If an input device happens to register around the time when EventHub's constructor runs, it
2061 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2062 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2063 // from getting registered, ensure that this path is not already covered by an existing device.
2064 for (const auto& [deviceId, device] : mDevices) {
2065 if (device->path == devicePath) {
2066 return; // device was already registered
2067 }
2068 }
2069
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 char buffer[80];
2071
Chris Ye8594e192020-07-14 10:34:06 -07002072 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073
Chris Ye8594e192020-07-14 10:34:06 -07002074 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002075 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002076 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002077 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078 }
2079
2080 InputDeviceIdentifier identifier;
2081
2082 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002083 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002084 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085 } else {
2086 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002087 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002088 }
2089
2090 // Check to see if the device is on our excluded list
2091 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002092 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002094 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002096 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002097 }
2098 }
2099
2100 // Get device driver version.
2101 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002102 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002103 ALOGE("could not get driver version 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
2108 // Get device identifier.
2109 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002110 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002111 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002112 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002113 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 }
2115 identifier.bus = inputId.bustype;
2116 identifier.product = inputId.product;
2117 identifier.vendor = inputId.vendor;
2118 identifier.version = inputId.version;
2119
2120 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002121 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2122 // fprintf(stderr, "could not get location 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.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 }
2127
2128 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002129 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2130 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131 } else {
2132 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002133 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134 }
2135
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002136 // Attempt to get the bluetooth address of an input device from the uniqueId.
2137 if (identifier.bus == BUS_BLUETOOTH &&
2138 std::regex_match(identifier.uniqueId,
2139 std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2140 identifier.bluetoothAddress = identifier.uniqueId;
2141 // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2142 for (auto& c : *identifier.bluetoothAddress) {
2143 c = ::toupper(c);
2144 }
2145 }
2146
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147 // Fill in the descriptor.
2148 assignDescriptorLocked(identifier);
2149
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 // Allocate device. (The device object takes ownership of the fd at this point.)
2151 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002152 std::unique_ptr<Device> device =
2153 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2154 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155
Chris Ye8594e192020-07-14 10:34:06 -07002156 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002158 " vendor %04x\n"
2159 " product %04x\n"
2160 " version %04x\n",
2161 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002162 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2163 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2164 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2165 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002166 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2167 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002168
2169 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002170 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171
2172 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002173 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2174 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2175 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2176 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2177 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2178 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002179 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002180 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002182 // See if this is a device with keys. This could be full keyboard, or other devices like
2183 // gamepads, joysticks, and styluses with buttons that should generate key presses.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002184 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002185 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2186 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2187 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002188 bool haveStylusButtons = device->keyBitmask.test(BTN_STYLUS) ||
2189 device->keyBitmask.test(BTN_STYLUS2) || device->keyBitmask.test(BTN_STYLUS3);
2190 if (haveKeyboardKeys || haveGamepadButtons || haveStylusButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002191 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192 }
2193
2194 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002195 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2196 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002197 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198 }
2199
Prabir Pradhana3621852022-10-14 18:57:23 +00002200 // See if the device is specially configured to be of a certain type.
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002201 std::string deviceType;
2202 if (device->configuration && device->configuration->tryGetProperty("device.type", deviceType)) {
2203 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002204 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhana3621852022-10-14 18:57:23 +00002205 } else if (deviceType == "externalStylus") {
2206 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002207 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002208 }
2209
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210 // See if this is a touch pad.
2211 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002212 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213 // Some joysticks such as the PS3 controller report axes that conflict
2214 // with the ABS_MT range. Try to confirm that the device really is
2215 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002216 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002217 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Harry Cutts79cc9fa2022-10-28 15:32:39 +00002218 if (device->propBitmask.test(INPUT_PROP_POINTER) &&
2219 !device->keyBitmask.any(BTN_TOOL_PEN, BTN_TOOL_FINGER) && !haveStylusButtons) {
2220 device->classes |= InputDeviceClass::TOUCHPAD;
2221 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002223 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002224 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2225 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002226 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002227 // Is this a stylus that reports contact/pressure independently of touch coordinates?
Chris Ye66fbac32020-07-06 20:36:43 -07002228 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2229 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002230 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 }
2232
2233 // See if this device is a joystick.
2234 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2235 // from other devices such as accelerometers that also have absolute axes.
2236 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002237 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002239 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002240 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241 device->classes = assumedClasses;
2242 break;
2243 }
2244 }
2245 }
2246
Chris Yef59a2f42020-10-16 12:55:26 -07002247 // Check whether this device is an accelerometer.
2248 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2249 device->classes |= InputDeviceClass::SENSOR;
2250 }
2251
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252 // Check whether this device has switches.
2253 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002254 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002255 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 break;
2257 }
2258 }
2259
2260 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002261 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002262 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 }
2264
2265 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002266 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267 // Load the virtual keys for the touch screen, if any.
2268 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002269 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002270 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002271 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272 }
2273 }
2274
2275 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002276 // We need to do this for joysticks too because the key layout may specify axes, and for
2277 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002279 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2280 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002282 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 }
2284
2285 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002286 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002288 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002289 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2290 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 mBuiltInKeyboardId = device->id;
2292 }
2293
2294 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002295 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002296 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 }
2298
2299 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002300 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2301 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2302 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2303 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2304 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002305 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 }
2307
2308 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002309 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002310 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002311 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 break;
2313 }
2314 }
Prabir Pradhana3621852022-10-14 18:57:23 +00002315
2316 // See if this device has any stylus buttons that we would want to fuse with touch data.
2317 if (!device->classes.any(InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT)) {
2318 for (int32_t keycode : STYLUS_BUTTON_KEYCODES) {
2319 if (device->hasKeycodeLocked(keycode)) {
2320 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
2321 break;
2322 }
2323 }
2324 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 }
2326
2327 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002328 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002329 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002330 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002331 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332 }
2333
Chris Ye3fdbfef2021-01-06 18:45:18 -08002334 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002335 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002336 device->classes |= InputDeviceClass::BATTERY;
2337 }
Kim Low03ea0352020-11-06 12:45:07 -08002338
Chris Ye3fdbfef2021-01-06 18:45:18 -08002339 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002340 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002341 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002342 }
2343
Tim Kilbourn063ff532015-04-08 10:26:18 -07002344 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002345 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002346 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002347 }
2348
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002350 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002351 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 }
2353
Chris Ye1b0c7342020-07-28 21:57:03 -07002354 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2355 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002356 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2357 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358 }
2359
Chris Ye989bb932020-07-04 16:18:59 -07002360 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002361 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362 }
2363
Chris Ye989bb932020-07-04 16:18:59 -07002364 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002365
Chris Ye1b0c7342020-07-28 21:57:03 -07002366 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002367 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002368 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2369 device->classes.string().c_str(), device->configurationFile.c_str(),
2370 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2371 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002372
Chris Ye989bb932020-07-04 16:18:59 -07002373 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002374}
2375
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002376void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2377 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2378 if (!videoDevice) {
2379 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2380 return;
2381 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002382 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002383 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002384 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002385 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002386 }
2387 }
2388
2389 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2390 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002391 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002392 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002393 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2394}
2395
Chris Yed3fef462021-03-07 17:10:08 -08002396bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2397 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002398 if (videoDevice->getName() != device.identifier.name) {
2399 return false;
2400 }
2401 device.videoDevice = std::move(videoDevice);
2402 if (device.enabled) {
2403 registerVideoDeviceForEpollLocked(*device.videoDevice);
2404 }
2405 return true;
2406}
2407
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002408bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002409 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002410 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002411 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002412 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2413 return false;
2414 }
2415 return device->enabled;
2416}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002418status_t EventHub::enableDevice(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 %" PRId32 " already enabled", __func__, deviceId);
2427 return OK;
2428 }
2429 status_t result = device->enable();
2430 if (result != OK) {
2431 ALOGE("Failed to enable device %" PRId32, deviceId);
2432 return result;
2433 }
2434
Chris Ye989bb932020-07-04 16:18:59 -07002435 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002436
Chris Ye989bb932020-07-04 16:18:59 -07002437 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002438}
2439
2440status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002441 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002442 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002443 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002444 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2445 return BAD_VALUE;
2446 }
2447 if (!device->enabled) {
2448 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2449 return OK;
2450 }
Chris Ye989bb932020-07-04 16:18:59 -07002451 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002452 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453}
2454
2455void EventHub::createVirtualKeyboardLocked() {
2456 InputDeviceIdentifier identifier;
2457 identifier.name = "Virtual";
2458 identifier.uniqueId = "<virtual>";
2459 assignDescriptorLocked(identifier);
2460
Chris Ye989bb932020-07-04 16:18:59 -07002461 std::unique_ptr<Device> device =
2462 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Prabir Pradhancb42b472022-08-23 16:01:19 +00002463 identifier, nullptr /*associatedDevice*/);
Chris Ye1b0c7342020-07-28 21:57:03 -07002464 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2465 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002466 device->loadKeyMapLocked();
2467 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468}
2469
Chris Ye989bb932020-07-04 16:18:59 -07002470void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002471 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002472 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473}
2474
Chris Ye989bb932020-07-04 16:18:59 -07002475int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476 if (mControllerNumbers.isFull()) {
2477 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002478 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479 return 0;
2480 }
2481 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2482 // one
2483 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2484}
2485
Chris Ye989bb932020-07-04 16:18:59 -07002486void EventHub::releaseControllerNumberLocked(int32_t num) {
2487 if (num > 0) {
2488 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490}
2491
Chris Ye8594e192020-07-14 10:34:06 -07002492void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002494 if (device != nullptr) {
2495 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002496 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497 }
Chris Ye8594e192020-07-14 10:34:06 -07002498 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002499}
2500
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002501/**
2502 * Find the video device by filename, and close it.
2503 * The video device is closed by path during an inotify event, where we don't have the
2504 * additional context about the video device fd, or the associated input device.
2505 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002506void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002507 // A video device may be owned by an existing input device, or it may be stored in
2508 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002509 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002510 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002511 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002512 device->videoDevice = nullptr;
2513 return;
2514 }
2515 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002516 std::erase_if(mUnattachedVideoDevices,
2517 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2518 return videoDevice->getPath() == devicePath;
2519 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520}
2521
2522void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002523 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002524 while (!mDevices.empty()) {
2525 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526 }
2527}
2528
Chris Ye989bb932020-07-04 16:18:59 -07002529void EventHub::closeDeviceLocked(Device& device) {
2530 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2531 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532
Chris Ye989bb932020-07-04 16:18:59 -07002533 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002535 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002536 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2537 }
2538
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002539 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002540 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002541 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002542 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544
Chris Ye989bb932020-07-04 16:18:59 -07002545 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002546 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002547 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002548 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002549
Chris Ye989bb932020-07-04 16:18:59 -07002550 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002551}
2552
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002553base::Result<void> EventHub::readNotifyLocked() {
2554 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2555 uint8_t eventBuffer[512];
2556 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557
2558 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002559 do {
2560 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2561 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002563 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2564
2565 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2566 const inotify_event* event;
2567 event = (const inotify_event*)(eventBuffer + eventPos);
2568 if (event->len == 0) continue;
2569
2570 handleNotifyEventLocked(*event);
2571
2572 const ssize_t eventSize = EVENT_SIZE + event->len;
2573 sizeRead -= eventSize;
2574 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002575 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002576 return {};
2577}
2578
2579void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2580 if (event.wd == mDeviceInputWd) {
2581 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2582 if (event.mask & IN_CREATE) {
2583 openDeviceLocked(filename);
2584 } else {
2585 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2586 closeDeviceByPathLocked(filename);
2587 }
2588 } else if (event.wd == mDeviceWd) {
2589 if (isV4lTouchNode(event.name)) {
2590 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2591 if (event.mask & IN_CREATE) {
2592 openVideoDeviceLocked(filename);
2593 } else {
2594 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2595 closeVideoDeviceByPathLocked(filename);
2596 }
2597 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2598 addDeviceInputInotify();
2599 }
2600 } else {
2601 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603}
2604
Chris Ye8594e192020-07-14 10:34:06 -07002605status_t EventHub::scanDirLocked(const std::string& dirname) {
2606 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2607 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002608 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 return 0;
2610}
2611
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002612/**
2613 * Look for all dirname/v4l-touch* devices, and open them.
2614 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002615status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002616 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2617 if (isV4lTouchNode(entry.path())) {
2618 ALOGI("Found touch video device %s", entry.path().c_str());
2619 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002620 }
2621 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002622 return OK;
2623}
2624
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625void EventHub::requestReopenDevices() {
2626 ALOGV("requestReopenDevices() called");
2627
Chris Ye87143712020-11-10 05:05:58 +00002628 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629 mNeedToReopenDevices = true;
2630}
2631
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002632void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002633 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002634
2635 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002636 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002638 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002640 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002641
Chris Ye989bb932020-07-04 16:18:59 -07002642 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002644 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002645 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002647 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002648 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002650 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002651 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002652 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002653 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2654 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002655 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002656 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002657 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002658 "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002659 device->identifier.bus, device->identifier.vendor,
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002660 device->identifier.product, device->identifier.version,
2661 toString(device->identifier.bluetoothAddress).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002662 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002663 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002664 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002665 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00002666 dump += StringPrintf(INDENT3 "CountryCode: %d\n",
2667 device->associatedDevice ? device->associatedDevice->countryCode
2668 : InputDeviceCountryCode::INVALID);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002669 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002670 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002671 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2672 device->videoDevice ? device->videoDevice->dump().c_str()
2673 : "<none>");
2674 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2675 device->associatedDevice
2676 ? device->associatedDevice->sysfsRootPath.c_str()
2677 : "<none>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002678 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002679
2680 dump += INDENT "Unattached video devices:\n";
2681 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2682 dump += INDENT2 + videoDevice->dump() + "\n";
2683 }
2684 if (mUnattachedVideoDevices.empty()) {
2685 dump += INDENT2 "<none>\n";
2686 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687 } // release lock
2688}
2689
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002690void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002692 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002693}
2694
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002695std::string EventHub::AssociatedDevice::dump() const {
2696 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2697 batteryInfos.size(), lightInfos.size());
2698}
2699
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002700} // namespace android