Debian Codegraph @

src/Input/FGHIDEventInput.cxx

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // FGHIDEventInput.cxx -- handle event driven input devices via HIDAPI
2 //
3 // SPDX-License-Identifier: GPL-2.0-or-later
4 // SPDX-FileCopyrightText: 2017 James Turner <[email protected]>
5
6 #include "config.h"
7 #include "simgear/debug/debug_types.h"
8
9 #include "FGHIDEventInput.hxx"
10
11 #include <algorithm>
12 #include <cassert>
13 #include <cstdlib>
14 #include <unordered_set>
15 #include <string>
16
•17 #include <endian.h>
18
19 #include <Main/fg_props.hxx>
20 #include <hidapi/hidapi.h>
21 #include <hidapi/hidparse.h>
22
23 #include <simgear/debug/ErrorReportingCallback.hxx>
24 #include <simgear/io/lowlevel.hxx>
25 #include <simgear/misc/strutils.hxx>
26 #include <simgear/sg_inlines.h>
27 #include <simgear/structure/exception.hxx>
28
29 #include "FGHIDUsage.hxx"
30
31 using simgear::strutils::encodeHex;
32
33 namespace HID {
34
35 bool shouldPrefixWithAbs(uint32_t usagePage, uint32_t usage)
36 {
37 const auto enumUsage = static_cast<UsagePage>(usagePage);
38 if (enumUsage == UsagePage::GenericDesktop) {
39 switch (usage) {
40 case GD_Wheel:
41 case GD_Dial:
42 case GD_Hatswitch:
43 case GD_Slider:
44 case GD_Rx:
45 case GD_Ry:
46 case GD_Rz:
47 case GD_X:
48 case GD_Y:
49 case GD_Z:
50 return true;
51 default:
52 break;
53 }
54 }
55
56 return false;
57 }
58
59 ReportType reportTypeFromString(const std::string& s)
60 {
61 if (s == "input") return ReportType::In;
62 if (s == "output") return ReportType::Out;
63 if (s == "feature") return ReportType::Feature;
64 return ReportType::Invalid;
65 }
66 } // namespace HID
67
68 class FGHIDEventInput::FGHIDEventInputPrivate
69 {
70 public:
71 FGHIDEventInput* p = nullptr;
72
73 void evaluateDevice(hid_device_info* deviceInfo);
74 };
75
76 // anonymous namespace to define our device subclass
77 namespace {
78
79 class FGHIDDevice : public FGInputDevice
80 {
81 public:
82 FGHIDDevice(hid_device_info* devInfo,
83 FGHIDEventInput* subsys);
84
85 virtual ~FGHIDDevice();
86
87 bool Open() override;
88 void Close() override;
89 void Configure(SGPropertyNode_ptr node) override;
90
91 void update(double dt) override;
92 const char* TranslateEventName(FGEventData& eventData) override;
93 void Send(const char* eventName, double value) override;
94 void SendFeatureReport(unsigned int reportId, const simgear::UInt8Vector& data) override;
95 void SendOutputReport(unsigned int reportId, const simgear::UInt8Vector& data) override;
96
97 class Item
98 {
99 public:
100 Item(const std::string& n, uint32_t offset, uint8_t size) : name(n),
101 bitOffset(offset),
102 bitSize(size)
103 {
104 }
105
106 std::string name;
107 uint32_t bitOffset = 0; // form the start of the report
108 uint8_t bitSize = 1;
109 bool isRelative = false;
110 bool doSignExtend = false;
111 int lastValue = 0;
112 // int defaultValue = 0;
113 // range, units, etc not needed for now
114 // hopefully this doesn't need to be a list
115 FGInputEvent_ptr event;
116 };
117
118 private:
119 class Report
120 {
121 public:
122 Report(HID::ReportType ty, uint8_t n = 0) : type(ty), number(n) {}
123
124 HID::ReportType type;
125 uint8_t number = 0;
126 std::vector<Item*> items;
127
128 uint32_t currentBitSize() const
129 {
130 uint32_t size = 0;
131 for (auto i : items) {
132 size += i->bitSize;
133 }
134 return size;
135 }
136 };
137
138 bool parseUSBHIDDescriptor();
139 void parseCollection(hid_item* collection);
140 void parseItem(hid_item* item);
141
142 Report* getReport(HID::ReportType ty, uint8_t number, bool doCreate = false);
143
144 void sendReport(Report* report) const;
145
146 uint8_t countWithName(const std::string& name) const;
147 std::pair<Report*, Item*> itemWithName(const std::string& name) const;
148
149 void processInputReport(Report* report, unsigned char* data, size_t length,
150 double dt, int keyModifiers);
151
152 int maybeSignExtend(Item* item, int inValue);
153
154 void defineReport(SGPropertyNode_ptr reportNode);
155
156 void dumpRawBytes(const std::string& b) const;
157
158 std::vector<Report*> _reports;
159 std::string _hidPath;
160 hid_device* _device = nullptr;
161 bool _haveNumberedReports = false;
162 bool _debugRaw = false;
163
164 /// set if we parsed the device description our XML
165 /// instead of from the USB data. Useful on Windows where the data
166 /// is inaccessible, or devices with broken descriptors
167 bool _haveLocalDescriptor = false;
168
169 /// allow specifying the descriptor as hex bytes in XML
170 simgear::UInt8Vector _rawXMLDescriptor;
171
172 // all sets which will be send on the next update() call.
173 std::set<Report*> _dirtyReports;
174 };
175
176 class HIDEventData : public FGEventData
177 {
178 public:
179 // item, value, dt, keyModifiers
180 HIDEventData(FGHIDDevice::Item* it, int value, double dt, int keyMods) : FGEventData(value, dt, keyMods),
181 item(it)
182 {
183 assert(item);
184 }
185
186 FGHIDDevice::Item* item = nullptr;
187 };
188
189 FGHIDDevice::FGHIDDevice(hid_device_info* devInfo, FGHIDEventInput*)
190 {
191 class_id = "FGHIDDevice";
192 _hidPath = devInfo->path;
193
194 std::wstring manufacturerName, productName;
195 productName = devInfo->product_string ? std::wstring(devInfo->product_string)
196 : L"unknown HID device";
197
198 if (devInfo->manufacturer_string) {
199 manufacturerName = std::wstring(devInfo->manufacturer_string);
200 SetName(simgear::strutils::convertWStringToUtf8(manufacturerName) + " " +
201 simgear::strutils::convertWStringToUtf8(productName));
202 } else {
203 SetName(simgear::strutils::convertWStringToUtf8(productName));
204 }
205
206 const auto serial = devInfo->serial_number;
207 std::string path(devInfo->path);
208 // most devices return an empty serial number, unfortunately
209 if ((serial != nullptr) && std::wcslen(serial) > 0) {
210 SetSerialNumber(simgear::strutils::convertWStringToUtf8(serial));
211 }
212
213 std::string _usage = HID::nameForUsage(devInfo->usage_page, devInfo->usage);
214 SG_LOG(SG_INPUT, SG_DEBUG, "HID device " << _hidPath << " "
215 << "0x" << std::hex << devInfo->vendor_id << ":0x" << std::hex << devInfo->product_id << " "
216 << "release " << devInfo->release_number << " "
217 << "usage " << _usage << "(0x" << std::hex << devInfo->usage_page
218 << ":0x" << std::hex << devInfo->usage << ") "
219 << "ifn " << devInfo->interface_number << " "
220 << GetName() );
221
222 }
223
224 FGHIDDevice::~FGHIDDevice()
225 {
226 if (_device) {
227 hid_close(_device);
228 }
229 }
230
231 void FGHIDDevice::Configure(SGPropertyNode_ptr node)
232 {
233 // base class first
234 FGInputDevice::Configure(node);
235
236 if (node->hasChild("hid-descriptor")) {
237 _haveLocalDescriptor = true;
238 if (debugEvents) {
239 SG_LOG(SG_INPUT, SG_INFO, GetUniqueName() << " will configure using local HID descriptor");
240 }
241
242 for (auto report : node->getChild("hid-descriptor")->getChildren("report")) {
243 defineReport(report);
244 }
245 }
246
247 if (node->hasChild("hid-raw-descriptor")) {
248 _rawXMLDescriptor = simgear::strutils::decodeHex(node->getStringValue("hid-raw-descriptor"));
249 if (debugEvents) {
250 SG_LOG(SG_INPUT, SG_INFO, GetUniqueName() << " will configure using XML-defined raw HID descriptor");
251 }
252 }
253
254 if (node->getBoolValue("hid-debug-raw")) {
255 _debugRaw = true;
256 }
257 }
258
259 bool FGHIDDevice::Open()
260 {
261 SG_LOG(SG_INPUT, SG_INFO, "HID open " << GetUniqueName());
262 _device = hid_open_path(_hidPath.c_str());
263 if (_device == nullptr) {
264 SG_LOG(SG_INPUT, SG_WARN, GetUniqueName() << ": HID: Failed to open:" << _hidPath);
265 SG_LOG(SG_INPUT, SG_WARN, "\tnote on Linux you may need to adjust permissions of the device using UDev rules.");
266 return false;
267 }
268
269 if (_rawXMLDescriptor.empty()) {
270 _rawXMLDescriptor.resize(2048);
271 int descriptorSize = hid_get_report_descriptor(_device, _rawXMLDescriptor.data(), _rawXMLDescriptor.size());
272 if (descriptorSize <= 0) {
273 SG_LOG(SG_INPUT, SG_WARN, "HID: " << GetUniqueName() << " failed to read HID descriptor");
274 return false;
275 }
276
277 _rawXMLDescriptor.resize(descriptorSize);
278 }
279
280 if (!_haveLocalDescriptor) {
281 bool ok = parseUSBHIDDescriptor();
282 if (!ok)
283 return false;
284 }
285
286 for (auto& v : handledEvents) {
287 auto reportItem = itemWithName(v.first);
288 if (!reportItem.second) {
289 SG_LOG(SG_INPUT, SG_WARN, "HID device:" << GetUniqueName() << " has no element for event:" << v.first);
290 continue;
291 }
292
293 FGInputEvent_ptr event = v.second;
294 if (debugEvents) {
295 SG_LOG(SG_INPUT, SG_INFO, "\tfound item for event:" << v.first);
296 }
297
298 reportItem.second->event = event;
299 }
300
301 return true;
302 }
303
304 bool FGHIDDevice::parseUSBHIDDescriptor()
305 {
306 #if defined(SG_WINDOWS)
307 if (_rawXMLDescriptor.empty()) {
308 SG_LOG(SG_INPUT, SG_ALERT, GetUniqueName() << ": on Windows, there is no way to extract the UDB-HID report descriptor. "
309 << "\nPlease supply the report descriptor in the device XML configuration.");
310 SG_LOG(SG_INPUT, SG_ALERT, "See this page:<> for information on extracting the report descriptor on Windows");
311 return false;
312 }
313 #endif
314
315 if (_debugRaw) {
316 SG_LOG(SG_INPUT, SG_INFO, "\nHID: descriptor for:" << GetUniqueName() << "\n\t" << encodeHex(_rawXMLDescriptor, ':'));
317 }
318
319 hid_item* rootItem = nullptr;
320 hid_parse_reportdesc(_rawXMLDescriptor.data(), _rawXMLDescriptor.size(), &rootItem);
321 if (debugEvents) {
322 SG_LOG(SG_INPUT, SG_INFO, "\nHID: scan for:" << GetUniqueName());
323 }
324
325 parseCollection(rootItem);
326
327 hid_free_reportdesc(rootItem);
328 return true;
329 }
330
331 void FGHIDDevice::parseCollection(hid_item* c)
332 {
333 for (hid_item* child = c->collection; child != nullptr; child = child->next) {
334 if (child->collection) {
335 parseCollection(child);
336 } else {
337 // leaf item
338 parseItem(child);
339 }
340 }
341 }
342
343 auto FGHIDDevice::getReport(HID::ReportType ty, uint8_t number, bool doCreate) -> Report*
344 {
345 if (number > 0) {
346 _haveNumberedReports = true;
347 }
348
349 for (auto report : _reports) {
350 if ((report->type == ty) && (report->number == number)) {
351 return report;
352 }
353 }
354
355 if (doCreate) {
356 auto r = new Report{ty, number};
357 _reports.push_back(r);
358 return r;
359 } else {
360 return nullptr;
361 }
362 }
363
364 auto FGHIDDevice::itemWithName(const std::string& name) const -> std::pair<Report*, Item*>
365 {
366 for (auto report : _reports) {
367 for (auto item : report->items) {
368 if (item->name == name) {
369 return std::make_pair(report, item);
370 }
371 }
372 }
373
374 return std::make_pair(static_cast<Report*>(nullptr), static_cast<Item*>(nullptr));
375 }
376
377 uint8_t FGHIDDevice::countWithName(const std::string& name) const
378 {
379 uint8_t result = 0;
380 size_t nameLength = name.length();
381
382 for (auto report : _reports) {
383 for (auto item : report->items) {
384 if (strncmp(name.c_str(), item->name.c_str(), nameLength) == 0) {
385 result++;
386 }
387 }
388 }
389
390 return result;
391 }
392
393 void FGHIDDevice::parseItem(hid_item* item)
394 {
395 std::string name = HID::nameForUsage(item->usage >> 16, item->usage & 0xffff);
396 if (hid_parse_is_relative(item)) {
397 name = "rel-" + name; // prefix relative names
398 } else if (HID::shouldPrefixWithAbs(item->usage >> 16, item->usage & 0xffff)) {
399 name = "abs-" + name;
400 }
401
402 const auto ty = static_cast<HID::ReportType>(item->type);
403 auto existingItem = itemWithName(name);
404 if (existingItem.second) {
405 // type fixup
406 const HID::ReportType existingItemType = existingItem.first->type;
407 if (existingItemType != ty) {
408 // might be an item named identically in input/output and feature reports
409 // -> prefix the feature one with 'feature'
410 if (ty == HID::ReportType::Feature) {
411 name = "feature-" + name;
412 } else if (existingItemType == HID::ReportType::Feature) {
413 // rename this existing item since it's a feature
414 existingItem.second->name = "feature-" + name;
415 }
416 }
417 }
418
419 // do the count now, after we did any renaming, since we might have
420 // N > 1 for the new name
421 int existingCount = countWithName(name);
422 if (existingCount > 0) {
423 if (existingCount == 1) {
424 // rename existing item 0 to have the "-0" suffix
425 auto existingItem = itemWithName(name);
426 existingItem.second->name += "-0";
427 }
428
429 // define the new nae
430 std::stringstream os;
431 os << name << "-" << existingCount;
432 name = os.str();
433 }
434
435 auto report = getReport(ty, item->report_id, true /* create */);
436 uint32_t bitOffset = report->currentBitSize();
437
438 if (debugEvents) {
439 SG_LOG(SG_INPUT, SG_INFO, GetUniqueName() << ": add:" << name << ", bits: " << bitOffset << ":" << (int)item->report_size << ", report=" << (int)item->report_id);
440 }
441
442 Item* itemObject = new Item{name, bitOffset, item->report_size};
443 itemObject->isRelative = hid_parse_is_relative(item);
444 itemObject->doSignExtend = (item->logical_min < 0) || (item->logical_max < 0);
445 report->items.push_back(itemObject);
446 }
447
448 void FGHIDDevice::Close()
449 {
450 if (_device) {
451 hid_close(_device);
452 _device = nullptr;
453 }
454 }
455
456 void FGHIDDevice::update(double dt)
457 {
458 if (!_device) {
459 return;
460 }
461
462 uint8_t reportBuf[65];
463 int readCount = 0;
464 while (true) {
465 readCount = hid_read_timeout(_device, reportBuf, sizeof(reportBuf), 0);
466
467 if (readCount <= 0) {
468 break;
469 }
470
471 int modifiers = fgGetKeyModifiers();
472 const uint8_t reportNumber = _haveNumberedReports ? reportBuf[0] : 0;
473 auto inputReport = getReport(HID::ReportType::In, reportNumber, false);
474 if (!inputReport) {
475 SG_LOG(SG_INPUT, SG_WARN, GetName() << ": FGHIDDevice: Unknown input report number:" << static_cast<int>(reportNumber));
476 } else {
477 uint8_t* reportBytes = _haveNumberedReports ? reportBuf + 1 : reportBuf;
478 size_t reportSize = _haveNumberedReports ? readCount - 1 : readCount;
479 processInputReport(inputReport, reportBytes, reportSize, dt, modifiers);
480 }
481 }
482
483 FGInputDevice::update(dt);
484
485 for (auto rep : _dirtyReports) {
486 sendReport(rep);
487 }
488
489 _dirtyReports.clear();
490 }
491
492 void FGHIDDevice::sendReport(Report* report) const
493 {
494 if (!_device) {
495 return;
496 }
497
498 uint8_t reportBytes[65];
499 size_t reportLength = 0;
500 memset(reportBytes, 0, sizeof(reportBytes));
501 reportBytes[0] = report->number;
502
503 // fill in valid data
504 for (auto item : report->items) {
505 reportLength += item->bitSize;
506 if (item->lastValue == 0) {
507 continue;
508 }
509
510 writeBits(reportBytes + 1, item->bitOffset, item->bitSize, item->lastValue);
511 }
512
513 reportLength /= 8;
514
515 if (_debugRaw) {
516 SG_LOG(SG_INPUT, SG_INFO, "sending bytes: " << encodeHex(reportBytes, ':'));
517 }
518
519 // send the data, based on the report type
520 if (report->type == HID::ReportType::Feature) {
521 hid_send_feature_report(_device, reportBytes, reportLength + 1);
522 } else {
523 assert(report->type == HID::ReportType::Out);
524 hid_write(_device, reportBytes, reportLength + 1);
525 }
526 }
527
528 int FGHIDDevice::maybeSignExtend(Item* item, int inValue)
529 {
530 return item->doSignExtend ? signExtend(inValue, item->bitSize) : inValue;
531 }
532
533 void FGHIDDevice::processInputReport(Report* report, unsigned char* data,
534 size_t length,
535 double dt, int keyModifiers)
536 {
537 if (_debugRaw) {
538 SG_LOG(SG_INPUT, SG_INFO, GetName() << " FGHIDDeivce received input report:" << (int)report->number << ", len=" << length);
539 {
540 SG_LOG(SG_INPUT, SG_INFO, "\tbytes: " << encodeHex(data, length, ':'));
541 }
542 }
543
544 for (auto item : report->items) {
545 int value = extractBits(data, length, item->bitOffset, item->bitSize);
546
547 value = maybeSignExtend(item, value);
548
549 // suppress events for values that aren't changing
550 if (item->isRelative) {
551 // suppress spurious 0-valued relative events
552 if (value == 0) {
553 continue;
554 }
555 } else {
556 // suppress no-change events for absolute items
557 if (value == item->lastValue) {
558 continue;
559 }
560 }
561
562 item->lastValue = value;
563 if (!item->event)
564 continue;
565
566 if (_debugRaw) {
567 SG_LOG(SG_INPUT, SG_INFO, "\titem:" << item->name << " = " << value);
568 }
569
570 HIDEventData event{item, value, dt, keyModifiers};
571 HandleEvent(event);
572 }
573 }
574
575 void FGHIDDevice::SendFeatureReport(unsigned int reportId, const simgear::UInt8Vector& data)
576 {
577 if (!_device) {
578 return;
579 }
580
581 if (_debugRaw) {
582 SG_LOG(SG_INPUT, SG_INFO, GetName() << ": FGHIDDevice: Sending feature report:" << (int)reportId << ", len=" << data.size());
583 SG_LOG(SG_INPUT, SG_INFO, "\tbytes: " << encodeHex(data, ':'));
584 }
585
586 uint8_t buf[65];
587 size_t len = std::min(data.size() + 1, sizeof(buf));
588 buf[0] = reportId;
589 memcpy(buf + 1, data.data(), len - 1);
590 size_t r = hid_send_feature_report(_device, buf, len);
591 if (r < 0) {
592 SG_LOG(SG_INPUT, SG_WARN, GetName() << ": FGHIDDevice: Sending feature report failed, error-string is:\n"
593 << simgear::strutils::error_string(errno));
594 }
595 }
596
597 const char* FGHIDDevice::TranslateEventName(FGEventData& eventData)
598 {
599 HIDEventData& hidEvent = static_cast<HIDEventData&>(eventData);
600 return hidEvent.item->name.c_str();
601 }
602
603 void FGHIDDevice::Send(const char* eventName, double value)
604 {
605 // even though this called 'Send' it's really 'mark value for sending when we update', to
606 // avoid generating multiple output reports in a single update frame.
607 auto item = itemWithName(eventName);
608 if (item.second == nullptr) {
609 SG_LOG(SG_INPUT, SG_WARN, GetName() << ": FGHIDDevice:unknown item name:" << eventName);
610 return;
611 }
612
613 int intValue = static_cast<int>(value);
614 if (item.second->lastValue == intValue) {
615 return; // not actually changing
616 }
617
618 lastEventName->setStringValue(eventName);
619 lastEventValue->setDoubleValue(value);
620
621 // update the stored value prior to sending
622 item.second->lastValue = intValue;
623 _dirtyReports.insert(item.first);
624 }
625
626 void FGHIDDevice::SendOutputReport(unsigned int reportId, const simgear::UInt8Vector& data)
627 {
628 if (!_device) {
629 return;
630 }
631
632 auto r = getReport(HID::ReportType::Out, reportId);
633 if (!r) {
634 SG_LOG(SG_INPUT, SG_DEV_ALERT, "HID device does not define an output report with ID:" << reportId);
635 return;
636 }
637
638
639 if (_debugRaw) {
640 SG_LOG(SG_INPUT, SG_INFO, GetName() << ": FGHIDDevice: output feature:" << (int)reportId << ", len=" << data.size());
641 SG_LOG(SG_INPUT, SG_INFO, "\tbytes: " << encodeHex(data, ':'));
642 }
643
644 uint8_t buf[65];
645 size_t len = std::min(data.size() + 1, sizeof(buf));
646 buf[0] = reportId;
647 memcpy(buf + 1, data.data(), len - 1);
648
649 auto result = hid_write(_device, buf, len);
650 if (result < 0) {
651 SG_LOG(SG_INPUT, SG_DEV_ALERT, GetName() << ": FGHIDDevice: Sending outpit report failed, error-string is:\n"
652 << simgear::strutils::error_string(errno));
653 }
654 }
655
656 void FGHIDDevice::defineReport(SGPropertyNode_ptr reportNode)
657 {
658 const int nChildren = reportNode->nChildren();
659 uint32_t bitCount = 0;
660 const auto rty = HID::reportTypeFromString(reportNode->getStringValue("type"));
661 if (rty == HID::ReportType::Invalid) {
662 SG_LOG(SG_INPUT, SG_WARN, GetName() << ": FGHIDDevice: invalid report type:" << reportNode->getStringValue("type"));
663 return;
664 }
665
666 const auto id = reportNode->getIntValue("id");
667 if (id > 0) {
668 _haveNumberedReports = true;
669 }
670
671 auto report = new Report(rty, id);
672 _reports.push_back(report);
673
674 for (int c = 0; c < nChildren; ++c) {
675 const auto n = reportNode->getChild(c);
676 const int size = n->getIntValue("size", 1); // default to a single bit
677 if (n->getNameString() == "unused-bits") {
678 bitCount += size;
679 continue;
680 }
681
682 if (n->getNameString() == "type" || n->getNameString() == "id") {
683 continue; // already handled above
684 }
685
686 // allow repeating items
687 uint8_t count = n->getIntValue("count", 1);
688 std::string name = n->getNameString();
689 const auto lastHypen = name.rfind("-");
690 std::string baseName = name.substr(0, lastHypen + 1);
691 int baseIndex = std::stoi(name.substr(lastHypen + 1));
692
693 const bool isRelative = (name.find("rel-") == 0);
694 const bool isSigned = n->getBoolValue("is-signed", false);
695
696 for (uint8_t i = 0; i < count; ++i) {
697 std::ostringstream oss;
698 oss << baseName << (baseIndex + i);
699 Item* itemObject = new Item{oss.str(), bitCount, static_cast<uint8_t>(size)};
700 itemObject->isRelative = isRelative;
701 itemObject->doSignExtend = isSigned;
702 report->items.push_back(itemObject);
703 bitCount += size;
704 }
705 }
706 }
707
708
709 } // namespace
710
711
712 int extractBits(uint8_t* bytes, size_t lengthInBytes, size_t bitOffset, size_t bitSize)
713 {
714 const size_t wholeBytesToSkip = bitOffset >> 3;
715 const size_t offsetInByte = bitOffset & 0x7;
716
717 // work out how many whole bytes to copy
718 const size_t bytesToCopy = std::min(sizeof(uint32_t), (offsetInByte + bitSize + 7) / 8);
719 uint32_t v = 0;
720 // this goes from byte alignment to word alignment safely
721 memcpy((void*)&v, bytes + wholeBytesToSkip, bytesToCopy);
•722 // the memcpy arranges v in little-endian order, so swap if needed
723 v = le32toh(v);
724
725 // shift down so lowest bit is aligned
726 v = v >> offsetInByte;
727
728 // mask off any extraneous top bits
729 const uint32_t mask = ~(0xffffffff << bitSize);
730 v &= mask;
731
732 return v;
733 }
734
735 int signExtend(int inValue, size_t bitSize)
736 {
737 const int m = 1U << (bitSize - 1);
738 return (inValue ^ m) - m;
739 }
740
741 void writeBits(uint8_t* bytes, size_t bitOffset, size_t bitSize, int value)
742 {
743 size_t wholeBytesToSkip = bitOffset >> 3;
744 uint8_t* dataByte = bytes + wholeBytesToSkip;
745 size_t offsetInByte = bitOffset & 0x7;
746 size_t bitsInByte = std::min(bitSize, 8 - offsetInByte);
747 uint8_t mask = 0xff >> (8 - bitsInByte);
748
749 *dataByte |= ((value & mask) << offsetInByte);
750
751 if (bitsInByte < bitSize) {
752 // if we have more bits to write, recurse
753 writeBits(bytes, bitOffset + bitsInByte, bitSize - bitsInByte, value >> bitsInByte);
754 }
755 }
756
757 FGHIDEventInput::FGHIDEventInput() : FGEventInput("Input/HID", "/input/hid"),
758 d(new FGHIDEventInputPrivate)
759 {
760 d->p = this; // store back pointer to outer object on pimpl
761 }
762
763 FGHIDEventInput::~FGHIDEventInput()
764 {
765 }
766
767 void FGHIDEventInput::reinit()
768 {
769 SG_LOG(SG_INPUT, SG_INFO, "Re-Initializing HID input bindings");
770 FGHIDEventInput::shutdown();
771 FGHIDEventInput::init();
772 FGHIDEventInput::postinit();
773 }
774
775 void FGHIDEventInput::postinit()
776 {
777 SG_LOG(SG_INPUT, SG_INFO, "HID event input starting up");
778
779 hid_init();
780
781 hid_device_info* devices = hid_enumerate(0 /* vendor ID */, 0 /* product ID */);
782
783 // open each device path only once, it may appear multiple times with different usage value
784 std::unordered_set<std::string> seenPaths;
785 for (hid_device_info* curDev = devices; curDev != nullptr; curDev = curDev->next) {
786 if (curDev->path) {
787 std::string pathStr(curDev->path);
788 if (seenPaths.find(pathStr) == seenPaths.end()) {
789 seenPaths.insert(pathStr);
790 d->evaluateDevice(curDev);
791 } else {
792 std::string _usage = HID::nameForUsage(curDev->usage_page, curDev->usage);
793 SG_LOG(SG_INPUT, SG_DEBUG, "Skipping duplicate path " << pathStr << " "
794 << "usage " << _usage << "(0x" << std::hex << curDev->usage_page << ":0x"
795 << std::hex << curDev->usage << ")");
796 }
797 }
798 }
799 hid_free_enumeration(devices);
800 }
801
802 void FGHIDEventInput::shutdown()
803 {
804 SG_LOG(SG_INPUT, SG_INFO, "HID event input shutting down");
805 FGEventInput::shutdown();
806
807 hid_exit();
808 }
809
810 //
811 // read all elements in each input device
812 //
813 void FGHIDEventInput::update(double dt)
814 {
815 FGEventInput::update(dt);
816 }
817
818
819 // Register the subsystem.
820 SGSubsystemMgr::Registrant<FGHIDEventInput> registrantFGHIDEventInput;
821
822 ///////////////////////////////////////////////////////////////////////////////////////////////
823
824 void FGHIDEventInput::FGHIDEventInputPrivate::evaluateDevice(hid_device_info* deviceInfo)
825 {
826 // allocate an input device, and add to the base class to see if we have
827 // a config
828 p->AddDevice(new FGHIDDevice(deviceInfo, p));
829 }
830
831 ///////////////////////////////////////////////////////////////////////////////////////////////