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

비밀번호

댓글 작성자
 




... 91  92  93  94  95  96  [97]  98  99  100  101  102  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11544정성태6/10/201823980.NET Framework: 765. C# 7.2 - 숫자 리터럴의 선행 밑줄과 뒤에 오지 않는 명명된 인수
11543정성태6/9/201823400.NET Framework: 764. C# 7.2 - private protected 접근자 추가파일 다운로드1
11542정성태6/9/201861912개발 환경 구성: 381. Azure Web App 확장 예제 - Remove Custom Headers
11541정성태6/9/201821098개발 환경 구성: 380. Azure Web App 확장 배포 방법 [1]
11540정성태6/9/201821266개발 환경 구성: 379. Azure Web App 확장 예제 제작 [2]
11539정성태6/8/201821768.NET Framework: 763. .NET Core 2.1 - Tiered Compilation 도입파일 다운로드1
11538정성태6/8/201820534.NET Framework: 762. .NET Core 2.1 - 확장 도구(Tools) 관리 [1]
11537정성태6/8/201825617.NET Framework: 761. C# - SmtpClient로 SMTP + SSL/TLS 서버를 이용하는 방법 [5]
11536정성태6/7/201822502.NET Framework: 760. Microsoft Build 2018 - The future of C# 동영상 내용 정리 [1]파일 다운로드1
11535정성태6/7/201825156.NET Framework: 759. C# - System.Span<T> 성능 [1]
11534정성태6/6/201830660.NET Framework: 758. C# 7.2 - Span<T> [6]
11533정성태6/5/201833319.NET Framework: 757. 포인터 형 매개 변수를 갖는 C++ DLL의 함수를 C#에서 호출하는 방법파일 다운로드1
11532정성태6/5/201822635.NET Framework: 756. JSON의 escape sequence 문자 처리 방식
11531정성태6/4/201826884오류 유형: 468. JSON.parse가 허용하지 않는 문자 [9]
11530정성태5/31/201827688.NET Framework: 755. C# 7.2 - 스택에만 생성할 수 있는 값 타입 지원 - "ref struct" [2]파일 다운로드1
11529정성태5/23/201824933.NET Framework: 754. 닷넷의 관리 포인터(Managed Pointer)와 System.TypedReference [6]파일 다운로드1
11528정성태5/17/201824433.NET Framework: 753. C# 7.2 - 3항 연산자에 ref 지원(conditional ref operator) [1]
11527정성태5/17/201822161오류 유형: 467. RDP 로그인 에러 - This could be due to CredSSP encryption oracle remediation.
11526정성태5/16/201822104.NET Framework: 752. C# 7.2 - 메서드의 반환값 및 로컬 변수에 ref readonly 기능 추가파일 다운로드1
11525정성태5/16/201826176.NET Framework: 751. C# 7.2 - 메서드의 매개 변수에 in 변경자 추가 [3]파일 다운로드1
11524정성태5/15/201825047.NET Framework: 750. C# 7.2 - readonly 구조체 [5]파일 다운로드1
11523정성태5/15/201822240.NET Framework: 749. C# - 값 형식의 readonly 인스턴스에 대한 메서드 호출 시 defensive copy 발생 [1]파일 다운로드1
11522정성태5/15/201820676개발 환경 구성: 378. Azure - VM 진단 설정 화면의 "This subscription is not registered with the Microsoft.Insights resource provider."
11521정성태5/15/201818989개발 환경 구성: 377. Azure - 원하는 성능 데이터로 모니터링 대시보드 구성
11520정성태5/12/201821160.NET Framework: 748. C# 7.1 - 참조 어셈블리(Ref Assemblies)
11519정성태5/12/201823055개발 환경 구성: 376. ASP.NET Web Application 프로젝트의 FileSystem 배포(Publish) 시 Before/After Task 설정 방법 [1]
... 91  92  93  94  95  96  [97]  98  99  100  101  102  103  104  105  ...