실리의 프로그램 사이트

유니티로 핸드폰과 컴퓨터간의 블루투스 통신을 해보자(완료) 본문

Unity 강좌

유니티로 핸드폰과 컴퓨터간의 블루투스 통신을 해보자(완료)

sillyknight 2017. 3. 9. 16:54

자 이제 마지막으로 유니티에서 코드를 짜서 통신을 해보는 부분만 남았습니다.


PC에서는 시리얼 통신으로 포트를 열고 데이터를 주고 받을 텐데요.


PC 에서 핸드폰으로 전송하는 부분만을 구현해보겠습니다.(나머지 부분은 시간이 없어서 필요하신분이 있으시면 댓글로 남겨주세요)






유니티 프로젝트를 생성 후 에셋폴더에 위와 같이 Plugins 폴더와 안드로이드 폴더를 생성합니다.


저 같은 경우 제가 하는 프로젝트의 경우는 Silly라는 폴더를 만들어서 씬과 스크립트를 저장합니다. 폴더는 편하신데로 만드시면 됩니다.


만들어진 폴더에 이전 강의에서 생성했던 bluetoothCode.jar 파일을 넣습니다.


AndroidManifest.xml 파일을 생성합니다.


AndroidManifest.xml 파일 안에 아래와 같이 코드를 넣습니다.


<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <application android:icon="@drawable/app_icon"

                 android:label="@string/app_name">

        <activity android:name="com.sillyent.unitybluetoothcode.BluetoothActivity"

                  android:label="@string/app_name"

                  android:launchMode="singleTask"                  android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

            <meta-data android:name="unityplayer.UnityActivity" android:value="true" />

        </activity>

    </application>

    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="24" />


    <!-- bluetooth tag-->

    <uses-permission android:name="android.permission.BLUETOOTH"/>

    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />



</manifest>





BluetoothControl.cs 파일을 생성합니다.(아래는 코드 내용입니다.)



using UnityEngine;

using UnityEngine.UI;


public class BluetoothControl : MonoBehaviour {



    public Text textDevices;

#if UNITY_EDITOR

#elif UNITY_ANDROID

    AndroidJavaObject _activity;

#endif

    // Use this for initialization

    void Start () {

#if UNITY_EDITOR

        SerialPortControl.GetInstance().OpenPort("COM3", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);

        textDevices.text = "";


#elif UNITY_ANDROID

        AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");

        _activity = jc.GetStatic<AndroidJavaObject>("currentActivity");


        Debug.Log("_activity 생성");

#endif

    }



    public void CallBluetoothInit()

    {

#if UNITY_EDITOR

#elif UNITY_ANDROID

        _activity.Call("BluetoothInit");

#endif

    }


    public void CallConnectedDevice(string name)

    {

#if UNITY_EDITOR

#elif UNITY_ANDROID

        _activity.Call("ConnectedDevice",name);

#endif

    }



    public void ErrorMessage(string errorMsg)

    {

        string msg = errorMsg;


        Debug.Log("Silly :: ErrorMessage :: " + errorMsg);

    }


    public void SearchDevice(string devices)

    {

        string[] device = devices.Split(',');


        for(int i=0;i<devices.Length;i++)

        {

            Debug.Log("Silly :: SearchDevice :: " + device[i]);

        }

        

    }


    public void ReceiveData(string str)

    {

        Debug.Log("Silly :: " + str);

        textDevices.text = str;

    }


    public void SendData(string str)

    {

#if UNITY_EDITOR

        SerialPortControl.GetInstance().SendData(str);

#endif

    }



}

 



SerialPortControl.cs 파일을 생성합니다.


using UnityEngine;

using System.IO.Ports;

using System;


public class SerialPortControl : MonoBehaviour {


    


    private static SerialPortControl instance;

    private static GameObject Contain;


    public SerialPort sp;


    public static SerialPortControl GetInstance()

    {

        if (!instance)

        {

            Contain = new GameObject();

            Contain.name = "SerialPortControl";

            instance = Contain.AddComponent(typeof(SerialPortControl)) as SerialPortControl;

        }

        return instance;


    }


    public void OpenPort(string port,int baud, Parity parity, int bits, StopBits stopbits)

    {

        try

        {

            sp = new SerialPort(port, baud, parity, bits, stopbits);

            sp.ReadTimeout = 200;

            sp.Handshake = Handshake.None;

            sp.ErrorReceived += new SerialErrorReceivedEventHandler(ErrorReceive);

            sp.DtrEnable = true;

            sp.DataReceived += new SerialDataReceivedEventHandler(DataReceive);

            sp.Open();

            Debug.Log("Silly :: OpenPort :: " + port + " open!");

        }

        catch(Exception ex)

        {

            Debug.Log("Silly :: " + ex);

        }

    }


    void ErrorReceive(object sender, SerialErrorReceivedEventArgs e)

    {

        Debug.Log("Silly :: ErrorReceive :: " + e.ToString());

    }


    void DataReceive(object sender, SerialDataReceivedEventArgs e)

    {

        try

        {

            int bytes = sp.ReadByte();

            Debug.Log(bytes);


        }

        catch(Exception ex)

        {

            Debug.Log("Silly :: " + ex);

        }

    }


    public void SendData(string data)

    {

        try

        {

            sp.Write(data);


        }

        catch (Exception ex)

        {

            Debug.Log("Silly :: " + ex);

            

        }

    }   

}



여기까지 하시면 유니티에서 통신을 할 준비가 되신겁니다.


유니티에서 버튼을 생성하시고 Send 버튼, Connect 버튼, 초기화 버튼을 만들고 데이터가 들어올 텍스트 박스만 만드시면 됩니다.



1. 모바일에서 빌드


2. PC에서 빌드


3. PC 유니티 창에서 포트가 오픈 된것을 확인(당연히 블루투스가 있는 PC만 가능합니다. 포트 또한 열어주셔야 합니다.)


4. 모바일에서 초기화 버튼 클릭.


5. 모바일에서 Connect 버튼 클릭.


6. PC에서 Send 버튼을 눌러 데이터 전송.



이렇게 하시면 모바일에서 PC의 데이터를 받을 수 있는 것을 확인하실 수 있을 겁니다.


궁금한 점은 댓글로 남겨주시기 바랍니다.










Comments