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

Xamarin - 기존 리모컨 기능을 핸드폰의 적외선 송신으로 구현

집에 있는 리모컨의 기능을 핸드폰으로 복사하는 것이 가능합니다. 이를 위해서는 우선 기존 리모컨들의 신호 값을 알아야 하는데, 다음의 글에 따라 아두이노를 이용하면 가능합니다.

아두이노에서 적외선 수신기 기본 사용법
; https://www.sysnet.pe.kr/2/0/11670

사실 송신 기능도 핸드폰 대신 아두이노를 이용한 송신기로 구현할 수는 있습니다.

아두이노에서 적외선 송신기 기본 사용법
; https://www.sysnet.pe.kr/2/0/11671

문제는 저런 식으로 아두이노로 구현하는 것은 불편한 면이 많습니다. 가령, 현실적으로 쓰기 위해선 기능에 따른 버튼도 더 늘려야 하고 브레드보드가 아닌 만능 기판에, ... 케이스까지 만들기 위해 3D 프린터라든가 기타 여러 도구들까지 장만을 해야 합니다. (사실, 언젠가는 저도 ^^ 그렇게까지 해보고 싶습니다.) 그런데, 생각해 보면 마감 잘 된 도구가 하나 있습니다. 바로 휴대폰입니다. 검색해 보면 마침 API 19(KitKat)부터 적외선 송신 기능도 제공한다고 합니다.

Using Infrared port
; https://forums.xamarin.com/discussion/12205/using-infrared-port

Xamarin의 경우 ConsumerIrManager 타입을 이용해,

Android.Hardware.ConsumerIrManager Class
; https://developer.xamarin.com/api/type/Android.Hardware.ConsumerIrManager/

쉽게 접근할 수 있습니다. 그럼 뭐, 다 준비된 거죠. ^^ Visual Studio에서 Xamarin 프로젝트를 생성하고 해당 App에서 적외선 송신 기능을 사용하겠다는 요구를 manifest에 기록하고,

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          android:versionCode="1"
          android:versionName="1.0"
          package="IRController.IRController">
    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="27" />
    <uses-permission android:name="android.permission.TRANSMIT_IR"></uses-permission>

    <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme">
    </application>

</manifest>

다음과 같이 리모컨 기능을 대신할 버튼을 만든 다음,

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:text="Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minWidth="25px"
        android:minHeight="25px"
        android:id="@+id/btnTurnLightOnOff"
    />
</RelativeLayout>

이것을 누르면 그에 해당하는 적외선 송신을 하면 됩니다.

using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
using Android.Content;

namespace IRController
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        Android.Hardware.ConsumerIrManager _ir;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            Button button = FindViewById<Button>(Resource.Id.btnTurnLightOnOff);
            button.Click += btnTurnLightOnOff_Click;

        }

        private void btnTurnLightOnOff_Click(object sender, System.EventArgs e)
        {
            _ir = ApplicationContext.GetSystemService(Context.ConsumerIrService)
                as Android.Hardware.ConsumerIrManager;

            int [] light_onoff_signal_buf = { 3550, 1750, 600, 400, 600, 1800, 550, 450, 600, 450, 600, 1800, 550, 450, 600, 450, 600, 500, 600, 450, 600, 400, 650, 400, 550 };
            _ir.Transmit(38, light_onoff_signal_buf);
        }
    }
}

위의 코드에서 Transmit 메서드를 보면,

Android.Hardware.ConsumerIrManager.Transmit Method
; https://developer.xamarin.com/api/member/Android.Hardware.ConsumerIrManager.Transmit/p/System.Int32/System.Int32[]/

지난번 "아두이노에서 적외선 송신기 기본 사용법"의 코드와 거의 똑같다는 것을 알 수 있습니다. 즉, Raw Data와 함께 주파수만 지정하면 되는 것입니다.

제가 가지고 있는 핸드폰이 LG V20인데 다행히 적외선 송신 기능이 있는 제품입니다. 위의 앱을 설치해서 실행해 보면, 와~~~ ^^ 정말 핸드폰으로 형광등을 On/Off 하는 것이 가능해졌습니다. 그런데, 여기서 문제가 있습니다. V20 핸드폰의 적외선 송신기가 원래의 형광등을 제어하던 리모컨의 출력보다 약한 것 같습니다. 재미있는 것은 동일 높이의 정면에서 하면 핸드폰으로 잘 동작을 하는데 높이가 달라지거나 사잇각이 커지면 핸드폰으로는 대상 수신기에서 잘 잡아내지 못합니다.

종합해 보면, 어떤 적외선 수신 제품을 (현실적으로) 제어하고 싶은 경우라면 직접 핸드폰에서 신호를 보내는 것보다는 네트워크 기능이 있는 아두이노를 상시 켜 놓고 그 아두이노의 적외선 송신기를 (잘 수신이 되도록 위치를 잡아 놓고) 사용하는 것이 좋을 것 같습니다. 암튼, 좀 아쉽군요. ^^ 핸드폰 하나로 다 될 것 같아서 기대에 부풀었는데.

(첨부 파일은 이 글의 Android/Xamarin 프로젝트입니다.)




적외선 통신을 다루면서 왜 38Khz를 고정 상수로 전달할까... 하는 의문이 있었는데요, 다음의 글에서 이를 설명하고 있습니다.

적외선 통신을 알아보자.
; http://dokkodai.tistory.com/106

즉, 적외선 통신은 37 ~ 42 Khz로 변조를 한다는데, 리모컨의 경우 38Khz로 하는 것이 일반적이라고 합니다.




참고로, 다음과 같은 식의 오류가 발생한다면?

Unhandled Exception:

Java.Lang.SecurityException: <Timeout exceeded getting exception details> occurred

"Timeout"이긴 하지만 예외의 종류가 SecurityException인 것이 더 중요합니다. 즉, IR 기능 사용에 대한 사용자 허락을 받을 수 있도록 manifest에 "android.permission.TRANSMIT_IR" 권한 요구를 명시하지 않아서 그런 것입니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/29/2018]

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

비밀번호

댓글 작성자
 




... 46  47  [48]  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12740정성태7/29/202114785오류 유형: 747. SharePoint - InvalidOperationException 0x80131509
12739정성태7/28/202115169오류 유형: 746. Azure Active Directory - IDW10106: The 'ClientId' option must be provided.
12738정성태7/28/202116144오류 유형: 745. Azure Active Directory - Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).
12737정성태7/28/202115245오류 유형: 744. Azure Active Directory - The resource principal named api://...[client_id]... was not found in the tenant
12736정성태7/28/202115525오류 유형: 743. Active Azure Directory에서 "API permissions"의 권한 설정이 "Not granted for ..."로 나오는 문제
12735정성태7/27/202115311.NET Framework: 1081. C# - Azure AD 인증을 지원하는 데스크톱 애플리케이션 예제(Windows Forms) [2]파일 다운로드1
12734정성태7/26/202132140스크립트: 20. 특정 단어로 시작하거나/끝나는 문자열을 포함/제외하는 정규 표현식 - Look-around
12733정성태7/23/202120091.NET Framework: 1081. Self-Contained/SingleFile 유형의 .NET Core/5+ 실행 파일을 임베딩한다면? [1]파일 다운로드2
12732정성태7/23/202113483오류 유형: 742. SharePoint - The super user account utilized by the cache is not configured.
12731정성태7/23/202115529개발 환경 구성: 584. Add Internal URLs 화면에서 "Save" 버튼이 비활성화 된 경우
12730정성태7/23/202117001개발 환경 구성: 583. Visual Studio Code - Go 코드에서 입력을 받는 경우
12729정성태7/22/202115427.NET Framework: 1080. xUnit 단위 테스트에 메서드/클래스 수준의 문맥 제공 - Fixture
12728정성태7/22/202115534.NET Framework: 1079. MSTestv2 단위 테스트에 메서드/클래스/어셈블리 수준의 문맥 제공
12727정성태7/21/202116632.NET Framework: 1078. C# 단위 테스트 - MSTestv2/NUnit의 Assert.Inconclusive 사용법(?) [1]
12726정성태7/21/202116401VS.NET IDE: 169. 비주얼 스튜디오 - 단위 테스트 선택 시 MSTestv2 외의 xUnit, NUnit 사용법 [1]
12725정성태7/21/202114919오류 유형: 741. Failed to find the "go" binary in either GOROOT() or PATH
12724정성태7/21/202117825개발 환경 구성: 582. 윈도우 환경에서 Visual Studio Code + Go (Zip) 개발 환경 [1]
12723정성태7/21/202114591오류 유형: 740. SharePoint - Alternate access mappings have not been configured 경고
12722정성태7/20/202114367오류 유형: 739. MSVCR110.dll이 없어 exe 실행이 안 되는 경우
12721정성태7/20/202115603오류 유형: 738. The trust relationship between this workstation and the primary domain failed. - 세 번째 이야기
12720정성태7/19/202114909Linux: 43. .NET Core/5+ 응용 프로그램의 Ubuntu (Debian) 패키지 준비
12719정성태7/19/202114083오류 유형: 737. SharePoint 설치 시 "0x800710D8 The object identifier does not represent a valid object." 오류 발생
12718정성태7/19/202114070개발 환경 구성: 581. Windows에서 WSL로 파일 복사 시 root 소유권으로 적용되는 문제파일 다운로드1
12717정성태7/18/202114278Windows: 195. robocopy에서 파일의 ADS(Alternate Data Stream) 정보 복사를 제외하는 방법
12716정성태7/17/202115362개발 환경 구성: 580. msbuild의 Exec Task에 robocopy를 사용하는 방법파일 다운로드1
12715정성태7/17/202122522오류 유형: 736. Windows - MySQL zip 파일 버전의 "mysqld --skip-grant-tables" 실행 시 비정상 종료 [1]
... 46  47  [48]  49  50  51  52  53  54  55  56  57  58  59  60  ...