Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)
(시리즈 글이 7개 있습니다.)
사물인터넷: 5. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 이더넷 카드로 쓰는 방법
; https://www.sysnet.pe.kr/2/0/11353

사물인터넷: 6. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드로 쓰는 방법
; https://www.sysnet.pe.kr/2/0/11354

사물인터넷: 7. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법
; https://www.sysnet.pe.kr/2/0/11355

사물인터넷: 8. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법
; https://www.sysnet.pe.kr/2/0/11356

사물인터넷: 10. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법 (두 번째 이야기)
; https://www.sysnet.pe.kr/2/0/11363

사물인터넷: 11. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법 (절대 좌표)
; https://www.sysnet.pe.kr/2/0/11364

사물인터넷: 12. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드 및 마우스로 쓰는 방법 (절대 좌표, 상대 좌표, 휠)
; https://www.sysnet.pe.kr/2/0/11369




Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법 (두 번째 이야기)

지난 글에서,

Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법
; https://www.sysnet.pe.kr/2/0/11356

Raspberry Pi Zero를 마우스 + 키보드 장치로 컴퓨터에 인식시키는 방법을 살펴봤는데요. 거기서 사용했던 방법은, 파이에서 2개의 USB 장치를 구현하는 것으로 했었습니다. 그런데, 1개의 USB 장치로 2개의 내부 HID 장치를 구현하는 것이 가능합니다. 이에 대한 내용을 다음의 글에서 자세하게 설명하고 있습니다.

Tutorial about USB HID Report Descriptors
; http://eleccelerator.com/tutorial-about-usb-hid-report-descriptors/

위의 글을 "Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법" 장치에 적용해 보면, 마우스와 키보드에 대해 각각의 report descriptors를 이어붙인 다음 개별 장치에 대해 REPORT_ID를 부여하면 되는 것입니다.

다음은 이에 대한 구현입니다.

05, 01, USAGE_PAGE (Generic Desktop)
09, 06, USAGE (Keyboard)
a1, 01, COLLECTION (Application)
85, 01,     REPORT_ID (1)
05, 07      USAGE_PAGE (Keyboard)
19, e0      USAGE_MINIMUM (Keyboard LeftControl)
29, e7      USAGE_MINIMUM (Keyboard Right GUI)
15, 00      LOGICAL_MINIMUM (0)
25, 01      LOGICAL_MAXIMUM (1)
75, 01      REPORT_SIZE (1)
95, 08      REPORT_COUNT (8)
81, 02      INPUT (Data, Var, Abs)
95, 01      REPORT_COUNT (1)
75, 08      REPORT_SIZE (8)
81, 03      INPUT (Cnst, Var, Abs)
95, 05      REPORT_COUNT (5)
75, 01      REPORT_SIZE (1)
05, 08      USAGE_PAGE (LEDs)
19, 01      USAGE_MINIMUM (Num Lock)
29, 05      USAGE_MAXIMUM (Kana)
91, 02      OUTPUT (Data, Var, Abs)
95, 01      REPORT_COUNT (1)
75, 03      REPORT_SIZE (3)
91, 03      OUTPUT (Cnst, Var, Abs)
95, 06      REPORT_COUNT (6)
75, 08      REPORT_SIZE (8)
15, 00      LOGICAL_MINIMUM (0)
25, 65      LOGICAL_MAXIMUM (101)
05, 07      USAGE_PAGE (Keyboard)
19, 00      USAGE_MINIMUM (Reserved (no event indicated))
29, 65      USAGE_MAXIMUM (Keyboard Application)
81, 00      INPUT (Data, Ary, Abs)
C0      END_COLLECTION

05, 01  USAGE_PAGE (Generic Desktop)
09, 02  USAGE (Mouse)
a1, 01  COLLECTION (Application)
09, 01      USAGE (Pointer)
a1, 00      COLLECTION (Physical)
85, 02          REPORT_ID (2)
05, 09          USAGE_PAGE (Button)
19, 01          USAGE_MINIMUM (Button 1)
29, 03          USAGE_MAXIMUM (Button 3)
15, 00          LOGICAL_MINIMUM (0)
25, 01          LOGICAL_MAXIMUM (1)
95, 03          REPORT_COUNT (3)
75, 01          REPORT_SIZE (1)
81, 02          INPUT (Data, Var, Abs)
95, 01          REPORT_COUNT (1)
75, 05          REPORT_SIZE (5)
81, 03          INPUT (Cnst, Var, Abs)
05, 01          USAGE_PAGE (Generic Desktop)
09, 30          USAGE (X)
09, 31          USAGE (Y)
15, 81          LOGICAL_MINIMUM (-127)
25, 7f          LOGICAL_MAXIMUM (127)
75, 08          REPORT_SIZE (8)
95, 02          REPORT_COUNT (2)
81, 06          INPUT (Data, Var, Rel)
C0          END_COLLECTION
C0      END_COLLECTION

위와 같이 적용하면, 키보드와 마우스 장치로 write 해야 할 바이트의 구조가 "Tutorial about USB HID Report Descriptors" 글에 나온 대로 다음과 같이 바뀝니다.

struct keyboard_report_t
{
    uint8_t report_id;
    uint8_t modifier;
    uint8_t reserved;
    uint8_t keycode[6];
}
 
struct mouse_report_t
{
    uint8_t report_id;
    uint8_t buttons;
    int8_t x;
    int8_t y;
}

하지만 실제로 위의 구조로 테스트해보면 키보드의 경우 write 함수 호출에서 실패하는 것을 확인할 수 있습니다.

int size = sizeof(keyboard_report_t); // size == 9

int result = write(fd, keyPress, size); // result == 8
if (result != size)
{
    perror("failed to key press");
    return;
} 

왠지 키보드에 전송하는 데이터는 8바이트를 넘어서는 안되는 것입니다. (혹시 이 부분에 대해 아시는 분은 덧글 부탁드립니다. ^^)

그래서, 키보드 데이터 중에서 keycode 6바이트를 다음과 같이 5바이트로 변경해야 합니다.

struct keyboard_report_t
{
    uint8_t report_id;
    uint8_t modifier;
    uint8_t reserved;
    uint8_t keycode[5];
}

그리고 이를 맞춰 주기 위해 report descriptors도 그 부분을 6에서 5로 바꿔야 합니다. 그래서 최종 report descriptors는 다음과 같이 구성됩니다.

05, 01, USAGE_PAGE (Generic Desktop)
09, 06, USAGE (Keyboard)
a1, 01, COLLECTION (Application)
85, 01,     REPORT_ID (1)
05, 07      USAGE_PAGE (Keyboard)
19, e0      USAGE_MINIMUM (Keyboard LeftControl)
29, e7      USAGE_MINIMUM (Keyboard Right GUI)
15, 00      LOGICAL_MINIMUM (0)
25, 01      LOGICAL_MAXIMUM (1)
75, 01      REPORT_SIZE (1)
95, 08      REPORT_COUNT (8)
81, 02      INPUT (Data, Var, Abs)
95, 01      REPORT_COUNT (1)
75, 08      REPORT_SIZE (8)
81, 03      INPUT (Cnst, Var, Abs)
95, 05      REPORT_COUNT (5)
75, 01      REPORT_SIZE (1)
05, 08      USAGE_PAGE (LEDs)
19, 01      USAGE_MINIMUM (Num Lock)
29, 05      USAGE_MAXIMUM (Kana)
91, 02      OUTPUT (Data, Var, Abs)
95, 01      REPORT_COUNT (1)
75, 03      REPORT_SIZE (3)
91, 03      OUTPUT (Cnst, Var, Abs)
95, 05      REPORT_COUNT (5)
75, 08      REPORT_SIZE (8)
15, 00      LOGICAL_MINIMUM (0)
25, 65      LOGICAL_MAXIMUM (101)
05, 07      USAGE_PAGE (Keyboard)
19, 00      USAGE_MINIMUM (Reserved (no event indicated))
29, 65      USAGE_MAXIMUM (Keyboard Application)
81, 00      INPUT (Data, Ary, Abs)
C0      END_COLLECTION

05, 01  USAGE_PAGE (Generic Desktop)
09, 02  USAGE (Mouse)
a1, 01  COLLECTION (Application)
09, 01      USAGE (Pointer)
a1, 00      COLLECTION (Physical)
85, 02          REPORT_ID (2)
05, 09          USAGE_PAGE (Button)
19, 01          USAGE_MINIMUM (Button 1)
29, 03          USAGE_MAXIMUM (Button 3)
15, 00          LOGICAL_MINIMUM (0)
25, 01          LOGICAL_MAXIMUM (1)
95, 03          REPORT_COUNT (3)
75, 01          REPORT_SIZE (1)
81, 02          INPUT (Data, Var, Abs)
95, 01          REPORT_COUNT (1)
75, 05          REPORT_SIZE (5)
81, 03          INPUT (Cnst, Var, Abs)
05, 01          USAGE_PAGE (Generic Desktop)
09, 30          USAGE (X)
09, 31          USAGE (Y)
15, 81          LOGICAL_MINIMUM (-127)
25, 7f          LOGICAL_MAXIMUM (127)
75, 08          REPORT_SIZE (8)
95, 02          REPORT_COUNT (2)
81, 06          INPUT (Data, Var, Rel)
C0          END_COLLECTION
C0      END_COLLECTION

이를 반영해 쉘 스크립트를 만들어 실행하면,

#!/bin/bash
# From the README at https://github.com/girst/hardpass

dtoverlay dwc2
modprobe dwc2
modprobe libcomposite
cd /sys/kernel/config/usb_gadget/
mkdir -p g1
cd g1
echo 0x1d6b > idVendor # Linux Foundation
echo 0x0104 > idProduct # Multifunction Composite Gadget
echo 0x0100 > bcdDevice # v1.0.0
echo 0x0200 > bcdUSB # USB2
mkdir -p strings/0x409
echo "fedcba9876543210" > strings/0x409/serialnumber
echo "girst" > strings/0x409/manufacturer
echo "Hardpass" > strings/0x409/product

N="usb0"
mkdir -p functions/hid.$N
echo 1 > functions/hid.usb0/protocol
echo 1 > functions/hid.usb0/subclass
echo 8 > functions/hid.usb0/report_length

echo -ne \\x05\\x01\\x09\\x06\\xa1\\x01\\x85\\x01\\x05\\x07\\x19\\xe0\\x29\\xe7\\x15\\x00\\x25\\x01\\x75\\x01\\x95\\x08\\x81\\x02\\x95\\x01\\x75\\x08\\x81\\x03\\x95\\x05\\x75\\x01\\x05\\x08\\x19\\x01\\x29\\x05\\x91\\x02\\x95\\x01\\x75\\x03\\x91\\x03\\x95\\x05\\x75\\x08\\x15\\x00\\x25\\x65\\x05\\x07\\x19\\x00\\x29\\x65\\x81\\x00\\xc0\\x05\\x01\\x09\\x02\\xa1\\x01\\x09\\x01\\xa1\\x00\\x85\\x02\\x05\\x09\\x19\\x01\\x29\\x03\\x15\\x00\\x25\\x01\\x95\\x03\\x75\\x01\\x81\\x02\\x95\\x01\\x75\\x05\\x81\\x03\\x05\\x01\\x09\\x30\\x09\\x31\\x15\\x81\\x25\\x7f\\x75\\x08\\x95\\x02\\x81\\x06\\xC0\\xC0 > functions/hid.usb0/report_desc

C=1
mkdir -p configs/c.$C/strings/0x409
echo "Config $C: ECM network" > configs/c.$C/strings/0x409/configuration
echo 250 > configs/c.$C/MaxPower
ln -s functions/hid.usb0 configs/c.$C/

ls /sys/class/udc > UDC

다음과 같이 2개의 HID 구성 요소("HID Keyboard Device", "HID-compliant mouse")를 내장한 1개의 "USB Input Device"가 생성됩니다.

rd_1usb_2hid_1.png

참고로, 기존 실습을 한 경우 다음과 같이 서비스를 제거한 다음,

$ sudo systemctl disable create-dual-usb
$ sudo rm /etc/systemd/system/create-dual-usb.service
$ sudo systemctl daemon-reload

위의 USB 장치 등록 쉘 스크립트를 dual2.sh로 저장 후,

$ cd /share
$ sudo nano dual2.sh
$ chmod +x ./dual2.sh

/etc/systemd/system/ 디렉터리에 create-dual2-usb.service 파일을 만들어,

$ cd /etc/systemd/system/
$ sudo nano create-dual2-usb.service

내용을 채운 다음,

[Unit]
Description=Create Mouse/Keyboard USB gadgets

[Service]
Type=oneshot
ExecStart=/share/dual2.sh
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

다시 서비스로 등록해 주면 됩니다.

$ sudo systemctl daemon-reload
$ sudo systemctl enable create-dual2-usb
$ sudo reboot




장치가 인식되었으면 이제 driver 측의 코드도 변경해야 합니다.

Linux USB HID gadget driver
; https://www.kernel.org/doc/Documentation/usb/gadget_hid.txt

위의 코드에서 mouse와 keyboard의 첫 번째 바이트를 해당하는 report id로 채워야 합니다.

int keyboard_fill_report(char report[8], char buf[BUF_LEN], int *hold)
{
    char *tok = strtok(buf, " ");
    int key = 0;
    int i = 0;

    report[0] = 1;

    for (; tok != NULL; tok = strtok(NULL, " ")) {

        if (strcmp(tok, "--quit") == 0)
            return -1;

        if (strcmp(tok, "--hold") == 0) {
            *hold = 1;
            continue;
        }

        if (key < 5) {
            for (i = 0; kval[i].opt != NULL; i++)
                if (strcmp(tok, kval[i].opt) == 0) {
                    report[3 + key++] = kval[i].val;
                    break;
                }
            if (kval[i].opt != NULL)
                continue;
        }

        if (key < 5)
            if (islower(tok[0])) {
                report[3 + key++] = (tok[0] - ('a' - 0x04));
                continue;
            }

        for (i = 0; kmod[i].opt != NULL; i++)
            if (strcmp(tok, kmod[i].opt) == 0) {
                report[1] = report[1] | kmod[i].val;
                break;
            }
        if (kmod[i].opt != NULL)
            continue;

        if (key < 5)
            fprintf(stderr, "unknown option: %s\n", tok);
    }
    return 8;
}

int mouse_fill_report(char report[8], char buf[BUF_LEN], int *hold)
{
    char *tok = strtok(buf, " ");
    int mvt = 0;
    int i = 0;

    report[0] = 2;

    for (; tok != NULL; tok = strtok(NULL, " ")) {

        if (strcmp(tok, "--quit") == 0)
            return -1;

        if (strcmp(tok, "--hold") == 0) {
            *hold = 1;
            continue;
        }

        for (i = 0; mmod[i].opt != NULL; i++)
            if (strcmp(tok, mmod[i].opt) == 0) {
                report[1] = report[1] | mmod[i].val;
                break;
            }
        if (mmod[i].opt != NULL)
            continue;

        if (!(tok[0] == '-' && tok[1] == '-') && mvt < 2) {
            errno = 0;
            report[2 + mvt++] = (char)strtol(tok, NULL, 0);
            if (errno != 0) {
                fprintf(stderr, "Bad value:'%s'\n", tok);
                report[2 + mvt--] = 0;
            }
            continue;
        }

        fprintf(stderr, "unknown option: %s\n", tok);
    }
    return 4;
}

이후, 테스트는 이전 글과 동일하게 수행하면 됩니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 1/12/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13030정성태4/15/20226496오류 유형: 804. 정규 표현식 오류 - Quantifier {x,y} following nothing.
13029정성태4/14/20226900Windows: 203. iisreset 후에도 이전에 설정한 전역 환경 변수가 w3wp.exe에 적용되는 문제
13028정성태4/13/20226811.NET Framework: 1193. (appsettings.json처럼) web.config의 Debug/Release에 따른 설정 적용
13027정성태4/12/20227102.NET Framework: 1192. C# - 환경 변수의 변화를 알리는 WM_SETTINGCHANGE Win32 메시지 사용법파일 다운로드1
13026정성태4/11/20228633.NET Framework: 1191. C 언어로 작성된 FFmpeg Examples의 C# 포팅 전체 소스 코드 [3]
13025정성태4/11/20227973.NET Framework: 1190. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 vaapi_encode.c, vaapi_transcode.c 예제 포팅
13024정성태4/7/20226466.NET Framework: 1189. C# - 런타임 환경에 따라 달라진 AppDomain.GetCurrentThreadId 메서드
13023정성태4/6/20226767.NET Framework: 1188. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 transcoding.c 예제 포팅 [3]
13022정성태3/31/20226671Windows: 202. 윈도우 11 업그레이드 - "PC Health Check"를 통과했지만 여전히 업그레이드가 안 되는 경우 해결책
13021정성태3/31/20226842Windows: 201. Windows - INF 파일을 이용한 장치 제거 방법
13020정성태3/30/20226581.NET Framework: 1187. RDP 접속 시 WPF UserControl의 Unloaded 이벤트 발생파일 다운로드1
13019정성태3/30/20226575.NET Framework: 1186. Win32 Message를 Code로부터 메시지 이름 자체를 구하고 싶다면?파일 다운로드1
13018정성태3/29/20227117.NET Framework: 1185. C# - Unsafe.AsPointer가 반환한 포인터는 pinning 상태일까요? [5]
13017정성태3/28/20226917.NET Framework: 1184. C# - GC Heap에 위치한 참조 개체의 주소를 알아내는 방법 - 두 번째 이야기 [3]
13016정성태3/27/20227772.NET Framework: 1183. C# 11에 추가된 ref 필드의 (우회) 구현 방법파일 다운로드1
13015정성태3/26/20229123.NET Framework: 1182. C# 11 - ref struct에 ref 필드를 허용 [1]
13014정성태3/23/20227695VC++: 155. CComPtr/CComQIPtr과 Conformance mode 옵션의 충돌 [1]
13013정성태3/22/20226025개발 환경 구성: 641. WSL 우분투 인스턴스에 파이썬 2.7 개발 환경 구성하는 방법
13012정성태3/21/20225348오류 유형: 803. C# - Local '...' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
13011정성태3/21/20226827오류 유형: 802. 윈도우 운영체제에서 웹캠 카메라 인식이 안 되는 경우
13010정성태3/21/20225752오류 유형: 801. Oracle.ManagedDataAccess.Core - GetTypes 호출 시 "Could not load file or assembly 'System.DirectoryServices.Protocols...'" 오류
13009정성태3/20/20227380개발 환경 구성: 640. docker - ibmcom/db2 컨테이너 실행
13008정성태3/19/20226676VS.NET IDE: 176. 비주얼 스튜디오 - 솔루션 탐색기에서 프로젝트를 선택할 때 csproj 파일이 열리지 않도록 만드는 방법
13007정성태3/18/20226260.NET Framework: 1181. C# - Oracle.ManagedDataAccess의 Pool 및 그것의 연결 개체 수를 알아내는 방법파일 다운로드1
13006정성태3/17/20227336.NET Framework: 1180. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 remuxing.c 예제 포팅
13005정성태3/17/20226200오류 유형: 800. C# - System.InvalidOperationException: Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.
... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...