unity Android 串口通讯完整项目实例

package com.unity.sp;
 
 
  
  
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
 
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;
  
 
  
 
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android_serialport_api.ComPort;
 
 
 
//import android.serialport.sample.R;
  
 
 
public class MyserialActivity extends UnityPlayerActivity {
        public static ComPort mComPort;
        public static ComPort mComPort3;
         
  
         private static final int Port = 5281;
    @Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Intent intent = new Intent();  
                 intent.setAction("android.intent.action.HIDE_NAVIGATION_BAR");  
                 MyserialActivity.this.sendBroadcast(intent); 
                   
    }
     
     
    public void OpenttyS1()
        {  
            if(mComPort == null)
            {
                    mComPort = new ComPort();
            }
                 
                mComPort.Start("ttyS1");
        }
     
     
    public void OpenttyS3()
           {  
               if(mComPort3 == null)
               {
                       mComPort3 = new ComPort();
               }
                    
               mComPort3.Start("ttyS3");
           }
     
     
     
    public static String bytes2HexString(byte[] b, int len) {
                  String ret = "";
                  for (int i = 0; i < len; i++) {
                   String hex = Integer.toHexString(b[ i ] & 0xFF);
                   if (hex.length() == 1) {
                    hex = '0' + hex;
                   }
                   ret += hex.toUpperCase();
                  }
                  return ret;
                }
         
        public static byte uniteBytes(byte src0, byte src1) { 
                byte _b0 = Byte.decode("0x" + new String(new byte[]{src0})).byteValue(); 
                _b0 = (byte)(_b0 << 4); 
                byte _b1 = Byte.decode("0x" + new String(new byte[]{src1})).byteValue(); 
                byte ret = (byte)(_b0 ^ _b1); 
                return ret; 
                } 
         
        public   void ttyS1Send(byte[] data,int length)
        {        
                mComPort.SendData(data, length);
        }
         
        public   void ttyS3Send(byte[] data,int length)
        {         
  
                mComPort3.SendData(data, length);
        }
         
        public void RestartSystem()
        {
                new ServerThread().start();
        }
                        class ServerThread extends Thread {
                                    ServerSocket serversocket = null;
                                    @Override
                                    public void run() 
                                    {
                                            super.run();
                                        try {
                                            serversocket = new ServerSocket(Port);
                                            Socket socket = serversocket.accept();
                                            while (true) {
                                 
                                 
                                             //   OutputStream ou = socket.getOutputStream();
                                                DataOutputStream wirter = new DataOutputStream(socket.getOutputStream());
                                                BufferedReader buffer = new BufferedReader(
                                                        new InputStreamReader(socket.getInputStream()));
                                 
                                 
                                                wirter.writeBytes("reboot\n");
                                                try {
                                                    Thread.sleep(1000);
                                                } catch (InterruptedException e) {
                                                    e.printStackTrace();
                                                }
                                 
                                            }
                                 
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        } finally {
                                            try {
                                                serversocket.close();
                                            } catch (IOException e) {[mw_shl_code=java,true]/*
 * Copyright 2009 Cedric Priscal
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */
 
package android_serialport_api;
 
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.security.InvalidParameterException;
 
import com.unity3d.player.UnityPlayer;
 
import android.R.string;
import android.util.Log;
 
import android_serialport_api.SerialPort; 
 
public  class ComPort {
 
        protected SerialPort mSerialPort;
        protected OutputStream mOutputStream;
        private InputStream mInputStream;
        private ReadThread mReadThread;
 
        private String unityFunction="";
         
        private static StringBuffer SendBuffer=null;
         
        private class ReadThread extends Thread {
 
                 
                @Override
                public void run() {
                        super.run();
                        while(!isInterrupted()) {
                                int size=0;
                                try {
                                        byte[] buffer = new byte[64];
                                        for(int k=0;k<64;k++)
                                                buffer[k]=0;
                                        if (mInputStream == null) return;
                                        size = mInputStream.read(buffer);
                                        if (size > 0) {
                                                onDataReceived(buffer, size);
                                        }
                                } catch (IOException e) {
                                        e.printStackTrace();
                                        return;
                                }
                        }
                }
        }
 
        public ComPort()
        {
                SendBuffer=new StringBuffer();
        }
         
        private void DisplayError(String reason) {
                /*AlertDialog.Builder b = new AlertDialog.Builder(this);
                b.setTitle("Error");
                b.setMessage(resourceId);
                b.setPositiveButton("OK", new OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                                SerialPortActivity.this.finish();
                        }
                });
                b.show();*/
                 
                Destroy();
                Log.e("openserialport",reason);
        }
 
 
        public void Start(String pname) {
                //UnityPlayer.UnitySendMessage("SerialPort","ReviceData_s1", "尝试绑定串口");
                int baudrateSpeed;
                if(pname.equals("ttyS1"))
                {
                        unityFunction="ReviceData_s1";
                        baudrateSpeed=115200;
                }else
                {
                        unityFunction="ReviceData_s3";
                        baudrateSpeed=57600;
                }
                 
                 
                 
                try {
                        if (mSerialPort == null) {
 
                                //mSerialPort = new SerialPort(new File("/dev/ttyS2"), 115200, 0);
                                mSerialPort = new SerialPort(new File("/dev/"+pname), baudrateSpeed, 0);
                                UnityPlayer.UnitySendMessage("SerialPort","ReviceData_s1", "串口绑定成功");
                        }
                        mOutputStream = mSerialPort.getOutputStream();
                        mInputStream = mSerialPort.getInputStream();
 
                        /* Create a receiving thread */
                        if(baudrateSpeed==115200)
                        {
                                mReadThread = new ReadThread();
                                mReadThread.start();
                        }
 
                } catch (SecurityException e) {
                        UnityPlayer.UnitySendMessage("SerialPort","ReviceData_s1", "串口绑定失败1");
                        DisplayError("error_security");
                         
                } catch (IOException e) {
                        UnityPlayer.UnitySendMessage("SerialPort","ReviceData_s1", "串口绑定失败2");
                        DisplayError("error_unknown");
                } catch (InvalidParameterException e) {
                        UnityPlayer.UnitySendMessage("SerialPort","ReviceData_s1", "串口绑定失败3");
                        DisplayError("error_configuration");
                }
                UnityPlayer.UnitySendMessage("SerialPort","ReviceData_s1", "获取攒口读写接口 "+pname);
        }
 
        //protected abstract void onDataReceived(final byte[] buffer, final int size);
         
         
         
         
         
        private static Charset getDefaultCharset() {
            String encoding = System.getProperty("file.encoding", "UTF-8");
            try {
                return Charset.forName(encoding);
            } catch (UnsupportedCharsetException e) {
                return Charset.forName("UTF-8");
            }
        }
         
         
        public void SendData(byte[] buffer, int size)
        {
                try {
                        if (mOutputStream != null) {
                                 
                                mOutputStream.write(buffer,0, size);
                                 
                        } else {
                                return;
                        }
                //} catch (IOException e) {
                } catch (Exception e) {
                        //UnityPlayer.UnitySendMessage("SerialPort","ReviceData_s1", "串口java发送失败3");
                        //e.printStackTrace();
                        return;
                }
        }
         
        public static String bytes2HexString(byte[] b, int len) {
                  String ret = "";
                  for (int i = 0; i < len; i++) {
                   String hex = Integer.toHexString(b[ i ] & 0xFF);
                   if (hex.length() == 1) {
                    hex = '0' + hex;
                   }
                   ret += hex.toUpperCase();
                  }
                  return ret;
                }
         
        public static String bytes2HexString2(byte[] b, int len) {
                SendBuffer.delete(0, SendBuffer.length());
                  for (int i = 0; i < len; i++) {
                   String hex = Integer.toHexString(b[ i ] & 0xFF);
                   if (hex.length() == 1) {
                    hex = '0' + hex;
                   }
                   SendBuffer.append( hex.toUpperCase());
                  }
                  return SendBuffer.toString();
                }
         
        protected void onDataReceived(byte[] buffer, int size) {
                // ignore incoming data
                 
                //try {
                        if (mOutputStream != null) {
                                 
                  
                                String sss= bytes2HexString2(buffer, size);
  
                                                UnityPlayer.UnitySendMessage("SerialPort",unityFunction,sss);
                                         
                                }
                                 
                                //mOutputStream.write(buffer,0, size);
                                //UnityPlayer.UnitySendMessage("Main Camera","java_messgae","hi unity.this is java com msg.");
                                 
                        } //else {
                        //        return;
                //        }
                //} catch (IOException e) {
                //        e.printStackTrace();
                //        return;
                //}
                 
                //mOutputStream.write(buffer);
          
         
 
        public void Destroy() {
                if (mReadThread != null)
                        mReadThread.interrupt();
                 
                if (mSerialPort != null) {
                        mSerialPort.close();
                        mSerialPort = null;
                }
        }
}
/*
 * Copyright 2009 Cedric Priscal
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */
 
package android_serialport_api;
 
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
import android.util.Log;
 
public class SerialPort {
 
        private static final String TAG = "SerialPort";
 
        /*
         * Do not remove or rename the field mFd: it is used by native method close();
         */
        private FileDescriptor mFd;
        private FileInputStream mFileInputStream;
        private FileOutputStream mFileOutputStream;
 
        public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException {
 
                /* Check access permission */
                if (!device.canRead() || !device.canWrite()) {
                        try {
                                /* Missing read/write permission, trying to chmod the file */
                                Process su;
                                su = Runtime.getRuntime().exec("/system/bin/su");
                                String cmd = "chmod 666 " + device.getAbsolutePath() + "\n"
                                                + "exit\n";
                                su.getOutputStream().write(cmd.getBytes());
                                if ((su.waitFor() != 0) || !device.canRead()
                                                || !device.canWrite()) {
                                        throw new SecurityException();
                                }
                        } catch (Exception e) {
                                e.printStackTrace();
                                throw new SecurityException();
                        }
                }
 
                mFd = open(device.getAbsolutePath(), baudrate, flags,8);
                if (mFd == null) {
                        Log.e(TAG, "native open returns null");
                        throw new IOException();
                }
                mFileInputStream = new FileInputStream(mFd);
                mFileOutputStream = new FileOutputStream(mFd);
        }
 
        // Getters and setters
        public InputStream getInputStream() {
                return mFileInputStream;
        }
 
        public OutputStream getOutputStream() {
                return mFileOutputStream;
        }
 
        // JNI
        private native static FileDescriptor open(String path, int baudrate, int flags,int min_byte);
        public native void close();
        static {
                System.loadLibrary("serial_port");
        }
}
/*
 * Copyright 2009 Cedric Priscal
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */
 
package android_serialport_api;
 
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
import android.util.Log;
 
public class SerialPort {
 
        private static final String TAG = "SerialPort";
 
        /*
         * Do not remove or rename the field mFd: it is used by native method close();
         */
        private FileDescriptor mFd;
        private FileInputStream mFileInputStream;
        private FileOutputStream mFileOutputStream;
 
        public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException {
 
                /* Check access permission */
                if (!device.canRead() || !device.canWrite()) {
                        try {
                                /* Missing read/write permission, trying to chmod the file */
                                Process su;
                                su = Runtime.getRuntime().exec("/system/bin/su");
                                String cmd = "chmod 666 " + device.getAbsolutePath() + "\n"
                                                + "exit\n";
                                su.getOutputStream().write(cmd.getBytes());[attach]150981[/attach][attach]150981[/attach]
 
 
                                if ((su.waitFor() != 0) || !device.canRead()
                                                || !device.canWrite()) {
                                        throw new SecurityException();
                                }
                        } catch (Exception e) {
                                e.printStackTrace();
                                throw new SecurityException();
                        }
                }
 
                mFd = open(device.getAbsolutePath(), baudrate, flags,8);
                if (mFd == null) {
                        Log.e(TAG, "native open returns null");
                        throw new IOException();
                }
                mFileInputStream = new FileInputStream(mFd);
                mFileOutputStream = new FileOutputStream(mFd);
        }
 
        // Getters and setters
        public InputStream getInputStream() {
                return mFileInputStream;
        }
 
        public OutputStream getOutputStream() {
                return mFileOutputStream;
        }
 
        // JNI
        private native static FileDescriptor open(String path, int baudrate, int flags,int min_byte);
        public native void close();
        static {
                System.loadLibrary("serial_port");
        }
}
附件位置
http://www.manew.com/thread-110837-1-1.html

你可能感兴趣的:(Unity3D)