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

비밀번호

댓글 작성자
 




... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12845정성태10/6/20218097.NET Framework: 1120. C# - BufferBlock<T> 사용 예제 [5]파일 다운로드1
12844정성태10/3/20216131오류 유형: 764. MSI 설치 시 "... is accessible and not read-only." 오류 메시지
12843정성태10/3/20216588스크립트: 29. 파이썬 - fork 시 기존 클라이언트 소켓 및 스레드의 동작파일 다운로드1
12842정성태10/1/202124802오류 유형: 763. 파이썬 오류 - AttributeError: type object '...' has no attribute '...'
12841정성태10/1/20218377스크립트: 28. 모든 파이썬 프로세스에 올라오는 특별한 파일 - sitecustomize.py
12840정성태9/30/20218427.NET Framework: 1119. Entity Framework의 Join 사용 시 다중 칼럼에 대한 OR 조건 쿼리파일 다운로드1
12839정성태9/15/20219495.NET Framework: 1118. C# 11 - 제네릭 타입의 특성 적용파일 다운로드1
12838정성태9/13/20219146.NET Framework: 1117. C# - Task에 전달한 Action, Func 유형에 따라 달라지는 async/await 비동기 처리 [2]파일 다운로드1
12837정성태9/11/20218088VC++: 151. Golang - fmt.Errorf, errors.Is, errors.As 설명
12836정성태9/10/20217677Linux: 45. 리눅스 - 실행 중인 다른 프로그램의 출력을 확인하는 방법
12835정성태9/7/20218947.NET Framework: 1116. C# 10 - (15) CallerArgumentExpression 특성 추가 [2]파일 다운로드1
12834정성태9/7/20217319오류 유형: 762. Visual Studio 2019 Build Tools - 'C:\Program' is not recognized as an internal or external command, operable program or batch file.
12833정성태9/6/20216771VC++: 150. Golang - TCP client/server echo 예제 코드파일 다운로드1
12832정성태9/6/20217609VC++: 149. Golang - 인터페이스 포인터가 의미 있을까요?
12831정성태9/6/20216151VC++: 148. Golang - 채널에 따른 다중 작업 처리파일 다운로드1
12830정성태9/6/20218367오류 유형: 761. Internet Explorer에서 파일 다운로드 시 "Your current security settings do not allow this file to be downloaded." 오류
12829정성태9/5/202110018.NET Framework: 1115. C# 10 - (14) 구조체 타입에 기본 생성자 정의 가능파일 다운로드1
12828정성태9/4/20218146.NET Framework: 1114. C# 10 - (13) 단일 파일 내에 적용되는 namespace 선언파일 다운로드1
12827정성태9/4/20218128스크립트: 27. 파이썬 - 웹 페이지 데이터 수집을 위한 scrapy Crawler 사용법 요약
12826정성태9/3/202110372.NET Framework: 1113. C# 10 - (12) 문자열 보간 성능 개선 [1]파일 다운로드1
12825정성태9/3/20217928개발 환경 구성: 603. GoLand - WSL 환경과 연동
12824정성태9/2/202117003오류 유형: 760. 파이썬 tensorflow - Dst tensor is not initialized. 오류 메시지
12823정성태9/2/20216739스크립트: 26. 파이썬 - PyCharm을 이용한 fork 디버그 방법
12822정성태9/1/202111947오류 유형: 759. 파이썬 tensorflow - ValueError: Shapes (...) and (...) are incompatible [2]
12821정성태9/1/20217501.NET Framework: 1112. C# - .NET 6부터 공개된 ISpanFormattable 사용법
12820정성태9/1/20217804VC++: 147. Golang - try/catch에 대응하는 panic/recover [1]파일 다운로드1
... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...