分享

【新提醒】【unity Android 串口通讯完整项目实例】

 鸿蛟家平 2017-12-15
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./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;
                }
        }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多