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

비밀번호

댓글 작성자
 




1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13532정성태1/17/20242179닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242065닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242042닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20241922닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242062Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242012오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242109닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242065오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242117오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20241933오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242094닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242154닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20241892오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20241985닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242255닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242101스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242194닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242473닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242115개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242038닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20242002개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242020닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20241956닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20241979오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242029오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242718닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...