Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)

Synology NAS(DS216+II)에 FTDI 장치 연결 후 C#(.NET Core)으로 DTR 제어

라즈베리 파이의 경우,

Raspberry PI Zero (W)에 FTDI 장치 연결 후 C/C++로 DTR 제어
; https://www.sysnet.pe.kr/2/0/11716

아쉽게도 저 프로그램을 C#으로 만들 수는 없습니다. 왜냐하면 .NET Core가 제공되지 않기 때문입니다. 반면, Synology NAS(DS216+II)의 경우,

Synology NAS(DS216+II)에서 FTDI 장치를 C/C++로 제어
; https://www.sysnet.pe.kr/2/0/11733

docker를 통해 .NET Core 응용 프로그램을 실행하는 것이 가능하므로,

Synology NAS(DS216+II)에 docker 설치 후 .NET Core 2.1 응용 프로그램 실행하는 방법
; https://www.sysnet.pe.kr/2/0/11713

C#으로도 FTDI 장치를 제어할 수 있습니다. 간단하게 만들어 볼까요? ^^




우선, 기존에 C/C++ 예제로 구했던 read 프로그램을 기반으로 하겠습니다.

$ cp -r read ftdidtr

복사한 ftdidtr 디렉터리에서 Makefile을 다음과 같이 수정해 줍니다.

export CC = gcc

TOPDIR  := $(shell cd ..; cd ..; pwd)
include $(TOPDIR)/Rules.make

APP = ftdidtr

all: $(APP)

$(APP): main.c
       $(CC) main.c -o $(APP) $(CFLAGS)

clean:
        -rm -f *.o ; rm $(APP)

그다음, main.c의 내용을 다음과 같이 "라즈베리 파이를 이용해 원격 컴퓨터의 전원 스위치 제어"의 역할만 하도록 변경합니다.

$ cat main.c

/*
        To build use the following gcc statement
        (assuming you have the d2xx library in the /usr/local/lib directory).
        gcc -o read main.c -L. -lftd2xx -Wl,-rpath,/usr/local/lib
*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include "../../ftd2xx.h"

int main(int argc, char *argv[])
{
        FT_STATUS       ftStatus;
        FT_HANDLE       ftHandle0;
        int iport;
        DWORD libraryVersion = 0;

        ftStatus = FT_GetLibraryVersion(&libraryVersion);
        if (ftStatus == FT_OK)
        {
                printf("Library version = 0x%x\n", (unsigned int)libraryVersion);
        }
        else
        {
                printf("Error reading library version.\n");
                return 1;
        }

        if(argc > 1) {
                sscanf(argv[1], "%d", &iport);
        }
        else {
                iport = 0;
        }
        printf("Opening port %d\n", iport);

        ftStatus = FT_Open(iport, &ftHandle0);
        if(ftStatus != FT_OK) {
                /*
                        This can fail if the ftdi_sio driver is loaded
                        use lsmod to check this and rmmod ftdi_sio to remove
                        also rmmod usbserial
                 */
                printf("FT_Open(%d) failed\n", iport);
                return 1;
        }
        printf("FT_Open succeeded.  Handle is %p\n", ftHandle0);

        FT_SetDtr(ftHandle0);

        usleep(500 * 1000); // 500ms

        FT_ClrDtr(ftHandle0);

        FT_Close(ftHandle0);

        return 0;
}

빌드 후 실행해 보면, 정상적으로 500ms 동안 DTR 신호가 On 되는 것을 확인할 수 있습니다.




C/C++로 구현을 했으니, 이제 C#으로도 당연히 구현할 수 있습니다. C#만큼 Native 모듈과 자연스러운 연동이 가능한 언어도 드문데요. ^^ FTDI 라이브러리를 빌드해서 얻은 libftd2xx.so, libftd2xx.so.1.4.8 파일 2개를,

$ ls /usr/local/lib
libftd2xx.a  libftd2xx.so  libftd2xx.so.1.4.8  libftd2xx.txt  python2.7

C# .NET Core 프로젝트에 추가한 후 다음과 같이 소스 코드를 구성하면 됩니다.

using System;
using System.Runtime.InteropServices;
using System.Threading;

namespace FtdiDtr
{
    class Program
    {
        [DllImport("libftd2xx.so")]
        private static extern int FT_GetLibraryVersion(out int version);

        [DllImport("libftd2xx.so")]
        private static extern int FT_Open(int iport, out IntPtr ftHandle);

        [DllImport("libftd2xx.so")]
        private static extern int FT_Close(IntPtr ftHandle);

        [DllImport("libftd2xx.so")]
        private static extern int FT_SetDtr(IntPtr ftHandle);

        [DllImport("libftd2xx.so")]
        private static extern int FT_ClrDtr(IntPtr ftHandle);

        static void Main(string[] args)
        {
            int version;
            FT_GetLibraryVersion(out version);

            Console.WriteLine("FT Version: 0x" + version.ToString("x"));

            IntPtr ftHandle = IntPtr.Zero;

            Console.WriteLine("Opening...");
            int result = FT_Open(0, out ftHandle);
            Console.WriteLine(result);

            if (ftHandle != IntPtr.Zero)
            {
                FT_SetDtr(ftHandle);
                Thread.Sleep(500);
                FT_ClrDtr(ftHandle);

                Console.WriteLine("Closing...");
                FT_Close(ftHandle);
            }
        }
    }
}

이후 docker 이미지를 생성하도록 Dockerfile 추가와 그에 맞게 csproj 파일을 변경하고,

.NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성
; https://www.sysnet.pe.kr/2/0/11708

배포(Publish) 후 생성된 이미지를 Synology NAS(DS216+II) 장비에 복사합니다.

Synology NAS(DS216+II)에 docker 설치 후 .NET Core 2.1 응용 프로그램 실행하는 방법
; https://www.sysnet.pe.kr/2/0/11713

c:\temp> docker save -o c:\temp\ftdidtr.img ftdidtr
c:\temp> pscp c:\temp\ftdidtr.img testuser@test_linux:/docker

그다음 Synology NAS(DS216+II) 측의 shell에서 docker 이미지를 로드하고,

$ docker load -i /volume1/docker/ftdidtr.img

$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ftdidtr             latest              205ea304ca0b        8 minutes ago       255MB

실행하면 됩니다.

$ docker run --rm ftdidtr

그런데, 위와 같이 실행하면 docker 호스트 측의 장비에 연결된 USB 장치를 인식하지 못하므로, 다음과 같이 실행해야 합니다.

$ docker run --rm --privileged ftdidtr
FT Version: 0x10408
Opening...
0
Closing...

테스트를 위해 Synology NAS(DS216+II)에 USB 케이블로 FTDI를 연결 후, DTR에 LED와 저항을 직렬로 3.3V 단자에 연결하면 docker run 시에 LED가 0.5 초 동안 불이 들어오는 것을 확인할 수 있습니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 10/11/2018]

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

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  68  69  70  71  [72]  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
11839정성태3/12/201913988디버깅 기술: 124. .NET Core 웹 앱을 호스팅하는 Azure App Services의 프로세스 메모리 덤프 및 windbg 분석 개요 [3]
11838정성태3/7/201916776.NET Framework: 811. (번역글) .NET Internals Cookbook Part 1 - Exceptions, filters and corrupted processes [1]파일 다운로드1
11837정성태3/6/201926392기타: 74. 도서: 시작하세요! C# 7.3 프로그래밍 [10]
11836정성태3/5/201914332오류 유형: 525. Visual Studio 2019 Preview 4/RC - C# 8.0 Missing compiler required member 'System.Range..ctor' [1]
11835정성태3/5/201914086.NET Framework: 810. C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법 [3]파일 다운로드1
11834정성태3/4/201912992개발 환경 구성: 432. Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
11833정성태3/4/201913744개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201910796오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201910365오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201910188오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201912058개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201918449개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201912378오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201912267오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201917121개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201911927오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201913383오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201911539오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201912010오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201915124오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201913797Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201912712VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/20199907오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201912383Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201911289오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201910089오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
... 61  62  63  64  65  66  67  68  69  70  71  [72]  73  74  75  ...