blob: e26bc8c6dc22263f0c9e8c67e3b1328e657f1a29 [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:
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +0000955 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +0100956 case NAME_NOT_FOUND:
957 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +0000958 outKeyCode = locationKeyCode;
959 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +0100960 default:
961 ALOGW("Failed to get key code for key location: Key character map returned error %s",
962 statusToString(mapKeyRes).c_str());
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +0000963 outKeyCode = AKEYCODE_UNKNOWN;
964 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +0100965 }
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +0000966 // Remap if there is a Key remapping added to the KCM and return the remapped key
967 return device->getKeyCharacterMap()->applyKeyRemapping(outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +0100968}
969
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
971 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000972 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973
974 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700975 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
976 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
977 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 }
979 }
980 }
981 return AKEY_STATE_UNKNOWN;
982}
983
984status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
985 *outValue = 0;
986
987 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000988 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989
990 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700991 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700993 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
994 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
995 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996 return -errno;
997 }
998
999 *outValue = info.value;
1000 return OK;
1001 }
1002 }
1003 return -1;
1004}
1005
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001006bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001007 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001008 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009
1010 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001011 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001012 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001013 std::vector<int32_t> scanCodes =
1014 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001016 // check the possible scan codes identified by the layout map against the
1017 // map of codes actually emitted by the driver
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001018 for (const int32_t scanCode : scanCodes) {
1019 if (device->keyBitmask.test(scanCode)) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001020 outFlags[codeIndex] = 1;
1021 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022 }
1023 }
1024 }
1025 return true;
1026 }
1027 return false;
1028}
1029
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001030void EventHub::addKeyRemapping(int32_t deviceId, int32_t fromKeyCode, int32_t toKeyCode) const {
1031 std::scoped_lock _l(mLock);
1032 Device* device = getDeviceLocked(deviceId);
1033 if (device == nullptr) {
1034 return;
1035 }
1036 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1037 if (kcm) {
1038 kcm->addKeyRemapping(fromKeyCode, toKeyCode);
1039 }
1040}
1041
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001042status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1043 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001044 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001046 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047
Chris Ye66fbac32020-07-06 20:36:43 -07001048 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001050 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1051 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1053 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001054 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 }
1056 }
1057
1058 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001059 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001060 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001061 status = NO_ERROR;
1062 }
1063 }
1064
1065 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001066 if (kcm) {
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001067 // Remap keys based on user-defined key remappings and key behavior defined in the
1068 // corresponding kcm file
1069 *outKeycode = kcm->applyKeyRemapping(*outKeycode);
1070
1071 // Remap keys based on Key behavior defined in KCM file
1072 std::tie(*outKeycode, *outMetaState) =
1073 kcm->applyKeyBehavior(*outKeycode, metaState);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001074 } else {
1075 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 }
1077 }
1078 }
1079
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001080 if (status != NO_ERROR) {
1081 *outKeycode = 0;
1082 *outFlags = 0;
1083 *outMetaState = metaState;
1084 }
1085
1086 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087}
1088
1089status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001090 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091 Device* device = getDeviceLocked(deviceId);
1092
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001093 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1094 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001096 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1097 if (!info.has_value()) {
1098 return NAME_NOT_FOUND;
1099 }
1100 *outAxisInfo = *info;
1101 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102}
1103
Chris Yef59a2f42020-10-16 12:55:26 -07001104base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001105 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001106 std::scoped_lock _l(mLock);
1107 Device* device = getDeviceLocked(deviceId);
1108
1109 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1110 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1111 }
1112 return Errorf("Device not found or device has no key layout.");
1113}
1114
Chris Yee2b1e5c2021-03-10 22:45:12 -08001115// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1116// associated with the device ID. Returns an empty map if no miscellaneous device found.
1117const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1118 int32_t deviceId) const {
1119 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1120 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001121 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001122 return EMPTY_BATTERY_INFO;
1123 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001124 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001125}
1126
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001127std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001128 std::scoped_lock _l(mLock);
1129 std::vector<int32_t> batteryIds;
1130
Prabir Pradhan51894782022-08-23 16:29:10 +00001131 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001132 batteryIds.push_back(id);
1133 }
1134
1135 return batteryIds;
1136}
1137
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001138std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1139 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001140 std::scoped_lock _l(mLock);
1141
1142 const auto infos = getBatteryInfoLocked(deviceId);
1143
1144 auto it = infos.find(batteryId);
1145 if (it != infos.end()) {
1146 return it->second;
1147 }
1148
1149 return std::nullopt;
1150}
1151
1152// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001153// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001154const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1155 int32_t deviceId) const {
1156 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1157 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001158 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001159 return EMPTY_LIGHT_INFO;
1160 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001161 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001162}
1163
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001164std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001165 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001166 std::vector<int32_t> lightIds;
1167
Prabir Pradhan51894782022-08-23 16:29:10 +00001168 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001169 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001170 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001171
Chris Ye3fdbfef2021-01-06 18:45:18 -08001172 return lightIds;
1173}
1174
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001175std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001176 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001177
Chris Yee2b1e5c2021-03-10 22:45:12 -08001178 const auto infos = getLightInfoLocked(deviceId);
1179
1180 auto it = infos.find(lightId);
1181 if (it != infos.end()) {
1182 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001183 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001184
Chris Ye3fdbfef2021-01-06 18:45:18 -08001185 return std::nullopt;
1186}
1187
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001188std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001189 std::scoped_lock _l(mLock);
1190
Chris Yee2b1e5c2021-03-10 22:45:12 -08001191 const auto infos = getLightInfoLocked(deviceId);
1192 auto it = infos.find(lightId);
1193 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001194 return std::nullopt;
1195 }
1196 std::string buffer;
1197 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1198 &buffer)) {
1199 return std::nullopt;
1200 }
1201 return std::stoi(buffer);
1202}
1203
1204std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001205 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001206 std::scoped_lock _l(mLock);
1207
Chris Yee2b1e5c2021-03-10 22:45:12 -08001208 const auto infos = getLightInfoLocked(deviceId);
1209 auto lightIt = infos.find(lightId);
1210 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001211 return std::nullopt;
1212 }
1213
1214 auto ret =
1215 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1216
1217 if (!ret.has_value()) {
1218 return std::nullopt;
1219 }
1220 std::array<LightColor, COLOR_NUM> colors = ret.value();
1221
1222 std::string intensityStr;
1223 if (!base::ReadFileToString(lightIt->second.path /
1224 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1225 &intensityStr)) {
1226 return std::nullopt;
1227 }
1228
1229 // Intensity node outputs 3 color values
1230 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1231 std::smatch results;
1232
1233 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1234 return std::nullopt;
1235 }
1236 std::unordered_map<LightColor, int32_t> intensities;
1237 for (size_t i = 1; i < results.size(); i++) {
1238 int value = std::stoi(results[i].str());
1239 intensities.emplace(colors[i - 1], value);
1240 }
1241 return intensities;
1242}
1243
1244void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1245 std::scoped_lock _l(mLock);
1246
Chris Yee2b1e5c2021-03-10 22:45:12 -08001247 const auto infos = getLightInfoLocked(deviceId);
1248 auto lightIt = infos.find(lightId);
1249 if (lightIt == infos.end()) {
1250 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001251 return;
1252 }
1253
1254 if (!base::WriteStringToFile(std::to_string(brightness),
1255 lightIt->second.path /
1256 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1257 ALOGE("Can not write to file, error: %s", strerror(errno));
1258 }
1259}
1260
1261void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1262 std::unordered_map<LightColor, int32_t> intensities) {
1263 std::scoped_lock _l(mLock);
1264
Chris Yee2b1e5c2021-03-10 22:45:12 -08001265 const auto infos = getLightInfoLocked(deviceId);
1266 auto lightIt = infos.find(lightId);
1267 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001268 ALOGE("Light Id %d does not exist.", lightId);
1269 return;
1270 }
1271
1272 auto ret =
1273 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1274
1275 if (!ret.has_value()) {
1276 return;
1277 }
1278 std::array<LightColor, COLOR_NUM> colors = ret.value();
1279
1280 std::string rgbStr;
1281 for (size_t i = 0; i < COLOR_NUM; i++) {
1282 auto it = intensities.find(colors[i]);
1283 if (it != intensities.end()) {
1284 rgbStr += std::to_string(it->second);
1285 // Insert space between colors
1286 if (i < COLOR_NUM - 1) {
1287 rgbStr += " ";
1288 }
1289 }
1290 }
1291 // Append new line
1292 rgbStr += "\n";
1293
1294 if (!base::WriteStringToFile(rgbStr,
1295 lightIt->second.path /
1296 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1297 ALOGE("Can not write to file, error: %s", strerror(errno));
1298 }
1299}
1300
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001301InputDeviceCountryCode EventHub::getCountryCode(int32_t deviceId) const {
1302 std::scoped_lock _l(mLock);
1303 Device* device = getDeviceLocked(deviceId);
1304 if (device == nullptr || !device->associatedDevice) {
1305 return InputDeviceCountryCode::INVALID;
1306 }
1307 return device->associatedDevice->countryCode;
1308}
1309
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001310void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001311 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312
1313 mExcludedDevices = devices;
1314}
1315
1316bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001317 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001319 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1320 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 }
1322 return false;
1323}
1324
Arthur Hungcb40a002021-08-03 14:31:01 +00001325bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1326 std::scoped_lock _l(mLock);
1327 Device* device = getDeviceLocked(deviceId);
1328 if (device != nullptr) {
1329 return device->hasKeycodeLocked(keyCode);
1330 }
1331 return false;
1332}
1333
Michael Wrightd02c5b62014-02-10 15:10:22 -08001334bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001335 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001336 Device* device = getDeviceLocked(deviceId);
1337 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001338 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001339 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 }
1341 return false;
1342}
1343
1344void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001345 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001347 if (device != nullptr && device->hasValidFd()) {
1348 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 }
1350}
1351
1352void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001353 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354 outVirtualKeys.clear();
1355
Chris Ye87143712020-11-10 05:05:58 +00001356 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001357 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001358 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001359 const std::vector<VirtualKeyDefinition> virtualKeys =
1360 device->virtualKeyMap->getVirtualKeys();
1361 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 }
1363}
1364
Chris Ye3a1e4462020-08-12 10:13:15 -07001365const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001366 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001368 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 return device->getKeyCharacterMap();
1370 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001371 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372}
1373
Chris Ye3a1e4462020-08-12 10:13:15 -07001374bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001375 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 Device* device = getDeviceLocked(deviceId);
Philip Junker90bc9492021-12-10 18:39:42 +01001377 if (device == nullptr || map == nullptr || device->keyMap.keyCharacterMap == nullptr) {
1378 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379 }
Philip Junker90bc9492021-12-10 18:39:42 +01001380 device->keyMap.keyCharacterMap->combine(*map);
1381 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382}
1383
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001384static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1385 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001386 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001388 if (!identifier.uniqueId.empty()) {
1389 rawDescriptor += "uniqueId:";
1390 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001391 }
1392 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001393 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 }
1395
1396 if (identifier.vendor == 0 && identifier.product == 0) {
1397 // If we don't know the vendor and product id, then the device is probably
1398 // built-in so we need to rely on other information to uniquely identify
1399 // the input device. Usually we try to avoid relying on the device name or
1400 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001401 if (!identifier.name.empty()) {
1402 rawDescriptor += "name:";
1403 rawDescriptor += identifier.name;
1404 } else if (!identifier.location.empty()) {
1405 rawDescriptor += "location:";
1406 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407 }
1408 }
1409 identifier.descriptor = sha1(rawDescriptor);
1410 return rawDescriptor;
1411}
1412
1413void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1414 // Compute a device descriptor that uniquely identifies the device.
1415 // The descriptor is assumed to be a stable identifier. Its value should not
1416 // change between reboots, reconnections, firmware updates or new releases
1417 // of Android. In practice we sometimes get devices that cannot be uniquely
1418 // identified. In this case we enforce uniqueness between connected devices.
1419 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001420 // Note that we explicitly do not use the path or location for external devices
1421 // as their path or location will change as they are plugged/unplugged or moved
1422 // to different ports. We do fallback to using name and location in the case of
1423 // internal devices which are detected by the vendor and product being 0 in
1424 // generateDescriptor. If two identical descriptors are detected we will fallback
1425 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1426 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427
1428 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001429 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001430 // Enforce that the generated descriptor is unique.
1431 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1432 identifier.nonce++;
1433 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001435 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001436 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437}
1438
Prabir Pradhancb42b472022-08-23 16:01:19 +00001439std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1440 const std::filesystem::path& devicePath) const {
1441 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1442 getSysfsRootPath(devicePath.c_str());
1443 if (!sysfsRootPathOpt) {
1444 return nullptr;
1445 }
1446
1447 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001448
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001449 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001450 AssociatedDevice{.sysfsRootPath = path,
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001451 .countryCode = readCountryCodeLocked(path),
Prabir Pradhancb42b472022-08-23 16:01:19 +00001452 .batteryInfos = readBatteryConfiguration(path),
1453 .lightInfos = readLightsConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001454
1455 bool associatedDeviceChanged = false;
1456 for (const auto& [id, dev] : mDevices) {
1457 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1458 if (*associatedDevice != *dev->associatedDevice) {
1459 associatedDeviceChanged = true;
1460 dev->associatedDevice = associatedDevice;
1461 }
1462 associatedDevice = dev->associatedDevice;
1463 }
1464 }
1465 ALOGI_IF(associatedDeviceChanged,
1466 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1467 path.c_str(), associatedDevice->dump().c_str());
1468
1469 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001470}
1471
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001472void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001473 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001475 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 ff_effect effect;
1477 memset(&effect, 0, sizeof(effect));
1478 effect.type = FF_RUMBLE;
1479 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001480 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001481 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1482 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001483 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484 effect.replay.delay = 0;
1485 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1486 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001487 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 return;
1489 }
1490 device->ffEffectId = effect.id;
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 = 1;
1498 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1499 ALOGW("Could not start 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 device->ffEffectPlaying = true;
1504 }
1505}
1506
1507void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001508 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001510 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 if (device->ffEffectPlaying) {
1512 device->ffEffectPlaying = false;
1513
1514 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001515 ev.input_event_sec = 0;
1516 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 ev.type = EV_FF;
1518 ev.code = device->ffEffectId;
1519 ev.value = 0;
1520 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1521 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001522 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523 return;
1524 }
1525 }
1526 }
1527}
1528
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001529std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001530 std::scoped_lock _l(mLock);
1531 std::vector<int32_t> vibrators;
1532 Device* device = getDeviceLocked(deviceId);
1533 if (device != nullptr && device->hasValidFd() &&
1534 device->classes.test(InputDeviceClass::VIBRATOR)) {
1535 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1536 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1537 }
1538 return vibrators;
1539}
1540
Josh Bartel938632f2022-07-19 15:34:22 -05001541/**
1542 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1543 */
1544bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1545 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001546 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001547 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548 }
1549 }
Josh Bartel938632f2022-07-19 15:34:22 -05001550
1551 for (const auto& [id, device] : mDevices) {
1552 if (descriptor == device->identifier.descriptor) {
1553 return true;
1554 }
1555 }
1556 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557}
1558
1559EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001560 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561 deviceId = mBuiltInKeyboardId;
1562 }
Chris Ye989bb932020-07-04 16:18:59 -07001563 const auto& it = mDevices.find(deviceId);
1564 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565}
1566
Chris Ye8594e192020-07-14 10:34:06 -07001567EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001568 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001570 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 }
1572 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001573 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574}
1575
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001576/**
1577 * The file descriptor could be either input device, or a video device (associated with a
1578 * specific input device). Check both cases here, and return the device that this event
1579 * belongs to. Caller can compare the fd's once more to determine event type.
1580 * Looks through all input devices, and only attached video devices. Unattached video
1581 * devices are ignored.
1582 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001583EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001584 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001585 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001586 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001587 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001588 }
1589 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1590 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001591 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001592 }
1593 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001594 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1595 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001596 return nullptr;
1597}
1598
Chris Yee2b1e5c2021-03-10 22:45:12 -08001599std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001600 std::filesystem::path batteryPath;
1601 {
1602 // Do not read the sysfs node to get the battery state while holding
1603 // the EventHub lock. For some peripheral devices, reading battery state
1604 // can be broken and take 5+ seconds. Holding the lock in this case would
1605 // block all other event processing during this time. For now, we assume this
1606 // call never happens on the InputReader thread and read the sysfs node outside
1607 // the lock to prevent event processing from being blocked by this call.
1608 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001609
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001610 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001611 auto it = infos.find(batteryId);
1612 if (it == infos.end()) {
1613 return std::nullopt;
1614 }
1615 batteryPath = it->second.path;
1616 } // release lock
1617
Chris Yee2b1e5c2021-03-10 22:45:12 -08001618 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001619
1620 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001621 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001622 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001623 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001624 }
1625
1626 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1627 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001628 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001629 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001630 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001631 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1632 if (levelIt != BATTERY_LEVEL.end()) {
1633 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001634 }
1635 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001636
Kim Low03ea0352020-11-06 12:45:07 -08001637 return std::nullopt;
1638}
1639
Chris Yee2b1e5c2021-03-10 22:45:12 -08001640std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001641 std::filesystem::path batteryPath;
1642 {
1643 // Do not read the sysfs node to get the battery state while holding
1644 // the EventHub lock. For some peripheral devices, reading battery state
1645 // can be broken and take 5+ seconds. Holding the lock in this case would
1646 // block all other event processing during this time. For now, we assume this
1647 // call never happens on the InputReader thread and read the sysfs node outside
1648 // the lock to prevent event processing from being blocked by this call.
1649 std::scoped_lock _l(mLock);
1650
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001651 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001652 auto it = infos.find(batteryId);
1653 if (it == infos.end()) {
1654 return std::nullopt;
1655 }
1656 batteryPath = it->second.path;
1657 } // release lock
1658
Chris Yee2b1e5c2021-03-10 22:45:12 -08001659 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001660
Andy Chenf9f1a022022-08-29 20:07:10 -04001661 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001662 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001663 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1664 return std::nullopt;
1665 }
1666
Chris Yed1936772021-02-22 10:30:40 -08001667 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001668 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1669 if (statusIt != BATTERY_STATUS.end()) {
1670 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001671 }
1672
1673 return std::nullopt;
1674}
1675
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001676std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001677 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001679 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001681 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 bool awoken = false;
1683 for (;;) {
1684 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1685
1686 // Reopen input devices if needed.
1687 if (mNeedToReopenDevices) {
1688 mNeedToReopenDevices = false;
1689
1690 ALOGI("Reopening all input devices due to a configuration change.");
1691
1692 closeAllDevicesLocked();
1693 mNeedToScanDevices = true;
1694 break; // return to the caller before we actually rescan
1695 }
1696
1697 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001698 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1699 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001700 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001701 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001702 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1703 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001704 events.push_back({
1705 .when = now,
1706 .deviceId = deviceId,
1707 .type = DEVICE_REMOVED,
1708 });
Chris Ye989bb932020-07-04 16:18:59 -07001709 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001710 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001711 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712 break;
1713 }
1714 }
1715
1716 if (mNeedToScanDevices) {
1717 mNeedToScanDevices = false;
1718 scanDevicesLocked();
1719 mNeedToSendFinishedDeviceScan = true;
1720 }
1721
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001722 while (!mOpeningDevices.empty()) {
1723 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1724 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001725 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001726 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1727 events.push_back({
1728 .when = now,
1729 .deviceId = deviceId,
1730 .type = DEVICE_ADDED,
1731 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001732
1733 // Try to find a matching video device by comparing device names
1734 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1735 it++) {
1736 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001737 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001738 // videoDevice was transferred to 'device'
1739 it = mUnattachedVideoDevices.erase(it);
1740 break;
1741 }
1742 }
1743
1744 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1745 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001746 ALOGW("Device id %d exists, replaced.", device->id);
1747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001749 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 break;
1751 }
1752 }
1753
1754 if (mNeedToSendFinishedDeviceScan) {
1755 mNeedToSendFinishedDeviceScan = false;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001756 events.push_back({
1757 .when = now,
1758 .type = FINISHED_DEVICE_SCAN,
1759 });
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001760 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 break;
1762 }
1763 }
1764
1765 // Grab the next input event.
1766 bool deviceChanged = false;
1767 while (mPendingEventIndex < mPendingEventCount) {
1768 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001769 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 if (eventItem.events & EPOLLIN) {
1771 mPendingINotify = true;
1772 } else {
1773 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1774 }
1775 continue;
1776 }
1777
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001778 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779 if (eventItem.events & EPOLLIN) {
1780 ALOGV("awoken after wake()");
1781 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001782 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 ssize_t nRead;
1784 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001785 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1786 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 } else {
1788 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001789 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001790 }
1791 continue;
1792 }
1793
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001794 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001795 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001796 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1797 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001798 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 continue;
1800 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001801 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1802 if (eventItem.events & EPOLLIN) {
1803 size_t numFrames = device->videoDevice->readAndQueueFrames();
1804 if (numFrames == 0) {
1805 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001806 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001807 }
1808 } else if (eventItem.events & EPOLLHUP) {
1809 // TODO(b/121395353) - consider adding EPOLLRDHUP
1810 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001811 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001812 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1813 device->videoDevice = nullptr;
1814 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001815 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1816 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001817 ALOG_ASSERT(!DEBUG);
1818 }
1819 continue;
1820 }
1821 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001823 int32_t readSize =
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001824 read(device->fd, readBuffer.data(),
1825 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1827 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001828 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001829 " capacity: %zu errno: %d)\n",
1830 device->fd, readSize, readBuffer.size(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001832 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 } else if (readSize < 0) {
1834 if (errno != EAGAIN && errno != EINTR) {
1835 ALOGW("could not get event (errno=%d)", errno);
1836 }
1837 } else if ((readSize % sizeof(struct input_event)) != 0) {
1838 ALOGE("could not get event (wrong size: %d)", readSize);
1839 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001840 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001842 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843 for (size_t i = 0; i < count; i++) {
1844 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001845 events.push_back({
1846 .when = processEventTimestamp(iev),
1847 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
1848 .deviceId = deviceId,
1849 .type = iev.type,
1850 .code = iev.code,
1851 .value = iev.value,
1852 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001854 if (events.size() >= EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855 // The result buffer is full. Reset the pending event index
1856 // so we will try to read the device again on the next iteration.
1857 mPendingEventIndex -= 1;
1858 break;
1859 }
1860 }
1861 } else if (eventItem.events & EPOLLHUP) {
1862 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001863 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001865 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001867 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1868 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 }
1870 }
1871
1872 // readNotify() will modify the list of devices so this must be done after
1873 // processing all other events to ensure that we read all remaining events
1874 // before closing the devices.
1875 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1876 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00001877 const auto res = readNotifyLocked();
1878 if (!res.ok()) {
1879 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
1880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 deviceChanged = true;
1882 }
1883
1884 // Report added or removed devices immediately.
1885 if (deviceChanged) {
1886 continue;
1887 }
1888
1889 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001890 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891 break;
1892 }
1893
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001894 // Poll for events.
1895 // When a device driver has pending (unread) events, it acquires
1896 // a kernel wake lock. Once the last pending event has been read, the device
1897 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1898 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1899 // is called again for the same fd that produced the event.
1900 // Thus the system can only sleep if there are no events pending or
1901 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902 //
1903 // The timeout is advisory only. If the device is asleep, it will not wake just to
1904 // service the timeout.
1905 mPendingEventIndex = 0;
1906
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001907 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908
1909 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1910
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001911 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912
1913 if (pollResult == 0) {
1914 // Timed out.
1915 mPendingEventCount = 0;
1916 break;
1917 }
1918
1919 if (pollResult < 0) {
1920 // An error occurred.
1921 mPendingEventCount = 0;
1922
1923 // Sleep after errors to avoid locking up the system.
1924 // Hopefully the error is transient.
1925 if (errno != EINTR) {
1926 ALOGW("poll failed (errno=%d)\n", errno);
1927 usleep(100000);
1928 }
1929 } else {
1930 // Some events occurred.
1931 mPendingEventCount = size_t(pollResult);
1932 }
1933 }
1934
1935 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001936 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937}
1938
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001939std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001940 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001941
1942 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001943 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001944 return {};
1945 }
1946 return device->videoDevice->consumeFrames();
1947}
1948
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949void EventHub::wake() {
1950 ALOGV("wake() called");
1951
1952 ssize_t nWrite;
1953 do {
1954 nWrite = write(mWakeWritePipeFd, "W", 1);
1955 } while (nWrite == -1 && errno == EINTR);
1956
1957 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001958 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 }
1960}
1961
1962void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01001963 status_t result;
1964 std::error_code errorCode;
1965
1966 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
1967 result = scanDirLocked(DEVICE_INPUT_PATH);
1968 if (result < 0) {
1969 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
1970 }
1971 } else {
1972 if (errorCode) {
1973 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
1974 errorCode.message().c_str());
1975 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001976 }
Philip Quinn39b81682019-01-09 22:20:39 -08001977 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001978 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001979 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001980 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982 }
Chris Ye989bb932020-07-04 16:18:59 -07001983 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984 createVirtualKeyboardLocked();
1985 }
1986}
1987
1988// ----------------------------------------------------------------------------
1989
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001991 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1992 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1993 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1994 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1995 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1996 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997};
1998
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001999status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002000 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002001 struct epoll_event eventItem = {};
2002 eventItem.events = EPOLLIN | EPOLLWAKEUP;
2003 eventItem.data.fd = fd;
2004 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
2005 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002006 return -errno;
2007 }
2008 return OK;
2009}
2010
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002011status_t EventHub::unregisterFdFromEpoll(int fd) {
2012 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
2013 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
2014 return -errno;
2015 }
2016 return OK;
2017}
2018
Chris Ye989bb932020-07-04 16:18:59 -07002019status_t EventHub::registerDeviceForEpollLocked(Device& device) {
2020 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002021 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002022 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002023 return result;
2024 }
Chris Ye989bb932020-07-04 16:18:59 -07002025 if (device.videoDevice) {
2026 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002027 }
2028 return result;
2029}
2030
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002031void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2032 status_t result = registerFdForEpoll(videoDevice.getFd());
2033 if (result != OK) {
2034 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2035 }
2036}
2037
Chris Ye989bb932020-07-04 16:18:59 -07002038status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2039 if (device.hasValidFd()) {
2040 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002041 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002042 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002043 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002044 }
2045 }
Chris Ye989bb932020-07-04 16:18:59 -07002046 if (device.videoDevice) {
2047 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002048 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002049 return OK;
2050}
2051
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002052void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2053 if (videoDevice.hasValidFd()) {
2054 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2055 if (result != OK) {
2056 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002057 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002058 }
2059 }
2060}
2061
Chris Yed3fef462021-03-07 17:10:08 -08002062void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002063 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002064 SHA256_CTX ctx;
2065 SHA256_Init(&ctx);
2066 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2067 identifier.uniqueId.size());
2068 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2069 SHA256_Final(digest.data(), &ctx);
2070
2071 std::string obfuscatedId;
2072 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2073 obfuscatedId += StringPrintf("%02x", digest[i]);
2074 }
2075
Chris Yed3fef462021-03-07 17:10:08 -08002076 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2077 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002078 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002079}
2080
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002081void EventHub::openDeviceLocked(const std::string& devicePath) {
2082 // If an input device happens to register around the time when EventHub's constructor runs, it
2083 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2084 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2085 // from getting registered, ensure that this path is not already covered by an existing device.
2086 for (const auto& [deviceId, device] : mDevices) {
2087 if (device->path == devicePath) {
2088 return; // device was already registered
2089 }
2090 }
2091
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092 char buffer[80];
2093
Chris Ye8594e192020-07-14 10:34:06 -07002094 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095
Chris Ye8594e192020-07-14 10:34:06 -07002096 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002097 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002098 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002099 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002100 }
2101
2102 InputDeviceIdentifier identifier;
2103
2104 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002105 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002106 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 } else {
2108 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002109 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110 }
2111
2112 // Check to see if the device is on our excluded list
2113 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002114 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002116 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002118 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119 }
2120 }
2121
2122 // Get device driver version.
2123 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002124 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002125 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002127 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128 }
2129
2130 // Get device identifier.
2131 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002132 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002133 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002135 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136 }
2137 identifier.bus = inputId.bustype;
2138 identifier.product = inputId.product;
2139 identifier.vendor = inputId.vendor;
2140 identifier.version = inputId.version;
2141
2142 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002143 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2144 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145 } else {
2146 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002147 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 }
2149
2150 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002151 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2152 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 } else {
2154 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002155 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 }
2157
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002158 // Attempt to get the bluetooth address of an input device from the uniqueId.
2159 if (identifier.bus == BUS_BLUETOOTH &&
2160 std::regex_match(identifier.uniqueId,
2161 std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2162 identifier.bluetoothAddress = identifier.uniqueId;
2163 // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2164 for (auto& c : *identifier.bluetoothAddress) {
2165 c = ::toupper(c);
2166 }
2167 }
2168
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169 // Fill in the descriptor.
2170 assignDescriptorLocked(identifier);
2171
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172 // Allocate device. (The device object takes ownership of the fd at this point.)
2173 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002174 std::unique_ptr<Device> device =
2175 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2176 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177
Chris Ye8594e192020-07-14 10:34:06 -07002178 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002179 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002180 " vendor %04x\n"
2181 " product %04x\n"
2182 " version %04x\n",
2183 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002184 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2185 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2186 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2187 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002188 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2189 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190
2191 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002192 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193
2194 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002195 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2196 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2197 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2198 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2199 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2200 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002201 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002202 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002204 // See if this is a device with keys. This could be full keyboard, or other devices like
2205 // gamepads, joysticks, and styluses with buttons that should generate key presses.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002206 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002207 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2208 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2209 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002210 bool haveStylusButtons = device->keyBitmask.test(BTN_STYLUS) ||
2211 device->keyBitmask.test(BTN_STYLUS2) || device->keyBitmask.test(BTN_STYLUS3);
2212 if (haveKeyboardKeys || haveGamepadButtons || haveStylusButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002213 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 }
2215
2216 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002217 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2218 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002219 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220 }
2221
Prabir Pradhana3621852022-10-14 18:57:23 +00002222 // See if the device is specially configured to be of a certain type.
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002223 std::string deviceType;
2224 if (device->configuration && device->configuration->tryGetProperty("device.type", deviceType)) {
2225 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002226 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhana3621852022-10-14 18:57:23 +00002227 } else if (deviceType == "externalStylus") {
2228 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002229 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002230 }
2231
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232 // See if this is a touch pad.
2233 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002234 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235 // Some joysticks such as the PS3 controller report axes that conflict
2236 // with the ABS_MT range. Try to confirm that the device really is
2237 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002238 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002239 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Harry Cutts79cc9fa2022-10-28 15:32:39 +00002240 if (device->propBitmask.test(INPUT_PROP_POINTER) &&
2241 !device->keyBitmask.any(BTN_TOOL_PEN, BTN_TOOL_FINGER) && !haveStylusButtons) {
2242 device->classes |= InputDeviceClass::TOUCHPAD;
2243 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002245 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002246 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2247 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002248 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002249 // Is this a stylus that reports contact/pressure independently of touch coordinates?
Chris Ye66fbac32020-07-06 20:36:43 -07002250 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2251 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002252 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253 }
2254
2255 // See if this device is a joystick.
2256 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2257 // from other devices such as accelerometers that also have absolute axes.
2258 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002259 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002261 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002262 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 device->classes = assumedClasses;
2264 break;
2265 }
2266 }
2267 }
2268
Chris Yef59a2f42020-10-16 12:55:26 -07002269 // Check whether this device is an accelerometer.
2270 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2271 device->classes |= InputDeviceClass::SENSOR;
2272 }
2273
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 // Check whether this device has switches.
2275 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002276 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002277 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 break;
2279 }
2280 }
2281
2282 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002283 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002284 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 }
2286
2287 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002288 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 // Load the virtual keys for the touch screen, if any.
2290 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002291 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002292 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002293 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 }
2295 }
2296
2297 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002298 // We need to do this for joysticks too because the key layout may specify axes, and for
2299 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002301 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2302 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002304 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 }
2306
2307 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002308 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002310 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002311 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2312 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313 mBuiltInKeyboardId = device->id;
2314 }
2315
2316 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002317 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002318 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 }
2320
2321 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002322 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2323 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2324 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2325 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2326 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002327 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328 }
2329
2330 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002331 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002332 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002333 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 break;
2335 }
2336 }
Prabir Pradhana3621852022-10-14 18:57:23 +00002337
2338 // See if this device has any stylus buttons that we would want to fuse with touch data.
2339 if (!device->classes.any(InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT)) {
2340 for (int32_t keycode : STYLUS_BUTTON_KEYCODES) {
2341 if (device->hasKeycodeLocked(keycode)) {
2342 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
2343 break;
2344 }
2345 }
2346 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347 }
2348
2349 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002350 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002351 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002352 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002353 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 }
2355
Chris Ye3fdbfef2021-01-06 18:45:18 -08002356 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002357 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002358 device->classes |= InputDeviceClass::BATTERY;
2359 }
Kim Low03ea0352020-11-06 12:45:07 -08002360
Chris Ye3fdbfef2021-01-06 18:45:18 -08002361 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002362 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002363 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002364 }
2365
Tim Kilbourn063ff532015-04-08 10:26:18 -07002366 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002367 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002368 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002369 }
2370
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002372 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002373 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374 }
2375
Chris Ye1b0c7342020-07-28 21:57:03 -07002376 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2377 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002378 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2379 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380 }
2381
Chris Ye989bb932020-07-04 16:18:59 -07002382 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002383 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384 }
2385
Chris Ye989bb932020-07-04 16:18:59 -07002386 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002387
Chris Ye1b0c7342020-07-28 21:57:03 -07002388 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002389 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002390 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2391 device->classes.string().c_str(), device->configurationFile.c_str(),
2392 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2393 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002394
Chris Ye989bb932020-07-04 16:18:59 -07002395 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002396}
2397
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002398void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2399 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2400 if (!videoDevice) {
2401 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2402 return;
2403 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002404 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002405 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002406 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002407 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002408 }
2409 }
2410
2411 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2412 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002413 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002414 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002415 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2416}
2417
Chris Yed3fef462021-03-07 17:10:08 -08002418bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2419 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002420 if (videoDevice->getName() != device.identifier.name) {
2421 return false;
2422 }
2423 device.videoDevice = std::move(videoDevice);
2424 if (device.enabled) {
2425 registerVideoDeviceForEpollLocked(*device.videoDevice);
2426 }
2427 return true;
2428}
2429
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002430bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002431 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002432 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002433 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002434 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2435 return false;
2436 }
2437 return device->enabled;
2438}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002440status_t EventHub::enableDevice(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 %" PRId32 " already enabled", __func__, deviceId);
2449 return OK;
2450 }
2451 status_t result = device->enable();
2452 if (result != OK) {
2453 ALOGE("Failed to enable device %" PRId32, deviceId);
2454 return result;
2455 }
2456
Chris Ye989bb932020-07-04 16:18:59 -07002457 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002458
Chris Ye989bb932020-07-04 16:18:59 -07002459 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002460}
2461
2462status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002463 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002464 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002465 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002466 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2467 return BAD_VALUE;
2468 }
2469 if (!device->enabled) {
2470 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2471 return OK;
2472 }
Chris Ye989bb932020-07-04 16:18:59 -07002473 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002474 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475}
2476
2477void EventHub::createVirtualKeyboardLocked() {
2478 InputDeviceIdentifier identifier;
2479 identifier.name = "Virtual";
2480 identifier.uniqueId = "<virtual>";
2481 assignDescriptorLocked(identifier);
2482
Chris Ye989bb932020-07-04 16:18:59 -07002483 std::unique_ptr<Device> device =
2484 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Prabir Pradhancb42b472022-08-23 16:01:19 +00002485 identifier, nullptr /*associatedDevice*/);
Chris Ye1b0c7342020-07-28 21:57:03 -07002486 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2487 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002488 device->loadKeyMapLocked();
2489 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490}
2491
Chris Ye989bb932020-07-04 16:18:59 -07002492void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002493 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002494 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495}
2496
Chris Ye989bb932020-07-04 16:18:59 -07002497int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498 if (mControllerNumbers.isFull()) {
2499 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002500 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501 return 0;
2502 }
2503 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2504 // one
2505 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2506}
2507
Chris Ye989bb932020-07-04 16:18:59 -07002508void EventHub::releaseControllerNumberLocked(int32_t num) {
2509 if (num > 0) {
2510 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512}
2513
Chris Ye8594e192020-07-14 10:34:06 -07002514void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002515 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002516 if (device != nullptr) {
2517 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002518 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519 }
Chris Ye8594e192020-07-14 10:34:06 -07002520 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002521}
2522
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002523/**
2524 * Find the video device by filename, and close it.
2525 * The video device is closed by path during an inotify event, where we don't have the
2526 * additional context about the video device fd, or the associated input device.
2527 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002528void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002529 // A video device may be owned by an existing input device, or it may be stored in
2530 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002531 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002532 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002533 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002534 device->videoDevice = nullptr;
2535 return;
2536 }
2537 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002538 std::erase_if(mUnattachedVideoDevices,
2539 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2540 return videoDevice->getPath() == devicePath;
2541 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542}
2543
2544void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002545 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002546 while (!mDevices.empty()) {
2547 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002548 }
2549}
2550
Chris Ye989bb932020-07-04 16:18:59 -07002551void EventHub::closeDeviceLocked(Device& device) {
2552 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2553 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002554
Chris Ye989bb932020-07-04 16:18:59 -07002555 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002557 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002558 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2559 }
2560
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002561 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002562 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002563 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002564 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002566
Chris Ye989bb932020-07-04 16:18:59 -07002567 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002568 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002569 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002570 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002571
Chris Ye989bb932020-07-04 16:18:59 -07002572 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573}
2574
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002575base::Result<void> EventHub::readNotifyLocked() {
2576 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2577 uint8_t eventBuffer[512];
2578 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579
2580 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002581 do {
2582 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2583 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002585 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2586
2587 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2588 const inotify_event* event;
2589 event = (const inotify_event*)(eventBuffer + eventPos);
2590 if (event->len == 0) continue;
2591
2592 handleNotifyEventLocked(*event);
2593
2594 const ssize_t eventSize = EVENT_SIZE + event->len;
2595 sizeRead -= eventSize;
2596 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002598 return {};
2599}
2600
2601void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2602 if (event.wd == mDeviceInputWd) {
2603 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2604 if (event.mask & IN_CREATE) {
2605 openDeviceLocked(filename);
2606 } else {
2607 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2608 closeDeviceByPathLocked(filename);
2609 }
2610 } else if (event.wd == mDeviceWd) {
2611 if (isV4lTouchNode(event.name)) {
2612 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2613 if (event.mask & IN_CREATE) {
2614 openVideoDeviceLocked(filename);
2615 } else {
2616 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2617 closeVideoDeviceByPathLocked(filename);
2618 }
2619 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2620 addDeviceInputInotify();
2621 }
2622 } else {
2623 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2624 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625}
2626
Chris Ye8594e192020-07-14 10:34:06 -07002627status_t EventHub::scanDirLocked(const std::string& dirname) {
2628 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2629 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002630 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631 return 0;
2632}
2633
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002634/**
2635 * Look for all dirname/v4l-touch* devices, and open them.
2636 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002637status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002638 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2639 if (isV4lTouchNode(entry.path())) {
2640 ALOGI("Found touch video device %s", entry.path().c_str());
2641 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002642 }
2643 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002644 return OK;
2645}
2646
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647void EventHub::requestReopenDevices() {
2648 ALOGV("requestReopenDevices() called");
2649
Chris Ye87143712020-11-10 05:05:58 +00002650 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651 mNeedToReopenDevices = true;
2652}
2653
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002654void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002655 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656
2657 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002658 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002659
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002660 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002661
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002662 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002663
Chris Ye989bb932020-07-04 16:18:59 -07002664 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002665 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002666 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002667 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002669 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002670 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002672 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002673 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002674 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002675 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2676 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002677 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002678 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002679 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002680 "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002681 device->identifier.bus, device->identifier.vendor,
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002682 device->identifier.product, device->identifier.version,
2683 toString(device->identifier.bluetoothAddress).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002684 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002685 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002686 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002687 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00002688 dump += StringPrintf(INDENT3 "CountryCode: %d\n",
2689 device->associatedDevice ? device->associatedDevice->countryCode
2690 : InputDeviceCountryCode::INVALID);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002691 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002692 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002693 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2694 device->videoDevice ? device->videoDevice->dump().c_str()
2695 : "<none>");
2696 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2697 device->associatedDevice
2698 ? device->associatedDevice->sysfsRootPath.c_str()
2699 : "<none>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002701
2702 dump += INDENT "Unattached video devices:\n";
2703 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2704 dump += INDENT2 + videoDevice->dump() + "\n";
2705 }
2706 if (mUnattachedVideoDevices.empty()) {
2707 dump += INDENT2 "<none>\n";
2708 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709 } // release lock
2710}
2711
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002712void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002714 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715}
2716
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002717std::string EventHub::AssociatedDevice::dump() const {
2718 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2719 batteryInfos.size(), lightInfos.size());
2720}
2721
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002722} // namespace android